Member-only story
MicroPython Tutorial XVIII
Ok, lets do something else for a break and indeed touch on the last sensor we’re going cover, which is called ironically touch, pun intended.
You get two touch sensors in both kits I believe, and it is quite simple to use them, with just two properties. Either they are being touched or not basically.
Let combine this with a common requirement you get in lots of app, the requirement to time something. We’re going a use a special method you get with MicroPython and combined with some simple math. Here is our basic script.
#!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.parameters import Color, Port
from pybricks.tools import wait, StopWatch
from pybricks.ev3devices import TouchSensortouchS3 = TouchSensor(Port.S3)watch = StopWatch()
ptime = 0
gap = 1000while True:
if touchS3.pressed():
brick.light(Color.YELLOW)
print("reset",watch.time())
watch.reset()
else:
timeFreeze = watch.time() // gap
timInt = timeFreeze % gap
if ptime != timInt:
print("watch.time",timInt)
ptime = timInt
if timInt % 2 == 0:
brick.light(Color.RED)
else:
brick.light(Color.BLACK)
What does it do. We import the standard libraries and define a touch sensor that we previously plugged into port 3. Now we start a “stop watch” process that basically starts to count as soon…