Exemple #1
0
 def test_ledsOff(self):
     my_leds = Leds()
     my_leds.set_color('LEFT', (0.5, 0.3))
     my_leds.set_color('RIGHT', 'AMBER')
     sleep(5)
     my_leds.all_off()
     sleep(5)
Exemple #2
0
 def test_MoveTank(self):
     my_leds = Leds()
     my_leds.set_color('LEFT', (0.5, 0.3))
     my_leds.set_color('RIGHT', 'AMBER')
     sleep(2)
     my_leds.all_off()
     my_leds.animate_cycle(('RED', 'GREEN', 'AMBER'), duration=5)
Exemple #3
0
 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")
Exemple #4
0
def sensors():
    # Connect infrared and touch sensors to any sensor ports
    ir = InfraredSensor()
    ts = TouchSensor()
    leds = Leds()

    leds.all_off()
    # stop the LEDs flashing (as well as turn them off)
    # is_pressed and proximity are not functions and do not need parentheses
    while not ts.is_pressed:  # Stop program by pressing the touch sensor button
        if ir.proximity < 40 * 1.4:  # to detect objects closer than about 40cm
            leds.set_color('LEFT', 'RED')
            leds.set_color('RIGHT', 'RED')
        else:
            leds.set_color('LEFT', 'GREEN')
            leds.set_color('RIGHT', 'GREEN')

        sleep(0.01)  # Give the CPU a rest
Exemple #5
0
def main():
    leds = Leds()

    leds.all_off()  # stop the LEDs flashing (as well as turn them off)
    while True:
        dist = us.distance_centimeters
        if dist < 20:  # to detect objects closer than 40cm
            # In the above line you can also use inches: us.distance_inches < 16
            leds.set_color('LEFT', 'RED')
            leds.set_color('RIGHT', 'RED')
        else:
            leds.set_color('LEFT', 'GREEN')
            leds.set_color('RIGHT', 'GREEN')

        print(dist)

        motor.on_to_position(50, int(dist))

        sleep(0.1)  # Give the CPU a rest
Exemple #6
0
#!/usr/bin/env python3
from ev3dev2.led import Leds
from time import sleep

leds = Leds()

leds.all_off()  # Turn all LEDs off. This also turns off the flashing.
sleep(1)

leds.set_color('LEFT', 'AMBER')
sleep(4)
#!/usr/bin/env python3
from ev3dev2.sensor.lego import InfraredSensor
from ev3dev2.led import Leds
from sys import stderr
from time import sleep

ir = InfraredSensor()
leds = Leds()

leds.all_off()  # Needed, to stop the LEDs flashing
while True:
    if ir.proximity < 40 * 1.4:  # To convert cm to proximity, multiply by 1.4
        leds.set_color('LEFT', 'RED')
        leds.set_color('RIGHT', 'RED')
    else:
        leds.set_color('LEFT', 'GREEN')
        leds.set_color('RIGHT', 'GREEN')
    print(str(int(ir.proximity * 0.7)) + ' cm approx', file=stderr)
    # To convert proximity to cm, multiply by 0.7.
    sleep(0.5)
Exemple #8
0
    def display_menu(self, start_page=0, before_run_function=None, after_run_function=None, skip_to_next_page=True):
        """
        Console Menu that accepts choices and corresponding functions to call.
        The user must press the same button twice: once to see their choice highlited,
        a second time to confirm and run the function. The EV3 LEDs show each state change:
        Green = Ready for button, Amber = Ready for second button, Red = Running
        Parameters:
        - `choices` a dictionary of tuples "button-name": ("function-name", function-to-call)
        NOTE: Don't call functions with parentheses, unless preceded by lambda: to defer the call
        - `before_run_function` when not None, call this function before each function run, passed with function-name
        - `after_run_function` when not None, call this function after each function run, passed with function-name
        """

        self.current_page = start_page

        console = Console()
        leds = Leds()
        button = Button()

        leds.all_off()
        leds.set_color("LEFT", "GREEN")
        leds.set_color("RIGHT", "GREEN")
        menu_positions = self.get_menu_positions(console)

        last = None  # the last choice--initialize to None

        self.menu_tone()
        self.debug("Starting Menu")
        while True:
            # display the menu of choices, but show the last choice in inverse
            console.reset_console()
            self.debug("Reset the display screen")
            console.set_font('Lat15-TerminusBold24x12.psf.gz', True)
            
            # store the currently selected menu page
            menu_page = self.menu_pages[self.current_page]
            # store the currently selected menu items
            menu_options_on_page = menu_page.items() 
            
            for btn, (name, _) in menu_options_on_page:
                align, col, row = menu_positions[btn]
                console.text_at(name, col, row, inverse=(btn == last), alignment=align)
            self.debug("Waiting for button press...")
            pressed = self.wait_for_button_press(button)
            self.debug("Registered button press: {}".format(pressed))
            
            # get the choice for the button pressed
            if pressed in menu_page:
                if last == pressed:   # was same button pressed?
                    console.reset_console()
                    leds.set_color("LEFT", "RED")
                    leds.set_color("RIGHT", "RED")

                    # call the user's subroutine to run the function, but catch any errors
                    try:
                        name, run_function = menu_page[pressed]
                        if before_run_function is not None:
                            self.debug('Running before function')
                            before_run_function(name)
                        self.press_tone()
                        type_of_run_function = type(run_function)
                        self.debug("Type of run_function: {}".format(type_of_run_function))

                        if isinstance(run_function, str):
                            self.debug("Running {}".format(run_function))
                            if run_function == 'next':
                                self.debug("About to call next")
                                self.next()
                            elif run_function =='back':
                                self.debug("About to call back")
                                self.back()
                        elif callable(run_function):
                            run_function()
                    except Exception as e:
                        print("**** Exception when running")
                        raise(e)
                    finally:
                        if after_run_function is not None:
                            after_run_function(name)
                        last = None
                        leds.set_color("LEFT", "GREEN")
                        leds.set_color("RIGHT", "GREEN")
                else:   # different button pressed
                    last = pressed
                    leds.set_color("LEFT", "AMBER")
                    leds.set_color("RIGHT", "AMBER")
