Mastering the `utime` Class in MicroPython
MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimised to run on microcontrollers and constrained systems. One of the essential modules in MicroPython is utime, which provides functions to handle time-related operations. Understanding the utime class is crucial for tasks such as scheduling events, measuring elapsed time, and implementing delays in your MicroPython projects.
Table of Contents#
Fundamental Concepts of utime#
The utime module in MicroPython offers a set of functions to work with time. Here are some of the key concepts:
Time Units#
MicroPython uses different time units depending on the function. The most common units are milliseconds (ms) and seconds (s). For example, some functions return time in milliseconds, while others use seconds for input parameters.
System Time#
The system time in MicroPython is a monotonic clock, which means it only moves forward and is not affected by changes in the real - world time (e.g., daylight saving time). This makes it suitable for measuring elapsed time between two events.
Sleep and Delay#
The utime module provides functions to introduce delays in your code. Delays are useful when you need to wait for a certain amount of time before performing the next operation, such as waiting for a sensor to stabilise.
Usage Methods#
sleep()#
The sleep() function is used to pause the execution of the program for a specified number of seconds. Here is an example:
import utime
print("Starting...")
utime.sleep(2) # Pause for 2 seconds
print("Two seconds have passed.")In this example, the program will print "Starting...", then pause for 2 seconds, and finally print "Two seconds have passed."
sleep_ms()#
Similar to sleep(), but it takes the delay time in milliseconds.
import utime
print("Starting...")
utime.sleep_ms(500) # Pause for 500 milliseconds (0.5 seconds)
print("Half a second has passed.")ticks_ms()#
This function returns the number of milliseconds passed since an arbitrary fixed point in time. It can be used to measure elapsed time.
import utime
start_time = utime.ticks_ms()
# Perform some operations
utime.sleep_ms(300)
end_time = utime.ticks_ms()
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time} ms")ticks_diff()#
The ticks_diff() function is used to calculate the difference between two tick values. It handles the wrap - around problem that can occur with ticks_ms().
import utime
start = utime.ticks_ms()
utime.sleep_ms(400)
end = utime.ticks_ms()
diff = utime.ticks_diff(end, start)
print(f"Difference: {diff} ms")Common Practices#
Measuring Execution Time#
You can use ticks_ms() and ticks_diff() to measure the execution time of a block of code.
import utime
start = utime.ticks_ms()
for i in range(1000):
pass
end = utime.ticks_ms()
execution_time = utime.ticks_diff(end, start)
print(f"Execution time: {execution_time} ms")Implementing a Simple Timer#
You can create a simple timer using ticks_ms() and a loop.
import utime
duration = 2000 # 2 seconds in milliseconds
start_time = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start_time) < duration:
# Do something while the timer is running
print("Timer is running...")
utime.sleep_ms(100)
print("Timer has ended.")Best Practices#
Avoid Long Delays#
Long delays in your code can make your program unresponsive. If you need to perform a long - running task, consider using a non - blocking approach, such as using interrupts or callbacks.
Handle Wrap - Around#
When using functions like ticks_ms(), be aware of the wrap - around problem. The tick values are stored in a limited number of bits, and they will eventually wrap around to zero. Use ticks_diff() to correctly calculate the difference between two tick values.
Use Appropriate Time Units#
Choose the appropriate time unit (seconds or milliseconds) based on your requirements. Using sleep_ms() for short delays can provide more precise timing.
Conclusion#
The utime class in MicroPython is a powerful tool for handling time - related operations in embedded systems. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can effectively use utime to schedule events, measure elapsed time, and introduce delays in your MicroPython projects. Whether you are working on a simple sensor project or a more complex embedded system, the utime module will be an essential part of your toolkit.
References#
- MicroPython official documentation: https://docs.micropython.org/
- MicroPython GitHub repository: https://github.com/micropython/micropython