The code below is used to get the MAC address of the WiFi interface of an ESP32 microcontroller. As I am not a developer and programmer, I created the code in VS Code with the help of AI and the Espressif discussion forum. We found useful examples in the posts of this forum and also on Github. Honestly, it was an interesting experience with what AI can do and what it can’t handle.
Please don’t forget to enable WiFi function in the ESP-IDF SDK Configuration Editor (menuconfig). You can use the gear icon on the bottom bat in VS Code to enter the menuconfig.
The code:
/*******************************************************************************************
ESP32: ESP-IDF code creted in VS Code to retrieve the MAC address of the Wifi controller
Code created by AI and OK1TK with support of the Espressive ESP32 forum
*******************************************************************************************/
#include <stdio.h>
#include "esp_wifi.h"
#include "esp_log.h"
#include "nvs_flash.h"
void app_main()
{
esp_err_t ret;
//Initialize the default NVS partition.
ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
// If NVS initialization fails due to uncleaned pages or a new version, we clear NVS and try again
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
// TCP/IP stack initialization
esp_netif_init();
esp_event_loop_create_default();
// Initialization WiFi
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ret = esp_wifi_init(&cfg);
if (ret != ESP_OK) {
ESP_LOGE("WiFi", "WiFi initialization FAILED!: %s", esp_err_to_name(ret));
return;
}
// Retrieving the the MAC address of the WiFi interface
uint8_t mac[6];
ret = esp_wifi_get_mac(ESP_IF_WIFI_STA, mac);
if (ret != ESP_OK) {
ESP_LOGE("WiFi", "Unable to retrieve the MAC address of the WiFi interface: %s", esp_err_to_name(ret));
return;
}
// Writing the MAC address of the WiFi interface to the terminal
ESP_LOGI("WiFi", "The WiFi interface MAC address: %02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}