|
1 | 1 | /*
|
2 |
| - This sketch trys to Connect to the best AP based on a given list |
| 2 | + This sketch shows how to use multiple WiFi networks. |
3 | 3 |
|
| 4 | + In this example, ESP8266 works in AP mode. |
| 5 | + It demonstrates: |
| 6 | + - Fast connect to previous WiFi network at startup |
| 7 | + - Registering multiple networks (at least 1) |
| 8 | + - Connect to WiFi with strongest signal (RSSI) |
| 9 | + - Fall back to connect to next WiFi when a connection failed or lost |
| 10 | +
|
| 11 | + To enable debugging output, select in the Arduino iDE: |
| 12 | + - Tools | Debug Port: Serial |
| 13 | + - Tools | Debug Level: WiFi |
4 | 14 | */
|
5 | 15 |
|
6 |
| -#include <ESP8266WiFi.h> |
7 | 16 | #include <ESP8266WiFiMulti.h>
|
8 | 17 |
|
9 | 18 | ESP8266WiFiMulti wifiMulti;
|
10 | 19 |
|
| 20 | +// WiFi connect timeout per AP. Increase when connecting takes longer. |
| 21 | +const uint32_t connectTimeoutMs = 5000; |
| 22 | + |
11 | 23 | void setup() {
|
12 | 24 | Serial.begin(115200);
|
| 25 | + Serial.println("\nESP8266 Multi WiFi example"); |
13 | 26 |
|
| 27 | + // Set WiFi to station mode |
14 | 28 | WiFi.mode(WIFI_STA);
|
| 29 | + |
| 30 | + // Register multi WiFi networks |
15 | 31 | wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
|
16 | 32 | wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
|
17 | 33 | wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");
|
18 |
| - |
19 |
| - Serial.println("Connecting Wifi..."); |
20 |
| - if (wifiMulti.run() == WL_CONNECTED) { |
21 |
| - Serial.println(""); |
22 |
| - Serial.println("WiFi connected"); |
23 |
| - Serial.println("IP address: "); |
24 |
| - Serial.println(WiFi.localIP()); |
25 |
| - } |
| 34 | + // More is possible |
26 | 35 | }
|
27 | 36 |
|
28 | 37 | void loop() {
|
29 |
| - if (wifiMulti.run() != WL_CONNECTED) { |
| 38 | + // Maintain WiFi connection |
| 39 | + if (wifiMulti.run(connectTimeoutMs) == WL_CONNECTED) { |
| 40 | + Serial.print("WiFi connected: "); |
| 41 | + Serial.print(WiFi.SSID()); |
| 42 | + Serial.print(" "); |
| 43 | + Serial.println(WiFi.localIP()); |
| 44 | + } else { |
30 | 45 | Serial.println("WiFi not connected!");
|
31 |
| - delay(1000); |
32 | 46 | }
|
| 47 | + |
| 48 | + delay(1000); |
33 | 49 | }
|
0 commit comments