State Machines in Python

This week you are going to implement state machines in Python. As a delivery you should keep a reflection document about your work where you include screen shots and your observations. The running code is in itself a feedback if you got it right.


Make sure you have STMPY and Jupyter lab set up like in the preparation. In case you have troubles with Python:

In case your notebook gets stuck, you can restart its Python kernel in the menu Kernel.

Today's Challenge

The tasks today are not particularly difficult, but a lot of details must come together to get it right. Also, as code is involved, it may be difficult for everyone in the team to have exactly the same understanding at the same time. So, take some time to explain the code to each other. Also, consider to repeat some parts of the assignment after the team activity on tour own.

Task 1: Traffic Light

A simple user interface representing the traffic light in the output of a cell in a Jupyter notebook.  

Task 2: Kitchen Timer

A simple user interface representing the kitchen timer in the output of a cell in a Jupyter notebook.  

Task 3: Head Lamp

You should design the state machine for the controller of a head lamp. This headlamp is used for outdoor activities. It has an infrared sensor attached, so that the LED can be switched on and off without fiddling with delicate buttons. It’s enough to swipe the hand in front of the sensor and the LED turns off. Another swipe turns the LED on again. However, to prevent the LED from turning off unintentionally, the swipe has to happen within a short time. If the hand is in front of the IR sensor for more than one second, the gesture is ignored.

The communication diagram below shows the context of the controller. It receives the signals hand and no_hand from the IR sensor, and it controls the LED with signals on and off.

State Machine Design

Design first a state machine diagram for the problem.

Implementation in Python

Create now from the state machine diagram a solution in Python using the STMPY patterns and libraries, like before.

A simple user interface representing the head lamp in the output of a cell in a Jupyter notebook.  

Debugging the State Machine

When running the implementation, does the state machine behave as intended? If not, what is the problem? Do you have to go back and also change the diagram, or is it more technical problems with the code? (Or a combination?)


Reflection Document about State Machine Implementation

Team Reflection

Individual Reflection