NodeMCU学习笔记--- WI-FI连接使用
Posted 初五霸
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NodeMCU学习笔记--- WI-FI连接使用相关的知识,希望对你有一定的参考价值。
NodeMCU学习笔记(3)— WI-FI连接使用
提示:作者使用 ESP8266 进行开发学习。
文章目录
前言
NodeMCU强大之处是继承了ESP8266的WI-FI功能,可以直接通过简单的设置进行联网。体积小、成本低、功能全、引脚丰富皆是NodeMCU的亮点。当然WI-FI能带来互联网更多的资源,让NodeMCU更强大、智能化。
本篇文章将使用Lua编写快速连入路由器的WI-FI、将NodeMCU(ESP8266)设置为热点或将两者共存的程序。主要学习内容有:
- 使用STA模式连接到已知的WI-FI;
- 将NodeMCU(ESP8266)设置为热点;
- 连入WI-FI和共享热点共存。
一、NodeMCU WI-FI无线模式
连接到 Wi-Fi 网络称为站点(Stations,简称为STA)。提供Wi-Fi 连接信号称为接入点 (Access Point ,简称为AP) 。
ESP8266 模块可以作为一个站点(STA)运行,因此我们可以将其连接到 Wi-Fi 网络。它还可以作为软接入点 (soft-AP) 运行,以建立自己的 Wi-Fi 网络。当 ESP8266 模块作为软接入点运行时,我们可以将其他站点连接到 ESP 8266模块。ESP8266 还可以作为站点(STA)和软接入点 (soft-AP)模式运行。这提供了构建例如网状网络的可能性[1]。ESP8266有三种工作模式 STA模式、AP模式、STA+AP模式。下面简单介绍他们的功能特点。
(1)Station (STA) 模式用于将 ESP8266 连接到由接入点建立的 WiFi 网络。
(2)ESP8266可以提供soft-AP,类似AP的功能,只是它没有连接到有线网络的接口。soft-AP可以同时连接的最大站点数可以设置为0~8个,ESP8266默认为4个。
当我们想给ESP8266设置已知需要连接的WI-FI名称和密码时,首先需要ESP8266工作在AP 模式。让我们手机或笔记本连入ESP8266的AP ,可以设置需要连接的WI-FI名称和密码,设置完成后,切换成STA模式,连入设置的WI-FI,进而联网或局域网通信。所以AP模式是在STA模式下将 ESP8266 连接到 WiFi 之前的中间步骤。
(3)ESP 8266可以在 soft-AP 和 Station 模式下运行,因此它可以充当网状网络的节点。
我们需要根据应用场景选择ESP8266的工作模式。往往最先需要使用soft-AP模式,然后长时间STA模式。以上是参考文章【1】所写,更详细的内容可以查看我文章尾部的参考文章链接。
二、WI-FI常用函数
(1)配置要使用的 WiFi 模式。
wifi.setmode()
NodeMCU 可以在三种 WiFi 模式,还有关闭模式。可以设置如下之一运行:
1) STA 模式,NodeMCU 设备加入现有网络;
2) AP 模式,它创建自己的网络,其他人可以加入;
3) STA + AP 模式,它既创建自己的网络,同时又加入另一个现有网络;
4) 关闭无线网络。
语法
wifi.setmode(mode[, save])
参数
mode value should be one of
wifi.STATION for when the device is connected to a WiFi router. This is often done to give the device access to the Internet.
wifi.SOFTAP for when the device is acting only as an access point. This will allow you to see the device in the list of WiFi networks (unless you hide the SSID, of course). In this mode your computer can connect to the device, creating a local area network. Unless you change the value, the NodeMCU device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP address, such as 192.168.4.2.
wifi.STATIONAP is the combination of wifi.STATION and wifi.SOFTAP. It allows you to create a local WiFi connection and connect to another WiFi router.
wifi.NULLMODE changing WiFi mode to NULL_MODE will put wifi into a low power state similar to MODEM_SLEEP, provided wifi.nullmodesleep(false) has not been called.
save choose whether or not to save wifi mode to flash
true WiFi mode configuration will be retained through power cycle. (Default)
false WiFi mode configuration will not be retained through power cycle.
返回
current mode after setup
(2)STA模式详细配置 。
wifi.sta.config()
语法
wifi.sta.config(station_config)
参数
station_config table containing configuration data for station
ssid string which is less than 32 bytes.
pwd string which is 0-64. Empty string indicates an open WiFi access point. Note: WPA requires a minimum of 8-characters, but the ESP8266 can also connect to a WEP access point (a 40-bit WEP key can be provided as its corresponding 5-character ASCII string).
auto defaults to true
true to enable auto connect and connect to access point, hence with auto=true there’s no need to call wifi.sta.connect()
false to disable auto connect and remain disconnected from access point
bssid string that contains the MAC address of the access point (optional)
You can set BSSID if you have multiple access points with the same SSID.
If you set BSSID for a specific SSID and would like to configure station to connect to the same SSID only without the BSSID requirement, you MUST first configure to station to a different SSID first, then connect to the desired SSID
The following formats are valid:
“DE:C1:A5:51:F1:ED”
“AC-1D-1C-B1-0B-22”
“DE AD BE EF 7A C0”
save Save station configuration to flash.
true configuration will be retained through power cycle. (Default).
false configuration will not be retained through power cycle.
Event callbacks will only be available if WIFI_SDK_EVENT_MONITOR_ENABLE is uncommented in user_config.h
Please note: To ensure all station events are handled at boot time, all relevant callbacks must be registered as early as possible in init.lua with either wifi.sta.config() or wifi.eventmon.register().
connected_cb: Callback to execute when station is connected to an access point. (Optional)
Items returned in table :
SSID: SSID of access point. (format: string)
BSSID: BSSID of access point. (format: string)
channel: The channel the access point is on. (format: number)
disconnected_cb: Callback to execute when station is disconnected from an access point. (Optional)
Items returned in table :
SSID: SSID of access point. (format: string)
BSSID: BSSID of access point. (format: string)
reason: See wifi.eventmon.reason below. (format: number)
authmode_change_cb: Callback to execute when the access point has changed authorization mode. (Optional)
Items returned in table :
old_auth_mode: Old wifi authorization mode. (format: number)
new_auth_mode: New wifi authorization mode. (format: number)
got_ip_cb: Callback to execute when the station received an IP address from the access point. (Optional)
Items returned in table :
IP: The IP address assigned to the station. (format: string)
netmask: Subnet mask. (format: string)
gateway: The IP address of the access point the station is connected to. (format: string)
dhcp_timeout_cb: Station DHCP request has timed out. (Optional)
Blank table is returned.
返回
true Success
false Failure
(3)以STA模式连接到 WI-FI。
wifi.sta.connect()
语法
wifi.sta.connect([connected_cb])
参数
connected_cb: Callback to execute when station is connected to an access point. (Optional)
Items returned in table :
SSID: SSID of access point. (format: string)
BSSID: BSSID of access point. (format: string)
channel: The channel the access point is on. (format: number)
返回
nil
当我们使用STA模式,这是最常用的三个函数。可以通过这三个函数进行连接已知的WI-FI信息。
(4)AP模式详细配置 。
wifi.ap.config()
在 AP 模式下设置 SSID 和密码。密码长度至少为 8 个字符。如果没有按照要求设置密码,SSID和密码设置无效,它将默认 SSID,例如 NODE_9997C3,且无密码。
语法
wifi.ap.config(cfg)
参数
cfg table to hold configuration
ssid SSID chars 1-32
pwd password chars 8-64
auth authentication method, one of wifi.OPEN (default), wifi.WPA_PSK, wifi.WPA2_PSK, wifi.WPA_WPA2_PSK
channel channel number 1-14 default = 6
hidden false = not hidden, true = hidden, default = false
max maximum number of connections 1-4 default=4
beacon beacon interval time in range 100-60000, default = 100
save save configuration to flash.
true configuration will be retained through power cycle. (Default)
false configuration will not be retained through power cycle.
Event callbacks will only be available if WIFI_SDK_EVENT_MONITOR_ENABLE is uncommented in user_config.h
Please note: To ensure all SoftAP events are handled at boot time, all relevant callbacks must be registered as early as possible in init.lua with either wifi.ap.config() or wifi.eventmon.register().
staconnected_cb: Callback executed when a new client has connected to the access point. (Optional)
Items returned in table :
MAC: MAC address of client that has connected.
AID: SDK provides no details concerning this return value.
stadisconnected_cb: Callback executed when a client has disconnected from the access point. (Optional)
Items returned in table :
MAC: MAC address of client that has disconnected.
AID: SDK provides no details concerning this return value.
probereq_cb: Callback executed when a probe request was received. (Optional)
Items returned in table :
MAC: MAC address of the client that is probing the access point.
RSSI: Received Signal Strength Indicator of client.
返回
true Success
false Failure
查看更多函数可以参考文章【2】。
三、WI-FI连接
(1)使用STA模式连接到已知的WI-FI。
1)代码如下:
print ("STA WI-FI Test...")
wifi.setmode(wifi.STATION)
cfg=
cfg.ssid="CSDN"
cfg.pwd="12345678"
wifi.sta.config(cfg)
counter=0
mytimer = tmr.create()
mytimer:register(2000,tmr.ALARM_AUTO,
function()
if wifi.sta.getip()==nil then
print("IP unavaiable,Wating...")
counter=counter+1
if(counter>10)then
node.restart()
end
else
print(wifi.sta.getip())
mytimer:stop()
end
end)
mytimer:start()
2)代码解释(实际烧录的程序没有注释):
3)运行测试:
连上WI-FI之后打印出当前NodeMCU的IP信息。具体信息如下:
NodeMCU IP:192.168.10.19
子网掩码:255.255.255.0
默认网关:192.168.10.10
(2)使用AP模式,将NodeMCU(ESP8266)设置为热点。
1)代码如下:
print ("AP WI-FI Test...")
wifi.setmode(wifi.SOFTAP)
cfg=
cfg.ssid="AP-IOT"
cfg.pwd="12345678"
wifi.ap.config(cfg)
counter=0
mytimer = tmr.create()
mytimer:register(2000,tmr.ALARM_AUTO,
function()
for mac,ip in pairs(wifi.ap.getclient()) do
print(mac,ip)
mytimer:stop()
end
end)
mytimer:start()
2)代码解释(实际烧录的程序没有注释):
3)运行测试:
运行后,电脑能搜索到AP-IOT。然后用设定的密码连接。
笔记本连上后查看,连接上的一些IP信息。
(3)连入WI-FI和共享热点共存。
1)代码如下:
print ("STA+AP WI-FI Test...")
wifi.setmode(wifi.STATIONAP)
cfg=
cfg.ssid="Play"
cfg.pwd="willyang"
wifi.sta.config(cfg)
cfg=
cfg.ssid="AP-IOT"
cfg.pwd="12345678"
wifi.ap.config(cfg)
f_sta = 0
f_ap = 0
mytimer = tmr.create()
mytimer:register(2000,tmr.ALARM_AUTO,
function()
for mac,ip in pairs(wifi.ap.getclient()) do
print(mac,ip)
f_ap = 1
end
if wifi.sta.getip()==nil then
print("IP unavaiable,Wating...")
else
print(wifi.sta.getip())
f_sta = 1
end
if(f_ap==1 and f_sta==1) then
mytimer:stop()
end
end)
mytimer:start()
2)代码解释(实际烧录的程序没有注释):
3)运行测试:
可以连接WI-FI,同时也可以为AP热点。
四、总结
本文编写了NodeMCU第一个WI-FI程序。将NodeMCU设置为STA模式、AP模式、STA+AP模式,分别对三种模式进行了测试,从测试的结果可知,不管进行那种模式的使用,需要配置WI-FI名称和密码。如果STA不配置WI-FI信息的话,将不会连上WI-FI路由。而AP模式下,不配置从官方文档可知[2],如果AP不配置或配置密码长度不够,AP热点会使用默认的SSID名称和无密码可连入。
下载遇到问题,或者说,程序下载后,没有按照程序逻辑执行,这都是因为ESP8266下载时,需要删除原来的程序。具体操作可以参考我上一篇文章。
参考文章:
[1] https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html
[2] https://nodemcu.readthedocs.io/en/release/modules/wifi/
上一篇文章:NodeMCU学习笔记(2)— 编写第一个NodeMCU程序"Hello World!"
下一篇文章:NodeMCU学习笔记(4)— GPIO使用
以上是关于NodeMCU学习笔记--- WI-FI连接使用的主要内容,如果未能解决你的问题,请参考以下文章
Arduino杀手在此!!NodeMCU手把手入门(持续更新)
NodeMCU学习笔记--- 编写第一个NodeMCU程序“Hello World!“