This probably won't answer your question completely, but here are some notes from me:
buttonState = current ; //read value again now that bouncing is over
This won't read the value again, it just copies current
into buttonValue
.
What you wanted is:
buttonState = digitalRead(BUTTON); // read value again now that bouncing is over
You have multiple issues with your debounce
call:
lastTimeDebounce
is never used by your code, so it is always zero.
lastButtonState
will be always buttonVal
making the debounce function useless.
Some other tips:
Don't use the same names for parameters as for global variables:
boolean debounce(boolean lastButton, long lastDebounce, int BUTTON)
The global variable BUTTON
will be shadowed by int BUTTON
, essentially overriding it.
Don't use global variables (unless you have a very good reason)
EDIT
I would strongly recommend writing a function that debounces only one pin.
Because if you want a function which can debounce any pin you would need a state variable for each pin (which needs arrays hence a lot of space).
EDIT2:
Here is a debounce function that should work:
const uint8_t PIN = 13;
/*
* Returns debounced value for `PIN`
*/
boolean debounce(void)
{
// Current state of the pin
boolean currentState;
// Last state of the pin, initial value is zero
static boolean lastCurrentState = 0;
// Timer
static unsigned long debounceTimer = millis();
// Debounced value, initial value is zero
static boolean debouncedValue = 0;
// We first read the current state of the pin
currentState = digitalRead(PIN);
// Then we look if the state has changed
if (currentState != lastCurrentState) {
// If it has, we need to reset the debounce timer
debounceTimer = millis();
}
// Then we check if the timer has expired
if ((millis() - 50) > debounceTimer) {
// The timer expired so we update the value
debouncedValue = currentState;
}
// Save the latest state
lastCurrentState = currentState;
// We always return a debounced value:
return debouncedValue;
}
But always test such things with an oscilloscope, no guarantee. FYI: this is not an ideal debounce function, but it should make the idea clear.