AVR | Blinking 2 LEDs Alternatively with the help of Button

In this tutorial, we will learn how to write a program to blink LEDs using a button such that when the button is in ON condition, LED 1 blinks and when the button is OFF the other LED i.e., LED 2 blinks. By Suryaveer Singh Last updated : May 12, 2023

Blink 2 LEDs Alternatively with the help of Button using AVR and Atmel Studio

C 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

Blink 2 leds in AVR

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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.