Beispiel #1
0
    def Launchrun():
        Sound.speak("ready to go")
        btn = Button()
        #adjust the while statement for however long you want it to go.
        while True:
            # V if up button is pressed, wait 1 second. if button is still pressed run program 1 if else run program 2 (repeat for each button)
            if btn.up:
                sleep(1)
                if btn.up:
                    Krab()
                else:
                    Krab()

            if btn.down:
                sleep(1)
                if btn.down:
                    Spider()
                else:
                    Spider()

            if btn.left:
                sleep(1)
                if btn.left:
                    Crane()
                else:
                    Crane()

            if btn.right:
                sleep(1)
                if btn.right:
                    Bulldozer()
                else:
                    Bulldozer()

            if btn.enter:
                sleep(1)
                if btn.enter:
                    Redcircle()
                else:
                    Traffic()
Beispiel #2
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
Beispiel #3
0
    def run(self):
        button = Button()

        #ultra = UltrasonicSensor(self.in1)
        infra = InfraredSensor(self.in2)
        touch = TouchSensor(self.in3)
        color = ColorSensor(self.in4)

        self.mode = 1
        self.max = 5
        while not button.backspace:
            #if self.mode == 1:
            #   print("U,Distance: %d" % ultra.distance_centimeters)
            if self.mode == 2:
                print("I,Proximity: %d" % infra.proximity)
            if self.mode == 3:
                print("T,Pressed: %s" % ("Yes" if touch.is_pressed else "No"))
            if self.mode == 4:
                print("C,Reflected light: %d" %
                      color.reflected_light_intensity)
            if self.mode == 5:
                print("C,Ambient light: %d" % color.ambient_light_intensity)
            if button.right:
                self.change_mode()
#!/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
Beispiel #5
0
import ev3dev2.fonts as fonts

# import python stand lib
import queue
import threading
import time
from time import sleep
import sys

console = Console(font='Lat15-TerminusBold20x10')
#Console.set_font(font='Lat15-TerminusBold24x12', reset_console=True)
#打印到LCD
print('start test:')

#按键
button = Button()

print('please press enter')
print(button.buttons_pressed, file=sys.stderr)
button.wait_for_pressed('enter', timeout_ms=10000)
print(button.buttons_pressed, file=sys.stderr)


def key_enter(new_state):
    print(new_state)
    print('press enter', file=sys.stderr)


#定义按键的响应函数
button.on_enter = key_enter
#!/usr/bin/python3
from multiprocessing import Process, Pipe
from multiprocessing.connection import Connection

from ev3dev2.button import Button
from ev3dev2.motor import OUTPUT_A, OUTPUT_B, SpeedPercent, MoveSteering
from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, list_sensors
from ev3dev2.sensor.lego import ColorSensor

from ev3_toys.logger import get_logger

btn = Button()
left_cs, right_cs, center_cs = ColorSensor(INPUT_1), ColorSensor(
    INPUT_2), ColorSensor(INPUT_3)
last_bl_cs = None
motors = MoveSteering(OUTPUT_B, OUTPUT_A)
logger_cs = get_logger('line.color_sensor')
logger_m = get_logger('line.motors')
SPEED_PERCENTAGE = -30
SPEED_TURN_PERCENTAGE = 5


def straight():
    motors.on(0, SpeedPercent(SPEED_PERCENTAGE))
    global last_bl_cs
    last_bl_cs = center_cs


def turn_right():
    if left_cs.reflected_light_intensity <= 15:
        motors.on(-SPEED_PERCENTAGE, SpeedPercent(SPEED_PERCENTAGE))
Beispiel #7
0
 def __init__(self):
     self.server_mac = '88:B1:11:79:C5:F6'
     self.port = 4
     self.us = UltrasonicSensor()
     self.btn = Button()
Beispiel #8
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))
Beispiel #9
0
#!/usr/bin/env python3
from ev3dev2.button import Button
from time import sleep

btn = Button()

# Do something when state of any button changes:


def left(state):
    if state:
        print('Left button pressed')
    else:
        print('Left button released')


def right(state):  # neater use of 'if' follows:
    print('Right button pressed' if state else 'Right button released')


def up(state):
    print('Up button pressed' if state else 'Up button released')


def down(state):
    print('Down button pressed' if state else 'Down button released')


def enter(state):
    print('Enter button pressed' if state else 'Enter button released')
Beispiel #10
0
#!/usr/bin/env python3 
import time
from ev3dev2.motor import LargeMotor, OUTPUT_B, OUTPUT_C, OUTPUT_D, SpeedPercent, MoveTank, MediumMotor
from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_4
from ev3dev2.sensor.lego import ColorSensor, GyroSensor
import ev3dev2.fonts as fonts
from ev3dev2.button import Button
from ev3dev2.sound import Sound
from ev3dev2.display import Display
btn = Button()
color = ColorSensor(INPUT_4)
tank_drive = MoveTank(OUTPUT_B, OUTPUT_C)  #This is the template whenever we code
gyro = GyroSensor(INPUT_1)
Sound_ = Sound()
Display_ = Display()
Sound_.play_tone(frequency=400, duration=0.5, volume=50) #plays a note so we know when the code starts
#------------------------------------------------Distance conversion--------------------------------------------------------------------------------
# Distance Conversion
wheelDiameter_mm = 56 # Look at the first number on the NUMBERxNUMBER on wheel
wheelCircumference_cm = (wheelDiameter_mm/10) * 3.14159265358979323846284338 # Convert to cm and multiply by pi for circumference
wheelCircumference_in = (wheelDiameter_mm/25.4) * 3.14159265358979323846284338 # Convert to in and multiply by pi for circumference
# inches to rotations:
# example: drive.on_for_rotations(SpeedPercent(100), SpeedPrecent(100), inToRotations(5))
# to go 5 inches
def inToRotations(inches):
    return inches/wheelCircumference_in
# centimeters to rotations:
# example: drive.on_for_rotations(SpeedPercent(100), SpeedPrecent(100), cmToRotations(5))
# to go 5 centimeters
def cmToRotations(cm):
    return cm/wheelCircumference_cm
#!/usr/bin/env python3
# An EV3 Python (library v2) solution to Exercise 3
# of the official Lego Robot Educator lessons that
# are part of the EV3 education software
import ev3dev2
from ev3dev2.motor import MoveTank, OUTPUT_B, OUTPUT_C
from ev3dev2.sensor.lego import ColorSensor
from ev3dev2.button import Button
from time import sleep
from ev3dev2.motor import SpeedNativeUnits

leftSpeeds=[]
rightSpeeds=[]
btn = Button() # we will use any button to stop script
tank_pair = MoveTank(OUTPUT_B, OUTPUT_C)
leftMotor = ev3dev2.motor.Motor(OUTPUT_B)
rightMotor = ev3dev2.motor.Motor(OUTPUT_C)
# Connect an EV3 color sensor to any sensor port.
cl = ColorSensor()

while not btn.any():
    leftSpeeds=[]
    rightSpeeds=[]
    for x in range(600):
           # exit loop when any button pressed
        # if we are over the black line (weak reflection)
        rintensity=cl.reflected_light_intensity
        lmotorpower=-((100/70)*(rintensity-70)+100)
        rmotorpower=-(100-((100/70)*(rintensity-70)+100))
        leftMotor.on(SpeedNativeUnits(lmotorpower))
        rightMotor.on(SpeedNativeUnits(rmotorpower))
Beispiel #12
0
from ev3dev2.sensor.lego import TouchSensor
from ev3dev2.led import Leds
from ev3dev2.sensor.lego import GyroSensor
from ev3dev2.sensor.lego import ColorSensor
from ev3dev2.button import Button
from ev3dev2.display import Display
import ev3dev2.fonts as fonts
from ev3dev2.sound import Sound
import logging
import time

logging.basicConfig(level=logging.DEBUG)

gyro = GyroSensor(INPUT_4)
disp = Display()
b = Button()
s = Sound()

color_left = ColorSensor(INPUT_1)
color_right = ColorSensor(INPUT_3)

# 14, 18, ...
# See all: https://python-ev3dev.readthedocs.io/en/latest/display.html
f = fonts.load('luBS18')


def show(text):
    #disp.text_grid(t, x=5, y=5)
    disp.clear()
    # 0 = left, 80 = far right?
    # align="center" doesn't seem to work
#!/usr/bin/env python3

from ev3dev2.sensor.lego import UltrasonicSensor
from ev3dev2.sensor.lego import GyroSensor
from ev3dev2.motor import MoveTank, OUTPUT_A, OUTPUT_D
from ev3dev2.button import Button
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)5s: %(message)s')
log = logging.getLogger(__name__)

gs = GyroSensor()
us = UltrasonicSensor()
tp = MoveTank(OUTPUT_A, OUTPUT_D)
button = Button()

try:
    while not button.any():
        while not button.any():
            tp.on(left_speed=50, right_speed=50)
            dist = int(us.distance_centimeters_continuous)
            log.info(dist)
            if dist < 60:
                break

        tp.on_for_rotations(50, -50, 1.15)

except (KeyboardInterrupt):
    print('interrupt')
    tp.on(left_speed=0, right_speed=0)
Beispiel #14
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")
Beispiel #15
0
def checkAbort():
    '''check if the up button is pressed, if it is, raise an exception and exit the program'''
    if Button().up:
        raise Exception("button up was pressed")
Beispiel #16
0
log.info('Stair climber starting......')

# define the touch sensor
ts = TouchSensor(INPUT_3)
# define the gyro sensor
gy = GyroSensor(INPUT_2)

# define the large motor on port B
lm_move = LargeMotor(OUTPUT_B)
# define the large motor on port D
lm_lifter = LargeMotor(OUTPUT_D)
# define the midium motor on port A
mm_move = MediumMotor(OUTPUT_A)

# define the button
btn = Button()

# define lcd display
lcd = Display()

# define sound
snd = Sound()

# define the steps to go, initial value is 0
steps = 1

# Declare function for one step
def oneStep():
	global gy
	global ts
Beispiel #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")
Beispiel #18
0
class Ev3Robot:
    def __init__(self,
                 wheel1=OUTPUT_B,
                 wheel2=OUTPUT_C,
                 wheel3=OUTPUT_A,
                 wheel4=OUTPUT_D):
        self.steer_pair = MoveSteering(wheel1, wheel2)
        self.gyro = GyroSensor()
        self.tank_pair = MoveTank(wheel1, wheel2)
        self.motor1 = LargeMotor(wheel1)
        self.motor2 = LargeMotor(wheel2)
        self.motor3 = MediumMotor(wheel3)
        self.motor4 = MediumMotor(wheel4)
        self.color1 = ColorSensor(INPUT_1)
        self.color4 = ColorSensor(INPUT_4)
        self._black1 = 0
        self._black4 = 0
        self._white1 = 100
        self._white4 = 100
        self.gyro.mode = 'GYRO-ANG'
        self.led = Leds()
        self.btn = Button()
        self.btn._state = set()

    def write_color(self, file, value):
        # opens a file
        f = open(file, "w")
        # writes a value to the file
        f.write(str(value))
        f.close()

    def read_color(self, file):
        # opens a file
        f = open(file, "r")
        # reads the value
        color = int(f.readline().strip())
        f.close()
        return color

    def pivot_right(self, degrees, speed=20):
        # makes the robot pivot to the right until the gyro sensor
        # senses that it has turned the required number of degrees
        self.tank_pair.on(left_speed=speed, right_speed=0)
        self.gyro.wait_until_angle_changed_by(degrees - 10)
        self.tank_pair.off()

    def pivot_left(self, degrees, speed=20):
        # makes the robot pivot to the left until the gyro sensor
        # senses that it has turned the required number of degrees
        self.tank_pair.on(left_speed=0, right_speed=speed)
        self.gyro.wait_until_angle_changed_by(degrees - 10)
        self.tank_pair.off()

    def old_spin_right(self, degrees, speed=20):
        #old program; don't use
        self.gyro.reset()
        value1 = self.gyro.angle
        self.tank_pair.on(left_speed=speed, right_speed=speed * -1)
        self.gyro.wait_until_angle_changed_by(degrees)
        value2 = self.gyro.angle
        self.tank_pair.on(left_speed=-30, right_speed=30)
        self.gyro.wait_until_angle_changed_by(value1 - value2 - degrees)
        self.stop()

    def old_spin_left(self, degrees, speed=20):
        #old program; don't use
        value1 = self.gyro.angle
        self.tank_pair.on(left_speed=speed * -1, right_speed=speed)
        self.gyro.wait_until_angle_changed_by(degrees)
        value2 = self.gyro.angle
        self.tank_pair.on(left_speed=8, right_speed=-8)
        self.gyro.wait_until_angle_changed_by(value2 - value1 - degrees + 5)
        self.tank_pair.off()

    def dog_gear(self, degrees, motor, speed=30):
        if motor == 3:
            self.motor3.on_for_degrees(degrees=degrees, speed=speed)
            self.motor3.off()
        else:
            self.motor4.on_for_degrees(degrees=degrees, speed=speed)

    def go_straight_forward(self, cm, speed=20, wiggle_factor=1):
        value1 = self.motor1.position
        angle0 = self.gyro.angle
        rotations = cm / 19.05  #divides by circumference of the wheel

        # calculates the amount of degrees the robot has turned, then turns the
        # opposite direction and repeats until the robot has gone the required
        # number of centimeters
        while abs(self.motor1.position - value1) / 360 < rotations:
            angle = self.gyro.angle - angle0
            self.steer_pair.on(steering=angle * wiggle_factor * -1,
                               speed=speed * -1)
        self.steer_pair.off()

    def go_straight_backward(self, cm, speed=20, wiggle_factor=1):
        # see go_straight_forward
        value1 = self.motor1.position
        angle0 = self.gyro.angle
        rotations = cm / 19.05
        while abs(self.motor1.position - value1) / 360 < rotations:
            angle = self.gyro.angle - angle0
            self.steer_pair.on(steering=angle * wiggle_factor, speed=speed)
        self.steer_pair.off()

    def calibrate(self):
        # turns the led lights orange, and waits for a button to be pressed
        # (signal that the robot is on black), then calculates the reflected
        # light intensity of the black line, then does the same on the white line
        self.led.set_color('LEFT', 'ORANGE')
        self.led.set_color('RIGHT', 'ORANGE')
        while not self.btn.any():
            sleep(0.01)
        self.led.set_color('LEFT', 'GREEN')
        self.led.set_color('RIGHT', 'GREEN')
        self._black1 = self.color1.reflected_light_intensity
        self._black4 = self.color4.reflected_light_intensity
        sleep(2)
        self.led.set_color('LEFT', 'ORANGE')
        self.led.set_color('RIGHT', 'ORANGE')

        while not self.btn.any():
            sleep(0.01)
        self.led.set_color('LEFT', 'GREEN')
        self.led.set_color('RIGHT', 'GREEN')
        self._white1 = self.color1.reflected_light_intensity
        self._white4 = self.color4.reflected_light_intensity
        sleep(3)
        self.write_color("/tmp/black1", self._black1)
        self.write_color("/tmp/black4", self._black4)
        self.write_color("/tmp/white1", self._white1)
        self.write_color("/tmp/white4", self._white4)

    def read_calibration(self):
        # reads the color files
        self._black1 = self.read_color("/tmp/black1")
        self._black4 = self.read_color("/tmp/black4")
        self._white1 = self.read_color("/tmp/white1")
        self._white4 = self.read_color("/tmp/white4")

    def align_white(self, speed=20, t=96.8, direction=1):
        # goes forward until one of the color sensors sees the white line.
        while self.calibrate_RLI(self.color1) < t and self.calibrate_RLI(
                self.color4) < t:
            self.steer_pair.on(steering=0, speed=speed * direction)
        self.steer_pair.off()
        # determines which sensor sensed the white line, then moves the opposite
        # motor until both sensors have sensed the white line
        if self.calibrate_RLI(self.color4) > t:
            while self.calibrate_RLI(self.color1) < t:
                self.motor1.on(speed=speed * direction)
            self.motor1.off()
        else:
            while self.calibrate_RLI(self.color4) < t:
                self.motor2.on(speed=speed * direction)
            self.motor2.off()

    def align_black(self, speed=20, t=4.7, direction=1):
        # see align_white
        while self.calibrate_RLI(self.color1) > t and self.calibrate_RLI(
                self.color4) > t:
            self.steer_pair.on(steering=0, speed=speed * direction)
        self.steer_pair.off()
        if self.calibrate_RLI(self.color4) < t:
            while self.calibrate_RLI(self.color1) > t:
                self.motor1.on(speed=speed * direction)
            self.motor1.off()
        else:
            while self.calibrate_RLI(self.color4) > t:
                self.motor2.on(speed=speed * direction)
            self.motor2.off()

    def align(self, t, speed=-20, direction=1):
        # aligns three times for extra accuracy
        self.align_white(speed=speed, t=100 - t, direction=direction)
        self.align_black(speed=-5, t=t, direction=direction)
        self.align_white(speed=-5, t=100 - t, direction=direction)

    def calibrate_RLI(self, color_sensor):
        # returns a scaled value based on what black and white are
        if (color_sensor.address == INPUT_1):
            black = self._black1
            white = self._white1
        else:
            black = self._black4
            white = self._white4
        return (color_sensor.reflected_light_intensity - black) / (white -
                                                                   black) * 100

    def stop(self):
        self.tank_pair.off()

    def spin_right(self, degrees, speed=30):
        self.turn(degrees, 100, speed)

    def spin_left(self, degrees, speed=30):
        self.turn(degrees, -100, speed)

    def turn(self, degrees, steering, speed=30):
        # turns at a decreasing speed until it turns the required amount of degrees
        value1 = self.gyro.angle
        s1 = speed
        d1 = 0
        while d1 < degrees - 2:
            value2 = self.gyro.angle
            d1 = abs(value1 - value2)
            slope = speed / degrees
            s1 = (speed - slope * d1) * (degrees / 90) + 3
            self.steer_pair.on(steering=steering, speed=s1)
        self.steer_pair.off()
