ESP8266 定时开关 [Micropython]

0. 引脚表

ESP8266 裸板是 22 个引脚。

ESP8266 NodeMCU 比较常见的是 ESP-12E, 开发板总共有30个引脚。

  • 开发板的引脚设置了新的丝印编码,与GPIO标号对应需要看图。
  • 在裸板的基础上增加了 3对电源引脚、一对RSV引脚。
  • 增加了一个 MicroUSB口、一个LED灯、两个按键,可以方便调试。

引脚如下图所示:



注意:开机之后有的引脚是默认上电的!!!
https://zhuanlan.zhihu.com/p/568057038
https://www.yiboard.com/thread-1834-1-1.html

1. 定时开关

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from machine import Pin

import network
import time
import ntptime

import uasyncio as asyncio

# === 0. wifi config ==========================
ssid = 'xxxx'
pswd = 'cccc'

led = Pin(2, Pin.OUT)
led.on()

async def wifi_connect():
while True:
try:
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, pswd)

status = wlan.ifconfig()
print('wifi={} ip={}'.format(ssid, status[0]))
print(time.localtime(), 'wifi time')
led.off()
await asyncio.sleep(300)

except Exception as e:
led.on()
print('ERROR', e)

# === 1. ntp update ==========================
async def ntp_update():
while True:
try:
# https://www.pool.ntp.org/zone/cn
ntptime.host = 'cn.pool.ntp.org'
ntptime.settime()
now = time.localtime(time.time() + 8*3600)
print(now, ntptime.host)
led.off()
await asyncio.sleep(300)

except Exception as e:
led.on()
print('ERROR', e)

# === 2. light control ==========================
light = Pin(5, Pin.OUT)
light.on()

async def led_control():
while True:
try:
now = time.localtime(time.time() + 8*3600)
hh, mm, ss = now[3], now[4], now[5]

if hh not in range(7, 22):
light.on()
else:
light.off()

await asyncio.sleep(3)

except Exception as e:
print('ERROR', e)


loop = asyncio.get_event_loop()
loop.create_task(wifi_connect())
loop.create_task(ntp_update())
loop.create_task(led_control())

loop.run_forever()