Python for EV3
· By Davinson Castaño Cano
Python can be used on the LEGO EV3 with the open-source ev3dev software or with the official LEGO version, LEGO MicroPython. To begin with, we recommend LEGO MicroPython:
- Download the EV3 MicroPython image for the microSD card.
- Flash it onto a microSD card with balenaEtcher.
- Insert the microSD card into the EV3 brick and turn it on.
- Install Visual Studio Code on your computer.
- Install and activate the LEGO Education EV3 extension.
- Connect the EV3 to your computer and start coding.
The EV3 MicroPython documentation is a good way to learn on your own.
Our first robot
First, build the driving base robot with the LEGO Education instructions. They also explain how to mount the colour sensor facing down and the ultrasonic sensor.
Programming the robot
This example works with the Robot Educator and the ultrasonic sensor. The robot drives forward until it finds an obstacle, then backs up and turns.
#!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.ev3devices import Motor, UltrasonicSensor
from pybricks.parameters import Port
from pybricks.tools import wait
from pybricks.robotics import DriveBase
brick.sound.beep()
# The ultrasonic sensor detects obstacles.
obstacle_sensor = UltrasonicSensor(Port.S4)
# Left and right motors on ports B and C.
left_motor = Motor(Port.B)
right_motor = Motor(Port.C)
# Wheel diameter and axle track of the Robot Educator, in mm.
wheel_diameter = 56
axle_track = 114
robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)
while True:
# Drive forward at 200 mm/s.
robot.drive(200, 0)
# Wait until an obstacle is closer than 300 mm.
while obstacle_sensor.distance() > 300:
wait(10)
# Back up for 2 s at 100 mm/s, then turn for 2 s at 60 °/s.
robot.drive_time(-100, 0, 2000)
robot.drive_time(0, 60, 2000)
The challenge
The challenge is to use the light sensor to program a line-follower robot. A solution with proportional control is in the LEGO Mindstorms EV3 with MicroPython project.
The real challenge is to build the fastest and most accurate line follower.