def main(): brick.sound.beep() sens1 = LegoPort(address ='ev3-ports:in1') # which port?? 1,2,3, or 4 #sens2 = LegoPort(address ='ev3-ports:in2') # which port?? 1,2,3, or 4 sens1.mode = 'ev3-analog' #sens2.mode = 'ev3-analog' utime.sleep(0.5) sensor_left=MySensor(Port.S1) # same port as above sensor_right=MySensor(Port.S2) # same port as above left_motor = Motor(Port.A) right_motor = Motor(Port.D) speed = 0 value = 100 while True: left_color = sensor_left.readvalue() right_color = sensor_right.readvalue() print('left sensor is ', left_color) print('right sensor is ', right_color) left_motor.run(speed) right_motor.run(speed)
class Rover: def __init__(self): """ Initialization of Rover.""" # Constants self._GAIN = 10 self._speed = SPEED_FAST # Initialize the EV3 brick self.ev3 = EV3Brick() # Initialize the motors self.left_motor = Motor(Port.B) self.right_motor = Motor(Port.C) def move(self, speed): speed *= self._GAIN speed_left = limit_speed(self._speed - speed) speed_right = limit_speed(self._speed + speed) self.left_motor.run(speed_left) self.right_motor.run(speed_right) def move_slow(self): """ Set initial speed to SPEED_SLOW.""" self._speed = SPEED_SLOW def move_fast(self): """ Set initial speed to SPEED_FAST.""" self._speed = SPEED_FAST def stop(self): self.left_motor.stop() self.right_motor.stop()
class Robot(): def __init__(self): self.motor = Motor(Port.B) self.ultrasonic = UltrasonicSensor(Port.S4) self.active = True self.speed = 0 self.colors = [None, Color.GREEN, Color.YELLOW, Color.RED] def setSpeed(self, acc): if acc < 0: self.speed = max(-3, self.speed - 1) elif acc > 0: self.speed = min(3, self.speed + 1) else: self.speed = 0 if self.speed != 0: self.motor.run(self.speed * 90) else: self.motor.stop() brick.light(self.colors[abs(self.speed)]) def inactive(self): self.active = False self.setSpeed(0) brick.sound.beep()
class Rov3r(IRBeaconRemoteControlledTank, EV3Brick): WHEEL_DIAMETER = 23 AXLE_TRACK = 65 def __init__(self, left_motor_port: Port = Port.B, right_motor_port: Port = Port.C, gear_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, color_sensor_port: Port = Port.S3, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): super().__init__(wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK, left_motor_port=left_motor_port, right_motor_port=right_motor_port, ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel) self.gear_motor = Motor(port=gear_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.color_sensor = ColorSensor(port=color_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def spin_gears(self, speed: float = 1000): while True: if Button.BEACON in self.ir_sensor.buttons( channel=self.ir_beacon_channel): self.gear_motor.run(speed=1000) else: self.gear_motor.stop() def change_screen_when_touched(self): while True: if self.touch_sensor.pressed(): self.screen.load_image(ImageFile.ANGRY) else: self.screen.load_image(ImageFile.FORWARD) def make_noise_when_seeing_black(self): while True: if self.color_sensor.color == Color.BLACK: self.speaker.play_file(file=SoundFile.OUCH) def main(self): self.speaker.play_file(file=SoundFile.YES) Process(target=self.make_noise_when_seeing_black).start() Process(target=self.spin_gears).start() Process(target=self.change_screen_when_touched).start() self.keep_driving_by_ir_beacon(speed=1000)
def run(): motor_b = Motor(Port.B) motor_c = Motor(Port.C) Gyro = GyroSensor(Port.S1) while Gyro.angle() <= 65: motor_c.run(900) motor_b.run(-900) motor_c.stop(Stop.BRAKE) motor_b.stop(Stop.BRAKE)
class Gripp3r(RemoteControlledTank): WHEEL_DIAMETER = 26 # milimeters AXLE_TRACK = 115 # milimeters def __init__( self, left_track_motor_port: Port = Port.B, right_track_motor_port: Port = Port.C, gripping_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): super().__init__( wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK, left_motor_port=left_track_motor_port, right_motor_port=right_track_motor_port, ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel) self.ev3_brick = EV3Brick() self.gripping_motor = Motor(port=gripping_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def grip_or_release_by_ir_beacon(self, speed: float = 500): if Button.BEACON in \ self.ir_sensor.buttons(channel=self.ir_beacon_channel): if self.touch_sensor.pressed(): self.ev3_brick.speaker.play_file(file=SoundFile.AIR_RELEASE) self.gripping_motor.run_time( speed=speed, time=1000, then=Stop.COAST, wait=True) else: self.ev3_brick.speaker.play_file(file=SoundFile.AIRBRAKE) self.gripping_motor.run(speed=-speed) while not self.touch_sensor.pressed(): pass self.gripping_motor.stop() while Button.BEACON in \ self.ir_sensor.buttons(channel=self.ir_beacon_channel): pass
class CuriosityRov3r(IRBeaconRemoteControlledTank, EV3Brick): WHEEL_DIAMETER = 35 # milimeters AXLE_TRACK = 130 # milimeters def __init__( self, left_motor_port: Port = Port.B, right_motor_port: Port = Port.C, medium_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, color_sensor_port: Port = Port.S3, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): super().__init__( wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK, left_motor_port=left_motor_port, right_motor_port=right_motor_port, ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel) self.medium_motor = Motor(port=medium_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.color_sensor = ColorSensor(port=color_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def spin_fan(self, speed: float = 1000): while True: if self.color_sensor.reflection() > 20: self.medium_motor.run(speed=speed) else: self.medium_motor.stop() def say_when_touched(self): while True: if self.touch_sensor.pressed(): self.screen.load_image(ImageFile.ANGRY) self.speaker.play_file(file=SoundFile.NO) self.medium_motor.run_time( speed=-500, time=3000, then=Stop.HOLD, wait=True) def main(self, speed: float = 1000): run_parallel( self.say_when_touched, self.spin_fan, self.keep_driving_by_ir_beacon)
class EV3Motor(OutEvent): def __init__(self, port, speed): OutEvent.__init__(self) assert (port != None) and (port in [ Port.A, Port.B, Port.C, Port.D ]), "[EV3Motor init] bad port value" self.port = port self.speed = speed self.motor = Motor(self.port) def declencher(self): self.motor.run(500)
class RoboDoz3r(RemoteControlledTank): WHEEL_DIAMETER = 24 # milimeters AXLE_TRACK = 100 # milimeters def __init__( self, left_motor_port: Port = Port.C, right_motor_port: Port = Port.B, shovel_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, ir_sensor_port: Port = Port.S4, tank_drive_ir_beacon_channel: int = 1, shovel_control_ir_beacon_channel: int = 4): super().__init__( wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK, left_motor_port=left_motor_port, right_motor_port=right_motor_port, polarity='inversed', ir_sensor_port=ir_sensor_port, ir_beacon_channel=tank_drive_ir_beacon_channel) self.ev3_brick = EV3Brick() self.shovel_motor = Motor(port=shovel_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.shovel_control_ir_beacon_channel = \ shovel_control_ir_beacon_channel def raise_or_lower_shovel_by_ir_beacon(self): """ If the channel 4 is selected on the IR remote then you can control raising and lowering the shovel on the RoboDoz3r. - Raise the shovel by either Up button - Raise the shovel by either Down button """ ir_beacon_button_pressed = \ set(self.ir_sensor.buttons( channel=self.shovel_control_ir_beacon_channel)) # raise the shovel if ir_beacon_button_pressed.intersection( {Button.LEFT_UP, Button.RIGHT_UP}): self.shovel_motor.run(speed=100) # lower the shovel elif ir_beacon_button_pressed.intersection( {Button.LEFT_DOWN, Button.RIGHT_DOWN}): self.shovel_motor.run(speed=-100) else: self.shovel_motor.hold()
def reverse(): motor = Motor(Port.D, Direction.CLOCKWISE) starttime = utime.ticks_ms() b = 0 while (not touch.pressed()) and (b < 3000): motor.run(360) currenttime = utime.ticks_ms() b = currenttime - starttime if motor.stalled(): break motor = Motor(Port.D, Direction.COUNTERCLOCKWISE) turn(1, (gg.angle() - anglecounter * 10))
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 Line_follow: def __init__(self, duration=0, wheel_diameter=55.5, axle_track=104): self.duration = duration self.wheel_diameter = wheel_diameter self.axle_track = axle_track self.ev3 = EV3Brick() self.left_motor, self.right_motor = Motor(Port.B), Motor(Port.C) self.line_sensor = ColorSensor(Port.S3) self.robot = DriveBase(self.left_motor, self.right_motor, wheel_diameter, axle_track) def follow(self): motor_speedlog = DataLog('error', 'integral', 'derivative', 'turn_rate', name='motor_speedlog', timestamp=True, extension='txt') black = 3 white = 62 threshold = (black + white) / 2 DRIVE_SPEED = 200 PROPORTIONAL_GAIN = 4.2 INTEGRAL_GAIN = 0.008 DERIVATIVE_GAIN = 0.01 integral = 0 derivative = 0 last_error = 0 while True: error = line_sensor.reflection() - threshold integral = integral + error derivative = error - last_error turn_rate = PROPORTIONAL_GAIN * error + INTEGRAL_GAIN + DERIVATIVE_GAIN + integral + DERIVATIVE_GAIN * derivative motor_speedlog.log(error, integral, derivative, turn_rate) self.left_motor.run(DRIVE_SPEED + turn_rate) self.right_motor.run(DRIVE_SPEED - turn_rate) last_error = error wait(10) def run(self): self.follow()
def run(): motor_b = Motor(Port.B) motor_c = Motor(Port.C) Gyro = GyroSensor(Port.S1) Gyro.reset_angle(0) motor_b.run_angle(500, 720, Stop.BRAKE, False) motor_c.run_angle(500, 720, Stop.BRAKE, True) wait(10) while Gyro.angle() <= 180: motor_c.run(100) motor_b.run(-100) wait(10) motor_b.run_angle(500, 720, Stop.BRAKE, False) motor_c.run_angle(500, 720, Stop.BRAKE, True)
class LineFollower: def __init__(self, controller): self.leftMotor = Motor(Port.B, positive_direction=Direction.COUNTERCLOCKWISE) self.rightMotor = Motor(Port.C, positive_direction=Direction.COUNTERCLOCKWISE) self.lightSensor = ColorSensor(Port.S3) self.controller = controller def run(self): while True: light = self.lightSensor.reflection() left, right = self.controller.getPower(float(light)) message = 'Z:%d L:%d R:%d' % (light, left, right) ev3.screen.print(message) self.leftMotor.run(left) self.rightMotor.run(right)
def main(): brick.sound.beep() sens1 = LegoPort(address = 'ev3-port:in1') sens1.mode = 'ev3-analog' utime.sleep(0.5) sensor_right = MySensor(Port.S1) sensor_left = MySensor(Port.S4) motor_right = Motor(Port.A) motor_left = Motor(Port.D) targetleft = 530 targetright = 250 KP = 3.75 KD = .3 KI = 0 left_prev_error = 0 right_prev_error = 0 left_sum_error = 0 right_sum_error = 0 leftspeed = 0 rightspeed = 0 while not Button.CENTER in brick.buttons(): print('left:') print(sensor_left.readvalue()) print('right:') print(sensor_right.readvalue()) #PID controller errorleft = sensor_left.readvalue() - targetleft print('left error:' + str(errorleft)) errorright = sensor_right.readvalue() - targetright print('right error:' str(errorright)) leftspeed = (errorleft * KP) + ((errorleft - left_prev_error) * KD) + (left_sum_error * KI) + 375 rightspeed = (errorright * KP) + ((errorright - right_prev_error) * KD) + (right_sum_error * KI) + 375 left_prev_error = errorleft right_prev_error = errorright left_sum_error += errorleft right_sum_error += errorright motor_left.run(leftspeed) motor_right.run(rightspeed)
def main(): brick.sound.beep() sens1 = LegoPort(address='ev3-ports:in4') # which port?? 1,2,3, or 4 #sens2 = LegoPort(address ='ev3-ports:in4') # which port?? 1,2,3, or 4 sens1.mode = 'ev3-analog' #sens2.mode = 'ev3-analog' utime.sleep(0.5) sensor_left = MySensor(Port.S4) # same port as above sensor_right = MySensor(Port.S2) # same port as above left_motor = Motor(Port.A) right_motor = Motor(Port.D) speed = 200 Kp = 3 speed = 250 Kd = 0.4 diff = 0 curr_gain = 0.8 last = [0, 0] while True: difflast = diff left_color = sensor_left.readvalue() right_color = sensor_right.readvalue() if last is [0, 0]: last = [left_color, right_color] left_color, right_color = left_color * curr_gain + ( last[0] * (1 - curr_gain)), right_color * curr_gain + (last[1] * (1 - curr_gain)) last = [left_color, right_color] diff = left_color - right_color deriv = diff - difflast # print(diff) # print(deriv) print("Left: {}, Right: {}, Diff: {}".format(left_color, right_color, diff)) controller = ((Kp * diff) + (Kd + deriv)) / 2 left_motor.run(speed + controller) right_motor.run(speed - controller)
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 Gripp3r(EV3Brick): WHEEL_DIAMETER = 26 AXLE_TRACK = 115 def __init__(self, left_motor_port: Port = Port.B, right_motor_port: Port = Port.C, grip_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): self.drive_base = DriveBase( left_motor=Motor(port=left_motor_port, positive_direction=Direction.CLOCKWISE), right_motor=Motor(port=right_motor_port, positive_direction=Direction.CLOCKWISE), wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK) self.drive_base.settings( straight_speed=750, # milimeters per second straight_acceleration=750, turn_rate=90, # degrees per second turn_acceleration=90) self.grip_motor = Motor(port=grip_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def keep_driving_by_ir_beacon( self, channel: int = 1, speed: float = 1000 # milimeters per second ): while True: ir_beacon_buttons_pressed = set( self.ir_sensor.buttons(channel=channel)) # forward if ir_beacon_buttons_pressed == {Button.LEFT_UP, Button.RIGHT_UP}: self.drive_base.drive( speed=speed, turn_rate=0 # degrees per second ) # backward elif ir_beacon_buttons_pressed == { Button.LEFT_DOWN, Button.RIGHT_DOWN }: self.drive_base.drive( speed=-speed, turn_rate=0 # degrees per second ) # turn left on the spot elif ir_beacon_buttons_pressed == { Button.LEFT_UP, Button.RIGHT_DOWN }: self.drive_base.drive( speed=0, turn_rate=-90 # degrees per second ) # turn right on the spot elif ir_beacon_buttons_pressed == { Button.LEFT_DOWN, Button.RIGHT_UP }: self.drive_base.drive( speed=0, turn_rate=90 # degrees per second ) # turn left forward elif ir_beacon_buttons_pressed == {Button.LEFT_UP}: self.drive_base.drive( speed=speed, turn_rate=-90 # degrees per second ) # turn right forward elif ir_beacon_buttons_pressed == {Button.RIGHT_UP}: self.drive_base.drive( speed=speed, turn_rate=90 # degrees per second ) # turn left backward elif ir_beacon_buttons_pressed == {Button.LEFT_DOWN}: self.drive_base.drive( speed=-speed, turn_rate=90 # degrees per second ) # turn right backward elif ir_beacon_buttons_pressed == {Button.RIGHT_DOWN}: self.drive_base.drive( speed=-speed, turn_rate=-90 # degrees per second ) # otherwise stop else: self.drive_base.stop() def grip_or_release_by_ir_beacon(self, speed: float = 500): while True: if Button.BEACON in self.ir_sensor.buttons( channel=self.ir_beacon_channel): if self.touch_sensor.pressed(): self.speaker.play_file(file=SoundFile.AIR_RELEASE) self.grip_motor.run_time(speed=speed, time=1000, then=Stop.BRAKE, wait=True) else: self.speaker.play_file(file=SoundFile.AIRBRAKE) self.grip_motor.run(speed=-speed) while not self.touch_sensor.pressed(): pass self.grip_motor.stop() while Button.BEACON in self.ir_sensor.buttons( channel=self.ir_beacon_channel): pass def main(self, speed: float = 1000): self.grip_motor.run_time(speed=-500, time=1000, then=Stop.BRAKE, wait=True) Thread(target=self.grip_or_release_by_ir_beacon).start() self.keep_driving_by_ir_beacon(speed=speed)
import time Vmoottori = Motor(Port.B, Direction.CLOCKWISE) Omoottori = Motor(Port.C, Direction.CLOCKWISE) variSensori = ColorSensor(Port.S2) # Play a sound #brick.sound.file("Taistelujaska.wav") va = True reitilla = False i = 0 laskuri = 0 while i < 50000: vari = variSensori.color() Vmoottori.run(-300) Omoottori.run(-300) time.sleep(0.05) if vari == 6: Vmoottori.run(200) Omoottori.run(-200) time.sleep(0.2) Vmoottori.run(-200) Omoottori.run(-200) time.sleep(1) Vmoottori.run(-200) Omoottori.run(200) time.sleep(0.5) i += 1 laskuri += 1 if laskuri > 30:
class Spik3r(EV3Brick): def __init__( self, sting_motor_port: Port = Port.D, go_motor_port: Port = Port.B, claw_motor_port: Port = Port.A, touch_sensor_port: Port = Port.S1, color_sensor_port: Port = Port.S3, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): self.sting_motor = Motor(port=sting_motor_port, positive_direction=Direction.CLOCKWISE) self.go_motor = Motor(port=go_motor_port, positive_direction=Direction.CLOCKWISE) self.claw_motor = Motor(port=claw_motor_port, positive_direction=Direction.CLOCKWISE) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel self.touch_sensor = TouchSensor(port=touch_sensor_port) self.color_sensor = ColorSensor(port=color_sensor_port) def sting_by_ir_beacon(self): while True: ir_buttons_pressed = set(self.ir_sensor.buttons(channel=self.ir_beacon_channel)) if ir_buttons_pressed == {Button.BEACON}: self.sting_motor.run_angle( speed=-750, rotation_angle=220, then=Stop.HOLD, wait=False) self.speaker.play_file(file=SoundFile.EV3) self.sting_motor.run_time( speed=-1000, time=1000, then=Stop.HOLD, wait=True) self.sting_motor.run_time( speed=1000, time=1000, then=Stop.HOLD, wait=True) while Button.BEACON in self.ir_sensor.buttons(channel=self.ir_beacon_channel): pass def be_noisy_to_people(self): while True: if self.color_sensor.reflection() > 30: for i in range(4): self.speaker.play_file(file=SoundFile.ERROR_ALARM) def pinch_if_touched(self): while True: if self.touch_sensor.pressed(): self.claw_motor.run_time( speed=500, time=1000, then=Stop.HOLD, wait=True) self.claw_motor.run_time( speed=-500, time=0.3 * 1000, then=Stop.HOLD, wait=True) def keep_driving_by_ir_beacon(self): while True: ir_buttons_pressed = set(self.ir_sensor.buttons(channel=self.ir_beacon_channel)) if ir_buttons_pressed == {Button.RIGHT_UP, Button.LEFT_UP}: self.go_motor.run(speed=910) elif ir_buttons_pressed == {Button.RIGHT_UP}: self.go_motor.run(speed=-1000) else: self.go_motor.stop() def main(self): self.screen.load_image(ImageFile.EVIL) run_parallel( self.be_noisy_to_people, self.sting_by_ir_beacon, self.pinch_if_touched, self.keep_driving_by_ir_beacon)
motorB = Motor(Port.B) motorC = Motor(Port.C) # 컬러 센서 선언 color_sensor1 = ColorSensor(Port.S1) color_sensor2 = ColorSensor(Port.S2) CRITERIA = 20 # 반사값 기준 설정 speed = 150 # 모터 속도 while True: if color_sensor1.reflection() > CRITERIA and color_sensor2.reflection( ) > CRITERIA: # 센서 2개 모두 선 위에 있지 않을 경우, 직진한다. motorB.run(speed) motorC.run(speed) elif color_sensor1.reflection() > CRITERIA and color_sensor2.reflection( ) <= CRITERIA: # 오른쪽 센서 1개만 선 위에 올라갔을 경우, 오른쪽으로 회전한다. motorB.run(speed) motorC.run(0) elif color_sensor1.reflection() <= CRITERIA and color_sensor2.reflection( ) > CRITERIA: # 왼쪽 센서 1개만 선 위에 올라갔을 경우, 왼쪽으로 회전한다. motorB.run(0) motorC.run(speed) elif color_sensor1.reflection() <= CRITERIA and color_sensor2.reflection(
#!/usr/bin/env pybricks-micropython from pybricks import ev3brick as brick from pybricks.hubs import EV3Brick from pybricks.ev3devices import Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor from pybricks.parameters import Port, Stop, Direction, Button, Color, SoundFile, ImageFile, Align from pybricks.tools import wait, StopWatch, DataLog from pybricks.robotics import DriveBase import time # 모터 선언 motorB = Motor(Port.B) motorC = Motor(Port.C) # 컬러 센서 선언 color_sensor = ColorSensor(Port.S1) # 반사값과 모터의 속도는 원하는 값으로 수정할 수 있다. # 단, 모터 속도가 너무 빠르면 반사값을 측정하는 주기가 길어져서 정확도가 낮아진다. while True: if color_sensor.reflection() < 30: # 반사값이 30보다 작다면, motorB.run(150) # 모터 B를 150의 속도로 동작하고 motorC.run(0) # 모터 C를 정지한다 else: # 반사값이 30 이상이라면, motorB.run(0) # 모터 B를 정지하고 motorC.run(150) # 모터 C를 150의 속도로 동작한다
# Then it sorts them by color. Then the process starts over and you can scan # and insert the next set of colored objects. while True: # Get the feed motor in the correct starting position. # This is done by running the motor forward until it stalls. This # 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.
class R3ptar: """ R3ptar can be driven around by the IR Remote Control, strikes when the Beacon button is pressed, and hisses when the Touch Sensor is pressed (inspiration from LEGO Mindstorms EV3 Home Edition: R3ptar: Tutorial #4) """ def __init__(self, steering_motor_port: Port = Port.A, driving_motor_port: Port = Port.B, striking_motor_port: Port = Port.D, touch_sensor_port: Port = Port.S1, ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): self.ev3_brick = EV3Brick() self.steering_motor = Motor(port=steering_motor_port, positive_direction=Direction.CLOCKWISE) self.driving_motor = Motor(port=driving_motor_port, positive_direction=Direction.CLOCKWISE) self.striking_motor = Motor(port=striking_motor_port, positive_direction=Direction.CLOCKWISE) self.touch_sensor = TouchSensor(port=touch_sensor_port) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def drive_by_ir_beacon( self, speed: float = 1000, # mm/s ): ir_beacons_pressed = \ set(self.ir_sensor.buttons(channel=self.ir_beacon_channel)) if ir_beacons_pressed == {Button.LEFT_UP, Button.RIGHT_UP}: self.driving_motor.run(speed=speed) elif ir_beacons_pressed == {Button.LEFT_DOWN, Button.RIGHT_DOWN}: self.driving_motor.run(speed=-speed) elif ir_beacons_pressed == {Button.LEFT_UP}: self.steering_motor.run(speed=-500) self.driving_motor.run(speed=speed) elif ir_beacons_pressed == {Button.RIGHT_UP}: self.steering_motor.run(speed=500) self.driving_motor.run(speed=speed) elif ir_beacons_pressed == {Button.LEFT_DOWN}: self.steering_motor.run(speed=-500) self.driving_motor.run(speed=-speed) elif ir_beacons_pressed == {Button.RIGHT_DOWN}: self.steering_motor.run(speed=500) self.driving_motor.run(speed=-speed) else: self.steering_motor.hold() self.driving_motor.stop() def strike_by_ir_beacon(self, speed: float = 1000): if Button.BEACON in \ self.ir_sensor.buttons(channel=self.ir_beacon_channel): self.striking_motor.run_time(speed=speed, time=1000, then=Stop.COAST, wait=True) self.striking_motor.run_time(speed=-speed, time=1000, then=Stop.COAST, wait=True) while Button.BEACON in \ self.ir_sensor.buttons(channel=self.ir_beacon_channel): pass def hiss_if_touched(self): if self.touch_sensor.pressed(): self.ev3_brick.speaker.play_file(file=SoundFile.SNAKE_HISS) def main(self, speed: float = 1000): """ R3ptar's main program performing various capabilities """ while True: self.drive_by_ir_beacon(speed=speed) self.strike_by_ir_beacon(speed=speed) self.hiss_if_touched() wait(1)
def BlueMission(): # Blue Run (Step Counter, Pull-Up Bar, Boccia Aim, Slide, Health Unit - 1) # DOWN BUTTON #!/usr/bin/env pybricks-micropython from pybricks.hubs import EV3Brick from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor) 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 # This program requires LEGO EV3 MicroPython v2.0 or higher. # Click "Open user guide" on the EV3 extension tab for more information. #define your variables ev3 = EV3Brick() left_motor = Motor(Port.C) right_motor = Motor(Port.B) medium_motor = Motor(Port.A) large_motor = Motor(Port.D) wheel_diameter = 56 axle_track = 115 line_sensor = ColorSensor(Port.S2) line_sensor1 = ColorSensor(Port.S3) robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track) # Go towards the step counter mission from base robot.settings(800) # Speed Change robot.straight(650) robot.stop(Stop.BRAKE) wait(20) # Slow the robot down to succesfully push the step counter. robot.settings(200) # Slowly pushes the step counter by going backward and forward a couple times to increase reliability. robot.straight(230) robot.straight(-20) robot.straight(50) robot.stop(Stop.BRAKE) #robot.straight(-45) #robot.stop(Stop.BRAKE) #robot.straight(120) #robot.stop(Stop.BRAKE) robot.straight(-60) robot.stop(Stop.BRAKE) # The robot then turns and goes backwards until the right color sensor detects black. #robot.settings(250,300,250,300) robot.turn(45) robot.straight(-100) while True: robot.drive(-100,0) if line_sensor.color() == Color.BLACK: robot.stop(Stop.BRAKE) break #The large motor attatchment comes down at the same time the robot takes a turn towards #the black line underneath the pull up bar left_motor.run_angle(50,-300,then=Stop.HOLD, wait=True) # The robot then goes straight towards the line under the pull-up bar. robot.straight(120) robot.stop(Stop.BRAKE) # Robot continues to go forwards until the left color sensor detects black. while True: robot.drive(115,0) if line_sensor.color() == Color.BLACK: robot.stop(Stop.BRAKE) break right_motor.run_angle(100,150,then=Stop.HOLD, wait=True) # The robot turns using the right motor until it detects black. while True: right_motor.run(100) if line_sensor.color() == Color.BLACK: robot.stop(Stop.BRAKE) break robot.straight(-90) large_motor.run_angle(100,150,then=Stop.HOLD, wait=True) robot.stop(Stop.BRAKE) robot.stop(Stop.BRAKE) while True: right_motor.run(40) if line_sensor.color() == Color.BLACK: robot.stop(Stop.BRAKE) break robot.stop(Stop.BRAKE) ev3.speaker.beep() BLACK = 9 WHITE = 85 threshold = (BLACK + WHITE) / 2 # Set the drive speed at 100 millimeters per second. DRIVE_SPEED = 100 # Set the gain of the proportional line controller. This means that for every PROPORTIONAL_GAIN = 1.2 runWhile = True robot.reset() ev3.speaker.beep() while True: # Calculate the deviation from the threshold. deviation = line_sensor.reflection() - threshold # Calculate the turn rate. turn_rate = PROPORTIONAL_GAIN * deviation # Set the drive base speed and turn rate. robot.drive(DRIVE_SPEED, turn_rate) wait(10) print(line_sensor1.color()) if line_sensor1.color() == Color.BLACK: robot.stop(Stop.BRAKE) break robot.stop(Stop.BRAKE) robot.stop(Stop.BRAKE) large_motor.run_angle(-150, 150, then=Stop.HOLD, wait=False) robot.turn(20) robot.stop(Stop.BRAKE) robot.settings(800) robot.straight(280) ev3.speaker.beep(3) while True: robot.drive(-115,0) if line_sensor.color() == Color.BLACK: ev3.speaker.beep(10) robot.stop(Stop.BRAKE) break robot.stop(Stop.BRAKE) # robot.straight(-10) robot.stop(Stop.BRAKE) robot.turn(50) # left_motor.run_angle(100, 150) ''' large_motor.run_angle(30,-20,then=Stop.HOLD, wait=False) robot.turn(10) robot.stop(Stop.BRAKE) large_motor.run_angle(100, -50, then=Stop.HOLD, wait=False) robot.turn(90) robot.stop(Stop.BRAKE) ''' BLACK = 9 WHITE = 85 threshold = (BLACK + WHITE) / 2 # Set the drive speed at 100 millimeters per second. DRIVE_SPEED = 100 # Set the gain of the proportional line controller. This means that for every PROPORTIONAL_GAIN = 1.2 runWhile = True robot.reset() ev3.speaker.beep() while True: # Calculate the deviation from the threshold. deviation = line_sensor.reflection() - threshold # Calculate the turn rate. turn_rate = PROPORTIONAL_GAIN * deviation # Set the drive base speed and turn rate. robot.drive(DRIVE_SPEED, turn_rate) wait(10) print(line_sensor.color()) if robot.distance() >= 500: robot.stop(Stop.BRAKE) break ev3.speaker.beep(3) while True: robot.drive(40,0) if line_sensor1.color() == Color.BLACK: robot.stop(Stop.BRAKE) break robot.stop(Stop.BRAKE) ev3.speaker.beep() robot.straight(30) robot.turn(-100) robot.straight(70) large_motor.run_angle(600,150,then=Stop.HOLD, wait=True) while True: robot.drive(-50, 0) if line_sensor1.color() == Color.BLACK: robot.stop(Stop.BRAKE) break robot.stop(Stop.BRAKE) right_motor.run_angle(600,500,then=Stop.HOLD,wait=True) robot.straight(20) BLACK = 9 WHITE = 85 threshold = (BLACK + WHITE) / 2 # Set the drive speed at 100 millimeters per second. DRIVE_SPEED = 100 # Set the gain of the proportional line controller. This means that for every PROPORTIONAL_GAIN = 1.2 runWhile = True robot.reset() ev3.speaker.beep() while True: # Calculate the deviation from the threshold. deviation = line_sensor1.reflection() - threshold # Calculate the turn rate. turn_rate = PROPORTIONAL_GAIN * deviation # Set the drive base speed and turn rate. robot.drive(DRIVE_SPEED, turn_rate) wait(10) print(line_sensor1.color()) if robot.distance() >= 580: robot.stop(Stop.BRAKE) break robot.stop(Stop.BRAKE) while True: robot.drive(50, 0) if line_sensor.color() == Color.BLACK: robot.stop(Stop.BRAKE) break robot.stop(Stop.BRAKE) ev3.speaker.beep(3) robot.turn(-45) robot.stop(Stop.BRAKE) robot.straight(30) large_motor.run_angle(1000,-150,then=Stop.HOLD, wait=True) robot.straight(-40) large_motor.run_angle(1000,150,then=Stop.HOLD, wait=True) robot.straight(40) large_motor.run_angle(1000,-150,then=Stop.HOLD, wait=True) robot.straight(-115) robot.turn(95) robot.straight(420) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100) robot.turn(-100) robot.turn(100)
def BlueMission(): #!/usr/bin/env pybricks-micropython from pybricks.hubs import EV3Brick from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor) 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 # This program requires LEGO EV3 MicroPython v2.0 or higher. # Click "Open user guide" on the EV3 extension tab for more information. #define your variables ev3 = EV3Brick() left_motor = Motor(Port.C) right_motor = Motor(Port.B) medium_motor = Motor(Port.A) large_motor = Motor(Port.D) wheel_diameter = 56 axle_track = 115 line_sensor = ColorSensor(Port.S2) line_sensor1 = ColorSensor(Port.S3) robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track) #go front towards the step counter robot.straight(650) robot.stop(Stop.BRAKE) wait(20) #makes the robot go slower robot.settings(40) #slowly pushes the step counter by going back and front 2 times robot.straight(140) robot.stop(Stop.BRAKE) robot.straight(-45) robot.stop(Stop.BRAKE) robot.straight(120) robot.stop(Stop.BRAKE) robot.settings(100) robot.straight(-30) robot.stop(Stop.BRAKE) #the robot then turns and goes backwards robot.turn(45) robot.straight(-100) # the robot then goes back until the right color sensor detects back while True: robot.drive(-30, 0) if line_sensor.color() == Color.BLACK: robot.stop(Stop.BRAKE) break #the large motor attatchment comes down at the same time the robot takes a turn towards the black line underneath the pull up bar large_motor.run_angle(50, 170, then=Stop.HOLD, wait=False) left_motor.run_angle(50, -300, then=Stop.HOLD, wait=True) #the robot then goes straight towards that line robot.straight(120) robot.stop(Stop.BRAKE) #robot continues to go forwards until the left color sensor detects black while True: robot.drive(30, 0) if line_sensor.color() == Color.BLACK: robot.stop(Stop.BRAKE) break right_motor.run_angle(50, 150, then=Stop.HOLD, wait=True) #the robot then turns with the right motor until it detects black while True: right_motor.run(85) if line_sensor.color() == Color.BLACK: robot.stop(Stop.BRAKE) break #follows the line underneath the pull up bar until the leftsensor detects black BLACK = 9 WHITE = 85 threshold = (BLACK + WHITE) / 2 # Set the drive speed at 100 millimeters per second. DRIVE_SPEED = 100 # Set the gain of the proportional line controller. This means that for every PROPORTIONAL_GAIN = 1.2 runWhile = True robot.reset() while True: # Calculate the deviation from the threshold. deviation = line_sensor.reflection() - threshold # Calculate the turn rate. turn_rate = PROPORTIONAL_GAIN * deviation # Set the drive base speed and turn rate. robot.drive(DRIVE_SPEED, turn_rate) wait(10) print(line_sensor.color()) if line_sensor1.color() == Color.BLACK: robot.stop(Stop.BRAKE) break #the robot then turns towards the boccia aim and moves straight to push it towards the target and finishes the misison robot.straight(100) #after line following, it goes straight for 100 mm robot.turn(50) robot.straight(100) robot.straight(-30) large_motor.run_angle(100, -65) robot.straight(-60) #the robot then takes a turn (at the same time bringing the attatchment down) towards the slide mission and completes the mission large_motor.run_angle(50, 80, then=Stop.HOLD, wait=False) robot.turn(-195) robot.straight(165) large_motor.run_angle(300, -120, then=Stop.HOLD, wait=True) robot.straight(-30) large_motor.run_angle(200, 120, then=Stop.HOLD, wait=True) ## The robot moves straight towards the mission, getting ready to attempt to push the slide figures off once more. (In case it didn't work before.) robot.straight(30) large_motor.run_angle(300, -120, then=Stop.HOLD, wait=True) robot.straight(-50) '''
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor) from pybricks.parameters import (Port, Stop, Direction, Button, Color, SoundFile, ImageFile, Align) from pybricks.tools import print, wait, StopWatch from pybricks.robotics import DriveBase encendido = False # Write your program here brick.sound.beep() # Reproduce un pitido. brick.sound.beep() # Inicializa un motor en el puerto B. test_motor = Motor(Port.B) # Enciende el motor a una rapidez de 500 grados por segundo (º/s). Hasta girar un ángulo de 90 grados. #test_motor.run_target(500, 90) # Reproducir otro pitido. while True: if Button.LEFT in brick.buttons(): #encendido = True test_motor.run(500) if Button.RIGHT in brick.buttons(): #encendido = False test_motor.stop(Stop.BRAKE) print (brick.buttons()) # Esta vez con un tono más alto (1000 Hz) y una duración más larga (500 ms). brick.sound.beep(1000, 2000, 100)
SoundFile, ImageFile, Align) from pybricks.tools import print, wait, StopWatch from pybricks.robotics import DriveBase # Write your program here motorA = Motor(Port.A) motorC = Motor(Port.C) robot = DriveBase(motorA, motorC, 56, 114) gs = GyroSensor(Port.S4) x = 0 while x < 2: print("Side 1") robot.drive_time(500, 0, 2000) motorA.run(250) motorC.run(-250) gs.reset_angle(0) while gs.angle() >= -75: wait(50) print("Gyro Angle :", gs.angle()) if gs.angle() <= -75: robot.stop(Stop.BRAKE) robot.stop(Stop.BRAKE) robot.drive_time(500, 0, 3500) print("side 2")
motor = Motor(Port.D, Direction.CLOCKWISE) starttime = utime.ticks_ms() b = 0 while (not touch.pressed()) and (b < 3000): motor.run(360) currenttime = utime.ticks_ms() b = currenttime - starttime if motor.stalled(): break motor = Motor(Port.D, Direction.COUNTERCLOCKWISE) turn(1, (gg.angle() - anglecounter * 10)) def turn(dir, ang): if dir == 1: frontmotor.run_angle(100, ang) else: frontmotor.run_angle(100, -ang) while True: print("angle", gg.angle()) motor.run(360) if dist.distance() < 100 or motor.stalled(): motor.stop() reverse() anglecounter += 1 print(gg.angle() - anglecounter * 10) utime.sleep(10)
left_up_motor = Motor(Port.A, positive_direction=Direction.COUNTERCLOCKWISE) right_up_motor = Motor(Port.B, positive_direction=Direction.COUNTERCLOCKWISE) left_down_motor = Motor(Port.C, positive_direction=Direction.CLOCKWISE) right_down_motor = Motor(Port.D, positive_direction=Direction.CLOCKWISE) Gyro = GyroSensor(Port.S1, positive_direction=Direction.CLOCKWISE) Gyro.reset_angle(0) for i in range(3): Gyro_angle = Gyro.angle() #Gyro_speed = Gyro.speed() print('Gyro angle: ', Gyro_angle) #print('Gyro speed: ', Gyro_speed) left_up_motor.run(300) right_up_motor.run(300) left_down_motor.run(300) right_down_motor.run(300) time.sleep(1) for i in range(5): Gyro_angle = Gyro.angle() #Gyro_speed = Gyro.speed() print('Gyro angle: ', Gyro_angle) #print('Gyro speed: ', Gyro_speed) left_up_motor.run(300) right_up_motor.run(-300) left_down_motor.run(300) right_down_motor.run(-300) time.sleep(1)