Beispiel #19
0
#!/usr/bin/env python3
from time import sleep
import os
from ev3dev2.button import Button

os.system('setfont Lat7-Terminus12x6')
btn = Button()

with open("status") as f:
    status = f.read().strip()

descriptions = {
    "off":
    "SmartSafe will not automatically start and will have to be manually started from SSH or Brickman.",
    "display":
    "SmartSafe will start automatically with 20 secounds of bootup and will break Brickman. To exit while running use SSH or say \"alexa open lego mindstorms\" then \"control 0 auth [your password]\"",
    "nodisplay":
    "SmartSafe will start automatically and will run in the background without displaying to the screen."
}

print("The current operation mode is", status)
print("[OK]")
sleep(1)
btn.wait_for_pressed("enter")
print("To change operation mode run _off.sh, _display.sh, or _nodisplay.sh")
print("[OK]")
sleep(1)
btn.wait_for_pressed("enter")
print("In this mode", descriptions[status])
print("[OK]")
sleep(1)
Beispiel #20
0
    def Traffic():
        Sound.speak("").wait()
        MA = MediumMotor("")
        MB = LargeMotor("outB")
        MC = LargeMotor("outC")
        MD = MediumMotor("")
        GY = GyroSensor("")
        C3 = ColorSensor("")
        C4 = ColorSensor("")
        T1 = TouchSensor("")

        GY.mode = 'GYRO-ANG'
        GY.mode = 'GYRO-RATE'
        GY.mode = 'GYRO-ANG'
        tank_drive = MoveTank(OUTPUT_B, OUTPUT_C)
        loop_gyro = 0
        gyro_adjust = 1
        starting_value = GY.value()
        gyro_correct_loops = 0
        straight_correct_loops = 0
        gyro_correct_straight = 0
        # change this to whatever speed what you want
        left_wheel_speed = 100
        right_wheel_speed = 100
        tank_drive.on_for_rotations(SpeedPercent(100), SpeedPercent(100),
                                    0.01)  #wheel alignment
        # change the loop_gyro verses the defined value argument to however far you want to go
        # if Gyro value is the same as the starting value, go straight, if more turn right, if less turn left
        # change the value to how far you want the robot to go
        tank_drive.on_for_rotations(
            SpeedPercent(-30), SpeedPercent(-30),
            0.675)  # Originally 0.95 - the robot starts out from base

        while GY.value(
        ) < 85:  #gyro turns 85 degrees and faces towards the swing
            left_wheel_speed = 100
            right_wheel_speed = -100
            #MB is left wheel & MC is right wheel
            MB.run_forever(speed_sp=left_wheel_speed)
            MC.run_forever(speed_sp=right_wheel_speed)
        MB.stop(stop_action="hold")
        MC.stop(stop_action="hold")

        while MB.position > -1600:  # this is the gyro program, the first line tells the bot to continue loop until it reaches a defined position
            if GY.value(
            ) == 90:  #this runs if the gyro is OK and already straight, sets a lot of variables as well
                left_wheel_speed = -300
                right_wheel_speed = -300
                MB.run_forever(speed_sp=left_wheel_speed)
                MC.run_forever(speed_sp=right_wheel_speed)
                gyro_adjust = 8
                gyro_correct_loops = 0
                gyro_correct_straight = 0
                straight_correct_loops = 0
            else:  #if the gyro is off it runs this section of code
                if GY.value() < 90:
                    correct_rate = abs(
                        GY.value()
                    )  # This captures the gyro value at the beginning of the statement
                    right_wheel_speed = right_wheel_speed - gyro_adjust  #changes the wheel speeds accordingly
                    left_wheel_speed = left_wheel_speed + gyro_adjust
                    MB.run_forever(speed_sp=left_wheel_speed)
                    MC.run_forever(speed_sp=right_wheel_speed)
                    left_wheel_speed = -300
                    right_wheel_speed = -300
                    if abs(
                            GY.value()
                    ) >= correct_rate:  # If gyro value has worsened despite the correction then change the adjust variable for next time
                        gyro_adjust = gyro_adjust + 1
                    gyro_correct_loops = gyro_correct_loops + 1
                    if GY.value(
                    ) == 0 and gyro_correct_straight == 0:  #runs only if bot isn't already on the original line it started from
                        while straight_correct_loops < gyro_correct_loops:  #Basically this messes up the gyro again so the bot can correct back to the line it was orignally on
                            right_wheel_speed = right_wheel_speed - gyro_adjust
                            left_wheel_speed = left_wheel_speed + gyro_adjust
                            straight_correct_loops = straight_correct_loops + 1
                        gyro_correct_straight = 1  #sets this to 1 so that it doesn't go off the line again
                        gyro_correct_loops = 0
                        straight_correct_loops = 0

                else:
                    correct_rate = abs(GY.value(
                    ))  # Same idea as the other if statement, just reversed
                    left_wheel_speed = left_wheel_speed - gyro_adjust
                    right_wheel_speed = right_wheel_speed + gyro_adjust
                    MB.run_forever(speed_sp=left_wheel_speed)
                    MC.run_forever(speed_sp=right_wheel_speed)
                    left_wheel_speed = -300
                    right_wheel_speed = -300
                    gyro_correct_loops = gyro_correct_loops + 1
                    if abs(GY.value()) >= correct_rate:
                        gyro_adjust = gyro_adjust + 1
                    if GY.value() == 0 and gyro_correct_straight == 0:
                        while straight_correct_loops < gyro_correct_loops:
                            left_wheel_speed = left_wheel_speed - gyro_adjust
                            right_wheel_speed = right_wheel_speed + gyro_adjust
                            straight_correct_loops = straight_correct_loops + 1
                        gyro_correct_straight = 1
                        gyro_correct_loops = 0
                        straight_correct_loops = 0

    # stop all motors
        MB.stop(stop_action="hold")
        MC.stop(stop_action="hold")

        while GY.value(
        ) > 19:  #this turns the bot towards the circle, need to be less than straight 90 degrees
            left_wheel_speed = -100
            right_wheel_speed = 100
            #MB is left wheel & MC is right wheel
            MB.run_forever(speed_sp=left_wheel_speed)
            MC.run_forever(speed_sp=right_wheel_speed)
        MB.stop(stop_action="hold")
        MC.stop(stop_action="hold")
        tank_drive.on_for_rotations(
            SpeedPercent(-30), SpeedPercent(-30),
            1.35)  #goes forward (2.5) slightly to move the block into tan

        tank_drive.on_for_rotations(SpeedPercent(30), SpeedPercent(30),
                                    0.7)  #drives back a bit (1)

        while GY.value() < 150:  #turns to face the bridge backwards
            left_wheel_speed = 100  #originaly 200
            right_wheel_speed = -100  #originaly 200
            MB.run_forever(speed_sp=left_wheel_speed)
            MC.run_forever(speed_sp=right_wheel_speed)
        MB.stop(stop_action="hold")
        MC.stop(stop_action="hold")
        # Drives up bridge
        tank_drive.on_for_rotations(SpeedPercent(50), SpeedPercent(50),
                                    3.5)  #Onto the bridge!!
        #stop the wheels and make them brake
        MB.stop(stop_action="hold")
        MC.stop(stop_action="hold")
        btn = Button()
        while True:
            if btn.enter:
                Launchrun()
