Skip to content

Instantly share code, notes, and snippets.

@Xayer
Created February 2, 2024 20:53
Show Gist options
  • Save Xayer/dfd2708d30487775aa8758b970be85db to your computer and use it in GitHub Desktop.
Save Xayer/dfd2708d30487775aa8758b970be85db to your computer and use it in GitHub Desktop.
Pybricks
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()
from pybricks.pupdevices import Remote
from pybricks.parameters import Button, Color
def button_to_color(buttons):
# Return a color depending on the button.
if Button.LEFT_PLUS in buttons:
return Color.RED
if Button.LEFT_MINUS in buttons:
return Color.GREEN
if Button.LEFT in buttons:
return Color.ORANGE
if Button.RIGHT_PLUS in buttons:
return Color.BLUE
if Button.RIGHT_MINUS in buttons:
return Color.YELLOW
if Button.RIGHT in buttons:
return Color.CYAN
if Button.CENTER in buttons:
return Color.VIOLET
# Return no color by default.
return Color.NONE
# Connect to the remote.
remote = Remote()
while True:
# Wait until a button is pressed.
pressed = ()
while not pressed:
pressed = remote.buttons.pressed()
# Convert button code to color.
color = button_to_color(pressed)
# Set the remote light color.
remote.light.on(color)
# Wait until all buttons are released.
while pressed:
pressed = remote.buttons.pressed()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment