接入点模式:开发板作为路由器(网关),可以让其他设备连接
无线终端模式:开发板作为终端,可以连接路由器WiFi
说明:此处使用ArduinoIDE来进行开发。
注意:上传代码前必须把“串口监视器” 关闭,否则可能上传出错,因为端口被占用了
1、配置接入点模式
即开启 “热点”
-
导入 ESP8266WiFi.h
库
-
配置WiFi名称(ssid)、密码(passwd)—— softAP()
1 2 3
| const char ssid[] = "MyWiFi"; const char passwd[] = "12345678"; WiFi.softAP(ssid, passwd);
|
-
获取开发板IP
完整code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #include <ESP8266WiFi.h>
char ssid[] = "MyWiFi"; char passwd[] = "1234567890";
void setup(){ Serial.begin(9600); Serial.print("wifi ssid: "); Serial.println(ssid); Serial.print("wifi password: "); Serial.println(passwd); WiFi.softAP(ssid, passwd);
Serial.print("IP Address: "); Serial.println(WiFi.softAPIP()); }
void loop(){ }
|
2、配置无线终端模式
只有1个WiFi
将开发板连接WiFi
1 2 3
| WiFi.mode(WIFI_STA); WiFi.begin(ssid, passwd);
|
多次尝试连接,直到连接上:
1 2 3 4
| while(WiFi.status() != WL_CONNECTED ){ delay(1000); }
|
连上WiFi后,获取wifi的ssid、开发板IP地址:
1 2
| WiFi.SSID(); WiFi.localIP();
|
完整code:
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
| #include <ESP8266WiFi.h>
String ssid = "aaa"; String password = "12345678"; void setup() { Serial.begin(9600); WiFi.begin(ssid, password); int i = 0; while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print(i++); Serial.print(' '); } Serial.println(""); Serial.print("Connecting to "); Serial.println(ssid); Serial.println("IP address: " ); Serial.println(WiFi.localIP()); }
void loop() { }
|
多个WiFi,自动连接最强信号的
-
先添加几个待选WiFi
1 2 3 4 5 6 7 8 9 10 11
| #include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
wifiMulti.addAP("aaaa", "11111111"); wifiMulti.addAP("bbbb", "22222222"); wifiMulti.addAP("cccc", "33333333");
|
-
多次尝试连接:wifiMulti.run()
1 2 3 4 5
| while (wifiMulti.run() != WL_CONNECTED) { delay(1000); Serial.print('...'); }
|
完整code:
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
| #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
void setup(){ Serial.begin(9600); wifiMulti.addAP("aaa", "12345678"); wifiMulti.addAP("bbb", "12345678"); wifiMulti.addAP("ccc", "12345678");
int i = 0; while (wifiMulti.run() != WL_CONNECTED){ delay(1000); Serial.print(++i); Serial.print(" "); }
Serial.println(""); Serial.print("IP Address: "); Serial.println(WiFi.localIP()); }
void loop(){
}
|