I am trying to create a toggle switch that turns On or Off an LED depending on its current state. If I press the button and it's On, I want it to turn Off the LED and visa-versa.
What happens with my current code is that it will work.... sometimes. The LED is off, then I press and release the button, the LED turns ON, then I press and release the button, the LED goes off. But sometimes it just stays On when I press the button or it doesn't turn On at all.
I wired 5v into 1 side of a momentary switch. On the other end I wired a 1K resistor to the negative side of the switch to pull down for any noise in the circuit and connected also the negative to Digital Input 2 on the Arduino. The positive side of the LED is wired to Digital Output 13 on the Arduino and the negative side is wired to the negative terminal with a 220K resistor.
As you can see from the code below I am using an "if" statement to test if the button is pressed and if the LED is On or not. Then I perform the appropriate digitalWrite to either turn the LED On or Off depending on the LED's current state.
int ledPin = 13;
int switchPin = 2;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(switchPin, INPUT);
}
void loop() {
if (digitalRead(switchPin) == LOW && digitalRead(ledPin) == HIGH) {
digitalWrite(ledPin, HIGH);
}
else if (digitalRead(switchPin) == LOW && digitalRead(ledPin) == LOW) {
digitalWrite(ledPin, LOW);
}
else if (digitalRead(switchPin) == HIGH && digitalRead(ledPin) == HIGH) {
digitalWrite(ledPin, LOW);
}
else if (digitalRead(switchPin) == HIGH && digitalRead(ledPin) == LOW) {
digitalWrite(ledPin, HIGH);
}
delay (5);
}
Can I perform a digitalRead on a pin I specified as an OUTPUT?
Is there a better way to accomplish this?
Any help is greatly appreciated!