Learn EV3 Python‎ > ‎

Using Sensors

The official documentation is HERE and HERE. See also the Sensor Modes page.

EV3 Python is compatible with all the standard EV3 and NXT sensors except the NXT light sensor cannot be used to detect colors (as of September 2016).

EV3 and/or NXT sensors can be attached to any of the EV3's four sensor ports but I will adhere to the useful convention that they should be attached as follows:
       port 1 = touch, port 2 = gyro, port 3 = color, port 4 = infrared or ultrasonic.
This convention is useful because it means you don't have to reconnect the sensors as you move from one EV3 tutorial to another.

if you don’t attach more than one sensor of a particular type, then it will not matter which port a sensor is plugged in to. You don't need to include any reference on your code to the sensor port number - your program will just work. However, if you connect more than one sensor of a given type then you need to specify the port number with 'in1', 'in2' etc or look at the port_name attribute.

As usual, I only mention what I think is most likely to be useful to you as a beginner. For sensors, that would include InfraredSensor(), TouchSensor(), UltrasonicSensor, ColorSensor(), LightSensor(), GyroSensor(), RemoteControl(), SoundSensor(), value(), mode() and units. Note that the EV3 'color' sensor corresponds to the NXT 'light' sensor.

As in the standard Lego EV3 software, many sensors can be used in different modes. Information about the different modes available for different Lego sensors can be found in the Lego section of the sensor-specific-resources section of THIS PAGE and selected information from that page is HERE. To set the desired mode for the sensor you are using, use mode as in the first example below. For example, if a single IR sensor is attached to any sensor port and named ir then you can set it to proximity mode with ir.mode = 'IR-PROX' . The touch sensor does not have multiple modes, of course, but for the other sensors it is important to always set the mode of the sensor before it is used.

The reading from every sensor in every mode (except the color sensor in RGB-RAW mode) is obtained with the value() method (a 'method' is a special kind of function). Don't forget to include the parentheses.

Example 1 (touch sensor & IR sensor)
The example below uses the touch sensor and the IR sensor. It continuously displays the distance value detected by the IR sensor, along with the corresponding units (pct, meaning percent, for the IR sensor). It turns the left LED from green to red when an object is brought close to the IR sensor, and turns it back to green when no object is close. The while loop runs as long as the touch sensor button is NOT pressed. When the touch sensor is pressed the loop is exited, a beep is sounded and the left LED is set to green (it might have been red when the loop was exited).

The example uses the assert statement to check that the sensors are attached. If the assertion fails then the program closes with a useful error message (in this case a text message). Assert is a statement and not a function, so it should be used without parentheses as here.

#!/usr/bin/env python3
# so that script can be run from Brickman

from ev3dev.ev3 import *

# Connect infrared and touch sensors to any sensor ports
# and check they are connected.

ir = InfraredSensor() 
assert ir.connected, "Connect a single infrared sensor to any sensor port"

ts = TouchSensor();    assert ts.connected, "Connect a touch sensor to any port" 
# can have 2 statements on same line if use semi colon

# Put the infrared sensor into proximity mode.
ir.mode = 'IR-PROX'

while not ts.value():    # Stop program by pressing touch sensor button
    # Infrared sensor in proximity mode will measure distance to the closest
    # object in front of it.
    distance = ir.value()

    if distance < 60:
        Leds.set_color(Leds.LEFT, Leds.RED)
    else:
        Leds.set_color(Leds.LEFT, Leds.GREEN)

Sound.beep()       
Leds.set_color(Leds.LEFT, Leds.GREEN)  
#make sure left led is green before exiting

Example 2 (touch sensor and EV3 ultrasonic sensor)
An ultrasonic sensor is included with the educational version of the EV3 kit but not with the home version (it can be bought separately). If you have a single EV3 ultrasonic sensor attached to the EV3 then you can modify the code of Example 1 to make it work with the EV3 US sensor as shown below. When you set the EV3 US sensor mode to US-DIST-CM as below you expect the sensor to return a value in cm, of course, and in a sense it does but it is one of several modes (see the sensor modes page) that also includes a first decimal place (but no decimal point) in the returned value. That means the value returned really represents mm rather cm. For example, if the sensor returns the value 90 cm it actually means 9.0 cm (or 90 mm) since the value includes one decimal place! Obviously, you need to take great care handling the values returned by these modes. To deal with this problems, I have included a division by ten in the code below to convert the distance from mm to cm. Thus the code below will make the color of the left LED change to red when an object is within 60.0 cm (600 mm) of the US sensor.

