Embedded C Program for Home Automation System
GPIO pins and input sensors; for example, use if statements to turn on/off lights based on sensor input with code like if(sensor == ON) light = ON;.Examples
How to Think About It
if conditions. The program runs in a loop to keep checking and updating device states.Algorithm
Code
#include <avr/io.h> #include <util/delay.h> int main(void) { DDRB |= (1 << PB0); // Set PB0 as output (light) DDRC &= ~(1 << PC0); // Set PC0 as input (sensor) while(1) { if (PINC & (1 << PC0)) { // If sensor is ON PORTB |= (1 << PB0); // Turn light ON } else { PORTB &= ~(1 << PB0); // Turn light OFF } _delay_ms(100); } return 0; }
Dry Run
Let's trace sensor input ON and OFF through the code
Initialize pins
PB0 set as output, PC0 set as input
Sensor input ON
PINC & (1 << PC0) is true, so PORTB |= (1 << PB0) sets PB0 HIGH
Light ON
Light connected to PB0 turns ON
Sensor input OFF
PINC & (1 << PC0) is false, so PORTB &= ~(1 << PB0) clears PB0
Light OFF
Light connected to PB0 turns OFF
| Step | Sensor Input (PC0) | Light Output (PB0) |
|---|---|---|
| 1 | N/A | Configured |
| 2 | 1 (ON) | 1 (ON) |
| 3 | 1 (ON) | 1 (ON) |
| 4 | 0 (OFF) | 0 (OFF) |
| 5 | 0 (OFF) | 0 (OFF) |
Why This Works
Step 1: Pin Setup
We set the sensor pin as input and the light pin as output using DDRx registers to control hardware pins.
Step 2: Reading Sensor
The program reads the sensor state by checking the input pin with PINC & (1 << PC0).
Step 3: Controlling Light
If the sensor is ON, the light pin is set HIGH to turn the light ON; otherwise, it is set LOW to turn it OFF.
Alternative Approaches
#include <avr/io.h>
#include <avr/interrupt.h>
ISR(PCINT1_vect) {
if (PINC & (1 << PC0)) {
PORTB |= (1 << PB0);
} else {
PORTB &= ~(1 << PB0);
}
}
int main(void) {
DDRB |= (1 << PB0);
DDRC &= ~(1 << PC0);
PCICR |= (1 << PCIE1);
PCMSK1 |= (1 << PCINT8);
sei();
while(1) {}
return 0;
}#include <avr/io.h> #include <util/delay.h> int main(void) { DDRB |= (1 << PB0); DDRC &= ~(1 << PC0); while(1) { if (PINC & (1 << PC0)) { PORTB |= (1 << PB0); } else { PORTB &= ~(1 << PB0); } _delay_ms(500); } return 0; }
Complexity: O(1) time, O(1) space
Time Complexity
The program runs in a continuous loop checking sensor input and updating output without loops dependent on input size, so time complexity is constant O(1).
Space Complexity
Uses fixed memory for registers and variables, no dynamic memory allocation, so space complexity is O(1).
Which Approach is Fastest?
Interrupt-driven approach is fastest in response time but more complex; polling is simpler but slower to react.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Polling Loop | O(1) | O(1) | Simple projects, easy to implement |
| Interrupts | O(1) | O(1) | Fast response, efficient CPU usage |
| Timer Polling | O(1) | O(1) | Balanced simplicity and responsiveness |