示例#1
0
def backup():
    """
    Back away from an obstacle.
    """

    # Sound backup alarm.
    spkr = Sound()
    # spkr.tone([(1000, 500, 500)] * 3)
    spkr.speak('du du')

    # Turn backup lights on:
    leds = Leds()

    for light in ('LEFT', 'RIGHT'):
        leds.set_color(light, 'RED')

    # Stop both motors and reverse for 1.5 seconds.
    # `run-timed` command will return immediately, so we will have to wait
    # until both motors are stopped before continuing.
    for m in motors:
        m.stop(stop_action='brake')
        m.run_timed(speed_sp=-500, time_sp=1500)

    # When motor is stopped, its `state` attribute returns empty list.
    # Wait until both motors are stopped:
    while any(m.state for m in motors):
        sleep(0.1)

    # Turn backup lights off:
    for light in ('LEFT', 'RIGHT'):
        leds.set_color(light, 'GREEN')
示例#2
0
文件: demo.py 项目: dkinneyBU/EV3
def speech_examples():
    sound = Sound()
    # see http://espeak.sourceforge.net/
    # values -a 200 -s 130 SHOULD BE INCLUDED if specifying any other options
    # a = amplitude (200 max, 100 default), s = speed 80-500, default = 175)
    opts = '-a 200 -s 150 -p 70 -v'
    # str_en = "I think you ought to know, I'm feeling very depressed"
    str_en = "Hello Big Daddy, your wish is my command"
    # Default voice = English, male
    # sound.speak(str_en)
    # English, male1 (lowest male tone)
    # sound.speak(str_en, espeak_opts='-a 200 -s 130 -ven+m1') # long form
    # English, male7 (highest male tone)
    # sound.speak(str_en, espeak_opts=opts+'en+m7') # using my variable 'opts'
    # English, female1 (lowest female tone)
    # sound.speak(str_en, espeak_opts=opts+'en+f1')
    # English, female5 (highest female tone)
    sound.speak(str_en, espeak_opts=opts + 'en+f5')
    sleep(5)
    # croak
    # sound.speak(str_en, espeak_opts=opts+'en+croak')
    # whisper
    # sound.speak(str_en, espeak_opts=opts+'en+whisper')
    # en-us = US English
    # sound.speak(str_en, espeak_opts=opts+'en-us')
    # en-rp = Received pronunciation ('BBC English')
    # sound.speak(str_en, espeak_opts=opts+'en-rp')
    # s = 80 is slowest possible speed
    # sound.speak(str_en, espeak_opts='-a 200 -s 80')
    # s = 300 is a high speed
    # sound.speak(str_en, espeak_opts='-a 200 -s 300')
    # French
    str_fr = 'Le chat est sous la chaise! Le singe est sur la branche!'
示例#3
0
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')
示例#4
0
class Speaker(Action):
    def __init__(self, text):
        self.text = text
        self.sound = Sound()

    def execute(self):
        self.sound.speak(self.text)
        return True
示例#5
0
文件: M03.py 项目: fll1627/2018-2019
def waitStart():
	speaker = Sound()
	speaker.speak('ready to run')
	touch = TouchSensor(INPUT_1)
	while not touch.is_pressed:
		sleep(0.1)
	mainThread = Thread(target=main)
	mainThread.start()
示例#6
0
def colorSensor():
    color_sensor = ColorSensor()
    sound = Sound()

    while True:
        color = color_sensor.color
        text = ColorSensor.COLORS[color]
        sound.speak(text)
示例#7
0
def on_message(client, userdata, msg):
    data = msg.payload.decode().split()
    comm = int(data[0])
    if comm == 0 and len(data) >= 2:
        sound = Sound()
        sound.speak(msg.payload.decode()[2:])
    elif comm == 1 and len(data) >= 4:
        print(int(data[1]), int(data[2]), int(data[3]))
        MoveTank(OUTPUT_B, OUTPUT_A).on_for_seconds(SpeedPercent(int(data[1])),
                                                    SpeedPercent(int(data[2])),
                                                    int(data[3]))
