Home »
Embedded Systems
AVR | Blinking 4 LEDs Alternatively
In this tutorial, we will learn how to blink 4 LEDs alternately using AVR microcontroller and Atmel Studio, also write a C program for it.
By Suryaveer Singh Last updated : May 12, 2023
The only difference would be here we would require 4 LEDs and we will do some changes in our programming.
Program to blink 4 LEDs Alternatively
#include <avr/io.h>
#define F_CPU 1000000
#include <util/delay.h>
int main(void)
{
DDRA=0x0F;
while(1)
{
PORTA=0x01;
_delay_ms(1000);
PORTA=0x02;
_delay_ms(1000);
PORTA=0x04;
_delay_ms(1000);
PORTA=0x08;
_delay_ms(1000);
}
}
Explanation
The detailed explanation of similar program has been done previously so hereI would explain you things shortly.
The DDRA = 0x0F represents the pins that are given to our four LEDs here F represents 1111 in binary i.e. 4 inputs are given to LED.
PINS: 7 6 5 4 3 2 1 0
INPUTS: 0 0 0 0 1 1 1 1
Here 7, 6, 5, 4, 3, 2, 1, 0 are the Pins of the A slot, the ATMEGA16 has four slot A, B, C, D and each port has 8 pins.
In the above program we have given our input to the pins 3,2,1,0.
Inside the While loop, we have written codes such that at a time only one of the LED glows. PORT = 0x01 represents that the input has been given to the 0th pin.
PORT = 0x02 represents that input has been given to 1 pin, and so on...
Simulation
Simulation Explanation
-
Devices required:
- ATMEGA16
- Four Resistors (330 ohm)
- Four LEDs
- Ground terminal
- Arrange the devices as shown above or you can arrange them more beautifully :)
- Debug the created HEX file in the ATMEGA16 and play the Simulation. You will find that all the LEDs will blink alternately.
In the similar way using more creative Ideas you can create more beautiful designs/patterns using LEDs. Decreasing the delay time will blink LEDs more quickly.
Just for an Example, you can try to blink 2-2 LEDs at a time the only change in the program would in the while loop, there in the PORTA you have to include two inputs at a Time.