mirror of
https://github.com/pybricks/pybricks-projects.git
synced 2026-09-15 02:52:41 +00:00
official_models/pup/trains_sensors: tilt project
This adds a project that shows how you can combine LEGO trains with the Powered Up Tilt Sensor to detect slopes in a train track.
This commit is contained in:
committed by
laurensvalk
parent
d000fe7d7a
commit
a30877fd3d
@@ -0,0 +1,32 @@
|
||||
# Rail slope detection
|
||||
|
||||
Made by: The Pybricks Authors
|
||||
|
||||
## Introduction
|
||||
|
||||
This project shows how you can integrate the
|
||||
[Tilt Sensor](https://docs.pybricks.com/en/latest/pupdevices.html#tilt-sensor)
|
||||
in your LEGO trains. You can use this sensor to detect a slope in the rail
|
||||
track.
|
||||
|
||||
## Demo
|
||||
|
||||
This program makes the train drive until it detects a slope of 8 degrees or
|
||||
more. Then it drives back down. You can watch a video
|
||||
[here](https://www.youtube.com/watch?v=Wc0mRIBjhIU).
|
||||
|
||||
## Requirements
|
||||
- Generic LEGO train, such as 60197 or 60198
|
||||
- Powered Up [Tilt Sensor](https://docs.pybricks.com/en/latest/pupdevices.html#tilt-sensor)
|
||||
|
||||
## Building instructions
|
||||
Build the train using the standard instructions. Mount the Tilt Sensor anywhere
|
||||
on the train. See the video for an example. Mount it horizontally. The side
|
||||
with the cable should face towards the front: in the direction of driving.
|
||||
|
||||
## Ports
|
||||
- Train motor on port A
|
||||
- Tilt sensor on port B
|
||||
|
||||
## Programming and running instructions
|
||||
The train must start on a horizontal track. Then run the program.
|
||||
@@ -0,0 +1,35 @@
|
||||
from pybricks.pupdevices import TiltSensor, DCMotor
|
||||
from pybricks.parameters import Port
|
||||
from pybricks.tools 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.
|
||||
train.dc(-50)
|
||||
|
||||
# We need to reach a constant speed before we can check tilt again,
|
||||
# because acceleration affects tilt. So we wait a second.
|
||||
wait(1000)
|
||||
|
||||
# Wait for the train to sense the hill.
|
||||
while True:
|
||||
pitch_now, roll_now = sensor.tilt()
|
||||
|
||||
wait(10)
|
||||
|
||||
# If we reached an extra 3 degrees, exit/break the loop.
|
||||
if pitch_now >= pitch_start + 8:
|
||||
break
|
||||
|
||||
# Drive backwards for a few seconds and then stop.
|
||||
train.dc(40)
|
||||
wait(3000)
|
||||
train.dc(0)
|
||||
Reference in New Issue
Block a user