示例#8
0
    def test_speak(self):
        spkr = Sound()
        spkr.connector.play_actual_sound = False
        spkr.speak("tests tests tests tests tests", volume=100, play_type=1)
        spkr.speak("kekeroni", volume=100, 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': 1.5,  # 200 words per minute, (5 / 200) * 60 = 1.5
                              'message': 'Saying: ``tests tests tests tests tests``',
                              'soundType': 'speak'})
示例#9
0
def play_sonic(button_pressed: Value, pipe: Pipe):
    child_conn = pipe[1]
    sound = Sound()
    # songs = ['sonic_songs/{}'.format(file) for file in listdir('sonic_songs')]
    # size = len(songs)
    # count = 0
    switch = {
        0: lambda: sound.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)
        ], play_type=Sound.PLAY_NO_WAIT_FOR_COMPLETE),
        1: lambda: (sound.speak("Chomp") for _ in range(5))
    }
    switch.get(0)
    while button_pressed.value == 0:
        switch.get(child_conn.recv())()
示例#10
0
文件: lego.py 项目: s4ln1x/uag
class lego_tank():
    def __init__(self):

        try:
            self.tank_drive = MoveTank(OUTPUT_D, OUTPUT_A)
            self.sound = Sound()
            self.sound.speak("Ready to start")
            self.sound.speak("Waiting for orders my commander")
        except:
            self.tank_drive = False

        self.degrees = 1230
        print("Create the tank_drive")

    def right(self):
        print("Turning right")
        if self.tank_drive:
            self.tank_drive.on_for_degrees(50, -50, 470)
        else:
            # We do not have outputs if we run this from our own computer
            pass

    def left(self):
        print("Turning left")
        if self.tank_drive:
            self.tank_drive.on_for_degrees(-50, 50, 470)
        else:
            # We do not have outputs if we run this from our own computer
            pass

    def forward(self):
        print("I am moving forward")
        if self.tank_drive:
            self.tank_drive.on_for_degrees(50, 50, self.degrees)
        else:
            # We do not have outputs if we run this from our own computer
            pass

    def backward(self):
        print("I am moving backwards")
        if self.tank_drive:
            self.tank_drive.on_for_degrees(50, 50, (-1) * self.degrees)
        else:
            # We do not have outputs if we run this from our own computer
            pass
示例#11
0
    def test_speak(self):
        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.speak("tests tests tests tests")
        sleep(3)
        for x in range(4):
            flip *= -1
            tank_drive.on_for_seconds(SpeedPercent(30 * flip),
                                      SpeedPercent(30 * flip), 1, True, True)
            s.speak("tests tests tests tests",
                    play_type=Sound.PLAY_NO_WAIT_FOR_COMPLETE)
        sleep(3)
def setup():
    global tank_drive, colorSensorLeft, colorSensorRight, ultra, sound, touchSensor, gyroSensor
    #g
    tank_drive = MoveTank(OUTPUT_A, OUTPUT_B)
    #tank_drive.gyro = GyroSensor('in4')
    #sleep(1)
    sound = Sound()
    #tank_drive.gyro.calibrate()
    sound.speak("setup")
    colorSensorLeft = ColorSensor('in1')
    colorSensorRight = ColorSensor('in2')

    colorSensorLeft.mode = 'COL-COLOR'
    colorSensorRight.mode = 'COL-COLOR'

    #ultra = UltrasonicSensor('in3')
    touchSensor = TouchSensor('in3')

    gyroSensor = GyroSensor('in4')
    gyroSensor.calibrate()
