from sys import stderr # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # define the motors, sensors and the brick largeMotor_Right = Motor(Port.B) largeMotor_Left = Motor(Port.C) panel = Motor(Port.D) gyro = GyroSensor(Port.S4) colourRight = ColorSensor(Port.S2) colourLeft = ColorSensor(Port.S3) colourkey = ColorSensor(Port.S1) ev3 = EV3Brick() robot = DriveBase(largeMotor_Left, largeMotor_Right, wheel_diameter=62, axle_track=104) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # turns all the motors off without using brakes def off(): # log doing the function print('Turning motors off', file=stderr) # stop the motors and turn the brake off Motor_Left.stop() largeMotor_Right.stop() panel.stop()
#!/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 esquerda = Motor(Port.B, Direction.COUNTERCLOCKWISE) direita = Motor(Port.C, Direction.COUNTERCLOCKWISE) MotorMA = Motor(Port.A) MotorMD = Motor(Port.D) gabriel = DriveBase(esquerda, direita, wheel_diameter=100, axle_track=166.2) #Ajustar valores (axeltrack 172????) ev3 = EV3Brick() def Acelera(qp_max, qf): # dados iniciais ---------------------- qi = 0 # posição inicial (em mm) # primeiro cálculo Dq = qf - qi # variação da posição (distância, em mm) # determinação das outras variáveis tf = 15 * Dq / (8 * qp_max) # tempo do movimento a3 = 16 * qp_max / (3 * tf**2) a4 = -8 * qp_max / (tf**3)
# 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) # 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) # The following loop makes the robot drive forward until it detects an # obstacle. Then it backs up and turns around. It keeps on doing this # until you stop the program. while True: # Begin driving forward at 200 millimeters per second. robot.drive(200, 0) # Wait until an obstacle is detected. This is done by repeatedly # doing nothing (waiting for 10 milliseconds) while the measured # distance is still greater than 300 mm. while obstacle_sensor.distance() > 300: wait(10) # Drive backward at 100 millimeters per second. Keep going for 2 seconds.
#!/usr/bin/env pybricks-micropython from pybricks.hubs import EV3Brick from pybricks.ev3devices import Motor from pybricks.parameters import Port from pybricks.robotics import DriveBase # Create your objects here. ev3 = EV3Brick() left_motor = Motor(Port.B) right_motor = Motor(Port.C) robot = DriveBase(left_motor, right_motor, wheel_diameter=55.5, axle_track=104) robot.straight(600) print('straight') robot.drive(50, 0) #drive 43cm wait(5000) stop() print('slower') robot.straight(-10)
#!/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 from pybricks import DriveBase # Write your program here brick.sound.beep() MotorB = Motor (Port.B) MotorC = Motor (Port.C) Cookie = DriveBase (MotorB, MotorC, 56, 60) Cookie.drive(200, 0) Cookie.drive_distance(100, 0, 300) def
class Robot: def __init__(self, left_motor_port, right_motor_port, med_motor_port, gyro_port, wheel_diameter, wheel_base): self.left_motor = Motor(left_motor_port) self.right_motor = Motor(right_motor_port) # self.med_motor = Motor(med_motor_port) self.robot = DriveBase(self.left_motor, self.right_motor, wheel_diameter, wheel_base) self.gyro = GyroSensor(gyro_port) # Function definitions # Gyro sensor reset, waits until the gyro has come to rest and then resets the value to zero # use at beginning of mission programs def resetGyro(self): brick.light(Color.RED) speed = self.gyro.speed() angle = self.gyro.angle() while speed != 0: wait(100) speed = self.gyro.speed() angle = self.gyro.angle() self.gyro.reset_angle(0) brick.light(Color.GREEN) # Drive the robot straight using the GyroSensor # def driveStraight(self, rotations, speed): distance = rotations * 360 # convert wheel rotations to degrees self.gyro.reset_angle(0) self.left_motor.reset_angle(0) self.right_motor.reset_angle(0) # set our amount to correct back towards straight correction = -2 if speed < 0: correction = 2 # start the robot driving self.robot.drive(speed, 0) # loop until the robot has travelled the distance we want # updating the steering angle of the drive based on the gyro measured drift and correction while abs(self.left_motor.angle()) <= distance and abs( self.right_motor.angle()) <= distance: drift = self.gyro.angle() print("Drift: " + str(drift)) steering = drift * correction #print("Steering: " + str(steering)) self.robot.drive(speed, steering) self.robot.stop(Stop.BRAKE) # Turn the robot an exact amount using the GryoSensor def turnDegrees(self, degrees): self.gyro.reset_angle(0) initial_power = 300 end_power = 50 left_motor_power = initial_power right_motor_power = initial_power * -1 if degrees < 0: left_motor_power = initial_power * -1 right_motor_power = initial_power initial_turn = abs(degrees * .75) self.left_motor.run(left_motor_power) self.right_motor.run(right_motor_power) angle = self.gyro.angle() print("Angle: " + str(angle)) while abs(angle) < initial_turn: wait(10) angle = self.gyro.angle() print("Angle: " + str(angle)) left_motor_power = end_power right_motor_power = end_power * -1 if degrees < 0: left_motor_power = end_power * -1 right_motor_power = end_power self.left_motor.run(left_motor_power) self.right_motor.run(right_motor_power) end_degrees = (abs(degrees) - 1) angle = self.gyro.angle() print("Angle: " + str(angle)) while abs(angle) < end_degrees: wait(10) angle = self.gyro.angle() print("Angle: " + str(angle)) self.left_motor.stop(Stop.BRAKE) self.right_motor.stop(Stop.BRAKE) print("Final Angle: " + str(self.gyro.angle())) def oldDrive(self, speed, turn): while True: self.robot.drive(speed, turn)
from pybricks.hubs import EV3Brick from pybricks.ev3devices import Motor, GyroSensor from pybricks.parameters import Port, Direction from pybricks.robotics import DriveBase from pybricks.tools import wait # Initialize the EV3 Brick. ev3 = EV3Brick() # Initialize the motors. left_motor = Motor(Port.B, positive_direction=Direction.COUNTERCLOCKWISE) right_motor = Motor(Port.C, positive_direction=Direction.COUNTERCLOCKWISE) lift_motor = Motor(Port.A) forklift_motor = Motor(Port.D) robot = DriveBase(left_motor, right_motor, wheel_diameter=94.2, axle_track=94) robot.settings(straight_speed=200, straight_acceleration=50, turn_rate=150, turn_acceleration=200) ev3.screen.draw_text(50, 60, "noot noot") ev3.speaker.beep() gyro_sensor = GyroSensor(Port.S2, Direction.COUNTERCLOCKWISE) def gyro_turn(angle, speed=150): gyro_sensor.reset_angle(0) if angle < 0: while gyro_sensor.angle() > angle: left_motor.run(speed=(-1 * speed))
#!/usr/bin/env pybricks-micropython from pybricks.hubs import EV3Brick from pybricks.ev3devices import Motor from pybricks.parameters import Port, Direction from pybricks.robotics import DriveBase # Initialize the EV3 Brick. ev3 = EV3Brick() # Initialize the motors. left_motor = Motor(Port.B) right_motor = Motor(Port.C) forklift_motor = Motor(Port.D, positive_direction=Direction.COUNTERCLOCKWISE) # Initialize the drive base. robot = DriveBase(left_motor, right_motor, wheel_diameter=94.2, axle_track=94) ev3.screen.draw_text(50, 60, "Testing!") ev3.speaker.beep() #forklift_motor.run_angle(speed=5005, rotation_angle=2*360) forklift_motor.run_angle(speed=5005, rotation_angle=-2 * 360) #owen is a loser #forklift_motor.run_angle(speed=25198, rotation_angle=10000) #forklift_motor.run_angle(speed=25198, rotation_angle=-8500) ev3.speaker.beep()
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) # 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) # Go forward 600mm robot.straight(750) # Drive forward till we sense white followed by black drive_utils.drive_till_black(robot, left_sensor) # Turn left drive_utils.gyro_turn(robot, gyro, -37)
class robot: #variaveis principais position = [0,0] Clawdir = -1 lista_lobby = [] posicao_lobby = 0 matrix = [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] #sensors resetY_Sensor = None chromoSensor = None #motors claw_Motor = None y_Motor = None x_Motor1 = None x_motor2 = None xAxisMotors = None #função de inicialização do robo def __init__(self): self.resetY_Sensor = TouchSensor(Port.S2) self.chromoSensor = ColorSensor(Port.S1) self.claw_Motor = Motor(Port.A) self.y_Motor = Motor(Port.B) self.x_Motor1 = Motor(Port.C) self.x_Motor1.set_run_settings(200, 100) self.x_Motor2 = Motor(Port.D) self.x_Motor2.set_run_settings(200, 100) self.xAxisMotors = DriveBase(self.x_Motor1,self.x_Motor2,50,100) self.reset() #metodo para resetar a garra def reset_Claw(self): self.claw_Motor.run_until_stalled(1000,Stop.BRAKE,38) self.claw_Motor.run_time(5500*-1, 1700,Stop.BRAKE) self.Clawdir = -1 #metodo para resetar o eixo do Y def reset_YAxis(self): self.y_Motor.run(300) while (self.resetY_Sensor.pressed()== False): wait(10) self.y_Motor.stop() #metodo para combinar ambos os resets anteriores def reset(self): self.reset_Claw() self.reset_YAxis() print("done reset") #metodo para abrir e fechar a garra def toggleClaw(self): self.claw_Motor.run_time(5500*self.Clawdir,1300,Stop.BRAKE) self.Clawdir = -self.Clawdir #metodo para o movimento no eixo dos Y def yAxis(self,pos): self.y_Motor.run_angle(100,-217.7*pos,Stop.BRAKE,True) #metodo para o movimento no eixo dos X def xAxis(self,pos,dir): self.xAxisMotors.drive_time(dir*18.75, 0, 1000*pos*4) #combinação de ambos os metodos anteriores def moveTo(self,xPos,yPos,resetY=True): dir = 1 if(resetY): self.reset_YAxis() if(xPos - self.position[0]<0): dir = -1 self.xAxis(abs(xPos - self.position[0]),dir) if(not(resetY)): self.yAxis(yPos - self.position[1]) else: self.yAxis(yPos +0.25) self.position[0]= xPos self.position[1]= yPos #metodo para o movimento no lobby onde lê as peças def moveToLobby(self,pos,resetY = True): if(pos%5==0): resetY = True self.moveTo(pos//5+5,pos%5,resetY) #metodo para o movimento dentro do campo de jogo def moveToGame(self,xPos,yPos): if(xPos>4 or yPos>4): quit() self.moveTo(xPos,yPos,True) #metodo para ler a cor repitindo 10 vezes def readColor(self): while(True): tempList = [] for x in range(10): wait(200) tempList += [self.testecor(self.chromoSensor.rgb())] tempList = list(dict.fromkeys(tempList)) print(tempList) if(len(tempList)==1): if(tempList[0]!=0): return tempList[0] #metodo para testar a cor individualmente def testecor(self,a): #print(a) if(a[0]>a[1]+a[2] and a[0]+a[1]+a[2]>25): return 1 #vermelho elif(a[2]> a[0]+a[1] and a[0]+a[1]+a[2]>25): return 2 #azul elif(a[0]+a[1]+a[2]<70): temp = self.chromoSensor.color() if(temp==3): return 3 #verde elif(temp==1): return 4 #preto else: return 0 #sem cor elif(a[0]+a[1]+a[2]<180): return 5 #amarelo #metodo que combina o movimento e a leitura de cores para ler todo o lobby def readLobby(self): pos = 0 self.moveToLobby(pos,True) while(len(self.lista_lobby)==0 or self.lista_lobby[-1]!=5): #le as peças ate ler amarelo self.lista_lobby.append(self.readColor()) print(self.lista_lobby[:-1]) pos+=1 if(self.lista_lobby[-1]!=5): self.moveToLobby(pos,False) self.lista_lobby = self.lista_lobby[:-1] self.reset_YAxis() countOfChars = {i:self.lista_lobby.count(i) for i in self.lista_lobby} print(countOfChars) global pecasExistentes global pecasExistentesOld pecasExistentes += [countOfChars[1]] pecasExistentes += [countOfChars[2]] pecasExistentes += [countOfChars[3]] pecasExistentes += [countOfChars[4]] pecasExistentesOld = pecasExistentes.copy() print(self.lista_lobby) #metodo que verifica se uma figura foi feita def checkFigure(self): #itera sobre todos os padrões e verifica se existe algum for pattern in figureSequence: result = match_pattern(self.matrix,globals()[pattern]) print(self.matrix) if(result != -1): globals()["score"] += globals()[pattern + "p"] for x in range(len(result[1])): for y in range(len(result[1][x])): if(result[1][x][y]==self.matrix[x+result[0][0]][y+result[0][1]]): pecasExistentes[result[1][x][y]-1] -= 1 self.matrix[x+result[0][0]][y+result[0][1]] = 0 brick.sound.file(SoundFile.DETECTED,VOLUME) brick.display.text(pattern) block = True while(block): if Button.CENTER in brick.buttons(): block = False wait(10) #metodo que combina os metodos anteriores para mover uma peça para uma posição especifica def movePieceTo(self, xPos, yPos): self.moveToLobby(self.posicao_lobby) self.matrix[xPos][yPos] = self.lista_lobby[self.posicao_lobby] self.posicao_lobby += 1 self.toggleClaw() self.moveToGame(xPos,yPos) self.claw_Motor.run_time(1000,1000,Stop.BRAKE) self.reset_YAxis() self.reset_Claw() self.checkFigure()
SoundFile, ImageFile, Align) from pybricks.tools import print, wait, StopWatch from pybricks.robotics import DriveBase from time import sleep # Write your program here CL = ColorSensor(Port.S1) LM = Motor(Port.B) RM = Motor(Port.C) WD = 56 AT = 114 btn = brick.buttons() print(btn) Robot = DriveBase(LM, RM, WD, AT) def limit(value): # returns a value within the range -100 to +100 return min(max(value, -100), 100) while not Button.LEFT in brick.buttons(): brick.display.text('Press the left button when the sensor is in dim light', (50, 60)) sleep(0.7) brick.display.clear() dim = CL.ambient() while not Button.RIGHT in brick.buttons(): brick.display.text('Press the RIGHT button when the sensor is in dim light', (50, 60)) sleep(0.7)
def slide(robot): robot.stop() motor_b, motor_c = Motor(Port.B, positive_direction=Direction.CLOCKWISE), Motor( Port.C, positive_direction=Direction.CLOCKWISE) robot = DriveBase(motor_b, motor_c, wheel_diameter=94.2, axle_track=95) robot.straight(220) wait(500) # robot.stop() while gyro.angle() < 265: robot.drive(-100, 80) dead_stop() motor_a.run_angle(1500, -1000, then=Stop.HOLD, wait=False) robot.straight(515) dead_stop() robot.turn(125) # 105 robot.stop() motor_b, motor_c = Motor( Port.B, positive_direction=Direction.COUNTERCLOCKWISE), Motor( Port.C, positive_direction=Direction.COUNTERCLOCKWISE) robot = DriveBase(motor_b, motor_c, wheel_diameter=94.2, axle_track=95) robot.straight(200) robot.turn(70) robot.turn(-60) LineFollow(100, 1.05, robot, 50) robot.straight(250)
def Treadmill(robot): moveTank(-300, 95, -130) robot.turn(105) robot.stop() motor_b, motor_c = Motor( Port.B, positive_direction=Direction.COUNTERCLOCKWISE), Motor( Port.C, positive_direction=Direction.COUNTERCLOCKWISE) robot = DriveBase(motor_b, motor_c, wheel_diameter=94.2, axle_track=95) LineFollow(70, 1.05, robot, 200) robot.turn(28) robot.straight(180) robot.turn(-28) motor_d.run_time(-500, 1000, then=Stop.COAST, wait=False) robot.straight(70) wait(1000) motor_d.run_time(-200, 10000, then=Stop.COAST, wait=True) robot.stop()
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() motor_b, motor_c, motor_d, motor_a = Motor(Port.B), Motor(Port.C), Motor( Port.D), Motor(Port.A) robot = DriveBase(motor_b, motor_c, wheel_diameter=94.2, axle_track=95) color = ColorSensor(Port.S3) gyro = GyroSensor(Port.S2) sonic = UltrasonicSensor(Port.S4) # initialize function myblocks here def moveTank(speed, steering, distance): robot.reset() robot.drive(speed, steering) if distance < 0: while robot.distance() > distance: pass else: while robot.distance() < distance: pass
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=68.8, axle_track=140) robot.settings(-300, 620, -620, -300) ev3.screen.draw_text(50, 60, "Pigeons!") ev3.speaker.beep() robot.straight(750) robot.stop() robot.settings(-25, 50, -310, -150) robot.straight(100) robot.straight(-20) robot.stop() robot.settings(-300, -300, -310, -150) robot.straight(-850) robot.stop()
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 struct # Initialize motors and sensors left_motor = Motor(Port.B) right_motor = Motor(Port.C) steer_motor = Motor(Port.A) forward = 0 left = 0 robot = DriveBase(left_motor, right_motor, 56, 120) obstacle_sensor = UltrasonicSensor(Port.S4) # Show the current voltage and active program brick.display.text("Voltage is: {}".format(brick.battery.voltage()), (5, 110)) wait(2000) # Read buttons and act accordingly. UP button ends brick.display.text("RACECAR") brick.display.text("USE PS4 CONTROLLER") brick.light(None) # PS4 control code # A helper function for converting stick values (0 - 255) # to more usable numbers (-100 - 100)
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() # Write your program here. ev3.speaker.beep() left = Motor(Port.B) right = Motor(Port.C) robot = DriveBase(left, right, 55.5, 104) ultra = UltrasonicSensor(Port.S2) robot.drive(150, 0) #20 cm 이상 -> 계속 직진한다. while ultra.distance() > 200: pass #20 cm 이하 -> 다음 프로그램 실행 #10 cm 후진 robot.straight(-100) #모터를 멈춘다. robot.stop()
from pybricks.parameters import Port, Stop, Direction, Button, Color from pybricks.tools import wait, StopWatch, DataLog from pybricks.robotics import DriveBase # SETUP SECTION # Initialize the EV3 Brick. # We'll call "brick" every time we want the brick to do something brick = EV3Brick() # Initialize the motors. left_motor = Motor(Port.B) right_motor = Motor(Port.C) # Initialize the drive base. # The DriveBase function will set up the driving mechanic to move both wheels together # We just need to say which motors we want to use as well as the wheels and the axle track # We'll call "robot" every time we want the robot to move robot = DriveBase(left_motor, right_motor, wheel_diameter=56, axle_track=114) # START ROBOT SECTION # Now that we're all set up, let's tell the robot what to do! # Let's make it beep, wait 2 seconds, and then beep again so we know it's ready # DRIVING SECTION #Below are some examples of driving commands to move the robot #Delete the "#" for the driving commands you want to use # ----- Going Straight ----- # robot.straight(10) robot.drive_time(999, 0, 999999999)
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.ev3devices import Motor SOUND_VOLUME=7 WHEEL_DIAMETER_MM=89 AXLE_TRACK_MM=135 SENSOR_TO_AXLE=68 # Get wheel circumference WHEEL_CIRCUM_MM=3.149*89 # 360 degrees -> WHEEL_CIRCUM_MM so 1 degree -> ? DEGREES_PER_MM=360/WHEEL_CIRCUM_MM #drive motors left_motor=Motor(Port.D, Direction.CLOCKWISE) right_motor=Motor(Port.C, Direction.CLOCKWISE) robot = DriveBase(left_motor, right_motor, WHEEL_DIAMETER_MM, AXLE_TRACK_MM) crane_motor=None ### Motor(Port.B, Direction.CLOCKWISE, [8,24]) rack_motor=None #### Motor(Port.A, Direction.CLOCKWISE) gyro=GyroSensor(Port.S1, Direction.COUNTERCLOCKWISE) color_sensor_left = None ### ColorSensor(Port.S1) color_sensor_right = None ### ColorSensor(Port.S4) color_sensor_center = ColorSensor(Port.S4) touch_sensor= TouchSensor(Port.S3)
class TrickyPlayingSoccer: WHEEL_DIAMETER = 44 AXLE_TRACK = 88 KICK_SPEED = 1000 def __init__(self): # Configure the hub, the kicker motor, and the sensors. self.hub = InventorHub() self.kicker_motor = Motor(Port.C) self.distance_sensor = UltrasonicSensor(Port.D) self.color_sensor = ColorSensor(Port.E) # Configure the drive base. left_motor = Motor(Port.B, Direction.COUNTERCLOCKWISE) right_motor = Motor(Port.A) self.drive_base = DriveBase(left_motor, right_motor, self.WHEEL_DIAMETER, self.AXLE_TRACK) # Prepare tricky to start kicking! self.distance_sensor.lights.off() self.reset_kicker_motor() self.distance_sensor.lights.on(100) def reset_kicker_motor(self): # Prepare the kicker motor for kicking. self.hub.light.off() self.kicker_motor.run_until_stalled(-self.KICK_SPEED, Stop.HOLD) self.kicker_motor.run_angle(self.KICK_SPEED, 325) def kick(self): # Kick the ball! self.kicker_motor.track_target(360) def run_to_and_kick_ball(self): # Drive until we see the red ball. self.drive_base.drive(speed=1000, turn_rate=0) while self.color_sensor.color() != Color.RED: wait(10) self.hub.light.on(Color.RED) self.hub.speaker.beep(frequency=100, duration=100) self.kick() self.drive_base.stop() self.hub.light.off() def celebrate(self): # Celebrate with light and sound. self.hub.display.image([[00, 11, 33, 11, 00], [11, 33, 66, 33, 11], [33, 66, 99, 66, 33], [11, 33, 66, 33, 11], [00, 11, 33, 11, 00]]) self.hub.speaker.beep(frequency=1000, duration=1000) self.hub.light.animate([Color.CYAN, Color.GREEN, Color.MAGENTA], interval=100) # Celebrate by dancing around. self.drive_base.drive(speed=0, turn_rate=360) self.kicker_motor.run_angle(self.KICK_SPEED, 5 * 360) # Party's over! Let's stop everything. self.hub.display.off() self.hub.light.off() self.drive_base.stop()
#!/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() clr_sense = ColorSensor(Port.S3) left_motor = Motor(Port.C) right_motor = Motor(Port.B) robot = DriveBase(left_motor, right_motor, 55, 142) # Define variables threshold = 10 speed = 100 turn = 20 # ---- MAIN LOOP ---- while clr_sense.color() != Color.RED: if clr_sense.reflection() > threshold: robot.drive(speed, turn) else: robot.drive(speed, turn * -1)
from pybricks.messaging import BluetoothMailboxClient, NumericMailbox import random # Initialize the motors. left_motor = Motor(Port.B) right_motor = Motor(Port.C) # Initialize the color sensor. line_sensor = ColorSensor(Port.S3) # Initialize the ultrasonic sensor. It is used to detect # obstacles as the robot drives around. obstacle_sensor = UltrasonicSensor(Port.S4) # Initialize the drive base. robot = DriveBase(left_motor, right_motor, wheel_diameter=55.5, axle_track=118) # Current speed, normal speed, maximum speed, and minimum speed DRIVE_SPEED = 90 NORMAL_SPEED = 90 MAX_SPEED = 130 MIN_SPEED = 80 # Calculate the light threshold. Choose values based on your measurements. BLACK = 5 WHITE = 70 threshold = (BLACK + WHITE) / 2 # Set the gain of the PID controller. PROPORTIONAL_GAIN = 0.4 INTEGRAL_GAIN = 0.1
class RemoteControlledTank: """ This reusable mixin provides the capability of driving a robot with a Driving Base by the IR beacon """ def __init__( self, wheel_diameter: float, axle_track: float, # both in milimeters left_motor_port: Port = Port.B, right_motor_port: Port = Port.C, polarity: str = 'normal', ir_sensor_port: Port = Port.S4, ir_beacon_channel: int = 1): if polarity == 'normal': left_motor = Motor(port=left_motor_port, positive_direction=Direction.CLOCKWISE) right_motor = Motor(port=right_motor_port, positive_direction=Direction.CLOCKWISE) else: left_motor = Motor(port=left_motor_port, positive_direction=Direction.COUNTERCLOCKWISE) right_motor = Motor(port=right_motor_port, positive_direction=Direction.COUNTERCLOCKWISE) self.driver = DriveBase(left_motor=left_motor, right_motor=right_motor, wheel_diameter=wheel_diameter, axle_track=axle_track) self.ir_sensor = InfraredSensor(port=ir_sensor_port) self.ir_beacon_channel = ir_beacon_channel def drive_by_ir_beacon( self, speed: float = 1000, # mm/s turn_rate: float = 90 # rotational speed deg/s ): ir_beacon_button_pressed = \ set(self.ir_sensor.buttons(channel=self.ir_beacon_channel)) # forward if ir_beacon_button_pressed == {Button.LEFT_UP, Button.RIGHT_UP}: self.driver.drive(speed=speed, turn_rate=0) # backward elif ir_beacon_button_pressed == {Button.LEFT_DOWN, Button.RIGHT_DOWN}: self.driver.drive(speed=-speed, turn_rate=0) # turn left on the spot elif ir_beacon_button_pressed == {Button.LEFT_UP, Button.RIGHT_DOWN}: self.driver.drive(speed=0, turn_rate=-turn_rate) # turn right on the spot elif ir_beacon_button_pressed == {Button.RIGHT_UP, Button.LEFT_DOWN}: self.driver.drive(speed=0, turn_rate=turn_rate) # turn left forward elif ir_beacon_button_pressed == {Button.LEFT_UP}: self.driver.drive(speed=speed, turn_rate=-turn_rate) # turn right forward elif ir_beacon_button_pressed == {Button.RIGHT_UP}: self.driver.drive(speed=speed, turn_rate=turn_rate) # turn left backward elif ir_beacon_button_pressed == {Button.LEFT_DOWN}: self.driver.drive(speed=-speed, turn_rate=turn_rate) # turn right backward elif ir_beacon_button_pressed == {Button.RIGHT_DOWN}: self.driver.drive(speed=-speed, turn_rate=-turn_rate) # otherwise stop else: self.driver.stop() def keep_driving_by_ir_beacon( self, speed: float = 1000, # mm/s turn_rate: float = 90 # rotational speed deg/s ): while True: self.drive_by_ir_beacon(speed=speed, turn_rate=turn_rate) wait(10)
# Configure 2 motors with default settings on Ports B and C. These # will be the left and right motors of the Driving Base. left_motor = Motor(Port.B) right_motor = Motor(Port.C) # The wheel diameter of the Robot Educator Driving Base is 56 mm. wheel_diameter = 56 # The axle track is the distance between the centers of each of the # wheels. This is 118 mm for the Robot Educator Driving Base. axle_track = 118 # The Driving Base is comprised of 2 motors. There is 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 drive command. robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track) # Set up the Touch Sensor on Port 1. It is used to increase the speed # of the robot. increase_touch_sensor = TouchSensor(Port.S1) # Set up the Touch Sensor on Port 2. It is used to decrease the speed # of the robot. decrease_touch_sensor = TouchSensor(Port.S2) # Initialize the "old_speed" variable to "None." It is used to check # whether the speed variable has changed. Setting it to "None" ensures # this check will be "True" when the speed variable is initialized with # a value. old_speed = None
from pybricks.tools import print, wait, StopWatch from pybricks.robotics import DriveBase import time import math #------------------------------------------------------------------------# # wir definieren globale Variablen um auf Motoren und Sensoren zuzugreifen function_l = Motor(Port.A, Direction.COUNTERCLOCKWISE) # linker Modul Motor function_r = Motor(Port.D, Direction.COUNTERCLOCKWISE) # rechter Modul Motor motor_r = Motor(Port.C, Direction.COUNTERCLOCKWISE) # rechter Rad Motor motor_l = Motor(Port.B, Direction.COUNTERCLOCKWISE) # linker Rad Motor robot = DriveBase( motor_l, motor_r, 94.2, 130.0 ) # Fahrgrundlage mit beiden Rad Motoren, Raddurchmesser und Abstand zwischen den Mittelpunkten zweier Räder col_l = ColorSensor(Port.S2) # linker Farbsensor col_l_range = [ 8, 90 ] # Spektrum in dem der linke Farbsensor, die Reflektion ausgibt(8 - schwarz; 90 - weiß) in Prozent col_r = ColorSensor(Port.S3) # rechter Farbsensor col_r_range = [ 6, 67 ] # Spektrum in dem der rechte Farbsensor, die Reflektion ausgibt(6 - schwarz; 67 - weiß) in Prozent MAX = 10000000.0 # Sehr hoher Wert sollten wir die maximale Leistung wollen WHEEL_DIAMETER = 9.42 # Raddurchmesser in cm WHEEL_CIRCUM = WHEEL_DIAMETER * math.pi # Radumfang in cm WHEEL_DISTANCE = 12.4 # Radstand in cm TURN_CIRCUM = WHEEL_DISTANCE * math.pi # Umfang des Wedekreis
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() # Write your program here. ev3.speaker.beep() # 왼쪽 모터 B 포트 모터 초기화 left_motor = Motor(Port.B) # 오른쪽 모터 C 포트 모터 초기화 right_motor = Motor(Port.C) # 드라이브베이스 초기화 robot = DriveBase(left_motor, right_motor, wheel_diameter=55.5, axle_track=104) #속도 100mm/s, 회전 속도: 0 deg/s robot.drive(100, 0) #1초 동안 모터 동작 wait(1000) #모터를 멈춘다. robot.stop()
from pybricks.hubs import EV3Brick from pybricks.ev3devices import Motor from pybricks.robotics import DriveBase from pybricks.media.ev3dev import SoundFile, ImageFile from pybricks.parameters import Direction, Port, Stop BRICK = EV3Brick() MEDIUM_MOTOR = Motor(port=Port.A, positive_direction=Direction.CLOCKWISE) LEFT_MOTOR = Motor(port=Port.B, positive_direction=Direction.CLOCKWISE) RIGHT_MOTOR = Motor(port=Port.C, positive_direction=Direction.CLOCKWISE) WHEEL_DIAMETER = 26 AXLE_TRACK = 140 DRIVE_BASE = DriveBase(left_motor=LEFT_MOTOR, right_motor=RIGHT_MOTOR, wheel_diameter=WHEEL_DIAMETER, axle_track=AXLE_TRACK) DRIVE_BASE.settings( straight_speed=250, # milimeters per second straight_acceleration=250, turn_rate=90, # degrees per second turn_acceleration=90) BRICK.screen.load_image(ImageFile.PINCHED_RIGHT) DRIVE_BASE.turn(angle=-30) MEDIUM_MOTOR.run_angle(speed=1000, rotation_angle=3 * 360, then=Stop.HOLD, wait=True)
right_motor = Motor(Port.D) frnt_left_motor = Motor(Port.B) frnt_right_motor = Motor(Port.A) gyro_sensor = GyroSensor(Port.S3) line_sensor_left = ColorSensor(Port.S4) line_sensor_right = ColorSensor(Port.S2) left_motor.reset_angle(0) right_motor.reset_angle(0) gyro_sensor.reset_angle(0) # Initialize the drive base. robot = DriveBase(left_motor, right_motor, wheel_diameter=53, axle_track=120) #endregion # # Actions will be used to change which way the robot drives. # Action = namedtuple('Action ', ['drive_speed', 'steering']) # # These are the pre-defined actions # STOP = Action(drive_speed=0, steering=0) # FORWARD_FAST = Action(drive_speed=150, steering=0) # FORWARD_SLOW = Action(drive_speed=40, steering=0) # BACKWARD_FAST = Action(drive_speed=-75, steering=0) # BACKWARD_SLOW = Action(drive_speed=-10, steering=0) # TURN_RIGHT = Action(drive_speed=0, steering=70) # TURN_LEFT = Action(drive_speed=0, steering=-70)
#!/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 from pybricks.robotics import DriveBase EV3_BRICK = EV3Brick() MEDIUM_MOTOR = Motor(port=Port.A, positive_direction=Direction.CLOCKWISE) LEFT_MOTOR = Motor(port=Port.B, positive_direction=Direction.CLOCKWISE) RIGHT_MOTOR = Motor(port=Port.C, positive_direction=Direction.CLOCKWISE) DRIVE_BASE = DriveBase(left_motor=LEFT_MOTOR, right_motor=RIGHT_MOTOR, wheel_diameter=26, axle_track=115) DRIVE_BASE.settings( straight_speed=750, # milimeters per second straight_acceleration=750, turn_rate=90, # degrees per second turn_acceleration=90) MEDIUM_MOTOR.run_time(speed=-500, time=1000, then=Stop.COAST, wait=True) DRIVE_BASE.straight(distance=300) EV3_BRICK.speaker.play_file(file=SoundFile.AIRBRAKE) MEDIUM_MOTOR.run_time(speed=500, time=1000, then=Stop.COAST, wait=True)
gyro_sensor = GyroSensor(Port.S3) #medium_motor.run_angle(90) # Initialize the color sensor. line_sensor = ColorSensor(Port.S2) left_motor.reset_angle(0) right_motor.reset_angle(0) gyro_sensor.reset_angle(0) fudge=1 speed=100 angle=0 robot = DriveBase(left_motor, right_motor, wheel_diameter=30, axle_track=135) left_motor.dc(90) right_motor.dc(90) """ initial_distance = 0 robot.reset() while ((robot.distance() - initial_distance) < 350) : drift = gyro_sensor.angle() print(gyro_sensor.angle()) angle = (drift * fudge) * -1 wait(10) i=0 speed=200 """