I have the following setup and sketch.
The problem is that when I click the button it works sometimes, but other times it executes On Off straight after On as if it's executing twice.
This is after pressing the button only 7 times:
Off
On
Off
On
Off
On
Off
On
Off
I thought that was the whole point of a state machine? That it continues to execute the next state (not multiple times at random).
Very very confused with this one.
//http://www.arduino.cc/playground/uploads/Code/FSM.zip
#include <FiniteStateMachine.h>
//http://www.arduino.cc/playground/uploads/Code/Button.zip
#include <Button.h>
//http://www.arduino.cc/playground/uploads/Code/LED.zip
#include <LED.h>
const byte NUMBER_OF_STATES = 2; //how many states are we cycling through?
//initialize states
State On = State(ledOn);
State Off = State(ledOff);
FSM ledStateMachine = FSM(On); //initialize state machine, start in state: On
Button button = Button(2, INPUT_PULLUP); //initialize the button (wire between pin 12 and ground)
LED led = LED(13); //initialize the LED
byte buttonPresses = 0; //counter variable, hols number of button presses
void setup(){
Serial.begin(9600);
}
//poor example, but then again; it's just an example
void loop(){
if (button.uniquePress()){
//increment buttonPresses and constrain it to [ 0, 1 ]
buttonPresses = ++buttonPresses % NUMBER_OF_STATES;
switch (buttonPresses){
case 0: ledStateMachine.transitionTo(On); Serial.println("On"); break;
case 1: ledStateMachine.transitionTo(Off); Serial.println("Off"); break;
}
}
ledStateMachine.update();
}
//utility functions
void ledOn(){ led.on(); }
void ledOff(){ led.off(); }
//end utility functions