def main(): '''The main function of our program''' # set the console just how we want it reset_console() set_cursor(OFF) set_font('Lat15-Terminus24x12') print('How are you?') print("") print("Hello Selina.") print("Hello Ethan.") STUD_MM = 8 tank = MoveDifferential(OUTPUT_A, OUTPUT_B, EV3Tire, 16 * STUD_MM) motorLift = MediumMotor(OUTPUT_D) sound = Sound() # sound.speak('How are you master!') # sound.speak("I like my family") # sound.speak("I like my sister and i like my brother.") sound.beep() eye = InfraredSensor(INPUT_1) robot = Robot(tank, None, eye) botton = Button() while not botton.any(): distance = eye.distance(channel=1) heading = eye.heading(channel=1) print('distance: {}, heading: {}'.format(distance, heading)) motorLift.on_to_position(speed=40, position=-7200, block=True) #20 Rounds if distance is None: sound.speak("I am lost, there is no beacon!") else: if (distance < 14): tank.off() sound.speak("I am very close to the beacon!") motorLift.on_to_position(speed=40, position=7200, block=True) sound.speak("I had to get some more rubbish.") sound.speak("Please wait while I lift up my fork.") tank.turn_right(speed=20, degrees=random.randint(290, 340)) # random.randint(150, 210) tank.on_for_seconds(left_speed=20, right_speed=20, seconds=20) tank.turn_right(speed=20, degrees=330) motorLift.on_to_position(speed=40, position=0, block=True) elif distance >= 100: sound.speak("I am too faraway from the beacon") elif (distance < 99) and (-4 <= heading <= 4): # in right heading sound.speak("Moving farward") tank.on(left_speed=20, right_speed=20) else: if heading > 0: tank.turn_left(speed=20, degrees=20) else: tank.turn_right(speed=20, degrees=20) sound.speak("I am finding the beacon.") time.sleep(0.1)
def trytospeak(): sound = Sound() #play a standard beep sound.beep() sleep(2) # pause for 2 seconds # Play a SINGLE 2000 Hz tone for 1.5 seconds sound.play_tone(2000, 1.5) sleep(2) # Play a SEQUENCE of tones sound.tone([(200, 2000, 400), (800, 1800, 2000)]) sleep(2) # Play a 500 Hz tone for 1 second and then wait 0.4 seconds # before playing the next tone # Play the tone three times sound.tone([(500, 1000, 400)] * 3) sleep(2) #text to speech sound.speak('Hello, my name is E V 3!') sound.speak('watch me talk')
def test_beep(self): print('Should beep 4 times, waits before driving') flip = 1 s = Sound() tank_drive = MoveTank(OUTPUT_A, OUTPUT_D) for x in range(4): flip *= -1 tank_drive.on_for_seconds(SpeedPercent(30 * flip), SpeedPercent(30 * flip), 1, True, True) s.beep() sleep(1) print('Should beep 4 times, sound plays during driving') s = Sound() tank_drive = MoveTank(OUTPUT_A, OUTPUT_D) flip = 1 for x in range(4): flip *= -1 tank_drive.on_for_seconds(SpeedPercent(30 * flip), SpeedPercent(30 * flip), 1, True, True) s.beep(play_type=Sound.PLAY_NO_WAIT_FOR_COMPLETE) sleep(3)
class BM: # ROBOTS HAVE FEELINGS TOO # BM = Big eMotions def __init__(self): self.light = Leds() self.sound = Sound() # A JOLLY GOOD TIME def calm(self): self.sound(100, "Sounds/Cat purr") self.light(Color.GREEN) # YOUR MOTHER WAS A HAMSTER def aggro(self): self.sound(100, "Sounds/Overpower") self.light(Color.RED) # AND YOUR FATHER SMELLS LIKE ELDERBERRIES def beep(self): self.sound.beep() # HIDE, THE KNIGHTS WHO SAY 'NI' ARE NEAR! def stealth(self): self.sound(100, "Sounds/Boo") self.light(None) # SNAKE? SNAKE??? SNAAKEEEEEEEE???? def scared(self): self.sound(100, "Sounds/Uh-oh") self.light(Color.YELLOW)
def lineFollowTillIntersectionRightPID(kp=1.0, ki=0, kd=0, color=ColorSensor(INPUT_1), color2=ColorSensor(INPUT_3), robot=MoveSteering(OUTPUT_A, OUTPUT_B)): """Function to follow a line till it encounters intersection""" # *an intersection is a line that is going through the line that the robot is following color.mode = 'COL-REFLECT' #setting color mode color2.mode = 'COL-REFLECT' #setting color mode lasterror = 0 sound = Sound() while color2.reflected_light_intensity <= Constants.WHITE and False == Constants.STOP: error = ( (Constants.WHITE + Constants.BLACK) / 2 ) - color.reflected_light_intensity # colorLeft.reflected_light_intensity - colorRight.reflected_light_intensity # correction = error * GAIN # correction = PID(error, lasterror, kp, ki, kd) correction = PIDMath(error=error, lasterror=lasterror, kp=kp, ki=ki, kd=kd) if correction > 100: correction = 100 if correction < -100: correction = -100 robot.on(speed=20, steering=correction) lasterror = error sound.beep() robot.off()
def mutlithreading(): """ In the first example below a thread called twenty_tones is started - it plays twenty tones while the main script waits for the touch sensor button to be 'bumped' (pressed and released) 5 times. The idea is that bumping five times will cause the tone-playing to be interrupted. But if you try running the script you will observe that in this case the playing of the tones is NOT interrupted if you bump the sensor 5 times. However, if the tones stop before the five bumps have been finished then program execution stops after the bumps (and the beep) have been completed, as you would expect. """ ts = TouchSensor() sound = Sound() def twenty_tones(): for j in range(0, 20): # Do twenty times. sound.play_tone(1000, 0.2) # 1000Hz for 0.2s sleep(0.5) t = Thread(target=twenty_tones) t.start() for i in range(0, 5): # Do five times, with i = 0, 1, 2, 3, 4. ts.wait_for_bump() sound.beep()
def run(): zMove.run(100, 1, 1, distance, robot.motorB, 1850, slowDownDistance=1500, stop=False) robot.soundGenerator.beep() zMove.run(100, 1, 1, light, robot.FRONT, 85, 100) robot.motorD.on_for_degrees(speed=-15, degrees=300) zMove.run(100, 1, 1, light, robot.BACK_LEFT, 85, 100) soundGenerator = Sound() soundGenerator.beep() sleep(0.5) squareUp.run(20, 2.5, 1) zMove.run(-50, 1, 1, distance, robot.motorB, 150) #gyroTurn.run(90, 80, 1) gyroTurn.run(90, [1, -1], 40, adjust=15) robot.motorD.on_for_degrees(speed=50, degrees=625) #gyroTurn.run(180, 80, 1) gyroTurn.run(178, [1, -1], 30, 40) zMove.run(-100, 1, 1, distance, robot.motorB, 2040) sleep(1) zPivot.run(50, robot.motorB, distance, robot.motorB, 200, robot.motorB)
def GyroDrift(gyro=GyroSensor(INPUT_2)): sound = Sound() gyro.mode = 'GYRO-RATE' while math.fabs(gyro.rate) > 0: show_text("Gyro drift rate: " + str(gyro.rate)) sound.beep() sleep(0.5) gyro.mode='GYRO-ANG'
def wait_stop_thread(): global STOP sound = Sound() while True: btn.wait_for_bump('left') STOP = True print("STOPPING...", file=stderr) sound.beep() sleep(1)
def wait_stop_thread(): '''Function to set STOP = True if left button is pressed''' global STOP sound = Sound() while True: btn.wait_for_bump('left') STOP = True print("STOPPING...", file=stderr) sound.beep() sleep(1)
class Music(object): """docstring for DiffRobot""" def __init__(self, r_address=OUTPUT_C): super(Music, self).__init__() self.sound = Sound() #fuerElise is already in another foulder on the robot. maybe we dont have to download it every time now. # Change code therefore and maybe folder def playMusic(self): self.sound.play_file( '/home/robot/robotics_ev3/Sounds/short_fuerElise.wav') self.sound.beep()
def test_beep(self): spkr = Sound() spkr.connector.play_actual_sound = False spkr.beep(play_type=1) spkr.beep(play_type=0) self.assertEqual(len(self.clientSocketMock.mock_calls), 2) fn_name, args, kwargs = self.clientSocketMock.mock_calls[0] self.assertEqual(fn_name, 'send_command') self.assertDictEqual(args[0].serialize(), {'type': 'SoundCommand', 'duration': 0.2, 'message': 'Playing note with frequency: 440.0', 'soundType': 'note'})
class TunerBase(metaclass=ABCMeta): def __init__(self): super(TunerBase, self).__init__() self._touch_sensor = TouchSensor() self._sound = Sound() self._name = ROBOT_NAME def tune(self): logger.info('The {} robot is starting tuning.'.format(self._name)) self._process() self._save_to_config() logger.info('The {} robot finished tuning.'.format(self._name)) @abstractmethod def stop(self): pass def _wait_button_press(self): self._sound.beep() FunctionResultWaiter( lambda: self._touch_sensor.is_pressed, None, check_function=lambda is_pressed: is_pressed == 1).run() FunctionResultWaiter( lambda: self._touch_sensor.is_pressed, None, check_function=lambda is_pressed: is_pressed == 0).run() def _check_button_hold(self): if self._touch_sensor.is_pressed: start_time = time.time() FunctionResultWaiter( lambda: self._touch_sensor.is_pressed, None, check_function=lambda is_pressed: is_pressed == 0).run() end_time = time.time() return end_time - start_time >= BUTTON_HOLD_TIME else: return None @abstractmethod def _process(self): pass @abstractmethod def _save_to_config(self): pass
def GyroDrift(gyro=GyroSensor(INPUT_2)): ''' Checking if the Gyro sensor's output is drifing and moving when the actual sensor is not. we need to do this becuase if the sensor is drifting then our GyroTurn's will not work correctly ''' sound = Sound() #Creating sound Shortcut gyro.mode = 'GYRO-RATE' #setting gyro mode while math.fabs( gyro.rate ) > 0: #while gyro is drifting loop, if it is not drifting then the loop will not take place show_text( "Gyro drift rate: " + str(gyro.rate)) #Showing the rate of how much gyro is drifting sound.beep() # Beep to indicate that it is displaying current value sleep(0.5) #waiting for value to change gyro.mode = 'GYRO-ANG' #reseting gyro mode for our use in other functions
def runWhiteLine(): # valkoinen mitattu 70, harmaa mitattu 12, keskiarvo ^40 # taustavari #ridColor = 20 # maalarinteippi ridColor = 40 # valkoinen paperi # Nopeus speed = 25 counter_max = 5 button = Button() colorS = ColorSensor(INPUT_3) sound = Sound() # ajaa eteenpain tank_pair = MoveTank(OUTPUT_A, OUTPUT_D) # kaantyy 2 sekunttia tank_pair.off() sound.beep() # Suoritussilmukka while True: intensity = colorS.reflected_light_intensity while (intensity > ridColor): # viivalla intensity = colorS.reflected_light_intensity tank_pair.on(50, 50) # Eteenpäin counter_max = 5 # alustetaan viivanhaun sektorin leveys if (intensity <= ridColor): #Ei viivalla -> alusta viivanhakumuuttujat speed = -speed i = 0 while (intensity <= ridColor and i < counter_max): # Ei viivalla -> intensity = colorS.reflected_light_intensity tank_pair.on(speed, -speed) # vasemman ja oikean nopeudet, kääntyy vasemmalle i += 1 counter_max += counter_max
def iGPS(r1, r2, r3): #constants x1 = 6 y1 = -6 x2 = 6 y2 = 114 x3 = 102 y3 = 114 #provided formulas x = (-(y2 - y3) * ((y2**2 - y1**2) + (x2**2 - x1**2) + (r1 - r2)) + (y1 - y2) * ((y3**2 - y2**2) + (x3**2 - x2**2) + (r2 - r3))) / (2 * ((x1 - x2) * (y2 - y3) - (x2 - x3) * (y1 - y2))) y = (-(x2 - x3) * ((x2**2 - x1**2) + (y2**2 - y1**2) + (r1 - r2)) + ((x1 - x2) * ((x3**2 - x2**2) + (y3**2 - y2**2) + (r2 - r3)))) / (2 * ((y1 - y2) * (x2 - x3) - (y2 - y3) * (x1 - x2))) #log to console print("r1: " + str(r1)) print("r2: " + str(r2)) print("r3: " + str(r3)) print("x: " + str(x)) print("y: " + str(y)) #print on screen lcd.draw.text((0, 10), "r1: " + str(r1)) lcd.draw.text((0, 20), "r2: " + str(r2)) lcd.draw.text((0, 30), "r3: " + str(r3)) lcd.draw.text((0, 40), "x: " + str(x)) lcd.draw.text((0, 50), "y: " + str(y)) lcd.update() #beep beep Sound.beep(0) Sound.beep(0) #keep on screen before ending time.sleep(10)
if button.up: t = t + 0.1 elif button.down and t > 0: t = t - 0.1 text = str(t) screen.text_pixels(text, x=89, y=64) screen.update() sleep(0.1) screen.text_pixels("GO!", x=89, y=64) screen.update() return t if __name__ == "__main__": speeker.beep() t = getInput() thread = threading.Thread(target=color_find, args=[t], daemon=False) try: thread.start() tank.follow_line(kp=11.3, ki=0.05, kd=3.2, speed=SpeedPercent(30), follow_for=follow_for_forever) except: tank.stop() exit()
""" """ KW = 2 puntos_destinos = np.array([[0.3, 0.0, 0.0], [0.3, 0.3, 0.0], [0.0, 0.3, 0.0], [0.0, 0.0, 0.0]]) n.navegacion_planificada(puntos_destinos, KW) """ """ KA = 1 KR = 5 punto_destino = np.array([[-1.0], [1.0], [0.0]]) n.navegacion_reactiva_campos_virtuales(punto_destino, KA, KR) """ """ sound.beep() f = open("log_angulos_izq.txt","w") angulo = 0 for i in range(0, 12): btn.wait_for_bump('left') f.write(str(angulo)+" "+str(m.posicion_motor_izquierdo)+"\n") angulo = angulo + (pi/6) sound.beep() f.close() """ """ f = open("log_descarga.txt","w")
done = change(b.buttons_pressed) time.sleep(0.05) count += 1 logging.info("And done.") logging.info("Running {}".format(progs[choice][0])) # added 1/9/2020 #gyro.reset() #time.sleep(1) progs[choice][1](gyro) s.beep() choice = choice + choice_incr if __name__ == "__main__": # Resets to 0, does not fix drift time.sleep(1) gyro.mode = GyroSensor.MODE_GYRO_ANG gyro.reset() time.sleep(GYRO_RESET_WAIT) logging.info("Starting angle: {}".format(gyro.angle)) b.on_change = change s.beep() s.beep() s.beep() while True: run_program(gyro)
# process the button event btn.process() # start the game while any direction is given if dx!=0 or dy!=0: # Calculate the new head position x=x+dx*step y=y+dy*step # record the new position by appending to list Sx.append(x) Sy.append(y) # detect whether the snake touch the burger if (abs(hx-x) < step-1) and (abs(hy-y) < step-1): sound.beep() # clean hanburger display.draw.ellipse((hx,hy,hx+step,hy+step),fill=None, outline='white') # regenerate hanburger createBuger() # 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')
#!/usr/bin/env python3 from ev3dev2.sound import Sound sound = Sound() sound.beep() # 비프 음 재생#!/usr/bin/env python3 from ev3dev2.sound import Sound sound = Sound() sound.play_tone(700, 1) #700Hz 주파수 1초간 재생
class Robot: def __init__(self): self.sound = Sound() self.direction_motor = MediumMotor(OUTPUT_D) self.swing_motorL = LargeMotor(OUTPUT_A) self.swing_motorC = LargeMotor(OUTPUT_B) self.swing_motorR = LargeMotor(OUTPUT_C) self.swing_motors = [ self.swing_motorL, self.swing_motorC, self.swing_motorR ] self.touch_sensor = TouchSensor(INPUT_1) self.console = Console(DEFAULT_FONT) self.buttons = Button() self.beeps_enabled = True def beep(self, frequency=700, wait_for_comeplete=False): if not self.beeps_enabled: return play_type = Sound.PLAY_WAIT_FOR_COMPLETE if wait_for_comeplete else Sound.PLAY_NO_WAIT_FOR_COMPLETE self.sound.beep("-f %i" % frequency, play_type=play_type) def calibrate_dir(self): ''' Calibrate direction motor ''' # Run motor with 25% power, and wait until it stops running self.direction_motor.on(SpeedPercent(-10), block=False) # while (not self.direction_motor.STATE_OVERLOADED): # print(self.direction_motor.duty_cycle) self.direction_motor.wait_until(self.direction_motor.STATE_OVERLOADED) self.direction_motor.stop_action = Motor.STOP_ACTION_COAST self.direction_motor.stop() time.sleep(.5) # Reset to straight # self.direction_motor.on_for_seconds(SpeedPercent(10), .835, brake=True, block=True) self.direction_motor.on_for_degrees(SpeedPercent(10), 127, brake=True, block=True) self.direction_motor.reset() print("Motor reset, position: " + str(self.direction_motor.position)) time.sleep(.5) def calibrate_swing(self): for m in self.swing_motors: m.stop_action = m.STOP_ACTION_HOLD m.on(SpeedPercent(6)) self.swing_motorC.wait_until(self.swing_motorC.STATE_OVERLOADED, 2000) for m in self.swing_motors: m.stop_action = m.STOP_ACTION_HOLD m.on_for_degrees(SpeedPercent(5), -15, brake=True, block=False) self.swing_motorC.wait_while('running') for m in self.swing_motors: m.reset() m.stop_action = m.STOP_ACTION_HOLD m.stop() print("Ready Angle: %i" % self.swing_motorC.position) def ready_swing(self, angle: int): right_angle = -(angle / 3) # adjust motors to target angle for m in self.swing_motors: m.stop_action = Motor.STOP_ACTION_HOLD m.on_for_degrees(SpeedPercent(2), right_angle, brake=True, block=False) self.swing_motorC.wait_while('running') for m in self.swing_motors: m.stop_action = Motor.STOP_ACTION_HOLD m.stop() print("Swing Angle: %i" % self.swing_motorC.position) def set_direction(self, direction): print("Setting direction to: " + str(direction)) #direction = self.__aim_correction(direction) self.direction_motor.on_for_degrees(SpeedPercent(10), round(direction * 3)) print("Direction set to: " + str(self.direction_motor.position)) # # def __aim_correction(self, direction): # x = direction # y = -0.00000000429085685725*x**6 + 0.00000004144345630728*x**5 + 0.00001219331494759860*x**4 + 0.00020702946527870400*x**3 + 0.00716486965517779000*x**2 + 1.29675836037884000000*x + 0.27064829453014400000 # # return y def shoot(self, power): print("SHOOT, power: %i" % power) for m in self.swing_motors: m.duty_cycle_sp = -power for m in self.swing_motors: m.run_direct() time.sleep(.5) self.swing_motorC.wait_until_not_moving() for m in self.swing_motors: m.reset() def wait_for_button(self): self.touch_sensor.wait_for_bump() def __set_display(self, str): self.console.set_font(font=LARGER_FONT, reset_console=True) self.console.text_at(str, column=1, row=1, reset_console=True) def wait_for_power_select(self, power=0, angle=0, steps=1): self.__set_display("Pow: %i\nAngle: %i" % (power, angle)) def left(): power -= steps if power < 0: power = 0 self.__set_display("Pow: %i\nAngle: %i" % (power, angle)) self.buttons.wait_for_released(buttons=['left'], timeout_ms=150) def right(): power += steps if power > 100: power = 100 self.__set_display("Pow: %i\nAngle: %i" % (power, angle)) self.buttons.wait_for_released(buttons=['right'], timeout_ms=150) def up(): angle += steps if angle > 110: angle = 110 self.__set_display("Pow: %i\nAngle: %i" % (power, angle)) self.buttons.wait_for_released(buttons=['up'], timeout_ms=150) def down(): angle -= steps if angle < 0: angle = 0 self.__set_display("Pow: %i\nAngle: %i" % (power, angle)) self.buttons.wait_for_released(buttons=['down'], timeout_ms=150) while not self.touch_sensor.is_pressed: if self.buttons.left: left() elif self.buttons.right: right() elif self.buttons.up: up() elif self.buttons.down: down() self.console.set_font(font=DEFAULT_FONT, reset_console=True) return (power, angle) def select_connection_mode(self): self.__set_display("Enable Connection\nLeft: True - Right: False") enabled = True while not self.touch_sensor.is_pressed: if self.buttons.left: enabled = True self.buttons.wait_for_released(buttons=['left']) break elif self.buttons.right: enabled = False self.buttons.wait_for_released(buttons=['right']) break self.console.set_font(font=DEFAULT_FONT, reset_console=True) return enabled def print(self, string): print(string)
mr = 0 c = 0 for i in range(10): if (media - 1.5 * stdev) < a[i] < (media + 1.5 * stdev): mr = mr + a[i] c = c + 1 if mr == 0: resultado = media else: resultado = mr / c return resultado while waiting: if btn.any(): # Checks if any button is pressed. sound.beep() # Wait for the beep to finish. global waiting waiting = False else: sleep(0.01) # Wait 0.01 second rgbmax_e = definir_rgbmax('esq') rgbmax_d = definir_rgbmax('dir') sound.speak('ok') #c = open('dist1.txt','w+') #c.close() # for i in range(100): # steering_pair.on_for_degrees(0,5,10) # sleep(0.02)
def configBuilder(configFile='robot.cfg'): """ Creates a robot config file based on user input and sensor/motor values """ # Make sure this is the global lego module, as it is used dynamicly later. Unsure if needed. global lego # Instantiate brick interface objects btn = Button() disp = Display() spkr = Sound() # Instantiate a ConfigParser object to writ and read the INI format config file config = ConfigParser() # Create the config file sections config['Drivebase'] = {} config['Sensors'] = {} config['AuxMotors'] = {} config['Other'] = {} # Used when detecting motors and sensors, as iterables outPorts = ['OUTPUT_A', 'OUTPUT_B', 'OUTPUT_C', 'OUTPUT_D'] senTypes = ['Color', 'Gyro', 'Touch', 'Ultrasonic', 'Infrared'] # Ask the user if the robot is to be used for FLL disp.text_pixels("Is this robot for FLL?") disp.text_pixels("Y", False, 10, 110) disp.text_pixels("N", False, 150, 110) disp.update() spkr.beep() # Wait for a button press (the outer loop is to allow for selection retry if # an invalid button is pressed) while True: while not btn.any(): pass # Get the list of currently pressed buttons selection = btn.buttons_pressed # Check if the first buton in the list is the left button if selection[0] == 'left': # If it is, set the ForFLL value to TRUE and exit the outer loop btn.wait_for_released('left') config['Other']['ForFLL'] = 'TRUE' break elif selection[0] == 'right': # Otherwise, check if the selection is right. If it is, set ForFLL to FLASE # and exit the outer loop btn.wait_for_released('right') config['Other']['ForFLL'] = 'FALSE' break else: # If both checks fail, play an error tone and go back to waiting for a button spkr.beep() spkr.beep('-f 380') # Clear the display for the next prompt disp.clear() # Auto-detect sensors for i in senTypes: try: # When a sensor object is instantiated without a port, it will find the first port with # that type of sensor connected. If that sensor is not connected, it will throw an error. # The getattr function is used to get the correct sensor type dynamically sensorClass = getattr(lego, i + 'Sensor') # Instantiate the current sensor type mySensor = sensorClass() # Get the port that the sensor is connected to port = str(mySensor.address) # sensor.adress will return sometheing like ev3:in1, so this replaces anything containing in# with INPUT_# port = re.sub('.*in([0-9]).*', 'INPUT_\g<1>', port) # Add port value to the config file config['Sensors'][i + 'Port'] = port except: # If the sensor instantiation failed, none of that kind of sensor are connected, so write the port value as None config['Sensors'][i + 'Port'] = 'None' finally: # Clear the object and class variables as they are reused every loop cycle mySensor = None sensorClass = None # Detect motors # Repeat test for each port for i in outPorts: try: # Instanitiate a Large Motor object at the current port. If there is a Lrge Motor at said port, this will suceed. # Otherwise, it will throw an error and exit the try block. motor = LargeMotor(eval(i)) # Print where the motor was found (port A, B, C, or D), and ask the user what the motor is being used for. disp.text_pixels("Found a Large Motor at " + "port " + i[-1]) disp.text_pixels("What kind of motor is this?", False, 0, 10) disp.text_pixels("Press left for left motor,", False, 0, 20) disp.text_pixels("right for right motor,", False, 0, 30) disp.text_pixels("up for Aux1, or down for Aux2", False, 0, 40) disp.update() # Beep to signal that user input is required spkr.beep() # Loop is used to allow for invalid button presses to repeat selection while True: # Wait for any button to be pressed while not btn.any(): pass # Store what it is (first button pressed, if multiple) selection = btn.buttons_pressed[0] if selection == 'left': # Wait for the button to be released, so the operation only occurs once btn.wait_for_released('left') # If left, store the current port as the left motor port config['Drivebase']['LeftMotorPort'] = i # Exit the loop, as this is a valid selection break elif selection == 'right': # Wait for the button to be released, so the operation only occurs once btn.wait_for_released('right') # If right, store the current port as the right motor port config['Drivebase']['RightMotorPort'] = i # Exit the loop, as this is a valid selection break elif selection == 'up': # Wait for the button to be released, so the operation only occurs once btn.wait_for_released('up') # If up, store the current port as the first auxillary motor port config['AuxMotors']['AuxMotor1'] = i # Exit the loop, as this is a valid selection break elif selection == 'down': # Wait for the button to be released, so the operation only occurs once btn.wait_for_released('down') # If down, store the current port as the second auxillary motor port config['AuxMotors']['AuxMotor2'] = i # Exit the loop, as this is a valid selection break else: # If the pressed button is not valid, play an error tone and repeat the selection menu spkr.beep() spkr.beep('-f 380') # If a motor is not found, no action is required. Apparently 'try' doesn't work without an 'except' except: pass # This works exactly the same as the Large Motor detection, except that it is detecting Medium Motors instead, # and there are no drivemotor selection options. for i in outPorts: try: motor = MediumMotor(eval(i)) disp.text_pixels("Found a Med Motor at port " + i[-1]) disp.text_pixels("Which AuxMotor is this?", False, 0, 10) disp.text_pixels("1", False, 10, 110) disp.text_pixels("2", False, 150, 110) disp.update() spkr.beep() while True: while not btn.any(): pass selection = btn.buttons_pressed[0] if selection == 'left': btn.wait_for_released('left') config['AuxMotors']['AuxMotor1'] = i break elif selection == 'right': btn.wait_for_released('right') config['AuxMotors']['AuxMotor2'] = i break else: spkr.beep() spkr.beep('-f 380') except: pass # Create a MoveTank object with the detected drive motors, as it is needed for the upcoming tests. mtrs = MoveTank(eval(config['Drivebase']['LeftMotorPort']), eval(config['Drivebase']['RightMotorPort'])) # A Foward-Facing Ultrasonic sensor is the only way to allow for calculating the wheel circumfrence. if config['Sensors']['UltrasonicPort'] is not 'None': # Ask the user if the detected Ultrasonic sensor is facing fowards us = UltrasonicSensor(eval(config['Sensors']['UltrasonicPort'])) disp.text_pixels("Does the Ultrasonic sensor") disp.text_pixels("face foward?", False, 0, 10) disp.text_pixels("Y", False, 10, 110) disp.text_pixels("N", False, 150, 110) disp.update() # Same selection system as before while not btn.any(): pass selection = btn.buttons_pressed[0] if selection == 'left': usNav = True elif selection == 'right': usNav = False else: usNav = False spkr.beep() else: usNav = False us = None # Using the variable usNav set previously, check if the Ultrasonic sensor faces fowards. if usNav: # Ask the user to place the robot facing a wall, then wait for a button press. disp.text_pixels("Place the robot facing a wall, ") disp.text_pixels("and press any button.", False, 0, 10) disp.update() while not btn.any(): pass # Set up some variables for averaging circsum = 0 sign = 1 tests = 3 # Repeat the wheelcircumfrence test multiple times to get a more accurate average for j in range(tests): # Determine if this is an even or odd loop cycle. This is used for calculating MotorsInverted, # as the motors are run backwards on odd cycles if j / 2 == round(j / 2): parity = 1 else: parity = -1 # More variables for averaging usSum = 0 readings = 5 # Take multiple sensor readings of how far away from the wall the robot is, and average them for i in range(readings): usSum += us.distance_centimeters sleep(0.1) stavg = round(usSum / readings, 2) # Reset averaging variable usSum = 0 # Move the robot one wheel rotation, foward on even loop cycles, or backward on odd mtrs.on_for_rotations(parity * 25, parity * 25, 1) # Take multiple sensor readings of how far away from the wall the robot is, and average them for i in range(readings): usSum += us.distance_centimeters sleep(0.1) enavg = round(usSum / readings, 2) # The absolute difference between the starting average and the ending average is the wheel circumfrence; # however, this is a cumulative sum of all wheel circumfrence measurements for averaging. circsum += abs(enavg - stavg) # Isolate the sign (-x or x to -1 or 1) of the wheel circumfrence (Used for MotorsInverted) sign = (enavg - stavg) / abs(enavg - stavg) # Calculate the average wheel circumfrence avg = round(circsum / tests, 2) # Write to config file variable config['Drivebase']['WheelCircumfrence'] = str(avg) # Set MotorsInverted in the config file, and set the 'polarity' variable (for inverting motor commands if necessary) polarity = 'normal' if sign < 0: config['Drivebase']['MotorsInverted'] = 'FALSE' polarity = 'normal' elif sign > 0: config['Drivebase']['MotorsInverted'] = 'TRUE' polarity = 'inversed' # Invert motor commands if necessary mtrs.set_polarity(polarity) # Ask the user to place the robot in a clear area, and wait for a button press disp.text_pixels("Place robot in clear area,") disp.text_pixels("and press any button.", False, 0, 10) disp.update() while not btn.any(): pass # Instantiate a Gyro Sensor object as the degrees turned is necessary for calculating the Width Between Wheels gs = GyroSensor(eval(config['Sensors']['GyroPort'])) # Create variables for averaging widthbetweenwheelssum = 0 ang = 0 # Repeat the trial multiple times and average the results for i in range(tests): # Reset the reported gyro angle to zero gs._ensure_mode(gs.MODE_GYRO_RATE) gs._ensure_mode(gs.MODE_GYRO_ANG) # Turn in place for one wheel rotation mtrs.on_for_degrees(25, -25, 360) # Wait for the robot to settle sleep(0.5) # Read the current angle of the robot ang = gs.angle # Calculate the width between the robot's wheels using the formula for arc length (ArcLength = (π * d * Θ) / 360) solved for d, # the diameter of the circle, which is the width between wheels. Absolute value is used so the direction of turn does not matter. wbw = abs((360 * float(config['Drivebase']['WheelCircumfrence'])) / (ang * math.pi)) # Add the calculated value to the running total (used for averaging) widthbetweenwheelssum += wbw # Calculate the average WBW value, round it to remove floating point errors, and store in the ConfigParser object config['Drivebase']['WidthBetweenWheels'] = str( round(widthbetweenwheelssum / tests, 2)) # The motor move command previously made the robot turn right. If the gyro reported this as a turn towards positive, it is not inverted. # Otherwise, the gyro is inverted. if ang > 0: config['Drivebase']['GyroInverted'] = 'FALSE' elif ang < 0: config['Drivebase']['GyroInverted'] = 'TRUE' else: # If the robot does not have an ultrasonic sensor that faces fowards, the robot cannot calculate the wheel circumfrence, which is required # to calculate widthbetweenwheels. The robot also cannot calculate MotorsInverted or GyroInverted. Therefore, empty valuse are written to # those parts of the config file, and the user is notified that they need to manually fill in that information. spkr.beep() spkr.beep() config['Drivebase']['WheelCircumfrence'] = '' config['Drivebase']['WidthBetweenWheels'] = '' config['Drivebase']['MotorsInverted'] = '' config['Drivebase']['GyroInverted'] = '' disp.text_pixels("The config file is missing some") disp.text_pixels("values that will need to be", False, 0, 10) disp.text_pixels("filled in before use.", False, 0, 20) disp.text_pixels("Press any button to exit.", False, 0, 40) disp.update() while not btn.any(): pass # Write placeholder values for the PID gains, so those functions may be usable, if poorly. # Because the WheelCircumfrence is calculated, the wheelcircumfrence value will include any gearing, # so the effective gear ratio is one. config['Drivebase']['GearRatio'] = '1' config['Drivebase']['kp'] = '1' config['Drivebase']['ki'] = '0' config['Drivebase']['kd'] = '0.5' config['Sensors']['kpLine'] = '0.5' config['Sensors']['kiLine'] = '0' config['Sensors']['kdLine'] = '2' # Tell the user that the PID values may (will) need to be tuned. spkr.beep() spkr.beep() disp.text_pixels("The PID gains in the config") disp.text_pixels("file are placeholder values", False, 0, 10) disp.text_pixels("and should be manually tuned.", False, 0, 20) disp.text_pixels("Press any button to end.", False, 0, 40) disp.update() while not btn.any(): pass # Write all the values stored in the ConfigParser object named config to a file in INI format, with the name passed by configFile. with open(configFile, 'w') as configfile: config.write(configfile)
from ev3dev2.sensor import INPUT_1, INPUT_2 from ev3dev2.sensor.lego import TouchSensor, ColorSensor from ev3dev2.sound import Sound import sys, os, time os.system('setfont Lat7-Terminus12x6') #os.system('setfont Lat2-TerminusBold14') cs = ColorSensor() so = Sound() so.beep() csHSV = (0,0,0) cs.rgb print("Set Max Value : \n") # print("Calibration White : \n") # print("Set Max Value : \n") # print("Press Touch Sensor : \n") # ts.wait_for_pressed() # time.sleep(0.01) # cs.calibrate_white() # so.beep() while True: print(cs.rgb, cs.reflected_light_intensity, cs.color_name, cs.raw) print(cs.green, cs.green_max)
from ev3dev2.sound import Sound mySnd = Sound() mySnd.beep() mySnd.speak("Hello, World!") mySnd.beep() # mySnd.play_tone(440, 1.5, 0) mySnd.tone([(440, 500, 0), (880, 1500, 0)])
from test_sound import test if testcase == 'test_display': from test_display import test #执行用例 test() exit() disp = Display() leds = Leds() sounds = Sound() #ts = TouchSensor(INPUT_2) sounds.beep() sleep(1) sounds.set_volume(100) sounds.speak(text='1.15') #sounds.speak(text='Welcome to the E V 3 dev project!') sleep(1) exit() ''' console.reset_console() console.text_at('Hello World!', column=1, row=5, reset_console=True, inverse=True) sleep(2) ''' # 在屏幕上显示字体
def test(): sounds = Sound() sounds.set_volume(100) sounds.beep() sounds.play_tone(300, 0.2) sleep(1) sounds.play_tone(500, 0.2) sleep(1) sounds.speak('start runing:') sleep(1) sounds.play_song(( ('D4', 'e3'), # intro anacrouse ('D4', 'e3'), ('D4', 'e3'), ('G4', 'h'), # meas 1 ('D5', 'h'), ('C5', 'e3'), # meas 2 ('B4', 'e3'), ('A4', 'e3'), ('G5', 'h'), ('D5', 'q'), ('C5', 'e3'), # meas 3 ('B4', 'e3'), ('A4', 'e3'), ('G5', 'h'), ('D5', 'q'), ('C5', 'e3'), # meas 4 ('B4', 'e3'), ('C5', 'e3'), ('A4', 'h.'), )) sleep(1) sounds.tone([(392, 350, 100), (392, 350, 100), (392, 350, 100), (311.1, 250, 100), (466.2, 25, 100), (392, 350, 100), (311.1, 250, 100), (466.2, 25, 100), (392, 700, 100), (587.32, 350, 100), (587.32, 350, 100), (587.32, 350, 100), (622.26, 250, 100), (466.2, 25, 100), (369.99, 350, 100), (311.1, 250, 100), (466.2, 25, 100), (392, 700, 100), (784, 350, 100), (392, 250, 100), (392, 25, 100), (784, 350, 100), (739.98, 250, 100), (698.46, 25, 100), (659.26, 25, 100), (622.26, 25, 100), (659.26, 50, 400), (415.3, 25, 200), (554.36, 350, 100), (523.25, 250, 100), (493.88, 25, 100), (466.16, 25, 100), (440, 25, 100), (466.16, 50, 400), (311.13, 25, 200), (369.99, 350, 100), (311.13, 250, 100), (392, 25, 100), (466.16, 350, 100), (392, 250, 100), (466.16, 25, 100), (587.32, 700, 100), (784, 350, 100), (392, 250, 100), (392, 25, 100), (784, 350, 100), (739.98, 250, 100), (698.46, 25, 100), (659.26, 25, 100), (622.26, 25, 100), (659.26, 50, 400), (415.3, 25, 200), (554.36, 350, 100), (523.25, 250, 100), (493.88, 25, 100), (466.16, 25, 100), (440, 25, 100), (466.16, 50, 400), (311.13, 25, 200), (392, 350, 100), (311.13, 250, 100), (466.16, 25, 100), (392.00, 300, 150), (311.13, 250, 100), (466.16, 25, 100), (392, 700)]) sounds.play_file('resources/xiaohuamao.wav') sleep(2)
#!/usr/bin/env python3 from ev3dev2.sound import Sound sound = Sound() sound.beep() # 비프 음 재생
#!/usr/bin/env python3 from ev3dev2.motor import MoveSteering, OUTPUT_B, OUTPUT_C from ev3dev2.sensor.lego import ColorSensor from ev3dev2.button import Button from ev3dev2.sound import Sound from time import sleep cl = ColorSensor() btn = Button() sound = Sound() steer_pair = MoveSteering(OUTPUT_B, OUTPUT_C) sound.speak('Press the Enter key when the sensor is in dim light') btn.wait_for_bump('enter') dim = cl.ambient_light_intensity sound.beep() sound.speak('Press the Enter key when the sensor is in bright light') btn.wait_for_bump('enter') bright = cl.ambient_light_intensity sound.beep() sound.speak('3, 2, 1, go!') while not btn.any(): # Press any key to exit intensity = cl.ambient_light_intensity steer = (200 * (intensity - dim) / (bright - dim)) - 100 steer = min(max(steer, -100), 100) steer_pair.on(steering=steer, speed=30) sleep(0.1) # wait for 0.1 seconds
try: missions[selectedProgram].run() if selectedProgram < numMissions - 1: selectedProgram = selectedProgram + 1 except Exception as e: soundGenerator.beep() robot.debug("EXCEPTION") robot.debug(e) selectedProgram = selectedProgram + 1 robot.afterMission() print(missionNames[selectedProgram]) # Register the buttonListener buttonListener.on_left = left buttonListener.on_right = right buttonListener.on_enter = enter soundGenerator.beep() # Read the calibrated values and test if the Gyro is drifting robot.init() #testoPesto.run() print(missionNames[selectedProgram]) # Our Main Loop while True: # Check if any buttons are pressed, and call the corresponding event handler buttonListener.process() # Debounce; Make sure the user has time to release the button sleep(0.1)