Sunday, February 3, 2013

Switch and LEDs

In this tutorial I am going to show you, how to blink a LED whenever a switch is pressed using AVR micro controller. I am using ATmega128/ ATmega64 (both of the micro controller can be used interchangeably as they differ in the size of flash memory only). The LED is connected to pin 0 of PORTC (PC0) and the switch is connected to the pin 0 of PORTA (PA0) of the micro controller. I have assumed that the LED is connected in sinking logic i.e. whenever +5V is provided by the controller the LED will be OFF and whenever the 0V is supplied the LED will be ON and the switch is ACTIVE LOW i.e. it provides a 0V on being pressed.

The step to program are as follow-

1. Set the corresponding PORTs as input or output.
2. Enable pull-up resistors for the input pin.
3. Check for the input continously.
4. Whenever the switch is pressed, turn on the LED.

Here is the code:

//Include AVR Header file
#include"avr/io.h"

void main()
{ 
//Set pin 0 of PORTC as output
DDRC |= (1<<0);

//Set pin 0 of PORTA as input
DDRA &=~ (1<<0);

//Enable pull-up resistor so that false inputs can be ignored
PORTA |= (1<<0);

  //infinite loop
while(1)
{
//Check for any input if an input (0v) is detected, turn ON the LED
if( !(PINA & (1<<0)))
PORTC &=~ (1<<0);

else //turn OFF the LED
PORTC |= (1<<0);
}
}
In place of LED you can connect different output devices such as Buzzer, Relays etc.

0 comments:

Post a Comment

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews