Skip to content

Allow on_state() functions #10

Open
@Thelmos

Description

@Thelmos

Allow states to have a on_state() function that will run while in that state.

Main program loop will need a call to run_machine() to resolve than on_state() calls and resolve timed transitions.

This example shows how it would work (not tested, can contain errors):

#include <Fsm.h>

/*
 * FSM Library sample with user and timed
 * transitions.
 * Uses a button and Arduino builtin led, 
 * button can be replaced just grounding 
 * pin.
 */

// Used pins
#define LED_PIN     13
#define BUTTON_PIN  8

//Events
#define BUTTON_EVENT  0

int buttonState = 0;

/* state 1:  led off
 * state 2:  led on
 * transition from s1 to s2 when pusshing button
 * transition back from s2 to s1 after 3 seconds
 * SECOND PARAM IS NEW "on_state()" FUNCTION
 */
State state_led_off(&led_off, &check_button, null);
State state_led_on(&led_on, null, null);
Fsm fsm(&state_led_off);

// Transition functions
void led_off()
{
  digitalWrite(LED_PIN, LOW);
}

void led_on()
{
  digitalWrite(LED_PIN, HIGH);
}

void check_button()
{
  buttonState = digitalRead(buttonPin);
  if (buttonState == LOW) {
    fsm.trigger(BUTTON_EVENT);
  }
}

// standard arduino functions
void setup()
{
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT);

  fsm.add_transition(&state_led_off, &state_led_on,
                     BUTTON_EVENT, null);
  fsm.add_timed_transition(&state_led_on, &state_led_off, 3000, NULL);
}

void loop()
{
  // Call fsm run
  fsm.run_machine();
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions