My worry was that as I added layers of complexity to the VCU, it would get to the point that unexpected things could start to happen. I'm sure we've all struggled to make sense of nested if...then...else statements. At the same time, the concept of a finite state machine was difficult to get my head around (and it seemed unnecessarily complicated). I thought I'd share here what I've learned, in case it's useful for anyone else grappling with the same thing...
Here's a simple example: my bike has a side stand.
When the side stand is down, I want:
- The side stand light to come on
- The charger to be (conditionally) enabled
- The throttle to be held at zero
- The side stand light to go out
- The charger to be disabled
Code: Select all
const int stand_light_pin = LED_BUILTIN; // Use on-board LED
const int stand_switch_pin = 2; // Switch is connected to earth on pin 2
boolean stand_switch_state = false;
void setup() {
pinMode(stand_light_pin, OUTPUT);
pinMode(stand_switch_pin, INPUT_PULLUP);
}
void loop() {
stand_switch_state = digitalRead(stand_switch_pin);
switch( stand_switch_state) {
case true: digitalWrite(stand_light_pin, HIGH); break;
case false: digitalWrite(stand_light_pin, LOW);
}
}
Here's the same functionality using the Automaton finite state machine library:
Code: Select all
#include <Automaton.h>
const int stand_light_pin = LED_BUILTIN; // Use on-board LED
const int stand_switch_pin = 2; // Switch is connected to earth on pin 2
Atm_led stand_light; // create a LED output machine
Atm_button stand_switch; // create a button input machine
void setup() {
Serial.begin( 115200 ); // for debugging output
stand_light.begin( stand_light_pin ); // start the LED machine
stand_switch.begin( stand_switch_pin ) // start the button machine
.onPress( stand_light, stand_light.EVT_ON ) // send an ON event to the LED machine
.onRelease( stand_light, stand_light.EVT_OFF) // send an OFF event to the LED machine
.trace( Serial ); // log events to serial console
}
void loop() {
automaton.run();
}
If you're still unconvinced, check out this fuel gauge example.
If this is useful for anyone, I'll post some more musings as I develop the VCU...