If you haven’t completed Units 2.1 and 2.2 yet, go back and finish them first.
Programs we’ve seen so far just focus on one task:
Being a Siren, playing a Sparkle sound when shaken, etc.
This is great if you build something that just needs to do that one thing.
Now think about the Cliq robot.
Motors, sensors, LED face, speakers, communication, more…
It can do a lot of different things!
A program to control Cliq will have to make lots of decisions:
At the very least; when to drive forwards or backwards, when and which way to turn, what to say, and when to listen.
This could get very complicated!
So, in this unit we’ll be talking about a new concept: state.
State lets programs know where they are, where they’ve been.
It allows us to make all kinds of new behaviours, from simple through complex, WITHOUT being too confused.
So we’ll start with a really SIMPLE example…
Simple Light Switch
There is not much to a light switch, is there?
- Pushed one way is “on“.
- Pushed the other way is “off“.
- Some metal inside makes or breaks the electrical circuit.
This sort of light switch is different – a button isn’t “on” or “off”, it’s just “clicked”.
How does it work? There’s a program inside!
(It’s the modern era. Programs are found everywhere, even inside modern button light switches)
How do we make a Light Switch program?
First let’s understand the “rules” of how a simple light switch program should work:
- If the button is clicked and the light is OFF, switch the light ON.
- If the button is clicked and the light is ON, switch the light OFF.
As a diagram, something like this:
Now, what about those times when the button is not being clicked – should the light be on or off?
Our program needs some memory, some way of knowing where it’s at.
We call this concept; state.
- The diagram above is a state diagram.
It is a simple way of thinking about our program before we build it.
- The circles are the program’s possible states.
This program has just two: ON and OFF.
- The arrows indicate how the program can transition from one state to another,
Both transitions in this program are triggered by button A click.
We will use a variable to store the current state.
To make things clear we’ll even name it
We could use numbers (eg
0 means OFF,
1 means ON) to represent the different states.
BUT! This becomes tricky when the program becomes more complex.
“if current_state equals 7, then… Which state is 7 again?”
We use variables to give each state a name;
Naming our states makes it much easier to understand the program.
Note: Every state named this way must be a different value, or else the program won’t be able to tell them apart!