Beispiel #21
0
#!/usr/bin/env micropython
import time
from ev3dev2.motor import MoveTank, OUTPUT_A, OUTPUT_D
from ev3dev2.button import Button

btn = Button()

tank_pair = MoveTank(OUTPUT_A, OUTPUT_D)


while True:
    if btn.any():
        break

    tank_pair.on(left_speed=10, right_speed=20)
    
    time.sleep(0.05)

tank_pair.off()
Beispiel #22
0
class MindstormsGadget(AlexaGadget):
    def __init__(self):
        super().__init__(gadget_config_path='./auth.ini')

        # order queue
        self.queue = Queue()

        self.button = Button()
        self.leds = Leds()
        self.sound = Sound()
        self.console = Console()
        self.console.set_font("Lat15-TerminusBold16.psf.gz", True)

        self.dispense_motor = LargeMotor(OUTPUT_A)
        self.pump_motor = LargeMotor(OUTPUT_B)
        self.touch_sensor = TouchSensor(INPUT_1)

        # Start threads
        threading.Thread(target=self._handle_queue, daemon=True).start()
        threading.Thread(target=self._test, daemon=True).start()

    def on_connected(self, device_addr):
        self.leds.animate_rainbow(duration=3, block=False)
        self.sound.play_song((('C4', 'e3'), ('C5', 'e3')))

    def on_disconnected(self, device_addr):
        self.leds.animate_police_lights('RED',
                                        'ORANGE',
                                        duration=3,
                                        block=False)
        self.leds.set_color("LEFT", "BLACK")
        self.leds.set_color("RIGHT", "BLACK")
        self.sound.play_song((('C5', 'e3'), ('C4', 'e3')))

    def _test(self):
        while 1:
            self.button.wait_for_pressed('up')
            order = {
                'name': 'Test',
                'tea': 'Jasmine',
                'sugar': 100,
                'ice': 100
            }
            self.queue.put(order)
            sleep(1)

    def _handle_queue(self):
        while 1:
            if self.queue.empty(): continue

            order = self.queue.get()
            self._make(name=order['name'],
                       tea=order['tea'],
                       sugar=order['sugar'],
                       ice=order['ice'])

    def _send_event(self, name, payload):
        self.send_custom_event('Custom.Mindstorms.Gadget', name, payload)

    def _affirm_receive(self):
        self.leds.animate_flash('GREEN',
                                sleeptime=0.25,
                                duration=0.5,
                                block=False)
        self.sound.play_song((('C3', 'e3'), ('C3', 'e3')))

    def on_custom_mindstorms_gadget_control(self, directive):
        try:
            payload = json.loads(directive.payload.decode("utf-8"))
            print("Control payload: {}".format(payload), file=sys.stderr)
            control_type = payload["type"]

            # regular voice commands
            if control_type == "automatic":
                self._affirm_receive()
                order = {
                    "name": payload["name"] or "Anonymous",
                    "tea": payload["tea"] or "Jasmine Milk Tea",
                    "sugar": payload["sugar"] or 100,
                    "ice": payload["ice"] or 100,
                }
                self.queue.put(order)

            # series of voice commands
            elif control_type == "manual":  # Expected params: [command]
                control_command = payload["command"]

                if control_command == "dispense":
                    self._affirm_receive()
                    if payload['num']:
                        self._dispense(payload['num'])
                    else:
                        self._dispense()

                elif control_command == "pour":
                    self._affirm_receive()
                    if payload['num']:
                        self._pour(payload['num'])
                    else:
                        self._pour()

        except KeyError:
            print("Missing expected parameters: {}".format(directive),
                  file=sys.stderr)

    def _make(self, name=None, tea="Jasmine Milk Tea", sugar=100, ice=100):
        if not self.touch_sensor.is_pressed:
            # cup is not in place
            self._send_event('CUP', None)
            self.touch_sensor.wait_for_pressed()
            sleep(3)  # cup enter delay

        # mid_col = console.columns // 2
        # mid_row = console.rows // 2
        # mid_col = 1
        # mid_row = 1
        # alignment = "L"

        process = self.sound.play_file('mega.wav', 100,
                                       Sound.PLAY_NO_WAIT_FOR_COMPLETE)

        # dispense boba
        self._dispense()

        # dispense liquid
        self._pour(tea=tea)

        # self.console.text_at(
        #     s, column=mid_col, row=mid_row, alignment=alignment, reset_console=True
        # )
        # notify alexa that drink is finished
        payload = {
            "name": name,
            "tea": tea,
            "sugar": sugar,
            "ice": ice,
        }
        self._send_event("DONE", payload)

        process.kill()  # kill song
        self.sound.play_song((('C4', 'q'), ('C4', 'q'), ('C4', 'q')),
                             delay=0.1)
        self.touch_sensor.wait_for_released()

    # dispense liquid
    def _pour(self, time_in_s=10, tea="Jasmine Milk Tea"):
        # send event to alexa
        payload = {"time_in_s": time_in_s, "tea": tea}
        self._send_event("POUR", payload)
        self.pump_motor.run_forever(speed_sp=1000)
        sleep(time_in_s)
        self.pump_motor.stop()

    # dispense boba
    def _dispense(self, cycles=10):
        # send event to alexa
        payload = {"cycles": cycles}
        self._send_event("DISPENSE", payload)

        # ensure the dispenser resets to the correct position everytime
        if cycles % 2:
            cycles += 1

        # agitate the boba to make it fall
        for i in range(cycles):
            deg = 45 if i % 2 else -45
            self.dispense_motor.on_for_degrees(SpeedPercent(75), deg)
            sleep(0.5)
