#!/usr/bin/env pybricks-micropython

from pybricks import ev3brick as brick
from pybricks.hubs import 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 wait, StopWatch, DataLog
from pybricks.robotics import DriveBase
import time

# 모터 선언
motorB = Motor(Port.B)
motorC = Motor(Port.C)

# 초음파 센서 선언
Ultrasonic_Sensor = UltrasonicSensor(Port.S1)

while True:
    #  화면의 글자를 지우고나서, 현재 감지된 물체와의 거리를 표시한다
    brick.display.clear()
    brick.display.text(str(Ultrasonic_Sensor.distance()) + "mm")

    if Ultrasonic_Sensor.distance() >= 120:
        # 물체와의 거리가 12cm보다 길다면 직진
        motorB.run(300)
        motorC.run(300)
    elif Ultrasonic_Sensor.distance() <= 100:
        # 물체와의 거리가 10cm보다 짧다면 후진
        motorB.run(-300)
        motorC.run(-300)
    else:
Example #2
0
from pybricks.ev3devices import Motor, InfraredSensor, TouchSensor, UltrasonicSensor
from pybricks.parameters import Port, Stop, Direction, Button, Color
import os

import array
from math import *
from matplotlib import pyplot

nb_mesures = 8  # nb de mesures. Le robot tourne sur lui-même à chaque mesure de 2pi/nb_mesures

motor_rotation = 360  # à définir avec les tests
motor_speed = 600  # idem

ev3 = EV3Brick()

sens = UltrasonicSensor(Port.S4)

LeftMotor = Motor(Port.A)
RightMotor = Motor(Port.B)

vectorx = []
vectory = []

for i in range(0, nb_mesures):
    result = sens.distance()
    a = result * cos((2 * pi * i) / nb_mesures)
    b = result * sin((2 * pi * i) / nb_mesures)
    vectorx.append(int(a))
    vectory.append(int(b))
    LeftMotor.run_angle(
        motor_speed, int(motor_rotation / nb_mesures), wait=False
Example #3
0
#!/usr/bin/env pybricks-micropython
#from ev3dev2.motor import LargeMotor, OUTPUT_A, OUTPUT_B, SpeedPercent, MoveTank
#from ev3dev2.sensor import INPUT_1
#from ev3dev2.sensor.lego import TouchSensor, InfraredSensor
#from ev3dev2.led import Leds
from time import *
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, InfraredSensor, TouchSensor, UltrasonicSensor
from pybricks.parameters import  Port, Stop, Direction, Button, Color
import os


ev3 = EV3Brick()

sens = UltrasonicSensor(Port.S4)

for i in range(0,10):
    #a = sens.proximity
    a = sens.distance()
    #os.system("echo value "+str(i)+" : "+str(a)+" >> ./log.txt")
    print(a)
    sleep(2)

Example #4
0
class WallE(DriveBase):
    # Init sensors
    line_sensor = ColorSensor(Port.S1)
    ultra_sensor = UltrasonicSensor(Port.S3)
    gyro_sensor = GyroSensor(Port.S4)

    # Init motors
    left_motor = Motor(Port.A)
    right_motor = Motor(Port.B)
    front_motor = Motor(Port.C)

    # CONSTANTS
    i = 5  # Konstant der bliver brugt til at skabe interval i range funktionen
    wheel_diameter = 47.56
    axle_track = 100  # Afstand mellem to aksler, i mm

    # BLACK, WHITE, GREY er definition af lysniveauet som sensoren måler
    # BLACK = 10
    # WHITE = 100
    # GREY = 48

    # Testbanens værdier
    BLACK = 8
    WHITE = 98
    GREY = 58

    # Motorens hastighed i grader per sekund
    DRIVE_SPEED = 200

    # En faktor der ganges på forskellige værdier
    PROPORTIONAL_GAIN = 2.5

    # Farve threshold
    threshold = (WHITE + GREY) / 2

    # Forklar kort
    robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)
    robot.settings(DRIVE_SPEED, 20, 50, 20)

    # Her sættes vores variabler ind så vi kan bruge funktionerne fra drivebase gennem vores klasse.
    def __init__(
        self,
    ):  # "self" repræsentere WallE, men så det kan bruges inde i klassen
        # "super()" er en placeholder for DriveBase klassen
        super().__init__(
            self.left_motor, self.right_motor, self.wheel_diameter, self.axle_track
        )

    # Funktion der får robotten til at søge linjen
    def seek_line(self, direction):
        can_drive = True
        turn_int = 5
        # Først tjekkes hvad der er givet som argument
        if direction == "right":
            # Sætter robotten til at dreje mod højre
            while can_drive:
                self.robot.turn(turn_int)
                # Tjekker om værdien for farvesensoren er inden for range
                if self.line_sensor.reflection() in range(
                    self.GREY - self.i, self.GREY + self.i
                ):
                    self.robot.stop()
                    can_drive = False
                    return True
        # Tjekker om argument er lig venstre
        elif direction == "left":
            # Sætter robotten til at dreje mod venstre
            while can_drive:
                self.robot.turn(-turn_int)
                # Tjekker om værdien for farvesensoren er inden for range
                if self.line_sensor.reflection() in range(
                    self.GREY - self.i, self.GREY + self.i
                ):
                    self.robot.stop()
                    can_drive = False
                    return True
        else:
            return False

    # Funktionen der får robotten til at søge ligeud efter linjen
    def seek_line_straight(self):
        can_drive = True
        turn_rate = 0
        # Sætter robotten til at køre
        while can_drive:
            self.robot.drive(self.DRIVE_SPEED, turn_rate)
            # Tjekker om værdien for farvesensoren er inden for range
            if self.line_sensor.reflection() in range(
                self.GREY - self.i, self.GREY + self.i
            ):
                self.robot.stop()
                can_drive = False
                return

    # Funktion for at følge linjen
    def follow_line(self):
        can_drive = True
        while can_drive:
            # Beregn afvigelse
            deviation = self.line_sensor.reflection() - self.threshold

            # Beregn turn_rate baseret på afvigelsen
            turn_rate = self.PROPORTIONAL_GAIN * deviation

            # Kør robot
            self.robot.drive(self.DRIVE_SPEED, turn_rate)

            # Tjekker om værdien for farvesensoren er inden for range
            if self.line_sensor.reflection() in range(self.BLACK - 5, self.BLACK + 5):
                self.robot.stop()
                can_drive = False
        return

    # Funktionen for at følge linjen fra venstre
    def follow_lineR2L(self):
        can_drive = True
        while can_drive:
            # Beregn afvigelse
            deviation = self.line_sensor.reflection() - self.threshold

            # Beregn turn_rate baseret på afvigelsen
            turn_rate = -self.PROPORTIONAL_GAIN * deviation

            # Kør robot
            self.robot.drive(self.DRIVE_SPEED, turn_rate)

            # Tjekker om værdien for farvesensoren er inden for range
            if self.line_sensor.reflection() in range(self.BLACK - 5, self.BLACK + 5):
                self.robot.stop()
                can_drive = False
        return

    def open_claw(self):
        self.front_motor.run_until_stalled(-600, then=Stop.HOLD, duty_limit=55)
        return

    def close_claw(self):
        self.front_motor.run_until_stalled(300, then=Stop.HOLD, duty_limit=65)
        return
Example #5
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

#################################
# Distanz Sensor
#################################

distanz_sensor = UltrasonicSensor(Port.S1)

# Distanz messen in mm
distanz = distanz_sensor.distance()

# Distanz schreiben
print("Distanz: ", distanz_sensor.distance(), " mm")

# Etwas machen, wenn Distanz zu kurz
if distanz_sensor.distance() < 100:
    print("Etwas ist nahe")
Example #6
0
# Initialize the EV3 Brick.
ev3 = EV3Brick()
# Initialize the motors.
left_motor = Motor(Port.B)

right_motor = Motor(Port.C)
# Initialize the drive base.

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

# Initiaize color sensor
cl = ColorSensor(Port.S4)

# Initiaize distance sensor

distance_sensor = UltrasonicSensor(Port.S2)

# arm motor
arm_motor = Motor(Port.A)

# Put the color sensor into COL-COLOR mode.

gyro = GyroSensor(Port.S3)


def left():
    robot.turn(-90)
    while gyro.angle() > -90:
        wait(2)
        break
Example #7
0
#!/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

# Config
ev3 = EV3Brick()

left_motor = Motor(Port.B)
right_motor = Motor(Port.C)

right_ultra = UltrasonicSensor(Port.S4)
front_ultra = UltrasonicSensor(Port.S3)

gyro = GyroSensor(Port.S2)

data = []

gyro.reset_angle(0)

count = 0
while gyro.angle() < 320:
    left_motor.run(200)
    right_motor.run(-200)
    print(front_ultra.distance())
    data.append(front_ultra.distance())
Example #8
0
#!/usr/bin/env pybricks-micropython
import math
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 

UltrasonicSensor = UltrasonicSensor(Port.S1) #Definieren des Ultraschallsensors 
leftcolorsensor = ColorSensor(Port.S2) #Definieren des linken Farbsensors 
rightcolorsensor = ColorSensor(Port.S3) #Definieren des rechten Farbsensors
gyro = GyroSensor(Port.s4) #Definieren des Gyrosensors

rightMotor = Motor(Port.A) #Definition des rechten Motors
leftMotor = Motor(Port.B) #Definition des linken Motors

watch=StopWatch() #Definieren der Stoppuhr
navi=[] #Einbauen einer list/eines Speichers

V=300 #Definieren der Geschwindigkeit

gyro.reset_angle(0) #Setzen des Winkelwertes auf 0 
rot = gyro.angle() #Messen des Winkelwertes
while abs(rot)<85: #Solange der Wert der Rotation kleiner ist als 85,  
    seconds = watch.time()/1000 #Zähle Zeit in Sekunden
    print(seconds) 
    
    leftMotor.run(V) #Beide Motoren fahren vorwärts
    rightMotor.run(V)
Example #9
0
#---------------------------------------------------------------------------------
# MAIN CODE:

# API KEY
Key = 'nP2wSEqGl-xYpCbU4DPqXhE6oeRSpYPqExh1I8y_6d'

# Initializing ev3 Block
ev3 = EV3Brick()

# Initializing Swing Motor Instances
baseMotor = Motor(Port.C, Direction.CLOCKWISE)
baseMotor2 = Motor(Port.A, Direction.CLOCKWISE)

# Intializing Ultrasonic Sensor Instance
sense = UltrasonicSensor(Port.S2)
dist = sense.distance()

while True:
    # GET call for the systemlink activation
    l_activate = Get_SL('launch_Activate')
    model = Get_SL('model_Select')

    # Reads in the ultrasonic sensor data for each trial
    dist = sense.distance()

    # Reads in model and actiavtion state
    if (model == '1'):
        if (l_activate == '1'):

            print('Using AI')
Example #10
0
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics import DriveBase
from threading import Thread

brick.sound.beep()
brick.display.clear()

# Engine declaration ----------------------------------------------------------------------
motorDirectionLeft = Motor(Port.A)
#motorRideUp = Motor(Port.B)
#motorGoDown = Motor(Port.C)
motorDirectionRight = Motor(Port.D)

# Sensor declaration ----------------------------------------------------------------------
sensorColorLeft = ColorSensor(Port.S1)
sensorUltrassonicFront = UltrasonicSensor(Port.S2)
sensorUltrassonicSide = UltrasonicSensor(Port.S3)
sensorColorRight = ColorSensor(Port.S4)

