Can You Use Time 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 optimized to run on microcontrollers and constrained systems. Time handling is a crucial aspect in many embedded applications, such as scheduling tasks, measuring intervals, and creating time - based events. In this blog, we will explore how to use time in MicroPython, covering fundamental concepts, usage methods, common practices, and best practices.

Table of Contents#

  1. Fundamental Concepts
  2. Usage Methods
  3. Common Practices
  4. Best Practices
  5. Conclusion
  6. References

1. Fundamental Concepts#

Time Representation#

In MicroPython, time can be represented in different ways. One of the most common ways is using the number of milliseconds or seconds since a specific reference point, often called the epoch.

Time Modules#

MicroPython provides several modules related to time:

  • time module: This is the primary module for basic time - related functions such as getting the current time, sleeping, and measuring time intervals.
  • utime module: In some MicroPython implementations, utime is used instead of time. The functionality is similar, but utime is often more lightweight and suitable for resource - constrained devices.

2. Usage Methods#

Getting the Current Time#

import time
 
# Get the current time in seconds since the epoch
current_time = time.time()
print(f"Current time in seconds: {current_time}")
 
# On some MicroPython platforms, you can also get the time in milliseconds
try:
    current_time_ms = time.ticks_ms()
    print(f"Current time in milliseconds: {current_time_ms}")
except AttributeError:
    print("ticks_ms() not available on this platform.")
 

In this code, we first import the time module. Then we use the time() function to get the current time in seconds. Additionally, we try to use the ticks_ms() function to get the current time in milliseconds, which may not be available on all platforms.

Sleeping#

Sleeping is used to pause the execution of the program for a certain period.

import time
 
print("Before sleeping")
# Sleep for 2 seconds
time.sleep(2)
print("After sleeping")
 
# Sleep for 500 milliseconds
try:
    time.sleep_ms(500)
    print("After sleeping for 500 ms")
except AttributeError:
    print("sleep_ms() not available on this platform.")
 

Here, we use the sleep() function to pause the program for 2 seconds. We also try to use the sleep_ms() function to sleep for 500 milliseconds.

Measuring Time Intervals#

import time
 
start_time = time.ticks_ms()
# Simulate some work
for i in range(1000):
    pass
end_time = time.ticks_ms()
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time} ms")
 

In this example, we use ticks_ms() to record the start and end times of a loop. Then we calculate the elapsed time by subtracting the start time from the end time.

3. Common Practices#

Blinking an LED at a Fixed Interval#

import machine
import time
 
# Assume LED is connected to pin 2
led = machine.Pin(2, machine.Pin.OUT)
 
while True:
    led.on()
    time.sleep(0.5)
    led.off()
    time.sleep(0.5)
 

This code blinks an LED connected to pin 2 at a fixed interval of 500 milliseconds on and 500 milliseconds off.

Periodic Data Sampling#

import machine
import time
 
# Assume a sensor is connected to pin 3
sensor = machine.ADC(machine.Pin(3))
 
while True:
    sensor_value = sensor.read()
    print(f"Sensor value: {sensor_value}")
    time.sleep(1)
 

In this example, we read data from a sensor connected to pin 3 every second.

4. Best Practices#

Avoid Long Sleeps#

Long sleeps can prevent other tasks from running, especially in a multi - tasking environment. If possible, use shorter sleeps and implement a more sophisticated scheduling mechanism.

Use Non - Blocking Time Functions#

In some cases, you may need to perform other tasks while waiting for a certain time to pass. You can use non - blocking time functions to achieve this. For example, instead of using sleep(), you can use ticks_diff() to check if a certain time interval has passed.

import time
 
start_time = time.ticks_ms()
interval = 1000  # 1 second
 
while True:
    current_time = time.ticks_ms()
    if time.ticks_diff(current_time, start_time) >= interval:
        print("One second has passed.")
        start_time = current_time
 
    # Do other tasks here
    pass
 

In this code, we use ticks_diff() to check if one second has passed without blocking the execution of other tasks.

5. Conclusion#

Time handling is an essential part of MicroPython programming, especially for embedded applications. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can effectively use time in your MicroPython projects. Whether you are blinking an LED, sampling sensor data, or implementing complex scheduling algorithms, the time - related functions in MicroPython provide the necessary tools.

6. References#