I am trying to write a program in which I am interfacing a switch and a LED. I want a program so that when I press the switch the LED turns on and when I press again that led turns off. Right now I have made a program in which when I press the switch the LED turns on and then goes off.
void main()
{
DDRA=0x01; // Interfacing LED at PORTA.0
DDRB=0xFE; // Interfacing Switch at PORTB.0
PORTB=0xFF;
while(1)
{
if(PINB==0xFE)
{
PORTA=0x01;
}
else
{
PORTA=0x00;
}
}
}
Answer
I guess, you are dealing with a push button and not a switch. So Pin0
on PORTB (PB0)
stays LOW as long as you are pushing the button, the if statement
is fulfilled and your LED will be turned on. But once you release the button, PB0
will go back HIGH and the else branch
will be executed, thus your LED will be turned off immediately.
You need an additional variable, which changes only on button pushes and remains unchanged on button releases. Then you can control the LED with this variable.
Example:
void main()
{
DDRA |= (1< DDRB &= ~(1<
uint8_t status = 0;
while(1)
{
if(!(PINB & (1< {
status = !status;
}
if(status)
{
PORTA |= (1< }
else
{
PORTA &= ~(1< }
}
}
In addition have a look at this question about bit operations. Very useful when you want to change only one bit on a PORT and let the rest unchanged.
A simpler soultion is to toggle the LED controller pin itself on button pushes. To do so, the XOR operator: ^
could be used as follows PORTA ^= (1<
1
(HIGH) with the current value of the PIN.
- If the LED is on, the current value of the PIN is
1
(HIGH), which we XOR with another1
. The result will be1 XOR 1 = 0
so the LED will be turned off. - Now, when the LED is off, the current value of the PIN is
0
(LOW), which we XOR with1
again. The result will be0 XOR 1 = 1
so the LED will be turned on.
Example:
void main()
{
DDRA |= (1< DDRB &= ~(1<
while(1)
{
if(!(PINB & (1< {
PORTA ^= (1< }
}
}
No comments:
Post a Comment