Skip to main content
CGran.2
Associate
Jun 14, 2021 7:40 AM UTC
Question

Counting up from GPIO READ

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
    Jun 14, 2021 8:52 AM UTC

    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
    Jun 14, 2021 9:30 AM UTC

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

    waclawek.jan
    Super User
    Jun 14, 2021 10:43 AM UTC

    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
    Jun 14, 2021 1:01 PM UTC

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