# 03. Traffic light

This example of digital output uses 3 LEDs to create a traffic light. It starts with the red, after 7 seconds becomes green, after 10 seconds becomes yellow and after 3 seconds it resumes with the red (see Figure 2 and Video 1). It can be managed from the Internet via start and stop commands. ## 1. Circuit

Connect the 3 LEDs as shown in Figure 1:

• red LED to the PINs R and d1
• yellow LED to the PINs d2 and d3
• green LED to the PINs d4 and GND.

The longest PIN is positive.

## 2. Sketch

Write a sketch K to define:

• the output connections:
``  red :: !d1, yellow :: d2, gnd :: d3, green :: d4``
• the variable s for the state of the automaton
• the commands to start and stop the system: `start, stop`
• the rules for implementing the automaton in Figure 2
``gnd :: d3``
``green :: d4``
``red :: !d1``
``yellow :: d2``
``s=0``
``start = [gnd=0, status=0, s=1]``
``stop = [red=0, yellow=0, green=0, status=1, led=1, s=0]``
``s==1 -> [red=1, yellow=0, green=0, s=2 ## 7]``
``s==2 -> [red=0, yellow=0, green=1, s=3 ## 10]``
``s==3 -> [red=0, yellow=1, green=0, s=1 ## 3]``

or simply load the sketch into the workspace with the command

``] charge e03_traffic_light``

The start command contains `status=0` to disable the status LED. The stop command contains `status=1` to enable the status LED. Find out what happens if you don't use `status=0`. ## 3. Try and learn

Try the following commands now:

• `] start`

the traffic light starts with the red, after 7 seconds becomes green, after 10 seconds becomes yellow and after 3 seconds it resumes with the red (see Video 1)

### Video 1 - traffic light

• `] pause`

the traffic light stops

• `] play`

the traffic light resumes

• `] stop`

turns off the traffic light

• `] ?`
``--- Pin connections``
``gnd :: d3   ``
``green :: d4   ``
``red :: !d1   ``
``yellow :: d2   ``
``--- Variables``
``s = 0   ``
``--- Commands``
``start = [gnd=0,status=0,s=1]   ``
``stop = [red=0,yellow=0,green=0,status=1,led=1,s=0]   ``
``--- Rules``
``s==1 -> [red=1,yellow=0,green=0,s=2 ##7]   ``
``s==2 -> [red=0,yellow=0,green=1,s=3 ##10]   ``
``s==3 -> [red=0,yellow=1,green=0,s=1 ##3]``

shows the sketch in the workspace

• `] save`

stores on archive the sketch in workspace

• `] new`

erase the workspace

• `] ?`
``null``

shows the sketch in the workspace

• `] cat`
``--- /smick.k``
``gnd :: d3``
``green :: d4``
``red :: !d1``
``yellow :: d2``
``s = 0``
``start=[gnd=0,status=0,s=1]``
``stop=[red=0,yellow=0,green=0,status=1,led=1,s=0]``
``s==1 -> [red=1,yellow=0,green=0,s=2 ##7]``
``s==2 -> [red=0,yellow=0,green=1,s=3 ##10]``
``s==3 -> [red=0,yellow=1,green=0,s=1 ##3]``
``ok``

shows the sketch stored on archive after the last save

• `] load`

loads the sketch in the workspace

• `] ?`

Wath does it show?

## 4. Summarizing

In this lesson you learned:

• how to use more LEDs
• the commands: status, start, pause, play, stop, save, new, cat, load.