How to control LED using Button
This is the 2nd tutorial in the AVR Series, and today we will see how to use a button. We will use this button to control the LED on our ATtiny85 MCU.
The button is connected to the pin PB0, which we need to configure as the input pin. Below is the connection diagram showing how the button is connected.
One end of the button is connected to the pin PB0 and another end is connected to the Ground.
I have also shown the LED connected to the pin PB1, but the breakout board I am using already have the LED on it.
The Code
There are 2 pins involved in this tutorial. The button is connected to the pin PB0 and the LED is connected to the pin PB1.
The pin PB0 needs to be configured as input, and I am going to enable the pull-up on this pin. This will keep the default state of the pin to HIGH.
TO set the pin as input, we need to write a 0 in the DDRB register, and to enable the pull-up for the input pin we write a 1 to the respective bit of the POTRB register.
DDRB = 0x02; // 0b 0000 0010 -> PB0 = Input, PB1 = Output
PORTB = 0x01; // 0b 0000 0001 -> PB0 = Pull-up, PB1 = Out LOW
The value 0x02 is set to the DDRB register. This is equivalent of the binary 0000 0010. Here the bit PB0 is set to 0, so that it can be used as the input pin and the bit PB1 is set to 1 so that it can be used as the output pin.
The value 0x01 is set to the PORTB register. This is equivalent of the binary 0000 0001. Here the bit PB0 is set to 1 so that the Pull-up is enable for the pin and the bit PB1 is set to 0 so that the default state of the LED can be LOW.
while(1)
{
if ((PINB&(1<<PINB0)) == 0) // If the Button is pressed, the PB0 goes LOW
{
PORTB |= 1<<PB1; // Turn the LED ON
}
else // If the button is released, the PB0 goes HIGH
{
PORTB &= ~(1<<PB1); // Turn the LED OFF
}
}
The PINB Register is used to read the input state of the Pins. Similalry the PORTB register is used to set the output state of the pin.
In the while loop we read the state of the pin PB0. Since we have enabled the Pull-up for this pin, the default state of PB0 remains HIGH. When the button is presses, The pin is pulled LOW to the ground.
If this happens, we turn the LED ON by setting the pin PB1.
When the button is released, the pin PN0 is pulled up to HIGH again. At this point we turn the LED OFF.
Result
Below is the gif showing the result of the above code.
As you can see whenever the button is pressed, and for as long as the button is pressed, the LED remains ON. As soon as the button is released, the LED turns OFF again.