In: Computer Science
in arduino, having two LED lights, I need to find a way to turn one LED with the push of a button, then with a next push of the button turn off the first LED and turn the second LED on. Help with the circuit and code would be appreciated.
Answer : please up vote or comment for any query i will update the same .Thanks
Circuit Description
1. push button connected to PIN 2
2. LED1 connected to PIN 13
3. LED2 connected to PIN 12
Program plan : -
1. push button set INPUTand PULL UP on to detect LOW state when button pressed
2. set OUTPUT LED1 and LED2
3. read button state as LOW if first time turn ON LED1 and turn OFF LED2
4. button pressed again turn OFF LED1 and turn ON LED2
Program :
int pushButton = 2; //pushbutton pin of arduin UNO
int LED1=13; //pin of LED1
int LED2=12; //pin of LED2
int count=0; //to check for button press count
void setup() {
pinMode(pushButton, INPUT); //set push button pin as input
digitalWrite(pushButton,HIGH); //turn on pull up resistor
pinMode(LED1,OUTPUT); //set LED1 pin as output
pinMode(LED2,OUTPUT); //set LED2 pin as output
}
void loop() {
int buttonState = digitalRead(pushButton); //read push button
state
if(buttonState==LOW) //if button state is LOW button pressed
{
if(count==0) //if first time button pressed turn on LED1 and turn
off LED2
{
digitalWrite(LED1,HIGH);
digitalWrite(LED2,LOW);
count++; //increment count by 1
}
else if(count==1) //if button pressed second time
{
digitalWrite(LED1,LOW); //turn off LED1 and turn on LED2
digitalWrite(LED2,HIGH);
count=0;
}
delay(200); //delay for debounce to cancel noise
}
}
Circuit Diagram :