[Diao Ye Learns Programming] MicroPython Manual WiPy Real-Time Clock (RTC)

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
WiPy is a MicroPython-based wireless microcontroller module that provides a complete hardware and software solution designed to simplify the development and deployment of Internet of Things (IoT) devices.

1. Microcontroller module: WiPy is a microcomputer module that integrates a processor, memory, wireless communication module and other necessary components. It is designed to provide a compact, low-power hardware platform capable of running high-level programming languages ​​​​such as MicroPython and having the ability to connect to the Internet and other devices.
2. MicroPython: MicroPython is a streamlined version of the Python programming language, specially developed for embedded systems and microcontroller design. It provides the core functions and syntax of the Python language, allowing developers to use familiar Python syntax for hardware control and IoT application development. As the operating environment of MicroPython, WiPy can directly interpret and execute MicroPython code.
3. Internet of Things (IoT): The Internet of Things refers to a network that connects various physical devices (such as sensors, actuators, embedded systems, etc.) through the Internet to achieve intelligence and interconnection. As a wireless microcontroller module, WiPy has wireless communication capabilities and can be connected to other devices and cloud platforms in the Internet of Things to achieve remote control and data exchange.
4. Wireless communication module: WiPy has one or more built-in wireless communication modules, common ones including Wi-Fi, Bluetooth, LoRa, etc. These wireless communication modules enable WiPy to communicate with other devices through wireless networks to achieve data transmission, remote control, cloud connection and other functions. Developers can choose appropriate wireless communication modules based on specific needs.
5. Development and deployment: WiPy provides a set of convenient development tools and development environment, allowing developers to quickly develop, debug and test applications. Once developed, WiPy can be deployed directly into actual IoT devices to communicate and interact with other devices. WiPy's compact design and low power consumption make it ideal for deployment in embedded systems and IoT devices.

Insert image description here
MicroPython's WiPy Real-Time Clock (RTC) is a device used to provide precise time and date information.

main feature:

Time and date tracking: WiPy RTC can track the current time and date information, including year, month, day, hour, minute, second, etc. It provides a high-precision clock function that can accurately record time and date changes.
Battery backup: WiPy RTC usually has battery backup function, that is, when the main power supply is cut off, the RTC can still continue to work and maintain the accuracy of time and date. This prevents the loss of time and date information and ensures the time continuity of the system.
Common function support: WiPy RTC usually provides commonly used functions, such as alarm clock function, timer function, etc. These functions can be configured and used according to application needs, providing more time management and timing functions.

Application scenarios:

Real-time data recording: WiPy RTC can be applied to scenarios that require recording real-time data, such as weather stations, data collection equipment, etc. It can provide accurate timestamps to mark the time of data collection, ensuring data accuracy and traceability.
Time scheduling and control: For applications that need to execute tasks or control events according to time plans, such as timed switches, timed task scheduling, etc., WiPy RTC can provide precise time information for time triggering and time control to achieve precise time scheduling.
Logging and timestamps: WiPy RTC can be used to generate log records and timestamps for event tracking, troubleshooting and other applications. By recording the time when an event occurred, it can help analyze and locate the problem, and sort and compare the sequence of events.

Precautions:

Initialization and calibration: Before using WiPy RTC, initialization and calibration operations are required to ensure the accuracy of time and date. This can usually be configured by setting the initial time and date, calibrating the clock frequency, etc.
Battery maintenance: If WiPy RTC has a battery backup function, you need to pay attention to regular maintenance of the battery status to ensure the reliability and durability of the backup power supply. If the battery is low or damaged, time and date information may be lost or inaccurate.
Time zone and daylight saving time: In applications, the impact of time zone and daylight saving time needs to be considered. WiPy RTC usually provides relevant configuration options that can be set and adjusted according to actual needs to ensure time accuracy and consistency.

To summarize, MicroPython’s WiPy Real-Time Clock (RTC) is a device that provides precise time and date information. It has features like time and date tracking, battery backup, and support for frequently used functions. WiPy RTC is suitable for application scenarios such as real-time data recording, time scheduling and control, logging and timestamps. When using WiPy RTC, you need to pay attention to initialization and calibration, battery maintenance, and time zone and daylight saving time to ensure the accuracy and reliability of the time.

Insert image description here

Case 1: Use MicroPython to read RTC time

from machine import RTC
import time

rtc = RTC()

while True:
    # 读取RTC时间
    current_time = rtc.datetime()
    print("Current time: {0}".format(current_time))
    time.sleep(1)  # 延时1秒

Case 2: Set RTC time using MicroPython

from machine import RTC
import time

rtc = RTC()

while True:
    # 设置RTC时间为当前时间加1天
    rtc.datetime((datetime.datetime.now() + datetime.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S'))
    print("Set RTC time to: {0}".format(rtc.datetime()))
    time.sleep(1)  # 延时1秒

Case 3: Use MicroPython to check whether the specified RTC time point is reached

from machine import RTC
import time

rtc = RTC()
target_time = rtc.datetime((datetime.datetime.now() + datetime.timedelta(hours=1)).strftime('%Y-%m-%d %H:%M:%S'))

while True:
    # 获取当前时间
    current_time = rtc.datetime()
    print("Current time: {0}".format(current_time))
    # 检查是否到达指定的RTC时间点
    if current_time >= target_time:
        print("Target time has been reached!")
        break
    time.sleep(1)  # 延时1秒

Case 4: Basic use

from machine import RTC  
  
# 初始化RTC模块  
rtc = RTC()  
  
# 获取当前时间  
current_time = rtc.now()  
print("当前时间:", current_time)

Case 5: Set RTC time

from machine import RTC  
  
# 初始化RTC模块  
rtc = RTC()  
  
# 设置RTC时间为当前时间加上10秒  
set_time = rtc.now() + (10, 0)  
rtc.set(set_time)  
  
# 获取设置后的时间  
current_time = rtc.now()  
print("设置后的时间:", current_time)

Case 6: Get the time in real time and output it to the serial port

from machine import RTC, UART  
import utime  
  
# 初始化RTC模块  
rtc = RTC()  
  
# 初始化串口模块  
uart = UART(115200)  
  
# 循环输出当前时间到串口  
while True:  
    current_time = rtc.now()  
    uart.write("当前时间:{}\n".format(current_time))  
    utime.sleep(1)  # 休眠1秒

These examples demonstrate respectively obtaining the current time, setting the RTC time and obtaining the time in real time and outputting it to the serial port. It should be noted that when setting the RTC time, the time format needs to be converted into a tuple form of (year, month, day, hour, minute, second). At the same time, when obtaining time in real time and outputting it to the serial port, you need to use the utime.sleep() function to control the frequency of output time.

Case 7: Use RTC to set and get the current date and time, and print it out. Reference code example:

# 导入必要的模块
from machine import RTC
import time

# 初始化RTC对象
rtc = RTC()

# 设置当前的日期和时间,格式为(年, 月, 日, 星期, 时, 分, 秒, 微秒)
rtc.datetime((2023, 4, 6, 4, 11, 54, 3, 0)) # 设置为2023年4月6日星期四11:54:03

# 获取当前的日期和时间,并打印出来
print(rtc.datetime()) # 打印为(2023, 4, 6, 4, 11, 54, 3, 0)

Case 8: Use RTC to set a scheduled alarm clock. When the alarm clock sounds, reference code example for controlling a buzzer to sound:

# 导入必要的模块
from machine import RTC, Pin
import time

# 初始化RTC对象
rtc = RTC()

# 初始化Pin对象,连接到一个蜂鸣器(假设为P10)
buzzer = Pin('P10', mode=Pin.OUT)

# 定义一个闹钟处理函数,用于控制蜂鸣器发出声音
def alarm_handler(alarm):
    buzzer.value(1) # 打开蜂鸣器
    time.sleep(1) # 等待1秒
    buzzer.value(0) # 关闭蜂鸣器

# 设置一个闹钟,在5秒后触发,并执行闹钟处理函数
rtc.alarm(RTC.ALARM0, 5000)
rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler)

# 等待闹钟触发
while True:
    pass

Case 9: Use RTC to synchronize network time and save it to an SD card. Reference code case:

# 导入必要的模块
from machine import RTC, SPI, Pin
import network
import ntptime
import os
import sdcard # 从 https://github.com/micropython/micropython/tree/master/drivers/sdcard 下载

# 初始化RTC对象
rtc = RTC()

# 连接到WLAN网络(假设为your_ssid和your_password)
wlan = network.WLAN(mode=network.WLAN.STA)
wlan.connect('your_ssid', auth=(network.WLAN.WPA2, 'your_password'))
while not wlan.isconnected():
    time.sleep_ms(50)

# 同步网络时间,并设置到RTC上
ntptime.settime()
print(rtc.datetime()) # 打印同步后的日期和时间

# 初始化SPI总线和SD卡对象
spi = SPI(0, mode=SPI.MASTER, baudrate=1000000, polarity=0, phase=0)
sd = sdcard.SDCard(spi, Pin('P10')) # SD卡的CS引脚连接到P10

# 挂载SD卡到文件系统
os.mount(sd, '/sd')

# 切换到SD卡目录
os.chdir('/sd')

# 创建一个新文件,并写入当前的日期和时间
f = open('time.txt', 'w')
f.write(str(rtc.datetime()))
f.close()

# 卸载SD卡
os.umount('/sd')

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/133412940