コード例 #1
0
ファイル: shared_all.py プロジェクト: menlosparks/fll
def any_button_pressed(waiting_color=Color.RED):
    brick.light(waiting_color)

    while not any(brick.buttons()):
        wait(150)
    brick.light(Color.BLACK)
    return brick.buttons().copy()
コード例 #2
0
def bilderZeigen():
    '''
    Zeigt alle Bilder
    '''
    # Ist zu kompliziert im Moment
    import inspect
    members = inspect.getmembers(ImageFile)
    members = [(name, data) for (name, data) in members
               if not name.startswith('_')]
    i = 0
    while True:
        name, data = members[i]
        print('ImageFile.{}'.format(name))
        brick.display.clear()
        brick.display.image(data)
        brick.display.text("")
        brick.display.text('ImageFile.{}'.format(name))
        wait(50)
        buttons = brick.buttons()
        while not any(buttons):
            buttons = brick.buttons()
            wait(10)
        if Button.RIGHT in buttons:
            i += 1
        if Button.LEFT in buttons:
            i -= 1
        if Button.CENTER in buttons:
            pass
        if Button.UP in buttons:
            i = 0
        if Button.DOWN in buttons:
            break
        print("i={}".format(i))
        if abs(i) >= len(members):
            i = 0
コード例 #3
0
def soundAbspielen():
    '''
    Spielt alle Töne ab
    '''
    # Ist zu kompliziert im Moment
    import inspect
    members = inspect.getmembers(SoundFile)
    members = [(name, data) for (name, data) in members
               if not name.startswith('_')]
    i = 0
    while True:
        name, data = members[i]
        print('SoundFile.{}'.format(name))
        brick.display.clear()
        brick.display.text("")
        brick.display.text('SoundFile.{}'.format(name))
        brick.sound.file(data)
        wait(50)
        buttons = brick.buttons()
        while not any(buttons):
            buttons = brick.buttons()
            wait(10)
        if Button.RIGHT in buttons:
            i += 1
        if Button.LEFT in buttons:
            i -= 1
        if Button.CENTER in buttons:
            pass
        if Button.UP in buttons:
            i = 0
        if Button.DOWN in buttons:
            break
        print("i={}".format(i))
        if not i < len(members):
            i = 0
コード例 #4
0
def WaitForButton():
    print("Please unplug the EV3 then press any button to continue.")
    while not any(brick.buttons()):
        NewColor()
        wait(100)

    while any(brick.buttons()):
        wait(10)
コード例 #5
0
ファイル: main.py プロジェクト: limingzhou23/Python
def buttonLoop(robot):
    while True:
        if not any(brick.buttons()):
            wait(10)
        else:
            if Button.LEFT in brick.buttons():
                robot.setSpeed(-1)
            elif Button.RIGHT in brick.buttons():
                robot.setSpeed(1)
            elif Button.CENTER in brick.buttons():
                robot.setSpeed(0)
            elif Button.UP in brick.buttons():
                return robot.inactive()
            wait(500)
コード例 #6
0
def Jerry():
    threshold = 500
    count = 0

    while not Button.CENTER in brick.buttons():
        while True:
            while sonarSensor.distance() < threshold:
                # give Jerry an initial speed boost
                # the closer the object is to Jerry, the faster the speed boost
                pid = (threshold - sonarSensor.distance()) * 0.75

                # only the first time Jerry detects an object close to it
                if count == 0:
                    robot.drive(-pid, 0)
                else:
                    robot.drive(-100, 0)

                # slows down after hitting a wall
                if (touchSensor.pressed() == True):
                    # backs up, changes direction, and starts running at normal speed
                    robot.drive(100, 0)
                    robot.drive_time(100, 90, 1000)
                    count = 1
            while sonarSensor.distance() >= threshold:
                # staying idle and just spinning
                left_motor.dc(20)
                wait(100)
コード例 #7
0
def proportional(calibrate_val):
    # initialize local variables
    left_val = left_sensor.read()
    right_val = right_sensor.read()
    run = True
    speed = 100  # values determined from testing to be the best four our robot
    desired_r = 200  # desired right sensor value
    desired_l = 200  # desired left sensor value
    k_p = 2  # proportional constant

    while run and (count < 1000):
        left_val = left_sensor.read(
        ) + calibrate_val  # left sensor was determined through testing to need a static offeset to match the right sensor's value
        right_val = right_sensor.read()
        left_speed = (
            k_p * (left_val - desired_l)
        ) + speed  # left side transfer function from the sensor output to the motor input
        right_speed = (
            k_p * (right_val - desired_r)
        ) + speed  # right side transfer function from the sensor output to the motor input
        left_motor.run(left_speed)
        right_motor.run(right_speed)

        if Button.CENTER in brick.buttons():
            # ends run loop
            run = False

    # ends main loop
    return True
コード例 #8
0
def control_motor(button1, button2, motor, limit_reached, speed, speed_unit,
                  speed_max):
    if limit_reached:
        brick.sound.beeps(1)
        motor.stop(Stop.HOLD)
        new_speed = 0
    else:
        new_speed = speed
        if button1 in brick.buttons():
            new_speed = speed + speed_unit
        elif button2 in brick.buttons():
            new_speed = speed - speed_unit
        new_speed = min(new_speed, speed_max)
        new_speed = max(new_speed, -speed_max)
        motor.run(new_speed)
    return new_speed
コード例 #9
0
ファイル: main.py プロジェクト: suryavip/ev3py-RPM-sensor
 def poll(self):
     while True:
         state = self.button in brick.buttons()
         if state == True and self.lastState == False:
             self.ifPressed()
         self.lastState = state
         wait(10)
コード例 #10
0
def control_grip(released):
    if Button.CENTER in brick.buttons():
        if released:
            motor_grip.run_until_stalled(200, Stop.HOLD, 50)  # pick
        else:
            motor_grip.run_target(200, -90)  # release
        return not released
    return released
コード例 #11
0
def wait_for_buttonpress():
    # waiting for next command
    brick.sound.file('OOT_PauseMenu_Select.wav')
    brick.light(Color.RED)
    while not any(brick.buttons()):
        wait(10)

    # running next command acknowledgement
    brick.light(Color.GREEN)
コード例 #12
0
def SensorTest():

    while not Button.LEFT in brick.buttons():
        brick.display.text(colorSensor.ambient())

    while not Button.RIGHT in brick.buttons():
        brick.display.text(touchSensor.pressed())

    while not Button.CENTER in brick.buttons():
        brick.display.text(sonarSensor.distance())

    while not Button.DOWN in brick.buttons():
        left_motor.dc(30)
        wait(2000)
        left_motor.dc(0)

    while not Button.UP in brick.buttons():
        right_motor.dc(30)
        wait(2000)
        right_motor.dc(0)
コード例 #13
0
def displayMenu():
    # Clear display

    # Create a menu for the missions
    selectedMission = 0
    length = len(missionList)
    repaint = True

    while True:
        if repaint:
            brick.display.clear()
            brick.display.text("City Shaper Missions:", (0, 20))
            for i in range(length):
                if i == selectedMission:
                    prefix = ">>> "
                else:
                    prefix = "    "
                brick.display.text(prefix + str(i) + ". " + missionList[i])
            repaint = False
        up_pressed = Button.UP in brick.buttons()
        down_pressed = Button.DOWN in brick.buttons()
        center_pressed = Button.CENTER in brick.buttons()
        if center_pressed:
            break
        elif up_pressed:
            selectedMission = selectedMission - 1
            if selectedMission < 0:
                selectedMission = 0
            repaint = True
        elif down_pressed:
            selectedMission = selectedMission + 1
            if selectedMission >= length:
                selectedMission = selectedMission - 1
            repaint = True

    return selectedMission
コード例 #14
0
ファイル: tests.py プロジェクト: pmargani/EV3Python
def display_gyro_values():

    print("HW reset, then btn press:")
    while not any(brick.buttons()):
        wait(50)

    robot = Robot()
    wait(500)
    robot.reset_gyro_angle()
    wait(500)

    while True:
        angle = robot.get_gyro_angle()
        print(angle)
        wait(50)
コード例 #15
0
ファイル: main.py プロジェクト: 0xJeremy/ta-me-35
def GetDataArray(tsensor):
    data = []
    down = False
    start = None
    while True:
        if Button.CENTER in brick.buttons():
            return data
        if tsensor.pressed():
            if not down:
                down = True
                start = time.time()
        else:
            if down:
                data.append(time.time() - start)
                print("New data: {}".format(data[-1]))
                down = False
コード例 #16
0
ファイル: lightSensor.py プロジェクト: pmargani/EV3Python
def calibrateLightSensor(port):
    sensor = ColorSensor(port)

    # first display values
    btns = brick.buttons()
    while len(btns) == 0:
        r = getSensorValue(sensor)
        printMsg("value on port %d: %f" % (port, r))
        printMsg("press any key")
        wait(10)
        btns = brick.buttons()

    printMsg("place over dark, then press any key")
    wait(2000)
    btns = brick.buttons()
    while len(btns) == 0:
        r = getSensorValue(sensor)
        btns = brick.buttons()

    low = r
    printMsg("dark value is %f " % low)
    printMsg("light, press any key")
    wait(2000)
    btns = brick.buttons()

    while len(btns) == 0:
        r = getSensorValue(sensor)
        btns = brick.buttons()

    high = r
    printMsg("highest value: %f" % high)

    printMsg("calibrated values:")
    wait(2000)
    btns = brick.buttons()
    while len(btns) == 0:
        r = getSensorValue(sensor)
        c = calibrateValue(r, low, high)
        btns = brick.buttons()
        printMsg("calibrated value: %f " % c)
        wait(100)

    return low, high
コード例 #17
0
def main():
    brick.sound.beep()
    sens1 = LegoPort(address = 'ev3-port:in1')
    sens1.mode = 'ev3-analog'
    utime.sleep(0.5)
    sensor_right = MySensor(Port.S1)
    sensor_left = MySensor(Port.S4)
    motor_right = Motor(Port.A)
    motor_left = Motor(Port.D)

    targetleft = 530
    targetright = 250
    KP = 3.75
    KD = .3
    KI = 0
    left_prev_error = 0
    right_prev_error = 0
    left_sum_error = 0
    right_sum_error = 0
    leftspeed = 0
    rightspeed = 0

    while not Button.CENTER in brick.buttons():
        print('left:')
        print(sensor_left.readvalue())
        print('right:')
        print(sensor_right.readvalue())

        #PID controller
        errorleft = sensor_left.readvalue() - targetleft
        print('left error:' + str(errorleft))
        errorright = sensor_right.readvalue() - targetright 
        print('right error:' str(errorright))

        leftspeed = (errorleft * KP) + ((errorleft - left_prev_error) * KD) + (left_sum_error * KI) + 375
        rightspeed = (errorright * KP) + ((errorright - right_prev_error) * KD) + (right_sum_error * KI) + 375
        
        left_prev_error = errorleft
        right_prev_error = errorright

        left_sum_error += errorleft
        right_sum_error += errorright

        motor_left.run(leftspeed)
        motor_right.run(rightspeed)
コード例 #18
0
def testButtons():
    while True:
        pressed = brick.buttons()
        # 'len' is a special function that returns the length of a list
        numPressed = len(pressed)
        print("number of buttons pressed: ", numPressed)
        print("buttons pressed: ", pressed)
        if numPressed == 1:
            # Use the []'s to acces an element in the list
            # NOTE: zero is the FIRST element, not 1!!!!
            buttonPressed = pressed[0]
            if buttonPressed == Button.LEFT:
                print("You are pressing just the LEFT button!")
        wait(1000)


# call the function!
#testButtons()
コード例 #19
0
def calibrateColorSensor(colorSensor, sensorName="", position=""):
    while not any(brick.buttons()):
        brick.display.text("Place so that ", (5, 50))
        brick.display.text(sensorName + " color")
        brick.display.text("sensor hovers over")
        brick.display.text(position)
        brick.display.text("then press")
        brick.display.text("any button")
        wait(100)
    ambienceDetected = colorSensor.ambient()
    wait(200)
    brick.display.clear()
    wait(100)
    # if (rightColorSensor.color() == Color.BLACK):
    #     print("Sees black R")
    # if (leftColorSensor.color() == Color.BLACK):
    #     print("Sees black L")
    return ambienceDetected
コード例 #20
0
ファイル: tests.py プロジェクト: pmargani/EV3Python
def prepare_gyro(port=Port.S4):
    """
    Run this before you use the gyro sensor to try and
    detect issues, and fix them.
    """

    drifting = True
    while drifting:
        drifting = test_gyro_drift(port=port)
        if drifting:
            printMsg("Detected Drift!")
            printMsg("Perform HW Cal,")
            printMsg("Then press any btn.")
            while not any(brick.buttons()):
                wait(50)
        else:
            printMsg("No Drift Detected.")

    printMsg("Gyro ready for Use!")
コード例 #21
0
ファイル: main.py プロジェクト: PedroSousa97/Python-AI-Robot
 def checkFigure(self):
     for pattern in figureSequence:
         result = match_pattern(self.matrix, globals()[pattern])
         #print(result)
         print(self.matrix)
         if (result != -1):
             for x in range(len(result[1])):
                 for y in range(len(result[1][x])):
                     if (result[1][x][y] == self.matrix[x + result[0][0]][
                             y + result[0][1]]):
                         pecasExistentes[result[1][x][y] - 1] -= 1
                         self.matrix[x + result[0][0]][y + result[0][1]] = 0
             brick.sound.file(SoundFile.DETECTED, VOLUME)
             brick.display.text(pattern)
             block = True
             while (block):
                 if Button.CENTER in brick.buttons():
                     block = False
                 wait(10)
コード例 #22
0
def proportional_derivative(calibrate_val):
    # initialize local variables
    watch = StopWatch()
    prev_time = 0  # time when the previous value was taken
    curr_time = 0  # time when the current value was taken
    prev_left = 0  # previous left sensor value
    prev_right = 0  # previous right sensor value
    curr_left = 0  # current left sensor value
    curr_right = 0  # current right sensor value
    run = True

    speed = 0  # values determined from testing to be the best four our robot
    desired_r = 200  # desired right sensor value
    desired_l = 200  # desired left sensor value
    k_p = 2  # proportional constant
    k_d = 2  # derivative constant
    while run and (count < 1000):
        curr_time = watch.time()
        if curr_time == 0:
            prev_time = curr_time
        curr_left = left_sensor.read(
        ) + calibrate_val  # left sensor was determined through testing to need a static offeset to match the right sensor's value
        curr_right = right_sensor.read()
        if prev_left == 0:
            prev_left = curr_left
        if prev_right == 0:
            prev_right = curr_right
        left_speed = prop_deriv_control(L0, L1, time0, time1, desired_l, k_p,
                                        k_d, speed)
        right_speed = prop_deriv_control(R0, R1, time0, time1, desired_r, k_p,
                                         k_d, speed)
        prev_time = curr_time
        prev_left = curr_left
        prev_right = curr_right
        left_motor.run(left_speed)
        right_motor.run(right_speed)
        if Button.CENTER in brick.buttons():
            # ends run loop
            run = False

    # ends main loop
    return True
コード例 #23
0
ファイル: main.py プロジェクト: 0xJeremy/ta-me-35
def main():
    display("Please enter training data")
    touchSensor = TouchSensor(Port.S1)
    training_data = GetDataArray(touchSensor)
    clusters = CalculateMeans(2, training_data)

    dot = min(clusters)
    dash = max(clusters)

    print("Dot length: {} sec".format(dot))
    print("Dash length: {} sec".format(dash))

    while True:
        if Button.LEFT in brick.buttons():
            break
        letter = findLetter(GetDataArray(touchSensor), dot, dash)
        if letter is None:
            print("LETTER NOT FOUND")
            display("Not found")
        else:
            print("THE LETTER IS: {}".format(letter))
            display("The letter is: {}".format(letter))
        wait(0.5)
コード例 #24
0
def bang_bang(calibrate_val):
    #initialize local variables
    wheelDiameter = 56
    wheelBase = 175
    car = DriveBase(
        left_motor, right_motor, wheelDiameter, wheelBase
    )  # used the DriveBase class in this controller for convenience
    left_val = left_sensor.read()
    right_val = right_sensor.read()
    run = True
    speed = 200  # values chosen from testing to be the best for our robot
    turn_speed = 120
    tolerance_range = 100  # Effectively controls how sensitive the controller is to changes in the light signal

    while run:
        left_val = left_sensor.read(
        ) + calibrate_val  # left sensor was determined through testing to need a static offeset to match the right sensor's value
        right_val = right_sensor.read()

        # decides to turn based on the difference between sensor values
        if (left_val > (right_val + tolerance_range)):
            # turn right
            car.drive(speed, turn_speed)
        elif (left_val < (right_val - tolerance_range)):
            # turn left
            car.drive(speed, -turn_speed)
        else:
            # drive forward
            car.drive(speed, 0)

        if Button.CENTER in brick.buttons():
            # ends run loop
            run = False

    # ends main loop
    return True
コード例 #25
0
ファイル: main.py プロジェクト: TheVinhLuong102/EV3-IoT-Train
    # check for new Train commands
    if NewTrain:
        if Train == TRAIN_STOP:
            client.publish(MQTT_Topic_4DBrix, 'mot,s')
        elif Train == TRAIN_FORW:
            client.publish(MQTT_Topic_4DBrix, 'mot,f,' + str(Speed))
        elif Train == TRAIN_BCKW:
            client.publish(MQTT_Topic_4DBrix, 'mot,b,' + str(Speed))
        NewTrain = False
        wait(WAIT_TRAIN)

    # check for new pressed buttons
    if nDebounce > 0:
        nDebounce = nDebounce - 1
        wait(1)
    elif any(brick.buttons()):
        nDebounce = DEBOUNCE
        b = brick.buttons()
        if Button.LEFT in b:
            client.publish(MQTT_Topic_Train, TRAIN_FORW)
        elif Button.RIGHT in b:
            client.publish(MQTT_Topic_Train, TRAIN_BCKW)
        elif Button.CENTER in b:
            # Stop is processed immediately
            client.publish(MQTT_Topic_4DBrix, 'mot,s')
            client.publish(MQTT_Topic_Train, TRAIN_STOP)
        elif Button.UP in b:
            client.publish(MQTT_Topic_BFMode, BFMODE_TRUE)
        elif Button.DOWN in b:
            client.publish(MQTT_Topic_BFMode, BFMODE_FALSE)
コード例 #26
0
from pybricks import ev3brick as brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                 InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
                                 SoundFile, ImageFile, Align)
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics import DriveBase

# Write your program here
brick.sound.beep()

#Exempel hämtat från
#https://antonsmindstorms.com/2019/06/15/how-to-run-python-on-an-ev3-brick/

# Clear the display
brick.display.clear()

# Print ``Hello`` near the middle of the screen
brick.display.text("Hello", (60, 50))

# Print ``World`` directly underneath it
brick.display.text("World")

# Show the current voltage
brick.display.text("Voltage is: {}".format(brick.battery.voltage()))

# Wait until a button is pressed
while not brick.buttons():
    wait(10)
コード例 #27
0
#!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.tools import print, wait, StopWatch
from pybricks.parameters import (Port, SoundFile, Button, ImageFile, Align)
from botbuilder import robot, teamalpha as alpha, teambeta as beta
missions = [
 "Images/gift.jpg", "Images/Ramp.jpg", "Images/StackBlocks.jpg", "Images/truck.jpg", ]
time = StopWatch()
Start = False
CurrentMission = 0
brick.display.image(missions[CurrentMission])

while True:
    # Wait until any of the buttons are pressed
    while not any(brick.buttons()):
        wait(10)

    if Button.DOWN in brick.buttons():
        print("It's time for the DOWN BUTTON")
        CurrentMission += 1
        if len(missions) == CurrentMission:
            CurrentMission = 0

    elif Button.UP in brick.buttons():
        print("It's time for the UP BUTTON")
        CurrentMission -= 1
        if -1 == CurrentMission:
            CurrentMission = len(missions) - 1

    elif Button.CENTER in brick.buttons():
        if Start == False:
コード例 #28
0
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                 InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
                                 SoundFile, ImageFile, Align)
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics import DriveBase

encendido = False
# Write your program here
brick.sound.beep()

# Reproduce un pitido.
brick.sound.beep()
# Inicializa un motor en el puerto B.
test_motor = Motor(Port.B)
# Enciende el motor a una rapidez de 500 grados por segundo (º/s). Hasta girar un ángulo de 90 grados.
#test_motor.run_target(500, 90)
# Reproducir otro pitido.
while True:
    if Button.LEFT in brick.buttons():
        #encendido = True
        test_motor.run(500)
    if Button.RIGHT in brick.buttons():
        #encendido = False
        test_motor.stop(Stop.BRAKE)
    
    print (brick.buttons())

# Esta vez con un tono más alto (1000 Hz) y una duración más larga (500 ms).
brick.sound.beep(1000, 2000, 100)
コード例 #29
0
ファイル: main.py プロジェクト: kentoyama/581Lab1
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
                                 SoundFile, ImageFile, Align)
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics import DriveBase

# Write your program here
right = Motor(Port.B, Direction.COUNTERCLOCKWISE)
left = Motor(Port.C, Direction.COUNTERCLOCKWISE)
stop_type = Stop.COAST
right.run_time(613.88, 4400, Stop.BRAKE, False)
left.run_time(613.88, 4400, Stop.BRAKE, True)
right.stop()
left.stop()
wait(1000)
brick.sound.beep()
while not Button.CENTER in brick.buttons():
    wait(10)

ultrasonicSensor = UltrasonicSensor(Port.S1)
stop_type = Stop.COAST

while ultrasonicSensor.distance() > 515 or ultrasonicSensor.distance(
) < 485:  # + distance the sensor is from the front of the robot

    if ultrasonicSensor.distance() > 515:
        right.run(200)
        left.run(215)
        wait(100)
        right.stop()
        left.stop()
    if ultrasonicSensor.distance() < 485:
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                 InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
                                 SoundFile, ImageFile, Align)
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics import DriveBase


brick.sound.beep()
#Sets up sensor and motors
moving_motor = Motor(Port.B)
rotating_motor = Motor(Port.A)
color_sensor = ColorSensor(Port.S1)
print("Set up motors and sensor")
#Get the deciding value
while Button.LEFT not in brick.buttons():
    wait(1)
white = color_sensor.reflection()
brick.sound.beep()
while Button.RIGHT not in brick.buttons():
    wait(1)
black = color_sensor.reflection()
brick.sound.beep()
deciding_value = (white + black)/2
print("Deciding value = %s, white = %s. black = %s" % (deciding_value, white, black))
while True:
    if color_sensor.reflection() < deciding_value: #Checks to see if the robot is on line
        brick.display.text("%s Sensed line" % color_sensor.reflection())
        print("%s Sensed line" % color_sensor.reflection())
        moving_motor.reset_angle(0)
        print("reset angle")