def __init__(self): # Initialize each motor with the correct direction and gearing. self.left_rear_wheels = Motor(Port.E, Direction.CLOCKWISE, self.REAR_GEARS) self.right_rear_wheels = Motor(Port.F, Direction.COUNTERCLOCKWISE, self.REAR_GEARS) self.left_front_wheel = Motor(Port.C, Direction.COUNTERCLOCKWISE, None) self.right_front_wheel = Motor(Port.D, Direction.CLOCKWISE, None) # Initialize sensors, named after the Perseverance Mars Rover instruments. self.mast_cam = UltrasonicSensor(Port.B) self.sherloc = ColorSensor(Port.A) # Initialize the hub and start the animation self.hub = InventorHub() self.hub.display.animate(self.HEART_BEAT, 30)
def __init__(self): # Configure the hub, the kicker motor, and the sensors. self.hub = InventorHub() self.kicker_motor = Motor(Port.C) self.distance_sensor = UltrasonicSensor(Port.D) self.color_sensor = ColorSensor(Port.E) # Configure the drive base. left_motor = Motor(Port.B, Direction.COUNTERCLOCKWISE) right_motor = Motor(Port.A) self.drive_base = DriveBase(left_motor, right_motor, self.WHEEL_DIAMETER, self.AXLE_TRACK) # Prepare tricky to start kicking! self.distance_sensor.lights.off() self.reset_kicker_motor() self.distance_sensor.lights.on(100)
def __init__(self): self.hub = InventorHub() # Configure the drive base self.left_motor = Motor(Port.C, Direction.COUNTERCLOCKWISE) self.right_motor = Motor(Port.A) self.drive_base = DriveBase(self.left_motor, self.right_motor, wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK) # Configure other motors and sensors self.arm_movement_motor = Motor(Port.D) self.action_motor = Motor(Port.B) self.color_sensor = ColorSensor(Port.E) self.distance_sensor = UltrasonicSensor(Port.F)
def __init__(self): self.hub = InventorHub(top_side=Axis.Z, front_side=-Axis.X) # Configure the leg motors self.front_left_leg_motor = Motor(Port.D) self.front_right_leg_motor = \ Motor(Port.C, Direction.COUNTERCLOCKWISE) self.rear_left_leg_motor = Motor(Port.B) self.rear_right_leg_motor = \ Motor(Port.A, Direction.COUNTERCLOCKWISE) self.leg_motors = [ self.front_left_leg_motor, self.front_right_leg_motor, self.rear_left_leg_motor, self.rear_right_leg_motor ] # Configure the sensors self.color_sensor = ColorSensor(Port.F) self.distance_sensor = UltrasonicSensor(Port.E)
run on the TechnicHub use port-B (just to take a port) Port-A seemed too obvious First phase: functions for each of the documented functions and parameters """ from pybricks import version from pybricks.hubs import PrimeHub from pybricks.parameters import Color, Port from pybricks.pupdevices import ColorSensor from pybricks.tools import wait # instantiate the devices hub = PrimeHub() sensor = ColorSensor(Port.B) # show version and battery level as reference print(version) print("hub_battery_voltage:", hub.battery.voltage(), "mV") hub.light.on(Color.BLUE) sensor.lights.off() # tool(s) def strFixed(instr): __outstr = "%-36s" % instr return __outstr
from pybricks.pupdevices import ColorSensor from pybricks.parameters import Port from pybricks.tools import wait # Initialize the sensor. sensor = ColorSensor(Port.A) # Show the default color map. print(sensor.color_map()) while True: # Read the HSV values. h, s, v = sensor.hsv() # Read the corresponding color based on the existing settings. color = sensor.color() # Print the measured values. print("Hue:", h, "Sat:", s, "Val:", v, "Col:", color) # Wait so we can read the value. wait(100)
from pybricks.pupdevices import Motor, ColorSensor from pybricks.parameters import Port, Direction from pybricks.tools import wait, StopWatch from pybricks.geometry import Axis # Initialize motors. left = Motor(Port.C, Direction.COUNTERCLOCKWISE) right = Motor(Port.D) left.reset_angle(0) right.reset_angle(0) # Initialize hub and color sensor. # You can also use the TechnicHub and/or the ColorDistanceSensor # instead. hub = InventorHub() sensor = ColorSensor(Port.A) # Initialize position buffer for speed calculation. DT = 5 window = int(300 / DT) buf = [0] * window idx = 0 angle = 0 DRIVE_SPEED = 300 PAUSE = 5000 # Timer to generate reference position. watch = StopWatch() while True: # Get angular rate and estimated angle.
""" This program is for Kiki the Dog. Follow the corresponding building instructions in the LEGO® SPIKE™ Prime App. Kiki shall respond to the blue, yellow or green objects by displaying something on the Hub's screen. """ from pybricks.hubs import PrimeHub from pybricks.pupdevices import ColorSensor from pybricks.parameters import Color, Icon, Port # Configure the Hub and the Color Sensor hub = PrimeHub() color_sensor = ColorSensor(Port.B) # Kiki walks around and sees things while True: # if he sees blue, he thinks it's the sky above if color_sensor.color() == Color.BLUE: hub.display.image([[100, 100, 100, 100, 100], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) # if he sees yellow, he thinks it's a house elif color_sensor.color() == Color.YELLOW: hub.display.image(Icon.UP) # if he sees green, he thinks it's the grass below elif color_sensor.color() == Color.GREEN: hub.display.image([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0],
# SPDX-License-Identifier: MIT # Copyright (c) 2020 The Pybricks Authors """ Hardware Module: 1 Description: Verifies color sensing and calibration capability. """ from pybricks.pupdevices import Motor, ColorSensor, UltrasonicSensor from pybricks.parameters import Port, Color # Initialize devices. motor = Motor(Port.A) color_sensor = ColorSensor(Port.B) ultrasonic_sensor = UltrasonicSensor(Port.C) SPEED = 500 # Color angle targets angles = { "GREEN": 20, "BLUE": 110, "RED": 200, "YELLOW": 290, "BLACK": 250, "WHITE": 75, "NONE": 162, } # Verify saturated colors without calibration. for name in ("GREEN", "BLUE", "RED", "YELLOW"): motor.run_target(SPEED, angles[name])
# SPDX-License-Identifier: MIT # Copyright (c) 2020 The Pybricks Authors """ Hardware Module: 1 Description: Verifies that sensors do not give stale data after a mode change. """ from pybricks.pupdevices import Motor, ColorSensor from pybricks.parameters import Port, Color from pybricks.tools import wait # Initialize devices. motor = Motor(Port.A) color_sensor = ColorSensor(Port.B) SPEED = 500 # Initialize sensor to make sure we're in the expected mode. color_sensor.color() wait(500) # Color angle targets angles = { "GREEN": 20, "BLUE": 110, "RED": 200, "YELLOW": 290, "BLACK": 250, "WHITE": 75, "NONE": 162,
from pybricks.pupdevices import ColorSensor from pybricks.parameters import Port, Color from pybricks.tools import wait # Initialize the sensor. sensor = ColorSensor(Port.A) # Here we choose only red, yellow, green, and blue, and provide the hues. hues = {Color.RED: 350, Color.YELLOW: 30, Color.GREEN: 110, Color.BLUE: 210} # Save the updated settings. The values dictionary is empty because we don't # need to detect black/white in this demo application. sensor.color_map(hues, 30, {}) # color() works as usual, but it only returns red/yellow/green/blue, or None. # This avoids accidentally detecting black on the dark gray train tracks. while True: print(sensor.color()) wait(100)
# SPDX-License-Identifier: MIT # Copyright (c) 2021 The Pybricks Authors """ Hardware Module: 1 Description: Verify that ambient() and reflection() refuse an argument. """ from pybricks.pupdevices import ColorSensor from pybricks.parameters import Port # Initialize device. color_sensor = ColorSensor(Port.B) # Get the ambient light intensity to verify that the default works. ambient_light_default = color_sensor.ambient() # verify an argument passed to ambient is correctly refused. expected = "function doesn't take keyword arguments" try: ambient_light_surface_true = color_sensor.ambient(surface=True) except Exception as e: assert str(e) == expected, "Expected '{0}' == '{1}'".format(e, expected) # Get the reflected light intensity to verify that the default works. reflection_default = color_sensor.reflection() # verify an argument passed to reflection is correctly refused. expected = "function doesn't take keyword arguments" try: reflection_surface_true = color_sensor.reflection(surface=True)
class TrickyPlayingSoccer: WHEEL_DIAMETER = 44 AXLE_TRACK = 88 KICK_SPEED = 1000 def __init__(self): # Configure the hub, the kicker motor, and the sensors. self.hub = InventorHub() self.kicker_motor = Motor(Port.C) self.distance_sensor = UltrasonicSensor(Port.D) self.color_sensor = ColorSensor(Port.E) # Configure the drive base. left_motor = Motor(Port.B, Direction.COUNTERCLOCKWISE) right_motor = Motor(Port.A) self.drive_base = DriveBase(left_motor, right_motor, self.WHEEL_DIAMETER, self.AXLE_TRACK) # Prepare tricky to start kicking! self.distance_sensor.lights.off() self.reset_kicker_motor() self.distance_sensor.lights.on(100) def reset_kicker_motor(self): # Prepare the kicker motor for kicking. self.hub.light.off() self.kicker_motor.run_until_stalled(-self.KICK_SPEED, Stop.HOLD) self.kicker_motor.run_angle(self.KICK_SPEED, 325) def kick(self): # Kick the ball! self.kicker_motor.track_target(360) def run_to_and_kick_ball(self): # Drive until we see the red ball. self.drive_base.drive(speed=1000, turn_rate=0) while self.color_sensor.color() != Color.RED: wait(10) self.hub.light.on(Color.RED) self.hub.speaker.beep(frequency=100, duration=100) self.kick() self.drive_base.stop() self.hub.light.off() def celebrate(self): # Celebrate with light and sound. self.hub.display.image([[00, 11, 33, 11, 00], [11, 33, 66, 33, 11], [33, 66, 99, 66, 33], [11, 33, 66, 33, 11], [00, 11, 33, 11, 00]]) self.hub.speaker.beep(frequency=1000, duration=1000) self.hub.light.animate([Color.CYAN, Color.GREEN, Color.MAGENTA], interval=100) # Celebrate by dancing around. self.drive_base.drive(speed=0, turn_rate=360) self.kicker_motor.run_angle(self.KICK_SPEED, 5 * 360) # Party's over! Let's stop everything. self.hub.display.off() self.hub.light.off() self.drive_base.stop()
from pybricks.pupdevices import ColorSensor from pybricks.parameters import Port from pybricks.tools import wait # Initialize the sensor. sensor = ColorSensor(Port.A) while True: # The standard color() method always "rounds" the # measurement to the nearest "whole" color. # That's useful for most applications. # But you can get the original hue, saturation, # and value without "rounding", as follows: color = sensor.hsv() # Print the results. print(color) # Wait so we can read the value. wait(500)
class ExplorationRover(): """Control the Mars Exploration Rover.""" # In this robot, we want to detect red and cyan/teal "mars rocks". ROCK_COLORS = (Color.RED, Color.CYAN) # These are the gears between the motor and the rear wheels. REAR_GEARS = (8, 24, 12, 20) # An animation of heart icons of varying brightness, giving a heart beat. HEART_BEAT = [ Icon.HEART * i / 100 for i in list(range(0, 100, 4)) + list(range(100, 0, -4)) ] def __init__(self): # Initialize each motor with the correct direction and gearing. self.left_rear_wheels = Motor(Port.E, Direction.CLOCKWISE, self.REAR_GEARS) self.right_rear_wheels = Motor(Port.F, Direction.COUNTERCLOCKWISE, self.REAR_GEARS) self.left_front_wheel = Motor(Port.C, Direction.COUNTERCLOCKWISE, None) self.right_front_wheel = Motor(Port.D, Direction.CLOCKWISE, None) # Initialize sensors, named after the Perseverance Mars Rover instruments. self.mast_cam = UltrasonicSensor(Port.B) self.sherloc = ColorSensor(Port.A) # Initialize the hub and start the animation self.hub = InventorHub() self.hub.display.animate(self.HEART_BEAT, 30) def calibrate(self): # First, measure the color of the floor. This makes it easy to explicitly # ignore the floor later. This is useful if your floor has a wood color, # which can appear red or yellow to the sensor. self.floor_color = self.sherloc.hsv() # Set up all the colors we want to distinguish, including no color at all. self.sherloc.detectable_colors(self.ROCK_COLORS + (self.floor_color, None)) def drive(self, speed, steering, time=None): # Drive the robot at a given speed and steering for a given amount of time. # Speed and steering is expressed as degrees per second of the wheels. self.left_rear_wheels.run(speed + steering) self.left_front_wheel.run(speed + steering) self.right_rear_wheels.run(speed - steering) self.right_front_wheel.run(speed - steering) # If the user specified a time, wait for this duration and then stop. if time is not None: wait(time) self.stop() def stop(self): # Stops all the wheels. self.left_rear_wheels.stop() self.left_front_wheel.stop() self.right_rear_wheels.stop() self.right_front_wheel.stop() def scan_rock(self, time): # Stops the robot and moves the scan arm. self.stop() self.left_front_wheel.run(100) # During the given duration, scan for rocks. watch = StopWatch() while watch.time() < time: # If a rock color is detected, display it and make a sound. if self.sherloc.color() in self.ROCK_COLORS: self.hub.display.image(Icon.CIRCLE) self.hub.speaker.beep() else: self.hub.display.off() wait(10) # Turn the arm motor and restore the heartbeat animation again. self.hub.display.animate(self.HEART_BEAT, 30) self.left_front_wheel.stop()
from pybricks.pupdevices import ColorSensor from pybricks.parameters import Port, Color from pybricks.tools import wait # Initialize the sensor. sensor = ColorSensor(Port.A) # First, decide which objects you want to detect. # Then measure their color with the hsv() method, # as shown in the previous example. Write them down # as shown below. The name is optional, but it is # useful when you print the color value. green = Color(h=132, s=94, v=26, name='GREEN_BRICK') magenta = Color(h=348, s=96, v=40, name='MAGENTA_BRICK') brown = Color(h=17, s=78, v=15, name='BROWN_BRICK') red = Color(h=359, s=97, v=39, name='RED_BRICK') # Put your colors in a list or tuple. # Including None is optional. Just omit it if # you always want to get one of your colors. my_colors = (green, magenta, brown, red, None) # Save your colors. sensor.detectable_colors(my_colors) # color() works as usual, but it only # returns one of your specified colors. while True: color = sensor.color() # Print the color.
# SPDX-License-Identifier: MIT # Copyright (c) 2020 The Pybricks Authors """ Hardware Module: 1 Description: Verifies reflection sensing, by asserting that the colors None, Black, Red, and Yellow have ascending reflection values. """ from pybricks.pupdevices import Motor, ColorSensor from pybricks.parameters import Port # Initialize devices. motor = Motor(Port.A) color_sensor = ColorSensor(Port.B) SPEED = 500 # Color angle targets angles = { "GREEN": 20, "BLUE": 110, "RED": 200, "YELLOW": 290, "BLACK": 250, "WHITE": 75, "NONE": 162, } previous_reflection = 0
from pybricks.pupdevices import ColorSensor from pybricks.parameters import Port from pybricks.tools import wait # Initialize the sensor. sensor = ColorSensor(Port.A) # Repeat forever. while True: # Get the ambient color values. Instead of scanning the color of a surface, # this lets you scan the color of light sources like lamps or screens. hsv = sensor.hsv(surface=False) color = sensor.color(surface=False) # Get the ambient light intensity. ambient = sensor.ambient() # Print the measurements. print(hsv, color, ambient) # Point the sensor at a computer screen or colored light. Watch the color. # Also, cover the sensor with your hands and watch the ambient value. # Wait so we can read the printed line wait(100)
# Copyright (c) 2021 The Pybricks Authors """ Hardware Module: 1 Description: Verify color sensor arguments, by asserting that the same color is reported by: - using the default argument, e.g. surface=True - and using NO argument. """ from pybricks.pupdevices import ColorSensor from pybricks.parameters import Port # Initialize device. color_sensor = ColorSensor(Port.B) # Verify that the default and NO-argument calls report the same color. # Assume that the lighting will not change a lot during measuring. hsv_default = color_sensor.hsv() hsv_surface_true = color_sensor.hsv(surface=True) # the default is surface=True. # do not use surface=False in this test, that causes a mode switch and that would need more time. assert hsv_default == hsv_surface_true, "Expected default '{0}' == '{1}'".format( hsv_default, hsv_surface_true ) color_default = color_sensor.color() color_surface_true = color_sensor.color(surface=True) # the default is surface=True. assert color_default == color_surface_true, "Expected default '{0}' == '{1}'".format( color_default, color_surface_true )
from pybricks.pupdevices import ColorSensor from pybricks.parameters import Port from pybricks.tools import wait # Initialize the sensor. sensor = ColorSensor(Port.A) # Repeat forever. while True: # Turn on one light at a time, at half the brightness. # Do this for all 3 lights and repeat that 5 times. for i in range(5): sensor.lights.on(50, 0, 0) wait(100) sensor.lights.on(0, 50, 0) wait(100) sensor.lights.on(0, 0, 50) wait(100) # Turn all lights on at maximum brightness. sensor.lights.on(100) wait(500) # Turn all lights off. sensor.lights.off() wait(500)
from pybricks.pupdevices import ColorSensor from pybricks.parameters import Port, Color from pybricks.tools import wait # Initialize the sensor. sensor = ColorSensor(Port.A) # Get the current color settings. hues, saturation, values = sensor.color_map() # Let's say we have used the hsv() method to determine # that the orange hue is 10. We can add it like this. hues[Color.ORANGE] = 10 # Also, let's say that we are not interested in blue. # So, we remove it from the hues dictionary. hues.pop(Color.BLUE) # Now save the new settings sensor.color_map(hues, saturation, values) # Now use the color() method as usual. Now it can also detect ORANGE # and it will not report BLUE, because we removed it from the hues. while True: print(sensor.color()) wait(100)