示例#13
0
class Robot:
    def __init__(self):
        self.leds = Leds()
        self.tank_drive = MoveTank(OUTPUT_A, OUTPUT_B)
        self.tank_drive.set_polarity(LargeMotor.POLARITY_INVERSED)
        self.color = ColorSensor()
        self.ultra = UltrasonicSensor()
        self.sound = Sound()

    # Controls the robot led colors

    def set_leds(self, color):
        self.leds.set_color("LEFT", color)
        self.leds.set_color("RIGHT", color)

    # Movement control for the robot, sets the left and righ
    # engine speeds to 100

    def move(self, speed_left=100, speed_right=100):
        self.tank_drive.on(speed_left, speed_right)

    # Stop control for the robot

    def stop(self, brake=True):
        self.tank_drive.off(brake)

    # Returns the ultrasound sensor distance in centimetres

    def get_distance(self):
        return self.ultra.distance_centimeters

    # Returns the light sensor reflected light intensity value

    def get_color(self):
        return self.color.reflected_light_intensity

    # Controls the speaker

    def speak(self, say):
        self.sound.speak(text=say, play_type=Sound.PLAY_NO_WAIT_FOR_COMPLETE)
示例#14
0
    def draw(self, path=None, multicolor=False):
        speaker = Sound()

        if path is not None:
            if multicolor:
                speaker.speak("Printing multi color image")
                print("\nPrinting multi color image...")
            else:
                speaker.speak("Printing single color image")
                print("\nPrinting single color image...")

            binarized, img_x, img_y = utilities.binarize_image(
                path, self._x_res, self._y_res, multicolor)
        else:
            binarized, img_x, img_y = utilities.generate_and_binarize_test_image(
                self._pixel_size)
            speaker.speak("Printing test page")
            print("\nPrinting test page...")

        quick_calibration = False
        for layer, i in zip(binarized, range(1, utilities.NUM_OF_COLORS)):
            speaker.speak("Insert a {} pen and press the touch sensor".format(
                utilities.palette_names[i]))
            self._touch.wait_for_pressed()
            self.calibrate(quick_calibration)

            p_codes = utilities.binarized_image_to_p_codes(
                layer, img_x, img_y, self._padding_left)
            if self._interpret_p_codes(p_codes):
                break

            self._paper_scroll(self._y_res)
            self._fb_motor.reset()
            self._ud_motor.reset()
            self._lr_motor.reset()
            quick_calibration = True

        speaker = Sound()
        speaker.speak("Printing finished")
        print("Printing finished")
示例#15
0
    def _interpret_p_codes(self, p_codes):
        btn = Button()
        speaker = Sound()
        self._current_line = 0
        abort = False

        print("---------- p_codes:----------")
        print("-------------- Line {} --------------".format(
            self._current_line))
        for x in p_codes:
            if btn.down:
                speaker.speak("Aborting")
                print("\nAborting...")
                abort = True
                break

            if x[0] == utilities.Command.PEN_UP:
                if not self._is_pen_up:
                    self._pen_up(x[1])

            elif x[0] == utilities.Command.PEN_DOWN:
                if self._is_pen_up:
                    self._pen_down(x[1])

            elif x[0] == utilities.Command.PEN_RIGHT:
                self._pen_right(x[1])

            elif x[0] == utilities.Command.PEN_LEFT:
                self._pen_left(x[1])

            elif x[0] == utilities.Command.SCROLL:
                self._paper_scroll(x[1])

        if not self._is_pen_up:
            self._pen_up(1)
        self._ud_motor.stop()

        return abort
示例#16
0
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={})
示例#17
0
文件: demo.py 项目: dkinneyBU/EV3
def speak_and_rotate():
    sound = Sound()
    os.system('setfont Lat15-TerminusBold14')
    mL = LargeMotor('outB')
    mL.stop_action = 'hold'
    mR = LargeMotor('outC')
    mR.stop_action = 'hold'
    print('Hello, my name is EV3D4!')
    str_en = 'Hello, my name is E V 3 D 4!'
    opts = '-a 200 -s 150 -p 70 -v'
    sound.speak(str_en, espeak_opts=opts + 'en+f5')
    sleep(2)
    str_en = "Performing perimeter scan"
    sound.speak(str_en, espeak_opts=opts + 'en+f5')
    # Sound.speak('Hello, my name is Evie, 3 D 4!').wait()
    mL.run_to_rel_pos(position_sp=1662, speed_sp=300)
    mR.run_to_rel_pos(position_sp=-1662, speed_sp=300)
    #mL.wait_while('running')
    #mR.wait_while('running')
    sleep(1)
    str_en = "At your command Big Daddy"
    sound.speak(str_en, espeak_opts=opts + 'en+f5')
    sleep(1)
