一、方法一(會編譯,功能很強大)
自動配網首先想到的是esp8266的startsmart功能。官方文檔介紹如下:
1、僅在wifi.STATION模式下可用。
2、語法:
wifi.startsmart(type, callback)
參量
type ESP_TOUCH爲0,AIR_KISS爲1。
callbackfunction(ssid, password) end在配置後會被調用的形式的回調函數。
3、範例
wifi.setmode(wifi.STATION)
wifi.startsmart(0,
function(ssid, password)
print(string.format("Success. SSID:%s ; PASSWORD:%s", ssid, password))
end
)
然並卵,出錯了!~~~~~~~~
爲啥呢?原來官方默認是關閉的,指導爲啥!~
咋辦呢?度娘有解決辦法,思路是修改源文件,再重新編譯。
這個博客介紹的很棒,有空研究下!點這裏
嫌編譯麻煩的,可以刷下下邊這個固件,先試試!不過模塊不應適合你!~~ NodeMCU固件(含WiFi配置) 鏈接:https://pan.baidu.com/s/1jwWB7ZxoEY1tK0Tilq_OoA 提取碼:0y6t
二、使用enduser模塊實現
1、構建添加模塊固件
2、
3、電腦連接模塊開放的網絡
4、通過網頁配置聯網 192.168.4.1或者example.com
5、配網成功後貌似模塊的網絡信號就消失了
官方語法:
wifi.setmode(wifi.STATIONAP)
wifi.ap.config({ssid="MyPersonalSSID", auth=wifi.OPEN})
enduser_setup.manual(true)
enduser_setup.start(
function()
print("Connected to WiFi as:" .. wifi.sta.getip())
end,
function(err, str)
print("enduser_setup: Err #" .. err .. ": " .. str)
end
)
**
但是,但是,但是,實踐證明!~手動連接成功率不高,又慢!!!建議自動模式!!!! 只需要 enduser_setup.start()就OK!其他步驟同上文!
**
enduser_setup.start(
function()
print("Connected to WiFi as:" .. wifi.sta.getip())
end,
function(err, str)
print("enduser_setup: Err #" .. err .. ": " .. str)
end
)
下邊看 使用nodemcu玩轉物聯網系列(八)實現自動配網:
led_pin = 1--需要控制的led燈
--原來的手動
--wifi.setmode(wifi.STATION)
--cfg = {}
--cfg.ssid = "kyn"
--cfg.pwd = "20160118"
--wifi.sta.config(cfg)
--wifi.sta.connect()
--自動配網
enduser_setup.start(
function()
print("Connected to WiFi as:" .. wifi.sta.getip())
end,
function(err, str)
print("enduser_setup: Err #" .. err .. ": " .. str)
end
)
DeviceId = "587667371"
ProductId = "325428"
AuthoInfo = "test"
host = "183.230.40.39"
port = 6002
timer = tmr.create()
function con()
if wifi.sta.getip() == nil then
print("coneting........")
else
timer:stop()
print("success!~")
print(wifi.sta.getip())
client_hum = mqtt.Client(DeviceId,120,ProductId,AuthoInfo)
client_hum:connect(host,port,0,
function(client)
print("connect success!")
end)
function h()
client_hum:subscribe("$dp",0,
function(client)
print("subscribe success")
end)
client_hum:on("message",
function(client,topic,message)
print(message)
pwm.setup(led_pin, 500, 0)
pwm.start(led_pin)
pwm.setduty(led_pin,message)
end)
end
timer:alarm(1000,tmr.ALARM_AUTO,h)
end
end
timer:alarm(1000,tmr.ALARM_AUTO,con)
部分內容轉載了:https://blog.csdn.net/dianzishi123/article/details/84962435
向作者致謝!~