In this program to make two LEDs toggle when the push button is pressed is very simple. First, the pins are initialized: Pins outputting to the LEDs are set to output in the DDR (Data Direction Register). One of the LEDs are toggled high, so at the start, one is on and one is off. Then, the never ending loop is started and the code within that block gets executed until the microcontroller loses power. Withing this loop, the pin that is connected to the push button is constantly checked to determine if it is on. If it is pressed, and exhibits a 1, then it checks if the button was firsts released. This is important, because if we don't have this check, the button will just toggle continuously while the button is pressed. We only want the button to toggle if the button is pressed and then released
#include <avr/io.h>
int main(void)
{
DDRB |= 1 << PINB0; //Set Direction for output on PINB0
PORTB ^= 1 << PINB0; //Toggling only Pin 0 on port b
DDRB |= 1 << PINB2; //Set Direction for Output on PINB2
DDRB &= ~(1 << PINB1); //Data Direction Register input PINB1
PORTB |= 1 << PINB1; //Set PINB1 to a high reading
int Pressed = 0; //Initialize/Declare the Pressed variable
while (1)
{
if (bit_is_clear(PINB, 1)) //Check is the button is pressed
{
//Make sure that the button was released first
if (Pressed == 0)
{
PORTB ^= 1 << PINB0; //Toggle LED in pin 0
PORTB ^= 1 << PINB2; //Toggle LED on pin 2
Pressed = 1;
}
}
else
{
//This code executes when the button is not pressed.
Pressed = 0;
}
}
}
Video
You can complete download Atmel Studio files and Proteus File Click Here or Click Here
Proteus Software free download with Crick Click Here
No comments