class CuriosityRov3r(IRBeaconRemoteControlledTank): def __init__( self, left_motor_port: str = OUTPUT_B, right_motor_port: str = OUTPUT_C, medium_motor_port: str = OUTPUT_A, touch_sensor_port: str = INPUT_1, color_sensor_port: str = INPUT_3, ir_sensor_port: str = INPUT_4, ir_beacon_channel: int = 1): super().__init__( 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 = MediumMotor(address=medium_motor_port) self.touch_sensor = TouchSensor(address=touch_sensor_port) self.color_sensor = ColorSensor(address=color_sensor_port) self.ir_sensor = InfraredSensor(address=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel self.dis = Display() self.noise = Sound() def spin_fan(self, speed: float = 100): if self.color_sensor.reflected_light_intensity > 20: self.medium_motor.on( speed=speed, brake=False, block=False) else: self.medium_motor.off(brake=True) def say_when_touched(self): if self.touch_sensor.is_pressed: self.dis.image_filename( filename='/home/robot/image/Angry.bmp', clear_screen=True) self.dis.update() self.noise.play_file( wav_file='/home/robot/sound/No.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.medium_motor.on_for_seconds( speed=-50, seconds=3, brake=True, block=True) def main(self, speed: float = 100): while True: self.drive_once_by_ir_beacon(speed=speed) self.say_when_touched() self.spin_fan(speed=speed)
class Ev3rstorm(IRBeaconRemoteControlledTank): def __init__( self, left_foot_motor_port: str = OUTPUT_B, right_foot_motor_port: str = OUTPUT_C, bazooka_blast_motor_port: str = OUTPUT_A, touch_sensor_port: str = INPUT_1, color_sensor_port: str = INPUT_3, ir_sensor_port: str = INPUT_4, ir_beacon_channel: int = 1): super().__init__( left_motor_port=left_foot_motor_port, right_motor_port=right_foot_motor_port, motor_class=LargeMotor, ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel) self.bazooka_blast_motor = MediumMotor(address=bazooka_blast_motor_port) self.touch_sensor = TouchSensor(address=touch_sensor_port) self.color_sensor = ColorSensor(address=color_sensor_port) self.screen = Display() self.speaker = Sound() def blast_bazooka_if_touched(self): if self.touch_sensor.is_pressed: if self.color_sensor.ambient_light_intensity < 5: # 15 not dark enough self.speaker.play_file( wav_file='/home/robot/sound/Up.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.bazooka_blast_motor.on_for_rotations( speed=100, rotations=-3, brake=True, block=True) else: self.speaker.play_file( wav_file='/home/robot/sound/Down.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.bazooka_blast_motor.on_for_rotations( speed=100, rotations=3, brake=True, block=True) self.touch_sensor.wait_for_released() def main(self, driving_speed: float = 100): self.screen.image_filename( filename='/home/robot/image/Target.bmp', clear_screen=True) self.screen.update() while True: self.drive_once_by_ir_beacon(speed=driving_speed) self.blast_bazooka_if_touched()
class Ev3rstorm(RemoteControlledTank): def __init__(self, left_foot_motor_port: str = OUTPUT_B, right_foot_motor_port: str = OUTPUT_C, bazooka_blast_motor_port: str = OUTPUT_A, touch_sensor_port: str = INPUT_1, color_sensor_port: str = INPUT_3, ir_beacon_channel: int = 1): super().__init__(left_motor_port=left_foot_motor_port, right_motor_port=right_foot_motor_port, polarity=Motor.POLARITY_NORMAL, speed=1000, channel=ir_beacon_channel) self.bazooka_blast_motor = MediumMotor( address=bazooka_blast_motor_port) self.touch_sensor = TouchSensor(address=touch_sensor_port) self.color_sensor = ColorSensor(address=color_sensor_port) self.screen = Display() self.speaker = Sound() def blast_bazooka_whenever_touched(self): while True: if self.touch_sensor.is_pressed: if self.color_sensor.ambient_light_intensity < 5: # 15 not dark enough self.speaker.play_file( wav_file='/home/robot/sound/Up.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.bazooka_blast_motor.on_for_rotations(speed=100, rotations=-3, brake=True, block=True) else: self.speaker.play_file( wav_file='/home/robot/sound/Down.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.bazooka_blast_motor.on_for_rotations(speed=100, rotations=3, brake=True, block=True) self.touch_sensor.wait_for_released() def main(self): self.screen.image_filename(filename='/home/robot/image/Target.bmp', clear_screen=True) self.screen.update() Thread(target=self.blast_bazooka_whenever_touched, daemon=True).start() super().main() # RemoteControlledTank.main()
def show_text(string, font_name='courB24', font_width=15, font_height=24): lcd = Display() lcd.clear() strings = wrap(string, width=int(180/font_width)) for i in range(len(strings)): x_val = 89-font_width/2*len(strings[i]) y_val = 63-(font_height+1)*(len(strings)/2-i) lcd.text_pixels(strings[i], False, x_val, y_val, font=font_name) lcd.update()
def test(): print("start", file=sys.stderr) display = Display() display.draw.rectangle((10, 10, 80, 50), fill='black') #display.draw.bitmap((0,0),im) #显示图片 display.image.paste(Image.open('resources/2019-11-10_00126.png'), (0, 0)) display.update() sleep(5) print("end", file=sys.stderr)
def show_text(string, font_name='courB24', font_width=15, font_height=24): # A function to show text on the robot's screen '''Function to show a text on EV3 screen. This code is copied from ev3python.com''' lcd = Display() # Defining screen lcd.clear() # Clearing the screen so there isnt already text strings = wrap(string, width=int(180 / font_width)) # for i in range(len(strings)): x_val = 89 - font_width / 2 * len(strings[i]) y_val = 63 - (font_height + 1) * (len(strings) / 2 - i) lcd.text_pixels(strings[i], False, x_val, y_val, font=font_name) lcd.update()
class Rov3r(IRBeaconRemoteControlledTank): def __init__( self, left_motor_port: str = OUTPUT_B, right_motor_port: str = OUTPUT_C, gear_motor_port: str = OUTPUT_A, touch_sensor_port: str = INPUT_1, color_sensor_port: str = INPUT_3, ir_sensor_port: str = INPUT_4, ir_beacon_channel: int = 1): super().__init__( 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.gear_motor = MediumMotor(address=gear_motor_port) self.touch_sensor = TouchSensor(address=touch_sensor_port) self.color_sensor = ColorSensor(address=color_sensor_port) self.ir_sensor = InfraredSensor(address=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel self.speaker = Sound() self.dis = Display(desc='Display') def spin_gears(self, speed: float = 100): while True: if self.ir_sensor.beacon(channel=self.ir_beacon_channel): self.gear_motor.on( speed=speed, block=False, brake=False) else: self.gear_motor.off(brake=True) def change_screen_when_touched(self): while True: if self.touch_sensor.is_pressed: self.dis.image_filename( filename='/home/robot/image/Angry.bmp', clear_screen=True) self.dis.update() else: self.dis.image_filename( filename='/home/robot/image/Fire.bmp', clear_screen=True) self.dis.update() def make_noise_when_seeing_black(self): while True: if self.color_sensor.color == ColorSensor.COLOR_BLACK: self.speaker.play_file( wav_file='/home/robot/sound/Ouch.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) def main(self): self.speaker.play_file( wav_file='/home/robot/sound/Yes.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) Thread(target=self.make_noise_when_seeing_black, daemon=True).start() Thread(target=self.spin_gears, daemon=True).start() Thread(target=self.change_screen_when_touched, daemon=True).start() self.keep_driving_by_ir_beacon(speed=100)
mcube.flipper_away(100) mcube.scan() leds.set_color('LEFT', 'GREEN') leds.set_color('RIGHT', 'YELLOW') mcube.resolve() motors_off() leds.set_color('RIGHT', 'GREEN') motors_off() write_text('presented by', 'KMXdev') sleep(5) write_text('unterstützt von:', 'Dr. Tannenberg', '&', 'Lego Roberta') sleep(5) write_text('Neustart', '-> Mittlere Taste') pressed = wait_for_button_press() if pressed == "down": dpl.image.paste(eegg, (0, 0)) dpl.update() sleep(5) except Exception as e: log.exception(e) mcube.shutdown_robot() sys.exit(1)
class Sweep3r(IRBeaconRemoteControlledTank): def __init__( self, left_foot_motor_port: str = OUTPUT_B, right_foot_motor_port: str = OUTPUT_C, medium_motor_port: str = OUTPUT_A, touch_sensor_port: str = INPUT_1, color_sensor_port: str = INPUT_3, ir_sensor_port: str = INPUT_4, ir_beacon_channel: int = 1): super().__init__( left_motor_port=left_foot_motor_port, right_motor_port=right_foot_motor_port, ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel) self.medium_motor = MediumMotor(address=medium_motor_port) self.touch_sensor = TouchSensor(address=touch_sensor_port) self.color_sensor = ColorSensor(address=color_sensor_port) self.ir_sensor = InfraredSensor(address=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel self.screen = Display() self.speaker = Sound() def drill(self, speed: float = 100): while True: if self.ir_sensor.beacon(channel=self.ir_beacon_channel): self.medium_motor.on_for_rotations( speed=speed, rotations=2, block=True, brake=True) def move_when_touched(self): while True: if self.touch_sensor.is_pressed: self.tank_driver.on_for_seconds( left_speed=100, right_speed=-100, seconds=2, brake=True, block=True) def move_when_see_smothing(self): while True: if self.color_sensor.reflected_light_intensity > 30: self.tank_driver.on_for_seconds( left_speed=-100, right_speed=100, seconds=2, brake=True, block=True) def main(self, speed: float = 100): self.screen.image_filename( filename='/home/robot/image/Neutral.bmp', clear_screen=True) self.screen.update() Process(target=self.move_when_touched, daemon=True).start() Process(target=self.move_when_see_smothing, daemon=True).start() Process(target=self.drill, daemon=True).start() self.keep_driving_by_ir_beacon(speed=speed)
class Ev3rstorm(IRBeaconRemoteControlledTank): def __init__( self, left_foot_motor_port: str = OUTPUT_B, right_foot_motor_port: str = OUTPUT_C, bazooka_blast_motor_port: str = OUTPUT_A, touch_sensor_port: str = INPUT_1, color_sensor_port: str = INPUT_3, ir_sensor_port: str = INPUT_4, ir_beacon_channel: int = 1): super().__init__( left_motor_port=left_foot_motor_port, right_motor_port=right_foot_motor_port, motor_class=LargeMotor, ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel) self.bazooka_blast_motor = MediumMotor(address=bazooka_blast_motor_port) self.touch_sensor = TouchSensor(address=touch_sensor_port) self.color_sensor = ColorSensor(address=color_sensor_port) self.leds = Leds() self.speaker = Sound() self.screen = Display() def dance_whenever_ir_beacon_pressed(self): while True: while self.ir_sensor.beacon(channel=self.tank_drive_ir_beacon_channel): self.tank_driver.on_for_seconds( left_speed=randint(-100, 100), right_speed=randint(-100, 100), seconds=1, brake=False, block=True) def keep_detecting_objects_by_ir_sensor(self): while True: if self.ir_sensor.proximity < 25: self.leds.animate_police_lights( color1=Leds.ORANGE, color2=Leds.RED, group1=Leds.LEFT, group2=Leds.RIGHT, sleeptime=0.5, duration=5, block=False) self.speaker.play_file( wav_file='/home/robot/sound/Object.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.speaker.play_file( wav_file='/home/robot/sound/Detected.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.speaker.play_file( wav_file='/home/robot/sound/Error alarm.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) else: self.leds.all_off() def blast_bazooka_whenever_touched(self): while True: if self.touch_sensor.is_pressed: if self.color_sensor.ambient_light_intensity < 5: # 15 not dark enough self.speaker.play_file( wav_file='/home/robot/sound/Up.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.bazooka_blast_motor.on_for_rotations( speed=100, rotations=-3, brake=True, block=True) self.speaker.play_file( wav_file='/home/robot/sound/Laughing 1.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) else: self.speaker.play_file( wav_file='/home/robot/sound/Down.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.bazooka_blast_motor.on_for_rotations( speed=100, rotations=3, brake=True, block=True) self.speaker.play_file( wav_file='/home/robot/sound/Laughing 2.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.touch_sensor.wait_for_released() def main(self, driving_speed: float = 100): self.screen.image_filename( filename='/home/robot/image/Target.bmp', clear_screen=True) self.screen.update() # FIXME # Traceback (most recent call last): # File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner # self.run() # File "/usr/lib/python3.5/threading.py", line 862, in run # self._target(*self._args, **self._kwargs) # File "/home/robot/Ev3rstorm/Ev3rstorm-Super.EV3Dev2.Python3.Threading.py", line 170, in dance_whenever_ir_beacon_pressed # while self.ir_sensor.beacon(channel=self.ir_beacon_channel): # File "/usr/lib/python3/dist-packages/ev3dev2/sensor/lego.py", line 909, in beacon # return 'beacon' in self.buttons_pressed(channel) # File "/usr/lib/python3/dist-packages/ev3dev2/sensor/lego.py", line 919, in buttons_pressed # return self._BUTTON_VALUES.get(self.value(channel), []) # File "/usr/lib/python3/dist-packages/ev3dev2/sensor/__init__.py", line 203, in value # self._value[n], value = self.get_attr_int(self._value[n], 'value' + str(n)) # File "/usr/lib/python3/dist-packages/ev3dev2/__init__.py", line 307, in get_attr_int # return attribute, int(value) # ValueError: invalid literal for int() with base 10: '' Thread(target=self.dance_whenever_ir_beacon_pressed, daemon=True).start() # DON'T use IR Sensor in 2 different modes in the same program / loop # - https://github.com/pybricks/support/issues/62 # - https://github.com/ev3dev/ev3dev/issues/1401 # Thread(target=self.keep_detecting_objects_by_ir_sensor, # daemon=True).start() Thread(target=self.blast_bazooka_whenever_touched, daemon=True).start() self.keep_driving_by_ir_beacon(speed=driving_speed)
self.send_response(200) self.send_header("Cache-control", "no cache") self.end_headers() self.wfile.write(value.encode("utf-8")) def error(self, code): self.send_response(code) self.send_header("Cache-control", "no cache") self.end_headers() if __name__ == "__main__": port = 9000 os.chdir(os.path.join(os.path.dirname(__file__), "snap")) server = HTTPServer(("", port), Ev3Handler) if len(sys.argv) > 1: port = int(sys.argv[1]) try: #print("Server Running") d = Display() d.text_grid("Robotica \neducativa \n UTN FRT", font='luBS24') d.update() led = Leds() led.set_color('LEFT', (0, 0)) led.set_color('RIGHT', (0, 0)) server.serve_forever() except KeyboardInterrupt: pass server.server_close() #print(time.asctime(), "Server Stops - %s:%s" % ("", port))
class Ev3rstorm: def __init__(self, left_foot_motor_port: str = OUTPUT_B, right_foot_motor_port: str = OUTPUT_C, bazooka_blast_motor_port: str = OUTPUT_A, touch_sensor_port: str = INPUT_1, color_sensor_port: str = INPUT_3, ir_sensor_port: str = INPUT_4, ir_beacon_channel: int = 1): self.tank_driver = MoveTank(left_motor_port=left_foot_motor_port, right_motor_port=right_foot_motor_port, motor_class=LargeMotor) self.bazooka_blast_motor = MediumMotor( address=bazooka_blast_motor_port) self.touch_sensor = TouchSensor(address=touch_sensor_port) self.color_sensor = ColorSensor(address=color_sensor_port) self.ir_sensor = InfraredSensor(address=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel self.leds = Leds() self.speaker = Sound() self.screen = Display() def drive_once_by_ir_beacon(self, speed: float = 100): # forward if self.ir_sensor.top_left( channel=self.ir_beacon_channel) and self.ir_sensor.top_right( channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=speed, right_speed=speed) # backward elif self.ir_sensor.bottom_left(channel=self.ir_beacon_channel ) and self.ir_sensor.bottom_right( channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=-speed, right_speed=-speed) # turn left on the spot elif self.ir_sensor.top_left(channel=self.ir_beacon_channel ) and self.ir_sensor.bottom_right( channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=-speed, right_speed=speed) # turn right on the spot elif self.ir_sensor.top_right( channel=self.ir_beacon_channel) and self.ir_sensor.bottom_left( channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=speed, right_speed=-speed) # turn left forward elif self.ir_sensor.top_left(channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=0, right_speed=speed) # turn right forward elif self.ir_sensor.top_right(channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=speed, right_speed=0) # turn left backward elif self.ir_sensor.bottom_left(channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=0, right_speed=-speed) # turn right backward elif self.ir_sensor.bottom_right(channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=-speed, right_speed=0) # otherwise stop else: self.tank_driver.off(brake=False) def dance_if_ir_beacon_pressed(self): while self.ir_sensor.beacon(channel=self.ir_beacon_channel): self.tank_driver.on_for_seconds(left_speed=randint(-100, 100), right_speed=randint(-100, 100), seconds=1, brake=False, block=True) def detect_object_by_ir_sensor(self): if self.ir_sensor.proximity < 25: self.leds.animate_police_lights(color1=Leds.ORANGE, color2=Leds.RED, group1=Leds.LEFT, group2=Leds.RIGHT, sleeptime=0.5, duration=5, block=False) self.speaker.play_file(wav_file='/home/robot/sound/Object.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.speaker.play_file(wav_file='/home/robot/sound/Detected.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.speaker.play_file( wav_file='/home/robot/sound/Error alarm.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) else: self.leds.all_off() def blast_bazooka_if_touched(self): if self.touch_sensor.is_pressed: if self.color_sensor.ambient_light_intensity < 5: # 15 not dark enough self.speaker.play_file(wav_file='/home/robot/sound/Up.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.bazooka_blast_motor.on_for_rotations(speed=100, rotations=-3, brake=True, block=True) self.speaker.play_file( wav_file='/home/robot/sound/Laughing 1.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) else: self.speaker.play_file(wav_file='/home/robot/sound/Down.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.bazooka_blast_motor.on_for_rotations(speed=100, rotations=3, brake=True, block=True) self.speaker.play_file( wav_file='/home/robot/sound/Laughing 2.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.touch_sensor.wait_for_released() def main(self, driving_speed: float = 100): self.screen.image_filename(filename='/home/robot/image/Target.bmp', clear_screen=True) self.screen.update() while True: self.drive_once_by_ir_beacon(speed=driving_speed) self.dance_if_ir_beacon_pressed() # DON'T use IR Sensor in 2 different modes in the same program / loop # - https://github.com/pybricks/support/issues/62 # - https://github.com/ev3dev/ev3dev/issues/1401 # self.detect_object_by_ir_sensor() self.blast_bazooka_if_touched()
from ev3dev2.sensor.lego import TouchSensor from ev3dev2.sensor.lego import Sensor from ev3dev2.sensor import INPUT_1, INPUT_2 from ev3dev2.display import Display lcd = Display() # Connect Pixy camera pixy = Sensor() # Connect TouchSensor ts = TouchSensor(address=INPUT_1) # Set mode pixy.mode = 'ALL' while not ts.value(): lcd.clear() if pixy.value(0) != 0: # Object with SIG1 detected x = pixy.value(1) y = pixy.value(2) w = pixy.value(3) h = pixy.value(4) dx = int(w / 2) # Half of the width of the rectangle dy = int(h / 2) # Half of the height of the rectangle xb = x + int(w / 2) # X-coordinate of bottom-right corner yb = y - int(h / 2) # Y-coordinate of the bottom-right corner lcd.draw.rectangle((dx, dy, xb, yb), fill='black') lcd.update() for i in range(0, 4): print(pixy.value(i), file=stderr)
class Spik3r: def __init__(self, sting_motor_port: str = OUTPUT_D, go_motor_port: str = OUTPUT_B, claw_motor_port: str = OUTPUT_A, touch_sensor_port: str = INPUT_1, color_sensor_port: str = INPUT_3, ir_sensor_port: str = INPUT_4, ir_beacon_channel: int = 1): self.sting_motor = LargeMotor(address=sting_motor_port) self.go_motor = LargeMotor(address=go_motor_port) self.claw_motor = MediumMotor(address=claw_motor_port) self.ir_sensor = InfraredSensor(address=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel self.touch_sensor = TouchSensor(address=touch_sensor_port) self.color_sensor = ColorSensor(address=color_sensor_port) self.dis = Display() self.speaker = Sound() def sting_by_ir_beacon(self): while True: if self.ir_sensor.beacon(channel=self.ir_beacon_channel): self.sting_motor.on_for_degrees(speed=-75, degrees=220, brake=True, block=False) self.speaker.play_file(wav_file='/home/robot/sound/Blip 1.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.sting_motor.on_for_seconds(speed=-100, seconds=1, brake=True, block=True) self.sting_motor.on_for_seconds(speed=100, seconds=1, brake=True, block=True) while self.ir_sensor.beacon(channel=self.ir_beacon_channel): pass def be_noisy_to_people(self): while True: if self.color_sensor.reflected_light_intensity > 30: for i in range(4): self.speaker.play_file( wav_file='/home/robot/sound/Blip 2.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) def pinch_if_touched(self): while True: if self.touch_sensor.is_pressed: self.claw_motor.on_for_seconds(speed=50, seconds=1, brake=True, block=True) self.claw_motor.on_for_seconds(speed=-50, seconds=0.3, brake=True, block=True) def keep_driving_by_ir_beacon(self): while True: if self.ir_sensor.top_left(channel=self.ir_beacon_channel) and \ self.ir_sensor.top_right(channel=self.ir_beacon_channel): self.go_motor.on(speed=91, block=False, brake=False) elif self.ir_sensor.top_right(channel=self.ir_beacon_channel): self.go_motor.on(speed=-100, brake=False, block=False) else: self.go_motor.off(brake=True) def main(self): self.dis.image_filename(filename='/home/robot/image/Evil.bmp', clear_screen=True) self.dis.update() # FIXME: .sting_by_ir_beacon stops responding after a while Process(target=self.be_noisy_to_people, daemon=True).start() Process(target=self.sting_by_ir_beacon, daemon=True).start() Process(target=self.pinch_if_touched, daemon=True).start() self.keep_driving_by_ir_beacon()
from ev3dev2.motor import LargeMotor, OUTPUT_B, OUTPUT_C, MoveSteering, MoveTank from ev3dev2.display import Display TANK_DRIVER = MoveTank(left_motor_port=OUTPUT_B, right_motor_port=OUTPUT_C, motor_class=LargeMotor) STEER_DRIVER = MoveSteering(left_motor_port=OUTPUT_B, right_motor_port=OUTPUT_C, motor_class=LargeMotor) SCREEN = Display() SCREEN.image_filename(filename='/home/robot/image/Neutral.bmp', clear_screen=True) SCREEN.update() TANK_DRIVER.on_for_rotations(left_speed=75, right_speed=75, rotations=5, brake=True, block=True) SCREEN.image_filename(filename='/home/robot/image/Middle left.bmp', clear_screen=True) SCREEN.update() STEER_DRIVER.on_for_rotations(steering=50, speed=75, rotations=5, brake=True,
# prepare for the initial position # detect the upper position of the lifter lm_lifter.on( -100, brake=True) while( not ts.is_pressed ): sleep(0.05) # approaching the initial position with high speed lm_lifter.on_for_rotations(90, 7) # nearly approached the initial position, approaching with lower speed lm_lifter.on_for_degrees(20, 240) # clear the lcd display lcd.clear() # show the steps lcd.text_pixels( str(steps), True, 80, 50, font='courB18') lcd.update() log.info('wait user to supply the steps') # wait user to supply the steps to go while( True ): if(not btn.buttons_pressed): sleep(0.01) continue if btn.check_buttons(buttons=['up']): steps += 1 elif(btn.check_buttons(buttons=['down']) ): steps -= 1 if( steps < 0 ): steps = 0 elif(btn.check_buttons(buttons=['enter'])):
print ('Connected') leds.set_color('LEFT', 'GREEN') leds.set_color('RIGHT', 'GREEN') while True: data = client.recv(size) if data: #print(data, file=sys.stderr) cmd = Command.unpickled(data) if cmd: leftMotor.on(speed=cmd.left_drive) rightMotor.on(speed=cmd.right_drive) do_kick = cmd.do_kick > 0 if do_kick != kicking: kicking = do_kick if do_kick: kickMotor.run_to_abs_pos(position_sp=-100, speed_sp=kick_power*max_kick//screenh, stop_action="hold") kick_power = kick_power - (25 if kick_power > 25 else kick_power) else: kickMotor.run_to_abs_pos(position_sp=-10, speed_sp=200, stop_action="coast") kick_power = kick_power + (1 if kick_power < screenh else 0) display.rectangle(x1=0, y1=0, x2=screenw, y2=kick_power) display.update() except: #print("Closing socket") client.close() s.close()
class MindstormsGadget(AlexaGadget): """ A Mindstorms gadget that performs movement based on voice commands. Four types of commands are supported: sit, stay, come, speak, heel. """ def __init__(self): """ Performs Alexa Gadget initialization routines and ev3dev resource allocation. """ super().__init__() # Gadget state self.heel_mode = False self.patrol_mode = False self.sitting = False # Ev3dev initialization self.leds = Leds() self.sound = Sound() # Connect infrared and touch sensors. self.ir = InfraredSensor() self.ts = TouchSensor() # Init display self.screen = Display() # Connect medium motor on output port A: self.medium_motor = MediumMotor(OUTPUT_A) # Connect two large motors on output ports B and C: self.left_motor = LargeMotor(OUTPUT_B) self.right_motor = LargeMotor(OUTPUT_C) # Gadget states self.bpm = 0 self.trigger_bpm = "off" # Start threads threading.Thread(target=self._patrol_thread, daemon=True).start() threading.Thread(target=self._heel_thread, daemon=True).start() threading.Thread(target=self._touchsensor_thread, daemon=True).start() # ------------------------------------------------ # Callbacks # ------------------------------------------------ def on_connected(self, device_addr): """ Gadget connected to the paired Echo device. :param device_addr: the address of the device we connected to """ print("{} Connected to Echo device".format(self.friendly_name)) # Draw blinking eyes of the puppy threading.Thread(target=self._draweyes, daemon=True).start() # Turn lights on: for light in ('LEFT', 'RIGHT'): self.leds.set_color(light, 'GREEN') def on_disconnected(self, device_addr): """ Gadget disconnected from the paired Echo device. :param device_addr: the address of the device we disconnected from """ # Turn lights off: for light in ('LEFT', 'RIGHT'): self.leds.set_color(light, 'BLACK') def on_custom_mindstorms_gadget_control(self, directive): """ Handles the Custom.Mindstorms.Gadget control directive. :param directive: the custom directive with the matching namespace and name """ try: payload = json.loads(directive.payload.decode("utf-8")) print("Control payload: {}".format(payload)) control_type = payload["type"] if control_type == "command": # Expected params: [command] self._activate(payload["command"]) except KeyError: print("Missing expected parameters: {}".format(directive)) # On Amazon music play def on_alexa_gadget_musicdata_tempo(self, directive): """ Provides the music tempo of the song currently playing on the Echo device. :param directive: the music data directive containing the beat per minute value """ tempo_data = directive.payload.tempoData for tempo in tempo_data: print("tempo value: {}".format(tempo.value)) if tempo.value > 0: # dance pose #self.drive.on_for_seconds(SpeedPercent(5), SpeedPercent(25), 1) self.right_motor.run_timed(speed_sp=750, time_sp=2500) self.left_motor.run_timed(speed_sp=-750, time_sp=2500) # shake ev3 head threading.Thread(target=self._sitdown).start() self.leds.set_color("LEFT", "GREEN") self.leds.set_color("RIGHT", "GREEN") time.sleep(3) # starts the dance loop self.trigger_bpm = "on" threading.Thread(target=self._dance_loop, args=(tempo.value, )).start() elif tempo.value == 0: # stops the dance loop self.trigger_bpm = "off" self.leds.set_color("LEFT", "BLACK") self.leds.set_color("RIGHT", "BLACK") def _dance_loop(self, bpm): """ Perform motor movement in sync with the beat per minute value from tempo data. :param bpm: beat per minute from AGT """ color_list = ["GREEN", "RED", "AMBER", "YELLOW"] led_color = random.choice(color_list) motor_speed = 400 milli_per_beat = min(1000, (round(60000 / bpm)) * 0.65) print("Adjusted milli_per_beat: {}".format(milli_per_beat)) while self.trigger_bpm == "on": # Alternate led color and motor direction led_color = "BLACK" if led_color != "BLACK" else random.choice( color_list) motor_speed = -motor_speed self.leds.set_color("LEFT", led_color) self.leds.set_color("RIGHT", led_color) self.right_motor.run_timed(speed_sp=motor_speed, time_sp=150) self.left_motor.run_timed(speed_sp=-motor_speed, time_sp=150) time.sleep(milli_per_beat / 1000) self.left_motor.run_timed(speed_sp=-motor_speed, time_sp=150) self.right_motor.run_timed(speed_sp=motor_speed, time_sp=150) time.sleep(milli_per_beat / 1000) self.right_motor.run_timed(speed_sp=350, time_sp=300) self.left_motor.run_timed(speed_sp=-350, time_sp=300) time.sleep(milli_per_beat / 1000) self.right_motor.run_timed(speed_sp=motor_speed, time_sp=150) self.left_motor.run_timed(speed_sp=-motor_speed, time_sp=150) time.sleep(milli_per_beat / 1000) def _move(self, direction, duration: int, speed: int, is_blocking=False): """ Handles move commands from the directive. Right and left movement can under or over turn depending on the surface type. :param direction: the move direction :param duration: the duration in seconds :param speed: the speed percentage as an integer :param is_blocking: if set, motor run until duration expired before accepting another command """ print("Move command: ({}, {}, {}, {})".format(direction, speed, duration, is_blocking)) if direction in Direction.FORWARD.value: #self.drive.on_for_seconds(SpeedPercent(speed), SpeedPercent(speed), duration, block=is_blocking) self.right_motor.run_timed(speed_sp=-750, time_sp=2500) self.left_motor.run_timed(speed_sp=-750, time_sp=2500) if direction in Direction.BACKWARD.value: #self.drive.on_for_seconds(SpeedPercent(-speed), SpeedPercent(-speed), duration, block=is_blocking) self.right_motor.run_timed(speed_sp=750, time_sp=2500) self.left_motor.run_timed(speed_sp=750, time_sp=2500) if direction in (Direction.RIGHT.value + Direction.LEFT.value): self._turn(direction, speed) #self.drive.on_for_seconds(SpeedPercent(speed), SpeedPercent(speed), duration, block=is_blocking) self.right_motor.run_timed(speed_sp=750, time_sp=2500) self.left_motor.run_timed(speed_sp=-750, time_sp=2500) if direction in Direction.STOP.value: #self.drive.off() self.right_motor.stop self.left_motor.stop self.heel_mode = False self.patrol_mode = False def _activate(self, command): """ Handles preset commands. :param command: the preset command """ print("Activate command: ({}".format(command)) if command in Command.COME.value: #call _come method self.right_motor.run_timed(speed_sp=750, time_sp=2500) self.left_motor.run_timed(speed_sp=50, time_sp=100) if command in Command.HEEL.value: #call _hell method self.heel_mode = True if command in Command.SIT.value: # call _sit method self.heel_mode = False self._sitdown() if command in Command.STAY.value: # call _stay method self.heel_mode = False self._standup() def _turn(self, direction, speed): """ Turns based on the specified direction and speed. Calibrated for hard smooth surface. :param direction: the turn direction :param speed: the turn speed """ if direction in Direction.LEFT.value: #self.drive.on_for_seconds(SpeedPercent(0), SpeedPercent(speed), 2) self.right_motor.run_timed(speed_sp=0, time_sp=100) self.left_motor.run_timed(speed_sp=750, time_sp=100) if direction in Direction.RIGHT.value: #self.drive.on_for_seconds(SpeedPercent(speed), SpeedPercent(0), 2) self.right_motor.run_timed(speed_sp=750, time_sp=100) self.left_motor.run_timed(speed_sp=0, time_sp=100) def _send_event(self, name: EventName, payload): """ Sends a custom event to trigger a sentry action. :param name: the name of the custom event :param payload: the sentry JSON payload """ self.send_custom_event('Custom.Mindstorms.Gadget', name.value, payload) def _heel_thread(self): """ Monitors the distance between the puppy and an obstacle when heel command called. If the maximum distance is breached, decrease the distance by following an obstancle """ while True: while self.heel_mode: distance = self.ir.proximity print("Proximity distance: {}".format(distance)) # keep distance and make step back from the object if distance < 45: threading.Thread(target=self.__movebackwards).start() self._send_event(EventName.BARK, {'distance': distance}) # follow the object if distance > 60: threading.Thread(target=self.__moveforwards).start() # otherwise stay still else: threading.Thread(target=self.__stay).start() time.sleep(0.2) time.sleep(1) def _touchsensor_thread(self): print("Touch sensor activated") while True: if self.ts.is_pressed: self.leds.set_color("LEFT", "RED") self.leds.set_color("RIGHT", "RED") if (self.sitting): threading.Thread(target=self._standup).start() self.sitting = False else: threading.Thread(target=self._sitdown).start() self.sitting = True else: self.leds.set_color("LEFT", "GREEN") self.leds.set_color("RIGHT", "GREEN") def _sitdown(self): self.medium_motor.on_for_rotations(SpeedPercent(20), 0.5) def _standup(self): # run the wheels backwards to help the puppy to stand up. threading.Thread(target=self.__back).start() self.medium_motor.on_for_rotations(SpeedPercent(50), -0.5) def __back(self): self.right_motor.run_timed(speed_sp=-350, time_sp=1000) self.left_motor.run_timed(speed_sp=-350, time_sp=1000) def __movebackwards(self): self.right_motor.run_timed(speed_sp=-650, time_sp=1000) self.left_motor.run_timed(speed_sp=-650, time_sp=1000) def __moveforwards(self): self.right_motor.run_timed(speed_sp=650, time_sp=1000) self.left_motor.run_timed(speed_sp=650, time_sp=1000) def __stay(self): self.right_motor.run_timed(speed_sp=0, time_sp=1000) self.left_motor.run_timed(speed_sp=0, time_sp=1000) def _draweyes(self): close = True while True: self.screen.clear() if close: #self.screen.draw.ellipse(( 5, 30, 75, 50),fill='white') #self.screen.draw.ellipse((103, 30, 173, 50), fill='white') self.screen.draw.rectangle((5, 60, 75, 50), fill='black') self.screen.draw.rectangle((103, 60, 173, 50), fill='black') #self.screen.draw.rectangle(( 5, 30, 75, 50), fill='black') #self.screen.draw.rectangle((103, 30, 173, 50), fill='black') time.sleep(10) else: #self.screen.draw.ellipse(( 5, 30, 75, 100)) #self.screen.draw.ellipse((103, 30, 173, 100)) #self.screen.draw.ellipse(( 35, 30, 105, 30),fill='black') #self.screen.draw.ellipse((133, 30, 203, 30), fill='black') self.screen.draw.rectangle((5, 10, 75, 100), fill='black') self.screen.draw.rectangle((103, 10, 173, 100), fill='black') close = not close # toggle between True and False # Update screen display # Applies pending changes to the screen. # Nothing will be drawn on the screen screen # until this function is called. self.screen.update() time.sleep(1) def _patrol_thread(self): """ Performs random movement when patrol mode is activated. """ while True: while self.patrol_mode: print("Patrol mode activated randomly picks a path") direction = random.choice(list(Direction)) duration = random.randint(1, 5) speed = random.randint(1, 4) * 25 while direction == Direction.STOP: direction = random.choice(list(Direction)) # direction: all except stop, duration: 1-5s, speed: 25, 50, 75, 100 self._move(direction.value[0], duration, speed) time.sleep(duration) time.sleep(1)
# draw hanburger display.draw.ellipse((hx,hy,hx+step,hy+step)) # clear the score on screen so that new score could be shown properly display.draw.text((0,2), 'Score {0}'.format(length), fill='white') length += 1 else: tmpx=Sx[0] tmpy=Sy[0] # clean the snake tail display.draw.rectangle((tmpx,tmpy,tmpx+step,tmpy+step), fill='white', outline='white') # pop the unused element Sx.pop(0) Sy.pop(0) dead = isDead(Sx, Sy) if dead: sound.beep() logo = Image.open('/home/robot/LEGO/pics/Bomb.bmp') display.image.paste(logo, (0,0)) display.update() sleep(3) exit() # Draw snake head display.draw.rectangle((x, y, x+step, y+step),fill='black') display.update() sleep(waittime)
class Ev3rstorm(IRBeaconRemoteControlledTank): def __init__(self, left_foot_motor_port: str = OUTPUT_B, right_foot_motor_port: str = OUTPUT_C, bazooka_blast_motor_port: str = OUTPUT_A, touch_sensor_port: str = INPUT_1, color_sensor_port: str = INPUT_3, ir_sensor_port: str = INPUT_4, ir_beacon_channel: int = 1): super().__init__(left_motor_port=left_foot_motor_port, right_motor_port=right_foot_motor_port, motor_class=LargeMotor, ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel) self.bazooka_blast_motor = MediumMotor( address=bazooka_blast_motor_port) self.touch_sensor = TouchSensor(address=touch_sensor_port) self.color_sensor = ColorSensor(address=color_sensor_port) self.leds = Leds() self.speaker = Sound() self.screen = Display() def dance_whenever_ir_beacon_pressed(self): while True: while self.ir_sensor.beacon( channel=self.tank_drive_ir_beacon_channel): self.tank_driver.on_for_seconds(left_speed=randint(-100, 100), right_speed=randint(-100, 100), seconds=1, brake=False, block=True) def keep_detecting_objects_by_ir_sensor(self): while True: if self.ir_sensor.proximity < 25: self.leds.animate_police_lights(color1=Leds.ORANGE, color2=Leds.RED, group1=Leds.LEFT, group2=Leds.RIGHT, sleeptime=0.5, duration=5, block=False) self.speaker.play_file(wav_file='/home/robot/sound/Object.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.speaker.play_file( wav_file='/home/robot/sound/Detected.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.speaker.play_file( wav_file='/home/robot/sound/Error alarm.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) else: self.leds.all_off() def blast_bazooka_whenever_touched(self): while True: if self.touch_sensor.is_pressed: if self.color_sensor.ambient_light_intensity < 5: # 15 not dark enough self.speaker.play_file( wav_file='/home/robot/sound/Up.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.bazooka_blast_motor.on_for_rotations(speed=100, rotations=-3, brake=True, block=True) self.speaker.play_file( wav_file='/home/robot/sound/Laughing 1.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) else: self.speaker.play_file( wav_file='/home/robot/sound/Down.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.bazooka_blast_motor.on_for_rotations(speed=100, rotations=3, brake=True, block=True) self.speaker.play_file( wav_file='/home/robot/sound/Laughing 2.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.touch_sensor.wait_for_released() def main(self, driving_speed: float = 100): self.screen.image_filename(filename='/home/robot/image/Target.bmp', clear_screen=True) self.screen.update() Process(target=self.dance_whenever_ir_beacon_pressed, daemon=True).start() # DON'T use IR Sensor in 2 different modes in the same program / loop # - https://github.com/pybricks/support/issues/62 # - https://github.com/ev3dev/ev3dev/issues/1401 # Process(target=self.keep_detecting_objects_by_ir_sensor, # daemon=True).start() Process(target=self.blast_bazooka_whenever_touched, daemon=True).start() self.keep_driving_by_ir_beacon(speed=driving_speed)
class Ui(threading.Thread): M_FONT = 'helvB12' def __init__(self, config): threading.Thread.__init__(self) self.roboId = config['id'] self.threadID = 1 self.name = 'ui-thread' self.isRunning = True self.messageText = '-' self.statusText = '-' self.powerSupplyText = '-' self.lcd = Display() self.btn = Button() self.sound = Sound() self.leds = Leds() self.theFont = fonts.load(Ui.M_FONT) self.lcd.clear() self.drawText() self.lcd.update() def drawText(self): self.lcd.draw.text((0, 0), 'RoboRinth', font=self.theFont) self.lcd.draw.text((0, 14), 'ID: ' + self.roboId, font=self.theFont) self.lcd.draw.text((0, 28), 'Status: ' + self.statusText, font=self.theFont) self.lcd.draw.text((0, 42), 'Msg: ' + self.messageText, font=self.theFont) # self.lcd.draw.text((0,56), 'Pwr: ' + self.powerSupplyText, font=self.theFont) def run(self): while self.isRunning: self.lcd.clear() self.drawText() self.lcd.update() self.btn.process() sleep(1) # sleep(0.5) self.lcd.clear() self.lcd.draw.rectangle((0, 0, 178, 128), fill='white') self.lcd.update() def registerBackspaceHandler(self, backspaceHandler): self.btn.on_backspace = backspaceHandler def stop(self): self.isRunning = False self.join() def setMessageText(self, text): self.messageText = text def setStatusText(self, text): self.statusText = text def setPowerSupplyText(self, text): self.powerSupplyText = text def playStartSound(self): self.sound.tone([(800, 200, 0), (1200, 400, 100)]) def setStatusLed(self, color): if color == 'green': self.leds.set_color('RIGHT', 'GREEN') elif color == 'orange': self.leds.set_color('RIGHT', 'ORANGE') else: print('unsupported color: ' + str(color))
class Ev3rstorm: def __init__(self, left_foot_motor_port: str = OUTPUT_B, right_foot_motor_port: str = OUTPUT_C, bazooka_blast_motor_port: str = OUTPUT_A, touch_sensor_port: str = INPUT_1, color_sensor_port: str = INPUT_3, ir_sensor_port: str = INPUT_4, ir_beacon_channel: int = 1): self.tank_driver = MoveTank(left_motor_port=left_foot_motor_port, right_motor_port=right_foot_motor_port, motor_class=LargeMotor) self.bazooka_blast_motor = MediumMotor( address=bazooka_blast_motor_port) self.touch_sensor = TouchSensor(address=touch_sensor_port) self.color_sensor = ColorSensor(address=color_sensor_port) self.ir_sensor = InfraredSensor(address=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel self.screen = Display() self.speaker = Sound() def drive_once_by_ir_beacon(self, speed: float = 100): # forward if self.ir_sensor.top_left( channel=self.ir_beacon_channel) and self.ir_sensor.top_right( channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=speed, right_speed=speed) # backward elif self.ir_sensor.bottom_left(channel=self.ir_beacon_channel ) and self.ir_sensor.bottom_right( channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=-speed, right_speed=-speed) # turn left on the spot elif self.ir_sensor.top_left(channel=self.ir_beacon_channel ) and self.ir_sensor.bottom_right( channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=-speed, right_speed=speed) # turn right on the spot elif self.ir_sensor.top_right( channel=self.ir_beacon_channel) and self.ir_sensor.bottom_left( channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=speed, right_speed=-speed) # turn left forward elif self.ir_sensor.top_left(channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=0, right_speed=speed) # turn right forward elif self.ir_sensor.top_right(channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=speed, right_speed=0) # turn left backward elif self.ir_sensor.bottom_left(channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=0, right_speed=-speed) # turn right backward elif self.ir_sensor.bottom_right(channel=self.ir_beacon_channel): self.tank_driver.on(left_speed=-speed, right_speed=0) # otherwise stop else: self.tank_driver.off(brake=False) def keep_driving_by_ir_beacon(self, speed: int = 100): while True: self.drive_once_by_ir_beacon(speed=speed) def blast_bazooka_whenever_touched(self): while True: if self.touch_sensor.is_pressed: if self.color_sensor.ambient_light_intensity < 5: # 15 not dark enough self.speaker.play_file( wav_file='/home/robot/sound/Up.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.bazooka_blast_motor.on_for_rotations(speed=100, rotations=-3, brake=True, block=True) else: self.speaker.play_file( wav_file='/home/robot/sound/Down.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) self.bazooka_blast_motor.on_for_rotations(speed=100, rotations=3, brake=True, block=True) self.touch_sensor.wait_for_released() def main(self, driving_speed: float = 100): self.screen.image_filename(filename='/home/robot/image/Target.bmp', clear_screen=True) self.screen.update() Thread(target=self.blast_bazooka_whenever_touched, daemon=True).start() self.keep_driving_by_ir_beacon(speed=driving_speed)
def cmToRotations(cm): return cm/wheelCircumference_cm # inches to millimeters: def inToMillimeters(inches): return inches * 25.4 # centimeters to millimeters: def cmToMillimeters(cm): #hhm it works... questionable -- no syntax errors! return cm * 10 # Yay, no syntax errors! def drive_cm(power, cm): rt = cmToRotations(cm) tank_drive.on_for_rotations(SpeedPercent(power), SpeedPercent(power), int(rt) ) def drive_cm_new(power, cm): rt = cmToRotations(cm) tank_drive.on_for_rotations(SpeedPercent(power), SpeedPercent(power), rt) #--------------------------------------------------------------------------------------------------------------------------------------------- while True: if (btn.down): break pass btn.wait_for_released('enter') finish = time.time() Display_.clear() Display_.draw.text((0,0), str(finish - start), font=fonts.load('helvR24')) Display_.update() time.sleep(5) drive_cm_new(50, 50) time.sleep(5) drive_cm_new(-50, 50) start = time.time()
def master_function(): cl = ColorSensor() ts = TouchSensor() ir = InfraredSensor() sound = Sound() steer_pair = MoveSteering(OUTPUT_B, OUTPUT_C) medium_motor = MediumMotor() pixy = Sensor(address=INPUT_2) # assert pixy.connected, "Error while connecting Pixy camera to port 1" # pixy.mode = 'SIG1' # lcd = Sensor.Screen() lcd = Display() def top_left_channel_1_action(state): move() def bottom_left_channel_1_action(state): move() def top_right_channel_1_action(state): move() def bottom_right_channel_1_action(state): move() def move(): buttons = ir.buttons_pressed() # a list if len(buttons) == 1: medium_motor.off() if buttons == ['top_left']: steer_pair.on(steering=0, speed=40) elif buttons == ['bottom_left']: steer_pair.on(steering=0, speed=-40) elif buttons == ['top_right']: steer_pair.on(steering=100, speed=30) elif buttons == ['bottom_right']: steer_pair.on(steering=-100, speed=30) elif len(buttons) == 2: steer_pair.off() if buttons == ['top_left', 'top_right']: medium_motor.on(speed_pct=10) elif buttons == ['bottom_left', 'bottom_right']: medium_motor.on(speed_pct=-10) else: # len(buttons)==0 medium_motor.off() steer_pair.off() # Associate the event handlers with the functions defined above ir.on_channel1_top_left = top_left_channel_1_action ir.on_channel1_bottom_left = bottom_left_channel_1_action ir.on_channel1_top_right = top_right_channel_1_action ir.on_channel1_bottom_right = bottom_right_channel_1_action opts = '-a 200 -s 150 -p 70 -v' speech_pause = 0 while not ts.is_pressed: # rgb is a tuple containing three integers ir.process() red = cl.rgb[0] green = cl.rgb[1] blue = cl.rgb[2] intensity = cl.reflected_light_intensity print('{4} Red: {0}\tGreen: {1}\tBlue: {2}\tIntensity: {3}'.format( str(red), str(green), str(blue), str(intensity), speech_pause), file=stderr) lcd.clear() print(pixy.mode, file=stderr) if pixy.value(0) != 0: # Object with SIG1 detected x = pixy.value(1) y = pixy.value(2) w = pixy.value(3) h = pixy.value(4) dx = int(w / 2) # Half of the width of the rectangle dy = int(h / 2) # Half of the height of the rectangle xb = x + int(w / 2) # X-coordinate of bottom-right corner yb = y - int(h / 2) # Y-coordinate of the bottom-right corner lcd.draw.rectangle((xa, ya, xb, yb), fill='black') lcd.update() speech_pause += 1 if speech_pause == 200: # try replacing with ir.distance(), ir.heading() # or ir.heading_and_distance() distance = ir.heading_and_distance() if distance == None: # distance() returns None if no beacon detected str_en = 'Beacon off?' else: str_en = 'Beacon heading {0} and distance {1}'.format( distance[0], distance[1]) sound.speak(str_en, espeak_opts=opts + 'en+f5') print(str_en, file=stderr) speech_pause = 0 str_en = 'Terminating program' sound.speak(str_en, espeak_opts=opts + 'en+f5')
exit() ''' console.reset_console() console.text_at('Hello World!', column=1, row=5, reset_console=True, inverse=True) sleep(2) ''' # 在屏幕上显示字体 if True: #显示有效的Display字体 print(fonts.available(), file=sys.stderr) sleep(2) exit() disp.clear() disp.draw.text((10, 10), 'Hello World!', font=fonts.load('courB18')) disp.update() # 改变面板显示灯的颜色 leds.set_color("LEFT", "GREEN") leds.set_color("RIGHT", "RED") # 英文转语音 sleep(1) sounds.speak(text='Welcome to the E V 3 dev project!') sleep(1) # 控制电机转动 m = LargeMotor(OUTPUT_A) #m.on_for_rotations(SpeedPercent(75), 1) m.on_for_degrees(50, 50) sleep(1)
class MindstormsGadget(AlexaGadget): """ A Mindstorms gadget that performs movement based on voice commands. Two types of commands are supported, directional movement and preset. """ def __init__(self): """ Performs Alexa Gadget initialization routines and ev3dev resource allocation. """ super().__init__() # Gadget state self.heel_mode = False self.patrol_mode = False self.sitting = False # Ev3dev initialization self.leds = Leds() self.sound = Sound() # Connect infrared and touch sensors. self.ir = InfraredSensor() self.ts = TouchSensor() # Init display self.screen = Display() self.dance = False self.sound = Sound() self.drive = MoveTank(OUTPUT_B, OUTPUT_C) self.sound.speak('Hello, my name is Beipas!') # Connect medium motor on output port A: self.medium_motor = MediumMotor(OUTPUT_A) # Connect two large motors on output ports B and C: self.left_motor = LargeMotor(OUTPUT_B) self.right_motor = LargeMotor(OUTPUT_C) # Gadget states self.bpm = 0 self.trigger_bpm = "off" self.eyes = True # Start threads threading.Thread(target=self._dance_thread, daemon=True).start() threading.Thread(target=self._patrol_thread, daemon=True).start() threading.Thread(target=self._heel_thread, daemon=True).start() threading.Thread(target=self._touchsensor_thread, daemon=True).start() threading.Thread(target=self._eyes_thread, daemon=True).start() def on_connected(self, device_addr): """ Gadget connected to the paired Echo device. :param device_addr: the address of the device we connected to """ self.leds.set_color("LEFT", "GREEN") self.leds.set_color("RIGHT", "GREEN") logger.info("{} connected to Echo device".format(self.friendly_name)) def on_disconnected(self, device_addr): """ Gadget disconnected from the paired Echo device. :param device_addr: the address of the device we disconnected from """ self.leds.set_color("LEFT", "BLACK") self.leds.set_color("RIGHT", "BLACK") logger.info("{} disconnected from Echo device".format( self.friendly_name)) def on_custom_mindstorms_gadget_control(self, directive): """ Handles the Custom.Mindstorms.Gadget control directive. :param directive: the custom directive with the matching namespace and name """ try: payload = json.loads(directive.payload.decode("utf-8")) print("Control payload: {}".format(payload), file=sys.stderr) control_type = payload["type"] if control_type == "move": speed = random.randint(3, 4) * 25 # Expected params: [direction, duration, speed] self._move(payload["direction"], int(payload["duration"]), speed) if control_type == "command": # Expected params: [command] self._activate(payload["command"]) except KeyError: print("Missing expected parameters: {}".format(directive), file=sys.stderr) def _dance_thread(self): """ Perform motor movement in sync with the beat per minute value from tempo data. :param bpm: beat per minute from AGT """ bpm = 100 color_list = ["GREEN", "RED", "AMBER", "YELLOW"] led_color = random.choice(color_list) motor_speed = 400 milli_per_beat = min(1000, (round(60000 / bpm)) * 0.65) print("Adjusted milli_per_beat: {}".format(milli_per_beat)) while True: while self.dance == True: print("Dancing") # Alternate led color and motor direction led_color = "BLACK" if led_color != "BLACK" else random.choice( color_list) motor_speed = -motor_speed self.leds.set_color("LEFT", led_color) self.leds.set_color("RIGHT", led_color) self.right_motor.run_timed(speed_sp=motor_speed, time_sp=150) self.left_motor.run_timed(speed_sp=-motor_speed, time_sp=150) time.sleep(milli_per_beat / 1000) self.left_motor.run_timed(speed_sp=-motor_speed, time_sp=150) self.right_motor.run_timed(speed_sp=motor_speed, time_sp=150) time.sleep(milli_per_beat / 1000) self.right_motor.run_timed(speed_sp=350, time_sp=300) self.left_motor.run_timed(speed_sp=-350, time_sp=300) time.sleep(milli_per_beat / 1000) self.right_motor.run_timed(speed_sp=motor_speed, time_sp=150) self.left_motor.run_timed(speed_sp=-motor_speed, time_sp=150) time.sleep(milli_per_beat / 1000) def _move(self, direction, duration: int, speed=70, is_blocking=False): """ Handles move commands from the directive. Right and left movement can under or over turn depending on the surface type. :param direction: the move direction :param duration: the duration in seconds :param speed: the speed percentage as an integer :param is_blocking: if set, motor run until duration expired before accepting another command """ print("Move command: ({}, {}, {}, {})".format(direction, speed, duration, is_blocking), file=sys.stderr) if direction in Direction.FORWARD.value: self.drive.on_for_seconds(SpeedPercent(speed), SpeedPercent(speed), duration, block=is_blocking) if direction in Direction.BACKWARD.value: self.drive.on_for_seconds(SpeedPercent(-speed), SpeedPercent(-speed), duration, block=is_blocking) if direction in (Direction.RIGHT.value): self.drive.on_for_seconds(SpeedPercent(-speed), SpeedPercent(speed), duration, block=is_blocking) if direction in (Direction.LEFT.value): self.drive.on_for_seconds(SpeedPercent(speed), SpeedPercent(-speed), duration, block=is_blocking) if direction in Direction.STOP.value: self.drive.off() self.patrol_mode = False self.dance = False def _activate(self, command): """ Handles preset commands. :param command: the preset command """ print("Activate command: ({}".format(command)) if command in Command.COME.value: #call _come method self.right_motor.run_timed(speed_sp=750, time_sp=2500) self.left_motor.run_timed(speed_sp=750, time_sp=2500) if command in Command.HEEL.value: #call _hell method self.heel_mode = True if command in Command.SIT.value: # call _sit method self.heel_mode = False self.trigger_bpm == "on" self._sitdown() if command in Command.SENTRY.value: # call _stay method self.trigger_bpm == "on" self.heel_mode = False self._standup() if command in Command.STAY.value: # call _stay method self.heel_mode = False self._standup() if command in Command.ANGRY.value: # call _stay method self._angrybark() if command in Command.CUTE.value: # call _stay method self._cutebark() if command in Command.COFFIN.value: # call _stay method self.dance = True self.trigger_bpm = "on" self._coffinbark() self.dance = False if command in Command.DANCE.value: # call _stay method self.trigger_bpm = "on" self.dance = True print(self.dance) def _turn(self, direction, speed): """ Turns based on the specified direction and speed. Calibrated for hard smooth surface. :param direction: the turn direction :param speed: the turn speed """ if direction in Direction.LEFT.value: #self.drive.on_for_seconds(SpeedPercent(0), SpeedPercent(speed), 2) self.right_motor.run_timed(speed_sp=0, time_sp=100) self.left_motor.run_timed(speed_sp=750, time_sp=100) if direction in Direction.RIGHT.value: #self.drive.on_for_seconds(SpeedPercent(speed), SpeedPercent(0), 2) self.right_motor.run_timed(speed_sp=750, time_sp=100) self.left_motor.run_timed(speed_sp=0, time_sp=100) def _patrol_thread(self): """ Performs random movement when patrol mode is activated. """ while True: while self.patrol_mode: print("Patrol mode activated randomly picks a path") direction = random.choice(list(Direction)) duration = random.randint(1, 5) speed = random.randint(1, 4) * 25 while direction == Direction.STOP: direction = random.choice(list(Direction)) # direction: all except stop, duration: 1-5s, speed: 25, 50, 75, 100 self._move(direction.value[0], duration, speed) time.sleep(duration) time.sleep(1) def _send_event(self, name: EventName, payload): """ Sends a custom event to trigger a sentry action. :param name: the name of the custom event :param payload: the sentry JSON payload """ self.send_custom_event('Custom.Mindstorms.Gadget', name.value, payload) def _heel_thread(self): """ Monitors the distance between the puppy and an obstacle when heel command called. If the maximum distance is breached, decrease the distance by following an obstancle """ while True: while self.heel_mode: distance = self.ir.proximity print("Proximity distance: {}".format(distance)) # keep distance and make step back from the object if distance < 35: threading.Thread(target=self.__movebackwards).start() # self._send_event(EventName.BARK, {'distance': distance}) # follow the object if distance > 50: threading.Thread(target=self.__moveforwards).start() # otherwise stay still else: threading.Thread(target=self.__stay).start() time.sleep(0.2) time.sleep(1) def _touchsensor_thread(self): print("Touch sensor activated") while True: if self.ts.is_pressed: self.leds.set_color("LEFT", "RED") self.leds.set_color("RIGHT", "RED") if (self.sitting): threading.Thread(target=self._standup).start() self.sitting = False else: threading.Thread(target=self._sitdown).start() self.sitting = True else: self.leds.set_color("LEFT", "GREEN") self.leds.set_color("RIGHT", "GREEN") def _eyes_thread(self): print("Drawing Eyes") while True: while self.eyes: self._draweyes() def _sitdown(self): self.medium_motor.on_for_rotations(SpeedPercent(20), 0.5) def _standup(self): # run the wheels backwards to help the puppy to stand up. threading.Thread(target=self.__back).start() self.medium_motor.on_for_rotations(SpeedPercent(50), -0.5) def __back(self): self.right_motor.run_timed(speed_sp=-350, time_sp=1000) self.left_motor.run_timed(speed_sp=-350, time_sp=1000) def __movebackwards(self): self.right_motor.run_timed(speed_sp=-750, time_sp=2500) self.left_motor.run_timed(speed_sp=-750, time_sp=2500) def __moveforwards(self): self.right_motor.run_timed(speed_sp=750, time_sp=2500) self.left_motor.run_timed(speed_sp=750, time_sp=2500) def __stay(self): self.right_motor.run_timed(speed_sp=0, time_sp=1000) self.left_motor.run_timed(speed_sp=0, time_sp=1000) def _angrybark(self): self.sound.play_file('angry_bark.wav') def _cutebark(self): self.sound.play_file('cute_bark.wav') def _coffinbark(self): self.sound.play_file('coffin_dance.wav') def _draweyes(self): close = True while True: self.screen.clear() # if close: # self.screen.draw.line(50,65,90, 100, width=5) # self.screen.draw.line(50,105,90, 105, width=5) # self.screen.draw.line(120,100,160,65, width=5) # self.screen.draw.line(120,105,160,105, width=5) # time.sleep(10) # else: # self.screen.draw.rectangle(50,45,90, 125, radius=10, fill_color='white') # self.screen.draw.rectangle(120,45,160,125, radius=10, fill_color='white') # self.screen.draw.rectangle(65,65,80, 105, radius=7, fill_color='black') # self.screen.draw.rectangle(130,65,145,105, radius=7, fill_color='black') ## alt # self.screen.draw.line(50,105,90, 105, width=5).rotate(135) # self.screen.draw.line(50,105,90, 105, width=5) # self.screen.draw.line(50,105,90, 105, width=5).rotate(45) # self.screen.draw.line(50,105,90, 105, width=5) if close: # self.screen.draw.ellipse(( 5, 30, 75, 50),fill='white') # self.screen.draw.ellipse((103, 30, 173, 50), fill='white') self.screen.draw.rectangle((5, 60, 75, 50), fill='black') self.screen.draw.rectangle((103, 60, 173, 50), fill='black') # self.screen.draw.rectangle(( 5, 30, 75, 50), fill='black') # self.screen.draw.rectangle((103, 30, 173, 50), fill='black') time.sleep(10) else: # self.screen.draw.ellipse(( 5, 30, 75, 100)) # self.screen.draw.ellipse((103, 30, 173, 100)) # self.screen.draw.ellipse(( 35, 30, 105, 30),fill='black') # self.screen.draw.ellipse((133, 30, 203, 30), fill='black') self.screen.draw.rectangle((5, 10, 75, 100), fill='black') self.screen.draw.rectangle((103, 10, 173, 100), fill='black') close = not close # toggle between True and False # Update screen display # Applies pending changes to the screen. # Nothing will be drawn on the screen screen # until this function is called. self.screen.update() time.sleep(1)