I have a push button PC13 and my LED PA5. I want to push my button so that the current state (on, off and toggle) switches to the next one. So for example: The LED is currently on, I push a button, LED switches off, I push the button again and it toggles, I push the button again and it stays on, and so on. When I debug this the counter variable switches to the desired number I am currently at and while I debug this it works perfectly fine. However, as soon as I upload it to the board it doesn't work like in debug state. It is on and then toggles and every additional button push doesn't change.
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
int counter = 0;
while (1)
{
int stateOfPushButton = 0;
if (!HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13) == 1){ //Check if button pressed
HAL_Delay(5); //check for bounce
if (!HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13) == 1){
stateOfPushButton = 1;
}
}
counter = (counter + stateOfPushButton)%3;
if(counter == 0){
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5,GPIO_PIN_SET); //Led Switch On
}
else if(counter == 1){
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5,GPIO_PIN_RESET); //Led Switch Off
}
else{
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5); // Led toggled
HAL_Delay(1000);
}
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
EDIT:
I added a delay function to check for bounces in the button, proposed by @Jose and the problem persists.
EDIT 2:
It works better, although not ideal, when decreasing the delay function. I guess, my interrupt gets into conflict with the delay function.
question from:
https://stackoverflow.com/questions/65859746/switching-between-on-off-and-toggle-led-stm32f303re 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…