Similarly, if you set the mode to US-DIST-IN  you expect the value to be in inches but in fact it is in tenths of an inch so you need to divide the value by 10 to get inches. Or, put another way, the value is in inches but includes the first decimal place of the value. Confusing, isn't it? If you use inches you will probably want to use a distance less than 60.0 inches for the led to switch to red. Note that the problem with the EV3 ultrasonic sensor is NOT shared by the NXT ultrasonic sensor, which simply gives the reading as an integer (zero decimal places).

#!/usr/bin/env python3
# so that script can be run from Brickman

from ev3dev.ev3 import *

# Connect ultrasonic and touch sensors to any sensor port
# and check they are connected.
us = UltrasonicSensor() 
assert us.connected, "Connect a single US sensor to any sensor port"
ts = TouchSensor();    assert ts.connected, "Connect a touch sensor to any port"  
# can have 2 statements on same line if use semi colon

# Put the US sensor into distance mode.
us.mode='US-DIST-CM'

units = us.units
# reports 'cm' even though the sensor measures 'mm'

while not ts.value():    # Stop program by pressing touch sensor button
    # US sensor will measure distance to the closest
    # object in front of it.
    distance = us.value()/10  # convert mm to cm
    print(str(distance) + " " + units)

    if distance < 60:  #This is an inconveniently large distance
        Leds.set_color(Leds.LEFT, Leds.RED)
    else:
        Leds.set_color(Leds.LEFT, Leds.GREEN)

Sound.beep()       
Leds.set_color(Leds.LEFT, Leds.GREEN)  #set left led green before exiting


Example 3 (two touch sensors)
Usually you will not have two sensors of the same type plugged into the EV3 and you will not have to specify or determine where the sensors are attached. But in this example let's assume we have TWO touch sensors plugged into the EV3. We will SPECIFY which ports the sensors are plugged into using 'in1' and 'in2' for sensor (input) ports 1 and 2. In this program the left led is set to green if the touch sensor on port 1 is not pressed and red if it is pressed (more specifically, if the touch sensor is not pressed then it returns a value of zero and the code then uses item zero from the tuple). In a similar way the touch sensor on port 2 controls the right led. To stop this program you will need to press Ctrl-C to interrupt the while loop.

#!/usr/bin/env python3
# so that script can be run from Brickman

from ev3dev.ev3 import *
from time   import sleep

# Connect TWO touch sensors to BOTH sensor ports 1 and 2
# and check they are both connected.

ts1 = TouchSensor('in1') 
assert ts1.connected, "Connect a touch sensor to sensor port 1"

ts2 = TouchSensor('in2')
assert ts2.connected, "Connect a touch sensor to sensor port 2"

while True:    # Stop this program with Ctrl-C
    Leds.set_color(Leds.LEFT, (Leds.GREEN, Leds.RED)[ts1.value()])
    Leds.set_color(Leds.RIGHT, (Leds.GREEN, Leds.RED)[ts2.value()])

# Stop program with Ctrl-C

Example 4 (gyro sensor and touch sensor)
The gyro sensor is included with the educational version of the EV3 kit but not with the home version (it can be bought separately). It measures the angle in degrees, giving the value of zero degrees to the orientation of the sensor when the program is started. Note that it is vital that the gyro sensor be absolutely still when the program is launched otherwise the reading will wander later even when the sensor is held still.

The sensor can also measure the rate of change of the angle, in degrees per second, but as a beginner you are likely to find that less useful.

The program below prints the measured angle to the console, then plays for one second a tone whose frequency depends on the angle, then waits for 0.5 second before repeating the cycle. Press the touch sensor button for at least a second to stop the program.

#!/usr/bin/env python3
# so that script can be run from Brickman

from ev3dev.ev3 import *
from time import sleep

# Connect gyro and touch sensors to any sensor port
# and check they are connected.
gy = GyroSensor() 
assert gy.connected, "Connect a single gyro sensor to any sensor port"
ts = TouchSensor();    assert ts.connected, "Connect a touch sensor to any port"  
# can have 2 statements on same line if use semi colon

# Put the gyro sensor into ANGLE mode.
gy.mode='GYRO-ANG'

units = gy.units
#reports 'deg' meaning degrees

while not ts.value():    # Stop program by pressing touch sensor button
    angle = gy.value()
    print(str(angle) + " " + units)
    Sound.tone(1000+angle*10, 1000).wait()
    sleep(0.5)

Sound.beep()

Example 5: Color sensor in COL-REFLECT mode
In this script the color sensor emits light and measures the reflected light intensity, returning twice every second a value which is theoretically between 0 and 100. For best results, place the sensor about 3 mm from the reflecting surface. Using that separation, I get a value of about 80 with normal white paper and about 5 with a typical black surface.

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

# Connect EV3 color sensor and check connected.

