def main(): #UARTtest() x_motor = Motor(Port.C) y_motor = Motor(Port.D) speed = 0 y_ang = 0 x_ang = 0 x_spd = 0 y_spd = 0 isTurnLeft= False isTurnRight= False light_value = 45 x_motor.reset_angle(0) y_motor.reset_angle(0) counter = 0 lightVal = '' while True: counter = counter + 1 anglestring, x_ang, y_ang = MotorAngles(x_motor,y_motor) uart.write(anglestring) #get light value from other ev3 wait(10) data = uart.read() data = data.decode('utf-8') #print("This is DATA: ", data) #print(type(data)) if (data is not '0') and (data is not '1'): data = '100' lightVal = int(data) print("Light Value is: ", lightVal) print(type(lightVal)) #lightVal = 1 if lightVal is 1: #print("IS BRAKING") #ev3.speaker.say("SHARK") start = time.time() if int(x_ang) > 0: x_motor.run(1000) if int(x_ang) < 0: x_motor.run(-1000) if int(y_ang) >0: y_motor.run(1000) if int(y_ang) < 0: y_motor.run(1000) wait(50) print( time.time() - start , " seconds") x_motor.stop() y_motor.stop() #x_motor.run_angle(100,10) #y_motor.run_angle(100,10) anglestring, x_ang, y_ang = MotorAngles(x_motor,y_motor) uart.write(anglestring)
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)
def kalibriere(self): headmotor = Motor(Port.A, Direction.COUNTERCLOCKWISE) farbsensor = ColorSensor(Port.S3) headmotor.run_until_stalled(speed=10, duty_limit=50) debug('winkel=' + str(headmotor.angle())) headmotor.run_target(speed=10, target_angle=-120, wait=False) while (farbsensor.reflection() < 10): # & (headmotor.speed() != 0): debug('farbwert=' + str(farbsensor.reflection())) time.sleep(0.1) headmotor.stop() headmotor.run_angle(speed=10, rotation_angle=15) debug(str(farbsensor.reflection())) # winkel auf 0 headmotor.reset_angle(0) self.angle_ist = 0 self._schreibe_winkel()
class SmallMotor: def __init__(self, ev3, port): self.ev3 = ev3 self.motor = Motor(port, Direction.COUNTERCLOCKWISE) self.motor.reset_angle(0) def reset(self): self.motor.run_until_stalled(100) self.motor.run_angle(800, -300) self.motor.reset_angle(0) def moveTo(self, angle, speed = 800, wait = False): print(self.motor.angle()) self.motor.run_target(speed, angle, Stop.HOLD, wait) print(self.motor.angle()) def move(self, speed = 20): self.motor.run(speed) def brake(self): self.motor.brake()
class SpikeManager: def __init__(self): # Initialize all devices self.ev3 = EV3Brick() self.usb_motor = Motor(Port.D) self.bt_motor = Motor(Port.C) self.left_button_motor = Motor(Port.B) self.right_button_motor = Motor(Port.A) # Reset all motor to mechanical stop self.usb_motor.run_until_stalled(-SPEED, duty_limit=50) self.bt_motor.run_until_stalled(-SPEED, duty_limit=20) self.left_button_motor.run_until_stalled(-SPEED, duty_limit=100) self.right_button_motor.run_until_stalled(SPEED, duty_limit=30) wait(500) # Reset the angles self.usb_motor.reset_angle(10) self.bt_motor.reset_angle(-20) self.left_button_motor.reset_angle(-25) self.right_button_motor.reset_angle(20) # Go to neutral position self.reset() def reset(self): self.usb_motor.run_target(SPEED, 0) self.bt_motor.run_target(SPEED, 0) self.left_button_motor.run_target(SPEED, 0) self.right_button_motor.run_target(SPEED, 0) def insert_usb(self): self.usb_motor.run_target(SPEED, 70, then=Stop.COAST) def remove_usb(self): self.usb_motor.run_target(SPEED, 0, then=Stop.COAST) def activate_dfu(self): self.bt_motor.dc(-40) wait(600) self.insert_usb() wait(8000) self.bt_motor.run_target(SPEED, 0) def shutdown(self): self.left_button_motor.run_target(SPEED, 20) wait(4000) self.left_button_motor.run_target(SPEED, 0)
def init_brick(): # Create your objects here. ev3 = EV3Brick() # Initilize our motors left_motor = Motor(Port.A) right_motor = Motor(Port.D) front_motor_1 = Motor(Port.C) front_motor_2 = Motor(Port.B) left_motor.reset_angle(0) right_motor.reset_angle(0) front_motor_1.reset_angle(0) front_motor_2.reset_angle(0) # Initialize the color sensor. left_sensor = ColorSensor(Port.S4) right_sensor = ColorSensor(Port.S1) # Speeds right_sensor = ColorSensor(Port.S1) left_sensor = ColorSensor(Port.S4) ARM_MOTOR_SPEED = 400 WHEEL_DIAMETER = 92 AXLE_TRACK = 130 DRIVE_SPEED_FAST = 350 DRIVE_SPEED_NORMAL = 200 DRIVE_SPEED_SLOW = 100 DRIVE_EXTRA_SLOW = 30 CIRCUMFERENCE = 3.14 * WHEEL_DIAMETER # Diameter = 100mm, Circumference = 314.10mm = 1 rotation # Initialize the Gyro sensor gyro = GyroSensor(Port.S2) gyro.reset_angle(0) # All parameters are in millimeters robot = DriveBase(left_motor, right_motor, wheel_diameter=config.WHEEL_DIAMETER, axle_track=config.AXLE_TRACK) # Set the straight speed and turn rate robot.settings(straight_speed=config.DRIVE_SPEED_NORMAL, turn_rate=config.TURN_RATE)
class MbMotor(): """ Control a motor, besides the fact that you can detect if a motor got stalled the main reason for this class is to solve a bug for pybricks.ev3devices.Motor. The bug is that when you set the motor to move in a Direction.COUNTERCLOCKWISE sometimes it failes to detect it. This class is made on top of pybricks.ev3devices.Motor Args: port (Port): The port of the device clockwise_direction (bool): Sets the defualt movement of the motor clockwise or counterclockwise, True for clockwise else counterclockwise exit_exec (Function): Function that returns True or False, the motor will stop if returns True """ def __init__(self, port, clockwise_direction=True, exit_exec=lambda: False): self.core = Motor(port) self.port = port self.direction = 1 if clockwise_direction else -1 self.exit_exec = exit_exec def angle(self): """ Get the distance the robot has moved in degrees Returns: angle (int): The distance the robot has moved in degrees """ return self.core.angle() * self.direction def speed(self): """ Get the speed of the motor Returns: speed (int): The current speed of the motor """ return self.core.speed() * self.direction def stalled(self, min_speed=0): if abs(self.speed()) <= abs(min_speed): return True return False def run_angle(self, speed, angle, wait=True, detect_stall=False): """ Run the motor to a specific angle Args: speed (int): The speed of the motor angle (int): Degrees to run the motor at wait (bool): Sets if the robot is going to stop for the motor to complete this method or not """ def exec(self, speed, angle): moved_enough = False self.reset_angle() self.run(speed) while True: if abs(self.angle()) > 50: moved_enough = True if moved_enough and detect_stall: if self.stalled(): break if abs(self.angle()) > abs(angle) or self.exit_exec(): break self.hold() if wait: exec(self, speed, angle) else: threading.Thread(target=exec, args=[self, speed, angle]).start() def run_time(self, speed, msec, wait=True): """ Run the motor to a amount of time Args: speed (int): The speed of the motor msec (int): Time to move the robot wait (bool): Sets if the robot is going to stop for the motor to complete this method or not """ def exec(self, speed, msec): self.reset_angle() self.run(speed) s = time() while True: if round(time() - s, 2) * 1000 >= abs(msec) or self.exit_exec(): break self.hold() if wait: exec(self, speed, msec) else: threading.Thread(target=exec, args=[self, speed, msec]).start() def run(self, speed): """ Run the motor to a constant speed Args: speed (int): Speed to run at Note: speed parameter should be between -800 and 800 """ self.core.run(speed * self.direction) def dc(self, speed): """ Run the motor to a constant speed Args: speed (int): Speed to run at Note: speed parameter should be between -100 and 100 """ self.core.dc(speed * self.direction) def hold(self): """ Stop the motor and hold its position """ self.core.hold() def brake(self): """ Passively stop the motor """ self.core.brake() def stop(self): """ No current is being aplied to the robot, so its gonna stop due to friction """ self.core.stop() def reset_angle(self, angle=0): """ Set the motor angle Args: angle (int): Angle to set the motor at """ self.core.reset_angle(angle) def is_stalled(self, min_speed=0): """ Check if the motor got stalled Args: min_speed (int): The minim speed the motor should be moving at """ if abs(self.speed()) <= abs(min_speed): return True return False def __repr__(self): return "Motor Properties:\nPort: " + str( self.port) + "\nDefault Direction: " + str(self.direction)
STARTUP = 1000 # pause (ms) at start DISTANCE_SAFE = 200 # distance (mm) to stop or reverse the Train DEBOUNCE = 125 # wait this time (ms) after each button is pressed (empyrical) WAIT_TRAIN = 50 # wait for Train (4DBrix) to receive command (empyrical) INITSpeed = 320 # initial speed of our Train (you choose) MAXSpeed = 1023 # maximum speed accepted by 4DBrix WiFi Controller MOTORSpeed = 1024 # speed to use with EV3 motor (360 = 1 turn/sec) TOLERANCE = 4 # acceptable tolerance when reading motor position SETTLE = 250 # time (ticks) for the user to change motor position before # considering it done (empyrical) us = UltrasonicSensor(Port.S1) m = Motor(Port.A) m.reset_angle(0) print('Motor Reset') # motor will be used to read speed so defining scale SCALE = round(360 / MAXSpeed, 2) m.run_target(MOTORSpeed, round(INITSpeed * SCALE), Stop.COAST) # show initial speed # Possible hostnames - use your own RIGHTMOST = 'iota' LEFTMOST = 'alpha' # get hostname to use as MQTT_ClientID and decide roles # LEFTMOST should be at LEFT or F extreme # RIGHTMOST should be at RIGHT or B extreme os.system('hostname > /dev/shm/hostname.txt')
Building instructions can be found at: https://education.lego.com/en-us/support/mindstorms-ev3/building-instructions#robot """ from pybricks.ev3devices import Motor, ColorSensor, GyroSensor from pybricks.parameters import Port , Direction from pybricks.tools import wait from pybricks.robotics import DriveBase import Dimensions # Initialize the motors. left_motor = Motor(Port.B , positive_direction=Direction.COUNTERCLOCKWISE, gears=[40,8]) right_motor = Motor(Port.C , positive_direction=Direction.COUNTERCLOCKWISE, gears=[40,8]) gyro_sensor = GyroSensor(Port.S3) # Initialize the color sensor. #line_sensor = ColorSensor(Port.S3) left_motor.reset_angle(0) right_motor.reset_angle(0) gyro_sensor.reset_angle(0) fudge=1 speed=100 angle=0 robot = DriveBase(left_motor, right_motor, wheel_diameter=30, axle_track=135) initial_distance = 0 robot.reset() while ((robot.distance() - initial_distance) < 350) : robot.drive(speed,angle) drift = gyro_sensor.angle() angle = (drift * fudge) * -1
# controlls the manual sound changes on button presses def manualSoundControl(): global sound, manualSound if sound == False: if Button.LEFT_UP in infraredSensor.buttons(2): switchSound() else: if Button.LEFT_DOWN in infraredSensor.buttons(2): switchSound() if Button.RIGHT_DOWN in infraredSensor.buttons(2): manualSound = False # system setup ev3.speaker.set_volume(100, which='_all_') motor.reset_angle(20) soundMotor.reset_angle(0) motor.run_target(500, 75, wait=True) ev3.light.on(Color.GREEN) watch.reset() # main project loop while shutdown == False: ''' finishing the progamm ''' if Button.LEFT_UP in infraredSensor.buttons(4): shutdown = True ''' checking touch sensor ''' if touchSensor.pressed() == True: if manualLight == False and manualSound == False:
from pybricks.tools import print, wait, StopWatch # from hub import print, wait_for_seconds, StopWatch from pybricks.robotics import DriveBase import urequests ev3 = EV3Brick() # Connect motor to port A and touch sensor to port S1 pointer=Motor(Port.A) # pointer = Motor('A') touch=TouchSensor(Port.S1) #set the arrow to blue bar (minimum) to begin with pointer.reset_angle(0) # defining the maximum and minimum temperatures shown by the dashboard # You can change the minimum and maximum temperatures based on your location. # Calculate where you should place the green (comfortable temperature) # and yellow (slightly uncomfortable temperature) bars on your design? blue_temp = 0 # minimum temperature in celsius red_temp = 40 # maximum temperature in celsius # Angle between red and blue bar. 180 degrees in our case. # It will be based on your gauge design. angle_bw_blueandred = 180 # Get the API key from openweathermap.org and replace the text YOUR_API_KEY with the key # don't remove the quotes
class MyRobot: def __init__(self, ev3, leftMotorPort, rightMotorPort, leftColorSensorPort, rightColorSensorPort): self.ev3 = ev3 self.leftMotor = Motor(leftMotorPort) self.rightMotor = Motor(rightMotorPort) self.rightMotor.control.limits(800, 500, 100) self.leftMotor.control.limits(800, 500, 100) if (leftColorSensorPort != None): self.leftColorSensor = RGBColor(leftColorSensorPort) print(self.leftColorSensor.getReflection()) if (rightColorSensorPort != None): self.rightColorSensor = RGBColor(rightColorSensorPort) print(self.rightColorSensor.getReflection()) ev3.speaker.set_speech_options('hu', 'f2', 200) def beep(self, hangmagassag=600, duration=100): self.ev3.speaker.beep(frequency=hangmagassag, duration=duration) def forwardAndStop(self, speed, angle): self.leftMotor.run_angle(speed, angle, Stop.HOLD, False) self.rightMotor.run_angle(speed, angle, Stop.HOLD, True) def forward(self, speed, angle): leftAngle = self.leftMotor.angle() rightAngle = self.rightMotor.angle() self.leftMotor.run(speed) self.rightMotor.run(speed) if (speed > 0): while (((self.leftMotor.angle() - leftAngle) + (self.rightMotor.angle() - rightAngle)) / 2 < angle): pass else: while (((leftAngle - self.leftMotor.angle()) + (rightAngle - self.rightMotor.angle())) / 2 < angle): pass def brake(self): self.leftMotor.brake() self.rightMotor.brake() def leftAngle(self): return self.leftMotor.angle() def rightAngle(self): return self.rightMotor.angle() def resetAngle(self): self.leftMotor.reset_angle(0) self.rightMotor.reset_angle(0) def turnLeft(self, speed): self.leftMotor.run_angle(speed, -148, Stop.HOLD, False) self.rightMotor.run_angle(speed, 148, Stop.HOLD, True) def turnRight(self, speed): self.leftMotor.run_angle(speed, 148, Stop.HOLD, False) self.rightMotor.run_angle(speed, -148, Stop.HOLD, True) def turnLeftWithRightMotor(self, speed): self.rightMotor.run_angle(speed, 296, Stop.HOLD, True) def turnLeftWithLeftMotor(self, speed): self.leftMotor.run_angle(speed, -296, Stop.HOLD, True) def turnRightWithRightMotor(self, speed): self.rightMotor.run_angle(speed, -296, Stop.HOLD, True) def turnRightWithLeftMotor(self, speed): self.leftMotor.run_angle(speed, 296, Stop.HOLD, True) def forwardWhile(self, speed, leftMotorConditionFunc, rightMotorConditionFunc): self.leftMotor.run(speed) self.rightMotor.run(speed) while (leftMotorConditionFunc() and rightMotorConditionFunc()): pass if (not leftMotorConditionFunc()): self.leftMotor.brake() while (rightMotorConditionFunc()): pass self.rightMotor.brake() else: self.rightMotor.brake() while (leftMotorConditionFunc()): pass self.leftMotor.brake() def say(self, text): return Thread(target=self.ev3.speaker.say(text)) def alignToWhite(self, speed, whiteThreshold): self.leftMotor.run(speed) self.rightMotor.run(speed) time.sleep(0.1) while (self.leftMotor.speed() != 0 or self.rightMotor.speed() != 0): if (self.leftColorSensor.getReflection() > whiteThreshold): self.leftMotor.brake() if (self.rightColorSensor.getReflection() > whiteThreshold): self.rightMotor.brake() def alignToBlack(self, speed, blackThreshold): self.leftMotor.run(speed) self.rightMotor.run(speed) time.sleep(0.1) while (self.leftMotor.speed() != 0 or self.rightMotor.speed() != 0): if (self.leftColorSensor.getReflection() < blackThreshold): self.leftMotor.brake() if (self.rightColorSensor.getReflection() < blackThreshold): self.rightMotor.brake() def alignToNotWhite(self, speed, whiteThreshold): self.leftMotor.run(speed) self.rightMotor.run(speed) time.sleep(0.1) while (self.leftMotor.speed() != 0 or self.rightMotor.speed() != 0): leftReflection = self.leftColorSensor.getReflection() rightReflection = self.rightColorSensor.getReflection() if (leftReflection < whiteThreshold): self.leftMotor.brake() if (rightReflection < whiteThreshold): self.rightMotor.brake() # print("r = {0}, l = {1}".format(rightReflection, leftReflection)) def measureColorSensors(self): while Button.CENTER not in self.ev3.buttons.pressed(): print('left reflection: {0}, right reflection: {1}'.format( self.leftColorSensor.getReflection(), self.rightColorSensor.getReflection())) time.sleep(0.2)
#Get the deciding value while Button.LEFT not in brick.buttons(): wait(1) white = color_sensor.reflection() brick.sound.beep() while Button.RIGHT not in brick.buttons(): wait(1) black = color_sensor.reflection() brick.sound.beep() deciding_value = (white + black)/2 print("Deciding value = %s, white = %s. black = %s" % (deciding_value, white, black)) while True: if color_sensor.reflection() < deciding_value: #Checks to see if the robot is on line brick.display.text("%s Sensed line" % color_sensor.reflection()) print("%s Sensed line" % color_sensor.reflection()) moving_motor.reset_angle(0) print("reset angle") moving_motor.run_target(500, -90) #Moves robot forward print("moved forward") else: brick.display.text("%s Nothing sensed, searching." % color_sensor.reflection()) incrament = 2 a = incrament b = 1 while color_sensor.reflection() > deciding_value: rotating_motor.run_target(500,a*b) a = a + incrament b = - b print("searching") print("end of else") print("end of while")
class Puppy: # These constants are used for positioning the legs. HALF_UP_ANGLE = 25 STAND_UP_ANGLE = 65 STRETCH_ANGLE = 125 # These constants are for positioning the head. HEAD_UP_ANGLE = 0 HEAD_DOWN_ANGLE = -40 # These constants are for the eyes. #replaced HURT, HEART, SQUINTY with AWAKE,DIZZY,PINCHED_MIDDLE respectively NEUTRAL_EYES = Image(ImageFile.NEUTRAL) TIRED_EYES = Image(ImageFile.TIRED_MIDDLE) TIRED_LEFT_EYES = Image(ImageFile.TIRED_LEFT) TIRED_RIGHT_EYES = Image(ImageFile.TIRED_RIGHT) SLEEPING_EYES = Image(ImageFile.SLEEPING) HURT_EYES = Image(ImageFile.AWAKE) ANGRY_EYES = Image(ImageFile.ANGRY) HEART_EYES = Image(ImageFile.DIZZY) SQUINTY_EYES = Image(ImageFile.PINCHED_MIDDLE) def __init__(self): # Initialize the EV3 brick. self.ev3 = EV3Brick() # Initialize the motors connected to the back legs. self.left_leg_motor = Motor(Port.D, Direction.COUNTERCLOCKWISE) self.right_leg_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE) # Initialize the motor connected to the head. # Worm gear moves 1 tooth per rotation. It is interfaced to a 24-tooth # gear. The 24-tooth gear is connected to parallel 12-tooth gears via # an axle. The 12-tooth gears interface with 36-tooth gears. self.head_motor = Motor(Port.C, Direction.COUNTERCLOCKWISE, gears=[[1, 24], [12, 36]]) # Initialize the Color Sensor. self.color_sensor = ColorSensor(Port.S4) # Initialize the touch sensor. self.touch_sensor = TouchSensor(Port.S1) # This attribute is used by properties. self._eyes = None # These attributes are used by the playful behavior. self.playful_timer = StopWatch() self.playful_bark_interval = None def adjust_head(self): """Use the up and down buttons on the EV3 brick to adjust the puppy's head up or down. """ self.ev3.screen.show_image(ImageFile.EV3_ICON) self.ev3.light.on(Color.ORANGE) while True: buttons = self.ev3.buttons.pressed() if Button.CENTER in buttons: break elif Button.UP in buttons: self.head_motor.run(20) elif Button.DOWN in buttons: self.head_motor.run(-20) else: self.head_motor.stop() wait(100) self.head_motor.stop() self.head_motor.reset_angle(0) self.ev3.light.on(Color.GREEN) def move_head(self, target): """Move the head to the target angle. Arguments: target (int): The target angle in degrees. 0 is the starting position, negative values are below this point and positive values are above this point. """ self.head_motor.run_target(20, target) def reset(self): # must be called when puppy is sitting down. self.left_leg_motor.reset_angle(0) self.right_leg_motor.reset_angle(0) self.behavior = self.idle # The next 10 methods define the 10 behaviors of the puppy. def idle(self): """The puppy is idle.""" self.stand_up() self.eyes = self.NEUTRAL_EYES def go_to_sleep(self): """Makes the puppy go to sleep. Press the center button and touch sensor at the same time to awaken the puppy.""" self.eyes = self.TIRED_EYES self.sit_down() self.move_head(self.HEAD_DOWN_ANGLE) self.eyes = self.SLEEPING_EYES self.ev3.speaker.play_file(SoundFile.SNORING) if self.touch_sensor.pressed( ) and Button.CENTER in self.ev3.buttons.pressed(): self.behavior = self.wake_up def wake_up(self): """Makes the puppy wake up.""" self.eyes = self.TIRED_EYES self.ev3.speaker.play_file(SoundFile.DOG_WHINE) self.move_head(self.HEAD_UP_ANGLE) self.sit_down() self.stretch() wait(1000) self.stand_up() self.behavior = self.idle def act_playful(self): """Makes the puppy act playful.""" self.eyes = self.NEUTRAL_EYES self.stand_up() self.playful_bark_interval = 0 if self.playful_timer.time() > self.playful_bark_interval: self.ev3.speaker.play_file(SoundFile.DOG_BARK_2) self.playful_timer.reset() self.playful_bark_interval = randint(4, 8) * 1000 def act_angry(self): """Makes the puppy act angry.""" self.eyes = self.ANGRY_EYES self.ev3.speaker.play_file(SoundFile.DOG_GROWL) self.stand_up() wait(1500) self.ev3.speaker.play_file(SoundFile.DOG_BARK_1) def act_hungry(self): """Makes the puppy act hungry.""" self.eyes = self.HURT_EYES self.sit_down() self.ev3.speaker.play_file(SoundFile.DOG_WHINE) def go_to_bathroom(self): """Makes the puppy go to the bathroom.""" self.eyes = self.SQUINTY_EYES self.stand_up() wait(100) self.right_leg_motor.run_target(100, self.STRETCH_ANGLE) wait(800) self.ev3.speaker.play_file(SoundFile.HORN_1) wait(1000) for _ in range(3): self.right_leg_motor.run_angle(100, 20) self.right_leg_motor.run_angle(100, -20) self.right_leg_motor.run_target(100, self.STAND_UP_ANGLE) self.behavior = self.idle def act_happy(self): """Makes the puppy act happy.""" self.eyes = self.HEART_EYES # self.move_head(self.?) self.sit_down() for _ in range(3): self.ev3.speaker.play_file(SoundFile.DOG_BARK_1) self.hop() wait(500) self.sit_down() self.reset() def sit_down(self): """Makes the puppy sit down.""" self.left_leg_motor.run(-50) self.right_leg_motor.run(-50) wait(1000) self.left_leg_motor.stop() self.right_leg_motor.stop() wait(100) def walk_steps(self): """Makes the puppy walk a certain number of steps. Modify front wheels to roll by removing anchoring pegs and switching pegs through the axle to non-friction pegs. Change steps to adjuct the number of steps.""" #steps equals number of steps pup takes steps = 10 self.stand_up() for value in range(1, steps + 1): self.left_leg_motor.run_target(-100, 25, wait=False) self.right_leg_motor.run_target(-100, 25) while not self.left_leg_motor.control.target_tolerances(): wait(200) self.left_leg_motor.run_target(100, 65, wait=False) self.right_leg_motor.run_target(100, 65) while not self.left_leg_motor.control.target_tolerances(): wait(200) self.left_leg_motor.run_target(50, 65, wait=False) self.right_leg_motor.run_target(50, 65) wait(100) def walk_timed(self): """Makes the puppy walk a certain time in ms. Modify front wheels to roll by removing anchoring pegs and switching pegs through the axle to non-friction pegs. Change walk_time to adjust the time the puppy walks in ms.""" #walk_time equals desired walk time in ms walk_time = 6000 elapsed_time = StopWatch() while elapsed_time.time() < walk_time: self.left_leg_motor.run_target(-100, 25, wait=False) self.right_leg_motor.run_target(-100, 25) while not self.left_leg_motor.control.target_tolerances(): wait(200) self.left_leg_motor.run_target(100, 65, wait=False) self.right_leg_motor.run_target(100, 65) while not self.left_leg_motor.control.target_tolerances(): wait(200) self.left_leg_motor.run_target(50, 65, wait=False) self.right_leg_motor.run_target(50, 65) wait(100) elapsed_time.reset() # The next 4 methods define actions that are used to make some parts of # the behaviors above. def stand_up(self): """Makes the puppy stand up.""" self.left_leg_motor.run_target(100, self.HALF_UP_ANGLE, wait=False) self.right_leg_motor.run_target(100, self.HALF_UP_ANGLE) while not self.left_leg_motor.control.target_tolerances(): wait(100) self.left_leg_motor.run_target(50, self.STAND_UP_ANGLE, wait=False) self.right_leg_motor.run_target(50, self.STAND_UP_ANGLE) while not self.left_leg_motor.control.target_tolerances(): wait(100) wait(500) def stretch(self): """Makes the puppy stretch its legs backwards.""" self.stand_up() self.left_leg_motor.run_target(100, self.STRETCH_ANGLE, wait=False) self.right_leg_motor.run_target(100, self.STRETCH_ANGLE) self.ev3.speaker.play_file(SoundFile.DOG_WHINE) self.left_leg_motor.run_target(100, self.STAND_UP_ANGLE, wait=False) self.right_leg_motor.run_target(100, self.STAND_UP_ANGLE) wait(500) def hop(self): """Makes the puppy hop.""" self.left_leg_motor.run(500) self.right_leg_motor.run(500) wait(275) self.left_leg_motor.stop() self.right_leg_motor.stop() wait(275) self.left_leg_motor.run(-50) self.right_leg_motor.run(-50) wait(275) self.left_leg_motor.stop() self.right_leg_motor.stop() @property def eyes(self): """Gets and sets the eyes.""" return self._eyes @eyes.setter def eyes(self, value): if value != self._eyes: self._eyes = value self.ev3.screen.show_image(value) def run(self): """This is the main program run loop.""" self.sit_down() self.adjust_head() self.eyes = self.SLEEPING_EYES self.reset() #self.eyes = self.SLEEPING_EYES """The following code cycles through all of the behaviors, separated by beeps.""" self.act_playful() wait(1000) self.ev3.speaker.beep() self.act_happy() wait(1000) self.ev3.speaker.beep() self.act_hungry() wait(1000) self.ev3.speaker.beep() self.act_angry() wait(1000) self.ev3.speaker.beep() self.go_to_bathroom() wait(1000) self.ev3.speaker.beep() self.go_to_sleep() wait(1000) self.ev3.speaker.beep() self.wake_up() wait(1000) self.ev3.speaker.beep() self.walk_steps() wait(1000) self.ev3.speaker.beep() self.walk_timed() wait(1000) self.ev3.speaker.beep() self.idle() wait(1000) self.ev3.speaker.beep()
from pybricks.parameters import Port, Stop, Direction, Button, Color from pybricks.tools import wait, StopWatch, DataLog from pybricks.robotics import DriveBase from pybricks.media.ev3dev import SoundFile, ImageFile from time import sleep # Create your objects here. ev3 = EV3Brick() # Initilize our motors left_motor = Motor(Port.A) right_motor = Motor(Port.D) front_motor_1 = Motor(Port.C) front_motor_2 = Motor(Port.B) left_motor.reset_angle(0) right_motor.reset_angle(0) front_motor_1.reset_angle(0) front_motor_2.reset_angle(0) # Initialize the color sensor. left_sensor = ColorSensor(Port.S4) right_sensor = ColorSensor(Port.S1) # Initialize the Gyro sensor gyro = GyroSensor(Port.S2) gyro.reset_angle(0) # All parameters are in millimeters robot = DriveBase(left_motor, right_motor,
while motor_avarge()>=-450: PID(-200,0,1,1,1) stop1() robot.stop() reset_all() while True: PID(-500,-200,1,1,1) stop1() elif Button.UP in brick.buttons(): while not Button.CENTER in brick.buttons(): reset_all() while motor_avarge()<=780: PID(150,0,8,1,1) stop1() robot.stop() left_M.reset_angle(0) right_M.reset_angle(0) while motor_avarge()<=470: followline(100,1.2,1,1) stop1() robot.stop() time.sleep(0.1) first_gyro.reset_angle(0) second_gyro.reset_angle(0) while first_gyro.angle()<=25: robot.drive(10,-100) stop1() robot.stop() reset_all() while motor_avarge()<=1000: PID(160,0,8,1,1)
from pybricks.robotics import DriveBase import struct # Initialize motors and sensors rotate_motor = Motor(Port.A) tilt_motor = Motor(Port.B) radar_motor = Motor(Port.C) antenna_motor = Motor(Port.D) vscale = 1 radar = 0 antenna = 0 antenna_c = 0 rotate = 0 tilt = 0 rotate_motor.reset_angle(0) tilt_motor.reset_angle(0) #obstacle_sensor = UltrasonicSensor(Port.S4) #color_sensor = ColorSensor(Port.1) # fLASH SOME LIGHTS brick.light(Color.BLACK) wait(200) brick.light(Color.GREEN) wait(200) brick.light(Color.ORANGE) wait(200) brick.light(Color.RED) wait(200) brick.light(Color.YELLOW) wait(200)
class Puppy: # Constants for leg angle HALF_UP_ANGLE = 25 STAND_UP_ANGLE = 65 STRETCH_ANGLE = 125 # Loads the different eyes HEART_EYES = Image(ImageFile.LOVE) SQUINTY_EYES = Image(ImageFile.TEAR) def __init__(self): # Sets up the brick self.ev3 = EV3Brick() # Identifies which motor is connected to which ports self.left_leg_motor = Motor(Port.D, Direction.COUNTERCLOCKWISE) self.right_leg_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE) # Sets up the gear ratio (automatically translates it to the correct angle) self.head_motor = Motor(Port.C, Direction.COUNTERCLOCKWISE, gears=[[1, 24], [12, 36]]) # Sets up touch sensor self.touch_sensor = TouchSensor(Port.S1) # Sets up constants for the eye self.eyes_timer_1 = StopWatch() self.eyes_timer_1_end = 0 self.eyes_timer_2 = StopWatch() self.eyes_timer_2_end = 0 self.eyes_closed = False def movements(self): self.ev3.screen.load_image(ImageFile.EV3_ICON) self.ev3.light.on(Color.ORANGE) dog_pat = 0 # Movement interactions while True: buttons = self.ev3.buttons.pressed() if Button.CENTER in buttons: break elif Button.UP in buttons: self.head_motor.run(20) elif Button.DOWN in buttons: self.head_motor.run(-20) elif self.touch_sensor.pressed(): self.ev3.speaker.play_file(SoundFile.DOG_BARK_1) self.eyes = self.HEART_EYES self.sit_down() dog_pat += 1 print(dog_pat) elif dog_pat == 3: self.go_to_bathroom() dog_pat -= 3 print(dog_pat) else: self.head_motor.stop() wait(100) self.head_motor.stop() self.head_motor.reset_angle(0) self.ev3.light.on(Color.GREEN) # Below this line I honestly have no clue how it works. It came from the boiler plate of functions def move_head(self, target): self.head_motor.run_target(20, target) @property def eyes(self): return self._eyes @eyes.setter def eyes(self, value): if value != self._eyes: self._eyes = value self.ev3.screen.load_image(value) def update_eyes(self): if self.eyes_timer_1.time() > self.eyes_timer_1_end: self.eyes_timer_1.reset() if self.eyes == self.SLEEPING_EYES: self.eyes_timer_1_end = urandom.randint(1, 5) * 1000 self.eyes = self.TIRED_RIGHT_EYES else: self.eyes_timer_1_end = 250 self.eyes = self.SLEEPING_EYES if self.eyes_timer_2.time() > self.eyes_timer_2_end: self.eyes_timer_2.reset() if self.eyes != self.SLEEPING_EYES: self.eyes_timer_2_end = urandom.randint(1, 10) * 1000 if self.eyes != self.TIRED_LEFT_EYES: self.eyes = self.TIRED_LEFT_EYES else: self.eyes = self.TIRED_RIGHT_EYES def stand_up(self): self.left_leg_motor.run_target(100, self.HALF_UP_ANGLE, wait=False) self.right_leg_motor.run_target(100, self.HALF_UP_ANGLE) while not self.left_leg_motor.control.done(): wait(100) self.left_leg_motor.run_target(50, self.STAND_UP_ANGLE, wait=False) self.right_leg_motor.run_target(50, self.STAND_UP_ANGLE) while not self.left_leg_motor.control.done(): wait(100) wait(500) def sit_down(self): self.left_leg_motor.run(-50) self.right_leg_motor.run(-50) wait(1000) self.left_leg_motor.stop() self.right_leg_motor.stop() wait(100) def go_to_bathroom(self): self.eyes = self.SQUINTY_EYES self.stand_up() wait(100) self.right_leg_motor.run_target(100, self.STRETCH_ANGLE) wait(800) self.ev3.speaker.play_file(SoundFile.HORN_1) wait(1000) for _ in range(3): self.right_leg_motor.run_angle(100, 20) self.right_leg_motor.run_angle(100, -20) self.right_leg_motor.run_target(100, self.STAND_UP_ANGLE) def run(self): self.movements() self.eyes = self.SLEEPING_EYES
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)
from pybricks.tools import wait, StopWatch, DataLog from pybricks.robotics import DriveBase from pybricks.media.ev3dev import SoundFile, ImageFile esquerda = Motor(Port.B, Direction.COUNTERCLOCKWISE) direita = Motor(Port.C, Direction.COUNTERCLOCKWISE) MotorMA = Motor(Port.A) MotorMD = Motor(Port.D) # EsqCor = ColorSensor(Port.S1) # DirCor = ColorSensor(Port.S4) gabriel = DriveBase(esquerda, direita, wheel_diameter=100, axle_track=166.2) #Ajustar valores ev3 = EV3Brick() while True: if Button.LEFT in ev3.buttons.pressed(): MotorMA.run(-400) if Button.RIGHT in ev3.buttons.pressed(): MotorMA.run(400) if Button.DOWN in ev3.buttons.pressed(): MotorMD.run(-400) if Button.UP in ev3.buttons.pressed(): MotorMD.run(400) if ev3.buttons.pressed() == []: MotorMD.stop() MotorMA.stop() if Button.CENTER in ev3.buttons.pressed(): MotorMD.reset_angle(0) MotorMA.reset_angle(0)
turn_motor = Motor(Port.C, Direction.COUNTERCLOCKWISE, [12,36]) extend_motor = Motor(Port.B, Direction.CLOCKWISE, [8,48]) grip_motor = Motor(Port.A, Direction.CLOCKWISE, [12,8]) turn_sensor = TouchSensor(Port.S1) extend_sensor = TouchSensor(Port.S2) brick.sound.beep() brick.light(Color.GREEN) #turn_motor.run_time(255,5000,Stop.BRAKE,True) turn_motor.run_until_stalled(255, Stop.COAST, 50) brick.sound.file(SoundFile.TWO) s.send(bytes('two\n', 'utf-8')) turn_motor.reset_angle(-90) turn_home_found = False while not turn_home_found: turn_motor.run_until_stalled(-255,Stop.COAST,50) if turn_sensor.pressed() == True: turn_home_found = True brick.sound.file(SoundFile.THREE) s.send(bytes('three\n', 'utf-8')) break turn_motor.reset_angle(0) while True:
import utils_motor # Play a beep sound brick.sound.beep() print('Should display on VisualStudio') # Clear the display brick.display.clear() brick.display.text("Hello", (0, 20)) # Initialize a motors and reset their angles base_motor = Motor(Port.C) leg_motor = Motor(Port.A) infrared = InfraredSensor(Port.S1) base_motor.reset_angle(0.0) leg_motor.reset_angle(0.0) step_angle = 10 print('Hello Robot') while True: # Get current distance distance = infrared.distance() # Get current angles angle_base, angle_leg = utils_motor.get_curr_angle(base_motor, leg_motor) print('Angle base:', angle_base) print('Angle leg:', angle_leg) print('Distance sensor:', distance) # Move arm/leg depending on the button pressed if Button.UP in brick.buttons():
# 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() # Initialize the gripper. First rotate the motor until it stalls. # Stalling means that it cannot move any further. This position # corresponds to the closed position. Then rotate the motor # by 90 degrees such that the gripper is open.
# motor moves the robot forward while the lift motor moves the rear # structure down for a set amount of degrees to move to its starting # position. Finally, the lift motor resets the angle to "0." This # means that when it moves to "0" later on, it returns to this starting # position. rear_motor.dc(-20) lift_motor.dc(100) while not touch_sensor.pressed(): wait(10) lift_motor.dc(-100) rear_motor.dc(40) wait(50) lift_motor.run_angle(-145, 510) rear_motor.hold() lift_motor.run_angle(-30, 44) lift_motor.reset_angle(0) gyro_sensor.reset_angle(0) # Initialize the steps variable to 0. steps = 0 # This loop checks the Brick Buttons to update and display the steps # variable. It repeats until the Center Button is pressed. while True: # Display the steps variable on the screen. ev3.screen.clear() ev3.screen.draw_text(70, 50, steps) wait(200) # Wait until any Brick Button is pressed. while not any(ev3.buttons.pressed()):
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()
print(e) result = 'failed' return result def Create_SL(Tag, Type): urlBase, headers = SL_setup() urlTag = urlBase + Tag propName = {"type": Type, "path": Tag} try: urequests.put(urlTag, headers=headers, json=propName).text except Exception as e: print(e) m_rot.reset_angle(0) m_elbow.reset_angle(0) m_hand.reset_angle(45) def grab(): m_hand.run_target(500, 0) def open_up(): m_hand.run_target(500, 45) def one_eighty(): grab() m_elbow.run_target(1000, 1200)
mB.set_run_settings(200, 250) # max speed, max accel mC.set_run_settings(200, 250) # max speed, max accel gy = GyroSensor(Port.S3) gy2 = GyroSensor(Port.S2) gy.mode='GYRO-RATE' # deliver turn-rate (must integrate for angle) gy2.mode='GYRO-RATE' # deliver turn-rate (must integrate for angle) sleep(0.5) gy.mode='GYRO-ANG' # changing modes causes recalibration gy2.mode='GYRO-ANG' # changing modes causes recalibration sleep(3) gy.reset_angle(0) gy2.reset_angle(0) mB.reset_angle(0) mC.reset_angle(0) angle = 0 # global var holding accumulated turn angle runB = False # whether Motor B should be running right now runC = False t = Thread(target=printAngle) tstart = watch.time() / 1000 t.start() # start angle monitor routine brick.sound.beep(400, 10) # initialization-complete sound # ==========================================
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): ...
# means that it cannot move any further. From this end point, the motor # rotates backward by 180 degrees. Then it is in the starting position. feed_motor.run_until_stalled(120, duty_limit=30) feed_motor.run_angle(450, -200) # Get the conveyor belt motor in the correct starting position. # This is done by first running the belt motor backward until the # touch sensor becomes pressed. Then the motor stops, and the the angle is # reset to zero. This means that when it rotates backward to zero later # on, it returns to this starting position. belt_motor.run(-500) while not touch_sensor.pressed(): pass belt_motor.stop() wait(1000) belt_motor.reset_angle(0) # When we scan the objects, we store all the color numbers in a list. # We start with an empty list. It will grow as we add colors to it. color_list = [] # This loop scans the colors of the objects. It repeats until 8 objects # are scanned and placed in the chute. This is done by repeating the loop # while the length of the list is still less than 8. while len(color_list) < 8: # Show an arrow that points to the color sensor. ev3.screen.load_image(ImageFile.RIGHT) # Show how many colored objects we have already scanned. ev3.screen.print(len(color_list))
def random_negate(): return [-1, 1][random.randrange(2)] def check_container_full(): return color_sensor_ramp.color() != calibration_ramp global last_direction_change last_direction_change = 0 # reset axes motor_arm.run_until_stalled(100, Stop.COAST, 30) motor_arm.reset_angle(0) motor_grabber.run_until_stalled(100, Stop.COAST, 30) motor_grabber.reset_angle(0) calibration_surface = color_sensor_floor.color() calibration_ramp = color_sensor_ramp.color() while ball_count < 4: global last_direction_change collision_avoidance() check_ball() if check_container_full(): break # run every 1s if watch.time() - last_direction_change > random_direction_change_interval: