Example #1
0
def RedMission():

    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                     InfraredSensor, UltrasonicSensor,
                                     GyroSensor)
    from pybricks.parameters import Port, Stop, Direction, Button, Color
    from pybricks.tools import wait, StopWatch, DataLog
    from pybricks.robotics import DriveBase
    from pybricks.media.ev3dev import SoundFile, ImageFile

    # This program requires LEGO EV3 MicroPython v2.0 or higher.
    # Click "Open user guide" on the EV3 extension tab for more information.

    # Create your objects here.
    ev3 = EV3Brick()

    left_motor = Motor(Port.C)
    right_motor = Motor(Port.B)
    wheel_diameter = 56
    axle_track = 115

    robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)

    Medium_Motor = Motor(Port.A)
    Large_Motor = Motor(Port.D)

    leftcolorsensor = ColorSensor(Port.S3)
    rightcolorsensor = ColorSensor(Port.S2)

    robot.straight(200)
    robot.turn(-115)
    Medium_Motor.run_angle(300, 135, then=Stop.HOLD, wait=True)
    robot.stop(Stop.BRAKE)
    robot.settings(200)
    robot.turn(-60)
    robot.straight(400)

    robot.stop(Stop.BRAKE)
Example #2
0
def BlackMission(): # Black Run (Innovatice Architecture, Health Units, Hopscotch, Bringing Slide Figures back HOME)
    # LEFT BUTTON
    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                    InfraredSensor, UltrasonicSensor, GyroSensor)
    from pybricks.parameters import Port, Stop, Direction, Button, Color
    from pybricks.tools import wait, StopWatch, DataLog
    from pybricks.robotics import DriveBase
    from pybricks.media.ev3dev import SoundFile, ImageFile


    # This program requires LEGO EV3 MicroPython v2.0 or higher.
    # Click "Open user guide" on the EV3 extension tab for more information.

    # define your variables
    ev3 = EV3Brick()
    left_motor = Motor(Port.C)
    right_motor = Motor(Port.B)
    medium_motor = Motor(Port.A)
    large_motor = Motor(Port.D)
    wheel_diameter = 56
    axle_track = 115  
    line_sensor = ColorSensor(Port.S2)
    line_sensor1 = ColorSensor(Port.S3)
    robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)
    
    robot.settings(500) # To change the SPEED

    # Pushing our innovative architecture and the health units.
    robot.straight(-350) 
    robot.straight(50)
    robot.turn(-15)
    robot.straight(-70)
    robot.turn(-220)
    large_motor.run_angle(60,80,then=Stop.HOLD, wait=True)
    robot.stop(Stop.BRAKE)
    robot.straight(-340)
    large_motor.run_angle(60,-80,then=Stop.HOLD, wait=True)
    robot.stop(Stop.BRAKE)
Example #3
0
def init_brick():
    # Create your objects here.
    ev3 = EV3Brick()

    # Initilize our motors
    left_motor = Motor(Port.A)
    right_motor = Motor(Port.D)
    front_motor_1 = Motor(Port.C)
    front_motor_2 = Motor(Port.B)

    left_motor.reset_angle(0)
    right_motor.reset_angle(0)
    front_motor_1.reset_angle(0)
    front_motor_2.reset_angle(0)

    # Initialize the color sensor.
    left_sensor = ColorSensor(Port.S4)
    right_sensor = ColorSensor(Port.S1)

    # Speeds
    right_sensor = ColorSensor(Port.S1)
    left_sensor = ColorSensor(Port.S4)
    ARM_MOTOR_SPEED = 400
    WHEEL_DIAMETER = 92
    AXLE_TRACK = 130
    DRIVE_SPEED_FAST = 350
    DRIVE_SPEED_NORMAL = 200
    DRIVE_SPEED_SLOW = 100
    DRIVE_EXTRA_SLOW = 30
    CIRCUMFERENCE = 3.14 * WHEEL_DIAMETER # Diameter = 100mm, Circumference = 314.10mm = 1 rotation
    # Initialize the Gyro sensor
    gyro = GyroSensor(Port.S2)
    gyro.reset_angle(0)

    # All parameters are in millimeters
    robot = DriveBase(left_motor, right_motor, wheel_diameter=config.WHEEL_DIAMETER, axle_track=config.AXLE_TRACK)

    # Set the straight speed and turn rate
    robot.settings(straight_speed=config.DRIVE_SPEED_NORMAL, turn_rate=config.TURN_RATE)
Example #4
0
class Robot:
    brick = EV3Brick()
    left_wheel = Motor(Port.A)
    right_wheel = Motor(Port.D)
    wheel_diameter = 95
    axle_track = 120
    robot = DriveBase(left_wheel, right_wheel, wheel_diameter, axle_track)

    def __init__(self, name, mood):
        self.name = name
        self.mood = mood

    def tell_me_about_yourself(self):
        print("The robot's name is " + self.name + ".")
        print("This robot is " + self.mood + ".")
        print("Wheel diameter is", self.wheel_diameter, ".")
        print("Axle Track is", self.axle_track, ".")
        print()

    def move_forward(self, distance_mm):
        print("Move forward", distance_mm, ".")
        self.robot.straight(-distance_mm)
      
    def turn(self, angle):
        print("Turn", angle, "degrees.")
        self.robot.turn(angle)

    def beep(self, number_of_beeps):
        print("Beep",number_of_beeps,"times.")
        x = 1
        while x <= number_of_beeps: 
            self.brick.speaker.beep()
            wait(30)
            x = x + 1

    def move_backwards(self, distance_mm):
        print("Move backwards",distance_mm,".")
        self.robot.straight(distance_mm)
    def __init__(self,
                 left_track_motor_port: Port = Port.B,
                 right_track_motor_port: Port = Port.C,
                 bazooka_blast_motor_port: Port = Port.A,
                 touch_sensor_port: Port = Port.S1,
                 color_sensor_port: Port = Port.S3,
                 ir_sensor_port: Port = Port.S4,
                 ir_beacon_channel: int = 1):
        super().__init__(wheel_diameter=self.WHEEL_DIAMETER,
                         axle_track=self.AXLE_TRACK,
                         left_motor_port=left_track_motor_port,
                         right_motor_port=right_track_motor_port,
                         ir_sensor_port=ir_sensor_port,
                         ir_beacon_channel=ir_beacon_channel)

        self.ev3_brick = EV3Brick()

        self.bazooka_blast_motor = \
            Motor(port=bazooka_blast_motor_port,
                  positive_direction=Direction.CLOCKWISE)

        self.touch_sensor = TouchSensor(port=touch_sensor_port)
        self.color_sensor = ColorSensor(port=color_sensor_port)
    def __init__(self,
                 left_track_motor_port: Port = Port.B,
                 right_track_motor_port: Port = Port.C,
                 gripping_motor_port: Port = Port.A,
                 touch_sensor_port: Port = Port.S1,
                 ir_sensor_port: Port = Port.S4,
                 ir_beacon_channel: int = 1):
        super().__init__(wheel_diameter=self.WHEEL_DIAMETER,
                         axle_track=self.AXLE_TRACK,
                         left_motor_port=left_track_motor_port,
                         right_motor_port=right_track_motor_port,
                         ir_sensor_port=ir_sensor_port,
                         ir_beacon_channel=ir_beacon_channel)

        self.ev3_brick = EV3Brick()

        self.gripping_motor = Motor(port=gripping_motor_port,
                                    positive_direction=Direction.CLOCKWISE)

        self.touch_sensor = TouchSensor(port=touch_sensor_port)

        self.ir_sensor = InfraredSensor(port=ir_sensor_port)
        self.ir_beacon_channel = ir_beacon_channel
Example #7
0
    def __init__(self):
        # Initialize all devices
        self.ev3 = EV3Brick()
        self.usb_motor = Motor(Port.D)
        self.bt_motor = Motor(Port.C)
        self.left_button_motor = Motor(Port.B)
        self.right_button_motor = Motor(Port.A)

        # Reset all motor to mechanical stop
        self.usb_motor.run_until_stalled(-SPEED, duty_limit=50)
        self.bt_motor.run_until_stalled(-SPEED, duty_limit=20)
        self.left_button_motor.run_until_stalled(-SPEED, duty_limit=100)
        self.right_button_motor.run_until_stalled(SPEED, duty_limit=30)
        wait(500)

        # Reset the angles
        self.usb_motor.reset_angle(10)
        self.bt_motor.reset_angle(-20)
        self.left_button_motor.reset_angle(-25)
        self.right_button_motor.reset_angle(20)

        # Go to neutral position
        self.reset()
Example #8
0
    def __init__(self):

        # Sets up the brick
        self.ev3 = EV3Brick()

        # Identifies which motor is connected to which ports
        self.left_leg_motor = Motor(Port.D, Direction.COUNTERCLOCKWISE)
        self.right_leg_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE)

        # Sets up the gear ratio (automatically translates it to the correct angle)
        self.head_motor = Motor(Port.C,
                                Direction.COUNTERCLOCKWISE,
                                gears=[[1, 24], [12, 36]])

        # Sets up touch sensor
        self.touch_sensor = TouchSensor(Port.S1)

        # Sets up constants for the eye
        self.eyes_timer_1 = StopWatch()
        self.eyes_timer_1_end = 0
        self.eyes_timer_2 = StopWatch()
        self.eyes_timer_2_end = 0
        self.eyes_closed = False
Example #9
0
def button_loop():
    # Initialize the EV3 Brick.
    ev3 = EV3Brick()

    while True:
        # Wait until any Brick Button is pressed.
        while not any(ev3.buttons.pressed()):
            wait(10)

        # Respond to the Brick Button press.

        # Check whether Up Button is pressed
        if Button.UP in ev3.buttons.pressed():
            ev3.speaker.beep(600)
            step_counter_pull_up_bar_dance_battle()

            # To avoid registering the same command again, wait until
            # the Up Button is released before continuing.
            while Button.UP in ev3.buttons.pressed():
                wait(10)

        # Check whether Down Button is pressed
        if Button.DOWN in ev3.buttons.pressed():
            ev3.speaker.beep(600)
            knock_bench()

            # To avoid registering the same command again, wait until
            # the Down Button is released before continuing.
            while Button.DOWN in ev3.buttons.pressed():
                wait(10)

        if Button.LEFT in ev3.buttons.pressed():
            ev3.speaker.beep(600)
            treadmill()

            while Button.LEFT in ev3.buttons.pressed():
                wait(10)
Example #10
0
    def __init__(
            self,
            left_motor_port: Port = Port.C, right_motor_port: Port = Port.B,
            shovel_motor_port: Port = Port.A,
            touch_sensor_port: Port = Port.S1,
            ir_sensor_port: Port = Port.S4,
            tank_drive_ir_beacon_channel: int = 1,
            shovel_control_ir_beacon_channel: int = 4):
        super().__init__(
            wheel_diameter=self.WHEEL_DIAMETER, axle_track=self.AXLE_TRACK,
            left_motor_port=left_motor_port, right_motor_port=right_motor_port,
            polarity='inversed',
            ir_sensor_port=ir_sensor_port,
            ir_beacon_channel=tank_drive_ir_beacon_channel)

        self.ev3_brick = EV3Brick()

        self.shovel_motor = Motor(port=shovel_motor_port,
                                  positive_direction=Direction.CLOCKWISE)

        self.touch_sensor = TouchSensor(port=touch_sensor_port)

        self.shovel_control_ir_beacon_channel = \
            shovel_control_ir_beacon_channel
Example #11
0
    def __init__(self,
                 left_motor_port: str = Port.B,
                 right_motor_port: str = Port.C,
                 lift_motor_port: str = Port.A,
                 ir_sensor_port: str = Port.S4,
                 ir_beacon_channel: int = 1):
        self.ev3_brick = EV3Brick()

        left_motor = Motor(port=left_motor_port,
                           positive_direction=Direction.COUNTERCLOCKWISE)
        right_motor = Motor(port=right_motor_port,
                            positive_direction=Direction.COUNTERCLOCKWISE)
        self.drive_base = DriveBase(left_motor=left_motor,
                                    right_motor=right_motor,
                                    wheel_diameter=self.WHEEL_DIAMETER,
                                    axle_track=self.AXLE_TRACK)

        self.lift_motor = Motor(port=lift_motor_port,
                                positive_direction=Direction.CLOCKWISE)

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

        self.reversing = False
Example #12
0
def BlackandGreen():

    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                     InfraredSensor, UltrasonicSensor,
                                     GyroSensor)
    from pybricks.parameters import Port, Stop, Direction, Button, Color
    from pybricks.tools import wait, StopWatch, DataLog
    from pybricks.robotics import DriveBase
    from pybricks.media.ev3dev import SoundFile, ImageFile

    # This program requires LEGO EV3 MicroPython v2.0 or higher.
    # Click "Open user guide" on the EV3 extension tab for more information.

    #define your variables
    ev3 = EV3Brick()
    left_motor = Motor(Port.C)
    right_motor = Motor(Port.B)
    medium_motor = Motor(Port.A)
    large_motor = Motor(Port.D)
    wheel_diameter = 56
    axle_track = 115
    line_sensor = ColorSensor(Port.S2)
    line_sensor1 = ColorSensor(Port.S3)
    robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)
    #follows the line underneath the pull up bar until the leftsensor detects black
    BLACK = 9
    WHITE = 85
    threshold = (BLACK + WHITE) / 2
    # Set the drive speed at 100 millimeters per second.
    DRIVE_SPEED = 100
    # Set the gain of the proportional line controller. This means that for every
    PROPORTIONAL_GAIN = 1.2
    runWhile = True
    #goes straight to get ready for line following then resets the distance
    robot.straight(250)
    robot.reset()
    #starts to follow the line towards the replay logo
    while True:
        # Calculate the deviation from the threshold.
        deviation = line_sensor.reflection() - threshold
        # Calculate the turn rate.
        turn_rate = PROPORTIONAL_GAIN * deviation
        # Set the drive base speed and turn rate.
        robot.drive(DRIVE_SPEED, turn_rate)
        wait(10)
        print(robot.distance())
        if (robot.distance() >= 450):
            robot.stop(Stop.BRAKE)
            break
    #the robot pushes the phone into the replay logo and moves back to get ready to drop the health units into the replay logo
    robot.straight(-75)
    robot.stop(Stop.BRAKE)
    #the robot then turns so it is going to be perfectly into the replay logo
    robot.turn(-35)
    #the robot drops the health units
    large_motor.run_angle(100, 150)
    #then turns to an angle to go back to base
    robot.turn(50)
    robot.straight(-1000)

    wait(50)

    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                     InfraredSensor, UltrasonicSensor,
                                     GyroSensor)
    from pybricks.parameters import Port, Stop, Direction, Button, Color
    from pybricks.tools import wait, StopWatch, DataLog
    from pybricks.robotics import DriveBase
    from pybricks.media.ev3dev import SoundFile, ImageFile

    # This program requires LEGO EV3 MicroPython v2.0 or higher.
    # Click "Open user guide" on the EV3 extension tab for more information.

    # Create your objects here.
    ev3 = EV3Brick()

    left_motor = Motor(Port.C)
    right_motor = Motor(Port.B)
    medium_motor = Motor(Port.A)
    front_largeMotor = Motor(Port.D)

    wheel_diameter = 56
    axle_track = 114.3

    robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)

    ## Write your code here:

    ## The robot goes straight until the Boccia Mission's target.
    robot.straight(1060)

    ## The robot moves the large motor down to drop the cubes in the target.
    front_largeMotor.run_angle(80, 70, then=Stop.HOLD, wait=True)
    front_largeMotor.run_angle(-80, 70, then=Stop.HOLD, wait=True)

    ## Dance Mission

    ## The robot moves backwards to reach the Dance Floor so it can Dance as the last mission.
    robot.straight(-185)
    robot.turn(-70)
    robot.straight(138)

    ## The following code is all the dance moves we do for the Dance Mission.

    robot.turn(160)
    robot.turn(-160)
    robot.straight(60)
    front_largeMotor.run_target(500, 60)
    front_largeMotor.run_target(500, -40)
    robot.straight(-60)
    robot.turn(260)
    robot.turn(-260)
    robot.turn(100)
    robot.straight(40)
    robot.turn(100)
    front_largeMotor.run_angle(500, 30)
Example #13
0
def YellowMission():

    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                     InfraredSensor, UltrasonicSensor,
                                     GyroSensor)
    from pybricks.parameters import Port, Stop, Direction, Button, Color
    from pybricks.tools import wait, StopWatch, DataLog
    from pybricks.robotics import DriveBase
    from pybricks.media.ev3dev import SoundFile, ImageFile

    # This program requires LEGO EV3 MicroPython v2.0 or higher.
    # Click "Open user guide" on the EV3 extension tab for more information.

    # Create your objects here.
    ev3 = EV3Brick()
    left_motor = Motor(Port.C)
    right_motor = Motor(Port.B)
    medium_motor = Motor(Port.A)
    front_largeMotor = Motor(Port.D)
    wheel_diameter = 56
    axle_track = 115

    robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)
    # Initialize the color sensor.
    line_sensor = ColorSensor(Port.S2)
    line_sensor2 = ColorSensor(Port.S3)

    robot.straight(110)

    # Calculate the light threshold. Choose values based on your measurements.
    BLACK = 9
    WHITE = 85
    threshold = (BLACK + WHITE) / 2

    # Set the drive speed at 100 millimeters per second.
    DRIVE_SPEED = 100

    # Set the gain of the proportional line controller. This means that for every
    # percentage point of light deviating from the threshold, we set the turn
    # rate of the drivebase to 1.2 degrees per second.

    # For example, if the light value deviates from the threshold by 10, the robot
    # steers at 10*1.2 = 12 degrees per second.
    PROPORTIONAL_GAIN = 1.2
    runWhile = True
    # Start following the line endlessly.
    while runWhile:
        # Calculate the deviation from the threshold.
        deviation = line_sensor.reflection() - threshold

        # Calculate the turn rate.
        turn_rate = PROPORTIONAL_GAIN * deviation

        # Set the drive base speed and turn rate.
        robot.drive(DRIVE_SPEED, turn_rate)

        if robot.distance() == 800:
            runWhile = False

    robot.stop(Stop.BRAKE)

    robot.drive(100, 0)
    if line_sensor2 and cl.Color() == Color.BLACK:
        robot.stop(Stop.BRAKE)

    # robot stops after finishing up line following code
    robot.stop(Stop.BRAKE)

    # robot turns after finishing up line following code
    robot.turn(-103.5)
    # robot goes straight as it heads towards the mission
    robot.straight(138)
    # robot turns right for 90 degrees
    robot.turn(80)
    # robot goes straight towards the mission to line the attachment to the wheel
    robot.straight(97)
    # large motor attachment goes down to trap the wheel in
    front_largeMotor.run_angle(60, 162)
    # robot moves backwards to bring wheel outside of the large circle
    robot.straight(-115)
    # large motor releases the trapped tire
    front_largeMotor.run_angle(60, -148)
    # robot moves straight to get closer the wheel
    robot.straight(38)
    # robot turns so the wheel can get into the smaller target
    robot.turn(-40)
    robot.stop(Stop.BRAKE)
    # robot goes backwards to leave the target and the wheel inside of it
    robot.straight(-110)
    # robot turns towards the weight machine
    robot.turn(-30)
    # going straight from row machine to weight machine
    robot.straight(505)
    # stopping for accuracy.
    robot.stop(Stop.BRAKE)
    # turning towards the weight machine.
    robot.turn(30)
    # robot goes straight to get closer to the weight machine
    robot.straight(145)
    # large motor going down to complete mission (weight machine).
    front_largeMotor.run_angle(120, 130)
    # going backwards away from the weight machine
    robot.straight(-120)
    # large motor goes back up
    # front_largeMotor.run_angle(50, -100)
    ## The robot is turning away from the Weight Machine and towards the Boccia.
    robot.turn(-127)
    ## The robot is moving straight towards the Boccia Mission.
    robot.straight(290)
    # the robot turns right to turn the aim boccia with the yellow axle on the bottom of the bot.
    robot.turn(60)
    # robot.straight(-10)
    # robot.turn(15)
    # front_largeMotor.run_angle(50, 60)
    # robot.straight(55)
    # the large motor goes up to push the yellow cube down into the target area.
    front_largeMotor.run_angle(50, -50)
    robot.straight(-100)
    robot.turn(-45)
    robot.straight(900)
    robot.turn(25)
    robot.straight(700)
Example #14
0
def main():
    ev3 = EV3Brick()
    ev3.speaker.beep()
    ev3.screen.clear()
    ev3.light.on(Color.YELLOW)

    colors = ColorSensor(Port.S3)
    left_motor = Motor(Port.B, Direction.CLOCKWISE)
    right_motor = Motor(Port.C, Direction.CLOCKWISE)

    startup = True
    direction = 1

    ev3.light.off()

    while (not ev3.buttons.pressed()):

        if (not checkForLine(ev3, colors)):
            left_motor.stop()
            right_motor.stop()

            # no more line! either:
            # a) the line turned
            # b) we were not running straight and went to side of line
            # c) there was never a line to begin with

            # (b)
            newDir = findLineSmallMotion(ev3, colors, left_motor, right_motor,
                                         direction)

            if (0 != newDir):
                direction = newDir
            else:
                # (a)
                newDir = findLineLargeMotion(ev3, colors, left_motor,
                                             right_motor, direction)

                if (0 != newDir):
                    direction = -1 * newDir
                else:
                    startup = True

            # (c)
            if (startup):
                ev3.speaker.beep()

                ev3.speaker.say("put me on the line")
                while (not checkForLine(ev3, colors)):
                    wait(100)

                ev3.speaker.say("press any button to start")
                while (not ev3.buttons.pressed()):
                    wait(10)

                continue

        startup = False

        # go
        left_motor.run(400)
        right_motor.run(400)

        wait(10)
Example #15
0
def BlueMission():

    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                     InfraredSensor, UltrasonicSensor,
                                     GyroSensor)
    from pybricks.parameters import Port, Stop, Direction, Button, Color
    from pybricks.tools import wait, StopWatch, DataLog
    from pybricks.robotics import DriveBase
    from pybricks.media.ev3dev import SoundFile, ImageFile

    # This program requires LEGO EV3 MicroPython v2.0 or higher.
    # Click "Open user guide" on the EV3 extension tab for more information.

    #define your variables
    ev3 = EV3Brick()
    left_motor = Motor(Port.C)
    right_motor = Motor(Port.B)
    medium_motor = Motor(Port.A)
    large_motor = Motor(Port.D)
    wheel_diameter = 56
    axle_track = 115
    line_sensor = ColorSensor(Port.S2)
    line_sensor1 = ColorSensor(Port.S3)
    robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)

    #go front towards the step counter
    robot.straight(650)
    robot.stop(Stop.BRAKE)
    wait(20)

    #makes the robot go slower
    robot.settings(40)

    #slowly pushes the step counter by going back and front 2 times
    robot.straight(140)
    robot.stop(Stop.BRAKE)
    robot.straight(-45)
    robot.stop(Stop.BRAKE)
    robot.straight(120)
    robot.stop(Stop.BRAKE)
    robot.settings(100)
    robot.straight(-30)
    robot.stop(Stop.BRAKE)
    #the robot then turns and goes backwards
    robot.turn(45)
    robot.straight(-100)
    # the robot then goes back until the right color sensor detects back
    while True:
        robot.drive(-30, 0)
        if line_sensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break
    #the large motor attatchment comes down at the same time the robot takes a turn towards the black line underneath the pull up bar
    large_motor.run_angle(50, 170, then=Stop.HOLD, wait=False)
    left_motor.run_angle(50, -300, then=Stop.HOLD, wait=True)
    #the robot then goes straight towards that line
    robot.straight(120)
    robot.stop(Stop.BRAKE)
    #robot continues to go forwards until the left color sensor detects black
    while True:
        robot.drive(30, 0)
        if line_sensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break
    right_motor.run_angle(50, 150, then=Stop.HOLD, wait=True)
    #the robot then turns with the right motor until it detects black
    while True:
        right_motor.run(85)
        if line_sensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break
    #follows the line underneath the pull up bar until the leftsensor detects black
    BLACK = 9
    WHITE = 85
    threshold = (BLACK + WHITE) / 2
    # Set the drive speed at 100 millimeters per second.
    DRIVE_SPEED = 100
    # Set the gain of the proportional line controller. This means that for every
    PROPORTIONAL_GAIN = 1.2
    runWhile = True
    robot.reset()
    while True:
        # Calculate the deviation from the threshold.
        deviation = line_sensor.reflection() - threshold
        # Calculate the turn rate.
        turn_rate = PROPORTIONAL_GAIN * deviation
        # Set the drive base speed and turn rate.
        robot.drive(DRIVE_SPEED, turn_rate)
        wait(10)
        print(line_sensor.color())
        if line_sensor1.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break
    #the robot then turns towards the boccia aim and moves straight to push it towards the target and finishes the misison
    robot.straight(100)  #after line following, it goes straight for 100 mm
    robot.turn(50)
    robot.straight(100)
    robot.straight(-30)
    large_motor.run_angle(100, -65)
    robot.straight(-60)
    #the robot then takes a turn (at the same time bringing the attatchment down) towards the slide mission and completes the mission
    large_motor.run_angle(50, 80, then=Stop.HOLD, wait=False)
    robot.turn(-195)
    robot.straight(165)
    large_motor.run_angle(300, -120, then=Stop.HOLD, wait=True)
    robot.straight(-30)
    large_motor.run_angle(200, 120, then=Stop.HOLD, wait=True)
    ## The robot moves straight towards the mission, getting ready to attempt to push the slide figures off once more. (In case it didn't work before.)
    robot.straight(30)
    large_motor.run_angle(300, -120, then=Stop.HOLD, wait=True)
    robot.straight(-50)
    '''
Example #16
0
class ColorSorter(object):
    # Initializing objects needed
    ev3 = EV3Brick()

    # Initializing and assigning sensors
    # TODO: Update this when final robot is built
    color_sensor = ColorSensor(Port.B)
    claw_motor = Motor(Port.C)
    arm_motor = Motor(Port.D)
    conveyor_motor = Motor(Port.S1)

    # Initializing misc. values
    claw_grip_speed = -100
    claw_angle = 60
    arm_speed = -100
    arm_angle = 75
    conveyor_speed = -100
    conveyor_angle = 195

    # Initial RGB tresholds
    red_treshold = 50
    green_treshold = 50
    blue_treshold = 50

    def wait_for_button_input(self):
        while True:
            if self.ev3.buttons.pressed():
                self.ev3.speaker.beep()
                wait(500)
                break
            continue

    # TODO: Update calibrate method
    def calibrate(self, calibration_time=2):
        """
        Reads RGB values from the color sensor in the given time, and sets their average as a treshold
        """
        if calibration_time < 2:
            print(
                "Error: calibration time must be minimum 2 seconds, setting to 2 (default)..."
            )
            calibration_time = 2

        # Initializes all needed variables to calculate average
        red_value = green_value = blue_value = readings = 0

        # Uses StopWatch object to keep track of time
        start_time = time.time()

        # Reads in rgb values until calibration time is reached
        while time.time() - start_time < calibration_time:
            self.conveyor_motor.run(self.conveyor_speed)
            red, green, blue = self.color_sensor.rgb()
            red_value += red
            green_value += green
            blue_value += blue
            readings += 1
        self.conveyor_motor.stop()

        # Avoid divison by zero error
        if readings == 0:
            readings = 1

        # Updates tresholds based on average of readings
        self.red_treshold = red_value // readings + 10
        self.green_treshold = green_value // readings + 10
        self.blue_treshold = blue_value // readings + 10
        print("Calibrated")

    def run_conveyor(self):
        self.conveyor_motor.run_angle(self.conveyor_speed, self.conveyor_angle)

    # TODO: write grip open and grip close methods (or grip open/close method?)
    def grip(self):
        self.claw_motor.run_angle(self.claw_grip_speed,
                                  self.claw_angle,
                                  then=Stop.HOLD)
        self.claw_grip_speed *= -1

    def read_color(self):
        """
        Reads RGB-values from the RGB-sensor, and compares the values to find which color it is. Returns a string of the color name.
        """
        red, green, blue = self.color_sensor.rgb()
        print("R: {}, G: {}, B: {}".format(red, green, blue))
        if red > 25 and green < 15 and blue < 40:
            print("Red detected")
            return "red"
        elif 33 < red < 53 and 13 < green < 33 and 9 < blue < 29:
            print("Yellow detected")
            return "yellow"
        else:
            print("No color recognized")
            return "none"

    def arm_up(self):
        self.arm_motor.run_angle(self.arm_speed,
                                 self.arm_angle,
                                 then=Stop.HOLD)

    def arm_down(self):
        self.arm_motor.run_angle((self.arm_speed * -1),
                                 self.arm_angle,
                                 then=Stop.HOLD)
def Initialize(online):
    # dictionary for å holde på all infoen om EV3en.
    # Den inneholder  info om hvilken joystick som er koblet til,
    # navnet til filen der målingene skal lagres,
    # hvilke sensorer som skal brukes,
    # og socketobjektet som gjør det mulig å kommunisere
    # mellom PC og EV3 live (for plotting).
    # Sistnevnte tas kun med hvis det kjøres i online-modus.
    robot = {}

    # Initialiser EV3en. Dette objektet vil altså referere til EV3en,
    # og ved hjelp av denne er det mulig å få EV3en til å utføre kommandoer.
    # F.eks. vil "ev3.speaker.beep()" få robotten til å gi fra seg et lite pip.
    ev3 = EV3Brick()
    robot["brick"] = ev3

    # joystick er en dictionary som inneholder
    # all nødvendig info om joysticken.
    joystick = {}
    joystick["id"] = identifyJoystick()
    joystick["FORMAT"] = 'llHHI'
    joystick["EVENT_SIZE"] = struct.calcsize(joystick["FORMAT"])
    try:
        joystick["in_file"] = open("/dev/input/event2", "rb")
    except OSError:  # hvis ingen joystick er koblet til
        joystick["in_file"] = None
    robot["joystick"] = joystick

    # Initialiser sensorer.
    # Her legges det til alle sensorer som skal brukes i prosjektet.
    # I tillegg til sensoren,
    # må det og legges til hvilken port sensoren er koblet til.
    # Utfyllende info om de ulike sensorklassene,
    # inkludert paramerte og metoder finnes på:
    # https://docs.pybricks.com/en/latest/ev3devices.html
    # Her er det viktig å kommentere vekk de sensorene som ikke skal brukes.
    # Pass på at sensoren er koblet til den porten som er gitt som parameter!
    myColorSensor = ColorSensor(Port.S1)
    robot["myColorSensor"] = myColorSensor

    myTouchSensor = TouchSensor(Port.S2)
    robot["myTouchSensor"] = myTouchSensor

    myUltrasonicSensor = UltrasonicSensor(Port.S3)
    robot["myUltrasonicSensor"] = myUltrasonicSensor

    myGyroSensor = GyroSensor(Port.S4)
    robot["myGyroSensor"] = myGyroSensor

    # Initialiserer motorer.
    # Her legges det til alle motorer som skal brukes i prosjektet.
    # I tillegg til motorene,
    # må det og legges til hvilken port motorene er koblet til.
    # Utfyllende info om Motor-klassen,
    # inkludert parametre og metoder finnes på:
    # https://pybricks.github.io/ev3-micropython/ev3devices.html
    # Her er det viktig å kommentere vekk de motorene som ikke skal brukes.
    # Pass på at motoren er koblet til den porten som er gitt som parameter!
    motorA = Motor(Port.A)
    motorA.reset_angle(0)
    robot["motorA"] = motorA

    motorB = Motor(Port.B)
    motorB.reset_angle(0)
    robot["motorB"] = motorB

    motorC = Motor(Port.C)
    motorC.reset_angle(0)
    robot["motorC"] = motorC

    motorD = Motor(Port.D)
    motorD.reset_angle(0)
    robot["motorD"] = motorD

    # Fila hvor målingene lagres.
    # OBS: Her er 'w' parameteren gitt, slik at for hver kjøring så vil
    # alle gamle målinger slettes og erstattes med nye.
    # For andre mulige parametre, se:
    # https://docs.python.org/3/library/functions.html#open
    robot["out_file"] = open("measurements.txt", "w")

    if online:
        # Sett opp socketobjektet, og hør etter for "connection"
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        robot["sock"] = sock
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(("", 8070))
        sock.listen(1)

        # Gi et pip fra robotten samt print i terminal
        # for å vise at den er klar
        print("Waiting for connection")
        ev3.speaker.beep()

        # Motta koblingen og send tilbake "acknowledgment"
        connection, address = sock.accept()
        connection.send(b"ack")
        print("Acknowlegment sent")
        robot["connection"] = connection

    # returnerer robot dictionaryen med all informasjonen
    return robot
Example #18
0
def BlueMission(): # Blue Run (Step Counter, Pull-Up Bar, Boccia Aim, Slide, Health Unit - 1)
    # DOWN BUTTON
    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                    InfraredSensor, UltrasonicSensor, GyroSensor)
    from pybricks.parameters import Port, Stop, Direction, Button, Color
    from pybricks.tools import wait, StopWatch, DataLog
    from pybricks.robotics import DriveBase
    from pybricks.media.ev3dev import SoundFile, ImageFile


    # This program requires LEGO EV3 MicroPython v2.0 or higher.
    # Click "Open user guide" on the EV3 extension tab for more information.

    #define your variables
    ev3 = EV3Brick()
    left_motor = Motor(Port.C)
    right_motor = Motor(Port.B)
    medium_motor = Motor(Port.A)
    large_motor = Motor(Port.D)
    wheel_diameter = 56
    axle_track = 115  
    line_sensor = ColorSensor(Port.S2)
    line_sensor1 = ColorSensor(Port.S3)
    robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)
  
    # Go towards the step counter mission from base
    robot.settings(800) # Speed Change
    robot.straight(650)
    robot.stop(Stop.BRAKE)
    wait(20)

    # Slow the robot down to succesfully push the step counter. 
    robot.settings(200)

    # Slowly pushes the step counter by going backward and forward a couple times to increase reliability. 
    robot.straight(230)
    robot.straight(-20)
    robot.straight(50)
    robot.stop(Stop.BRAKE)
    
    #robot.straight(-45)
    #robot.stop(Stop.BRAKE)
    #robot.straight(120) 
    #robot.stop(Stop.BRAKE)
    
    robot.straight(-60)
    robot.stop(Stop.BRAKE)
    
    # The robot then turns and goes backwards until the right color sensor detects black. 
    #robot.settings(250,300,250,300)
    robot.turn(45)
    robot.straight(-100)

    while True:
        robot.drive(-100,0)
        if line_sensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break 

    #The large motor attatchment comes down at the same time the robot takes a turn towards 
    #the black line underneath the pull up bar
    left_motor.run_angle(50,-300,then=Stop.HOLD, wait=True)
    
    # The robot then goes straight towards the line under the pull-up bar. 
    robot.straight(120)
    robot.stop(Stop.BRAKE)
    
    # Robot continues to go forwards until the left color sensor detects black.
    while True:
        robot.drive(115,0)
        if line_sensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break 
    right_motor.run_angle(100,150,then=Stop.HOLD, wait=True)
    
    # The robot turns using the right motor until it detects black.
    while True:
        right_motor.run(100)
        if line_sensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break
    robot.straight(-90)
    large_motor.run_angle(100,150,then=Stop.HOLD, wait=True)

    robot.stop(Stop.BRAKE)
    
    robot.stop(Stop.BRAKE)

    while True:
        right_motor.run(40)
        if line_sensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break

    robot.stop(Stop.BRAKE)

    ev3.speaker.beep()
    
    BLACK = 9
    WHITE = 85
    threshold = (BLACK + WHITE) / 2
    # Set the drive speed at 100 millimeters per second.
    DRIVE_SPEED = 100
    # Set the gain of the proportional line controller. This means that for every
    PROPORTIONAL_GAIN = 1.2
    runWhile = True
    robot.reset()
    ev3.speaker.beep()
    while True:
        # Calculate the deviation from the threshold.
        deviation = line_sensor.reflection() - threshold
        # Calculate the turn rate.
        turn_rate = PROPORTIONAL_GAIN * deviation
        # Set the drive base speed and turn rate.
        robot.drive(DRIVE_SPEED, turn_rate)
        wait(10)
        print(line_sensor1.color())
        if line_sensor1.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break
    robot.stop(Stop.BRAKE)

    
    robot.stop(Stop.BRAKE)
    large_motor.run_angle(-150, 150, then=Stop.HOLD, wait=False)
    robot.turn(20)
    robot.stop(Stop.BRAKE)
    robot.settings(800)
    robot.straight(280)
    ev3.speaker.beep(3)
    while True:
        robot.drive(-115,0)
        if line_sensor.color() == Color.BLACK:
            ev3.speaker.beep(10)
            robot.stop(Stop.BRAKE)
            break 
    robot.stop(Stop.BRAKE)
    # robot.straight(-10)
    robot.stop(Stop.BRAKE)
    robot.turn(50)
    
    # left_motor.run_angle(100, 150)
    '''
    large_motor.run_angle(30,-20,then=Stop.HOLD, wait=False)
    robot.turn(10)
    robot.stop(Stop.BRAKE)
    
    large_motor.run_angle(100, -50, then=Stop.HOLD, wait=False)
    robot.turn(90)
    robot.stop(Stop.BRAKE)
    
    '''
    BLACK = 9
    WHITE = 85
    threshold = (BLACK + WHITE) / 2
    # Set the drive speed at 100 millimeters per second.
    DRIVE_SPEED = 100
    # Set the gain of the proportional line controller. This means that for every
    PROPORTIONAL_GAIN = 1.2
    runWhile = True
    robot.reset()
    ev3.speaker.beep()
    while True:
        # Calculate the deviation from the threshold.
        deviation = line_sensor.reflection() - threshold
        # Calculate the turn rate.
        turn_rate = PROPORTIONAL_GAIN * deviation
        # Set the drive base speed and turn rate.
        robot.drive(DRIVE_SPEED, turn_rate)
        wait(10)
        print(line_sensor.color())
        if robot.distance() >= 500:
            robot.stop(Stop.BRAKE)
            break
    ev3.speaker.beep(3)

    while True:
        robot.drive(40,0)
        if line_sensor1.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break

    robot.stop(Stop.BRAKE)
    ev3.speaker.beep()
    robot.straight(30)
    robot.turn(-100)
    robot.straight(70)
    large_motor.run_angle(600,150,then=Stop.HOLD, wait=True)

    while True:
        robot.drive(-50, 0)
        if line_sensor1.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break
    robot.stop(Stop.BRAKE)

    right_motor.run_angle(600,500,then=Stop.HOLD,wait=True)

    
    robot.straight(20)
    BLACK = 9
    WHITE = 85
    threshold = (BLACK + WHITE) / 2
    # Set the drive speed at 100 millimeters per second.
    DRIVE_SPEED = 100
    # Set the gain of the proportional line controller. This means that for every
    PROPORTIONAL_GAIN = 1.2
    runWhile = True
    robot.reset()
    ev3.speaker.beep()
    while True:
        # Calculate the deviation from the threshold.
        deviation = line_sensor1.reflection() - threshold
        # Calculate the turn rate.
        turn_rate = PROPORTIONAL_GAIN * deviation
        # Set the drive base speed and turn rate.
        robot.drive(DRIVE_SPEED, turn_rate)
        wait(10)
        print(line_sensor1.color())
        if robot.distance() >= 580:
            robot.stop(Stop.BRAKE)
            break
    robot.stop(Stop.BRAKE)
    
    while True:
        robot.drive(50, 0)
        if line_sensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break
    robot.stop(Stop.BRAKE)
    ev3.speaker.beep(3)

    robot.turn(-45)
    robot.stop(Stop.BRAKE)
    
    robot.straight(30)
    
    large_motor.run_angle(1000,-150,then=Stop.HOLD, wait=True)
    robot.straight(-40)
    large_motor.run_angle(1000,150,then=Stop.HOLD, wait=True)
    robot.straight(40)
    large_motor.run_angle(1000,-150,then=Stop.HOLD, wait=True)

    robot.straight(-115)
    robot.turn(95)
    robot.straight(420)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
Example #19
0
from pybricks.hubs import EV3Brick as brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                 InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import Port, Stop, Direction, Button, Color
from pybricks.tools import wait, StopWatch, DataLog
from pybricks.robotics import DriveBase
from pybricks.media.ev3dev import SoundFile, ImageFile

brick.sound.beep()
#hahaha

# test_motor = Motor(Port.B)
# test_motor.run_target(500, 90)
# brick.sound.beep(1000, 500)

if Button.LEFT in brick.buttons():
    brick.light(Color.GREEN)
    brick.sound.beep(2000, 500, 20)
    brick.sound.beeps(3)

while not any(brick.buttons()):
    wait(10)

while any(brick.buttons()):
    wait(10)

#------------------------------------------------------

brick.display.clear()  #очистка дисплея
brick.display.text("EV3", (100, 50))  #first line
brick.display.text("Mindshtorms", (100, 50))  #second line
Example #20
0
def RedMission1():

    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                     InfraredSensor, UltrasonicSensor,
                                     GyroSensor)
    from pybricks.parameters import Port, Stop, Direction, Button, Color
    from pybricks.tools import wait, StopWatch, DataLog
    from pybricks.robotics import DriveBase
    from pybricks.media.ev3dev import SoundFile, ImageFile

    # This program requires LEGO EV3 MicroPython v2.0 or higher.
    # Click "Open user guide" on the EV3 extension tab for more information.

    # Create your objects here.
    ev3 = EV3Brick()

    left_motor = Motor(Port.C)
    right_motor = Motor(Port.B)
    wheel_diameter = 56
    axle_track = 115

    robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)

    Medium_Motor = Motor(Port.A)
    Large_Motor = Motor(Port.D)

    leftcolorsensor = ColorSensor(Port.S3)
    rightcolorsensor = ColorSensor(Port.S2)

    #####

    BLACK = 9
    WHITE = 85
    threshold = (BLACK + WHITE) / 2

    ######

    robot.straight(320)
    robot.turn(110)

    while True:
        robot.drive(90, 0)
        if leftcolorsensor.reflection() <= 9:
            robot.stop(Stop.BRAKE)
            break

    robot.turn(-110)

    robot.straight(200)

    # Calculate the light threshold. Choose values based on your measurements.
    BLACK = 6
    WHITE = 85
    threshold = (BLACK + WHITE) / 2

    # Set the drive speed at 100 millimeters per second.
    DRIVE_SPEED = 110

    # Set the gain of the proportional line controller. This means that for every
    # percentage point of light deviating from the threshold, we set the turn
    # rate of the drivebase to 1.2 degrees per second.

    # For example, if the light value deviates from the threshold by 10, the robot
    # steers at 10*1.2 = 12 degrees per second.
    PROPORTIONAL_GAIN = 1.2
    runWhile = True
    # Start following the line endlessly.
    while runWhile:
        # Calculate the deviation from the threshold.
        deviation = rightcolorsensor.reflection() - threshold

        # Calculate the turn rate.
        turn_rate = PROPORTIONAL_GAIN * deviation

        # Set the drive base speed and turn rate.
        robot.drive(DRIVE_SPEED, turn_rate)

        if robot.distance() == 1000:
            runWhile = False

    # robot stops after finishing up line following code

    robot.stop(Stop.BRAKE)

    robot.straight(-40)

    robot.turn(-50)
    robot.straight(145)
    Large_Motor.run_angle(50, 90, then=Stop.HOLD, wait=True)

    #robot continues run, to do Boccia mission

    while True:
        robot.drive(-80, 0)
        if leftcolorsensor.reflection() <= 10:
            robot.stop(Stop.BRAKE)
            break

    robot.straight(80)
    robot.turn(60)
    robot.straight(100)

    Large_Motor.run_angle(-50, 150, then=Stop.HOLD, wait=True)
    robot.straight(-40)
    Large_Motor.run_angle(50, 150, then=Stop.HOLD, wait=True)

    robot.straight(-40)

    while True:
        robot.drive(-80, 0)
        if leftcolorsensor.reflection() <= 9:
            robot.stop(Stop.BRAKE)
            break

    robot.straight(40)
    robot.turn(-85)

    robot.straight(340)
    robot.turn(165)

    robot.straight(55)
    Large_Motor.run_angle(-50, 150, then=Stop.HOLD, wait=True)

    robot.straight(20)

    Medium_Motor.run_angle(150, 250, then=Stop.HOLD, wait=True)
    robot.turn(70)
    Medium_Motor.run_angle(-150, 250, then=Stop.HOLD, wait=True)
    robot.turn(-20)
    robot.straight(-35)
    Medium_Motor.run_angle(150, 250, then=Stop.HOLD, wait=True)

    robot.turn(30)
    robot.straight(-130)
Example #21
0
#!/usr/bin/env pybricks-micropython

from pybricks.hubs import EV3Brick 
brick = EV3Brick()

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
from threading import (Thread, _thread)



# create a global lock object
sound_lock =  _thread.allocate_lock()


# then use this function to play sounds
def play_file(file):
    sound_lock.acquire()
    try:
        brick.speaker.play_file(file)
    finally:
        sound_lock.release()
Example #22
0
def Initialize(online):
    """
    Initialiserer robot-dictionaryen som innheolder robot-objektet og
    en socket-forbindelse (hvis online = True) for kommunikasjon til roboten.
    Initialiserer alle sensorer og motorer.
    Initialiserer fila på EV3en som brukes for å lagre målinger.
    Det eneste som skal forandres på fra prosjekt til prosjekt er sensorer,
    motorer og hva som returneres av funksjonen.

    Parametre:
    online - bool; bestemmer om det kjøres i online modus eller ikke.
    Ved kjøring i online modus blir det satt opp ett socket-objekt
    for live kommunikasjon til PC.
    """

    # robot inneholder all info om robotten
    robot = {}

    ev3 = EV3Brick()
    robot["brick"] = ev3

    # joystick inneholder all info om joysticken.
    joystick = {}
    joystick["id"] = identifyJoystick()
    joystick["FORMAT"] = 'llHHI'
    joystick["EVENT_SIZE"] = struct.calcsize(joystick["FORMAT"])
    try:
        joystick["in_file"] = open("/dev/input/event2", "rb")
    except OSError:  # hvis ingen joystick er koblet til
        joystick["in_file"] = None
    robot["joystick"] = joystick

    # Fila hvor målingene lagres
    out_file = open("measurements.txt", "w")

    if online:
        # Sett opp socketobjektet, og hør etter for "connection"
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        robot["sock"] = sock
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(("", 8070))
        sock.listen(1)

        # Gi et pip fra robotten samt print i terminal
        # for å vise at den er klar for socketkobling fra PC
        print("Waiting for connection from computer.")
        #ev3.speaker.beep()

        # Motta koblingen og send tilbake "acknowledgment" som byte
        connection, _ = sock.accept()
        connection.send(b"ack")
        print("Acknowlegment sent to computer.")
        robot["connection"] = connection

    # Sensorer
    myColorSensor = ColorSensor(Port.S1)

    # Motorer
    # motorA = Motor(Port.A)
    # motorA.reset_angle(0)

    return robot, myColorSensor, out_file
Example #23
0
#!/usr/bin/env pybricks-micropython

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, InfraredSensor
from pybricks.media.ev3dev import SoundFile
from pybricks.parameters import Button, Direction, Port, Stop

from time import sleep

HUB = EV3Brick()

MEDIUM_MOTOR = Motor(port=Port.A, positive_direction=Direction.CLOCKWISE)
TAIL_MOTOR = Motor(port=Port.B, positive_direction=Direction.CLOCKWISE)
CHEST_MOTOR = Motor(port=Port.D, positive_direction=Direction.CLOCKWISE)

IR_SENSOR = InfraredSensor(port=Port.S4)


def drive_once_by_ir_beacon(channel: int = 1, speed: float = 1000):
    ir_beacons_pressed = set(IR_SENSOR.buttons(channel=channel))

    if ir_beacons_pressed == {Button.LEFT_UP, Button.RIGHT_UP}:
        TAIL_MOTOR.run(speed=speed)

    elif ir_beacons_pressed == {Button.LEFT_DOWN, Button.RIGHT_DOWN}:
        TAIL_MOTOR.run(speed=-speed)

    elif ir_beacons_pressed == {Button.LEFT_UP}:
        MEDIUM_MOTOR.run(speed=-500)

        TAIL_MOTOR.run(speed=speed)
Example #24
0
 def __init__(self, port):
     self.ev3=EV3Brick()
     self.cam = I2CDevice(port, 0x54)
     wait(200)
Example #25
0
def RedMission(): # Red Run (Bench Mission (including backrest removal))
    # UP BUTTON
    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                    InfraredSensor, UltrasonicSensor, GyroSensor)
    from pybricks.parameters import Port, Stop, Direction, Button, Color
    from pybricks.tools import wait, StopWatch, DataLog
    from pybricks.robotics import DriveBase
    from pybricks.media.ev3dev import SoundFile, ImageFile


    # This program requires LEGO EV3 MicroPython v2.0 or higher.
    # Click "Open user guide" on the EV3 extension tab for more information.


    # Create your objects here.
    ev3 = EV3Brick()

    left_motor = Motor(Port.C)
    right_motor = Motor(Port.B)
    wheel_diameter = 56
    axle_track = 115

    robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)

    Medium_Motor = Motor(Port.A)
    Large_Motor = Motor(Port.D)

    leftcolorsensor = ColorSensor(Port.S3)
    rightcolorsensor = ColorSensor(Port.S2)

    robot.settings(500)
    robot.straight(290)
    robot.stop(Stop.BRAKE)
    robot.settings(700,400,700,400)
    robot.turn(110)
    robot.stop(Stop.BRAKE)
    while True:
        robot.drive(200,0)
        if leftcolorsensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break 
    robot.stop(Stop.BRAKE)
    ev3.speaker.beep(3)
    robot.turn(-110)
    robot.straight(80)
    BLACK = 9
    WHITE = 85
    threshold = (BLACK + WHITE) / 2
    # Set the drive speed at 100 millimeters per second.
    DRIVE_SPEED = 100
    # Set the gain of the proportional line controller. This means that for every
    PROPORTIONAL_GAIN = 1.2
    runWhile = True
    robot.reset()
    ev3.speaker.beep()
    
    while True:
        # Calculate the deviation from the threshold.
        deviation = rightcolorsensor.reflection() - threshold
        # Calculate the turn rate.
        turn_rate = PROPORTIONAL_GAIN * deviation
        # Set the drive base speed and turn rate.
        robot.drive(DRIVE_SPEED, turn_rate)
        wait(10)
        print(rightcolorsensor.color())
        
        if robot.distance() >= 100:
            robot.stop(Stop.BRAKE)
            break
    robot.stop(Stop.BRAKE)
    BLACK = 9
    WHITE = 85
    threshold = (BLACK + WHITE) / 2
    # Set the drive speed at 100 millimeters per second.
    DRIVE_SPEED = 100
    # Set the gain of the proportional line controller. This means that for every
    PROPORTIONAL_GAIN = 1.2
    runWhile = True
    robot.reset()
    
    while True:
        # Calculate the deviation from the threshold.
        deviation = rightcolorsensor.reflection() - threshold
        # Calculate the turn rate.
        turn_rate = PROPORTIONAL_GAIN * deviation
        # Set the drive base speed and turn rate.
        robot.drive(DRIVE_SPEED, turn_rate)
        wait(10)
        print(rightcolorsensor.color())
        
        if leftcolorsensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break

    robot.turn(-25)
    robot.straight(230)
    Large_Motor.run_angle(50,100,then = Stop.HOLD, wait = True)
    
    robot.straight(-60)
    robot.turn(35)
    robot.straight(-10)
    Large_Motor.run_angle(50,-50,then = Stop.HOLD, wait = True)
    robot.straight(-85)
    robot.turn(-85)
    robot.straight(500)
    robot.turn(-20)
    robot.straight(250)
    Large_Motor.run_angle(50,-70,then = Stop.HOLD, wait = False)
    robot.turn(110)
    robot.stop(Stop.BRAKE)
Example #26
0
def BlueMission():
    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                    InfraredSensor, UltrasonicSensor, GyroSensor)
    from pybricks.parameters import Port, Stop, Direction, Button, Color
    from pybricks.tools import wait, StopWatch, DataLog
    from pybricks.robotics import DriveBase
    from pybricks.media.ev3dev import SoundFile, ImageFile


    # This program requires LEGO EV3 MicroPython v2.0 or higher.
    # Click "Open user guide" on the EV3 extension tab for more information.

    #define your variables
    ev3 = EV3Brick()
    left_motor = Motor(Port.C)
    right_motor = Motor(Port.B)
    medium_motor = Motor(Port.A)
    large_motor = Motor(Port.D)
    wheel_diameter = 56
    axle_track = 115  
    line_sensor = ColorSensor(Port.S2)
    line_sensor1 = ColorSensor(Port.S3)
    robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)

    #go front towards the step counter
    robot.settings(250)
    robot.straight(650)
    robot.stop(Stop.BRAKE)
    wait(20)

    #makes the robot go slower 
    robot.settings(40)

    #slowly pushes the step counter by going back and front 2 times
    robot.straight(140)
    robot.stop(Stop.BRAKE)
    robot.straight(-45)
    robot.stop(Stop.BRAKE)
    robot.straight(120) 
    robot.stop(Stop.BRAKE)
    robot.straight(-30)
    robot.stop(Stop.BRAKE)
    #the robot then turns and goes backwards
    robot.settings(250,500,250,500)
    robot.turn(45)
    robot.straight(-100)
    # the robot then goes back until the right color sensor detects back
    while True:
        robot.drive(-115,0)
        if line_sensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break 
    #the large motor attatchment comes down at the same time the robot takes a turn towards the black line underneath the pull up bar
    large_motor.run_angle(50,200,then=Stop.HOLD, wait=False)
    left_motor.run_angle(50,-300,then=Stop.HOLD, wait=True)
    #the robot then goes straight towards that line
    robot.straight(120)
    robot.stop(Stop.BRAKE)
    #robot continues to go forwards until the left color sensor detects black
    while True:
        robot.drive(115,0)
        if line_sensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break 
    right_motor.run_angle(50,150,then=Stop.HOLD, wait=True)
    #the robot then turns with the right motor until it detects black
    while True:
        right_motor.run(85)
        if line_sensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break
    #follows the line underneath the pull up bar until the leftsensor detects black
        #follows the line underneath the pull up bar until the leftsensor detects black
    BLACK = 9
    WHITE = 85
    threshold = (BLACK + WHITE) / 2
    # Set the drive speed at 100 millimeters per second.
    DRIVE_SPEED = 100
    # Set the gain of the proportional line controller. This means that for every
    PROPORTIONAL_GAIN = 1.2
    runWhile = True
    robot.reset()
    while True:
        # Calculate the deviation from the threshold.
        deviation = line_sensor.reflection() - threshold
        # Calculate the turn rate.
        turn_rate = PROPORTIONAL_GAIN * deviation
        # Set the drive base speed and turn rate.
        robot.drive(DRIVE_SPEED, turn_rate)
        wait(10)
        print(line_sensor1.color())
        if line_sensor1.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break
    #the robot then turns towards the boccia aim and moves straight to push it towards the target and finishes the misison 
    robot.turn(25)
    robot.straight(250)
    robot.straight(-50)
    # this is importate kekekekee
    large_motor.run_angle(75,-65)
    robot.straight(-60)
    while True:
        robot.drive(-70,0)
        if line_sensor.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            ev3.speaker.beep()
            break 
    while True:
        left_motor.run(-50)
        if line_sensor1.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            ev3.speaker.beep()
            break
    left_motor.run_angle(50, -20)
    right_motor.run_angle(50, 20)
    robot.settings(200)
    robot.straight(60)
    robot.turn(-137)
    #this is also importante jekeke
    large_motor.run_angle(50,80)
    robot.straight(143)
    large_motor.run_angle(550, -120)
    robot.straight(-40)
    large_motor.run_angle(550, 120)
    robot.straight(40)
    large_motor.run_angle(550, -120)
    large_motor.run_angle(300, 30, then=Stop.HOLD, wait=True)
    #robot.straight(40)
    large_motor.run_angle(300, -100, then=Stop.HOLD, wait=True)
    #goes to collect the health unit near the basketball (goes back to base)
    robot.straight(-200)
    robot.turn(40)
    robot.straight(556)
    robot.straight(50)
    robot.stop(Stop.BRAKE)
    while True:
        left_motor.run(50)
        if line_sensor1.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            ev3.speaker.beep()
            break
    robot.stop(Stop.BRAKE)
    
    robot.reset()
    # Calculate the light threshold. Choose values based on your measurements.
    BLACK = 9
    WHITE = 85
    threshold = (BLACK + WHITE) / 2

    # Set the drive speed at 100 millimeters per second.
    DRIVE_SPEED = 100

    # Set the gain of the proportional line controller. This means that for every
    # percentage point of light deviating from the threshold, we set the turn
    # rate of the drivebase to 1.2 degrees per second.

    # For example, if the light value deviates from the threshold by 10, the robot
    # steers at 10*1.2 = 12 degrees per second.
    PROPORTIONAL_GAIN = 1.2
    runWhile = True
    # Start following the line endlessly.
    while runWhile:
        # Calculate the deviation from the threshold.
        deviation = line_sensor1.reflection() - threshold

        # Calculate the turn rate.
        turn_rate = PROPORTIONAL_GAIN * deviation

        # Set the drive base speed and turn rate.
        robot.drive(DRIVE_SPEED, turn_rate)

        if robot.distance() >= 210:
            runWhile = False
            break
    robot.stop(Stop.BRAKE)
    robot.turn(5.244312)
    robot.straight(700)
    #the robot then goes back until the right color sensor detects back
    '''
    while True:
        if line_sensor1.color() == Color.BLACK:
            robot.stop(Stop.BRAKE)
            break 
    
    #robot.straight(980)
    '''
    robot.stop(Stop.BRAKE) 
Example #27
0
#!/usr/bin/env pybricks-micropython

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.media.ev3dev import SoundFile
from pybricks.parameters import Direction, Port, Stop

BRICK = EV3Brick()

STING_MOTOR = Motor(port=Port.D, positive_direction=Direction.CLOCKWISE)

GO_MOTOR = Motor(port=Port.B, positive_direction=Direction.CLOCKWISE)

STING_MOTOR.run_time(speed=400, time=1000, then=Stop.HOLD, wait=True)

# This block controls how far SPIK3R crawls.
GO_MOTOR.run_angle(speed=1000,
                   rotation_angle=3 * 360,
                   then=Stop.HOLD,
                   wait=True)

BRICK.speaker.play_file(file=SoundFile.ERROR_ALARM)

GO_MOTOR.run_angle(speed=-1000,
                   rotation_angle=2 * 360,
                   then=Stop.HOLD,
                   wait=True)

BRICK.speaker.play_file(file=SoundFile.ERROR_ALARM)

STING_MOTOR.run_angle(speed=-750,
Example #28
0
class Robot:
    brick = EV3Brick()
    left_wheel = Motor(Port.A)
    right_wheel = Motor(Port.D)
    gyro = GyroSensor(Port.S2, Direction.CLOCKWISE)
    wheel_diameter = 95
    axle_track = 120
    robot = DriveBase(left_wheel, right_wheel, wheel_diameter, axle_track)

    def __init__(self, name, mood):
        self.name = name
        self.mood = mood

    def tell_me_about_yourself(self):
        print("The robot's name is " + self.name + ".")
        print("This robot is " + self.mood + ".")
        print("Wheel diameter is", self.wheel_diameter, ".")
        print("Axle Track is", self.axle_track, ".")
        print()

    def move_forward(self, distance_mm):
        print("Move forward", distance_mm, ".")
        self.robot.straight(-distance_mm)

    def turn(self, angle):
        print("Turn", angle, "degrees.")
        self.robot.turn(angle)

    def gyro_reset(self):
        self.gyro.reset_angle(0)
        while self.gyro.angle() != 0:
            self.gyro.reset_angle(0)
            wait(50)

    def gyro_turn(self, degrees, direction):
        print("start: " + str(self.gyro.angle()))
        speed = 150
        if direction == Direction.CLOCKWISE:
            self.left_wheel.run(speed)
            self.right_wheel.run(-speed)
            while self.gyro.angle() < degrees:
                wait(10)
        else:
            self.left_wheel.run(-speed)
            self.right_wheel.run(speed)
            while self.gyro.angle() > degrees:
                wait(10)

        self.left_wheel.stop(Stop.BRAKE)
        self.right_wheel.stop(Stop.BRAKE)
        print("stop:  " + str(self.gyro.angle()))

    def gyro_drive(self, speed, heading, distance):
        self.robot.reset()
        actual_distance = 0
        while actual_distance < distance:
            correction = self.gyro.angle() * -10
            self.robot.drive(speed, correction)
            wait(10)
            actual_distance = self.robot.distance()

    def beep(self, number_of_beeps):
        print("Beep", number_of_beeps, "times.")
        x = 1
        while x <= number_of_beeps:
            self.brick.speaker.beep()
            wait(30)
            x = x + 1

    def move_backwards(self, distance_mm):
        print("Move backwards", distance_mm, ".")
        self.robot.straight(distance_mm)
Example #29
0
-----------------------------------------------------------------

This program requires LEGO® EV3 MicroPython v2.0.
Download: https://education.lego.com/en-us/support/mindstorms-ev3/python-for-ev3

Building instructions can be found at:
https://education.lego.com/en-us/support/mindstorms-ev3/building-instructions#robot
"""

from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor
from pybricks.parameters import Port
from pybricks.robotics import DriveBase

# Initialize the EV3 Brick.
ev3 = EV3Brick()

# Initialize the motors.
left_motor = Motor(Port.B)
right_motor = Motor(Port.C)
lift_motor = Motor(Port.A)

# Initialize the drive base.
robot = DriveBase(left_motor, right_motor, wheel_diameter=55.5, axle_track=104)






Example #30
0
def GreenMission():

    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                    InfraredSensor, UltrasonicSensor, GyroSensor)
    from pybricks.parameters import Port, Stop, Direction, Button, Color
    from pybricks.tools import wait, StopWatch, DataLog
    from pybricks.robotics import DriveBase
    from pybricks.media.ev3dev import SoundFile, ImageFile


    # This program requires LEGO EV3 MicroPython v2.0 or higher.
    # Click "Open user guide" on the EV3 extension tab for more information.


    # Create your objects here.
    ev3 = EV3Brick()

    left_motor = Motor(Port.C)
    right_motor = Motor(Port.B)
    medium_motor = Motor(Port.A)
    front_largeMotor = Motor(Port.D)

    wheel_diameter = 56
    axle_track = 114.3 

    robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)

    ## Write your code here: 
    robot.settings(300)
    ## The robot goes straight until the Boccia Mission's target. 
    robot.straight(1050)

    ## The robot moves the large motor down to drop the cubes in the target. 
    front_largeMotor.run_angle(80, 110, then=Stop.HOLD, wait=True)

    ## BOCCIA SHARE !!!
    robot.straight(-200)
    robot.turn(-100)
    robot.straight(130)
    front_largeMotor.run_angle(-80, 105, then=Stop.HOLD, wait=True)
    robot.straight(-30)
    robot.turn(-100)
    robot.straight(-80)

    
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)
    robot.turn(-100)
    robot.turn(100)


    ## Dance Mission
    '''
    #The robot moves backwards to reach the Dance Floor so it can Dance as the last mission. 
    robot.straight(-185)
    robot.turn(-80)
    robot.straight(110) 


    ## The following code is all the dance moves we do for the Dance Mission. 

    robot.turn(-75)

    robot.straight(50)

    front_largeMotor.run_angle(60, 50)

    robot.straight(40)

    front_largeMotor.run_angle(60, -50)
    
    robot.straight(-40)

    front_largeMotor.run_angle(60, 50)

    robot.straight(+30)

    front_largeMotor.run_angle(60, -50)
    
    robot.straight(-45)

    robot.turn(-500)

    robot.turn(500)

    
    front_largeMotor.run_angle(60, 50)
    robot.straight(92)
    front_largeMotor.run_angle(60, -50)
    robot.straight(-20)
    robot.straight(35)
    front_largeMotor.run_angle(60, -50)
    robot.straight(-60)
    robot.turn(100)
    robot.turn(-80)
    robot.turn(120)
    robot.turn(-400)
    
    large_motor.run_angle(20, -10)
    robot.straight(-30)

    
    robot.turn(-160)
    robot.straight(60)
    robot.straight(-60)
    robot.turn(260)
    robot.turn(-260)
    robot.turn(100)
    robot.straight(40)
    robot.turn(100)
    robot.straight(-25)
    '''
    robot.stop(Stop.BRAKE)