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

when the microcontroller is programmed, and the button is pressed several times, it is evident that the LEDs will toggle, sometimes correctly, and sometimes will toggle multiple times with only one button press. Add the capacitor and check the button pressing and LED toggling again. On the ocilliscope, with the capacitor installed, a gradual rise of the voltage is created when the button is pressed, opposed to a bunch of up and down voltages resulting from a bounce from the mechanical parts of the button. But when the button is released, it shows that the voltage is a direct change. This is because another capacitor is not installed between the button and the microcontrolle

#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;
}
}
}

Circuit Diagram

Video


No comments

Theme images by Dizzo. Powered by Blogger.