Mastering `ticks_ms` in MicroPython: A Comprehensive Guide
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 useful features in MicroPython is the ticks_ms function. This function provides a way to measure time in milliseconds, which is crucial for many applications such as real - time control, scheduling tasks, and measuring intervals. In this blog post, we will explore the fundamental concepts, usage methods, common practices, and best practices related to ticks_ms in MicroPython.
Table of Contents#
- [Fundamental Concepts of
ticks_ms](#fundamental - concepts - of - ticks_ms) - [Usage Methods](#usage - methods)
- [Common Practices](#common - practices)
- [Best Practices](#best - practices)
- Conclusion
- References
Fundamental Concepts of ticks_ms#
The ticks_ms function is part of the utime module in MicroPython. When you call utime.ticks_ms(), it returns an integer representing the number of milliseconds elapsed since an arbitrary fixed point in time. This fixed point is often the moment when the microcontroller starts up or resets.
It's important to note that the value returned by ticks_ms is a wrapping integer. This means that after reaching a maximum value (usually related to the size of the integer type used to represent the ticks), it will wrap around to zero and start counting again. This wrapping behavior is a key aspect to understand when working with ticks_ms, as it can affect how you calculate time differences.
Usage Methods#
Here is a basic example of using ticks_ms to measure the time taken to execute a simple operation:
import utime
# Record the start time
start_time = utime.ticks_ms()
# Perform some operation
result = 0
for i in range(1000):
result += i
# Record the end time
end_time = utime.ticks_ms()
# Calculate the elapsed time
elapsed_time = utime.ticks_diff(end_time, start_time)
print(f"The operation took {elapsed_time} milliseconds.")In this example, we first record the start time using utime.ticks_ms(). Then we perform a simple loop operation. After the operation is completed, we record the end time. To calculate the elapsed time, we use the utime.ticks_diff function. This function takes into account the wrapping behavior of ticks_ms and correctly calculates the difference between two tick values.
Common Practices#
Delaying Execution#
You can use ticks_ms to implement a non - blocking delay. A non - blocking delay allows other tasks to run while waiting for the specified time to pass.
import utime
# Set the delay time in milliseconds
delay_time = 1000
start_time = utime.ticks_ms()
while True:
current_time = utime.ticks_ms()
elapsed = utime.ticks_diff(current_time, start_time)
if elapsed >= delay_time:
print("Delay is over.")
break
# You can perform other tasks here
print("Doing other tasks...")
utime.sleep_ms(10)Periodic Task Execution#
ticks_ms can also be used to execute a task periodically.
import utime
# Set the period in milliseconds
period = 500
last_run_time = utime.ticks_ms()
while True:
current_time = utime.ticks_ms()
elapsed = utime.ticks_diff(current_time, last_run_time)
if elapsed >= period:
print("Running the periodic task.")
last_run_time = current_time
utime.sleep_ms(10)Best Practices#
Use ticks_diff for Calculations#
As mentioned earlier, always use the utime.ticks_diff function when calculating the difference between two tick values. This ensures that the wrapping behavior of ticks_ms is handled correctly.
Avoid Long - Running Loops#
When using ticks_ms in a loop, make sure to keep the loop iterations short. Long - running loops can prevent other tasks from running and may cause the system to become unresponsive. If possible, use a small sleep time within the loop to allow the system to handle other tasks.
Error Handling#
Be aware of potential errors such as integer overflow or incorrect time calculations due to incorrect use of ticks_ms and ticks_diff. Always test your code thoroughly, especially in scenarios where the tick values may wrap around.
Conclusion#
The ticks_ms function in MicroPython is a powerful tool for measuring time in milliseconds. By understanding its fundamental concepts, usage methods, common practices, and best practices, you can effectively use it in your MicroPython projects. Whether you need to measure the execution time of an operation, implement non - blocking delays, or execute tasks periodically, ticks_ms provides a reliable way to handle time - related operations on microcontrollers.
References#
- MicroPython official documentation: https://docs.micropython.org/
- MicroPython
utimemodule documentation: https://docs.micropython.org/en/latest/library/utime.html