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 TouchSensor
touchS3 = TouchSensor(Port.S3)watch = StopWatch()
ptime = 0
gap = 1000
while 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 as it is defined. It counts in 1000’s of a second.

Now if you press the touch sensor, it changes the LED colour on the brick to yellow and resets the “stop watch” counter.

It you do nothing, the script uses some simple math to work out when the gap seconds [in thousands of a second] has passed and prints it out. Blinking the LED red as it does so. You can make it blink faster by reducing the value help in the variable gap.

We have two more methods that we can call with stop watch and have added two more touch sensors with some code to make use of them.

    if touchS1.pressed():
brick.light(Color.GREEN)
print("resume",watch.time())
watch.resume()
wait(1000)
if touchS2.pressed():
brick.light(Color.ORANGE)
print("pause",watch.time())
watch.pause()
wait(1000)

Obviously this code assume you have an additional touch sensor. You need to add it before the touch S3 code previously shown.

What does it do. I hope it self evident, S2 will pause the “stop watch” and S3 will resume it where you left off.

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store