cl = ColorSensor()
assert cl.connected, "Connect a color sensor to any sensor port"

# Put the color sensor into COL-REFLECT mode
# to measure reflected light intensity.
# In this mode the sensor will return a value between 0 and 100
cl.mode='COL-REFLECT'

while True:
    print(cl.value())
    sleep(0.5)
    
# I get max 80 with white paper, 3mm separation 
# and 5 with black plastic, same separation

See also lesson 6 on this page.

Example 6: EV3 color sensor in COL-AMBIENT mode, touch sensor and large motor
In this program the color sensor measures ambient light intensity, returning a value between 0 and 100. This value is used to control the speed of a large motor attached to port B, so the brighter the ambient light the faster the motor will turn. Press the touch sensor button to stop the program. To make this program work with reflected light intensity rather than ambient light intensity, just replace COL-AMBIENT with COL-REFLECT.

#!/usr/bin/env python3
# so that script can be run from Brickman

from ev3dev.ev3 import *
from time import sleep

# Connect EV3 color sensor and touch sensor
# and check they are connected.

cl = ColorSensor() 
assert cl.connected, "Connect an EV3 color sensor to any sensor port"

ts = TouchSensor()
assert ts.connected, "Connect a touch sensor to any sensor port"

# Connect a large motor to port B and check it is connected.
m = LargeMotor('outB')
assert m.connected, "Connect a large motor to port B" 

# Put the color sensor into COL-AMBIENT mode
# to measure ambient light intensity.
# In this mode the sensor will return a value between 0 and 100
cl.mode='COL-AMBIENT'

# run_forever command will allow us to vary motor
# performance on the fly by adjusting speed_sp attribute.
m.run_forever(speed_sp = 0)

while not ts.value():    # Stop program by pressing touch sensor button
# set the motor's speed set point to be equal to
# the measured ambient light intensity value
    m.speed_sp = cl.value()

Sound.beep()

Example 7: EV3 color sensor in COL-COLOR mode and touch sensor
When the EV3 color sensor is in COL-COLOR mode it tries to recognise the color of standard Lego bricks placed about 5-6mm in front of the sensor (the distance is critical) and returns a corresponding integer value between 0 (unknown) and 7 (brown). The program below reads the integer once per second, converts it into the corresponding text string using a tuple and displays the string in the console. Press the touch sensor button for at least a second to stop the program.

To make the program speak the colors as well as displaying their text strings, uncomment the line highlighted in blue. This will slightly increase the time between measurements as I included a wait() function to ensure that the speech was not interrupted.

#!/usr/bin/env python3
# so that script can be run from Brickman

from ev3dev.ev3 import *
from time   import sleep

# Connect EV3 color sensor to any sensor port
# and check it is connected.

cl = ColorSensor() 
assert cl.connected, "Connect a single EV3 color sensor to any sensor port"

# Connect touch sensor to any sensor port
# and check it is connected.
ts = TouchSensor();    assert ts.connected, "Connect a touch sensor to any port"  
# you can have 2 statements on the same line if you use a semi colon

# Put the color sensor into COL-COLOR mode.
cl.mode='COL-COLOR'

colors=('unknown','black','blue','green','yellow','red','white','brown')
while not ts.value():    # Stop program by pressing touch sensor button
    print(colors[cl.value()])
    #Sound.speak(colors[cl.value()]).wait()
    sleep(1)
Sound.beep()

Example 8: EV3 color sensor in RGB-RAW mode and touch sensor

This mode is special since it returns 3 values simultaneously, representing the amounts of red, green and blue reflected light (any color can be obtained by mixing the correct amounts of red, green and blue light). These values can be referred to in code as value(0), value(1) and value(2) respectively. The following program prints the three values detected once every second. Press the touch sensor button for at least a second to stop the program. For more information see THIS PAGE.

#!/usr/bin/env python3
# so that script can be run from Brickman

from ev3dev.ev3 import *
from time   import sleep

# Connect EV3 color sensor to any sensor port
# and check it is connected.

cl = ColorSensor() 
assert cl.connected, "Connect a single EV3 color sensor to any sensor port"

# Connect touch sensor to any sensor port
# and check it is connected.
ts = TouchSensor();  assert ts.connected, "Connect a touch sensor to any port"  
# you can have 2 statements on the same line if you use a semi colon

# Put the color sensor into RGB mode.
cl.mode='RGB-RAW'

while not ts.value():    # Stop program by pressing touch sensor button
    red = cl.value(0)
    green=cl.value(1)
    blue=cl.value(2)
    print("Red: " + str(red) + ", Green: " + str(green) + ", Blue: " + str(blue))
    sleep(1)
Sound.beep()
Subpages (1): Sensor Modes
Comments