Hi all,
I am tying to use the debounce example as a function to toggle switch state. As i will have a few switch inputs in my Loop I though having 1 function to manage this would be better.
This is the code as it sits right now...
// constants won't change. They're used here to
// set pin numbers:
const int upMotor = 8;
const int dnMotor = 9;
const int button1 = 2;
const int button2 = 3;
void setup() {
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
pinMode(upMotor, OUTPUT);
pinMode(dnMotor, OUTPUT);
// set initial Motor state
Serial.begin(9600);
}
void loop(){
int upButtonState = LOW;
int dnButtonState = LOW;
int upButton;
int dnButton;
int upMotorState;
upButton = digitalRead(button1);
dnButton = digitalRead(button2);
digitalWrite(upMotor, upMotorState);
upButtonState = debounce(upButton);
Serial.print(upButton);
Serial.print(upButtonState);
Serial.print(upMotorState);
}
int debounce(int button) {
// the current state of the output pin
int outputState = LOW;
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50; // the debounce time; increase if the output flickers
// read the state of the switch into a local variable:
int reading = digitalRead(button);
Serial.print(" buttonState ");
Serial.print(buttonState);
Serial.print(" lastButtonState ");
Serial.print(lastButtonState);
Serial.print(" lastDebounceTime ");
Serial.print(lastDebounceTime);
Serial.println(reading);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited
// long enough since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the output if the new button state is HIGH
if (buttonState == HIGH) {
outputState = !outputState;
}
}
}
// set the output:
return outputState;
// save the reading. Next time through,
// it'll be the lastButtonState:
lastButtonState = reading;
}
Some notable behavior:
"upButton" and "reading" Both change state on the button press. Which is to be expected. However, "lastbuttonState" and "lastDebounceTime" do not change at all.
SO what I am assuming is that there is a breakdown somewhere around line 89 of this code "if (reading != lastButtonState)".
any ideas or suggestions what what to do next to see why this is getting stuck would be appreciated.