PymateIO-Delaying
Abstract
The "Cycle Timing" tutorial state the following:
NEVER USE BLOCKING INSTRUCTION in the mainloop
Blocking instruction locks the script execution in a waiting state... whereas critical operation may requires quick reaction from the script.
The sleep(), sleep_ms() are BLOCKING INSTRUCTIONS.
They should never be used in your script, neither in the mainloop
The solution for this is:
- use the EventTimer class
- set the delay on the EventTimer when the source event occurs.
- check the EventTimer.done at every mainloop cycle.
- Once done, it is time to executed the delayed code.
Remark: the done will assert True only once for every set()!
Practical example
As practical example, we will read DS18B20 OneWire sensor connected on the Pymate Expansion port.
The problem with the DS18B20 is required pause of 750ms between the temperature request and values reading.
Wiring DS18B20
Simple Example
Here follow a basic MicroPython script showing how to deal with the DS18B20 sensor.
This script makes a reading every 5 seconds (execution limited to 10 iteration).
Unfortunately, this use blocking instructions like sleep_ms() and sleep().
from machine import Pin
import onewire, ds18x20
import time
dat = Pin( "I2C4_SMB", Pin.IN )
bus = onewire.OneWire(dat)
ds = ds18x20.DS18X20( bus )
roms = ds.scan()
print( "Found devices", roms )
for i in range(10):
print( "%i: Read temperature" %i )
ds.convert_temp()
time.sleep_ms(750) # Required by OneWire protocol
for rom in roms:
print( 'ROM', rom, 'Temperature', ds.read_temp(rom) )
time.sleep( 5 )
print( "That's all Folks" )
PymateIO all right reserved © 2026 - Written by MCHobby for PymateIO
