Ethernet

This article explains how to programmatically switch between Ethernet and WiFi networks using an ESP32 IoT controller, covering hardware requirements, code examples, and network testing procedures to ensure seamless connectivity and efficient data communication.

Ethernet

Example: Switching Between Ethernet and WiFi

Hardware Requirements:

Example Code: You need to modify the WiFi SSID and password, then upload the program to the board.

```cpp
/*
   Ethernet and WiFi network switching control
   Default power-on starts in Ethernet mode:
   - Switches to WiFi mode after detecting Ethernet connection timeout
   - Automatically switches back to Ethernet mode when Ethernet is restored in WiFi mode
*/

#include <ETH.h>
#include <WiFi.h>
const char* ssid     = "yourssid";     // WiFi network name
const char* password = "yourpasswd";   // WiFi password

// Network status flags
static bool eth_connected = false;     // Ethernet connection status
bool wifi_mode = false;                // WiFi mode flag
bool eth_mode = true;                  // Ethernet mode flag
uint64_t time_start = 0 ;              // Ethernet startup timestamp
uint64_t time_connected = 0 ;          // Ethernet connection success timestamp

// WiFi event callback function
void WiFiEvent(WiFiEvent_t event)
{
  switch (event) {
    case ARDUINO_EVENT_ETH_START:       // Ethernet start event
      ETH.setHostname("esp32-ethernet"); // Set the device hostname
      time_start = millis();            // Record start time
      break;
    case ARDUINO_EVENT_ETH_CONNECTED:   // Physical layer connection established
      time_connected = millis();
      Serial.println("ETH Connected");
      if(wifi_mode){                    // If currently in WiFi mode, restart
        ESP.restart();
      }
      break;
    case ARDUINO_EVENT_ETH_GOT_IP:      // Successfully obtained IP address
      Serial.print("ETH MAC: ");
      Serial.print(ETH.macAddress());   // Print MAC address
      Serial.print(", IPv4: ");
      Serial.print(ETH.localIP());      // Print IP address
      if (ETH.fullDuplex()) {           // Full-duplex status check
        Serial.print(", FULL_DUPLEX");
      }
      Serial.print(", ");
      Serial.print(ETH.linkSpeed());    // Print connection speed
      Serial.println("Mbps");
      eth_connected = true;             // Update connection status
      break;
    case ARDUINO_EVENT_ETH_DISCONNECTED:// Physical connection disconnected
      Serial.println("ETH Disconnected");
      if(!wifi_mode){                   // If not in WiFi mode, attempt restart
        ESP.restart();
      }
      eth_connected = false;
      eth_mode = false;
      break;
    case ARDUINO_EVENT_ETH_STOP:        // Ethernet stop
      Serial.println("ETH Stopped");
      eth_connected = false;
      break;
    default:
      break;
  }
}

// Network connection test function
void testClient(const char * host, uint16_t port)
{
  Serial.print("\nconnecting to ");
  Serial.println(host);  // Output target host info

  WiFiClient client;
  // Attempt to establish a TCP connection
  if (!client.connect(host, port)) {
    Serial.println("connection failed");
    return;
  }
  // Send HTTP request
  client.printf("GET / HTTP/1.1\r\nHost: %s\r\n\r\n", host);
  // Wait for server response
  while (client.connected() && !client.available());
  // Read returned data
  while (client.available()) {
    Serial.write(client.read());
  }

  Serial.println("closing connection\n");
  client.stop();
}

void setup()
{
  Serial.begin(115200);          // Initialize serial
  WiFi.onEvent(WiFiEvent);       // Register network event callback
  ETH.begin();                   // Start Ethernet
  delay(5000);                   // Wait for 5 seconds to initialize
  
  // Ethernet connection timeout detection (4 seconds without connection)
  if((millis()-time_start>4000)&&(time_connected==0)){
    // Start WiFi connection
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    wifi_mode = true;            // Switch to WiFi mode
  }
}

void loop()
{
  // Test network in valid connection mode
  if (eth_connected||wifi_mode) {
    testClient("baidu.com", 80);  // Test connection to Baidu server
  }
  delay(10000);                   // 10-second detection cycle
}

Next, connect the Ethernet cable to the Ethernet port on the Edge101 motherboard. When the green LED on the Ethernet port is lit, it indicates a successful connection. The orange LED blinking indicates communication.

At this point, the serial monitor will print information such as Ethernet connection success, the Ethernet MAC address, and IP address. The program will then access www.baidu.com every 10 seconds and return the retrieved data.

If the Ethernet cable is unplugged, the serial monitor will display "Ethernet Disconnected." The motherboard will then restart and attempt to connect to the network via WiFi. Once connected, it will access the website.

Was this article helpful?

TOP