cancel
Showing results for 
Search instead for 
Did you mean: 

Counting up from GPIO READ

CGran.2
Associate II

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...

4 REPLIES 4

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

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

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

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