Question: Looking for the pseudo-code to implement: Toggle LED when buttons are
ID: 3778610 • Letter: Q
Question
Question:
Looking for the pseudo-code to implement: Toggle LED when buttons are pressed in this order: press button 1, press button 1, hold button 2 will turn on LED. After button 2 is released the LED will turn off. Overlaps are okay, any time button1 is pressed consecutively twice, then button 2 is pressed the LED will turn on.
We are given the following functions for button_pushed and button_released:
int ReadButton1Status( void )
{
if(GPIOA->IDR & GPIO_Pin_4 )
{
return( BUTTON_PUSHED );
}
return( BUTTON_RELEASED );
}
int ReadButton2Status( void )
{
if(GPIOA->IDR & GPIO_Pin_5 )
{
return( BUTTON_PUSHED );
}
return( BUTTON_RELEASED );
}
This is our code, currently it is WRONG because the first time button1 is pressed twice and button2 is held the LED turns on, but after that pressing button2 always turns the LED on:
while (1)
{
while(btn1_counter <= 2) //if button 1 has not been pushed more than twice
{
if(BUTTON_PUSHED == ReadButton1Status()) //if button 1 is pushed, increment the counter
{
btn1_counter++;
}
if(BUTTON_PUSHED == ReadButton2Status()) //if button 2 is pushed, reset the counter
{
btn1_counter =0;
}
}
//if the button1 counter is greater than 2 and button 2 has been pushed
if ( (btn1_counter >= 2) && (BUTTON_PUSHED == ReadButton2Status()) )
{
btn1_counter =0; //reset the button 1 counter
GPIO_SetBits(GPIOA, GPIO_Pin_0); //light up first led
//if button 2 is released
if ((BUTTON_RELEASED == ReadButton2Status()) )
{
GPIO_ResetBits(GPIOA, GPIO_Pin_0); //reset LED
}
}
else
{
GPIO_ResetBits(GPIOA, GPIO_Pin_0);
}
}
Explanation / Answer
Try this code:
while (1)
{
while(btn1_counter < 2) //if button 1 has not been pushed more than twice
{
if(BUTTON_PUSHED == ReadButton1Status()) //if button 1 is pushed, increment the counter
{
btn1_counter++;
}
if(BUTTON_PUSHED == ReadButton2Status()) //if button 2 is pushed, reset the counter
{
btn1_counter =0;
}
}
//if the button1 counter is greater than 2 and button 2 has been pushed
if ( (btn1_counter == 2) && (BUTTON_PUSHED == ReadButton2Status()) )
{
btn1_counter =0; //reset the button 1 counter
GPIO_SetBits(GPIOA, GPIO_Pin_0); //light up first led
//till button 2 is not released
while(BUTTON_RELEASED != ReadButton2Status()) );
GPIO_ResetBits(GPIOA, GPIO_Pin_0); //reset LED
}
else
{
GPIO_ResetBits(GPIOA, GPIO_Pin_0);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.