#Movements --------------------------------------------------------------------------------
motorMovementForward = DriveBase(motorDirectionLeft, motorDirectionRight, 30,
                                 30)
motorMovementTurn = DriveBase(motorDirectionLeft, motorDirectionRight, 20, -32)


# Function detect green -------------------------------------------------------------------
def detectGreenRight():

    contGreen = 0
    motorMovementTurn.drive(-64, 0)
    wait(100)
Example #11
0
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()

right_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE)
left_motor = Motor(Port.D, Direction.COUNTERCLOCKWISE)
lifter = Motor(Port.B)

left_color = ColorSensor(Port.S1)
right_color = ColorSensor(Port.S4)

my_distance = UltrasonicSensor(Port.S2)

on_table = True
while True:

    while on_table:
        right_motor.run(700)
        left_motor.run(700)
        if my_distance.distance() < 200:
            lifter.run_angle(500, 200)
            lifter.run_angle(500, -200)
            print(my_distance.distance())
        if left_color.color() == None or right_color.color() == None:
            on_table = False

    if not on_table:
#!/usr/bin/env pybricks-micropython
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
left = Motor(Port.B)
right = Motor(Port.C)
robot = DriveBase(left, right, 56, 114)

obstacle_sensor = UltrasonicSensor(Port.S4)

robot.drive(200, 0)
while obstacle_sensor.distance() > 300:
    wait(10)
robot.stop()
Example #13
0
#!/usr/bin/env pybricks-micropython
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

ultrasonicSensor = UltrasonicSensor(Port.S1)
leftMotor = Motor(Port.B)  #Definition des linken Motors
rightMotor = Motor(Port.A)  #Definition des rechten Motors

d = ultrasonicSensor.distance(
)  #Messen der Distanz zwischen Roboter und potenziellem Hindernis

while (d > 175):  #solange d>175,
    leftMotor.run(800)  #fährt der linke Motor
    rightMotor.run(800)  #und der rechte Motor
    d = ultrasonicSensor.distance()  #und die Distanz wird wieder gemessen.

    #sobald die Distanz niedriger als 175 ist, stoppt der Roboter und das Programm
Example #14
0
     right_motor.stop()
     while nxt == False:
          Put_SL('Start17','BOOLEAN','true')
          nxt = Get_SL('Start17')
          nxt = True if nxt == 'true' else False
     while trigger == True:
          Put_SL('Start16','BOOLEAN','false')
          trigger = Get_SL('Start16')
          trigger = True if trigger == 'true' else False
     print('done')

left_motor = Motor(Port.D)
right_motor = Motor(Port.A)
left_sens = ColorSensor(Port.S2)
right_sens = ColorSensor(Port.S3)
dist_sens = UltrasonicSensor(Port.S4)
Kp = 45
Kd = 0.5
err = 0
speed = 400
nxt = Get_SL('Start17')
nxt = True if nxt == 'true' else False

while True:
     trigger = Get_SL('Start16')
     trigger = True if trigger == 'true' else False
     
     if trigger == True:
          PD_Controller(err,Kp,Kd,speed)
          dist = dist_sens.distance()
          print(dist)
Example #15
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
import math 

# Initialize the EV3

brick.sound.beep()

touch = TouchSensor(Port.S2)
ultra= UltrasonicSensor(Port.S1)
throw = Motor(Port.A, Direction.COUNTERCLOCKWISE)
 

def takeSecond(elem):
    return elem[0]
def KNN(categories, distance, x, k):
    dist = []
    for (i, val) in enumerate(distance):
        dist.append((abs(val-x),categories[i]))
        dist.sort(key=takeSecond)

    sum = 0
    for i in range(3):
        sum += dist[i][1] 
    return(sum/3)
motor2 = Motor(Port.B) 

# Name a motor
motor3 = Motor(Port.C)

# Name a motor
motor4 = Motor(Port.D)

# Name a sensor
sensor2 = TouchSensor(Port.S2)

# Name a sensor
sensor3 = TouchSensor(Port.S3)

