[Diao Ye Learns Programming] MicroPython Manual SAMD21 Clock and Time

Insert image description here
MicroPython is a lightweight version of the interpreter designed for running the Python 3 programming language in embedded systems. Compared with regular Python, the MicroPython interpreter is small (only about 100KB) and is compiled into a binary Executable file to run, resulting in higher execution efficiency. It uses a lightweight garbage collection mechanism and removes most of the Python standard library to accommodate resource-constrained microcontrollers.

The main features of MicroPython include:
1. The syntax and functions are compatible with standard Python, making it easy to learn and use. Supports most of Python's core syntax.
2. Directly access and control hardware, control GPIO, I2C, SPI, etc. like Arduino.
3. Powerful module system, providing file system, network, graphical interface and other functions.
4. Support cross-compilation to generate efficient native code, which is 10-100 times faster than the interpreter.
5. The amount of code is small and the memory usage is small. It is suitable for running on MCU and development boards with small memory.
6. Open source license, free to use. The Shell interactive environment provides convenience for development and testing.
7. The built-in I/O driver supports a large number of microcontroller platforms, such as ESP8266, ESP32, STM32, micro:bit, control board and PyBoard, etc. There is an active community.

MicroPython application scenarios include:
1. Rapidly build prototypes and user interactions for embedded products.
2. Make some small programmable hardware projects.
3. As an educational tool, it helps beginners learn Python and IoT programming.
4. Build smart device firmware to achieve advanced control and cloud connectivity.
5. Various microcontroller applications such as Internet of Things, embedded intelligence, robots, etc.

Things to note when using MicroPython:
1. Memory and Flash space are limited.
2. The explanation and execution efficiency is not as good as C language.
3. Some library functions are different from the standard version.
4. Optimize the syntax for the platform and correct the differences with standard Python.
5. Use memory resources rationally and avoid frequently allocating large memory blocks.
6. Use native code to improve the performance of speed-critical parts.
7. Use abstraction appropriately to encapsulate underlying hardware operations.

Generally speaking, MicroPython brings Python into the field of microcontrollers, which is an important innovation that not only lowers the programming threshold but also provides good hardware control capabilities. It is very suitable for the development of various types of Internet of Things and intelligent hardware.
Insert image description here
SAMD21 is a series of low-power microcontrollers using 32-bit ARM® Cortex®-M0+ processors, developed by Microchip Technology. The technical parameters of SAMD21 are as follows:

1. Processor: 32-bit ARM® Cortex®-M0+, with a maximum operating frequency of 48MHz and up to 2.46 Coremark per MHz.
2. Memory: Flash memory capacity ranges from 32KB to 256KB, and SRAM capacity ranges from 4KB to 32KB.
3. Power management: Supports multiple low-power modes, such as idle and standby modes, with a minimum power consumption of 3.5μA/MHz.
4. Peripherals: It has rich intelligent and flexible peripherals, such as direct memory access controller (DMAC), event system, timer/counter (TC/TCC), real-time clock (RTC), watchdog timer ( WDT), CRC-32 generator, Universal Serial Bus (USB) 2.0 interface, serial communication interface (SERCOM), Inter-IC Sound (I2S) interface, analog-to-digital converter (ADC/DAC), analog comparator ( AC) and Peripheral Touch Controller (PTC).
5. Packaging: Supports a variety of packaging forms, ranging from 32-pin to 64-pin, including TQFP, QFN, UFBGA and WLCSP.
6. Standard: Complies with AEC-Q100 Grade 1 automotive grade standard, operating temperature range is -40°C to +125°C.

Insert image description here

MicroPython's SAMD21 clock and time refers to the process of using the MicroPython language for clock and time management on the SAMD21 microcontroller.

main feature:

Clock sources and dividers: The SAMD21 microcontroller provides a variety of clock sources and dividers for generating clock signals of different frequencies. Developers can configure and control the clock source and frequency divider through the MicroPython language to meet the clock requirements of different applications.
Precise Time Measurement: The SAMD21 microcontroller has a high-precision clock module for precise time measurement. Through the time function provided by the MicroPython language, developers can obtain the current time, calculation time intervals, etc., to achieve precise control and management of time.
Low-power clock mode: The SAMD21 microcontroller supports a low-power clock mode and can be used in scenarios where energy saving is required. By configuring and controlling the clock module, low-power clock management can be achieved and battery life can be extended.

Application scenarios:

Real-time clock (RTC) application: The SAMD21 microcontroller has a built-in real-time clock (RTC) module to provide persistent time recording and timing functions. Through the MicroPython language, developers can configure the RTC module to implement real-time clock applications, such as timestamp recording, scheduled tasks, etc.
Timers and timer applications: The timer and timer modules of the SAMD21 microcontroller can be used to implement various timing and timing functions. Through the MicroPython language, developers can configure and control timers and timers to implement applications such as timing trigger events and measuring time intervals.
Low-power applications: The SAMD21 microcontroller's low-power clock mode is suitable for applications that require long running times and are sensitive to energy consumption. Through the MicroPython language, developers can configure and manage low-power clock modes to implement low-power applications, such as IoT devices, sensor nodes, etc.

Precautions:

Clock configuration and initialization: When using the clock function of SAMD21, correct clock configuration and initialization are required. Depending on the specific application needs, select the appropriate clock source and divider and ensure proper initialization procedures.
Clock Accuracy and Stability: The clock accuracy and stability of the SAMD21 microcontroller are very important for time management. Developers need to pay attention to selecting an appropriate clock source and perform reasonable calibration and verification to ensure the accuracy and stability of the clock.
Clock module conflict: The clock module of the SAMD21 microcontroller may conflict with other peripheral modules. When configuring the clock, care must be taken to avoid conflicts with other functional modules to ensure the normal operation of each module.

To sum up, MicroPython's SAMD21 clock and time management utilizes the rich clock module of the SAMD21 microcontroller and the support of the MicroPython language to achieve flexible configuration and precise management of clock and time. Suitable for scenarios such as real-time clock applications, timers and timer applications, and low-power applications. When using the clock and time functions, you need to pay attention to issues such as clock configuration and initialization, clock accuracy and stability, and clock module conflicts to ensure the accuracy and reliability of the clock and time.

Insert image description here

In MicroPython, we can use the clock and time functions of the SAMD21 microcontroller to achieve precise time control. The following are several practical application reference code examples:

Case 1: Use machine.Pin() to set the pin to input mode

import machine

pin = machine.Pin(2, machine.Pin.IN)  # 设置引脚2为输入模式

Key interpretation: This program uses the machine.Pin() function to create a pin object, and then sets the pin to input mode through the Pin.IN parameter. In this example, we set pin 2 to input mode so that we can read external signals.

Case 2: Use timer.delay() to implement delay

import time

time.sleep(2)  # 延迟2秒
print("延迟结束")

Key interpretation: This program uses Python’s built-in time.sleep() function to implement delay, and the parameter is the number of seconds of delay. In this example, the program will pause for 2 seconds before continuing.

Case 3: Use machine.RTC() to get the current time

import machine

rtc = machine.RTC()
print("当前时间:", rtc.datetime())

Key interpretation: This program uses the machine.RTC() function to create a real-time clock object, and then obtains the current time through the datetime() method and prints it out.

Case 4: Use timer.Timer() to implement a timer

import machine
from machine import Pin, Timer

def task():
    print("任务执行")

pin = Pin(2, Pin.OUT)  # 设置引脚2为输出模式
timer = Timer(-1)  # 创建一个定时器,初始值为-1,表示立即执行

timer.init(period=1000, mode=Timer.PERIODIC, callback=task)  # 初始化定时器,周期为1000毫秒(1秒),模式为周期性,回调函数为task

Key interpretation: This program uses the Pin and Timer classes in the machine module to implement the timer function. First, we set pin 2 to output mode, then create a timer object, specify the period as 1000 milliseconds (1 second), and set the callback function as task. When the timer reaches the set period, the callback function task will be automatically executed.

Case 5: Get the current time

import machine  
import utime  
  
# 获取当前时间  
current_time = utime.localtime()  
print("当前时间:", current_time)

Key points to interpret:

First, the machine and utime modules are imported. The machine module contains many hardware-related functions, while the utime module provides time-related functions.
Use the utime.localtime() function to get the current time and store it in the current_time variable.
Output the current time to the serial port through the print statement.

Case 6: Set RTC time

import machine  
import utime  
  
# 初始化RTC模块  
rtc = machine.RTC()  
  
# 设置RTC时间  
rtc.init((2023, 7, 5, 10, 0, 0, 0, 367))  
  
# 获取并打印当前RTC时间  
current_rtc_time = rtc.now()  
print("当前RTC时间:", current_rtc_time)

Key points to interpret:

First, the machine and utime modules are imported.
Use machine.RTC() to initialize the RTC module.
Use the rtc.init() function to set the RTC time to 10:00:00 on July 5, 2023. In this tuple, the first four parameters represent the year, month, day, and day of the week respectively, and the following parameters are the hours, minutes, seconds, and nanoseconds. The last parameter is the daylight saving time flag, which is set to 367 to enable daylight saving time.
Use rtc.now() to get the current RTC time and store it in the current_rtc_time variable.
Output the current RTC time to the serial port through the print statement.

Case 7: Using timer interrupt

import machine  
import utime  
  
# 设置定时器中断回调函数  
def timer_callback():  
    print("定时器中断触发")  
  
# 初始化定时器并设置中断回调函数  
timer = machine.Timer(2)  # Timer2  
timer.init(period=1000000, mode=machine.Timer.IMMEDIATE, callback=timer_callback)  
timer.start()  # 启动定时器  
  
# 主循环中加入延时以观察定时器中断的触发情况  
while True:  
    utime.sleep(1)  # 延迟1秒,观察定时器中断触发的结果

Key points to interpret:

The machine and utime modules are imported.
A callback function named timer_callback is defined, which is called when the timer is interrupted and outputs a message to the serial port.
Use machine.Timer(2) to initialize timer 2, set the period to 1 second (1000000 microseconds), the mode to trigger immediately (machine.Timer.IMMEDIATE), and specify the callback function timer_callback.
Use timer.start() to start the timer.
Use utime.sleep(1) in the main loop to delay in order to observe the result of the timer interrupt triggering. The delay here is 1 second. If the timer interrupt is triggered correctly, a message will be printed to the serial port every second.

Case 8: Use RTC module to set and obtain date and time

from machine import RTC

rtc = RTC() # 创建RTC对象
rtc.datetime((2023, 4, 6, 4, 11, 54, 3, 0)) # 设置RTC日期和时间
print(rtc.datetime()) # 获取RTC日期和时间,返回一个元组

This case uses the RTC module, which can create and control real-time clock objects. The RTC module has no parameters. The RTC object has a datetime method, which can accept a tuple containing year, month, day, week, hour, minute, second, and microsecond to set the RTC date and time. You can also call the datetime method without parameters to obtain the RTC date and time.

The RTC module needs to be connected to a 32kHz crystal oscillator to work properly. If no crystal is connected, the RTC date and time may be inaccurate or unstable.

The RTC module uses January 1, 2000 as the epoch start date, consistent with the time module.

Case 9: Delay and timing using time module

import time

start = time.ticks_ms() # 获取当前的毫秒计数器
time.sleep(1) # 延迟1秒
end = time.ticks_ms() # 获取当前的毫秒计数器
delta = time.ticks_diff(end, start) # 计算两个计数器之间的差值
print(delta) # 打印差值,应该接近1000

This case uses the time module, which provides functions to obtain the current time and date, measure time intervals and delays. The time module has the following functions:

time.sleep(seconds): Delay the specified time in seconds, which can be an integer or a floating point number.
time.sleep_ms(ms): Delay the specified time in milliseconds, must be an integer.
time.sleep_us(us): Delay the specified time in microseconds, must be an integer.
time.ticks_ms(): Returns an incrementing millisecond counter that wraps around after a certain value. The value is not explicitly exposed, but is guaranteed to be a power of 2.
time.ticks_us(): Returns an incrementing microsecond counter that wraps around after a certain value. The value is not explicitly exposed, but is guaranteed to be a power of 2.
time.ticks_diff(ticks1, ticks2): Measures the difference between two counters as a possibly wrapped signed value. The argument order is the same as for the subtraction operator.

Case 10: Using the ntptime module to synchronize network time

import ntptime
import network

sta = network.WLAN(network.STA_IF) # 创建一个STA对象
sta.active(True) # 激活STA对象
sta.connect('ssid', 'password') # 连接到指定的WiFi网络

ntptime.settime() # 同步网络时间到本地RTC
print(ntptime.time()) # 打印网络时间,以秒为单位

This case uses the ntptime module, which can obtain the current UTC time from the network server and set it to the local RTC. The ntptime module has the following functions:
ntptime.settime(): Gets the UTC time from the default or specified server and sets it to the local RTC. If no server is specified, pool.ntp.org is used as the default server.
ntptime.time(): Gets the UTC time from the default or specified server and returns the value in seconds. If no server is specified, pool.ntp.org is used as the default server.
ntptime.host(server): Set the server name or IP address from which UTC time is to be obtained.

Please note that the above cases are only for expanding ideas and may contain errors or inapplicability. Different hardware platforms, usage scenarios and MicroPython versions may lead to different usage methods. In actual programming, you need to adjust it according to your hardware configuration and specific needs, and conduct multiple actual tests. It is important to ensure that the hardware is connected correctly and to understand the specifications and characteristics of the sensors and devices used.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_41659040/article/details/133433395