Beispiel #23
0
#!/usr/bin/env python3
# Before running the drawbot script, run this script and
# use the left and right buttons
# to make the medium motor cam point upwards.

from ev3dev2.motor import MediumMotor
from ev3dev2.button import Button
from time import sleep

medium_motor = MediumMotor()
btn = Button()


# Press left button to turn medium motor left (counterclockwise)
def left(state):
    if state:  # if state = True
        medium_motor.on(speed=-10)
    else:
        medium_motor.stop()


# Press right button to turn medium motor right (clockwise)
def right(state):
    if state:
        medium_motor.on(speed=10)
    else:
        medium_motor.stop()


btn.on_left = left
btn.on_right = right
Beispiel #24
0
ent_sc_esq = INPUT_3
ent_sc_dir = INPUT_4
ent_us_lat = INPUT_2
ent_us_fr = INPUT_1

steering_pair = MoveSteering(ent_motor_esq, ent_motor_dir)
garra_g = LargeMotor(ent_motor_grande)
garra_m = MediumMotor(ent_motor_medio)

cor_esq = ColorSensor(ent_sc_esq)
cor_dir = ColorSensor(ent_sc_dir)
usl = UltrasonicSensor(ent_us_lat)
usf = UltrasonicSensor(ent_us_fr)

sound = Sound()
btn = Button()

#   FUNÇÕES
# Reconhecimento de cor
# RGBtoHSV
# escalarRGB
# definir_rgbmax
# cor
# autocompletar
# Movimentação
#alinhamento
#girar_pro_lado

# Reconhecimento de cor

Beispiel #25
0
ent_sc_esq = INPUT_3
ent_sc_dir = INPUT_4
ent_us_lat = INPUT_2
ent_us_fr = INPUT_1

steering_pair = MoveSteering(ent_motor_esq, ent_motor_dir)
garra_g = LargeMotor(ent_motor_grande)
garra_m = MediumMotor(ent_motor_medio)

