class Paper: def __init__(self): self.baseSpeed = 40 self.__r = 0.713 # x = 4.85, y = 6.80, x / y == 0.713 self.__m = LargeMotor(OUTPUT_C) def scroll(self, d, speed=1): if d == 0: return self.__m.on_for_rotations(SpeedPercent(self.baseSpeed * speed * self.__r), -d * self.__r, block=False) def scrollOut(self): # 把纸张送出去 pass def loadPaper(self): # 滚动到读取到纸张的位置,如果读到纸张返回True,不然返回False pass def waitScroll(self, t=None): # 等待滚动完成 self.__m.wait_until_not_moving(t)
def findTrack(): mLeft = LargeMotor(OUTPUT_B) mRight = LargeMotor(OUTPUT_C) drive.on_for_rotations(SpeedPercent(30), SpeedPercent(30), -0.2) sleep(0.2) mLeft.on_for_rotations(SpeedPercent(75), -0.5) sleep(0.5) sound.tone(300, 200)
def test_motor_on_for_rotations(self): clean_arena() populate_arena([('large_motor', 0, 'outA')]) m = LargeMotor() # simple case m.on_for_rotations(75, 5) self.assertEqual(m.speed_sp, int(round(0.75 * 1050))) self.assertEqual(m.position_sp, 5 * 360)
class Pen: def __init__(self): self.__udm = MediumMotor(OUTPUT_B) # up and down motor self.__lrm = LargeMotor(OUTPUT_A) self.isUp = False self.loading = False self.baseSpeed = 40 self.ll = 0 self.lr = 5 pass def up(self, d=0.6): self.__udm.on_for_rotations(SpeedPercent(75), d) self.isUp = True def down(self, d=0.6): # 放下笔 self.__udm.on_for_rotations(SpeedPercent(75), -d) self.isUp = False def load(self): if self.loading: return self.loading = True self.__udm.on_for_rotations(SpeedPercent(75), 4) def loaded(self): if not self.loading: return self.__udm.on_for_rotations(SpeedPercent(75), -4) self.loading = False def adjustUpDown(self, angle): # 调整放下笔的角度,angle正数为放下,负数为抬起 pass def move(self, d, speed=1): # 笔移动距离d,正数向右,负数向左 if d == 0: return self.__lrm.on_for_rotations(SpeedPercent(self.baseSpeed * speed), d, block=False) def moveToLeft(self): # 移动笔的位置到最左边,用于结束绘制后移动到最左边 pass def waitMove(self, t=None): # 等待笔左移右移结束 self.__lrm.wait_until_not_moving(t)
def test_single_motor(output): motor = LargeMotor(output) # motor.command = LargeMotor.COMMAND_RUN_FOREVER # for command in motor.commands: # print('Motor at {} set to {}'.format(output, command)) # motor.command = command motor.on_for_seconds(SpeedPercent(100), 5) # print_and_wait(motor) motor.on_for_rotations(SpeedPercent(30), 0.5) # print_and_wait(motor) motor.on_for_degrees(SpeedPercent(30), 45) # print_and_wait(motor) motor.on_to_position(SpeedPercent(30), 5)
def make_drink(order, length): _id = order["_id"] name = order["name"] tea = order["options"]["tea"] sugar = order["options"]["sugar"] ice = order["options"]["ice"] console.text_at( "Making Order for " + name + "\n" + tea + " " + str(sugar) + "%" + " " + str(ice) + "%" + "\nQueue Size: " + str(length), column=mid_col, row=mid_row, alignment=alignment, reset_console=True, ) sound = Sound() sound.speak("Dispensing boba") # dispense boba m = LargeMotor(OUTPUT_B) m.on_for_rotations(SpeedPercent(75), 10) sound.speak("Dispensing " + tea) # dispense liquid m = LargeMotor(OUTPUT_A) m.run_forever(speed_sp=1000) sleep(10) m.stop() s = name + ", your boba drink is finished. Please come pick it up" console.text_at(s, column=mid_col, row=mid_row, alignment=alignment, reset_console=True) sound.speak(s) requests.patch(URL + "/queue/" + _id, json={})
def test_motor_on_for_rotations(self): clean_arena() populate_arena([('large_motor', 0, 'outA')]) m = LargeMotor() # simple case m.on_for_rotations(75, 5) self.assertEqual(m.speed_sp, int(round(0.75 * 1050))) self.assertEqual(m.position_sp, 5 * 360) # None speed with self.assertRaises(ValueError): m.on_for_rotations(None, 5) # None distance with self.assertRaises(ValueError): m.on_for_rotations(75, None)
#!/usr/bin/env micropython from ev3dev2.motor import LargeMotor, OUTPUT_B LARGE_MOTOR = LargeMotor(address=OUTPUT_B) LARGE_MOTOR.on_for_seconds(speed=50.0, seconds=4.0, block=True, brake=True) LARGE_MOTOR.on_for_seconds(speed=100.0, seconds=4.0, block=True, brake=True) LARGE_MOTOR.on_for_seconds(speed=-100.0, seconds=4.0, block=True, brake=True) LARGE_MOTOR.on_for_rotations(speed=100.0, rotations=5.0, block=True, brake=True)
#!/usr/bin/env python3 from ev3dev2.motor import LargeMotor from time import sleep lm = LargeMotor() lm.on(speed=50, brake=True, block=False) sleep(1) lm.off() sleep(1) lm.on_for_seconds(speed=50, seconds=2, brake=True, block=True) sleep(1) lm.on_for_rotations(50, 3) sleep(1) lm.on_for_degrees(50, 90) sleep(1) lm.on_to_position(50, 180) sleep(1)
class Robot: def __init__(self, sensorList=[]): try: self.tank = MoveTank(OUTPUT_B, OUTPUT_C) self.outputList = [OUTPUT_B, OUTPUT_C] except: self.tank = None try: self.cs = ColorSensor() except: self.cs = None try: self.gyro = GyroSensor() except: self.gyro = None try: self.ultrasonicSensor = UltrasonicSensor() except: self.ultrasonicSensor = None try: self.large = LargeMotor(OUTPUT_D) self.outputList.append(OUTPUT_D) except: self.large = None try: self.medium = MediumMotor(OUTPUT_D) self.outputList.append(OUTPUT_D) except: self.medium = None # note: this function doesn quite work yet def turn(self, degree, leftmotor, rightmotor): if self.gyro is None: print("Gyro Needed For All Uses Of Turn") sys.exit(1) if self.tank is None: print("Tank Needed For All Uses Of Turn") sys.exit(1) self.tank.on(leftmotor, rightmotor) #self.gyro.reset() self.gyro.wait_until_angle_changed_by(degree) self.tank.off() def flashLEDs(self, color): my_leds = Leds() my_leds.all_off() my_leds.set_color("LEFT", color) my_leds.set_color("RIGHT", color) my_leds.all_off() my_leds.set_color("LEFT", "GREEN") my_leds.set_color("RIGHT", "GREEN") def moveUntilDistanceAway(self, distance, speed): ''' the function makes the robot move until it is a certain distance away from an object distance is how far away the ultrasonic sensor is from an object ''' if self.tank is None: print("Tank Needed For All Uses Of moveUntilDistanceAway") sys.exit(1) if self.ultrasonicSensor != None: print("Distance:", distance) while self.ultrasonicSensor.distance_centimeters_continuous > distance: print("Distance:", self.ultrasonicSensor.distance_centimeters_continuous) self.tank.on(SpeedPercent(10), SpeedPercent(10)) self.tank.on(SpeedPercent(speed), SpeedPercent(speed)) self.tank.off() else: print("Error with ultrasonic sensor!") def followLine(self, onLeft, followDistance): ''' onLeft, the first perameter, is a True/False value that will make the robot run on the left or right side of the line. make it True for left and False for Right ''' if self.tank is None: print("Tank Needed For All Uses Of followLine") sys.exit(1) angleMult = 1 #this sets the variable angleMult to 1 if not onLeft: #If the perameter onLeft is defined as True, then the variable angleMult is 3 angleMult = 3 #setting angleMult to 3 makes the robot turn in a way so it follows the left side for loopcount in range(followDistance): #repeats 100: value = self.cs.reflected_light_intensity #value is defined as the color sensor's reflected light intensity print(value) #the value of value shows up on the screen if value < 50: #if value, the color sensor's light intensity, is less than fifty, the tank moves one way self.tank.on(SpeedPercent(10 * angleMult), SpeedPercent(30 / angleMult)) else: self.tank.on(SpeedPercent(30 / angleMult), SpeedPercent(10 * angleMult)) self.tank.off() def goToLine(self, color, range, speed): if self.tank is None: print("Tank Needed For All Uses Of goToLine") sys.exit(1) self.cs = ColorSensor() while self.cs.reflected_light_intensity < (color - range) or ( self.cs.reflected_light_intensity > color + range): self.tank.on(SpeedPercent(speed), SpeedPercent(speed)) self.tank.off() def moveMotor(self, speed, lorm, dist): if lorm == "M": self.medium.on_for_rotations(SpeedPercent(speed), -dist) time.sleep(0.5) self.medium.on_for_rotations(SpeedPercent(speed), dist) if lorm == "L": self.large.on_for_rotations(SpeedPercent(speed), -dist) time.sleep(0.5) self.large.on_for_rotations(SpeedPercent(speed), dist) def moveForwardRot(self, rotations, speed): if self.tank is None: print("Tank Needed For All Uses Of moveForwardRot") sys.exit(1) self.tank.on_for_rotations(speed, speed, rotations) self.tank.off() def moveForwardCm(self, centimeters, speed, diam): circ = math.pi * diam if self.tank is None: print("Tank Needed For All Uses Of moveForwardCm") sys.exit(2) self.tank.on_for_rotations(speed, speed, float(centimeters) / circ) self.tank.off() def stopAll(self): self.tank.off() try: for out in self.outputList: m = Motor(out) m.stop() except: pass
def motor_test(): m = LargeMotor(OUTPUT_D) m.on_for_rotations(SpeedPercent(75), 5)
from ev3dev2.motor import LargeMotor, OUTPUT_A, OUTPUT_B, SpeedPercent, MoveTank m = LargeMotor(OUTPUT_A) m.on_for_rotations(SpeedPercent(75), 5)
TOUCH_SENSOR = TouchSensor(address=INPUT_1) COLOR_SENSOR = ColorSensor(address=INPUT_2) IR_SENSOR = InfraredSensor(address=INPUT_4) SPEAKER = Sound() while True: if COLOR_SENSOR.color == ColorSensor.COLOR_RED: MEDIUM_MOTOR.on_for_rotations(speed=100, rotations=3, block=True, brake=True) elif COLOR_SENSOR.color == ColorSensor.COLOR_YELLOW: LEG_MOTOR_RIGHT.on_for_rotations(speed=100, rotations=3, block=True, brake=True) SPEAKER.play_file(wav_file='/home/robot/sound/Error alarm.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) elif COLOR_SENSOR.color == ColorSensor.COLOR_GREEN: if IR_SENSOR.proximity <= 10: LEG_MOTOR_LEFT.on_for_seconds(speed=-91, seconds=1, brake=True, block=True) elif COLOR_SENSOR.color == ColorSensor.COLOR_BLUE: LEG_MOTOR_LEFT.on_for_seconds(speed=-91,
for i in range(5): MEDIUM_MOTOR.on_for_seconds( speed=75, seconds=0.2, block=True, brake=True) MEDIUM_MOTOR.on_for_seconds( speed=-75, seconds=0.2, block=True, brake=True) SPEAKER.play_file( wav_file='/home/robot/sound/Blip 3.wav', volume=100, play_type=Sound.PLAY_WAIT_FOR_COMPLETE) GO_MOTOR.on_for_rotations( speed=-100, rotations=2, brake=True, block=True) GO_MOTOR.on_for_rotations( speed=100, rotations=2, brake=True, block=True)
sleep(1) lm.on_for_seconds(speed=SpeedDPM(36000), seconds=3) # DPM(degrees per minute) 분당 36000도 sleep(1) #endregion #region 3.시간당 회전수로 제어 lm.on_for_seconds(speed=SpeedRPS(1), seconds=2) # RPS(rotations per second) 초당 1바퀴를 도는 속도로 seconds 초 동안 회전 sleep(1) lm.on_for_seconds(speed=SpeedRPM(100), seconds=3) # RPM(rotations per minute) 분당 100바퀴를 도는 속도 seconds 초 동안 회전 sleep(1) #endregion #endregion #region 바퀴 회전으로 제어 => on_for_rotations(speed, rotations, brake=True, block=True) #region 1.모터의 정격 스피드의 비율로 동작 lm.on_for_rotations(speed=50, rotations=3) # 정격 최대 속도(1050 deg/s)의 50%의 속도로 3바퀴 회전 sleep(1) lm.on_for_rotations(50, 3) # 매개 변수 이름을 명시하지 않아도 된다. sleep(1) #endregion #region 2.시간당 지정된 스피드로 rotations 바퀴만큼 회전 lm.on_for_rotations(speed=SpeedDPS(500), rotations=3) # DPS(degrees per second) 초당 500도를 도는 속도로 3바퀴 회전 sleep(1) lm.on_for_rotations(speed=SpeedRPS(1), rotations=3) # RPS(rotations per second) 초당 1 바퀴를 도는 속도로 3바퀴 회전 sleep(1) #endregion #endregion #region break, block # break : True 인 경우 모터가 동작을 완료하면 모터를 고정위치에 붙잡는다.
class ALBERT(object): def __init__(self): # ev3dev initialization self.leds = Leds() self.sound = Sound() self.arm_base = LargeMotor(OUTPUT_D) self.arm_shoulder = LargeMotor(OUTPUT_C) self.arm_wrist = LargeMotor(OUTPUT_B) self.arm_gripper = MediumMotor(OUTPUT_A) self.station = Workstation() self.color_sensor = ColorSensor(INPUT_1) self.find_indicator() self.rotate_base(STATION_COLOR) self.reset_all_motors() def find_indicator(self): ''' Search for a valid color indicator. ''' if self.color_sensor.color in VALID_COLORS: return self.arm_base.on(10) while self.color_sensor.color not in VALID_COLORS: pass self.arm_base.stop() def reset_all_motors(self): ''' Reset all motor tach counts. ''' self.arm_base.reset() self.arm_shoulder.reset() self.arm_wrist.reset() self.arm_gripper.reset() def rotate_base(self, color): ''' Rotate from one color indicator to another. Color order is: YELLOW <--> BLUE <--> RED STORE <--> STATION <--> STERILE ''' current_color = self.color_sensor.color if current_color == color: return direction = 1 if (current_color == STATION_COLOR and color == STERILE_COLOR) or current_color == STORE_COLOR: direction = -1 self.arm_base.on(SPEEDS[0] * direction, block=False) while self.color_sensor.color != color: pass self.arm_base.stop() self.arm_base.on_for_rotations(SPEEDS[0], direction * STRIPE_BIAS) def make_plate(self): ''' Sequence to make a plate. ''' self.get_plate() self.lift_lid() self.swab_plate() self.lower_lid() self.store_plate() def check_plate(self): ''' Sequence to check plate. ''' self.get_plate(from_storage=True, upside_down=True) self.move_to_keypoint(KP_UP_HORZ) refl = self.station.check_status() self.move_to_keypoint(KP_DOWN_HORZ) self.store_plate(is_upside_down=True) return refl def get_plate(self, from_storage=False, upside_down=False): ''' Sequence to get a plate and place it in the workstation. Post-conditions Gripper: WIDE Arm: DOWN Base: STATION ''' src = STORE_COLOR if from_storage else STERILE_COLOR self.move_to_keypoint(KP_UP_HORZ) self.rotate_base(src) self.set_gripper(GRIP_NARROW) self.move_to_keypoint(KP_DOWN_HORZ) self.set_gripper(GRIP_CLOSED) self.move_to_keypoint(KP_UP_HORZ) self.rotate_base(STATION_COLOR) dest_up = KP_UP_VERT_INVERT if upside_down else KP_UP_VERT dest_down = KP_DOWN_VERT_INVERT if upside_down else KP_DOWN_VERT self.move_to_keypoint(dest_up) self.move_to_keypoint(dest_down) self.set_gripper(GRIP_WIDE) self.move_to_keypoint(KP_DOWN_HORZ) def lift_lid(self): ''' Lift the dish lid. Pre-condition Gripper: WIDE Arm: DOWN Base: STATION Post-condition Gripper: CLOSED Arm: UP ''' self.move_to_keypoint(KP_DOWN_HORZ_LID) self.set_gripper(GRIP_CLOSED) self.move_to_keypoint(KP_UP_HORZ) def lower_lid(self): ''' Lower the dish lid. Pre-condition Gripper: CLOSED Arm: UP Base: STATION Post-condition Gripper: WIDE Arm: DOWN ''' self.move_to_keypoint(KP_DOWN_HORZ_LID) self.set_gripper(GRIP_WIDE) def swab_plate(self): ''' Call the Workstation swab routine. ''' self.station.swab() def store_plate(self, is_upside_down=False): ''' Sequence to store a plate. ''' src_down = KP_DOWN_VERT_INVERT if is_upside_down else KP_DOWN_VERT self.move_to_keypoint(src_down) self.set_gripper(GRIP_CLOSED) self.move_to_keypoint(KP_UP_HORZ) self.rotate_base(STORE_COLOR) self.move_to_keypoint(KP_DOWN_HORZ) self.set_gripper(GRIP_NARROW) self.move_to_keypoint(KP_UP_VERT) self.rotate_base(STATION_COLOR) self.set_gripper(GRIP_CLOSED) def move_to_keypoint(self, keypoint): ''' Move the should/wrist to a keypoint.''' # keypoint is [shoulder, wrist] with unit of rotations self.arm_shoulder.on_to_position( SPEEDS[1], keypoint[0] * self.arm_shoulder.count_per_rot) self.arm_wrist.on_to_position( SPEEDS[2], keypoint[1] * self.arm_wrist.count_per_rot) # pause to let things settle time.sleep(MOVE_PAUSE) def set_gripper(self, position): ''' Set the gripper position. ''' self.arm_gripper.on_to_position( 25, self.arm_gripper.count_per_rot * position) time.sleep(MOVE_PAUSE)
lm_move.stop() mm_move.stop() # reset gyro sensor gy.mode = 'GYRO-RATE' gy.mode = 'GYRO-ANG' log.info('prepare for the initial position') # 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)
#!/usr/bin/env python3 from ev3dev2.motor import LargeMotor, OUTPUT_B from ev3dev2.motor import SpeedDPS, SpeedRPS, SpeedRPM from time import sleep large_motor = LargeMotor(OUTPUT_B) # We'll make the motor turn 180 degrees # at speed 50 (525 dps for the large motor) large_motor.on_for_degrees(speed=50, degrees=180) # then wait one second sleep(1) # then – 180 degrees at 500 dps large_motor.on_for_degrees(speed=SpeedDPS(500), degrees=-180) sleep(1) # then 0.5 rotations at speed 50 (525 dps) large_motor.on_for_rotations(speed=50, rotations=0.5) sleep(1) # then – 0.5 rotations at 1 rotation per second (360 dps) large_motor.on_for_rotations(speed=SpeedRPS(1), rotations=-0.5)
# The current signature, x, and y values of the ball [Sig1, X1, Y1] = readValues() # A duplicate of the variables above, but will later be changed [Sig2, X2, Y2] = [Sig1, X1, Y1] #Let player know they can flick string2 = "Start" print(string2) sound.speak(string2) # This loop repeatedly checks whether the ball has been flicked and waits until it has while abs(X1 - X2) <= 8 and abs(Y1 - Y2) <= 8: #Current signature, x, and y values of the ball [Sig2, X2, Y2] = readValues() time.sleep(0.1) # Calculates the x-position of the ball when it reaches the goalie line Xe = -(((X1 - X2) * (Y1 - Ye)) / (Y1 - Y2)) + X1 # Limits the goalie to move within the resolution of the PixyMon (0-316 on the x-axis) if Xe > 316: Xe = 316 elif Xe < 0: Xe = 0 # Moves the goalie the distance it needs to move in pixels divided by 130, because the goalie moves # 130 pixels in one rotation. lm.on_for_rotations(speed=80, rotations=(Xe - BALL_START) / 130)
# TODO: Add code here colour_s1 = ColorSensor(INPUT_1) # sensor 1 for light intensity colour_s2 = ColorSensor(INPUT_2) # sensor 2 for light intensity lm = LargeMotor(OUTPUT_B); # left motor on PORT B rm = LargeMotor(OUTPUT_C); # right motor on PORT C a = 0.6; d = a * (colour_s2.reflected_light_intensity() - colour_s1.reflected_light_intensity()) while True: if (colour_s2.reflected_light_intensity() - colour_s1.reflected_light_intensity()) > d: lm.on_for_rotations(SpeedPercent(100), 2) # maybe change LEFT AND RIGHT rm.on_for_rotations(SpeedPercent(0), 2) elif (colour_s1.reflected_light_intensity() - colour_s2.reflected_light_intensity()) > d: lm.on_for_rotations(SpeedPercent(0), 2) # maybe change LEFT AND RIGHT rm.on_for_rotations(SpeedPercent(100), 2) elif ((colour_s2.reflected_light_intensity() - colour_s1.reflected_light_intensity()) <= d or (colour_s2.reflected_light_intensity() - colour_s1.reflected_light_intensity()) * -1 <= d): lm.on_for_rotations(SpeedPercent(100), 2) rm.on_for_rotations(SpeedPercent(100), 2)
#!/usr/bin/env python3 from ev3dev2.motor import LargeMotor, MediumMotor, OUTPUT_A, OUTPUT_B, SpeedPercent, MoveTank from ev3dev2.sensor import INPUT_1 from ev3dev2.sensor.lego import TouchSensor from ev3dev2.led import Leds m = LargeMotor("in1:i2c3:M2") m.on_for_rotations(SpeedPercent(100), 10)
from EV3Main import dispenser_scan from EV3Main import run_slave_motor from Network import host from ev3dev2.motor import LargeMotor, OUTPUT_C, SpeedPercent push = LargeMotor(OUTPUT_C) while True: dispenser_scan.dispense_and_scan(100, 100) run_slave_motor.send_signal push.on_for_rotations(SpeedPercent(100), 1)
# Set a variable for your right large motor, connected to port C r_motor = LargeMotor(OUTPUT_C) # 1. Move the motor with on() and sleep() methods # a. turning it on at speed 70 # b. telling the robot to wait 1 second # c. turning the robot off l_motor.on(70) sleep(1) l_motor.off() r_motor.on(70) sleep(1) r_motor.off() # 2. Move the motors with the on_for_seconds() method # - Speed 70% for 1 second r_motor.on_for_seconds(SpeedPercent(70), 1) l_motor.on_for_seconds(SpeedPercent(70), 1) # 3. Move the motors with the on_for_rotations() method # - Speed 70% for 2 wheel rotations l_motor.on_for_rotations(SpeedPercent(70), 2) r_motor.on_for_rotations(SpeedPercent(70), 2) # 3. Move the motors with the on_for_degrees() method # - Speed 70% 2 times 360 degrees (1 wheel rotation) r_motor.on_for_degrees(SpeedPercent(70), (360 * 2)) l_motor.on_for_degrees(SpeedPercent(70), (360 * 2))
class Rollers: """Rollers class witch allow managing paper. """ def __init__(self, power=30, prevent_paper_blocking=False): _debug(self, "Creating Rollers instance") self._default_power = power self._delta_in = 0 self._delta_out = 0 self._in = LargeMotor(OUTPUT_A) self._in.polarity = LargeMotor.POLARITY_NORMAL self._out = LargeMotor(OUTPUT_D) self._out.polarity = LargeMotor.POLARITY_INVERSED self._col = ColorSensor() self._col.mode = ColorSensor.MODE_COL_COLOR self._paper_taken = self._col.color == 6 self.reset(prevent_paper_blocking) def reset(self, prevent_paper_blocking=False, power=None): """Eject paper if present and prevent paper blocking :param prevent_paper_blocking: if true, roller will move to avoid paper blocking :param power: Power used to move rollers """ if power is None: power = self._default_power if self._paper_taken: self.eject_paper() elif prevent_paper_blocking: self._in.on_for_rotations(power, 3, block=False) self._out.on_for_rotations(power, 3) def up(self, power=None): """Move paper to the 'up' :param power: Power of the rotation """ if power is None: power = self._default_power self._in.on(power) self._out.on(power) def down(self, power=None): """Move paper to the 'down' :param power: Power of the rotation """ if power is None: power = self._default_power self._in.on(-power) self._out.on(-power) def stop(self): """ Stop moving rollers """ self._in.off() self._out.off() def save_energy(self): """Save energy and release motor's holding state""" self._in.off(False) self._out.off(False) @property def has_paper(self): """ Get the paper state :return True if paper present""" return self._paper_taken @property def position(self): """ Get rollers position :return: rollers position """ if not self.has_paper: return None return self._in.position - self._delta_in, self._out.position - self._delta_out @position.setter def position(self, value): """ Set Rollers position :param value: position reached""" self.go_to(value) def go_to(self, position, power=None, block=True, override=False): """Go to absolute position `position` :param position: Position Reached :param power: Power used to move :param block: If True, fonction will end at the end of the rotation :param override: if true, bypass limits""" if not self.has_paper: raise ValueError("There is no paper.") if power is None: power = self._default_power target_in = self._delta_in + position target_out = self._delta_out + position _debug(self, "Reached position is {}".format(position)) _debug(self, "Target In {}".format(target_in)) _debug(self, "Target Out {}".format(target_out)) if (not override) and (not 0 <= position <= 515): raise ValueError("Position is out of reachable bounds.") self._in.on_to_position(power, target_in, block=False) self._out.on_to_position(power, target_out, block=block) def move(self, value, power=None, block=True): """Move rollers (and paper if present) of `value` degrees :param value: Degrees to move :param power; Power used to move :param block: If True, fonction will end at the end of the rotation""" if power is None: power = self._default_power self._in.on_to_position(power, self._in.position + value, block=False) self._out.on_to_position(power, self._out.position + value, block=block) def up_limit(self, power=None): """Go to paper up limit :param power: Power used to move""" self.go_to(0, power) def down_limit(self, power=None): """Go to paper down limit :param power: Power used to move""" self.go_to(515, power) def take_paper(self, power=None, power_grip=15): """ Take paper into printer and stretch it :param power: Power used to take paper :param power_grip: Power used to stretch paper """ self.up(power) while self._col.color != 6: sleep(0.1) self.stop() self._out.on_for_seconds(power_grip, 1) self._paper_taken = self._col.color == 6 self.move(-130) sleep(0.2) self._delta_in = self._in.position self._delta_out = self._out.position def eject_paper(self, power=None): """ Eject paper :param power: Power used to eject paper """ self.up(power) sleep(0.5) while self._col.color == 6: sleep(0.1) sleep(0.5) self.stop() self._paper_taken = False self._delta_in = 0 self._delta_out = 0 @property def default_power(self): return self._default_power @default_power.setter def default_power(self, value): self._default_power = value
class Dinor3x: FAST_WALK_SPEED = 80 NORMAL_WALK_SPEED = 40 SLOW_WALK_SPEED = 20 def __init__(self, jaw_motor_port: str = OUTPUT_A, left_motor_port: str = OUTPUT_B, right_motor_port: str = OUTPUT_C, touch_sensor_port: str = INPUT_1, color_sensor_port: str = INPUT_3, ir_sensor_port: str = INPUT_4, ir_beacon_channel: int = 1): self.jaw_motor = MediumMotor(address=jaw_motor_port) self.left_motor = LargeMotor(address=left_motor_port) self.right_motor = LargeMotor(address=right_motor_port) self.tank_driver = MoveTank(left_motor_port=left_motor_port, right_motor_port=right_motor_port, motor_class=LargeMotor) self.steer_driver = MoveSteering(left_motor_port=left_motor_port, right_motor_port=right_motor_port, motor_class=LargeMotor) 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.roaring = False self.walk_speed = self.NORMAL_WALK_SPEED def roar_by_ir_beacon(self): """ Dinor3x roars when the Beacon button is pressed """ if self.ir_sensor.beacon(channel=self.ir_beacon_channel): self.roaring = True self.open_mouth() self.roar() elif self.roaring: self.roaring = False self.close_mouth() def change_speed_by_color(self): """ Dinor3x changes its speed when detecting some colors - Red: walk fast - Green: walk normally - White: walk slowly """ if self.color_sensor.color == ColorSensor.COLOR_RED: self.speaker.speak(text='RUN!', volume=100, play_type=Sound.PLAY_NO_WAIT_FOR_COMPLETE) self.walk_speed = self.FAST_WALK_SPEED self.walk(speed=self.walk_speed) elif self.color_sensor.color == ColorSensor.COLOR_GREEN: self.speaker.speak(text='Normal', volume=100, play_type=Sound.PLAY_NO_WAIT_FOR_COMPLETE) self.walk_speed = self.NORMAL_WALK_SPEED self.walk(speed=self.walk_speed) elif self.color_sensor.color == ColorSensor.COLOR_WHITE: self.speaker.speak(text='slow...', volume=100, play_type=Sound.PLAY_NO_WAIT_FOR_COMPLETE) self.walk_speed = self.SLOW_WALK_SPEED self.walk(speed=self.walk_speed) def walk_by_ir_beacon(self): """ Dinor3x walks or turns according to instructions from the IR Beacon - 2 top/up buttons together: walk forward - 2 bottom/down buttons together: walk backward - Top Left / Red Up: turn left on the spot - Top Right / Blue Up: turn right on the spot - Bottom Left / Red Down: stop - Bottom Right / Blue Down: calibrate to make the legs straight """ # forward if self.ir_sensor.top_left(channel=self.ir_beacon_channel) and \ self.ir_sensor.top_right: self.walk(speed=self.walk_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.walk(speed=-self.walk_speed) # turn left on the spot elif self.ir_sensor.top_left(channel=self.ir_beacon_channel): self.turn(speed=self.walk_speed) # turn right on the spot elif self.ir_sensor.top_right(channel=self.ir_beacon_channel): self.turn(speed=-self.walk_speed) # stop elif self.ir_sensor.bottom_left(channel=self.ir_beacon_channel): self.tank_driver.off(brake=True) # calibrate legs elif self.ir_sensor.bottom_right(channel=self.ir_beacon_channel): self.calibrate_legs() def calibrate_legs(self): self.tank_driver.on(left_speed=10, right_speed=20) self.touch_sensor.wait_for_released() self.tank_driver.off(brake=True) self.left_motor.on(speed=40) self.touch_sensor.wait_for_pressed() self.left_motor.off(brake=True) self.left_motor.on_for_rotations(rotations=-0.2, speed=50, brake=True, block=True) self.right_motor.on(speed=40) self.touch_sensor.wait_for_pressed() self.right_motor.off(brake=True) self.right_motor.on_for_rotations(rotations=-0.2, speed=50, brake=True, block=True) self.left_motor.reset() self.right_motor.reset() def walk(self, speed: float = 100): self.calibrate_legs() self.steer_driver.on(steering=0, speed=-speed) def turn(self, speed: float = 100): self.calibrate_legs() if speed >= 0: self.left_motor.on_for_degrees(degrees=180, speed=speed, brake=True, block=True) else: self.right_motor.on_for_degrees(degrees=180, speed=-speed, brake=True, block=True) self.tank_driver.on(left_speed=speed, right_speed=-speed) def close_mouth(self): self.jaw_motor.on_for_seconds(speed=-20, seconds=1, brake=False, block=False) def open_mouth(self): self.jaw_motor.on_for_seconds(speed=20, seconds=1, block=False, brake=False) def roar(self): self.speaker.play_file(wav_file='T-rex roar.wav', volume=100, play_type=Sound.PLAY_NO_WAIT_FOR_COMPLETE) self.jaw_motor.on_for_degrees(speed=40, degrees=-60, block=True, brake=True) for i in range(12): self.jaw_motor.on_for_seconds(speed=-40, seconds=0.05, block=True, brake=True) self.jaw_motor.on_for_seconds(speed=40, seconds=0.05, block=True, brake=True) self.jaw_motor.on_for_seconds(speed=20, seconds=0.5, brake=False, block=True) def main(self): self.close_mouth() while True: self.roar_by_ir_beacon() self.change_speed_by_color() self.walk_by_ir_beacon()
class MindstormsGadget(AlexaGadget): """ A Mindstorms gadget that can perform bi-directional interaction with an Alexa skill. """ def __init__(self): """ Performs Alexa Gadget initialization routines and ev3dev resource allocation. """ super().__init__() # Motors for the page turning. self.page_starter = LargeMotor(OUTPUT_A) self.page_turner = LargeMotor(OUTPUT_D) self.sound = Sound() self.leds = Leds() self._read_cmd = False # Start thread for sending Alexa messages threading.Thread(target=self._send_msg_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") print("{} 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") print("{} disconnected from Echo device".format(self.friendly_name)) 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 _send_msg_thread(self): """ Waits until a read command is sent from the Alexa device and then reads a page out of the book. """ count = 0 while True: if self._read_cmd: # Read text from the picture text = self._get_text_from_image() clean_text = text.replace('\n', ' ').replace('\r', ' ') #.replace("'", " ").replace('"', ' ').replace('\\u2022', ' ') sentences = self._split_into_word_sets(json.dumps(clean_text)) for sentence in sentences: sentence = sentence.replace('\\u2022', ' ').replace('\\u00a9', ' ') print(sentence) self._send_event(EventName.READ, {'text': sentence}) time.sleep(8) self._read_cmd = False # Wait time.sleep(1) def _ssh(self, host, cmd, user, password, timeout=30, bg_run=False): """SSH'es to a host using the supplied credentials and executes a command. Throws an exception if the command doesn't return 0. bgrun: run command in the background""" fname = tempfile.mktemp() fout = open(fname, 'wb') options = '-q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oPubkeyAuthentication=no' if bg_run: options += ' -f' ssh_cmd = 'ssh %s@%s %s "%s"' % (user, host, options, cmd) child = pexpect.spawn(ssh_cmd, timeout=timeout) child.expect(['password: '******'192.168.50.31' cd = 'python3 gocr.py' user = '******' psw = 'password' text = self._ssh(host, cd, user, psw, timeout=30, bg_run=False) return text def _chunk_word_array(self, words, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(words), n): yield words[i:i + n] def _combine_word_array(self, words): """Combine the words into sentences.""" sentences = [] for word_group in words: sentences.append(' '.join(word_group)) return sentences def _split_into_word_sets(self, text): """Split into words""" words = text.split() num_words = len(words) groups = self._chunk_word_array(words, 120) sentences = self._combine_word_array(groups) return sentences 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 == "turn": # Scrunch the page and turn the page. self.page_starter.on_for_rotations(SpeedPercent(20), -0.47) self.page_turner.on_for_rotations(SpeedPercent(30), 1) if control_type == "read": # Set variable so the read thread will send messages. self._read_cmd = True except KeyError: print("Missing expected parameters: {}".format(directive))
#!/usr/bin/env python3 from time import sleep from ev3dev2.motor import LargeMotor, OUTPUT_A, OUTPUT_D, SpeedPercent, MoveTank from ev3dev2.sensor import INPUT_1 from ev3dev2.sensor.lego import TouchSensor from ev3dev2.led import Leds from ev3dev2.sound import Sound # TODO: Add code here ts = TouchSensor() leds = Leds() leds.set_color("LEFT", "GREEN") leds.set_color("RIGHT", "GREEN") sound = Sound() sound.speak('Gorilla move right arm') m = LargeMotor(OUTPUT_D) m.on_for_rotations(SpeedPercent(10), 0.2) m.on_for_rotations(SpeedPercent(-10), 0.2) leds.set_color("LEFT", "RED") leds.set_color("RIGHT", "RED") sleep(0.01)
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.patrol_mode = False # Ev3dev initialization self.leds = Leds() self.sound = Sound() self.turnMotor = LargeMotor(OUTPUT_B) self.cardsMotor = LargeMotor(OUTPUT_D) # Start threads # threading.Thread(target=self._patrol_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 == "deal-initial": # Expected params: [game, playerCount] self._dealCardOnGameStart(payload["game"], int(payload["playerCount"])) if control_type == "deal-turn": # Expected params: [game, playerCount, playerTurn] self._dealCardOnGameTurn(payload["game"], int(payload["playerCount"]), int(payload["playerTurn"]), payload["gameCommand"]) except KeyError: print("Missing expected parameters: {}".format(directive), file=sys.stderr) def _dealCardOnGameStart(self, game, playerCount: int): """ Handles dealing the cards based on game type and the number of players """ print("Dealing cards: ({}, {})".format(game, playerCount), file=sys.stderr) if game in GameType.BLACKJACK.value: for i in range(playerCount): print("Dealing card to: ({})".format(i + 1), file=sys.stderr) self._moveToPlayer(i + 1, playerCount, False) self._dispenseCard() self._moveToBase(playerCount, playerCount) for i in range(playerCount): print("Dealing card to: ({})".format(i + 1), file=sys.stderr) self._moveToPlayer(i + 1, playerCount, False) self._dispenseCard() self._moveToBase(playerCount, playerCount) if game in GameType.UNO.value: for k in range(4): for i in range(playerCount): print("Dealing card to: ({})".format(i + 1), file=sys.stderr) self._moveToPlayer(i + 1, playerCount, False) self._dispenseCard() self._moveToBase(playerCount, playerCount) if game in GameType.SHUFFLE_CARDS.value: for k in range(5): self._moveToPlayer(1, 2, True) cardsToDispense = random.randint(1, 3) for k in range(cardsToDispense): self._dispenseCard() self._moveToBase(1, 2) self._moveToPlayer(2, 2, True) cardsToDispense = random.randint(1, 3) for k in range(cardsToDispense): self._dispenseCard() self._moveToBase(2, 2) def _dealCardOnGameTurn(self, game, playerCount: int, playerTurn: int, gameCommand): """ Handles dealing the card based on game type and the turn in the game """ print("Dealing cards: ({}, {}, {})".format(game, playerCount, playerTurn), file=sys.stderr) if game in GameType.BLACKJACK.value: if gameCommand in GameCommand.BLACKJACK_HIT.value: print("Dealing card to: ({})".format(playerTurn), file=sys.stderr) self._moveToPlayer(playerTurn, playerCount, True) self._dispenseCard() self._moveToBase(playerTurn, playerCount) if game in GameType.UNO.value: if gameCommand in GameCommand.UNO_DEAL_ONCE.value: print("Dealing card to: ({})".format(playerTurn), file=sys.stderr) cardsToDispense = random.randint(0, 3) if cardsToDispense > 0: for k in range(cardsToDispense): self._dispenseCard() if gameCommand in GameCommand.UNO_DEAL_TWICE.value: print("Dealing card to: ({})".format(playerTurn), file=sys.stderr) cardsToDispense = random.randint(0, 3) if cardsToDispense > 0: for k in range(cardsToDispense): self._dispenseCard() cardsToDispense = random.randint(0, 3) if cardsToDispense > 0: for k in range(cardsToDispense): self._dispenseCard() def _moveToPlayer(self, playerIndex: int, playerCount: int, oneTimeMove: bool): angle = -180 / playerCount turnAngle = angle print("Moving to player: ({}) out of ({})".format( playerIndex, playerCount), file=sys.stderr) if oneTimeMove == True: if playerIndex > 1: turnAngle = angle * (playerIndex - 1) if playerIndex == 1: turnAngle = 0 print("Angle: ({})".format(turnAngle), file=sys.stderr) self.turnMotor.on_for_degrees(SpeedPercent(15), turnAngle, True) time.sleep(.25) def _moveToBase(self, playerIndex: int, playerCount: int): print("Reset to base", file=sys.stderr) time.sleep(.50) angle = 180 / playerCount turnAngle = angle if playerIndex > 1: turnAngle = angle * (playerIndex - 1) if playerIndex == 1: turnAngle = 0 print("Angle: ({})".format(turnAngle), file=sys.stderr) self.turnMotor.on_for_degrees(SpeedPercent(15), turnAngle, True) def _dispenseCard(self): self.cardsMotor.on_for_rotations(SpeedPercent(-50), 0.5, True) time.sleep(.25) self.cardsMotor.on_for_rotations(SpeedPercent(-50), 0.2, True) time.sleep(.25) self.cardsMotor.on_for_rotations(SpeedPercent(50), 0.7, True)
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FLL Robot Framework project. -------------------------------------------------------------------------------- ''' from ev3dev2.motor import MediumMotor, LargeMotor, OUTPUT_B, OUTPUT_C largeMotor_Left = LargeMotor(OUTPUT_B) largeMotor_Right = LargeMotor(OUTPUT_C) mediumMotor = MediumMotor() # run these in parallel largeMotor_Left.on_for_rotations(speed=30, rotations=4, brake=True, block=False) largeMotor_Right.on_for_rotations(speed=40, rotations=3, brake=True, block=False) largeMotor_Left.wait_until_not_moving() largeMotor_Right.wait_until_not_moving() # run this after the previous have completed mediumMotor.on_for_seconds(speed=10, seconds=6)
#cs.mode = "COL-AMBIENT" t = time() while True: dist = us.distance_centimeters if time() - t > 1: print("dist:", dist) print("colr:", tuple(map(cs.value, [0, 1, 2]))) # print("colr:", cs.value()) t = time() if ts.is_pressed: speed = min(max(1, 100 - dist), 100) my_motor.on(speed) else: my_motor.stop() ''' rots = 10 my_motor.on_for_rotations(100, rots, block=False) print("Rotating {} times...".format(rots)) print("Motor holding:", my_motor.is_holding) my_motor.wait(lambda state: "holding" in state) print("Done!") print("Stopped at position", my_motor.position) # MoveSteering below - convenience for controlling two tires at once sleep(3) steering_drive = MoveSteering(OUTPUT_A, OUTPUT_B)
#!/usr/bin/env python3 import sys from ev3dev2.motor import LargeMotor, MediumMotor, MoveTank, MoveSteering from ev3dev2.motor import OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D from ev3dev2.sound import Sound # initialize objects sound = Sound() right_motor = LargeMotor(OUTPUT_B) left_motor = LargeMotor(OUTPUT_C) # print test phrase to brick and computer print("Hello my name is EV3!") # Display text on brick screen print("Hello my name is EV3!", file=sys.stderr) # Display text on computer # go forward 2 rotations at speed 100 sound.speak("Moving forward two rotations") right_motor.on_for_rotations(100, 2, block=False) left_motor.on_for_rotations(100, 2, block=True) # go forward 360 degrees at speed 100 sound.speak("Moving forward 360 degrees") right_motor.on_for_degrees(100, 360, block=False) left_motor.on_for_degrees(100, 360, block=True) # go forward for 3 seconds at speed 100 sound.speak("Moving forward for three seconds") right_motor.on_for_seconds(100, 3, block=False) left_motor.on_for_seconds(100, 3, block=True)