AVR | Blinking 2 LEDs Alternatively with the help of button

In this article we would learn a program to blink LEDs using a button such that when our button is in ON condition, LED 1 blinks and when our button is OFF the other LED i.e. LED 2 blinks.
Submitted by Suryaveer Singh, on June 20, 2018

Program to blink 2 LEDs Alternatively

#include<avr/io.h>

int main(void)
{
DDRA=0x03;
DDRD=0x00;

while(1)
{
if((PIND & 0x01) == 0x01)
PORTA=0x01;
else
PORTA=0x02;
}
}

Explanation

Here, DDRA = 0x03 indicates the input given to both our LEDs. The LEDs are connected in the terminal PA0 and PA1 i.e. the pin 0 & 1.

PINS:	7	6	5	4	3	2	1	0
INPUTS:	0	0	0	0	0	0	1	1

The input can be written in hexadecimal as 03. Therefore, we have written DDRA = 0x03.

DDRD = 0x00 represents the input to the button which we have connected in the D port.

Inside the IF statement we have represented the condition which says that when the button is pressed the input 1 will be given to the PORTA at the 0th PIN. i.e. LED 1 will glow.

In the else condition we have given the statement such that when our Button won’t be pressed the LED 2 would Blink continuously.

Simulation

Explanation

• Components needed:
1. 2 resistors (330 ohm)
2. 2 LEDs
3. ATmega16
4. Button
5. One resistor of 10k ohm value
6. Power Terminal
7. Two Ground Terminal
• Arrange the components as shown in the above image.
• Here we have connected the resistance of 10k here because the current from the power terminal will always prefer a low resistance path, so instead of going to the ground it will go directly to the ATmega16.
• While simulating the setup you will observe that when the Switch is OFF , LED 2 will glow continuously.
• And when you press the button you will observe that the LED 1 will glow and LED 2 will stop glowing.

What's New

Top Interview Coding Problems/Challenges!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates