0

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.

enter image description here

//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
2

Maybe you need some sort of debouncing? There's a tutorial on the Arduino site that I think will sort your problem out.

1

It doesn't look like the state machine is a problem here. More likely it's a problem of the button bouncing, as you don't have any code or circuitry to guard against it.

A button is typically a very simple component which doesn't necessarily make/break connections cleanly. Sometimes it will have a brief intermittent connection, making it look like it's been pressed/released multiple times. This is referred to as bouncing.

There's lots of material online about debouncing, whether in hardware or software. The top answer here may help:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.