Documentation > nControl > Train Automation Course
Traffic Light - Stop
For nControl™ 2019.2 or higher

What does this project do?
In this project we will create a train that automatically stops when it encounters a red traffic light. Before you can restart the train you will have to switch the traffic light to green.
What will you need to build this project?
  • 1x LEGO® PF train and a 4DBrix™ WiFi train controller   or   1x LEGO® PU train and a BLE112 dongle
  • a loop of LEGO® train tracks
  • 1x 4DBrix™ IR train detection sensor, traffic light and USB starter controller
  • nControl 2019.2 or higher
What will we focus on?
  • Linking the behavior of the train to the state of the sensor and traffic light.
Project File
Building the Set-up
Build loop with your LEGO® tracks. Add a the traffic light and put the train detection sensor in front of the traffic light so the sensor can see the train just before it reaches the traffic light.
Connect the traffic light to port 3 of your starter controller and the sensor to port 4 of the controller.
Writing the Trigger Script
When the sensor detects the train it has to check whether the traffic light and if it's red it needs to stop the train. So in the trigger script of the sensor tile we start by getting the objects of the train control tile and the traffic light tile:
train = self.getTile('Train 1')
light = self.getTile('Light 1')
Next we need to check the state of the traffic light. The API documentation shows you can do this with the .getState() function. It also shows that the red state of the traffic light is represented by the nConst.TL_RED constant. Checking whether the traffic light is red can be done with the following comparison:
light.getState() == nConst.TL_RED:
Stopping the train in case the light is red is done with an if statement:
train.stop()
self.disable()
self.sleep(3)
When we restart the train, we can use the trainPower variable we created as argument in the .goForward() function. As such we tell the train to start with the same power as it had before it was stopped.
if light.getState() == nConst.TL_RED:
   train.stop()
When the light is green the train can keep going so there is no else code block needed.

The complete trigger script becomes:
#Get the objects
train = self.getTile('Train 1')
light = self.getTile('Light 1')

#Stop the train if the light is red
if light.getState() == nConst.TL_RED:
   train.stop()
Testing the Script in Simulation Mode
To validate our script we have to test two scenarios:
  • Start the train, switch the traffic light to green and click the sensor tile. The train should not be stopped.
  • Switch the traffic light to red and click the sensor tile. This time the train should stop.
What Did We Learn?
In this project we learned:
  • How to link a traffic light, sensor and train control tile.
Documentation > nControl > Train Automation Course