I have been working my way through tons of examples and when I was working through the Banzi book I had something very odd happen.
I entered the code exactly as in the text (after making that damnable mistake with the = instead of ==, grrr...)
but I kept having problems with the debounce, only about 75% accuracy when using any amount of delay: tried 10, 20, 40, 80, 100, 200 etc; Still I was getting VERY inconsistent results. By accuracy I mean that a button push would flash the LED but not always change the state of the LED.
I put in a serial print to see if I could identify anything in the output that was odd. I placed this after the else statement at the very end of the program.
Serial.println(state);
and suddenly the thing worked beautifully. probably about 99% accuracy.
A little bit more fooling around and I moved the delay statement to the end of the loop instead of where it is in the book example and, without any other alteration, it is now working perfectly.
Can anyone explain why simply moving the delay function would cause such a radical change in behavior? Also, I switched all this code around about 15 times, going back and forth between my fix and the original code: in every case, the best accuracy is achieved by moving the delay function to the end of the loop.
Any advice on understanding this would help me understand coding much better.
I am using an UNO R3, arduino board.
Here is my code
//Example 03B: Turn on the LED when the button is pressed
//and keep it on after release
//with new and improved formula
// and now with fabulous debouncing included!!
const int LED = 13; //LED pin
const int BUTTON = 7; //button pin
int val = 0; //stores state of pin
int old_val = 0; //place to hold last state written
int state = 0; //holds value after a change
void setup(){
pinMode(LED, OUTPUT); //sets LED pin as output
pinMode(BUTTON, INPUT); //sets button pin as input
}
void loop(){
val = digitalRead(BUTTON); //Reads state of button
if (val == HIGH && old_val==LOW){
state = 1 - state; //changes state if value is high
}
old_val = val; //changes old_val to last val
if (state == 1){
digitalWrite(LED, HIGH); //writes current state to LED
}
else{
digitalWrite(LED, LOW);
}
delay(10); //the code only works reliably with the delay function here
}