# Name the ultrasonic sensor
sensor = UltrasonicSensor(Port.S4)

# Create a name for connecting two motors so that we can call it one
robot = DriveBase(motor, motor2, 56, 114)

# Have the robot "chase" an object a certain amount of times
i = 20

# Have the robot spin in a circle 5 times after it has done it's rotation a certain number of times. 
j = 10

# Have the robot run the program a certain number of times so that we don't have to keep restarting it 
o = 20

# Have the robot continue the loop 20 times
while o > 0:
Example #17
0
from pybricks.hubs import EV3Brick
from pybricks.tools import wait
from pybricks.parameters import Port
from pybricks.ev3devices import UltrasonicSensor


# Initialize the EV3
ev3 = EV3Brick()
ev3.speaker.beep(440,500)
ev3.speaker.beep(880,500)
ev3.speaker.beep(440,500)
ev3.speaker.beep(220,500)
ev3.speaker.beep(440,500)

# or if you want to do soem thinking while the notes are playing
ev3.speaker.beep(440,-1)
wait (100) # note we wait a little and then change the note frequency
ev3.speaker.beep(880,500)

# or for the more musically inclined
notes = ['G3/8','G3/8', 'G3/8', 'Eb3/2','R/8','F3/8','F3/8', 'F3/8', 'D3/2']
ev3.speaker.play_notes(notes, tempo=120)

# or if you want to make a theremin
dist = UltrasonicSensor(Port.S4)
while True:
     tone = dist.distance()*5
     ev3.speaker.beep(tone,-1)
     wait(10)

Example #18
0
#!/usr/bin/env pybricks-micropython

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

brick.sound.beep()

colorSensor = ColorSensor(Port.S4)
sonarSensor = UltrasonicSensor(Port.S2)
# touchSensor = TouchSensor(Port.S1)
touchSensor = TouchSensor(Port.S3)  # Tom touch sensor on S1

left_motor = Motor(Port.B)
right_motor = Motor(Port.C)

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


def SensorTest():

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

    while not Button.RIGHT in brick.buttons():
# colors:
# 1: black
# 2: blue
# 3: green
# 4: yellow
# 5: red
# 6: white
# 7: brown

motor_arm = Motor(Port.A)
motor_grabber = Motor(Port.D)
motor_l = Motor(Port.B)
motor_r = Motor(Port.C)
robot = DriveBase(motor_l, motor_r, 56,
                  114)  # wheel diameter (mm) | axle track (mm)
ultrasonic = UltrasonicSensor(Port.S1)
color_sensor_ramp = ColorSensor(Port.S2)
collision_button = TouchSensor(Port.S3)
color_sensor_floor = ColorSensor(Port.S4)
watch = StopWatch()
# ultrasonic2 = UltrasonicSensor(Port.S3)

collision_threshhold = 200  # mm
maximum_ball_count = 20  # size of storage container
random_direction_change_interval = 5000
drive_speed = 200  # mm/s
rotation_speed = 90  # deg/s
calibration_surface = -1
calibration_ramp = -1

ball_count = 0
Example #20
0
#!/usr/bin/env pybricks-micropython
#https://en.wikipedia.org/wiki/Piano_key_frequencies
#https://www.musicnotes.com/images/productimages/large/mtd/MN0168952.gif
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

motorB = Motor(Port.B)
sensor1 = UltrasonicSensor(Port.S1)
A = 440.000
G = 381.995
Fsharp = 369.994
E = 329.628
D = 293.665
C = 261.626
lowB = 246.942

#Hz = [261.626, 261.626, 391.995, 391.995, 440.000, 440.000, 391.995], d = [500, 500, 500, 500, 500, 500, 1000]


