def main(): coords = [0, 0] left.reset_angle(0) right.reset_angle(0) Kp, Ki, Kd, i, last_error, target = 20, 0, 0, 0, 0, 5 conveyor_belt = Motor(Port.A) directions_made = [] stopwatch = StopWatch() stopwatch.resume() driving_forward = False while True: if stopwatch.time() >= 100000: # OUR LAST HOPE FOR POINTS!!!!! robot.stop() if driving_forward: directions_made.append( ("forward", stopwatch.time() - start_time)) driving_forward = False break if lightSensor.refelctivity() <= 500: backward(1000) if cSensor.color() == Color.BLUE: robot.stop(Stop.BRAKE) if driving_forward: directions_made.append( ("forward", stopwatch.time() - start_time)) driving_forward = False conveyor_belt.run_time(-100, 1000, Stop.BRAKE, False) foundvictim() if LeftSensor.distance() >= 40: wait(500) robot.stop(Stop.BRAKE) if driving_forward: directions_made.append( ("forward", stopwatch.time() - start_time)) driving_forward = False leftturn() directions_made.append("left turn") robot.drive_time(-1000, 0, 1000) directions_made.append(("forward", 1000)) elif ForwardSensor.distance() <= 300: robot.stop(Stop.BRAKE) if driving_forward: directions_made.append( ("forward", stopwatch.time() - start_time)) driving_forward = False rightturn() directions_made.append("right turn") else: robot.drive(-1000, 0) driving_forward, start_time = True, stopwatch.time() for direction in directions_made: if direction == "left turn": robot.stop() rightturn() elif direction == "right turn": robot.stop() leftturn() else: robot.drive_time(-1000, 0, direction[1])
class Gripp3r(RemoteControlledTank): WHEEL_DIAMETER = 26 # milimeters AXLE_TRACK = 115 # milimeters def __init__( self, left_track_motor_port: Port = Port.B, right_track_motor_port: Port = Port.C, gripping_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): super().__init__( wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK, left_motor_port=left_track_motor_port, right_motor_port=right_track_motor_port, ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel) self.ev3_brick = EV3Brick() self.gripping_motor = Motor(port=gripping_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def grip_or_release_by_ir_beacon(self, speed: float = 500): if Button.BEACON in \ self.ir_sensor.buttons(channel=self.ir_beacon_channel): if self.touch_sensor.pressed(): self.ev3_brick.speaker.play_file(file=SoundFile.AIR_RELEASE) self.gripping_motor.run_time( speed=speed, time=1000, then=Stop.COAST, wait=True) else: self.ev3_brick.speaker.play_file(file=SoundFile.AIRBRAKE) self.gripping_motor.run(speed=-speed) while not self.touch_sensor.pressed(): pass self.gripping_motor.stop() while Button.BEACON in \ self.ir_sensor.buttons(channel=self.ir_beacon_channel): pass
class CuriosityRov3r(IRBeaconRemoteControlledTank, EV3Brick): WHEEL_DIAMETER = 35 # milimeters AXLE_TRACK = 130 # milimeters def __init__( self, left_motor_port: Port = Port.B, right_motor_port: Port = Port.C, medium_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, color_sensor_port: Port = Port.S3, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): super().__init__( wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK, left_motor_port=left_motor_port, right_motor_port=right_motor_port, ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel) self.medium_motor = Motor(port=medium_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.color_sensor = ColorSensor(port=color_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def spin_fan(self, speed: float = 1000): while True: if self.color_sensor.reflection() > 20: self.medium_motor.run(speed=speed) else: self.medium_motor.stop() def say_when_touched(self): while True: if self.touch_sensor.pressed(): self.screen.load_image(ImageFile.ANGRY) self.speaker.play_file(file=SoundFile.NO) self.medium_motor.run_time( speed=-500, time=3000, then=Stop.HOLD, wait=True) def main(self, speed: float = 1000): run_parallel( self.say_when_touched, self.spin_fan, self.keep_driving_by_ir_beacon)
def loop(dir): if dir == 1: test_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE) else: test_motor = Motor(Port.A) ret = http_get( "https://us-central1-ev3tempcontrol.cloudfunctions.net/getOccupiedRoom" ) print(ret) if ret == 'true': # test_motor.run_target(500, 90) test_motor.run_time(500, 2000) wait(1000)
class El3ctricGuitar: NOTES = [1318, 1174, 987, 880, 783, 659, 587, 493, 440, 392, 329, 293] N_NOTES = len(NOTES) def __init__(self, lever_motor_port: Port = Port.D, touch_sensor_port: Port = Port.S1, ir_sensor_port: Port = Port.S4): self.ev3_brick = EV3Brick() self.lever_motor = Motor(port=lever_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) def start_up(self): self.ev3_brick.screen.load_image(ImageFile.EV3) self.ev3_brick.light.on(color=Color.ORANGE) self.lever_motor.run_time(speed=50, time=1000, then=Stop.COAST, wait=True) self.lever_motor.run_angle(speed=50, rotation_angle=-30, then=Stop.BRAKE, wait=True) wait(100) self.lever_motor.reset_angle(angle=0) def play_note(self): if not self.touch_sensor.pressed(): raw = sum(self.ir_sensor.distance() for _ in range(4)) / 4 self.ev3_brick.speaker.beep( frequency=self.NOTES[min(int(raw / 5), self.N_NOTES - 1)] - 11 * self.lever_motor.angle(), duration=100) wait(1)
robot.drive(-200, -2) while robot.distance() > -500: robot.drive(-250, 20) robot.stop() while Button.CENTER not in ev3.buttons.pressed(): pass #treadmill accangle = 0 gyroSensor.reset_angle(0) straight(270, 200) line_follow(rightcolor, 175, 1.6, 0.04, 0.1, 0.01, 1200) # arives at treadmill #turntoangle(0.01) robot.drive(95, -1.5) #80, -2 mediummotor2.run_time(300, 1000, wait=True) #rolls up platform wait(900) #1500 robot.stop() leftmotor.hold() rightmotor.hold() mediummotor2.run_time(1000, 3500) #runs treadmill accangle = 1 oldstraight(2000, -500) # goes back #health units, minifigure on tire, weight machine, drop bricks elif Button.LEFT in ev3.buttons.pressed(): # set point 1 for gyro (parallel to south wall) accangle = 0 gyroSensor.reset_angle(0) #health units
# Сканирование штрих-кода def barcode(): pass # Путь к первой кормушке def first_feeder(): pass # Путь ко второй кормушке def second_feeder(): pass # Путь к третьей кормушке def third_feeder(): pass # Путь к четвётрой кормушке def fourth_feeder(): pass up_n_down_motor.run_time(-700, 2100) follow_black_line(6) left_motor.run_time(360, 1000)
class Kraz33Hors3: def __init__(self, back_foot_motor_port: Port = Port.C, front_foot_motor_port: Port = Port.B, gear_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, color_sensor_port: Port = Port.S3, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): self.front_foot_motor = Motor(port=front_foot_motor_port, positive_direction=Direction.CLOCKWISE) self.back_foot_motor = Motor( port=back_foot_motor_port, positive_direction=Direction.COUNTERCLOCKWISE) self.gear_motor = Motor(port=gear_motor_port) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.color_sensor = ColorSensor(port=color_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def drive_once_by_ir_beacon( self, speed: float = 1000 # deg/s ): ir_beacons_pressed = set( self.ir_sensor.buttons(channel=self.ir_beacon_channel)) # forward if ir_beacons_pressed == {Button.LEFT_UP, Button.RIGHT_UP}: self.front_foot_motor.run_time( speed=speed, time=1000, # ms then=Stop.COAST, wait=False) self.back_foot_motor.run_time( speed=speed, time=1000, # ms then=Stop.COAST, wait=True) # backward elif ir_beacons_pressed == {Button.LEFT_DOWN, Button.RIGHT_DOWN}: self.front_foot_motor.run_time( speed=-speed, time=1000, # ms then=Stop.COAST, wait=False) self.back_foot_motor.run_time( speed=-speed, time=1000, # ms then=Stop.COAST, wait=True) # move crazily elif ir_beacons_pressed == {Button.BEACON}: self.gear_motor.run(speed=speed) self.front_foot_motor.run_time( speed=speed / 3, time=1000, # ms then=Stop.COAST, wait=False) self.back_foot_motor.run_time( speed=-speed / 3, time=1000, # ms then=Stop.COAST, wait=True) else: self.gear_motor.stop() def keep_driving_by_ir_beacon( self, speed: float = 1000 # deg/s ): while True: self.drive_once_by_ir_beacon(speed=speed) def back_whenever_touched( self, speed: float = 1000 # deg/s ): while True: if self.touch_sensor.pressed(): self.front_foot_motor.run_time( speed=-speed, time=1000, # ms then=Stop.COAST, wait=False) self.back_foot_motor.run_time( speed=-speed, time=1000, # ms then=Stop.COAST, wait=True) def main( self, speed: float = 1000 # deg/s ): Process(target=self.back_whenever_touched).start() # FIXME: as soon as Touch Sensor pressed # OSError: [Errno 5] EIO: # Unexpected hardware input/output error with a motor or sensor: # --> Try unplugging the sensor or motor and plug it back in again. # --> To see which sensor or motor is causing the problem, # check the line in your script that matches # the line number given in the 'Traceback' above. # --> Try rebooting the hub/brick if the problem persists. self.keep_driving_by_ir_beacon(speed=speed)
# From https://docs.pybricks.com/en/latest/ev3devices.html#motors # --->>>>>> run_time(speed, time, then=Stop.HOLD, wait=True) # speed (rotational speed: deg/s) – Speed of the motor. # time (time: ms) – Duration of the maneuver. # then (Stop) – What to do after coming to a standstill. # Using a new mode from https://docs.pybricks.com/en/latest/parameters/stop.html # ---->>>>>>> Stop.COAST (Let the motor move freely) # wait (bool) – Wait for the maneuver to complete before continuing with the rest of the program. # The first is False for simultaneus moviment for i in range(0, len(vec_array)-1): if direction == 'left': esquerda.run(vec_array[i]) direita.run(-vec_array[i]) wait(dt*1000) elif direction == 'right': esquerda.run(-vec_array[i]) direita.run(vec_array[i]) wait(dt*1000) else: esquerda.HOLD() direita.HOLD() Acelera(600, 1480) MotorMA.run_time(-1000, 2500) Curva(100, 90, 'right') MotorMA.run_time(1000, 2500) Acelera(-200, -200) Curva(300, 90, 'left')
class R3ptar: """ R3ptar can be driven around by the IR Remote Control, strikes when the Beacon button is pressed, and hisses when the Touch Sensor is pressed (inspiration from LEGO Mindstorms EV3 Home Edition: R3ptar: Tutorial #4) """ def __init__(self, steering_motor_port: Port = Port.A, driving_motor_port: Port = Port.B, striking_motor_port: Port = Port.D, touch_sensor_port: Port = Port.S1, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): self.ev3_brick = EV3Brick() self.steering_motor = Motor(port=steering_motor_port, positive_direction=Direction.CLOCKWISE) self.driving_motor = Motor(port=driving_motor_port, positive_direction=Direction.CLOCKWISE) self.striking_motor = Motor(port=striking_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def drive_by_ir_beacon( self, speed: float = 1000, # mm/s ): ir_beacons_pressed = \ set(self.ir_sensor.buttons(channel=self.ir_beacon_channel)) if ir_beacons_pressed == {Button.LEFT_UP, Button.RIGHT_UP}: self.driving_motor.run(speed=speed) elif ir_beacons_pressed == {Button.LEFT_DOWN, Button.RIGHT_DOWN}: self.driving_motor.run(speed=-speed) elif ir_beacons_pressed == {Button.LEFT_UP}: self.steering_motor.run(speed=-500) self.driving_motor.run(speed=speed) elif ir_beacons_pressed == {Button.RIGHT_UP}: self.steering_motor.run(speed=500) self.driving_motor.run(speed=speed) elif ir_beacons_pressed == {Button.LEFT_DOWN}: self.steering_motor.run(speed=-500) self.driving_motor.run(speed=-speed) elif ir_beacons_pressed == {Button.RIGHT_DOWN}: self.steering_motor.run(speed=500) self.driving_motor.run(speed=-speed) else: self.steering_motor.hold() self.driving_motor.stop() def strike_by_ir_beacon(self, speed: float = 1000): if Button.BEACON in \ self.ir_sensor.buttons(channel=self.ir_beacon_channel): self.striking_motor.run_time(speed=speed, time=1000, then=Stop.COAST, wait=True) self.striking_motor.run_time(speed=-speed, time=1000, then=Stop.COAST, wait=True) while Button.BEACON in \ self.ir_sensor.buttons(channel=self.ir_beacon_channel): pass def hiss_if_touched(self): if self.touch_sensor.pressed(): self.ev3_brick.speaker.play_file(file=SoundFile.SNAKE_HISS) def main(self, speed: float = 1000): """ R3ptar's main program performing various capabilities """ while True: self.drive_by_ir_beacon(speed=speed) self.strike_by_ir_beacon(speed=speed) self.hiss_if_touched() wait(1)
from pybricks.robotics import DriveBase # Create your objects here. ev3 = EV3Brick() # Initialize the Ultrasonic Sensors. obstacle_sensor = UltrasonicSensor(Port.S1) color_sensor = ColorSensor(Port.S4) # Initialize two motors. left_motor = Motor(Port.B) right_motor = Motor(Port.C) arm_motor = Motor(Port.D) # The DriveBase is composed of two motors, with a wheel on each motor. robot = DriveBase(left_motor, right_motor, wheel_diameter=55.5, axle_track=104) #drive_time(speed:mm/s, steering:deg/s, time:ms) robot.drive_time(100, 0, 1000) #Drive forward 10cm robot.stop() #run arm motor (speed mm/s, rotational angle) arm_motor.run_angle(-100, 60) #run time with wait as FALSE #run_time(speed deg/s, time ms, then=Stop.HOLD, wait=True) left_motor.run_time(-100, 1000, Stop.HOLD, False) right_motor.run_time(-100, 1000, Stop.HOLD, False) arm_motor.run_time(50, 1000, Stop.HOLD, False) wait(1000)
class Gripp3r(IRBeaconRemoteControlledTank, EV3Brick): WHEEL_DIAMETER = 26 AXLE_TRACK = 115 def __init__(self, left_motor_port: Port = Port.B, right_motor_port: Port = Port.C, grip_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): super().__init__(wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK, left_motor_port=left_motor_port, right_motor_port=right_motor_port, ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel) self.drive_base.settings( straight_speed=750, # milimeters per second straight_acceleration=750, turn_rate=90, # degrees per second turn_acceleration=90) self.grip_motor = Motor(port=grip_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def grip_or_release_by_ir_beacon(self, speed: float = 500): while True: if Button.BEACON in self.ir_sensor.buttons( channel=self.ir_beacon_channel): if self.touch_sensor.pressed(): self.speaker.play_file(file=SoundFile.AIR_RELEASE) self.grip_motor.run_time(speed=speed, time=1000, then=Stop.BRAKE, wait=True) else: self.speaker.play_file(file=SoundFile.AIRBRAKE) self.grip_motor.run(speed=-speed) while not self.touch_sensor.pressed(): pass self.grip_motor.stop() while Button.BEACON in self.ir_sensor.buttons( channel=self.ir_beacon_channel): pass def main(self, speed: float = 1000): self.grip_motor.run_time(speed=-500, time=1000, then=Stop.BRAKE, wait=True) Thread(target=self.grip_or_release_by_ir_beacon).start() self.keep_driving_by_ir_beacon(speed=speed)
def run1(drive_base): drive_base.striaght(200) arm = Motor(Port.A) arm.run_time(360, 1, then=Stop.HOLD, wait=true) drive_base.striaght(-200)
#!/usr/bin/env pybricks-micropython from pybricks import ev3brick as brick from pybricks.hubs import EV3Brick from pybricks.ev3devices import Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor from pybricks.parameters import Port, Stop, Direction, Button, Color, SoundFile, ImageFile, Align from pybricks.tools import wait, StopWatch, DataLog from pybricks.robotics import DriveBase import time # B, C 모터 선언 motorB = Motor(Port.B) # 왼쪽 바퀴 motorC = Motor(Port.C) # 오른쪽 바퀴 # 후진 # B, C 모터를 -300의 속도로 3초(3,000ms)간 회전 # 속도가 음수가 되면 후진을 실시한다. motorB.run_time(-300, 3000, Stop.BRAKE, False) motorC.run_time(-300, 3000, Stop.BRAKE, True)
from pybricks.media.ev3dev import SoundFile from pybricks.parameters import Direction, Port, Stop BRICK = EV3Brick() MEDIUM_MOTOR = Motor(port=Port.A, positive_direction=Direction.CLOCKWISE) GO_MOTOR = Motor(port=Port.B, positive_direction=Direction.CLOCKWISE) MEDIUM_MOTOR.run_time( speed=500, time=1000, then=Stop.HOLD, wait=True) MEDIUM_MOTOR.run_time( speed=-500, time=0.3 * 1000, then=Stop.HOLD, wait=True) for i in range(2): for p in range(3): MEDIUM_MOTOR.run_time( speed=750, time=0.2 * 1000, then=Stop.HOLD,
wait(500) gsnow = gyro_angle_1 = gyroSensor.angle() print('GS Calibration finish ' + str(gsnow)) global accangle error = 0 turnrate = 0 robot.reset() while abs(robot.distance()) < desmond: error = accangle - gyroSensor.angle() turnrate = error / 0.25 robot.drive(sped, -turnrate) robot.stop() wait(10) accangle = 0 gyroSensor.reset_angle(0) straight(270, 200) line_follow(rightcolor, 175, 1.6, 0.04, 0.1, 0.01, 1200) #turntoangle(0.01) robot.drive(80, -2) mediummotor2.run_time(300, 1000) wait(1500) robot.stop() leftmotor.hold() rightmotor.hold() mediummotor2.run_time(1000, 2500) turntoangle(-1, True) accangle = 1 oldstraight(2000, -500)
class Robot: def __init__(self): """Class that represents the robot """ try: self.state = "Port 1: Right Color" self.right_color = ColorSensor(Port.S1) self.state = "Port 2: Center Color" self.center_color = ColorSensor(Port.S2) self.state = "Port 3: Left Color" self.left_color = ColorSensor(Port.S3) self.state = "Port 4: Gyro" self.gyro = GyroSensor(Port.S4, Direction.COUNTERCLOCKWISE) self.state = "Port A: Left Motor" self.left_motor = Motor(Port.A) self.state = "Port B: Right Motor" self.right_motor = Motor(Port.B) self.state = "Port C: Linear Gear" self.linear_attachment_motor = Motor(Port.C) self.state = "Port D: Block Dropper" self.dropper_attachment_motor = Motor(Port.D) self.wheel_diameter = 55 self.axle_track = 123 self.drive_base = DriveBase(self.left_motor, self.right_motor, self.wheel_diameter, self.axle_track) self.state = "OK" self.clock = StopWatch() self.dance_clock = 0 self.sign = 1 except: brick.screen.clear() big_font = Font(size=18) brick.screen.set_font(big_font) brick.screen.draw_text(0, 20, "Error!") brick.screen.draw_text(0, 40, self.state) def display_sensor_values(self): """Displays sensor values """ gyro_value = "Gyro : {}".format(self.gyro.angle()) left_color_value = "Left Color : {}".format( self.left_color.reflection()) right_color_value = "Right Color : {}".format( self.right_color.reflection()) center_color_value = "Center Color : {}".format( self.center_color.reflection()) big_font = Font(size=18) brick.screen.set_font(big_font) brick.screen.clear() brick.screen.draw_text(0, 20, gyro_value) brick.screen.draw_text(0, 40, left_color_value) brick.screen.draw_text(0, 60, right_color_value) brick.screen.draw_text(0, 80, center_color_value) def is_ok(self): """Tells if all sensors are plugged in :return: Checks the state of the sensors :rtype: Boolean """ return self.state == "OK" def beep(self, is_down=False): """Plays a series of beeps :param is_down: Tells if to play series downwards, defaults to False :type is_down: bool, optional """ beep_counts = range(1, 7) if not is_down else range(6, 0, -1) for beep_count in beep_counts: brick.speaker.beep(400 * beep_count, 100) wait(20) def drift_check(self): brick.speaker.beep(1200, 500) wait(100) brick.speaker.beep(1200, 500) drift = False start_gyro = self.gyro.angle() brick.screen.clear() big_font = Font(size=18) brick.screen.set_font(big_font) brick.screen.draw_text(0, 20, "Checking Gyro drift...") wait(2000) if start_gyro != self.gyro.angle(): brick.screen.draw_text(0, 60, "Error!") brick.screen.draw_text(0, 80, "Gyro drift") drift = True return drift def print_sensor_values(self): """Display robot sensor values. For debugging only """ print("Gyro: ", self.gyro.angle()) print("Left Color: ", self.left_color.reflection()) print("Right Color: ", self.right_color.reflection()) print("Center Color: ", self.center_color.reflection()) def stop_motors(self): """ Stops all motors """ self.left_motor.stop(Stop.BRAKE) self.right_motor.stop(Stop.BRAKE) self.linear_attachment_motor.stop(Stop.BRAKE) def drive(self, pid, speed, target_angle, duration): """Drives the robot using a gyro to a specific angle :param pid: Uses Pid instance with parameters set beforehand :type pid: Class :param speed: Speed of the robot :type speed: Number :param target_angle: Angle to drive the robot at :type target_angle: Number :param duration: Duration the function is run :type duration: Number """ # Inititialize values pid.reset() while pid.clock.time() < duration: # Calculatr error actual_angle = self.gyro.angle() error = (target_angle - actual_angle) % 360 error = error - (360 * int(error / 180)) # Calculate steering output steering = pid.compute_steering(error) # Drive the motors self.drive_base.drive(speed, steering) self.print_sensor_values # Stop motors self.drive_base.stop(Stop.BRAKE) def drive_dead_reckon(self, speed, duration, steering=0): self.drive_base.drive(speed, steering) wait(duration) self.drive_base.stop(Stop.BRAKE) def turn(self, pid, target_angle, tolerance=1): """Turns the robot to a specific angle. :param pid: Uses Pid instance with parameters set beforehand :type pid: Number :param target_angle: Angle the robot turns to :type target_angle: Number :param tolerance: How close to the target angle you want the robot to be :type tolerance: Number """ # Inititialize values pid.reset() error = tolerance + 1 min_speed = 50 while abs(error) > tolerance: # Calculate error actual_angle = self.gyro.angle() error = (target_angle - actual_angle) % 360 error = error - (360 * int(error / 180)) # Call Pid compute_steering steering = pid.compute_steering(error) * -1 # Set speed using a min_speed right_speed = max(min_speed, abs(steering)) if steering < 0: right_speed = -1 * right_speed left_speed = -1 * right_speed # Run motors self.left_motor.run(left_speed) self.right_motor.run(right_speed) # Stop motors self.left_motor.stop() self.right_motor.stop() def follow_line(self, pid, speed, duration, which_sensor, which_edge): """Follows the line using a color sensor. :param pid: Uses Pid instance with parameters set beforehand :type pid: Pid :param speed: Speed of the Robot :type speed: Number :param duration: Duration of the function :type duration: Number :param which_sensor: The sensor the robot uses to follow the line :type which_sensor: LineSensor :param which_edge: Which side the white is on relative to the robot :type which_edge: LineEdge """ # Inititialize values pid.reset() while pid.clock.time() < duration: # Selecting which sensor to use using an Enum if which_sensor == LineSensor.RIGHT: error = 50 - self.right_color.reflection() if which_sensor == LineSensor.LEFT: error = 50 - self.left_color.reflection() if which_sensor == LineSensor.CENTER: error = 50 - self.center_color.reflection() # Selecting which edge of the line to use if which_edge == LineEdge.RIGHT: pass else: error = error * -1 # Calculate steering steering = pid.compute_steering(error) # Run motors self.drive_base.drive(speed, steering) self.drive_base.stop(Stop.BRAKE) def stop_on_white(self, pid, speed, target_angle, which_sensor, color_value=80): """ Gyro drives until given color sensor is on white :param pid: PID setting of drive :type pid: Number :param speed: The speed the robot moves at :type speed: Number :param target_angle: the angle the gyro drives at :type target_angle: :param which_sensor: Chooses which color sensor to use :type which_sensor: Enum :param color_value: The value of color that the robot stops at :type color_value: Number """ # Inititialize values sensor = 0 pid.reset() target_angle = target_angle % 360 if which_sensor == LineSensor.LEFT: sensor = self.left_color elif which_sensor == LineSensor.RIGHT: sensor = self.right_color else: sensor = self.center_color while sensor.reflection() < color_value: # Calculate error actual_angle = self.gyro.angle() error = (target_angle - actual_angle) % 360 error = error - (360 * int(error / 180)) # Calculate steering output steering = pid.compute_steering(error) # Drive the motors self.drive_base.drive(speed, steering) self.print_sensor_values # Stop motors self.drive_base.stop(Stop.BRAKE) def stop_on_black(self, pid, speed, target_angle, which_sensor, color_value=15): """ Gyro drives until given color sensor is on black :param pid: PID setting of drive :type pid: Number :param speed: The speed the robot moves at :type speed: Number :param target_angle: the angle the gyro drives at :type target_angle: :param which_sensor: Chooses which color sensor to use :type which_sensor: Enum :param color_value: The value of color that the robot stops at :type color_value: Number """ # Inititialize values sensor = 0 pid.reset() target_angle = target_angle % 360 if which_sensor == LineSensor.LEFT: sensor = self.left_color elif which_sensor == LineSensor.RIGHT: sensor = self.right_color else: sensor = self.center_color while sensor.reflection() > color_value: # Calculate error actual_angle = self.gyro.angle() error = (target_angle - actual_angle) % 360 error = error - (360 * int(error / 180)) # Calculate steering output steering = pid.compute_steering(error) # Drive the motors self.drive_base.drive(speed, steering) self.print_sensor_values # Stop motors self.drive_base.stop(Stop.BRAKE) def align(self, speed, sensor1, sensor2): """Aligns using color sensors on black line :param speed: The speed the robot moves at :type speed: Number :param sensor1: The first sensor the robot uses to align :type sensor1: Enum :param sensor2: The second sensor the robot uses to align :type sensor2: Enum """ self.left_motor.run(speed) self.right_motor.run(speed) first_sensor = 0 second_sensor = 0 if sensor1 == LineSensor.LEFT: first_sensor = self.left_color elif sensor1 == LineSensor.RIGHT: first_sensor = self.right_color else: first_sensor = self.center_color if sensor2 == LineSensor.LEFT: second_sensor = self.left_color elif sensor2 == LineSensor.RIGHT: second_sensor = self.right_color else: second_sensor = self.center_color while True: first = False second = False if first_sensor.reflection() <= 10: self.left_motor.hold() first = True if second_sensor.reflection() <= 10: self.right_motor.hold() second = True if first and second == True: break def reset_sensors(self, reset_angle=0): """Reset the robot's sensor values :param reset_angle: inital angle for the gyro, defaults to 0 :type reset_angle: int, optional """ # Resets the gyro self.gyro.reset_angle(reset_angle) def run_linear(self, speed, time, wait=True): """Runs linear gear :param speed: The speed the linear gear moves at :type speed: Number :param time: How long the linear gear runs for :type time: Number :param wait: Wait for action to complete before next step :type wait: Boolean """ self.stop_motors() self.linear_attachment_motor.run_time(speed, time, Stop.BRAKE, wait) def move_linear(self, speed, rotations, wait=True): """Will calculate the ratio of the gears and then move the linear gear to a specific angle :param speed: The speed the linear gear moves at :type speed: Number :param rotations: How much the linear gear moves by in rotations :type rotations: Number :param wait: Wait for action to complete before next step :type wait: Boolean """ self.stop_motors() target_angle = rotations * 360 self.linear_attachment_motor.run_angle(speed, target_angle, Stop.BRAKE, wait) def run_dropper(self, speed, time, wait=True): """Runs block dropper :param speed: The speed the yeeter moves at :type speed: Number :param time: How long the yeeter runs for :type time: Number :param wait: Wait for action to complete before next step :type wait: Boolean """ self.stop_motors() self.dropper_attachment_motor.run_time(speed, time, Stop.BRAKE, wait) def move_dropper(self, speed, degrees, wait=True): """Will calculate the ratio of the gears and then move the block dropper to a specific angle :param speed: The speed the yeeter moves at :type speed: Number :param degrees: How much the yeeter moves by in degrees :type degrees: Number :param wait: Wait for action to complete before next step :type wait: Boolean """ self.stop_motors() self.dropper_attachment_motor.run_angle(speed, degrees, Stop.BRAKE, wait) def dance(self, speed, duration): if self.dance_clock == 0: self.dance_clock = self.clock.time() self.left_motor.run(speed * self.sign * -1) self.right_motor.run(speed * self.sign) if self.clock.time() - self.dance_clock > duration: self.sign *= -1 self.left_motor.run(speed * self.sign * -1) self.right_motor.run(speed * self.sign) self.dance_clock = self.clock.time() return True return False
class Wack3m: N_WHACK_TIMES = 10 def __init__( self, left_motor_port: str = Port.B, right_motor_port: str = Port.C, middle_motor_port: str = Port.A, touch_sensor_port: str = Port.S1, ir_sensor_port: str = Port.S4): self.ev3_brick = EV3Brick() self.left_motor = Motor(port=left_motor_port, positive_direction=Direction.CLOCKWISE) self.right_motor = Motor(port=right_motor_port, positive_direction=Direction.CLOCKWISE) self.middle_motor = Motor(port=middle_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) def start_up(self): self.ev3_brick.light.on(color=Color.RED) self.ev3_brick.screen.print('WACK3M') self.left_motor.run_time( speed=-1000, time=1000, then=Stop.HOLD, wait=True) self.left_motor.reset_angle(angle=0) self.middle_motor.run_time( speed=-1000, time=1000, then=Stop.HOLD, wait=True) self.middle_motor.reset_angle(angle=0) self.right_motor.run_time( speed=-1000, time=1000, then=Stop.HOLD, wait=True) self.right_motor.reset_angle(angle=0) def play(self): while True: self.ev3_brick.speaker.play_file(file=SoundFile.START) self.ev3_brick.screen.load_image(ImageFile.TARGET) self.ev3_brick.light.on(color=Color.ORANGE) while not self.touch_sensor.pressed(): wait(10) self.ev3_brick.speaker.play_file(file=SoundFile.GO) self.ev3_brick.light.on(color=Color.GREEN) total_response_time = 0 sleep(1) for _ in range(self.N_WHACK_TIMES): self.ev3_brick.light.on(color=Color.GREEN) self.ev3_brick.screen.load_image(ImageFile.EV3_ICON) sleep(uniform(0.1, 3)) which_motor = randint(1, 3) if which_motor == 1: self.left_motor.run_angle( speed=1000, rotation_angle=90, then=Stop.COAST, wait=True) start_time = time() self.ev3_brick.screen.load_image(ImageFile.MIDDLE_LEFT) self.left_motor.run_time( speed=-1000, time=500, then=Stop.HOLD, wait=True) proximity = self.ir_sensor.distance() while abs(self.ir_sensor.distance() - proximity) <= 4: wait(10) elif which_motor == 2: self.middle_motor.run_angle( speed=1000, rotation_angle=210, then=Stop.COAST, wait=True) start_time = time() self.ev3_brick.screen.load_image(ImageFile.NEUTRAL) self.middle_motor.run_time( speed=-1000, time=500, then=Stop.COAST, wait=True) proximity = self.ir_sensor.distance() while abs(self.ir_sensor.distance() - proximity) <= 5: wait(10) else: self.right_motor.run_angle( speed=1000, rotation_angle=90, then=Stop.COAST, wait=True) start_time = time() self.ev3_brick.screen.load_image(ImageFile.MIDDLE_RIGHT) self.right_motor.run_time( speed=-1000, time=500, then=Stop.HOLD, wait=True) proximity = self.ir_sensor.distance() while abs(self.ir_sensor.distance() - proximity) <= 5: wait(10) response_time = time() - start_time self.ev3_brick.screen.load_image(ImageFile.DIZZY) self.ev3_brick.screen.print(response_time) self.ev3_brick.light.on(color=Color.RED) self.ev3_brick.speaker.play_file(file=SoundFile.BOING) total_response_time += response_time average_response_time = total_response_time / self.N_WHACK_TIMES self.ev3_brick.screen.clear() self.ev3_brick.screen.print( 'Avg. Time: {:.1f}s'.format(average_response_time)) self.ev3_brick.speaker.play_file( file=SoundFile.FANTASTIC if average_response_time <= 1 else SoundFile.GOOD_JOB) self.ev3_brick.speaker.play_file(file=SoundFile.GAME_OVER) self.ev3_brick.light.on(color=Color.RED) sleep(4)
class Dinor3x(EV3Brick): """ Challenges: - Can you make DINOR3X remote controlled with the IR-Beacon? - Can you attach a colorsensor to DINOR3X, and make it behave differently depending on which color is in front of the sensor (red = walk fast, white = walk slow, etc.)? """ def __init__( self, left_motor_port: Port = Port.B, right_motor_port: Port = Port.C, jaw_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): self.left_motor = Motor(port=left_motor_port, positive_direction=Direction.CLOCKWISE) self.right_motor = Motor(port=right_motor_port, positive_direction=Direction.CLOCKWISE) self.jaw_motor = Motor(port=jaw_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def calibrate_legs(self): self.left_motor.run(speed=100) self.right_motor.run(speed=200) while self.touch_sensor.pressed(): pass self.left_motor.hold() self.right_motor.hold() self.left_motor.run(speed=400) while not self.touch_sensor.pressed(): pass self.left_motor.hold() self.left_motor.run_angle( rotation_angle=-0.2 * 360, speed=500, then=Stop.HOLD, wait=True) self.right_motor.run(speed=400) while not self.touch_sensor.pressed(): pass self.right_motor.hold() self.right_motor.run_angle( rotation_angle=-0.2 * 360, speed=500, then=Stop.HOLD, wait=True) self.left_motor.reset_angle(angle=0) self.right_motor.reset_angle(angle=0) def roar(self): self.speaker.play_file(file=SoundFile.T_REX_ROAR) self.jaw_motor.run_angle( speed=400, rotation_angle=-60, then=Stop.HOLD, wait=True) # FIXME: jaw doesn't close for i in range(12): self.jaw_motor.run_time( speed=-400, time=0.05 * 1000, then=Stop.HOLD, wait=True) self.jaw_motor.run_time( speed=400, time=0.05 * 1000, then=Stop.HOLD, wait=True) self.jaw_motor.run(speed=200) sleep(0.5) def close_mouth(self): self.jaw_motor.run(speed=200) sleep(1) self.jaw_motor.stop() def walk_until_blocked(self): self.left_motor.run(speed=-400) self.right_motor.run(speed=-400) while self.ir_sensor.distance() >= 25: pass self.left_motor.stop() self.right_motor.stop() def run_away(self): self.left_motor.run_angle( speed=750, rotation_angle=3 * 360, then=Stop.BRAKE, wait=False) self.right_motor.run_angle( speed=750, rotation_angle=3 * 360, then=Stop.BRAKE, wait=True) def jump(self): """ Dinor3x Mission 02 Challenge: make it jump """ ... # TRANSLATED FROM EV3-G MY BLOCKS # ------------------------------- def leg_adjust( self, cyclic_degrees: float, speed: float = 1000, leg_offset_percent: float = 0, mirrored_adjust: bool = False, brake: bool = True): ... def leg_to_pos( self, speed: float = 1000, left_position: float = 0, right_position: float = 0): self.left_motor.brake() self.right_motor.brake() self.left_motor.run_angle( speed=speed, rotation_angle=left_position - cyclic_position_offset( rotation_sensor=self.left_motor.angle(), cyclic_degrees=360), then=Stop.BRAKE, wait=True) self.right_motor.run_angle( speed=speed, rotation_angle=right_position - cyclic_position_offset( rotation_sensor=self.right_motor.angle(), cyclic_degrees=360), then=Stop.BRAKE, wait=True) def turn(self, speed: float = 1000, n_steps: int = 1): ... def walk(self, speed: float = 1000): ... def walk_steps(self, speed: float = 1000, n_steps: int = 1): ...
class Spik3r: def __init__( self, crushing_claw_motor_port: Port = Port.A, moving_motor_port: Port = Port.B, lightning_tail_motor_port: Port = Port.D, touch_sensor_port: Port = Port.S1, color_sensor_port: Port = Port.S3, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): self.ev3_brick = EV3Brick() self.crushing_claw_motor = \ Motor(port=crushing_claw_motor_port, positive_direction=Direction.CLOCKWISE) self.moving_motor = \ Motor(port=moving_motor_port, positive_direction=Direction.CLOCKWISE) self.lightning_tail_motor = \ Motor(port=lightning_tail_motor_port, positive_direction=Direction.CLOCKWISE) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel self.touch_sensor = TouchSensor(port=touch_sensor_port) self.color_sensor = ColorSensor(port=color_sensor_port) def sting_by_ir_beacon(self, speed: float = 1000): """ Spik3r stings with its Lightning Tail when the Beacon button is pressed (inspiration from LEGO Mindstorms EV3 Home Ed.: Spik3r: Tutorial #1) """ if Button.BEACON in \ self.ir_sensor.buttons(channel=self.ir_beacon_channel): self.lightning_tail_motor.run_angle( speed=-750, rotation_angle=220, then=Stop.HOLD, wait=False) self.ev3_brick.speaker.play_file(file=SoundFile.ERROR_ALARM) self.lightning_tail_motor.run_time( speed=-speed, time=1000, then=Stop.COAST, wait=True) self.lightning_tail_motor.run_time( speed=speed, time=1000, then=Stop.COAST, wait=True) while Button.BEACON in \ self.ir_sensor.buttons(channel=self.ir_beacon_channel): pass def move_by_ir_beacon(self, speed: float = 1000): """ Spik3r moves forward when the IR Beacon's two Up buttons are pressed, and turns right when only the Right Up button is pressed (inspiration from LEGO Mindstorms EV3 Home Ed.: Spik3r: Tutorial #2) """ ir_buttons_pressed = \ set(self.ir_sensor.buttons(channel=self.ir_beacon_channel)) if ir_buttons_pressed == {Button.RIGHT_UP, Button.LEFT_UP}: self.moving_motor.run(speed=speed) elif ir_buttons_pressed == {Button.RIGHT_UP}: self.moving_motor.run(speed=-speed) else: self.moving_motor.stop() def pinch_if_touched(self, speed: float = 1000): """ Spik3r crushes objects with its Claw when the Touch Sensor is pressed (inspiration from LEGO Mindstorms EV3 Home Ed.: Spik3r: Tutorial #3) """ if self.touch_sensor.pressed(): self.crushing_claw_motor.run_time( speed=speed, time=1000, then=Stop.COAST, wait=True) self.crushing_claw_motor.run_time( speed=-speed, time=1000, then=Stop.COAST, wait=True) def main(self, speed: float = 1000): """ Spik3r's main program performing various capabilities """ self.ev3_brick.screen.load_image(ImageFile.WARNING) while True: self.move_by_ir_beacon(speed=speed) self.sting_by_ir_beacon(speed=speed) self.pinch_if_touched(speed=speed) wait(1)
class Rac3Truck: WHEEL_DIAMETER = 30 # milimeters AXLE_TRACK = 120 # milimeters def __init__( self, left_motor_port: str = Port.B, right_motor_port: str = Port.C, polarity: str = 'inversed', steer_motor_port: str = Port.A, ir_sensor_port: str = Port.S4, ir_beacon_channel: int = 1): if polarity == 'normal': self.left_motor = Motor(port=left_motor_port, positive_direction=Direction.CLOCKWISE) self.right_motor = Motor(port=right_motor_port, positive_direction=Direction.CLOCKWISE) else: self.left_motor = \ Motor(port=left_motor_port, positive_direction=Direction.COUNTERCLOCKWISE) self.right_motor = \ Motor(port=right_motor_port, positive_direction=Direction.COUNTERCLOCKWISE) self.driver = DriveBase(left_motor=self.left_motor, right_motor=self.right_motor, wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK) self.steer_motor = Motor(port=steer_motor_port, positive_direction=Direction.CLOCKWISE) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def reset(self): self.steer_motor.run_time( speed=300, time=1500, then=Stop.COAST, wait=True) self.steer_motor.run_angle( speed=-500, rotation_angle=120, then=Stop.HOLD, wait=True) self.steer_motor.reset_angle(angle=0) def steer_left(self): if self.steer_motor.angle() > -65: self.steer_motor.run_target( speed=-200, target_angle=-65, then=Stop.HOLD, wait=True) else: self.steer_motor.hold() def steer_right(self): if self.steer_motor.angle() < 65: self.steer_motor.run_target( speed=200, target_angle=65, then=Stop.HOLD, wait=True) else: self.steer_motor.hold() def steer_center(self): if self.steer_motor.angle() < -7: self.steer_motor.run_target( speed=200, target_angle=4, then=Stop.HOLD, wait=True) elif self.steer_motor.angle() > 7: self.steer_motor.run_target( speed=-200, target_angle=-4, then=Stop.HOLD, wait=True) self.steer_motor.hold() wait(100) def drive_by_ir_beacon(self): ir_beacon_button_pressed = \ set(self.ir_sensor.buttons(channel=self.ir_beacon_channel)) # forward if ir_beacon_button_pressed == {Button.LEFT_UP, Button.RIGHT_UP}: self.driver.drive( speed=800, turn_rate=0) self.steer_center() # backward elif ir_beacon_button_pressed == {Button.LEFT_DOWN, Button.RIGHT_DOWN}: self.driver.drive( speed=-800, turn_rate=0) self.steer_center() # turn left forward elif ir_beacon_button_pressed == {Button.LEFT_UP}: self.left_motor.run(speed=600) self.right_motor.run(speed=1000) self.steer_left() # turn right forward elif ir_beacon_button_pressed == {Button.RIGHT_UP}: self.left_motor.run(speed=1000) self.right_motor.run(speed=600) self.steer_right() # turn left backward elif ir_beacon_button_pressed == {Button.LEFT_DOWN}: self.left_motor.run(speed=-600) self.right_motor.run(speed=-1000) self.steer_left() # turn right backward elif ir_beacon_button_pressed == {Button.RIGHT_DOWN}: self.left_motor.run(speed=-1000) self.right_motor.run(speed=-600) self.steer_right() # otherwise stop else: self.driver.stop() self.steer_center()
class Gripp3r(EV3Brick): WHEEL_DIAMETER = 26 AXLE_TRACK = 115 def __init__(self, left_motor_port: Port = Port.B, right_motor_port: Port = Port.C, grip_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): self.drive_base = DriveBase( left_motor=Motor(port=left_motor_port, positive_direction=Direction.CLOCKWISE), right_motor=Motor(port=right_motor_port, positive_direction=Direction.CLOCKWISE), wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK) self.drive_base.settings( straight_speed=750, # milimeters per second straight_acceleration=750, turn_rate=90, # degrees per second turn_acceleration=90) self.grip_motor = Motor(port=grip_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def keep_driving_by_ir_beacon( self, channel: int = 1, speed: float = 1000 # milimeters per second ): while True: ir_beacon_buttons_pressed = set( self.ir_sensor.buttons(channel=channel)) # forward if ir_beacon_buttons_pressed == {Button.LEFT_UP, Button.RIGHT_UP}: self.drive_base.drive( speed=speed, turn_rate=0 # degrees per second ) # backward elif ir_beacon_buttons_pressed == { Button.LEFT_DOWN, Button.RIGHT_DOWN }: self.drive_base.drive( speed=-speed, turn_rate=0 # degrees per second ) # turn left on the spot elif ir_beacon_buttons_pressed == { Button.LEFT_UP, Button.RIGHT_DOWN }: self.drive_base.drive( speed=0, turn_rate=-90 # degrees per second ) # turn right on the spot elif ir_beacon_buttons_pressed == { Button.LEFT_DOWN, Button.RIGHT_UP }: self.drive_base.drive( speed=0, turn_rate=90 # degrees per second ) # turn left forward elif ir_beacon_buttons_pressed == {Button.LEFT_UP}: self.drive_base.drive( speed=speed, turn_rate=-90 # degrees per second ) # turn right forward elif ir_beacon_buttons_pressed == {Button.RIGHT_UP}: self.drive_base.drive( speed=speed, turn_rate=90 # degrees per second ) # turn left backward elif ir_beacon_buttons_pressed == {Button.LEFT_DOWN}: self.drive_base.drive( speed=-speed, turn_rate=90 # degrees per second ) # turn right backward elif ir_beacon_buttons_pressed == {Button.RIGHT_DOWN}: self.drive_base.drive( speed=-speed, turn_rate=-90 # degrees per second ) # otherwise stop else: self.drive_base.stop() def grip_or_release_by_ir_beacon(self, speed: float = 500): while True: if Button.BEACON in self.ir_sensor.buttons( channel=self.ir_beacon_channel): if self.touch_sensor.pressed(): self.speaker.play_file(file=SoundFile.AIR_RELEASE) self.grip_motor.run_time(speed=speed, time=1000, then=Stop.BRAKE, wait=True) else: self.speaker.play_file(file=SoundFile.AIRBRAKE) self.grip_motor.run(speed=-speed) while not self.touch_sensor.pressed(): pass self.grip_motor.stop() while Button.BEACON in self.ir_sensor.buttons( channel=self.ir_beacon_channel): pass def main(self, speed: float = 1000): self.grip_motor.run_time(speed=-500, time=1000, then=Stop.BRAKE, wait=True) Thread(target=self.grip_or_release_by_ir_beacon).start() self.keep_driving_by_ir_beacon(speed=speed)
u = (Kp * error) + (Ki * integral) + (Kd * derivative) #limit u to safe values (between -1000 and 1000) if sp + abs(u) > (sp * 11): if u >= 0: u = (sp * 11) - sp else: u = sp - (sp * 11) print("Light level:", cs.reflection()) print("Distance:", us.distance()) # print("Color:", cs.color()) # print("Ambient light:", cs.ambient()) if u >= 0: #Go right if too bright. if not collected: if us.distance() < 40: slam() collected = True lm.run_time(sp + u, dt) rm.run_time(sp - u, dt) wait(5) else: #Go left if too dark. if not collected: if us.distance() < 40: slam() collected = True lm.run_time(sp - u, dt) rm.run_time(sp + u, dt) wait(5)
#Small Tire Flip robot.straight(1000) robot.stop() robot.settings(250, 300, 100, 600) StopAtWhiteLine() robot.straight(175) #robot turns toward the wall and reveres: robot.turn(-120) robot.straight(-180) #goes off the wall and turns to the wheel robot.straight(200) robot.turn(-65) robot.stop() #Goes foreward to flip the wheel medium_left.run_time(-200, 5000) robot.straight(80) medium_left.run_time(150, 5000) medium_left.stop() #Large Tire Flip #StopAtWhiteLineRightMotorBackwards() robot.turn(30) robot.straight(-50) medium_left.run_time(-200, 4000) robot.straight(110) medium_left.run_time(150, 6500) #back after both tire flip robot.turn(20) robot.straight(-550) robot.straight(150)
#!/usr/bin/env pybricks-micropython from pybricks.hubs import EV3Brick from pybricks.ev3devices import Motor from pybricks.media.ev3dev import SoundFile from pybricks.parameters import Direction, Port, Stop BRICK = EV3Brick() STING_MOTOR = Motor(port=Port.D, positive_direction=Direction.CLOCKWISE) GO_MOTOR = Motor(port=Port.B, positive_direction=Direction.CLOCKWISE) STING_MOTOR.run_time(speed=400, time=1000, then=Stop.HOLD, wait=True) # This block controls how far SPIK3R crawls. GO_MOTOR.run_angle(speed=1000, rotation_angle=3 * 360, then=Stop.HOLD, wait=True) BRICK.speaker.play_file(file=SoundFile.ERROR_ALARM) GO_MOTOR.run_angle(speed=-1000, rotation_angle=2 * 360, then=Stop.HOLD, wait=True) BRICK.speaker.play_file(file=SoundFile.ERROR_ALARM) STING_MOTOR.run_angle(speed=-750,
#!/usr/bin/env pybricks-micropython from pybricks import ev3brick as brick from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor) from pybricks.parameters import (Port, Stop, Direction, Button, Color, SoundFile, ImageFile, Align) from pybricks.tools import print, wait, StopWatch from pybricks.robotics import DriveBase # Write your program here right = Motor(Port.B, Direction.COUNTERCLOCKWISE) left = Motor(Port.C, Direction.COUNTERCLOCKWISE) stop_type = Stop.COAST right.run_time(613.88, 4400, Stop.BRAKE, False) left.run_time(613.88, 4400, Stop.BRAKE, True) right.stop() left.stop() wait(1000) brick.sound.beep() while not Button.CENTER in brick.buttons(): wait(10) ultrasonicSensor = UltrasonicSensor(Port.S1) stop_type = Stop.COAST while ultrasonicSensor.distance() > 515 or ultrasonicSensor.distance( ) < 485: # + distance the sensor is from the front of the robot if ultrasonicSensor.distance() > 515: right.run(200)
class Spik3r(EV3Brick): def __init__( self, sting_motor_port: Port = Port.D, go_motor_port: Port = Port.B, claw_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, color_sensor_port: Port = Port.S3, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): self.sting_motor = Motor(port=sting_motor_port, positive_direction=Direction.CLOCKWISE) self.go_motor = Motor(port=go_motor_port, positive_direction=Direction.CLOCKWISE) self.claw_motor = Motor(port=claw_motor_port, positive_direction=Direction.CLOCKWISE) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel self.touch_sensor = TouchSensor(port=touch_sensor_port) self.color_sensor = ColorSensor(port=color_sensor_port) def sting_by_ir_beacon(self): while True: ir_buttons_pressed = set(self.ir_sensor.buttons(channel=self.ir_beacon_channel)) if ir_buttons_pressed == {Button.BEACON}: self.sting_motor.run_angle( speed=-750, rotation_angle=220, then=Stop.HOLD, wait=False) self.speaker.play_file(file=SoundFile.EV3) self.sting_motor.run_time( speed=-1000, time=1000, then=Stop.HOLD, wait=True) self.sting_motor.run_time( speed=1000, time=1000, then=Stop.HOLD, wait=True) while Button.BEACON in self.ir_sensor.buttons(channel=self.ir_beacon_channel): pass def be_noisy_to_people(self): while True: if self.color_sensor.reflection() > 30: for i in range(4): self.speaker.play_file(file=SoundFile.ERROR_ALARM) def pinch_if_touched(self): while True: if self.touch_sensor.pressed(): self.claw_motor.run_time( speed=500, time=1000, then=Stop.HOLD, wait=True) self.claw_motor.run_time( speed=-500, time=0.3 * 1000, then=Stop.HOLD, wait=True) def keep_driving_by_ir_beacon(self): while True: ir_buttons_pressed = set(self.ir_sensor.buttons(channel=self.ir_beacon_channel)) if ir_buttons_pressed == {Button.RIGHT_UP, Button.LEFT_UP}: self.go_motor.run(speed=910) elif ir_buttons_pressed == {Button.RIGHT_UP}: self.go_motor.run(speed=-1000) else: self.go_motor.stop() def main(self): self.screen.load_image(ImageFile.EVIL) run_parallel( self.be_noisy_to_people, self.sting_by_ir_beacon, self.pinch_if_touched, self.keep_driving_by_ir_beacon)
class Spik3r(EV3Brick): def __init__(self, sting_motor_port: Port = Port.D, go_motor_port: Port = Port.B, claw_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, color_sensor_port: Port = Port.S3, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): self.sting_motor = Motor(port=sting_motor_port, positive_direction=Direction.CLOCKWISE) self.go_motor = Motor(port=go_motor_port, positive_direction=Direction.CLOCKWISE) self.claw_motor = Motor(port=claw_motor_port, positive_direction=Direction.CLOCKWISE) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel self.touch_sensor = TouchSensor(port=touch_sensor_port) self.color_sensor = ColorSensor(port=color_sensor_port) def sting_by_ir_beacon(self): while True: ir_buttons_pressed = set( self.ir_sensor.buttons(channel=self.ir_beacon_channel)) if ir_buttons_pressed == {Button.BEACON}: self.sting_motor.run_angle(speed=-750, rotation_angle=220, then=Stop.HOLD, wait=False) self.speaker.play_file(file=SoundFile.EV3) self.sting_motor.run_time(speed=-1000, time=1000, then=Stop.HOLD, wait=True) self.sting_motor.run_time(speed=1000, time=1000, then=Stop.HOLD, wait=True) while Button.BEACON in self.ir_sensor.buttons( channel=self.ir_beacon_channel): pass def be_noisy_to_people(self): while True: if self.color_sensor.reflection() > 30: for i in range(4): self.speaker.play_file(file=SoundFile.ERROR_ALARM) def pinch_if_touched(self): while True: if self.touch_sensor.pressed(): self.claw_motor.run_time(speed=500, time=1000, then=Stop.HOLD, wait=True) self.claw_motor.run_time(speed=-500, time=0.3 * 1000, then=Stop.HOLD, wait=True) def keep_driving_by_ir_beacon(self): while True: ir_buttons_pressed = set( self.ir_sensor.buttons(channel=self.ir_beacon_channel)) if ir_buttons_pressed == {Button.RIGHT_UP, Button.LEFT_UP}: self.go_motor.run(speed=910) elif ir_buttons_pressed == {Button.RIGHT_UP}: self.go_motor.run(speed=-1000) else: self.go_motor.stop() def main(self): self.screen.load_image(ImageFile.EVIL) # FIXME: OSError: [Errno 5] EIO: # Unexpected hardware input/output error with a motor or sensor: # --> Try unplugging the sensor or motor and plug it back in again. # --> To see which sensor or motor is causing the problem, # check the line in your script that matches # the line number given in the 'Traceback' above. # --> Try rebooting the hub/brick if the problem persists. Process(target=self.be_noisy_to_people).start() Process(target=self.sting_by_ir_beacon).start() Process(target=self.pinch_if_touched).start() self.keep_driving_by_ir_beacon()
class MarsRov3r(IRBeaconRemoteControlledTank, EV3Brick): WHEEL_DIAMETER = 40 AXLE_TRACK = 105 is_gripping = False def __init__( self, left_motor_port: Port = Port.B, right_motor_port: Port = Port.C, grip_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): super().__init__( wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK, left_motor_port=left_motor_port, right_motor_port=right_motor_port, ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel) self.drive_base.settings( straight_speed=750, # milimeters per second straight_acceleration=750, turn_rate=90, # degrees per second turn_acceleration=90) self.grip_motor = Motor(port=grip_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def grip_or_release_claw_by_ir_beacon(self): if Button.BEACON in \ self.ir_sensor.buttons(channel=self.ir_beacon_channel): if self.is_gripping: self.grip_motor.run_time( speed=1000, time=2000, then=Stop.HOLD, wait=True) self.speaker.play_file(file=SoundFile.AIR_RELEASE) self.is_gripping = False else: self.grip_motor.run_time( speed=-1000, time=2000, then=Stop.HOLD, wait=True) self.speaker.play_file(file=SoundFile.AIRBRAKE) self.is_gripping = True while Button.BEACON in self.ir_sensor.buttons(channel=1): pass def main(self): self.grip_motor.run_time( speed=500, time=1000, then=Stop.BRAKE, wait=True) while True: self.grip_or_release_claw_by_ir_beacon() self.drive_once_by_ir_beacon()
# Set up the Touch Sensor. It acts as an end-switch in the base # of the robot arm. It defines the starting point of the base. base_switch = TouchSensor(Port.S1) # Set up the Color Sensor. This sensor detects when the elbow # is in the starting position. This is when the sensor sees the # white beam up close. elbow_sensor = ColorSensor(Port.S3) # Initialize the elbow. First make it go down for one second. # Then make it go upwards slowly (15 degrees per second) until # the Color Sensor detects the white beam. Then reset the motor # angle to make this the zero point. Finally, hold the motor # in place so it does not move. elbow_motor.run_time(-30, 1000) elbow_motor.run(15) while elbow_sensor.reflection() < 32: wait(10) elbow_motor.reset_angle(0) elbow_motor.hold() # Initialize the base. First rotate it until the Touch Sensor # in the base is pressed. Reset the motor angle to make this # the zero point. Then hold the motor in place so it does not move. base_motor.run(-60) while not base_switch.pressed(): wait(10) base_motor.reset_angle(0) base_motor.hold()