OC
OceanRemote
Low-code IoT platform
← Back to Course

Connecting to WiFi - Complete Code

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
šŸ’” Important:

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
 */

#include 

const 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
 */

#include 

const 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");
}
        
āš ļø Common WiFi Issues & Solutions:
  • āŒ "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
 */

#include 

const 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();
}
        
šŸ“Š Power Saving Tips:
  • 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
 */

#include 

const 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() {}
        
šŸ“– Real-World Application - Nigerian Cassava Farm:

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

šŸŽ‰ Congratulations!

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!

šŸ“š Quick Reference - WiFi Commands:
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
šŸ’” Key Takeaways:
  • 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.