Consider this embedded C code snippet for blinking an LED connected to PORTB pin 0. What will the LED do when this code runs?
#include <avr/io.h> #include <util/delay.h> int main(void) { DDRB |= (1 << 0); // Set PORTB0 as output while(1) { PORTB ^= (1 << 0); // Toggle PORTB0 _delay_ms(500); } return 0; }
Look at how PORTB0 is toggled inside the infinite loop with a delay.
The code sets PORTB0 as output and toggles its state every 500 ms, causing the LED to blink on and off repeatedly.
Examine this code snippet intended to blink an LED on PORTD pin 2. What error will occur when compiling?
#include <avr/io.h> int main(void) { DDRD = 1 << 2; // Set PORTD2 as output while(1) { PORTD = 1 << 2; // Turn LED on _delay_ms(1000); PORTD = 0 << 2; // Turn LED off _delay_ms(1000); } return 0; }
Check if all required headers are included for delay functions.
The code uses _delay_ms but does not include <util/delay.h>, so the compiler will complain about an undeclared function.
This code is supposed to blink an LED on PORTC pin 5, but the LED stays off. What is the bug?
#include <avr/io.h> #include <util/delay.h> int main(void) { DDRC |= (1 << 5); // Set PORTC5 as output while(1) { PORTC = (1 << 5); // Turn LED on _delay_ms(300); PORTC = 0; // Turn LED off _delay_ms(300); } return 0; }
Think about how PORTC is assigned inside the loop and what happens to other pins.
Assigning PORTC directly overwrites all pins, so toggling does not happen properly. Using XOR toggle (^) preserves other pins and toggles the LED.
Identify the option that corrects the syntax error in this code snippet:
#include <avr/io.h>
#include <util/delay.h>
int main(void) {
DDRB |= (1 << 3) // Set PORTB3 as output
while(1) {
PORTB ^= (1 << 3);
_delay_ms(250);
}
return 0;
}Look carefully at the line before the while loop.
The missing semicolon after DDRB |= (1 << 3) causes a syntax error. Adding it fixes the code.
This code blinks an LED connected to PORTD pin 1. How many times will the LED turn on and off in 10 seconds?
#include <avr/io.h> #include <util/delay.h> int main(void) { DDRD |= (1 << 1); // Set PORTD1 as output for (int i = 0; i < 20; i++) { PORTD ^= (1 << 1); // Toggle LED _delay_ms(250); } return 0; }
Each toggle changes LED state. Count full on-off cycles in 10 seconds.
The loop toggles LED 20 times with 250 ms delay each toggle. One full blink cycle (on + off) takes 2 toggles = 500 ms. So 20 toggles = 5 seconds, which equals 10 full blinks.