Ev3dev sensors¶
Note
This class is only available on EV3.

EV3 MicroPython is built on top of ev3dev, which means that a sensor
may be supported even if it is not listed in this documentation. If so, you can
use it with the Ev3devSensor
class. This is easier and faster than using
the custom device classes given above.
To check whether you can use the Ev3devSensor
class:
Plug the sensor into your EV3 Brick.
Go to the main menu of the EV3 Brick.
Select Device Browser and then Sensors.
If your sensor shows up, you can use it.
Now select your sensor from the menu and choose set mode. This shows all
available modes for this sensor. You can use these mode names as the mode
setting below.
To learn more about compatible devices and what each mode does, visit the ev3dev sensors page.
-
class
Ev3devSensor
(port)¶ Read values of an ev3dev-compatible sensor.
- Parameters
port (Port) – Port to which the device is connected.
-
sensor_index
¶ Index of the ev3dev sysfs lego-sensor class.
Example: Reading values with the Ev3devSensor class
In this example we use the LEGO MINDSTORMS EV3 Color Sensor with the raw RGB mode. This gives uncalibrated red, green, and blue reflection values.
#!/usr/bin/env pybricks-micropython
from pybricks.parameters import Port
from pybricks.tools import wait
from pybricks.iodevices import Ev3devSensor
# Initialize an Ev3devSensor.
# In this example we use the
# LEGO MINDSTORMS EV3 Color Sensor.
sensor = Ev3devSensor(Port.S3)
while True:
# Read the raw RGB values
r, g, b = sensor.read('RGB-RAW')
# Print results
print('R: {0}\t G: {1}\t B: {2}'.format(r, g, b))
# Wait
wait(200)
Example: Extending the Ev3devSensor class
This example shows how to extend the Ev3devSensor
class by accessing
additional features found in the Linux system folder for this device.
#!/usr/bin/env pybricks-micropython
from pybricks.parameters import Port
from pybricks.iodevices import Ev3devSensor
class MySensor(Ev3devSensor):
"""Example of extending the Ev3devSensor class."""
def __init__(self, port):
"""Initialize the sensor."""
# Initialize the parent class.
super().__init__(port)
# Get the sysfs path.
self.path = '/sys/class/lego-sensor/sensor' + str(self.sensor_index)
def get_modes(self):
"""Get a list of mode strings so we don't have to look them up."""
# The path of the modes file.
modes_path = self.path + '/modes'
# Open the modes file.
with open(modes_path, 'r') as m:
# Read the contents.
contents = m.read()
# Strip the newline symbol, and split at every space symbol.
return contents.strip().split(' ')
# Initialize the sensor
sensor = MySensor(Port.S3)
# Show where this sensor can be found
print(sensor.path)
# Print the available modes
modes = sensor.get_modes()
print(modes)
# Read mode 0 of this sensor
val = sensor.read(modes[0])
print(val)