示例#18
0
 def __play_text_sound(self, words):
     sound = Sound()
     sound.speak(words)
示例#19
0
#!/usr/bin/env micropython
from ev3dev2.sound import Sound

sound = Sound()

sound.speak("jake operational")
示例#20
0
from roberta.ev3 import Hal
from ev3dev2.motor import LargeMotor, MediumMotor
from ev3dev2.motor import MoveSteering, OUTPUT_A, OUTPUT_D
from ev3dev2.motor import MoveTank, OUTPUT_A, OUTPUT_D
from ev3dev2.sound import Sound
from ev3dev import ev3 as ev3dev

#lm = LargeMotor(OUTPUT_A)
#rm = LargeMotor(OUTPUT_D)
mm = MediumMotor(OUTPUT_B)

sound = Sound()
opts = '-a 200 -s 130 -v'

text = 'Saluton amikoj, mi estas Robi! mi sxatas muziki kaj danci'
sound.speak(text, espeak_opts=opts+'eo')

class BreakOutOfALoop(Exception): pass
class ContinueLoop(Exception): pass

_brickConfiguration = {
    'wheel-diameter': 5.6,
    'track-width': 18.0,
    'actors': {
        'A':Hal.makeLargeMotor(ev3dev.OUTPUT_A, 'on', 'foreward', 'right'),
        'D':Hal.makeLargeMotor(ev3dev.OUTPUT_D, 'on', 'foreward', 'left'),
    }
}
hal = Hal(_brickConfiguration)

def s3():
示例#21
0
#!/usr/bin/env micropython

from ev3dev2.sound import Sound

sound = Sound()
sound.speak('Welcome to Griffy 3 point Oh!')
sound.speak('Hello Nate, Gideon and Kai')
示例#22
0
from ev3dev2.sound import Sound
from ev3dev2.motor import MoveSteering
from ev3dev2.motor import OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D

rob = MoveSteering(OUTPUT_D, OUTPUT_B)
mySnd = Sound()

mySnd.speak("Turning right in place")
rob.on_for_seconds(50, -50, 2)

mySnd.speak("Spiraling")

rob.on_for_seconds(20, 50, 2)
rob.off()

示例#23
0
#!/usr/bin/env python3
from ev3dev2.sound import Sound
from time import sleep

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
# [(500, 1000, 400)] * 3 is the same as
# [(500, 1000, 400), (500, 1000, 400), (500, 1000, 400)]
sound.tone([(500, 1000, 400)] * 3)
sleep(2)

#text to speech
sound.speak('Hello, my name is E V 3!')
示例#24
0
#!/usr/bin/env python3
from ev3dev2.sound import Sound

