MicroPython Tutorial VIII

Ok, lets go back to basics. Here is the code to do the basic buttons on the brick, with some additions to include the motor classes.

#!/usr/bin/env pybricks-micropython 
from pybricks import ev3brick as brick
from pybricks.parameters import Button, Port
from pybricks.ev3devices import Motor
while True:
if Button.DOWN in brick.buttons():
print(“DOWN button”,Button)
if Button.UP in brick.buttons():
print(“UP button”,Button)

To can then define motors by indicating which port they are connected too. Obviously in this example the motors would be physically connected to port C and port B.

leftMotor = Motor(Port.B)
rightMotor = Motor(Port.C)

A word of warning, the error messages you get you get when the ports aren’t connected firmly are not very explicit. This an example of what comes back if one of the motors isn’t connected at the time of writing. A feature of MicroPython I fear.

Traceback (most recent call last):
File “./motor.py”, line 8, in <module>
OSError: [Errno 19] ENODEV

Assuming you managed to connect them and you’re ready to go, try combining the commands you need to run the motors with your base script. You should end up with something along these lines.

while True:
if Button.DOWN in brick.buttons():
if Button.UP in brick.buttons():
if Button.RIGHT in brick.buttons():
if Button.LEFT in brick.buttons():
if Button.CENTER in brick.buttons():

The number given here 1020 deg/s is the theoretical maximum speed of the large EV3 motor, in reality you won’t get this much speed out of it. It will max out at 930 deg/s with no load, and 880 deg/s using the standard LEGO rover build.

The most useful command from a feedback point of view is the one shown in the box below. It will show you the rotational angle of the motor. Useful for positioning of your robot.

Image for post

Try adding it to your script and get a feeling for the numbers returned. Of course you may not wLEGOant to have your robot spinning uncontrollably in circles or indeed off into the distance, your looking for more control. Lets try some more commands with our base script.

Finally be careful when you implement this, put the rover on the floor perhaps else he might end up scooting off the table.

Written by

Coding for 35+ years, enjoying using and learning Swift/iOS development. Writer @ Better Programming, @The StartUp, @Mac O’Clock, Level Up Coding & More

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store