Hi I've finally succeeded with writing a buttondebounce routine.
I think I must use a pointer to the debounceroutine to reuse the routine for more buttons so that I can do something like
if (button1ReallyPressed)
a();
if (button2ReallyPressed)
b();
if (button3ReallyPressed)
c();
How can I do this modyfing the code:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
int ledState;
int buttonReallyPressed(int *i); //output-signal from the statemachine
void setup() {
ledState=LOW;
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
Serial.begin(9600);
}
void loop() {
int reading = digitalRead(buttonPin);
if(buttonReallyPressed(&reading) == HIGH){
ledState=!ledState;
digitalWrite(ledPin,ledState);
}
}//end loop
int buttonReallyPressed(int *reading){
//buttonstates - possible states in statemachine
/* Description of statemachine
button not pressed and "released" is true => State = "start"
button pressed => State goes from "start" to "firstButtonPressDetected". Timer starts.
button still pressed => "firstButtonPressDetected" goes immediately to "countingMilliseconds". Go back to "start" if button released to early.
if button pressed longer than 50ms go to "countingBiggerThanButtonDelayTime". Use this state for your outputfunction.
if button still not released go to "countingBiggerThanButtonDelayTimeNoReleaseYet" and do nothing wait for release.
When button released go to "start".
*/
const int start=0;
const int firstButtonPressDetected=1;
const int countingMilliseconds=2;
const int countingBiggerThanButtonDelayTime =3;
const int countingBiggerThanButtonDelayTimeNoReleaseYet=4;
const long debounceDelay = 50; // the debounce time; increase if the output flickers
long startTime=0;
long timeButtonPressed;
static int state;//Current state in statemachine
switch (state){
case start:
if (*reading == HIGH){
state = firstButtonPressDetected;
}
return LOW;
break;
case firstButtonPressDetected:
if (*reading == HIGH){
startTime=millis();
state = countingMilliseconds;
}
else{
state = start;
timeButtonPressed=0;
}
return LOW;
break;
case countingMilliseconds:
if (*reading == HIGH){
timeButtonPressed=millis()-startTime;
if (timeButtonPressed > debounceDelay){
state = countingBiggerThanButtonDelayTime;
}
}else{
state = start;
timeButtonPressed=0;
}
return LOW;
break;
case countingBiggerThanButtonDelayTime:
if (*reading == HIGH){
state = countingBiggerThanButtonDelayTimeNoReleaseYet;
return HIGH;
}
else{
state = start;
timeButtonPressed=0;
return LOW;
}
break;
case countingBiggerThanButtonDelayTimeNoReleaseYet:
if (*reading == LOW){
state = start;
timeButtonPressed=0;
}
return LOW;
break;
default:
return LOW;
break;
}//end switch
}