Exemple #9
0
def get_time() -> int:
    global timer

    return timer.value_ms


# Start sensor thread
sensor_thread = SensorThread(name="sensor_thread")
sensor_thread.daemon = True
sensor_thread.start()

# Main program loop
while running:
    console.reset_console()
    leds.all_off()

    state = "reset"
    reset_sensors_and_variables()
    calibrate_gyro_offset()

    sound.play_file("/home/robot/sounds/Speed up.wav")
    console.reset_console()
    leds.animate_flash('GREEN', duration=None, block=False)

    state = "ready"
    log.debug("Starting control loop")

    while ok == True:
        time = get_time()
Exemple #10
0
class Ev3rstorm:
    def __init__(self,
                 left_foot_motor_port: str = OUTPUT_B,
                 right_foot_motor_port: str = OUTPUT_C,
                 bazooka_blast_motor_port: str = OUTPUT_A,
                 touch_sensor_port: str = INPUT_1,
                 color_sensor_port: str = INPUT_3,
                 ir_sensor_port: str = INPUT_4,
                 ir_beacon_channel: int = 1):
        self.tank_driver = MoveTank(left_motor_port=left_foot_motor_port,
                                    right_motor_port=right_foot_motor_port,
                                    motor_class=LargeMotor)

        self.bazooka_blast_motor = MediumMotor(
            address=bazooka_blast_motor_port)

        self.touch_sensor = TouchSensor(address=touch_sensor_port)
        self.color_sensor = ColorSensor(address=color_sensor_port)

        self.ir_sensor = InfraredSensor(address=ir_sensor_port)
        self.ir_beacon_channel = ir_beacon_channel

        self.leds = Leds()
        self.speaker = Sound()
        self.screen = Display()

    def drive_once_by_ir_beacon(self, speed: float = 100):
        # forward
        if self.ir_sensor.top_left(
                channel=self.ir_beacon_channel) and self.ir_sensor.top_right(
                    channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=speed, right_speed=speed)

        # backward
        elif self.ir_sensor.bottom_left(channel=self.ir_beacon_channel
                                        ) and self.ir_sensor.bottom_right(
                                            channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=-speed, right_speed=-speed)

        # turn left on the spot
        elif self.ir_sensor.top_left(channel=self.ir_beacon_channel
                                     ) and self.ir_sensor.bottom_right(
                                         channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=-speed, right_speed=speed)

        # turn right on the spot
        elif self.ir_sensor.top_right(
                channel=self.ir_beacon_channel) and self.ir_sensor.bottom_left(
                    channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=speed, right_speed=-speed)

        # turn left forward
        elif self.ir_sensor.top_left(channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=0, right_speed=speed)

        # turn right forward
        elif self.ir_sensor.top_right(channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=speed, right_speed=0)

        # turn left backward
        elif self.ir_sensor.bottom_left(channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=0, right_speed=-speed)

        # turn right backward
        elif self.ir_sensor.bottom_right(channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=-speed, right_speed=0)

        # otherwise stop
        else:
            self.tank_driver.off(brake=False)

    def dance_if_ir_beacon_pressed(self):
        while self.ir_sensor.beacon(channel=self.ir_beacon_channel):
            self.tank_driver.on_for_seconds(left_speed=randint(-100, 100),
                                            right_speed=randint(-100, 100),
                                            seconds=1,
                                            brake=False,
                                            block=True)

    def detect_object_by_ir_sensor(self):
        if self.ir_sensor.proximity < 25:
            self.leds.animate_police_lights(color1=Leds.ORANGE,
                                            color2=Leds.RED,
                                            group1=Leds.LEFT,
                                            group2=Leds.RIGHT,
                                            sleeptime=0.5,
                                            duration=5,
                                            block=False)

            self.speaker.play_file(wav_file='/home/robot/sound/Object.wav',
                                   volume=100,
                                   play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

            self.speaker.play_file(wav_file='/home/robot/sound/Detected.wav',
                                   volume=100,
                                   play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

            self.speaker.play_file(
                wav_file='/home/robot/sound/Error alarm.wav',
                volume=100,
                play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

        else:
            self.leds.all_off()

    def blast_bazooka_if_touched(self):
        if self.touch_sensor.is_pressed:
            if self.color_sensor.ambient_light_intensity < 5:  # 15 not dark enough
                self.speaker.play_file(wav_file='/home/robot/sound/Up.wav',
                                       volume=100,
                                       play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                self.bazooka_blast_motor.on_for_rotations(speed=100,
                                                          rotations=-3,
                                                          brake=True,
                                                          block=True)

                self.speaker.play_file(
                    wav_file='/home/robot/sound/Laughing 1.wav',
                    volume=100,
                    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

            else:
                self.speaker.play_file(wav_file='/home/robot/sound/Down.wav',
                                       volume=100,
                                       play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                self.bazooka_blast_motor.on_for_rotations(speed=100,
                                                          rotations=3,
                                                          brake=True,
                                                          block=True)

                self.speaker.play_file(
                    wav_file='/home/robot/sound/Laughing 2.wav',
                    volume=100,
                    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

            self.touch_sensor.wait_for_released()

    def main(self, driving_speed: float = 100):
        self.screen.image_filename(filename='/home/robot/image/Target.bmp',
                                   clear_screen=True)
        self.screen.update()

        while True:
            self.drive_once_by_ir_beacon(speed=driving_speed)

            self.dance_if_ir_beacon_pressed()

            # DON'T use IR Sensor in 2 different modes in the same program / loop
            # - https://github.com/pybricks/support/issues/62
            # - https://github.com/ev3dev/ev3dev/issues/1401
            # self.detect_object_by_ir_sensor()

            self.blast_bazooka_if_touched()
Exemple #11
0
class Ev3rstorm(IRBeaconRemoteControlledTank):
    def __init__(self,
                 left_foot_motor_port: str = OUTPUT_B,
                 right_foot_motor_port: str = OUTPUT_C,
                 bazooka_blast_motor_port: str = OUTPUT_A,
                 touch_sensor_port: str = INPUT_1,
                 color_sensor_port: str = INPUT_3,
                 ir_sensor_port: str = INPUT_4,
                 ir_beacon_channel: int = 1):
        super().__init__(left_motor_port=left_foot_motor_port,
                         right_motor_port=right_foot_motor_port,
                         motor_class=LargeMotor,
                         ir_sensor_port=ir_sensor_port,
                         ir_beacon_channel=ir_beacon_channel)

        self.bazooka_blast_motor = MediumMotor(
            address=bazooka_blast_motor_port)

        self.touch_sensor = TouchSensor(address=touch_sensor_port)
        self.color_sensor = ColorSensor(address=color_sensor_port)

        self.leds = Leds()
        self.speaker = Sound()

    def detect_object_by_ir_sensor(self):
        if self.ir_sensor.proximity < 25:
            self.leds.animate_police_lights(color1=Leds.ORANGE,
                                            color2=Leds.RED,
                                            group1=Leds.LEFT,
                                            group2=Leds.RIGHT,
                                            sleeptime=0.5,
                                            duration=5,
                                            block=False)

            self.speaker.play_file(wav_file='/home/robot/sound/Object.wav',
                                   volume=100,
                                   play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

            self.speaker.play_file(wav_file='/home/robot/sound/Detected.wav',
                                   volume=100,
                                   play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

            self.speaker.play_file(
                wav_file='/home/robot/sound/Error alarm.wav',
                volume=100,
                play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

        else:
            self.leds.all_off()

    def blast_bazooka_if_touched(self):
        if self.touch_sensor.is_pressed:
            if self.color_sensor.ambient_light_intensity < 5:  # 15 not dark enough
                self.speaker.play_file(wav_file='/home/robot/sound/Up.wav',
                                       volume=100,
                                       play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                self.bazooka_blast_motor.on_for_rotations(speed=100,
                                                          rotations=-3,
                                                          brake=True,
                                                          block=True)

                self.speaker.play_file(
                    wav_file='/home/robot/sound/Laughing 1.wav',
                    volume=100,
                    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

            else:
                self.speaker.play_file(wav_file='/home/robot/sound/Down.wav',
                                       volume=100,
                                       play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                self.bazooka_blast_motor.on_for_rotations(speed=100,
                                                          rotations=3,
                                                          brake=True,
                                                          block=True)

                self.speaker.play_file(
                    wav_file='/home/robot/sound/Laughing 2.wav',
                    volume=100,
                    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

            self.touch_sensor.wait_for_released()

    def main(self, driving_speed: float = 100):
        while True:
            self.drive_once_by_ir_beacon(speed=driving_speed)

            # DON'T use IR Sensor in 2 different modes in the same program / loop
            # - https://github.com/pybricks/support/issues/62
            # - https://github.com/ev3dev/ev3dev/issues/1401
            # self.detect_object_by_ir_sensor()

            self.blast_bazooka_if_touched()
Exemple #12
0
class Ev3rstorm:
    def __init__(self,
                 left_foot_motor_port: str = OUTPUT_B,
                 right_foot_motor_port: str = OUTPUT_C,
                 bazooka_blast_motor_port: str = OUTPUT_A,
                 touch_sensor_port: str = INPUT_1,
                 color_sensor_port: str = INPUT_3,
                 ir_sensor_port: str = INPUT_4,
                 ir_beacon_channel: int = 1):
        self.tank_driver = MoveTank(left_motor_port=left_foot_motor_port,
                                    right_motor_port=right_foot_motor_port,
                                    motor_class=LargeMotor)

        self.bazooka_blast_motor = MediumMotor(
            address=bazooka_blast_motor_port)

        self.touch_sensor = TouchSensor(address=touch_sensor_port)
        self.color_sensor = ColorSensor(address=color_sensor_port)

        self.ir_sensor = InfraredSensor(address=ir_sensor_port)
        self.ir_beacon_channel = ir_beacon_channel

        self.leds = Leds()
        self.speaker = Sound()

    def drive_once_by_ir_beacon(self, speed: float = 100):
        # forward
        if self.ir_sensor.top_left(
                channel=self.ir_beacon_channel) and self.ir_sensor.top_right(
                    channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=speed, right_speed=speed)

        # backward
        elif self.ir_sensor.bottom_left(channel=self.ir_beacon_channel
                                        ) and self.ir_sensor.bottom_right(
                                            channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=-speed, right_speed=-speed)

        # turn left on the spot
        elif self.ir_sensor.top_left(channel=self.ir_beacon_channel
                                     ) and self.ir_sensor.bottom_right(
                                         channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=-speed, right_speed=speed)

        # turn right on the spot
        elif self.ir_sensor.top_right(
                channel=self.ir_beacon_channel) and self.ir_sensor.bottom_left(
                    channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=speed, right_speed=-speed)

        # turn left forward
        elif self.ir_sensor.top_left(channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=0, right_speed=speed)

        # turn right forward
        elif self.ir_sensor.top_right(channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=speed, right_speed=0)

        # turn left backward
        elif self.ir_sensor.bottom_left(channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=0, right_speed=-speed)

        # turn right backward
        elif self.ir_sensor.bottom_right(channel=self.ir_beacon_channel):
            self.tank_driver.on(left_speed=-speed, right_speed=0)

        # otherwise stop
        else:
            self.tank_driver.off(brake=False)

    def keep_driving_by_ir_beacon(self, speed: float = 100):
        while True:
            self.drive_once_by_ir_beacon(speed=speed)

    def dance_whenever_ir_beacon_pressed(self):
        while True:
            while self.ir_sensor.beacon(channel=self.ir_beacon_channel):
                self.tank_driver.on_for_seconds(left_speed=randint(-100, 100),
                                                right_speed=randint(-100, 100),
                                                seconds=1,
                                                brake=False,
                                                block=True)

    def keep_detecting_objects_by_ir_sensor(self):
        while True:
            if self.ir_sensor.proximity < 25:
                self.leds.animate_police_lights(color1=Leds.ORANGE,
                                                color2=Leds.RED,
                                                group1=Leds.LEFT,
                                                group2=Leds.RIGHT,
                                                sleeptime=0.5,
                                                duration=5,
                                                block=False)

                self.speaker.play_file(wav_file='/home/robot/sound/Object.wav',
                                       volume=100,
                                       play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                self.speaker.play_file(
                    wav_file='/home/robot/sound/Detected.wav',
                    volume=100,
                    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                self.speaker.play_file(
                    wav_file='/home/robot/sound/Error alarm.wav',
                    volume=100,
                    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

            else:
                self.leds.all_off()

    def blast_bazooka_whenever_touched(self):
        while True:
            if self.touch_sensor.is_pressed:
                if self.color_sensor.ambient_light_intensity < 5:  # 15 not dark enough
                    self.speaker.play_file(
                        wav_file='/home/robot/sound/Up.wav',
                        volume=100,
                        play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                    self.bazooka_blast_motor.on_for_rotations(speed=100,
                                                              rotations=-3,
                                                              brake=True,
                                                              block=True)

                    self.speaker.play_file(
                        wav_file='/home/robot/sound/Laughing 1.wav',
                        volume=100,
                        play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                else:
                    self.speaker.play_file(
                        wav_file='/home/robot/sound/Down.wav',
                        volume=100,
                        play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                    self.bazooka_blast_motor.on_for_rotations(speed=100,
                                                              rotations=3,
                                                              brake=True,
                                                              block=True)

                    self.speaker.play_file(
                        wav_file='/home/robot/sound/Laughing 2.wav',
                        volume=100,
                        play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                self.touch_sensor.wait_for_released()

    def main(self, driving_speed: float = 100):
        # FIXME
        # Unhandled exception in thread started by <bound_method b6bbfd60 <Thread object at b6bbe450>.<function run at 0xb6bb4a20>>
        # Traceback (most recent call last):
        #   File "threading/threading.py", line 15, in run
        #   File "ev3dev2/sensor/lego.py", line 885, in top_left
        #   File "ev3dev2/sensor/lego.py", line 919, in buttons_pressed
        #   File "ev3dev2/sensor/__init__.py", line 203, in value
        #   File "ev3dev2/__init__.py", line 307, in get_attr_int
        # ValueError: invalid syntax for integer with base 10: ''
        Thread(target=self.dance_whenever_ir_beacon_pressed).start()

        # DON'T use IR Sensor in 2 different modes in the same program / loop
        # - https://github.com/pybricks/support/issues/62
        # - https://github.com/ev3dev/ev3dev/issues/1401
        # Thread(target=self.keep_detecting_objects_by_ir_sensor).start()

        Thread(target=self.blast_bazooka_whenever_touched).start()

        self.keep_driving_by_ir_beacon(speed=driving_speed)
Exemple #13
0
#!/usr/bin/env python3
from ev3dev2.sensor.lego import TouchSensor, UltrasonicSensor
from ev3dev2.led import Leds
from time import sleep
# Connect ultrasonic and touch sensors to any sensor port
us = UltrasonicSensor()
ts = TouchSensor()
leds = Leds()
leds.all_off()  # stop the LEDs flashing (as well as turn them off)
while not ts.is_pressed:
    if us.distance_centimeters < 30:  # to detect objects closer than 40cm
        # In the above line you can also use inches: us.distance_inches < 16
        leds.set_color('LEFT', 'RED')
        leds.set_color('RIGHT', 'RED')
    else:
        leds.set_color('LEFT', 'GREEN')
        leds.set_color('RIGHT', 'GREEN')
    sleep(0.01)  # Give the CPU a rest
Exemple #14
0
def menu(choices, before_run_function=None, after_run_function=None, skip_to_next_page=True):
    """
    Console Menu that accepts choices and corresponding functions to call.
    The user must press the same button twice: once to see their choice highlited,
    a second time to confirm and run the function. The EV3 LEDs show each state change:
    Green = Ready for button, Amber = Ready for second button, Red = Running
    Parameters:
    - `choices` a dictionary of tuples "button-name": ("mission-name", function-to-call)
    NOTE: Don't call functions with parentheses, unless preceded by lambda: to defer the call
    - `before_run_function` when not None, call this function before each mission run, passed with mission-name
    - `after_run_function` when not None, call this function after each mission run, passed with mission-name
    """

    global proc
    console = Console()
    leds = Leds()
    button = Button()

    leds.all_off()
    leds.set_color("LEFT", "GREEN")
    leds.set_color("RIGHT", "GREEN")
    menu_positions = get_positions(console)

    last = None  # the last choice--initialize to None

    while True:
        # display the menu of choices, but show the last choice in inverse
        console.reset_console()
        for btn, (name, _) in choices.items():
            align, col, row = menu_positions[btn]
            console.text_at(name, col, row, inverse=(btn == last), alignment=align)

        pressed = wait_for_button_press(button)

        # get the choice for the button pressed
        if pressed in choices:
            if last == pressed:   # was same button pressed?
                console.reset_console()
                leds.set_color("LEFT", "RED")
                leds.set_color("RIGHT", "RED")

                # call the user's subroutine to run the mission, but catch any errors
                try:
                    name, mission_function = choices[pressed]
                    if before_run_function is not None:
                        before_run_function(name)
                    if name in ('NEXT', 'BACK', 'OFF'):
                        mission_function()
                    else:
                        # launch a sub process so it could be canceled with the enter button
                        # store the subprocess in self to reference in the stop function
                        proc = Process(target=mission_function)
                        debug('Starting {}'.format(name))
                        proc.start()
                        debug('Just started {} in proc {}'.format(name, proc.pid))
                        sleep(1)
                        proc.terminate()
                        # TODO: Need to figure out when to call self.proc.join
                except Exception as e:
                    print("**** Exception when running")
                    debug('Exception when running {}'.format(e))
                finally:
                    if after_run_function is not None:
                        after_run_function(name)
                    last = None
                    leds.set_color("LEFT", "GREEN")
                    leds.set_color("RIGHT", "GREEN")
            else:   # different button pressed
                last = pressed
                leds.set_color("LEFT", "AMBER")
                leds.set_color("RIGHT", "AMBER")
Exemple #15
0
#!/usr/bin/env python3
from ev3dev2.led import Leds
from time import sleep
led = Leds()
led.all_off()  # 모든 led 오프
sleep(1)
# 왼쪽 LED는 빨강, 오른쪽 LED는 노랑
led.set_color('LEFT', 'RED')
led.set_color('RIGHT', 'YELLOW')
sleep(3)
# RED 밝기와 GREEN 밝기 비율로 색을 만듬.
#(RED밝기,GREEN 밝기) 100%는 1로 스케일 설정
led.set_color('LEFT', (1, 0))  # 밝은 RED
led.set_color('RIGHT', (0, 1))  # 밝은 GREEN.
sleep(3)
Exemple #16
0
    while True:
        txt = Chat.receive()
        if not "//NOPRINT//" in txt:
            Printer.addToQueue(txt.rstrip())
            Printer.addToQueue(" ")
        Chat.send("[BTTRC] - Nachricht erhalten!", nosound=True)


if __name__ == "__main__":
    from ev3dev2.button import Button
    from ev3dev2.led import Leds

    l = Leds()
    b = Button()

    l.all_off()
    l.set_color("LEFT", "RED")
    l.set_color("RIGHT", "RED")

    print("[BTTRC] - Starten...")

    printprocess = Process(target=processQueue)
    printprocess.start()

    chat2printprocess = Process(target=chat2print)
    chat2printprocess.start()

    morse2chatprocess = Process(target=morse2chat)
    morse2chatprocess.start()

    Chat.send("[BTTRC] - Gestartet!", nosound=True)
Exemple #17
0
def menu(choices, before_run_function=None, after_run_function=None):
    """
    Console Menu that accepts choices and corresponding functions to call.
    The user must press the same button twice: once to see their choice highlited,
    a second time to confirm and run the function. The EV3 LEDs show each state change:
    Green = Ready for button, Amber = Ready for second button, Red = Running
    Parameters:
    - `choices` a dictionary of tuples "button-name": ("mission-name", function-to-call)
        Example:
            choices = {
                # "button-name": ("mission-name", function-to-call)
                # or "button-name": ("mission-name", lambda: call(x, y, z))
                "enter": ("CAL", lambda: auto_calibrate(robot, 1.0)),
                "up": ("MI2", fmission2),
                "right": ("MI3", fmission3),
                "down": ("MI4", fmission4),
                "left": ("MI5", fmission5)
            }
        where fmission2, fmission3 are functions;
        note don't call them with parentheses, unless preceded by lambda: to defer the call
    - `before_run_function` when not None, call this function before each mission run, passed with mission-name
    - `after_run_function` when not None, call this function after each mission run, passed with mission-name
    """

    console = Console()
    leds = Leds()
    button = Button()

    leds.all_off()
    leds.set_color("LEFT", "GREEN")
    leds.set_color("RIGHT", "GREEN")
    menu_positions = get_positions(console)

    last = None  # the last choice--initialize to None

    while True:
        # display the menu of choices, but show the last choice in inverse
        console.reset_console()
        for btn, (name, _) in choices.items():
            align, col, row = menu_positions[btn]
            console.text_at(name, col, row, inverse=(btn == last), alignment=align)

        pressed = wait_for_button_press(button)

        # get the choice for the button pressed
        if pressed in choices:
            if last == pressed:   # was same button pressed?
                console.reset_console()
                leds.set_color("LEFT", "RED")
                leds.set_color("RIGHT", "RED")

                # call the user's subroutine to run the mission, but catch any errors
                try:
                    name, mission_function = choices[pressed]
                    if before_run_function is not None:
                        before_run_function(name)
                    mission_function()
                except Exception as ex:
                    print("**** Exception when running")
                    print(ex)
                finally:
                    if after_run_function is not None:
                        after_run_function(name)
                    last = None
                    leds.set_color("LEFT", "GREEN")
                    leds.set_color("RIGHT", "GREEN")
            else:   # different button pressed
                last = pressed
                leds.set_color("LEFT", "AMBER")
                leds.set_color("RIGHT", "AMBER")
Exemple #18
0
class Ev3rstorm(RemoteControlledTank):
    def __init__(self,
                 left_foot_motor_port: str = OUTPUT_B,
                 right_foot_motor_port: str = OUTPUT_C,
                 bazooka_blast_motor_port: str = OUTPUT_A,
                 touch_sensor_port: str = INPUT_1,
                 color_sensor_port: str = INPUT_3,
                 ir_sensor_port: str = INPUT_4,
                 ir_beacon_channel: int = 1):
        super().__init__(left_motor_port=left_foot_motor_port,
                         right_motor_port=right_foot_motor_port,
                         polarity=Motor.POLARITY_NORMAL,
                         speed=1000,
                         channel=ir_beacon_channel)

        self.tank_driver = MoveTank(left_motor_port=left_foot_motor_port,
                                    right_motor_port=right_foot_motor_port,
                                    motor_class=LargeMotor)

        self.bazooka_blast_motor = MediumMotor(
            address=bazooka_blast_motor_port)

        self.touch_sensor = TouchSensor(address=touch_sensor_port)
        self.color_sensor = ColorSensor(address=color_sensor_port)

        self.ir_sensor = InfraredSensor(address=ir_sensor_port)
        self.ir_beacon_channel = ir_beacon_channel

        self.leds = Leds()
        self.speaker = Sound()

    def dance_whenever_ir_beacon_pressed(self):
        while True:
            while self.ir_sensor.beacon(channel=self.ir_beacon_channel):
                self.tank_driver.on_for_seconds(left_speed=randint(-100, 100),
                                                right_speed=randint(-100, 100),
                                                seconds=1,
                                                brake=False,
                                                block=True)

    def keep_detecting_objects_by_ir_sensor(self):
        while True:
            if self.ir_sensor.proximity < 25:
                self.leds.animate_police_lights(color1=Leds.ORANGE,
                                                color2=Leds.RED,
                                                group1=Leds.LEFT,
                                                group2=Leds.RIGHT,
                                                sleeptime=0.5,
                                                duration=5,
                                                block=False)

                self.speaker.play_file(wav_file='/home/robot/sound/Object.wav',
                                       volume=100,
                                       play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                self.speaker.play_file(
                    wav_file='/home/robot/sound/Detected.wav',
                    volume=100,
                    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                self.speaker.play_file(
                    wav_file='/home/robot/sound/Error alarm.wav',
                    volume=100,
                    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

            else:
                self.leds.all_off()

    def blast_bazooka_whenever_touched(self):
        while True:
            if self.touch_sensor.is_pressed:
                if self.color_sensor.ambient_light_intensity < 5:  # 15 not dark enough
                    self.speaker.play_file(
                        wav_file='/home/robot/sound/Up.wav',
                        volume=100,
                        play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                    self.bazooka_blast_motor.on_for_rotations(speed=100,
                                                              rotations=-3,
                                                              brake=True,
                                                              block=True)

                else:
                    self.speaker.play_file(
                        wav_file='/home/robot/sound/Down.wav',
                        volume=100,
                        play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                    self.bazooka_blast_motor.on_for_rotations(speed=100,
                                                              rotations=3,
                                                              brake=True,
                                                              block=True)

                self.touch_sensor.wait_for_released()

    def main(self):
        Thread(target=self.dance_whenever_ir_beacon_pressed,
               daemon=True).start()

        # DON'T use IR Sensor in 2 different modes in the same program / loop
        # - https://github.com/pybricks/support/issues/62
        # - https://github.com/ev3dev/ev3dev/issues/1401
        # Thread(target=self.keep_detecting_objects_by_ir_sensor).start()

        Thread(target=self.blast_bazooka_whenever_touched, daemon=True).start()

        super().main()  # RemoteControlledTank.main()
Exemple #19
0
def main():

    colourSensorAttachments = ColorSensor(constants.INPUT_COLOUR_SENSOR_ATTACHMENTS)

    leds = Leds()
    leds.all_off()


    # Set up debugging level ..

    # debug = constants.DEBUG_NONE 
    debug = constants.DEBUG | constants.DEBUG_THREAD_LIFECYCLE

    if debug:
        print('Waiting for an accessory ..', file=stderr)


    # Load JSON and strip out comments ..

    programsXML = ET.parse('data/programs.xml')
    programs = programsXML.getroot()

    
    while True:

        rgb = colourSensorAttachments.raw

        for program in programs:

            rProgram = int(program.get('r'))
            gProgram = int(program.get('g'))
            bProgram = int(program.get('b'))

            print(rgb, file=stderr)
            if abs(rgb[0] - rProgram) < constants.COLOUR_TOLERANCE and abs(rgb[1] - gProgram) < constants.COLOUR_TOLERANCE and abs(rgb[2] - bProgram) < constants.COLOUR_TOLERANCE:

                if debug:
                    print("Run {}".format(program.get('name')), file = stderr)


                # Load progam into memory ..

                dataXML = ET.parse('data/' + program.get('fileName'))
                steps = dataXML.getroot()

                threadPool = []
                stop_threads = False

                for step in steps:

                    inParallel = False if step.get('action') == 'launchInSerial' else True
                    thread = threading.Thread(target = launchSteps, args = (debug, lambda: stop_threads, step, inParallel))
                    threadPool.append(thread)
                    thread.start()

                    allThreadsCompleted = False

                    while not allThreadsCompleted:

                        if RobotLifted.isRobotLifted(debug, constants.ROBOT_LIFTED_USE_TOUCH_SENSOR):
                            stop_threads = True

                        for thread in threadPool:
                            if not thread.isAlive():
                                threadPool.remove(thread)

                        if not threadPool:
                            allThreadsCompleted = True


                        # If the robot has been lifted then exist the 'while' loop ..

                        if stop_threads:
                            break

                        sleep(0.1) # Give the CPU a rest


                    # If the robot has been lifted then exit the 'while' loop ..

                    if stop_threads:
                        break
               

    if debug:
        print('Finished.', file = stderr)
Exemple #20
0
            except Exception:
                return request_auth()
            user, pwd = decoded.split(b":", 1)
            try:
                proc = subprocess.run(
                    ["htpasswd", "-i", "-v", ".htpasswd", user],
                    timeout=1,
                    input=pwd)
            except subprocess.TimeoutExpired:
                return request_auth()
            if proc.returncode != 0:
                return request_auth()


LEDS = Leds()
LEDS.all_off()
LEDS.reset()

move_joystick = None
motors = {}
old_joystick_left_port = None
old_joystick_right_port = None
old_motor_1_port = None
old_motor_2_port = None


class EV3InfoHandler(BasicAuthHandler, tornado.websocket.WebSocketHandler):
    websockets = set()
    websockets_lock = Lock()

    def open(self):
#!/usr/bin/env python3
from ev3dev2.sensor.lego import InfraredSensor
from ev3dev2.led import Leds
from sys import stderr
from time import sleep

ir = InfraredSensor()
leds = Leds()

print(ir.driver_name, file=stderr)

leds.all_off()  # To stop the LEDs flashing
while True:
    if ir.proximity < 40 * 1.4:  # To convert cm to proximity, multiply by 1.4
        leds.set_color('LEFT', 'RED')
        leds.set_color('RIGHT', 'RED')
    else:
        leds.set_color('LEFT', 'GREEN')
        leds.set_color('RIGHT', 'GREEN')
    print(str(int(ir.proximity * 0.7)) + ' cm approx', file=stderr)
    # To convert proximity to cm, multiply by 0.7.
    sleep(0.5)
class Ev3rstorm(IRBeaconRemoteControlledTank):
    def __init__(
            self,
            left_foot_motor_port: str = OUTPUT_B, right_foot_motor_port: str = OUTPUT_C,
            bazooka_blast_motor_port: str = OUTPUT_A,
            touch_sensor_port: str = INPUT_1, color_sensor_port: str = INPUT_3,
            ir_sensor_port: str = INPUT_4, ir_beacon_channel: int = 1):
        super().__init__(
            left_motor_port=left_foot_motor_port, right_motor_port=right_foot_motor_port, motor_class=LargeMotor,
            ir_sensor_port=ir_sensor_port, ir_beacon_channel=ir_beacon_channel)

        self.bazooka_blast_motor = MediumMotor(address=bazooka_blast_motor_port)

        self.touch_sensor = TouchSensor(address=touch_sensor_port)
        self.color_sensor = ColorSensor(address=color_sensor_port)

        self.leds = Leds()
        self.speaker = Sound()
        self.screen = Display()

    
    def dance_whenever_ir_beacon_pressed(self):
        while True:
            while self.ir_sensor.beacon(channel=self.tank_drive_ir_beacon_channel):
                self.tank_driver.on_for_seconds(
                    left_speed=randint(-100, 100),
                    right_speed=randint(-100, 100),
                    seconds=1,
                    brake=False,
                    block=True)
                    

    def keep_detecting_objects_by_ir_sensor(self):
        while True:
            if self.ir_sensor.proximity < 25: 
                self.leds.animate_police_lights(
                    color1=Leds.ORANGE,
                    color2=Leds.RED,
                    group1=Leds.LEFT,
                    group2=Leds.RIGHT,
                    sleeptime=0.5,
                    duration=5,
                    block=False)
                
                self.speaker.play_file(
                    wav_file='/home/robot/sound/Object.wav',
                    volume=100,
                    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                self.speaker.play_file(                                  
                    wav_file='/home/robot/sound/Detected.wav',
                    volume=100,
                    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                self.speaker.play_file(
                    wav_file='/home/robot/sound/Error alarm.wav',
                    volume=100,
                    play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

            else:
                self.leds.all_off()


    def blast_bazooka_whenever_touched(self):
        while True:
            if self.touch_sensor.is_pressed:
                if self.color_sensor.ambient_light_intensity < 5:   # 15 not dark enough
                    self.speaker.play_file(
                        wav_file='/home/robot/sound/Up.wav',
                        volume=100,
                        play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                    self.bazooka_blast_motor.on_for_rotations(
                        speed=100,
                        rotations=-3,
                        brake=True,
                        block=True)

                    self.speaker.play_file(
                        wav_file='/home/robot/sound/Laughing 1.wav',
                        volume=100,
                        play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                else:
                    self.speaker.play_file(
                        wav_file='/home/robot/sound/Down.wav',
                        volume=100,
                        play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                    self.bazooka_blast_motor.on_for_rotations(
                        speed=100,
                        rotations=3,
                        brake=True,
                        block=True)

                    self.speaker.play_file(
                        wav_file='/home/robot/sound/Laughing 2.wav',
                        volume=100,
                        play_type=Sound.PLAY_WAIT_FOR_COMPLETE)

                self.touch_sensor.wait_for_released()
        
    
    def main(self, driving_speed: float = 100):
        self.screen.image_filename(
            filename='/home/robot/image/Target.bmp',
            clear_screen=True)
        self.screen.update()

        # FIXME
        # Traceback (most recent call last):
        # File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
        #   self.run()
        # File "/usr/lib/python3.5/threading.py", line 862, in run
        #   self._target(*self._args, **self._kwargs)
        # File "/home/robot/Ev3rstorm/Ev3rstorm-Super.EV3Dev2.Python3.Threading.py", line 170, in dance_whenever_ir_beacon_pressed
        #   while self.ir_sensor.beacon(channel=self.ir_beacon_channel):
        # File "/usr/lib/python3/dist-packages/ev3dev2/sensor/lego.py", line 909, in beacon
        #   return 'beacon' in self.buttons_pressed(channel)
        # File "/usr/lib/python3/dist-packages/ev3dev2/sensor/lego.py", line 919, in buttons_pressed
        #   return self._BUTTON_VALUES.get(self.value(channel), [])
        # File "/usr/lib/python3/dist-packages/ev3dev2/sensor/__init__.py", line 203, in value
        #   self._value[n], value = self.get_attr_int(self._value[n], 'value' + str(n))
        # File "/usr/lib/python3/dist-packages/ev3dev2/__init__.py", line 307, in get_attr_int
        #   return attribute, int(value)
        # ValueError: invalid literal for int() with base 10: ''
        Thread(target=self.dance_whenever_ir_beacon_pressed,
               daemon=True).start()

        # DON'T use IR Sensor in 2 different modes in the same program / loop
        # - https://github.com/pybricks/support/issues/62
        # - https://github.com/ev3dev/ev3dev/issues/1401
        # Thread(target=self.keep_detecting_objects_by_ir_sensor,
        #        daemon=True).start()

        Thread(target=self.blast_bazooka_whenever_touched,
               daemon=True).start()

        self.keep_driving_by_ir_beacon(speed=driving_speed)