Search code examples
cbuttonbinarycountergpio

binary count in C whit a button


printf("hello world\r\n");
fflush(stdout);
int number;
number = 0;
while (1)
{     


    if(HAL_GPIO_ReadPin(SW5_GPIO_Port,SW5_Pin)==GPIO_PIN_RESET){
        HAL_Delay(1000);
        number = number + 1 ;
        printf("number incremented with 1 is: %d\n",number);

    }
} 

i need to create a binary counter with 1 button i have declared 4 leds before with the name: LED5 LED6 LED7 LED8

if I click on the button I credit a number I have to convert this number to a binary value and display it on the given leds can you help me?

Yours sincerely


Solution

  • Using & and swift<< you can write this like:

    if (number & 1) {
      AL_GPIO_WritePin(SW5_GPIO_Port, GPIO_PIN_5, 1);
    } else {
      AL_GPIO_WritePin(SW5_GPIO_Port, GPIO_PIN_5, 0);
    }
    if (number & 1 << 1) {
      AL_GPIO_WritePin(SW5_GPIO_Port, GPIO_PIN_6, 1);
    } else {
      AL_GPIO_WritePin(SW5_GPIO_Port, GPIO_PIN_6, 0);
    }
    if (number & 1 << 2) {
      AL_GPIO_WritePin(SW5_GPIO_Port, GPIO_PIN_7, 1);
    } else {
      AL_GPIO_WritePin(SW5_GPIO_Port, GPIO_PIN_7, 0);
    }
    if (number & 1 << 3) {
      AL_GPIO_WritePin(SW5_GPIO_Port, GPIO_PIN_8, 1);
    } else {
      AL_GPIO_WritePin(SW5_GPIO_Port, GPIO_PIN_8, 0);
    }
    

    Not sure for the command to activate GPIO_PIN but the logic is here