def sing(Hz=[
    G, G, Fsharp, Fsharp, lowB, D, lowB, lowB, G, G, Fsharp, Fsharp, lowB, 1,
    G, G, Fsharp, Fsharp, lowB, D, lowB, D, E, C, D, lowB, 1
],
         d=[
             1, 1, 1, 1, 1, 0.5, 1.5, 1, 0.5, 1.5, 1, 1, 1, 3, 1, 1, 1, 1, 1,
             1, 2, 1, 1, 1, 1, 1, 3
Example #21
0
# - one ultrasonic sensor on Input 1 ('Port.S1') to prevent collision
# - one medium motor on Output A ('Port.A') to choose the Train's speed
# other MQTT clients can also participate

STARTUP = 1000  # pause (ms) at start
DISTANCE_SAFE = 200  # distance (mm) to stop or reverse the Train
DEBOUNCE = 125  # wait this time (ms) after each button is pressed (empyrical)
WAIT_TRAIN = 50  # wait for Train (4DBrix) to receive command (empyrical)
INITSpeed = 320  # initial speed of our Train (you choose)
MAXSpeed = 1023  # maximum speed accepted by 4DBrix WiFi Controller
MOTORSpeed = 1024  # speed to use with EV3 motor (360 = 1 turn/sec)
TOLERANCE = 4  # acceptable tolerance when reading motor position
SETTLE = 250  # time (ticks) for the user to change motor position before
# considering it done (empyrical)

us = UltrasonicSensor(Port.S1)
m = Motor(Port.A)

m.reset_angle(0)
print('Motor Reset')
# motor will be used to read speed so defining scale
SCALE = round(360 / MAXSpeed, 2)
m.run_target(MOTORSpeed, round(INITSpeed * SCALE),
             Stop.COAST)  # show initial speed

# Possible hostnames - use your own
RIGHTMOST = 'iota'
LEFTMOST = 'alpha'

# get hostname to use as MQTT_ClientID and decide roles
# LEFTMOST should be at LEFT or F extreme
#!/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,
                                 SoundFile, ImageFile, Align)
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics import DriveBase
ev3 = EV3Brick()

ultrasonicSensor = UltrasonicSensor(Port.S2)

left_motor = Motor(Port.A)
right_motor = Motor(Port.D)

program_running = True
distance = ultrasonicSensor.distance()

left_motor.run(800)
right_motor.run(800)
while distance > 195:
    distance = ultrasonicSensor.distance()
    print(distance)
left_motor.stop()
right_motor.stop()
Example #23
0
#!/usr/bin/env pybricks-micropython

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

# Initialize two motors with default settings on Port B and Port C.
# These will be the left and right motors of the drive base.
left_motor = Motor(Port.B)
right_motor = Motor(Port.C)

ultra_sensor = UltrasonicSensor(Port.S3)

# The wheel diameter of the Robot Educator is 56 millimeters.
wheel_diameter = 56

# The axle track is the distance between the centers of each of the wheels.
# For the Robot Educator this is 114 millimeters.
axle_track = 114

# The DriveBase is composed of two motors, with a wheel on each motor.
# The wheel_diameter and axle_track values are used to make the motors
# move at the correct speed when you give a motor command.
robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)


# This function makes the robot follow a wall.
Example #24
0
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
from threading import Thread

ev3 = EV3Brick()

rMotor = Motor(Port.A, positive_direction=Direction.COUNTERCLOCKWISE)
lMotor = Motor(Port.D, positive_direction=Direction.COUNTERCLOCKWISE)
cMotor = Motor(Port.C)
colorS = ColorSensor(Port.S3)
ultraS = UltrasonicSensor(Port.S4)

ev3.speaker.set_volume(100)  #Set volume to 100%
Lydeffekt = 0  #Variable for at start en lyd
Section_number = 1  #Variable for hvilket sektion af sangen der skal spilles
opgavenr = 0  #Variable for hvilken opgave der skal køres
active = 1  #Variable der viser om robotten skal kører
glCount = 0  #Grey line count. Bruges til opgave 4 med de parallele linjer