sound = Sound()
sound.speak("I'm not Alexa, I swear!")
示例#25
0
class Robot:
    """
    Robot is a class that instantiates and sets up the robot so that it is ready for use. It initializes the sensors
    and the tank drive, and it sets up the sensors. On top of that it provides functions so that the robot can be
    controlled.
    """
    def __init__(self, sensormap, bluetooth=None):
        """
        Initializer for a Robot.
        """
        self.bluetooth = bluetooth
        if bluetooth:
            self.bluetooth.initiate_connection()
            print('connected')
            if isinstance(bluetooth, BluetoothMaster):
                self.database = bluetooth.get_database()
        self.sensormap = sensormap
        self.sound = Sound()
        self.leds = Leds()

    def speak(self, text):
        """
        Speak in separate thread so it does not block anything.
        """
        threading.Thread(
            target=lambda: self.sound.speak(text, Sound.PLAY_NO_WAIT_FOR_COMPLETE)
        ).start()

    def start_drive(self, speed_percentage=40):
        """
        Activates the motors of the robot to move forward.
        :param speed_percentage: The speed of the Robot based on motor power. Percentage between 0 and 100.
        """
        self.sensormap.tank_drive.on(SpeedPercent(speed_percentage), SpeedPercent(speed_percentage))

    def reverse_for_rotations(self, nr_rotations, rpm=60, lock=None):
        """
        Reverses the Robot (makes it move backwards).
        :param nr_rotations: Number of degrees Robot turns.
        :param rpm: Speed at which the Robot reverses in rotations per minute.
        :param lock: Optional Lock to stop the operation when requested
        """
        self.sensormap.tank_drive.on_for_rotations(SpeedRPM(-rpm), SpeedRPM(-rpm), nr_rotations, block=False)
        end_time = datetime.now() + timedelta(seconds=(nr_rotations*60)/rpm)
        while datetime.now() < end_time:
            if lock and lock.is_locked():
                self.sensormap.tank_drive.stop()
                break
            time.sleep(0.01)

    def turn_for_rotations(self, rotations, rpm=30, lock=None):
        """
        Turn for a number of degrees with the given speed.
        Can be pre-empted when given a Lock.
        :param rotations: The number of rotations to turn.
        :param rpm: The speed to turn at.
        :param lock: Optional Lock to stop the operation when requested.
        """
        self.sensormap.tank_drive.on_for_rotations(SpeedRPM(rpm), SpeedRPM(-rpm), abs(rotations), block=False)
        end_time = datetime.now() + timedelta(seconds=(abs(rotations)*60)/abs(rpm))
        while datetime.now() < end_time:
            if lock and lock.is_locked():
                self.sensormap.tank_drive.stop()
                break
            time.sleep(0.01)

    def rotate_degrees(self, rotations, reverse_before_continue=True, rpm=35, lock=None):
        """
        Rotates the Robot.
        :param rotations: Number of rotations the Robot rotates.
        :param reverse_before_continue: True if Robot needs to reverse before turning, False if not.
        :param rpm: Speed at which the Robot turns.
        :param lock: Optional Lock to stop the operation when requested
        """
        if reverse_before_continue:
            self.reverse_for_rotations(.6, lock=lock)
        if rotations < 0:
            rpm *= -1
        self.turn_for_rotations(abs(rotations), rpm=rpm, lock=lock)
