Member-only story

MicroPython Tutorial XVII

Mark Lucking
4 min readAug 31, 2019

Sensors. Beyond the colour and gyro sensors you have more, two notable ones the ultrasonic and infrared. We used the infrared in an earlier tutorial with the remote in fact, although it has a few more tricks up its sleve.

Of course you you have one or the other depending on which set you buy. I wouldn’t go out and get the missing one in preference to the colour sensor, but if you still some money left, its your next investment.

Both sensors will measure distance, but report their findings differently. The ultrasonic reports in millimetres, the infrared reports as a percentage figure. But beware they don’t behave in the same manner as I discovered by accident a while back. Here is a simple piece of code to invoke them.

#!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.ev3devices import UltrasonicSensor, InfraredSensor
from pybricks.parameters import Port
from pybricks.tools import wait
ultra = UltrasonicSensor(Port.S1)
infra = InfraredSensor(Port.S2)
while True:
distance = ultra.distance()
distance2 = infra.distance()
print("ultra distance",distance,"infra distance",distance2)
wait(500)

All this does is define the two sensors and report the distances they see every 1/2 a second. I mounted them on my robot and build a lego tower to observe as you can see in this photo.

--

--

Mark Lucking
Mark Lucking

Written by Mark Lucking

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

No responses yet