├── .mpyproject.json ├── .vscode └── settings.json ├── README.md ├── boot.py ├── config.py ├── main.py ├── mqttConnect.py ├── test.py └── utils.py /.mpyproject.json: -------------------------------------------------------------------------------- 1 | //This is an automatically generated configuration file. 2 | //Please do not modify or delete it!!! 3 | { 4 | "projectName":"MicroPy_test" 5 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.autoComplete.extraPaths": [ 3 | "c:/Users/WhaleFall/.vscode/extensions/rt-thread.rt-thread-micropython-1.0.11/microExamples/code-completion" 4 | ], 5 | "python.linting.pylintArgs": [ 6 | "--init-hook", 7 | "import sys; sys.path.append('c:/Users/WhaleFall/.vscode/extensions/rt-thread.rt-thread-micropython-1.0.11/microExamples/code-completion')" 8 | ], 9 | "files.associations": { 10 | ".mpyproject.json": "jsonc" 11 | }, 12 | "MicroPython.executeButton": [ 13 | { 14 | "text": "▶", 15 | "tooltip": "运行", 16 | "alignment": "left", 17 | "command": "extension.executeFile", 18 | "priority": 3.5 19 | } 20 | ], 21 | "MicroPython.syncButton": [ 22 | { 23 | "text": "$(sync)", 24 | "tooltip": "同步", 25 | "alignment": "left", 26 | "command": "extension.execute", 27 | "priority": 4 28 | } 29 | ], 30 | "python.analysis.extraPaths": [ 31 | "c:/Users/WhaleFall/.vscode/extensions/rt-thread.rt-thread-micropython-1.0.11/microExamples/code-completion" 32 | ] 33 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ESP8266 MicroPython 入门笔记 2 | 3 | ## 介绍 4 | 5 | 该项目基于 `MicroPython` 使用 `esp8266` 单片机制作,定时上传温湿度到 mqtt 服务器,检测到人体就启动蜂鸣器并推送mqtt,可以通过 mqtt 控制蜂鸣器和板载 ide 灯,查询是否存在人体。方便我出去时监控我的房间是否有父母进入。进入就推送到 mqtt 到我的手机。本项目采用 Asyncio 支持,可以多个任务运行在同一时间线上,不会堵塞,高效处理。 6 | 7 | ## 烧写镜像 8 | 9 | ```shell 10 | python -m esptool read_mac # 读取设备 11 | python -m esptool -p COM6 erase_flash # 擦除闪存 12 | python -m esptool --port COM6 --baud 460800 write_flash --flash_size=detect 0 esp8266-20220618-v1.19.1.bin # 烧录固件 13 | ``` 14 | 15 | ## MicroPython 连接 WIFI 16 | esp8266芯片的核心就是与wifi功能,对应使用micropython里面的network模块。 17 | 18 | wifi模块有两种模式: 19 | 20 | - STA_IF 也就是station站点模式,将本芯片作为客户端连接到已知的无线网络上 21 | - AP_IF 也就是AP/热点模式,将本芯片作为无线热点,等待其他客户端连接上来 22 | 23 | ### WIFI 热点创建 24 | ```python 25 | import network 26 | ap = network.WLAN(network.AP_IF) # 指定用ap模式 27 | ap.active(True) # 启用wifi前需要先激活接口 28 | ap.config(essid="EUROPA-AP") # 设置热点名称 29 | ap.config(authmode=3, password='1234567890') # 设置认证模式与密码 30 | ``` 31 | config 参数: 32 | mac, MAC地址 33 | essid, 热点名称 34 | channel, wifi通道 35 | hidden, 是否隐藏 36 | authmode, 认证模式 37 | 0 – 无密码 38 | 1 – WEP认证 39 | 2 – WPA-PSK 40 | 3 – WPA2-PSK 41 | 4 – WPA/WPA2-PSK 42 | password, 连接密码 43 | dhcp_hostname, DHCP主机名 44 | 45 | > 使用AP热点模式时,esp8266芯片可提供的连接数量是有限的,最多支持4个客户端连接。 46 | 47 | ### 连接 WIFI 48 | ```python 49 | import network 50 | import utime 51 | 52 | sta_if = network.WLAN(network.STA_IF) # 配置wifi模式为station 53 | if not sta_if.isconnected(): # 判断有无连接 54 | print('connecting to network...') 55 | sta_if.active(True) # 激活wifi接口 56 | sta_if.connect('', '') # 连接现有wifi网络,需要替换为已知的热点名称和密码 57 | while not sta_if.isconnected(): 58 | utime.sleep(1) # 未连接上就等待一下,直到连接成功 59 | print('network config:', sta_if.ifconfig()) # 输出当前wifi网络给自己分配的网络参数 60 | # ('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8') 61 | ``` 62 | 63 | ### 连接网络 64 | 一旦wifi网络连接成功,那咱们就可以畅游网络,网络连接在micropython中主要是使用或封装socket模块来实现。 65 | 66 | 七层网络协议知道吧,socket模块应该是介于应用层和网络层+传输层中间的一个抽象封装,为上层应用层提供直接使用底层网络的能力。 67 | 68 | ## 上传文件 69 | ```shell 70 | ampy --port COM6 put test.txt 71 | ``` 72 | 73 | ```shell 74 | 用法: ampy [OPTIONS] COMMAND [ARGS]... 75 | 76 | ampy - Adafruit MicroPython工具 77 | 78 | Ampy是一个通过串行连接控制MicroPython板的工具。 79 | 使用ampy,你可以操作板子内部文件系统上的文件,甚至运行脚本。 80 | 甚至运行脚本。 81 | 82 | 选项。 83 | -p, --port PORT 连接板的串口名称。 可以选择 84 | 可以用AMPY_PORT环境变量指定。 [必需] -b, --baud 85 | 86 | -b, --baud BAUD 串行连接的波特率(默认为115200)。 87 | 可以选择用AMPY_BAUD环境变量来指定 88 | 变量指定。 89 | 90 | -d, --delay DELAY 进入RAW模式前的延迟时间,单位为秒(默认为0)。 91 | 可以选择用AMPY_DELAY环境变量来指定。 92 | 变量指定。 93 | 94 | --version 显示版本并退出。 95 | --help 显示此信息并退出。 96 | 97 | 命令。 98 | get 从板子上取回一个文件。 99 | ls 列出棋盘上一个目录的内容。 100 | mkdir 在板上创建一个目录。 101 | put 把一个文件或文件夹及其内容放在板上。 102 | reset 对板子进行软复位/重启。 103 | rm 从板上删除一个文件。 104 | rmdir 从板上强行删除一个文件夹及其所有子文件夹。 105 | run 运行一个脚本并打印其输出。 106 | 107 | 通过www.DeepL.com/Translator(免费版)翻译 108 | ``` -------------------------------------------------------------------------------- /boot.py: -------------------------------------------------------------------------------- 1 | # This file is executed on every boot (including wake-boot from deepsleep) 2 | #import esp 3 | # esp.osdebug(None) 4 | import uos 5 | import machine 6 | # uos.dupterm(None, 1) # disable REPL on UART(0) 7 | import gc 8 | # import webrepl 9 | # webrepl.start() 10 | gc.collect() 11 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | # config.py 2 | wifi_ssid = "HomeAP" 3 | wifi_passwd = "992829hws" 4 | 5 | # MQTT config 6 | blinker_tk = "335562d5d103" 7 | mserver = "broker-cn.emqx.io" 8 | port = 1883 9 | 10 | client_id = "mqttx_b6b02f34" # 可选 11 | user = None 12 | password = None 13 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # encoding=utf8 2 | # microPY main 3 | import config 4 | import time 5 | from utils import SingSong, connectWIFI, get_dht11, sync_ntp, HcSr501, reversePin 6 | from mqttConnect import MQTT 7 | from machine import Pin 8 | import dht 9 | 10 | try: 11 | import uasyncio 12 | except ImportError: 13 | import asyncio as uasyncio 14 | 15 | 16 | sound = SingSong(GPIO=15) # 蜂鸣器引脚 17 | 18 | led = Pin(2, Pin.OUT) # 板载 led 默认为高电平熄灭 19 | dh = Pin(4) # DH 温度传感器 20 | hc = HcSr501(GPIO=5) # Hc-sr 501 人体感应器 21 | 22 | 23 | # 初始化 MQTT 服务器 24 | mqtt = MQTT( 25 | server=config.mserver, 26 | port=config.port, 27 | client_id=config.client_id, 28 | user=config.user, 29 | password=config.password, 30 | ) 31 | 32 | 33 | def init(): 34 | """初始化操作,非异步""" 35 | 36 | # 循环连接 WIFI 设备 37 | while True: 38 | led.value(0) 39 | isWifi = connectWIFI(config.wifi_ssid, config.wifi_passwd) 40 | if isWifi: 41 | led.value(1) 42 | break 43 | else: 44 | led.value(1) 45 | time.sleep(1) 46 | 47 | if sync_ntp(): 48 | print("Sync Ntp Success!") 49 | 50 | 51 | def handle_msg(topic, msg): 52 | print(f"rec {topic}:{msg}") 53 | # 切换 板载 led 灯状态 54 | if "led" in msg: 55 | reversePin(led) 56 | 57 | # 控制蜂鸣器 58 | elif "sound" in msg: 59 | reversePin(sound.buzzer) 60 | 61 | # 获取人体感应器信息 62 | elif "hc" in msg: 63 | if hc.value == 1: 64 | msg = "somebody" 65 | else: 66 | msg = "nobody" 67 | 68 | mqtt.syncPubScribe(topic="/hyyhome/pub/hc/", msg=msg) 69 | 70 | # 测试信息 71 | elif "test" in msg: 72 | mqtt.syncPubScribe(topic="/hyyhome/pub/test/", msg="online!") 73 | 74 | 75 | async def asyncDht11(): 76 | """每5秒获取DHT11温度传感器数值,获取6次取平均数后上传mqtt""" 77 | wd_lst = [] 78 | sd_lst = [] 79 | while True: 80 | for _ in range(6): 81 | wd, sd = get_dht11(dh) 82 | wd_lst.append(wd) 83 | sd_lst.append(sd) 84 | print(f"{wd} {sd}") 85 | await uasyncio.sleep(5) 86 | # 计算平均值 87 | avg_wd = sum(wd_lst)/len(wd_lst) 88 | avg_sd = sum(sd_lst)/len(sd_lst) 89 | await mqtt.pubScribe("/hyyhome/pub/dht11/", msg='{"wd":%s,"sd":%s}' % (round(avg_wd, 1), round(avg_sd, 1))) 90 | wd_lst.clear() 91 | sd_lst.clear() 92 | 93 | 94 | async def asyncHc(): 95 | """监听人体感应器的信息""" 96 | save_v = 0 97 | while True: 98 | v = hc.value 99 | if v != save_v: 100 | if v == 1: 101 | msg = "somebody" 102 | else: 103 | msg = "nobody" 104 | save_v = v 105 | print(f"[HC] {msg}") 106 | await mqtt.pubScribe(topic="/hyyhome/pub/hc/", msg=msg) 107 | sound.start() 108 | await uasyncio.sleep(2) 109 | sound.stop() 110 | 111 | await uasyncio.sleep(1) 112 | 113 | 114 | async def main(): 115 | """main() 异步执行""" 116 | print("Asyncio start run!") 117 | # uasyncio.gather( 118 | # *( 119 | # # 监听 /hyyhome/fetch/ 下的所有信息 120 | # mqtt.subScribe(sub="/hyyhome/fetch/#", cb=handle_msg) 121 | # ) 122 | # ) 123 | # await mqtt.subScribe(sub="/hyyhome/fetch/#", cb=handle_msg) 124 | # await print("test...") 125 | 126 | # 打包成一个 task 才可以运行 127 | uasyncio.create_task(asyncDht11()) 128 | uasyncio.create_task(asyncHc()) 129 | # await 等待这个 task 运行完成,起到 while True 的作用 130 | await uasyncio.create_task(mqtt.subScribe(sub="/hyyhome/sub/#", cb=handle_msg)) 131 | 132 | 133 | if __name__ == "__main__": 134 | init() 135 | uasyncio.run(main()) 136 | -------------------------------------------------------------------------------- /mqttConnect.py: -------------------------------------------------------------------------------- 1 | # mqttConnect 2 | import gc 3 | from umqtt.simple import MQTTClient 4 | import urequests 5 | from utils import connectWIFI, wifi 6 | import config 7 | import utime 8 | # 兼容性导入 9 | try: 10 | import uasyncio 11 | except ImportError: 12 | import asyncio as uasyncio 13 | 14 | # 启动垃圾回收器 15 | gc.collect() 16 | 17 | 18 | # mqtts://broker.diandeng.tech:1883 电灯科技 19 | 20 | ### Config #### 21 | blinker_tk = "335562d5d103" 22 | mserver = "broker-cn.emqx.io" 23 | port = "1883" 24 | 25 | client_id = "mqttx_b6b02f04" # 可选 26 | user = None 27 | password = None 28 | ############### 29 | 30 | client: MQTTClient = None 31 | 32 | 33 | def online() -> bool: 34 | """点灯科技设备上线,获取 mqtt 协议配置""" 35 | global client_id, mserver, port, user, password 36 | 37 | url = "https://iot.diandeng.tech/api/v1/user/device/diy/auth?authKey=%s&protocol=mqtt" % blinker_tk 38 | resp = urequests.get(url).json() 39 | if resp.get("message") != 1000: 40 | return False 41 | mserver = resp['detail']['host'].replace("mqtt://", "") 42 | port = int(resp['detail']['port']) 43 | user = resp['detail']['iotId'] 44 | password = resp['detail']['iotToken'] 45 | client_id = resp['detail']['deviceName'] 46 | 47 | print(''' 48 | ############# 49 | # MQTT: %s:%s 50 | # ClientID: %s 51 | # User: %s 52 | # Pwd: %s 53 | # ########### 54 | ''' % (mserver, port, client_id, user, password) 55 | ) 56 | 57 | global client 58 | 59 | client = MQTTClient( 60 | server=mserver, 61 | port=int(port), 62 | 63 | client_id=client_id, 64 | user=user, 65 | password=password, 66 | ) 67 | 68 | 69 | class MQTT(object): 70 | """操作 MQTT 服务""" 71 | 72 | def __init__( 73 | self, 74 | server: str = mserver, 75 | port=int(port), 76 | 77 | client_id: str = client_id, 78 | user: str = user, 79 | password: str = password, 80 | ) -> None: 81 | global client 82 | 83 | client = MQTTClient( 84 | server=server, 85 | port=int(port), 86 | 87 | client_id=client_id, 88 | user=user, 89 | password=password, 90 | ) 91 | 92 | self.client = client 93 | self.content = '{"timestamp":%s,"data":%s}' 94 | 95 | async def subScribe(self, cb: function, sub="hyy9420"): 96 | """订阅主题并保持连接,cb 为回调函数""" 97 | a = 0 98 | isNeedConnect = True # 是否需要连接 99 | 100 | while True: 101 | try: 102 | if isNeedConnect: 103 | print("connecting mqtt......") 104 | self.client.connect() 105 | isNeedConnect = False 106 | 107 | a += 1 108 | print(f"Keepconnect {a}") 109 | self.client.set_callback(cb) # 设置回调 110 | self.client.subscribe(b'%s' % sub) # 设置订阅 111 | self.client.check_msg() # 非堵塞检查 112 | except Exception as e: 113 | # 如果连接发生错误就重连 114 | print(f"[ERROR] Reconnect Now!{e}") 115 | if not wifi.isconnected(): 116 | print("Network disconnect...") 117 | connectWIFI(config.wifi_ssid, config.wifi_passwd) 118 | # 设置重连 119 | isNeedConnect = True 120 | 121 | await uasyncio.sleep(1) # 异步休息 122 | 123 | async def pubScribe(self, topic: str, msg: str, retries=3, *args, **kw): 124 | """发布连接""" 125 | content = self.content % ( 126 | utime.mktime(utime.localtime())+946656000, msg) 127 | 128 | for _ in range(retries): 129 | try: 130 | print(f"send {topic} {content}") 131 | self.client.publish(topic, content, *args, **kw) 132 | return 133 | except Exception as e: 134 | print(f"[Error]send err:{e}") 135 | await uasyncio.sleep(1) 136 | continue 137 | 138 | def syncPubScribe(self, topic: str, msg: str, retries=3, *args, **kw): 139 | """同步发布连接""" 140 | content = self.content % ( 141 | utime.mktime(utime.localtime())+946656000, msg) 142 | 143 | for _ in range(retries): 144 | try: 145 | print(f"send {topic} {content}") 146 | self.client.publish(topic, content, *args, **kw) 147 | return 148 | except Exception as e: 149 | print(f"[Error]send err:{e}") 150 | continue 151 | 152 | async def ping(self): 153 | """保持ping链接""" 154 | while True: 155 | print("ping!") 156 | # self.client.ping() 157 | # self.client.publish("www9420", ="111") 158 | self.pubScribe("www9420", "111") 159 | await uasyncio.sleep(1) 160 | 161 | 162 | def __sub_cb(topic, msg): # 回调函数,收到服务器消息后会调用这个函数 163 | print(topic, msg) 164 | if "hello" in msg: 165 | client.publish("www9420", msg=b'hello esp8266') 166 | 167 | 168 | async def main(): 169 | mqtt = MQTT(mserver, port, client_id) 170 | # uasyncio.create_task(mqtt.keepConnect(sub_cb)) 171 | # uasyncio.create_task(mqtt.pubConnect("hyy9999", "startstart!!!")) 172 | await uasyncio.gather( 173 | *( 174 | mqtt.keepConnect(__sub_cb), 175 | mqtt.pubConnect("hyy9999", "startstart!!!"), 176 | mqtt.ping() 177 | ) 178 | ) 179 | 180 | 181 | if __name__ == "__main__": 182 | wifi.disconnect() 183 | print("wifi disconnect!") 184 | mqtt = MQTT() 185 | uasyncio.run(mqtt.subScribe(__sub_cb)) 186 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | # 测试文件 2 | 3 | from machine import Pin 4 | import utime 5 | from machine import Pin 6 | from utils import SingSong 7 | 8 | 9 | def test1(): 10 | GPIO = 5 # 蜂鸣器管脚定义 11 | buzzer = Pin(GPIO, Pin.OUT) # 设置蜂鸣器GPIO口为输入模式 12 | 13 | while True: 14 | buzzer.value(1) # 设置为高电平 15 | utime.sleep(0.3) # 延时 16 | buzzer.value(0) # 设置为低电平 17 | utime.sleep(1) # 延时 18 | 19 | 20 | def test2(): 21 | from machine import Pin, PWM 22 | import utime 23 | 24 | # 定义音调频率 25 | tones = {'1': 262, '2': 294, '3': 330, '4': 349, 26 | '5': 392, '6': 440, '7': 494, '-': 0} 27 | # 定义小星星旋律 28 | melody = "1155665-4433221-5544332-5544332-1155665-4433221" 29 | 30 | # 设置D7(GPIO 13)口为IO输出,然后通过PWM控制无缘蜂鸣器发声 31 | beeper = PWM(Pin(5, Pin.OUT), freq=0, duty=1000) 32 | 33 | for tone in melody: 34 | freq = tones[tone] 35 | if freq: 36 | beeper.init(duty=1000, freq=freq) # 调整PWM的频率,使其发出指定的音调 37 | else: 38 | beeper.duty(0) # 空拍时一样不上电 39 | # 停顿一下 (四四拍每秒两个音,每个音节中间稍微停顿一下) 40 | utime.sleep_ms(400) 41 | beeper.duty(0) # 设备占空比为0,即不上电 42 | utime.sleep_ms(100) 43 | 44 | beeper.deinit() # 释放PWM 45 | 46 | 47 | def test__(): 48 | p5 = Pin(5, Pin.IN) 49 | sound = SingSong(GPIO=15) # 蜂鸣器引脚 50 | sound.stop() 51 | p5.value(0) 52 | while True: 53 | print(p5.value(), end="") 54 | # # 人进入感应访问就输出高电平 55 | if (p5.value() == 1): 56 | sound.start() 57 | else: 58 | sound.stop() 59 | utime.sleep_ms(500) 60 | 61 | 62 | test__() 63 | 64 | if __name__ == "__main__": 65 | # test1() 66 | # sound = SingSong(GPIO=15) # 蜂鸣器引脚 67 | # sound.play("1-1-1", loop=True) 68 | pass 69 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | # encoding=utf8 2 | # utils/ConnectWIFI.py 3 | import network 4 | import utime 5 | from machine import Pin 6 | from utime import sleep 7 | try: 8 | import uasyncio 9 | except ImportError: 10 | import asyncio as uasyncio 11 | 12 | 13 | import dht 14 | import ntptime 15 | 16 | ### config #### 17 | wifi_ssid = "HomeAP" 18 | wifi_passwd = "992829hws" 19 | ############### 20 | 21 | wifi = network.WLAN(network.STA_IF) # 配置wifi模式为station 22 | 23 | 24 | # 重试函数,异常处理:(带参数的修饰器) 25 | def handle_error(tries=3): 26 | def deco(func): 27 | def wrapper(*arg, **kw): 28 | # 写逻辑 29 | for _ in range(tries): 30 | try: 31 | return func(*arg, **kw) 32 | except Exception as e: 33 | continue 34 | return False 35 | return wrapper 36 | return deco 37 | 38 | 39 | def reversePin(pin: Pin): 40 | """反转 Pin 高低电平状态""" 41 | v = pin.value() 42 | if v: 43 | pin.value(0) 44 | else: 45 | pin.value(1) 46 | 47 | 48 | def connectWIFI(wifi_ssid: str, wifi_passwd: str, timeout: int = 15) -> bool: 49 | """连接 WIFI""" 50 | global wifi 51 | 52 | if not wifi.isconnected(): 53 | print("Connecting to a WIFI network") 54 | wifi.active(True) 55 | wifi.connect(wifi_ssid, wifi_passwd) 56 | i = 0 57 | print("Connection ing", end="") 58 | while not wifi.isconnected(): 59 | utime.sleep(1) 60 | i += 1 61 | if i >= timeout: 62 | print("\nConnection timeout! Please check you SSID or PWD") 63 | return False 64 | print(".", end="") 65 | 66 | print("Connection successful!") 67 | print("network config:", wifi.ifconfig()) 68 | return True 69 | # ('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8') 70 | 71 | 72 | class SingSong(object): 73 | """操作蜂鸣器类""" 74 | 75 | def __init__(self, GPIO: int = 5): 76 | self.buzzer = Pin(GPIO, Pin.OUT) # 设置蜂鸣器GPIO口为输入模式 77 | self.buzzer.value(0) 78 | 79 | async def play(self, data: str, interval: int = 0.8, loop: bool = False): 80 | """异步操作蜂鸣器,使其按照规定的节奏 81 | (该蜂鸣器是高电平触发!) 82 | data 格式: 2-3-1-2-4 83 | 表示响2s停(interval)s 84 | loop 表示是否循环播放 85 | """ 86 | lst = data.split("-") 87 | 88 | while True: 89 | for l in lst: 90 | l = float(l) 91 | self.start() 92 | sleep(l) 93 | self.stop() 94 | # sleep(interval) # 暂停 95 | await uasyncio.sleep(interval) 96 | 97 | if not loop: 98 | break 99 | 100 | def sync_play(self, data: str, interval: int = 0.8, loop: bool = False): 101 | """控制蜂鸣器""" 102 | lst = data.split("-") 103 | 104 | while True: 105 | for l in lst: 106 | l = float(l) 107 | self.start() 108 | sleep(l) 109 | self.stop() 110 | sleep(interval) # 暂停 111 | 112 | if not loop: 113 | break 114 | 115 | def start(self): 116 | """设置为高电平,触发""" 117 | self.buzzer.value(1) 118 | 119 | def stop(self): 120 | """设置为低电平,关闭""" 121 | self.buzzer.value(0) 122 | 123 | def __del__(self): 124 | # 对象销毁时重新设置为低电平 125 | print("Object deleted!") 126 | self.buzzer.value(0) 127 | 128 | 129 | class HcSr501(object): 130 | """操作Hc-Sr501的类""" 131 | 132 | def __init__(self, GPIO: int = 5) -> None: 133 | self.hc = Pin(GPIO, Pin.IN) 134 | self.hc.value(0) # 一开始设置低电平 135 | 136 | @property 137 | def value(self): 138 | """属性值,获取当前电平状态""" 139 | return self.hc.value() 140 | 141 | 142 | def get_dht11(pin: Pin) -> tuple: 143 | """DHT11 温度传感器模块""" 144 | d = dht.DHT11(pin) 145 | d.measure() # 启动测量 146 | wd = d.temperature() 147 | sd = d.humidity() 148 | return wd, sd 149 | 150 | 151 | @handle_error(tries=3) 152 | def sync_ntp(): 153 | """通过网络校准时间""" 154 | ntptime.NTP_DELTA = 3155644800 # UTC+8 155 | ntptime.host = 'ntp1.aliyun.com' 156 | ntptime.settime() 157 | return True 158 | 159 | 160 | if __name__ == "__main__": 161 | # wifi.disconnect() 162 | connectWIFI(wifi_ssid, wifi_passwd) 163 | --------------------------------------------------------------------------------