示例#26
0
class Robot:
    def __init__(self):
        self.steer = MoveSteering(OUTPUT_B, OUTPUT_C)
        self.tank_pair = MoveTank(OUTPUT_B, OUTPUT_C)
        self.touch_sensor = TouchSensor()
        self.cl = ColorSensor()
        self.s = Sound()
        self.btn = Button()
        self.c_switch = True  # True: Turning left, comp right, False: opposite.
        self.col_switch = True  # True: black, False: white.
        self.tile_count = 0
        self.tile_length = 230
        # Sets up offset for variable light
        self.off_set = self.cl.reflected_light_intensity - 13
        self.black_range = range(0, 30)
        self.white_range = range(30, 100)

    def move_degrees(self, degrees):
        self.tank_pair.on_for_degrees(left_speed=10,
                                      right_speed=10,
                                      degrees=degrees)

    def run(self):
        # Moves the robot off starting pad and onto black-white tiles
        self.tank_pair.on_for_degrees(left_speed=50,
                                      right_speed=50,
                                      degrees=90)
        while (self.cl.reflected_light_intensity in self.black_range):
            self.tank_pair.on(left_speed=20, right_speed=20)
        self.tank_pair.off()
        while not (self.cl.reflected_light_intensity in self.black_range):
            self.tank_pair.on(left_speed=20, right_speed=20)
        self.tank_pair.off()
        self.tank_pair.on_for_degrees(left_speed=50,
                                      right_speed=50,
                                      degrees=self.tile_length * 0.75)
        self.tank_pair.on_for_degrees(left_speed=20,
                                      right_speed=-20,
                                      degrees=180)
        while not (self.cl.reflected_light_intensity in self.white_range):
            self.tank_pair.on(left_speed=-20, right_speed=-20)
        self.tank_pair.off()
        self.tank_pair.on_for_degrees(left_speed=20,
                                      right_speed=20,
                                      degrees=self.tile_length * 0.25)
        current_tile = self.getColour()
        self.center_robot(current_tile)
        while not (self.cl.reflected_light_intensity in current_tile):
            self.tank_pair.on(left_speed=20, right_speed=20)
        self.tank_pair.off()
        #self.tank_pair.on(left_speed=20, right_speed=20)

        while (self.tile_count < 15):
            moved_degrees = 0
            correct_alignment = True
            black_found = False
            while (True):
                while (self.cl.reflected_light_intensity in self.white_range):
                    self.tank_pair.on()
                self.tank_pair.off()
                if (self.cl.reflected_light_intensity in self.black_range):
                    black_found = True
                    print("found black")
                    break
            if (black_found):
                self.tile_count += 1
                self.tank_pair.on(left_speed=20, right_speed=20)
                if (correct_alignment and self.tile_count > 1):
                    self.move_degrees(self.tile_length * 0.25)
                    turn_degrees_right = 0
                    turn_degrees_left = 0
                    while not (self.cl.reflected_light_intensity
                               in self.white_range):
                        self.tank_pair.on_for_degrees(left_speed=10,
                                                      right_speed=-10,
                                                      degrees=10)
                        turn_degrees_right += 10
                    self.tank_pair.on_for_degrees(left_speed=-10,
                                                  right_speed=10,
                                                  degrees=turn_degrees_right)
                    while not (self.cl.reflected_light_intensity
                               in self.white_range):
                        self.tank_pair.on_for_degrees(left_speed=-10,
                                                      right_speed=10,
                                                      degrees=10)
                        turn_degrees_left += 10
                    if (turn_degrees_right < turn_degrees_left):
                        self.tank_pair.on_for_degrees(
                            left_speed=10,
                            right_speed=-10,
                            degrees=turn_degrees_left - turn_degrees_right)
                    elif (turn_degrees_left < turn_degrees_right):
                        self.tank_pair.on_for_degrees(
                            left_speed=10,
                            right_speed=-10,
                            degrees=turn_degrees_right - turn_degrees_left)
                    else:
                        self.s.speak("This should never have happened.")
                        self.tank_pair.on_for_degrees(
                            left_speed=10,
                            right_speed=-10,
                            degrees=turn_degrees_left)
            else:
                while not (self.cl.reflected_light_intensity
                           in self.white_range):
                    pass
            self.tank_pair.off()
            if (moved_degrees > self.tile_length):
                self.realign()
            else:
                self.realign()
        '''
        previous_tile_count = 0
        saw_black_realign = False
        saw_black = True
        while (self.tile_count < 15):
            if not (t.is_alive()):
                # check for realignment
                if (previous_tile_count < self.tile_count):
                    self.s.speak(str(self.tile_count))
                    previous_tile_count = self.tile_count
                if not (saw_black_realign):
                    self.realign()
                t.start()
                saw_black_realign = False
            if (self.cl.reflected_light_intensity in self.white_range and saw_black):
                self.tile_count +=1
                saw_black = False
                #self.tank_pair.off()
                #self.s.speak(str(self.tile_count))
                #self.tank_pair.on(left_speed=20, right_speed=20)
            if (self.cl.reflected_light_intensity in self.black_range):
                saw_black = True
                saw_black_realign = True
        self.tank_pair.off()
        '''
        '''
            if (self.cl.reflected_light_intensity > 55 and self.col_switch):
                self.tank_pair.off()
                self.titleCount += 1
                self.col_switch = False
                self.s.speak(str(self.titleCount))
                self.tank_pair.on(left_speed=20, right_speed=20)
            if (self.cl.reflected_light_intensity < 20 and not self.col_switch):
                self.col_switch = True
                '''

    def realign(self):
        # check side black is on
        self.s.speak("life is pain")

    # returns oposite colour
    def getColour(self):
        if (self.cl.reflected_light_intensity in self.black_range):
            return self.white_range
        elif (self.cl.reflected_light_intensity in self.white_range):
            return self.black_range

    def center_robot(self, colour):
        right_turn_count = 0
        left_turn_count = 0
        #bias = 1/2
        while not (self.cl.reflected_light_intensity in colour):
            self.tank_pair.on_for_degrees(left_speed=10,
                                          right_speed=-10,
                                          degrees=10)
            right_turn_count += 1
        #if (self.cl.reflected_light_intensity in self.gray_range):
        #    bias = 3/4
        self.tank_pair.on_for_degrees(left_speed=-10,
                                      right_speed=10,
                                      degrees=10 * right_turn_count)
        while not (self.cl.reflected_light_intensity in colour):
            self.tank_pair.on_for_degrees(left_speed=-10,
                                          right_speed=10,
                                          degrees=10)
            left_turn_count += 1
        #if (self.cl.reflected_light_intensity in self.gray_range):
        #    bias = 1/4
        #if (abs(left_turn_count-right_turn_count) < 2):
        #    bias = 1/2
        self.tank_pair.on_for_degrees(
            left_speed=10,
            right_speed=-10,
            degrees=(10 * (right_turn_count + left_turn_count) / 2))
        self.ninety_turn = 10 * (right_turn_count + left_turn_count) / 2

    def length_of_tile(self):
        count = 0
        while (self.cl.reflected_light_intensity in self.black_range):
            self.tank_pair.on_for_degrees(left_speed=10,
                                          right_speed=10,
                                          degrees=10)
            count += 1
        self.s.speak(str(count * 10))

    def checkColour(self):
        while not self.btn.any():
            self.touch_sensor.wait_for_pressed()
            self.s.speak(str(self.cl.reflected_light_intensity))
