MicroPython ESP32 RTC功能使用介绍

MicroPython ESP32 RTC功能使用介绍


  • Micropython esp32官方文档介绍:https://docs.micropython.org/en/latest/esp32/quickref.html#real-time-clock-rtc
  • 本示例基于Thonny平台开发。
  • 使用ESP32S3开发板测试。
  • ✨所使用的固件版本:MicroPython v1.19.1
RTC属于machine模块中的类

查询RTC相关内置的功能模块:

>>> from machine import RTC
>>> help(RTC)
object <class 'RTC'> is of type type
  init -- <function>
  datetime -- <function>
  memory -- <function>
  • RTC.init([year, month, day, week, hour, minute, second, microsecond])功能和rtc.datetime([year, month, day, week, hour, minute, second, microsecond])一样。
MicroPython v1.19.1 on 2022-09-23; YD-ESP32S3-N16R8 with ESP32S3R8

Type "help()" for more information.

>>> from machine import RTC
>>> rtc = RTC()
>>> rtc.init((2023, 11, 6, 1, 12, 12, 15, 12))
>>> rtc.datetime()
(2023, 11, 6, 0, 12, 12, 25, 119353)
>>> 
  • rtc.datetime([year, month, day, week, hour, minute, second, microsecond]):该方法用于设置或获取RTC时间。不带参数时,用于获取时间,带参数则是设置时间;设置时间时,参数week不参与设置,microsecond参数保留,暂未使用,默认是0。
  • year - 年,int类型。
    month - 月,int类型,范围[1 ~ 12]。
    day - 日,int类型,范围[1 ~ 31]。
    week - 星期,int类型,范围[0 ~ 6],其中0表示周日,[1 ~ 6]分别表示周一到周六;设置时间时,该参数不起作用,保留;获取时间时该参数有效。
    hour - 时,int类型,范围[0 ~ 23]。
    minute - 分,int类型,范围[0 ~ 59]。
    second - 秒,int类型,范围[0 ~ 59]。
    microsecond - 微秒,int类型,保留参数,暂未使用,设置时间时该参数写0即可。
  • rtc.memory(arry):形参为数组,可用于存储一个字符串。
import machine

rtc = machine.RTC()

# 获取RTC存储器的字节数组对象
data = 'hello'
rtc.memory(data)

# 获取RTC存储器的字节数组对象
print(rtc.memory())
>>> %Run -c $EDITOR_CONTENT
b'hello'
>>> 

测试例程

import machine
import time
rtc = machine.RTC()

# 设置RTC时间
# rtc.datetime((2023, 11, 6, 1, 12, 12, 15, 12))  # (,,,星期,,,,毫秒部分),设置星期无效
rtc.init((2023, 11, 6, 1, 12, 12, 15, 12))
# 定义星期数组
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

# rtc.datetime() # get date and time
# 循环获取RTC时间并打印
while True:
    
    year, month, day,weekday, hour, minute, second,  yearday = rtc.datetime()
    # 获取星期对应的数组成员
    weekday_name = weekdays[weekday]
    print("当前时间:{}-{}-{} {}:{}:{} Week:{}".format(year, month, day, hour, minute, second,weekday_name))
    # 读取RTC内存的值
    memory_value = rtc.memory()
    # 将内存值转换为字符串
    memory_str = memory_value.decode('utf-8')

    # 打印内存值
    print("RTC Memory:", memory_str)
    freq = machine.freq()  #查询运行频率
    print("freq:", freq)
    machine.freq(240000000)  #查询运行频率
    time.sleep(1)
  • 测试中,实际读到的rtc.memory()为空的。
    MicroPython ESP32 RTC功能使用介绍_第1张图片

你可能感兴趣的:(#,MicroPython,for,ESP32,MicroPython,esp32)