Embedded C Program to Control LED with Button
if (button_pin == PRESSED) { led_pin = ON; } inside a loop to turn on an LED when a button is pressed, and turn it off otherwise.Examples
How to Think About It
Algorithm
Code
#include <avr/io.h> #define BUTTON_PIN PD2 #define LED_PIN PD3 int main(void) { DDRD &= ~(1 << BUTTON_PIN); // Set button pin as input DDRD |= (1 << LED_PIN); // Set LED pin as output while (1) { if (PIND & (1 << BUTTON_PIN)) { // Button pressed (assuming active high) PORTD |= (1 << LED_PIN); // Turn LED ON } else { PORTD &= ~(1 << LED_PIN); // Turn LED OFF } } return 0; }
Dry Run
Let's trace pressing and releasing the button through the code
Initialize pins
BUTTON_PIN (PD2) set as input, LED_PIN (PD3) set as output
Button pressed
PIND & (1 << BUTTON_PIN) is true, so LED_PIN set high, LED turns ON
Button released
PIND & (1 << BUTTON_PIN) is false, so LED_PIN cleared, LED turns OFF
| Step | Button Pin State | LED Pin State | LED Status |
|---|---|---|---|
| 1 | Input mode set | Output mode set | LED OFF initially |
| 2 | Pressed (1) | Set high (1) | LED ON |
| 3 | Released (0) | Set low (0) | LED OFF |
Why This Works
Step 1: Pin Setup
We set the button pin as input to read its state and the LED pin as output to control the LED.
Step 2: Reading Button State
Inside the loop, we check if the button pin reads high (pressed) using PIND & (1 << BUTTON_PIN).
Step 3: Controlling LED
If pressed, we set the LED pin high to turn it on; otherwise, we clear it to turn the LED off.
Alternative Approaches
#include <avr/io.h> #define BUTTON_PIN PD2 #define LED_PIN PD3 int main(void) { DDRD &= ~(1 << BUTTON_PIN); // Button pin input PORTD |= (1 << BUTTON_PIN); // Enable pull-up resistor DDRD |= (1 << LED_PIN); // LED pin output while (1) { if (!(PIND & (1 << BUTTON_PIN))) { // Button pressed (active low) PORTD |= (1 << LED_PIN); // LED ON } else { PORTD &= ~(1 << LED_PIN); // LED OFF } } return 0; }
// Interrupt-based LED control example omitted for brevityComplexity: O(1) time, O(1) space
Time Complexity
The program runs in a continuous loop checking button state, which is a constant time operation each cycle.
Space Complexity
Uses fixed memory for registers and variables; no extra memory allocation.
Which Approach is Fastest?
Polling the button in a loop is simple and fast for small programs; interrupt-based methods can be more efficient for complex systems.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Polling in loop | O(1) | O(1) | Simple projects, easy to understand |
| Using pull-up resistor | O(1) | O(1) | Reliable button input without external resistor |
| Interrupt-based | O(1) | O(1) | Power saving and responsive in complex systems |