Completed
LEGO Mindstorms EV3 with MicroPython
Setting up MicroPython on the EV3 and our first mobile robots programmed in Python, such as a line follower with proportional control.
The documentation for controlling the LEGO Mindstorms EV3 with MicroPython is here:
Setup
To use MicroPython on the EV3 you need:
- A microSD card with the MicroPython image.
- Visual Studio Code with the LEGO Mindstorms EV3 MicroPython extension.
The blog post Python for EV3 walks through the process step by step.
Example: line follower
The robot calibrates the colour sensor by measuring a white and a black surface, then corrects its heading in proportion to the error from the midpoint.
from pybricks import ev3brick as brick
from pybricks.ev3devices import Motor, ColorSensor, UltrasonicSensor
from pybricks.parameters import Port
from pybricks.tools import wait
from pybricks.robotics import DriveBase
color_sensor = ColorSensor(Port.S4)
distance_sensor = UltrasonicSensor(Port.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)
brick.display.clear()
def calibrate():
brick.display.text("WHITE?")
brick.sound.beep()
while not any(brick.buttons()):
wait(10)
white = color_sensor.reflection()
while any(brick.buttons()):
wait(10)
brick.display.text("BLACK?")
brick.sound.beep()
while not any(brick.buttons()):
wait(10)
black = color_sensor.reflection()
return black, white
black, white = calibrate()
reference = (black + white) / 2
Kp = 1
brick.display.text("Reference at: " + str(reference))
while True:
measure = color_sensor.reflection()
error = reference - measure
robot.drive(100, Kp * error)
wait(50) Translated from Spanish.