State Machine, version 1

This was the first version of the state machine example we looked at in today’s lecture. This structure uses an extended if-else-if statement in the loop function to select the code for the current state each time the function repeats.

//
// State machine example 1: if-else-if inside loop
//

int state = 1;
unsigned long start_time;

void setup()
{
  // Green LEDs on D2, D3, D4
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  
  // Red LEDs on D5, D6, D7
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);

  // White LED on D8
  pinMode(8, OUTPUT);
}

void loop()
{
  int colour;
  colour = analogRead(0);
  
  if (state == 1) // WAITING
  {
    // Actuators
    green(0);
    red(1);
    white(0);

    // Change state?
    if (colour > 200) gotoState(2);
  }
  else if (state == 2) // FAN ON
  {
    // Actuators
    green(1);
    red(0);
    white(1);

    // Change state?
    if (colour < 200) gotoState(3);
  }
  else if (state == 3) // FAN ON WITH TIMEOUT
  {
    // Actuators
    green(1);
    red(1);
    white(1);

    // Change state?
    if (colour > 200) gotoState(2);
    if (millis() - start_time > 2000) gotoState(1);
  }
}

void gotoState(int new_state)
{
  state = new_state;
  start_time = millis();
}

void green(int on_off)
{
  if (on_off == 0)
  {
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
  }
  else
  {
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
  }
}

void red(int on_off)
{
  if (on_off == 0)
  {
    digitalWrite(5, LOW);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
  }
  else
  {
    digitalWrite(5, HIGH);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
  }
}

void white(int on_off)
{
  if (on_off == 0)
  {
    digitalWrite(8, LOW);
  }
  else
  {
    digitalWrite(8, HIGH);
  }
}
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s