2023-03-14 10:39 AM
Hi
I am trying to implement a single increment counter driven by a button press. I am using the STM32F429I-DISC1 evaluation board. I have created a GUI in touch GFX and that is displaying the counter number and increments when I press the blue button on the evaluation board. The problem that i'm having is that if you push and hold the pushbutton down then this keeps incrementing the counter until i release it. What i want to achieve is that a single press of the push button (regardless of duration) only increments the counter only 1 until it is released. Then it will increment again when it is pushed again.
I have written a simple case and switch statement to detect the pin high but I am struggling to restrict the counter to one increment per push. Here is the switch and case statement (feel free to suggest another method is this is not the correct way to implement this.
button_val = HAL_GPIO_ReadPin(GPIOA, B1_Pin); // Button val is the state of the pushbutton
switch (button_val)
{
case 1: ((button_val == 0) & (button_val_flag == 0)); // button_val_flag is the flag is the buffered state of the push button.
buttoncounter = buttoncounter;
case 2: ((button_val == 1) & (button_val_flag == 0));
buttoncounter ++;
button_val_flag = 1; // Increment the Counter by 1 & raise the flag for Input high.
Unicode::snprintf(ButtonTextAreaBuffer, BUTTONTEXTAREA_SIZE,"%u", buttoncounter); // Write to the variable for the button counter.
ButtonTextArea.invalidate(); // Invalidate the text area so that it can be updated on the screen.
//HAL_Delay (100);
button_val = HAL_GPIO_ReadPin(GPIOA, B1_Pin);
case 3: ((button_val == 1) & (button_val_flag == 1));
buttoncounter = buttoncounter;
case 4: ((button_val == 0) & (button_val_flag == 1));
button_val_flag = 0;
}
Any advice?
2023-03-14 10:55 AM
It looks as though you have made an error in your switch statement.
At the end of each case i.e. before the next case you need to have a "break" statement. Otherwise execution will fall into the next case - not what you normally want!
2023-03-14 11:30 AM
switch ( expression )
{
// declarations
// . . .
case constant_expression:
// statements executed if the expression equals the
// value of this constant_expression
break;
default:
// statements executed if expression does not equal
// any case constant_expression
}