While loop in Embedded C

Hi everyone, i started coding embedded C recently, based on my understanding of While loop it loops over the code as long as the while loop condition remains true, in my simple Led chaser code on ATmega324 bord i was expecting it to break as soon as i released the button switch but the loop kept executing every single line inside it and the LEDs kept lighting up. i came with a solution which was adding a For loop with an IF statement inside it to check if the push button is still pressed. but am still wondering why would the while loop keep on going while the condition is not TRUE anymore. "i believe that an IF statement would do that not a while loop" #define F_CPU 16000000UL //define the 16 MHZ crystal Clock #include <avr/io.h>
#include <util/delay.h> #define BUTTON_PIN (1<<PINB7) int main(void) { DDRD = 0b11111111; DDRB &= ~(1 << DDB7); // Set PB7 as input int x; PORTB |= (1 << PORTB7); //enable the the internal pull up resistor of PINB7
while (1) { while (!(PINB & BUTTON_PIN)) { PORTD = 0b0000001; _delay_ms(50); PORTD = 0b0000011; _delay_ms(50); PORTD = 0b0000111; _delay_ms(50); PORTD = 0b0001111; _delay_ms(50); PORTD = 0b0011111; _delay_ms(50); PORTD = 0b0111111; _delay_ms(50); PORTD = 0b1111111; _delay_ms(50); PORTD = 0b0000000; _delay_ms(50);
PORTD= 0b00000000; } PORTD= 0b00000000; } }
No description
No description
No description
3 Replies
Marvee Amasi
Marvee Amasi3w ago
Hi @Abdullah Batis , can you introduce a short delay after reading the button state to account for any bouncing that might occur. Cus you would need to allow the button to stabilize before reading its state again Instead of relying solely on the while loop, use an if statement with a small delay to check the button state
Abdullah Batis
Thanks for your help, really appreciated.
Marvee Amasi
Marvee Amasi2w ago
You are welcome
Want results from more Discord servers?
Add your server