/*
Simple 'finite state' machine
*/
#define redLed 10
#define greenLed 9
#define blueLed 8
/*
'enum' assigns a int value to a list of named items.
Value can be assigned to each named item.
If value isn't assigned, default starts with 0 or uses previous value of last assigned item.
Example: Used with Arduino pin names can be set using #define or could be set using 'enum'.
*/
// - - - user defined datatype that assigns a value to a name - - -
typedef enum {
RED, // = 0
GREEN, // = 1
BLUE // = 2
} States; // datatyupe is 'States' similar to saying 'int' for datatype
// Set the initial (i.e., starting) state
States state = RED; // state is an int, value is 0
void setup () {
Serial.begin(9600);
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
pinMode(blueLed, OUTPUT);
}
void loop() {
Serial.print("state: "); Serial.println(state);
digitalWrite(redLed, LOW);
digitalWrite(greenLed, LOW);
digitalWrite(blueLed, LOW);
// State-aware actions
switch(state) {
case RED:
digitalWrite(redLed, HIGH);
break;
case GREEN:
digitalWrite(greenLed, HIGH);
break;
case BLUE:
digitalWrite(blueLed, HIGH);
break;
}
delay(1000);
nextState();
}
// - - - - - FUCTIONS - - - - -
void nextState() {
if (state == RED) state = GREEN;
else if (state == GREEN) state = BLUE;
else state = RED;
}