#Hver procentdel afvigelse af lys fra 'threshold' ,
#sætter turn_rate i drivebase 1.5 grader i sekundet
#fx hvis lyset afviger 10 fra 'threshold', så drejer 10*x grader pr. sekund

proportionalGain = 1.5

#Drive base
Example #25
0
 def iniciaSensorUltra(self, portaSensor): # Para o sensor ultrassonico
     self.sensor = UltrasonicSensor(portaSensor)
     self.tipoSensor = "ultra"
Example #26
0
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, UltrasonicSensor, ColorSensor
from pybricks.parameters import Port, Color, Button
from pybricks.tools import wait, StopWatch
from pybricks.robotics import DriveBase

# Initialize the EV3 Brick.
ev3 = EV3Brick()

# Initialize the Ultrasonic Sensor. It is used to detect
# obstacles as the robot drives around.
obstacle_sensor = UltrasonicSensor(Port.S2)

# Initialize the color sensor.
line_sensor = ColorSensor(Port.S3)

# Initialize two motors with default settings on Port B and Port C.
# These will be the left and right motors of the drive base.
#left_motor = Motor(Port.B)
#right_motor = Motor(Port.C)

arm = Motor(Port.D)

ev3.speaker.set_speech_options(language='en-uk-north', voice='croak')
#ev3.speaker.set_speech_options(language='en-sc', voice='f1')

#ev3.speaker.say(" i like minecraft i want to play it now")
Example #27
0
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
from pybricks.robotics import DriveBase
from pybricks.media.ev3dev import SoundFile, ImageFile
import math

import ubinascii, ujson, urequests, utime

# Write your program here
ev3 = EV3Brick()
ev3.speaker.beep()

#set up ports
distSen = UltrasonicSensor(Port.S1)
chuck = Motor(Port.A)
yoss = Motor(Port.B)

top_cup = 115 #height of top of cup
start_pos = 200 #height of start
sens_pos = 70 #x position of sensor
theta = 45 #launch angle (degrees)

g = 9807 #mm/s^2
C = .42 #constant multiplier for speed to fit physical model

#coefficients for AI model
A_ai = 1.4416
B_ai = 124.88
Example #28
0
#!/usr/bin/env pybricks-micropython

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
LM = Motor(Port.B)
RM = Motor(Port.D)
WD = 56
AT = 114

Robot = DriveBase(LM, RM, WD, AT)

Eyes = UltrasonicSensor(Port.S3)
Col = ColorSensor(Port.S2)

while True:
    Robot.drive(0, 90)

    if Eyes.distance() < 350:
        wait(10)
        while Col.reflection() > 10:
            Robot.drive(200, 0)

        else:
            Robot.drive_time(-250, 0, 1500)
Example #29
0
 def __init__(self):
     self.motor = Motor(Port.B)
     self.ultrasonic = UltrasonicSensor(Port.S4)
     self.active = True
     self.speed = 0
     self.colors = [None, Color.GREEN, Color.YELLOW, Color.RED]
Example #30
0
    covar = covariance(xArray,mean_x,wArray,mean_w)
    print('x stats: mean=%.3f variance = %.3f' % (mean_x, var_x))
    print('w stats: mean=%.3f variance = %.3f' % (mean_w, var_w))
    print('Covariance: %.3f' %(covar))

#using linear regression:
def distRead(distanceSens, b0, b1):
    x = distanceSens.distance()
    print(x)
    w = b0 + (b1 * (x+40)) 
    motor1.run_angle(w, -360, wait = False)
    motor2.run_angle(w, -360)
    return x, w

#main code:
distanceSens = UltrasonicSensor(Port.S1)
motor1 = Motor(Port.D)
motor2 = Motor(Port.A)

g = 9.81*1000
r = 66
theta = (360 * math.sqrt(2)) / (4 * 3.41)
h = 90
c = 40

#w = 100
#wArray = []
#xArray = []
#[wArray, xArray] = dataCollection(w,motor1,motor2)
#print(wArray)
#print(xArray)