Documentation > nControl > Train Automation Course
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?
What will we focus on?
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:
What Did We Learn?
In this project we learned:
|