cor_esq = ColorSensor(ent_sc_esq)
cor_dir = ColorSensor(ent_sc_dir)
usl = UltrasonicSensor(ent_us_lat)
usf = UltrasonicSensor(ent_us_fr)

sound = Sound()
btn = Button()

#   FUNÇÕES


def distancia(sensor):
    a1 = sensor.distance_centimeters
    sleep(0.1)
    a2 = sensor.distance_centimeters
    sleep(0.1)
    a3 = sensor.distance_centimeters
    sleep(0.1)
    distancia = max(a1, a2, a3)
    return distancia

 def __init__(self):
     """Initialize the finite state machine class"""
     self.handlers = {}
     self.start_state = None
     self.end_states = []
     self.btn = Button()
Beispiel #27
0
#^^^^This line is required to tell the EV3 to run this file using Python|it is called a shebang line|it MUST be on the first line

# FLL 42, Pythonian Rabbotics's master program.

#---------------------------------------------------Imports and variable definitions-----------------------------------------------------------------
from ev3dev2.motor import LargeMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D, SpeedPercent, MoveTank, MediumMotor  #gives us accses to everything we need to run EV3 dev
from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3, INPUT_4
from ev3dev2.sensor.lego import ColorSensor
from ev3dev2.sensor.lego import GyroSensor
from ev3dev2.button import Button
from ev3dev2.sound import Sound
from ev3dev2.display import Display
import time
import sys

btn = Button()  # variable so we can get buttons pressed on EV3
color = ColorSensor(INPUT_4)  # color sensor for checking attachment color
tank_drive = MoveTank(
    OUTPUT_B, OUTPUT_C)  # Creates a variable so we can control the drivetrain
motorA = MediumMotor(OUTPUT_A)  # left medium motor
motorD = MediumMotor(OUTPUT_D)  # right medium motor
gyro = GyroSensor(INPUT_1)  # gyro variable
Sound_ = Sound()  # beepity beep
Display_ = Display()  # for displaying text
Sound_.play_tone(frequency=400, duration=0.5,
                 volume=50)  #plays a note so we know when the code starts
#---------------------------------------------------------------------------------------------------------------------------------------------------

#------------------------------------------------Distance conversion--------------------------------------------------------------------------------
# Distance Conversion
wheelDiameter_mm = 56  # Look at the first number on the NUMBERxNUMBER on wheel
Beispiel #28
0
class run2019:
    def __init__(self):
        self.btn = Button()
        self.LLight = LightSensor(INPUT_1)
        self.RLight = LightSensor(INPUT_4)
        self.cs = ColorSensor()

        self.drive = MoveTank(OUTPUT_A, OUTPUT_D)
        self.steer = MoveSteering(OUTPUT_A, OUTPUT_D)
        self.heightmotor = LargeMotor(OUTPUT_B)
        self.clawactuator = MediumMotor(OUTPUT_C)

        os.system('setfont Lat15-TerminusBold14')

        self.speed = 40
        self.sectionCache = 0
        self.orient = {'N': "1", 'E': "1", 'S': "1", 'W': "1"}

    def sensordata(self):
        print("Left Light Sensor: ", end="", file=sys.stderr)
        print(self.LLight.reflected_light_intensity, end=" ", file=sys.stderr)
        print("Right Light Sensor: ", end="", file=sys.stderr)
        print(self.RLight.reflected_light_intensity, file=sys.stderr)

    def turn(self, direc):  # Half - works
        self.drive.on_for_degrees(SpeedDPS(225), SpeedDPS(225), 223)
        if direc == "L" or direc == "l":
            self.steer.on_for_degrees(steering=-100,
                                      speed=SpeedDPS(720),
                                      degrees=400)
        elif direc == "R" or direc == "r":
            self.steer.on_for_degrees(steering=100,
                                      speed=SpeedDPS(720),
                                      degrees=720)
        self.steer.off()

    def dti(self,
            speed,
            n,
            startCounting=False,
            sectionCache=0):  # Drive to nth intersection
        kp = 1.1
        ki = 0
        kd = 0
        integral = 0
        perror = error = 0
        inters = 0
        piderror = 0
        while not self.btn.any(
        ):  # Remember to try stuff twice, this is a keyboard interrupt
            lv = self.LLight.reflected_light_intensity
            rv = self.RLight.reflected_light_intensity
            error = rv - lv
            integral += integral + error
            derivative = lv - perror

            piderror = (error * kp) + (integral * ki) + (derivative * kd)
            if speed + abs(piderror) > 100:
                if piderror >= 0:
                    piderror = 100 - speed
                else:
                    piderror = speed - 100
            self.drive.on(left_speed=speed - piderror,
                          right_speed=speed + piderror)
            sleep(0.01)
            perror = error

            # Drive up to nth intersection
            # These values are subject to change depending on outside factors, CHANGE ON COMPETITION DAY
            if (lv <= 50 and rv <= 55) or (lv <= 50 and rv >= 55) or (
                    lv >= 50 and rv <= 55):  # Currently at an intersection
                inters += 1
                if (startCounting == True):
                    sectionCache += 1
                if inters == n:  # Currently at nth intersection
                    self.drive.off()
                    return
                self.drive.off()
                self.drive.on_for_seconds(SpeedDPS(115), SpeedDPS(115), 1)

            print("Left Value: {}, Right Value: {}, P error: {}, Inters: {}".
                  format(lv, rv, piderror, inters),
                  file=sys.stderr)

    def main(self):
        self.heightmotor.on(speed=self.speed)
        self.heightmotor.wait_until_not_moving()
        # # while not btn.any():
        # #     sensordata()
        # # ## STORING COLOURS
        self.drive.on_for_degrees(
            left_speed=self.speed, right_speed=self.speed,
            degrees=50)  # To drive past little initial intersection
        print(self.orient, file=sys.stderr)  #DEBUG
        self.turn("L")
        # # # GO TO FIRST BNPs
        self.dti(self.speed, 5, startCounting=True)
        self.turn("L")
        self.dti(self.speed, 1)
