Search code examples
c++arduinoesp32

Dynamically get mac address of esp32 and use it in ethernet library


Can anyone enlighten me on how to get mac address dynamically from esp32 and use it in ethernet library. So far, I have got mac address from wifi library as follows:

#include <WiFi.h>
#include <Ethernet.h>
 byte mac[6] = {};    
 void setup(){
   Serial.begin(115200);
   delay(500);
   WiFi.macAddress(mac);
   if (Ethernet.begin(mac) == 0) {
    Serial.println(F("Failed DHCP"));
    }
}

I always end up getting "Failed DHCP" even though my esp32 is connected with the internet. One more problem that I face when storing mac address in separate array is that the hex number "A" is not stored as "0A". Please help me out.


Solution

  • Try using the following to get mac address,

    #include <WiFi.h>
    
    String macAddr = WiFi.macAddress();
    

    or use this,

    String getMacAddress()
    {
       uint8_t baseMac[6];
    
       // Get MAC address for WiFi station
       esp_read_mac(baseMac, ESP_MAC_WIFI_STA);
    
       char baseMacChr[18] = {0};
       sprintf(baseMacChr, "%02X:%02X:%02X:%02X:%02X:%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
    
       String macAddress = String(baseMacChr);
    
       Serial.print("MAC Address :: ");
       Serial.println(macAddress);
    
       return String(baseMacChr);
    }
    

    I used this for ESP32-S CAM and works great.