Connecting to WiFi - Complete Code
š¶ Connecting ESP32/ESP8266 to WiFi - Complete Guide
š” What You'll Learn in This Lesson:
- Connect your ESP32 or ESP8266 to any WiFi network
- Handle connection errors and timeouts gracefully
- Implement auto-reconnect for reliable operation
- Store WiFi credentials securely
- Optimize connection for battery-powered devices
š Why WiFi Connection Matters for IoT
Without internet connectivity, your IoT device can't send data to the cloud. Proper WiFi connection is the foundation of any IoT project!
| Feature | ESP32 | ESP8266 |
|---|---|---|
| WiFi Protocol | 802.11 b/g/n (2.4GHz) | 802.11 b/g/n (2.4GHz) |
| WiFi Library | WiFi.h |
ESP8266WiFi.h |
| Bluetooth | ā Yes (BLE + Classic) | ā No |
| Typical Current (WiFi on) | 120-180mA | 70-100mA |
ESP32 and ESP8266 only support 2.4GHz WiFi networks. They cannot connect to 5GHz networks!
š Basic ESP32 WiFi Connection (Step by Step)
/* * Basic ESP32 WiFi Connection * * This is the simplest way to connect your ESP32 to WiFi. * * Components Required: * - ESP32 development board * - Access to a 2.4GHz WiFi network * * Author: OceanRemote Education */ #include// ESP32 WiFi library // ========== WIFI CREDENTIALS ========== // REPLACE with your actual WiFi information! const char* ssid = "YOUR_WIFI_NAME"; // Your WiFi network name const char* password = "YOUR_WIFI_PASSWORD"; // Your WiFi password void setup() { // Step 1: Initialize Serial communication Serial.begin(115200); delay(1000); // Give serial time to initialize Serial.println("========================================"); Serial.println("š” ESP32 WiFi Connection Example"); Serial.println("========================================"); // Step 2: Start WiFi connection Serial.print("š Connecting to WiFi network: "); Serial.println(ssid); WiFi.begin(ssid, password); // Attempt connection // Step 3: Wait for connection (with visual feedback) while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } // Step 4: Connection successful! Serial.println("\nā WiFi connected successfully!"); Serial.print("š¶ IP address: "); Serial.println(WiFi.localIP()); Serial.print("š¶ Signal strength (RSSI): "); Serial.print(WiFi.RSSI()); Serial.println(" dBm"); Serial.println("========================================"); } void loop() { // Your code here - read sensors, send data, etc. // The WiFi stays connected automatically }
š Secure WiFi with Error Handling (Production-Ready)
Basic WiFi connection can get stuck forever if the network is down. This version handles errors!
/* * Secure ESP32 WiFi Connection with Error Handling * * Features: * - Connection timeout (won't get stuck forever) * - Retry mechanism * - Connection status monitoring * - Auto-reconnect on failure */ #includeconst char* ssid = "YOUR_WIFI_NAME"; const char* password = "YOUR_WIFI_PASSWORD"; // Connection settings const int MAX_CONNECTION_ATTEMPTS = 20; // Maximum retries const int CONNECTION_TIMEOUT_MS = 500; // Delay between attempts (ms) // Global connection status bool wifiConnected = false; void setup() { Serial.begin(115200); delay(1000); // Attempt WiFi connection wifiConnected = connectToWiFi(); if (wifiConnected) { Serial.println("ā System ready with WiFi!"); } else { Serial.println("ā ļø WiFi failed! Running in offline mode."); Serial.println(" (Will retry periodically)"); } } bool connectToWiFi() { Serial.println("========================================"); Serial.print("š” Connecting to: "); Serial.println(ssid); // Start connection WiFi.begin(ssid, password); int attempts = 0; while (WiFi.status() != WL_CONNECTED && attempts < MAX_CONNECTION_ATTEMPTS) { delay(CONNECTION_TIMEOUT_MS); Serial.print("."); attempts++; } Serial.println(); // New line after dots if (WiFi.status() == WL_CONNECTED) { Serial.println("ā WiFi connected!"); Serial.print("š¶ IP Address: "); Serial.println(WiFi.localIP()); Serial.print("š¶ Signal strength: "); Serial.print(WiFi.RSSI()); Serial.println(" dBm"); Serial.println("========================================"); return true; } else { Serial.println("ā WiFi connection failed!"); Serial.print(" Error code: "); Serial.println(WiFi.status()); Serial.println("========================================"); return false; } } void checkWiFiConnection() { // Check if WiFi is still connected if (WiFi.status() != WL_CONNECTED && wifiConnected) { Serial.println("ā ļø WiFi connection lost! Attempting to reconnect..."); wifiConnected = connectToWiFi(); if (!wifiConnected) { Serial.println("ā Reconnection failed. Entering offline mode."); } } } void loop() { // Check WiFi connection periodically checkWiFiConnection(); // Your main code here... // Only use WiFi if wifiConnected == true delay(1000); // Check every second }
ā»ļø Auto-Reconnect WiFi (For Long-Term Deployments)
Perfect for sensors that run 24/7. Automatically reconnects if WiFi drops!
/* * ESP32 Auto-Reconnect WiFi * Automatically reconnects when WiFi drops * Perfect for remote sensors and long-term deployments */ #includeconst char* ssid = "YOUR_WIFI_NAME"; const char* password = "YOUR_WIFI_PASSWORD"; unsigned long lastReconnectAttempt = 0; const unsigned long RECONNECT_INTERVAL = 30000; // Try every 30 seconds void setup() { Serial.begin(115200); connectToWiFi(); } void connectToWiFi() { Serial.print("š” Connecting to WiFi"); WiFi.begin(ssid, password); int attempts = 0; while (WiFi.status() != WL_CONNECTED && attempts < 20) { delay(500); Serial.print("."); attempts++; } if (WiFi.status() == WL_CONNECTED) { Serial.println("\nā WiFi connected!"); Serial.print("š¶ IP: "); Serial.println(WiFi.localIP()); } else { Serial.println("\nā WiFi connection failed"); } } void loop() { // Check connection status if (WiFi.status() != WL_CONNECTED) { unsigned long now = millis(); // Try to reconnect at intervals (don't hammer the network) if (now - lastReconnectAttempt > RECONNECT_INTERVAL) { lastReconnectAttempt = now; Serial.println("ā ļø WiFi lost! Attempting to reconnect..."); connectToWiFi(); } } else { // WiFi is connected - do your work here! // Send sensor data, etc. // Reset reconnect timer when connected lastReconnectAttempt = millis(); } delay(1000); }
š ESP8266 WiFi Connection
ESP8266 uses a different library but works the same way!
/* * ESP8266 WiFi Connection * Perfect for low-cost IoT projects * * Note: Uses ESP8266WiFi.h, not WiFi.h */ #include// ESP8266-specific library const char* ssid = "YOUR_WIFI"; const char* password = "YOUR_PASSWORD"; void setup() { Serial.begin(115200); delay(1000); Serial.println("š” ESP8266 WiFi Connection"); Serial.print("š Connecting to: "); Serial.println(ssid); WiFi.begin(ssid, password); int attempts = 0; while (WiFi.status() != WL_CONNECTED && attempts < 30) { delay(500); Serial.print("."); attempts++; } if (WiFi.status() == WL_CONNECTED) { Serial.println("\nā WiFi connected!"); Serial.print("š¶ IP Address: "); Serial.println(WiFi.localIP()); Serial.print("š¶ MAC Address: "); Serial.println(WiFi.macAddress()); } else { Serial.println("\nā WiFi connection failed!"); Serial.print(" Status: "); Serial.println(WiFi.status()); } } void loop() { // Your code here // Optional: Check connection periodically if (WiFi.status() != WL_CONNECTED) { Serial.println("ā ļø WiFi lost! Reconnecting..."); WiFi.reconnect(); } delay(1000); }
š ESP32 WiFi Status Codes
| Status Code | Meaning | Solution |
|---|---|---|
| WL_CONNECTED (3) | Connected to WiFi | ā Working normally |
| WL_NO_SSID_AVAIL (1) | Network not found | Check SSID name & signal range |
| WL_CONNECT_FAILED (4) | Wrong password | Verify WiFi password |
| WL_DISCONNECTED (6) | Router dropped connection | Check router stability, implement auto-reconnect |
| WL_IDLE_STATUS (0) | Idle / not connected | Still attempting connection |
š” WiFi Signal Strength (RSSI) Guide
RSSI Value Quality Recommendation
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
-30 to -50 Excellent Perfect for IoT sensors
-51 to -60 Very Good Works great
-61 to -70 Good Reliable connection
-71 to -80 Poor May drop occasionally
-81 to -90 Very Poor Unreliable - move closer to router
-90+ No signal Cannot connect
int rssi = WiFi.RSSI();
if (rssi > -60) {
Serial.println("ā
Excellent signal!");
} else if (rssi > -70) {
Serial.println("š” Good signal");
} else {
Serial.println("ā ļø Poor signal - consider moving sensor");
}
- ā "No serial data received": Press BOOT button while uploading, or check USB cable
- ā WiFi doesn't connect: ESP32/8266 only supports 2.4GHz (not 5GHz)
- ā Connection drops frequently: Implement auto-reconnect code (see above)
- ā Can't find your network: Check SSID spelling (case-sensitive!)
- ā ESP32 resets on WiFi connect: Power supply issue - use a better USB cable/battery
- ā "Brownout detector was triggered": Not enough power for WiFi - add capacitor or better supply
š Power Optimization for Battery-Powered WiFi
WiFi uses significant power. Here's how to minimize consumption:
/* * Power-Optimized WiFi Connection * For battery-powered sensors */ #includeconst char* ssid = "YOUR_WIFI"; const char* password = "YOUR_PASSWORD"; void connectWiFiAndSend() { // Step 1: Connect to WiFi WiFi.begin(ssid, password); int attempts = 0; while (WiFi.status() != WL_CONNECTED && attempts < 15) { delay(200); attempts++; } if (WiFi.status() == WL_CONNECTED) { // Step 2: Send your data sendDataToCloud(); // Step 3: Disconnect to save power WiFi.disconnect(true); WiFi.mode(WIFI_OFF); Serial.println("š” WiFi turned off to save power"); } } void setup() { Serial.begin(115200); connectWiFiAndSend(); // Go to deep sleep esp_sleep_enable_timer_wakeup(60 * 1000000ULL); // 60 seconds esp_deep_sleep_start(); }
- Connect to WiFi, send data, then disconnect immediately
- Use
WiFi.mode(WIFI_OFF)to completely power down WiFi radio - Send data in batches (collect readings, send once per hour)
- Use deep sleep between readings
- Reduce WiFi TX power if signal is strong
š§ Testing Your WiFi Connection
Use this sketch to debug WiFi issues:
/* * WiFi Diagnostic Tool * Tests connection and displays detailed information */ #includeconst char* ssid = "YOUR_WIFI"; const char* password = "YOUR_PASSWORD"; void setup() { Serial.begin(115200); delay(1000); Serial.println("========================================"); Serial.println("š§ ESP32 WiFi Diagnostic Tool"); Serial.println("========================================\n"); // Scan for available networks Serial.println("š” Scanning for WiFi networks..."); int n = WiFi.scanNetworks(); if (n == 0) { Serial.println("ā No networks found!"); } else { Serial.print("ā Found "); Serial.print(n); Serial.println(" networks:"); for (int i = 0; i < n; i++) { Serial.print(" "); Serial.print(i + 1); Serial.print(": "); Serial.print(WiFi.SSID(i)); Serial.print(" ("); Serial.print(WiFi.RSSI(i)); Serial.print(" dBm) "); Serial.println(WiFi.encryptionType(i) == ENC_TYPE_NONE ? "Open" : "Secured"); } Serial.println(); } // Attempt connection Serial.print("š Attempting to connect to: "); Serial.println(ssid); WiFi.begin(ssid, password); int attempts = 0; while (WiFi.status() != WL_CONNECTED && attempts < 30) { delay(500); Serial.print("."); attempts++; } Serial.println(); if (WiFi.status() == WL_CONNECTED) { Serial.println("ā CONNECTION SUCCESSFUL!"); Serial.print("š¶ IP Address: "); Serial.println(WiFi.localIP()); Serial.print("š¶ Subnet Mask: "); Serial.println(WiFi.subnetMask()); Serial.print("š¶ Gateway IP: "); Serial.println(WiFi.gatewayIP()); Serial.print("š¶ DNS IP: "); Serial.println(WiFi.dnsIP()); Serial.print("š¶ Signal Strength: "); Serial.print(WiFi.RSSI()); Serial.println(" dBm"); Serial.print("š¶ MAC Address: "); Serial.println(WiFi.macAddress()); // Test internet connectivity Serial.println("\nš Testing internet connectivity..."); if (WiFi.status() == WL_CONNECTED) { Serial.println("ā ESP32 has internet access!"); } } else { Serial.println("ā CONNECTION FAILED!"); Serial.print(" Error code: "); Serial.println(WiFi.status()); if (WiFi.status() == WL_NO_SSID_AVAIL) { Serial.println(" ā Network not found. Check SSID and signal range."); } else if (WiFi.status() == WL_CONNECT_FAILED) { Serial.println(" ā Wrong password. Verify your WiFi password."); } } Serial.println("\n========================================"); } void loop() {}
A farmer installed 5 soil moisture sensors across 10 acres using ESP8266 modules:
- š” Challenge: WiFi signal weak across large farm
- š” Solution: Installed WiFi extender + used auto-reconnect code
- š§ Result: 35% water savings, 28% yield increase
- š° ROI: System paid for itself in 3 months
"The auto-reconnect feature kept my sensors running even when power flickered!" - Farm owner, Nigeria
You can now reliably connect your ESP32/ESP8266 to any WiFi network!
ā Basic connection working
ā Error handling implemented
ā Auto-reconnect for reliability
ā Power optimization for batteries
Next lesson: Sending sensor data to OceanRemote cloud!
WiFi.begin(ssid, password); // Connect to WiFi WiFi.status(); // Check connection (WL_CONNECTED = 3) WiFi.localIP(); // Get IP address WiFi.RSSI(); // Get signal strength WiFi.macAddress(); // Get MAC address WiFi.reconnect(); // Force reconnection WiFi.disconnect(true); // Disconnect WiFi.mode(WIFI_OFF); // Turn off WiFi radio WiFi.setAutoReconnect(true); // Enable auto-reconnect
- Apply these concepts directly to your farm or project.
- Take notes on important details for the quiz.
- Use the button below to track your progress.