示例#27
0
if os.path.isfile(OPEN_BLING_path):
    os.remove(OPEN_BLING_path)

if os.path.isfile(OPEN_GREEN_LIGHT_path):
    os.remove(OPEN_GREEN_LIGHT_path)

if os.path.isfile(GREEN_LIGHT_path):
    os.remove(GREEN_LIGHT_path)







sound.speak("O, A, O, A")

print("OKOKOKOKOKOKOKOKOKOKOK")
'''
while True:
    if ts.is_pressed:
        mt.off()
        break
    if btn.check_buttons(buttons=['up']):
        mt.on(-50, -50)
    elif btn.check_buttons(buttons=['up']) == False:
        mt.off()
'''
ts.wait_for_bump()
sound.play_tone(2500, 0.1) 
示例#28
0
#执行用例
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)
'''

# 在屏幕上显示字体
if True:
    #显示有效的Display字体
    print(fonts.available(), file=sys.stderr)
    sleep(2)
#!/usr/bin/env python3

from time import sleep

from ev3dev2.sensor import INPUT_2
from ev3dev2.sensor.lego import TouchSensor
from ev3dev2.led import Leds
from ev3dev2.sound import Sound

ts = TouchSensor(INPUT_2)
leds = Leds()
speaker = Sound()

print("Press the touch sensor to change the LED color!")
speaker.speak("Press the touch sensor to change the LED color!")

while True:
    if ts.is_pressed:
        leds.set_color("LEFT", "GREEN")
        leds.set_color("RIGHT", "GREEN")
    else:
        leds.set_color("LEFT", "RED")
        leds.set_color("RIGHT", "RED")
    # don't let this loop use 100% of CPU
    sleep(0.01)
#!/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
示例#31
0
    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)
#     d = distancia_do_corre(usl)
#     c = open('testecor.txt','a')
#     n = str(i)
#     c = open('dist.txt','a')
#     c.write(n)
#     c.write(') ')
#     c.write(str(d))
#     c.write('\n')