Beispiel #29
0
#!/usr/bin/python3
from ev3dev2.motor import LargeMotor, OUTPUT_A, OUTPUT_B, OUTPUT_C, SpeedPercent, MoveTank, MediumMotor
from ev3dev2.led import Leds
from ev3dev2.button import Button
from ev3dev2.sound import Sound
from time import sleep
import os
os.system('setfont Lat15-TerminusBold14')

penLift = MediumMotor(OUTPUT_C)
penMove = LargeMotor(OUTPUT_A)
btn = Button()

penLift.on_for_degrees(speed=40, degrees=-850)
penMove.on_for_degrees(speed=20, degrees=500)
sleep(2)
while True:
    penMove.on_for_degrees(speed=20, degrees=-1000)
    penLift.on_for_degrees(speed=-20, degrees=10)
    if btn.enter:
        penMove.on_for_degrees(speed=20, degrees=500)
        penLift.on_for_degrees(speed=20, degrees=900)
        break
    penMove.on_for_degrees(speed=20, degrees=1000)
    penLift.on_for_degrees(speed=-20, degrees=10)
    if btn.enter:
        penMove.on_for_degrees(speed=20, degrees=-500)
        penLift.on_for_degrees(speed=20, degrees=900)
        break
Beispiel #30
0
class Ui(threading.Thread):
    M_FONT = 'helvB12'

    def __init__(self, config):
        threading.Thread.__init__(self)
        self.roboId = config['id']
        self.threadID = 1
        self.name = 'ui-thread'
        self.isRunning = True
        self.messageText = '-'
        self.statusText = '-'
        self.powerSupplyText = '-'
        self.lcd = Display()
        self.btn = Button()
        self.sound = Sound()
        self.leds = Leds()
        self.theFont = fonts.load(Ui.M_FONT)
        self.lcd.clear()
        self.drawText()
        self.lcd.update()

    def drawText(self):
        self.lcd.draw.text((0, 0), 'RoboRinth', font=self.theFont)
        self.lcd.draw.text((0, 14), 'ID: ' + self.roboId, font=self.theFont)
        self.lcd.draw.text((0, 28),
                           'Status: ' + self.statusText,
                           font=self.theFont)
        self.lcd.draw.text((0, 42),
                           'Msg: ' + self.messageText,
                           font=self.theFont)
        # self.lcd.draw.text((0,56), 'Pwr: ' + self.powerSupplyText, font=self.theFont)

    def run(self):
        while self.isRunning:
            self.lcd.clear()
            self.drawText()
            self.lcd.update()
            self.btn.process()
            sleep(1)
        # sleep(0.5)
        self.lcd.clear()
        self.lcd.draw.rectangle((0, 0, 178, 128), fill='white')
        self.lcd.update()

    def registerBackspaceHandler(self, backspaceHandler):
        self.btn.on_backspace = backspaceHandler

    def stop(self):
        self.isRunning = False
        self.join()

    def setMessageText(self, text):
        self.messageText = text

    def setStatusText(self, text):
        self.statusText = text

    def setPowerSupplyText(self, text):
        self.powerSupplyText = text

    def playStartSound(self):
        self.sound.tone([(800, 200, 0), (1200, 400, 100)])

    def setStatusLed(self, color):
        if color == 'green':
            self.leds.set_color('RIGHT', 'GREEN')
        elif color == 'orange':
            self.leds.set_color('RIGHT', 'ORANGE')
        else:
            print('unsupported color: ' + str(color))
Beispiel #31
0
# LARGEMOTORS USED FOR WHEELS

# Create object functions for basic movements for wheel pair blocks
steer_pair = Shiva_MoveSteering(LARGE_MOTOR_LEFT_PORT, LARGE_MOTOR_RIGHT_PORT)
steer_pair.set_polarity(LargeMotor.POLARITY_INVERSED)

tank_pair = Shiva_MoveTank(LARGE_MOTOR_LEFT_PORT, LARGE_MOTOR_RIGHT_PORT)
tank_pair.set_polarity(LargeMotor.POLARITY_INVERSED)

# Create GYROSENSOR
gyro.mode = ShivaGyro.MODE_GYRO_ANG

# Creates sound and button objects
sound = Sound()
button = Button()

# Debug print code


def debug_print(*args, **kwargs):
    '''Print debug messages to stderr.
    This shows up in the output panel in VS Code.
    '''
    print(*args, **kwargs, file=sys.stderr)


# outputs log data to VS Code instead of robot screen
log_file = open('log_data.txt', 'a+')

Beispiel #32
0
from time import sleep
from ev3dev2.button import Button
from ev3dev2.sound import Sound
from ev3dev2.display import Display
from PIL import Image
import array
import random
import os

#logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)5s: %(message)s')

log=logging.getLogger(__name__)
log.info("Starting Snake")

btn=Button()
sound=Sound()
display=Display()

# declare the variables
# direction x: 0-no move; 1-left; -1-right
dx=0
# direction y: 0-no move; 1-down; -1-up
dy=0
# Set burger position x
hx=random.randint(10, 170)
# set burger position y
hy=random.randint(20, 120)
# set the start x position of snake
Sx=[80]
# set the start y position of snake