How to get MAC Address in ESP-IDF

The MAC address is the unique identifier of your ESP32 Chip, and often used as the device_id in IoT Applications. Espressif (the manufacturer of ESP32 chips) programs a globally unique MAC address in the EFUSE of each chip in the factory. This MAC address is 6 bytes long, and often represented in the xx:xx:xx:xx:xx:xx format. An example MAC address is a0:76:4e:5a:ee:98.

If you are using the ESP-IDF framework, this MAC address can be accessed using the esp_efuse_mac_get_default() function defined in this file.

The syntax is as follows:

esp_err_t ret = ESP_OK;
uint8_t base_mac_addr[6];
ret = esp_efuse_mac_get_default(base_mac_addr);
if(ret != ESP_OK){
        ESP_LOGE(TAG, "Failed to get base MAC address from EFUSE BLK0. (%s)", esp_err_to_name(ret));
        ESP_LOGE(TAG, "Aborting");
        abort();
    } 

As you can see, this function stores the 6 bytes of the mac address into an array that we provide as an argument to this function. Now, if you wish to convert this into a continuous string (character array) for use in functions, you can convert it as shown below:

static const char *TAG = "extract_mac";

uint8_t index = 0;
char macId[50];
for(uint8_t i=0; i<6; i++){
   index += sprintf(&macId[index], "%02x", base_mac_addr[i]);
        }
ESP_LOGI(TAG, "macId = %s", macId);

This macId char array can now be used across several functions where you need to access the device_id.


For more tutorials on ESP32, check out https://iotespresso.com/category/esp32/. Also, you may find this course on ESP32 on Udemy to be quite helpful. Do check it out

Leave a comment

Your email address will not be published. Required fields are marked *