Created
February 2, 2024 20:53
-
-
Save Xayer/dfd2708d30487775aa8758b970be85db to your computer and use it in GitHub Desktop.
Pybricks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pybricks.hubs import CityHub | |
from pybricks.pupdevices import DCMotor, Light, ColorDistanceSensor, PFMotor | |
from pybricks.parameters import Button, Color, Direction, Port, Side, Stop | |
from pybricks.robotics import DriveBase | |
from pybricks.tools import wait, StopWatch | |
# Initialize the hub. | |
hub = CityHub() | |
trainMotor = DCMotor(Port.B, Direction.CLOCKWISE) | |
# Initialize the sensor. | |
sensor = ColorDistanceSensor(Port.A) | |
switch = PFMotor(sensor, 1, Color.BLUE) | |
switchSpeed = 30 | |
switchDuration = 100 | |
trainSpeed = 50 | |
def moveSwitch(speed: Int, duration: Int = 100): | |
switch.dc(switchSpeed) | |
wait(switchDuration) | |
switch.brake() | |
def switchStraight(): | |
moveSwitch(switchSpeed, switchDuration) | |
def switchLeft(): | |
moveSwitch(-switchSpeed, switchDuration) | |
def moveBackwards(): | |
trainMotor.dc(-trainSpeed) | |
def moveForwards(): | |
trainMotor.dc(trainSpeed) | |
def stopTrain(): | |
trainMotor.stop() | |
def detectColor(): | |
print("Detectable Color:") | |
print(sensor.color()) | |
def waitForColor(desired_color): | |
# While the color is not the desired color, we keep waiting. | |
detectColor() | |
# hub.light.on(desired_color) | |
while sensor.color() != desired_color: | |
wait(20) | |
while True: | |
moveForwards() | |
# Detect Red | |
waitForColor(Color.RED) | |
# Stop Train | |
stopTrain() | |
# Move backwards for 1 second | |
moveBackwards() | |
# Switch Left | |
switchLeft() | |
wait(2500) | |
# Move Forward | |
moveForwards() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment