ESP8266-NodeMCU可以快速的连接wifi网络,当然,也可以开启作为热点,下面简单的介绍如何链接wifi,参考代码是为了启动的时候可以读取wifi配置,方便编写代码后续更新wifi连接信息。

参考代码

boot.py

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
# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
import uos, machine
#uos.dupterm(None, 1) # disable REPL on UART(0)
import gc
import webrepl
import network
import utime
import ujson
wlan = network.WLAN(network.STA_IF)
wlan.active(True)

ssid = ""
pwd = ""

with open("wifi.json", "r", encoding="utf-8") as file:
wifi_cfg = ujson.loads(file.read())
ssid = wifi_cfg["ssid"]
pwd = wifi_cfg["passwd"]

count = 15

if not wlan.isconnected():
print("connect to wifi ", ssid)
wlan.connect(ssid, pwd)
while (not wlan.isconnected() and count > 0):
print("connect to wifi ", ssid, "...", dcount)
count = count - 1
utime.sleep(1)

if wlan.isconnected():
print(wlan.ifconfig())
else:
print("connect to wifi ", ssid, "failed!!!")
webrepl.start()
gc.collect()

wifi.json

1
{"ssid": "your-wifi-ssid", "passwd": "your-wifi-passwd"}

运行情况