Skip to main content
CGran.2
Associate
June 14, 2021
Question

Counting up from GPIO READ

  • June 14, 2021
  • 4 replies
  • 1100 views

Hi,all:

I wrote a code for counting up when GPIO ReadPin change high level to low, here is the code:

while(1)

{

HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_SET);

if(HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_10)==1)

{

HAL_Delay(1);

if(HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_10)==0)

{

cnt=cnt+1;

}

}

if(cnt==3)

{

HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET);

break;

}

}

It's work, but...

did it has any way to remove "HAL_Delay()", and make it work also?

I'm worried that it will affect the operation of other functions...

    This topic has been closed for replies.

    4 replies

    waclawek.jan
    Super User
    June 14, 2021

    Remember the pin's state in a variable, and compare the new reading to that variable to find out the 1->0 change.

    If the input comes from a pushbutton, you may need to implement some form of debouncing, ie. don't accept new state until it is stable for long enough. For that, you may need another variable, remembering the time when the state changed, and comparing that to any system time you have (e.g. systick-originated see how HAL_Delay() is implemented).

    JW

    CGran.2
    CGran.2Author
    Associate
    June 14, 2021

    so what I need to do is save data before read and after then compare, right?​

    waclawek.jan
    Super User
    June 14, 2021

    global variable:

    int pin_state;

    [...]

    while(1) {

    int new_pin_state = HAL_GPIO_ReadPin(GPIOE,GPIO_PIN_10);

    if ((pin_state == 1) && (new_pin_state == 0)) {

    // do here whatever you want to do for the 1-to-0 transition

    }

    pin_state = new_pin_state;

    }

    JW

    CGran.2
    CGran.2Author
    Associate
    June 14, 2021

    Thanks!!!! It help me a lot!!!