AVR GPIO Programming With C
AVR GPIO Programming With C
#include <util/delay.h>
while(1) {
PORTB &= ~0B100000; // Set PB5 low (turn the LED off)
TASK 2: To check and indicate the status of a sensor using the specified ports and bits of
ATmega328P.
A door sensor (here, assume the switch) is connected to pin 1 of Port B, and an LED is connected to
pin 5 of Port C. Write an AVR C program to monitor the door sensor and, when it opens, turn on the
LED.
#include <avr/io.h>
DDRB &= ~(1 << PB1); //Configure PB1 as input for the door sensor
while (1) {
if (PINB & (1 << PB1)) { // Check if the door sensor (PB1) is open
PORTC |= (1 << PC5); // If the sensor is open, turn on the LED (set PC5 high)
else {
PORTC &= ~(1 << PC5); // If the sensor is closed, turn off the LED (set PC5 low)
Post Lab Tasks
return 0;
TASK 3: To use the general I/O pins of ATmega328P as input or output pin based on the
given condition.
Write an AVR C program to monitor bit 7 of Port B. If it is 1, make bit 4 of Port B input; otherwise,
change pin 4 of Port B to output.
#include <avr/io.h>
while (1) {
DDRB &= ~(1 << PB4); // If PB7 is 1, make bit 4 of Port B (PB4) an input
} else {
return 0;
TASK 4: To control the specified pins of a given port without disturbing the rest of the pins.
Write an AVR C program to control a set of 8 LEDs connected to port D such that the first 4 LED
glow when input from a switch is high, and remain off when the input from switch is low. The
remaining 4 LED toggle continuously without disturbing the rest of the pins of port D.
#include <avr/io.h>
#include <util/delay.h>
DDRD |= 0x0F; // Configure PD0 to PD3 as output for the first 4 LEDs
DDRD |= 0xF0; // Configure PD4 to PD7 as output for the remaining 4 LEDs
DDRB &= ~(1 << PB0); // Configure PB0 as input for the switch
while (1) {
} else {
PORTD &= ~0x0F; // If the switch is low, turn off the first 4 LEDs (PD0 to PD3)
return 0;
#include <avr/io.h>
int main (void) {
DDRB &= ~((1 << PB0) | (1 << PB1)); // Configure PB0 and PB1 as input
DDRD |= (1 << PD0) | (1 << PD1) | (1 << PD2); // Configure PD0, PD1, and PD2 as output
while (1) {
// Read the status of PB0 and PB1
uint8_t input = PINB & 0x03; // Mask to get only the first 2 bits
switch (input) { // Update LEDs on PD0, PD1, and PD2 based on input
case 0b00:
PORTD &= ~((1 << PD0) | (1 << PD1) | (1 << PD2)); // Set PD[2:0] to 000
break;
case 0b01:
PORTD = (PORTD & ~((1 << PD0) | (1 << PD1) | (1 << PD2))) | (1 << PD0) | (1 <<
PD1); // Set PD[2:0] to 011
break;
Post Lab Tasks
case 0b10:
PORTD = (PORTD & ~((1 << PD0) | (1 << PD1) | (1 << PD2))) | (1 << PD2) | (1 << PD0);
// Set PD[2:0] to 101
break;
case 0b11:
PORTD |= (1 << PD0) | (1 << PD1) | (1 << PD2); // Set PD[2:0] to 111
break;
}
}
return 0;
}