State Machine, version 2

This was the second example from today’s class. In this structure, each state is given its own while loop with the Arduino loop function. Once the flow of control enters one of these loops, it continues within that loop until the state changes.

Note that each state’s loop must include statements to update the relevant sensor variables.

//
// State machine example 2: loops 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;

  while (state == 1) // WAITING
  {
    // Read sensors
    colour = analogRead(0);
  
    // Actuators
    green(0);
    red(1);
    white(0);

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

    // Change state?
    if (colour < 200) gotoState(3);
  }
  
  while (state == 3) // FAN ON WITH TIMEOUT
  {
    // Read sensors
    colour = analogRead(0);
  
    // 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);
  }
}
Advertisements
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 )

w

Connecting to %s