0

I am using an DE0 board and wanted to count number of slide switches in ON position (there are 10 of these), and then lit corresponding number of LED (10 of these too) on the board. However I don't know how to use the result from masking to the IOWR. Thank you

alt_u16 sw;

volatile int i = 0;

alt_u16 count = 0x0;

alt_u16 mask = 0x0001;

alt_u16 sw2;

int CountSWITCHES(alt_u16 sw);

int alt_main (void)
{
    while(1)
    {   
        sw = IORD_ALTERA_AVALON_PIO_DATA(SWITCHES_BASE); 

        IOWR_ALTERA_AVALON_PIO_DATA(LEDS_BASE, sw2);
    }
    return 0;
}

int CountSWITCHES(alt_u16 sw)
{
    for(i = 0; i < 10; i++)
    {
        if (sw & mask)
        {
            count++;
        }

        mask = mask >> 1;
    }
    return count;    
}

void TurnLedsON(alt_u16 sw2)
{
    sw2 = CountSWITCHES(sw);
}
LPs
  • 16,045
  • 8
  • 30
  • 61
Tom
  • 11
  • 1
  • 4
  • You're on the right track. See: http://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer – Gillespie Jan 27 '16 at 15:46
  • Don't forget that right shift will do sign-extension on integers (might be better to make it unsigned for that reason) – Gillespie Jan 27 '16 at 15:47
  • @RPGillespie I would assume `alt_u16` to be an unsigned type. – unwind Jan 27 '16 at 16:42

1 Answers1

1

Function CountSWITCHES is not correct, should be:

int CountSWITCHES(alt_u16 sw)
{
    alt_u16 mask = 1;

    for(i = 0; i < 10; i++)
    {
        if (sw & mask)
        {
            count++;
        }

        mask = mask << 1;
    }

    return count;    
}

BTW this function return the number of switches ON, but it doesn't return their position.

IOWR_ALTERA_AVALON_PIO_DATA(base, data) wants a bitfield data: each bit set to 1 will set to 1 the corresponding output of port (base) passed. This means that you must set bits of sw2 variable based on the switches position.

LPs
  • 16,045
  • 8
  • 30
  • 61