Logo
  • Home
  • Equipment
  • Tutorials
  • Calendar
  • TPZ Staff Page
  • (Beta) Tech Ai Support
The Possible Zone
Fab Lab Website
Fab Lab Website
/
Tutorials
/
Tutorials Database
/
State Machine for Beyond Possible Robot, Pt. 1

State Machine for Beyond Possible Robot, Pt. 1

Tags
electronicsarduino
Date
Author
U
Untitled
Documentation Type
Class
Beyond Possible
Class Section
Careers of the future

‣

What is a state machine?

To understand state machines, let’s make a state machine based on a classic childhood game: Freeze Tag.

Think about how you play Freeze Tag. You’re running to escape the person who is “It”, and if they tag you, you’re frozen. If a non-frozen teammate tags you, you’re back in the game!

“Frozen” and “running” are states describe a set of actions you should be performing. When you are in your “running” state, you are moving like the wind to stay out of reach of your opponent. When you are caught and “frozen”, you have to stand in place and beg for a friend to come and help.

image

What moves us between these states. What events make you go from “running” to “frozen” and back again?

Well, to go from “running” to “frozen”, the person who is “It” has to touch you. For you to get from “frozen” to “running”, a teammate has to touch you. We can show this with a state machine diagram:

image

State machines are useful because they help us to organize and modify the behavior of complex systems, such as the robot you’re building right now. If you use a state machine to control the robot, you can see what the robot should be doing, and the events which should trigger these actions. This means that state machines not only help us to build the robot’s brain, state machines also help us to diagnose any problems (aka debug your code!). If an event happens but doesn’t trigger the right state, you know something is wrong.

Getting Started

We’re going to modify some code to create a simple state machine to control our robot. This state machine will have two states, “SEARCH” and “FOLLOW”. Right now, only “FOLLOW” is working in the code.

image

Step 1: Download the state machine template and open in Arduino IDE

Download the code here

Step 2: Add a new “SEARCH” state

Under line 41, add an else {} statement to make “SEARCH” our default state.

else {
  state = "SEARCH";
}

Step 3: Add the behavior for the “SEARCH” state

Under line 72, add an else if {} statement to hold the “SEARCH” behavior.

  else if(state == "SEARCH") {
    turnLeft();
  }

Step 4: Test your code

What does your robot do when it doesn’t identify any objects?

Part 2