Lego EV3 with Python

Prerequisites

This will assume you already have Python installed and working on your computer, and that you know the basics of Python programming.

Install and setup

Step 1 - Setup a micro-SD card with the ev3dev software

Step 2 - Setup VS Code

Step 3 - Connect the EV3 to VS Code on your computer

Demo code

If you have built the “standard template robot” as per the instructions that come with the ev3 lego kits, you should have a robot that looks like this.

The following demonstration code will:

#!/usr/bin/env python3
import time
from ev3dev.ev3 import *
from ev3dev2.led import *

# Create variables
leds = Leds()
mB = LargeMotor('outB')
mC = LargeMotor('outC')

# Beeps and LED flashes
leds.all_off()
Sound.speak("I am E V 3, watch me dance.").wait()
for i in range(1,3): # run the indented loop three times
    leds.set_color("LEFT", "RED")
    leds.set_color("RIGHT", "GREEN")
    Sound.beep().wait()
    leds.set_color("LEFT", "GREEN")
    leds.set_color("RIGHT", "RED")
    Sound.beep().wait()

# Drive forward
leds.set_color("LEFT", "ORANGE")
leds.set_color("RIGHT", "ORANGE")
mB.run_forever(speed_sp=1000)
mC.run_forever(speed_sp=1000)
time.sleep(3)
mB.stop(stop_action='brake')
mC.stop(stop_action='brake')

# Spin clockwise
leds.all_off()
leds.set_color("RIGHT", "ORANGE")
mB.run_forever(speed_sp=-1000) # negative = drive backwards
mC.run_forever(speed_sp=1000)
time.sleep(3)
mB.stop(stop_action='brake')
mC.stop(stop_action='brake')

# Spin anticlockwise
leds.all_off()
leds.set_color("LEFT", "ORANGE")
mB.run_forever(speed_sp=1000)
mC.run_forever(speed_sp=-1000) # negative = drive backwards
time.sleep(3)
mB.stop(stop_action='brake')
mC.stop(stop_action='brake')

# Say good bye
leds.set_color("LEFT", "RED")
leds.set_color("RIGHT", "RED")
Sound.beep().wait()
Sound.speak("Have a nice day.").wait()
leds.all_off()

Motors

Import the library to have motor functionality

from ev3dev.ev3 import *

Example using the motors

mB = LargeMotor('outB')
mC = LargeMotor('outC')

mB.run_forever(speed_sp=720)
mC.run_forever(speed_sp=720)

time.sleep(3000)

mB.stop(stop_action='brake')
mC.stop(stop_action='brake')

To turn a motor a certain number of degrees

# Turn wheel 180 degrees at speed 900 then apply strong brake.
mA.run_to_rel_pos( position_sp=180, speed_sp=900, stop_action="brake" )

To turn a motor a certain period of time

# Turn wheel for 2000 milli seconds at speed 720
mA.run_timed(time_sp=2000, speed_sp=720)

To turn a motor “forever”

# Turn wheel at speed 1080
mA.run_forever(speed_sp=1080)

To stop a motor

# Stop actively turning and apply the brake
mA.stop(stop_action="brake")
# Stop actively turning, come to a rolling stop
mB.stop(stop_action="coast")

To pause your program while the motor is turning for an angle or set period of time

mC = LargeMotor('outC')
mC.run_timed(time_sp=3000, speed_sp=-750, stop_action='brake')
mC.wait_while('running')       # Wait until the 3 seconds has finished

Sensors

For sensors to work, you must import the library as shown:

from ev3dev.ev3 import *

It is usually optional to specify the input port numbers for each sensor. If there is only one sensor of that type, Python can work out which one you are asking for. If you use more than one (such as two touch sensors) then you do need to specify which port you want to refer to at that time. The sensor port code names to use in the parameters are in1, in2, in3 and in4.

Using ultrasonic sensor

# Setup
us = UltrasonicSensor() 
assert us.connected, "Connect an EV3 ultrasonic sensor to any sensor port"

# Use
us.mode='US-DIST-CM'
distance = us.value()
if distance < 20:
   print("An object is less than 20 cm away")

Using touch sensors

# Setup
ts1 = TouchSensor('in1')
ts2 = TouchSensor('in2')
assert ts1.connected, "Connect an EV3 touch sensor to sensor port 1"
assert ts2.connected, "Connect an EV3 touch sensor to sensor port 2"

# Use
if ts1.value() and ts2.value():
   print("Both touch are being pressed")

Using colour sensor to detect black/white reflection

# Setup
assert cs.connected, "Connect an EV3 color sensor to any sensor port"
cs.mode='COL-REFLECT'              # Color intensity mode

# Use
reflection = cs.value()            # Value will be between 0 and 99
if reflection < 25:
   print("It's very dark in here")
elif reflection > 75:
   print("I need my sunglasses!")
else:
   print("Just another grey day")

Using colour sensor to detect colours

# Setup
cs = ColorSensor('in3')
assert cs.connected, "Connect an EV3 color sensor to any sensor port"
cs.mode='COL-COLOR'            # Color detection mode
colorlist = ('unknown','black','blue','green','yellow','red','white','brown')

# Use
if colorlist[cs.value()] == "blue":
   print("The sensor can see blue")

Buttons

Create a variable for your button system

button = Button()

While loop until any button is pressed

while not button.any():
    # Do something

Checking button state

if button.backspace:
    print("You pressed backspace, so I'm going to quit")
    exit()

Create event handling functions

def left(state):
   if state:
        print("Left button pressed")
        else:
          print("Left button released")

def right(state):
   if state:
        print("Right button pressed")

def up(state):
   pass # Empty response just for demo purposes

def down(state):
   pass # Empty response just for demo purposes

def enter(state):
   pass # Empty response just for demo purposes

def backspace(state):
   pass # Empty response just for demo purposes

button.on_left = left
button.on_right = right
button.on_up = up
button.on_down = down
button.on_enter = enter
button.on_backspace = backspace

LEDs

For LEDs to work, you must import the library as shown:

from ev3dev2.led import *

Create a variable for your LEDs

leds = Leds()

To turn off all LEDs

leds.all_off()

The following examples should demonstrate how to set on/off individual LEDs to individual colours.

leds.set_color("LEFT", "RED")
leds.set_color("RIGHT", "GREEN")
leds.set_color("RIGHT", "AMBER")
leds.set_color("RIGHT", "ORANGE")
leds.set_color("RIGHT", "YELLOW")
leds.set_color("RIGHT", "BLACK")

Sounds

For sounds to work, you must import the full library as shown:

from ev3dev.ev3 import *

Play a beep

Sound.beep()

Play a tone

frequency = 1500 # hertz
duration = 2000  # milli seconds
Sound.tone(frequency, duration)

Play a sound file

Sound.play( "songfile.wav" )

Text to speech

Sound.speak("My name is C 3 P O. Human cyborg relations.")

References

A huge credit to Nigel Ward for his excellent written and video tutorials on using the EV3 with Python!