I'm following a tutorial in a book to turn off and on an LED using a pushbutton. Theoretically the LED should remain off until I turn it on using the pushbutton switch. What actually happens is that the LED is constantly on and not reacting to the pushbutton switch at all. Can someone please look this over and explain what is wrong? Here is the code and fritzing diagram of my wiring.
#define LED 13 // Pin for the LED
#define BUTTON 2 // The input pin where the
// pushbutton is connected
int val = 0; // variable stores value of input
// pin
int old_val = 0; // this variable stores previous
// value of val
int state = 0; // 0 = LED off and 1 = LED on
void setup() {
pinMode(LED, OUTPUT);
pinMode(BUTTON, INPUT);
}
void loop() {
val = digitalRead(BUTTON);
// check if there was a transition
if ((val == HIGH) && (old_val == LOW)) {
state = 1 - state;
delay(10);
}
old_val = val;
if (state = 1) {
digitalWrite(LED, HIGH); // turn LED on
} else {
digitalWrite(LED, LOW); // turn LED off
}
}
Sorry for the lack of a response you're probably looking for but ...
While comments can be interesting they can also be wrong, misleading or out of sync with the actual code.
I'm going to make a suggestion early on that you come up with some naming convention of symbols to allows you to reduce the need for comments as much as possible. This will make your cod easier to read and debug ...
Thank you HazardsMind! It works great now and I also just learned it's possible to assign variables within a conditional expression. I need to pay way more attention to my tokens. @Lloyddean, I'm obviously still in arduino kindergarten, but I will heed that advice. Thanks again.
Despite the errors in the code I think debounce would be an issue as well. When you push a button, it takes around 150ms to get it down. But in those 150ms the button sometimes doesn't just change the state at once but instead it could have on/off flicks of as fast as 5ms in one single push. This happens because of the hardware, but then the Arduino reads those debounces and thinks that that they are state changes. Consider adding some debounce code to you sketch.
Read more on the topic for a better understanding: