Train slope detection

This project was submitted by The Pybricks Authors.

 Building instructions  Improve project

Train slope detection

Detect the slope of the track. This lets you determine where the train is on the circuit.

Building instructions

Build the train using the standard instructions. Mount the tilt sensor horizontally in the train, with the cable side facing towards direction of driving:

Connect the motor to port A and connect the tilt sensor to port B.

Coding Instructions

This program makes the train drive until it detects a slope of 8 degrees or more. Then it drives back down.

from pybricks.pupdevices import TiltSensor, DCMotor
from pybricks.parameters import Port
from import wait

# Initialize the train motor.
# If you have a motor with encoders, use the Motor class instead.
train = DCMotor(Port.A)

# Initialize the tilt sensor.
sensor = TiltSensor(Port.B)

# Measure the tilt while the train is on a flat surface.
pitch_start, roll_start = sensor.tilt()

# Start driving.

# We need to reach a constant speed before we can check tilt again,
# because acceleration affects tilt. So we wait a second.

# Wait for the train to sense the hill.
while True:
    pitch_now, roll_now = sensor.tilt()


    # If we reached an extra 3 degrees, exit/break the loop.
    if pitch_now >= pitch_start + 8:

# Drive backwards for a few seconds and then stop.

Programming and running instructions

The train must start on a horizontal track. Then run the program.