ESP32 MAC address read and setting
Obtaining and setting the MAC address of ESP32/ESP8266
First, Lingshun Lab (lingshunlab.com) introduces how to use Arduino IDE programming to obtain and set (modify) the MAC address of ESP32/ESP8266.
WiFi.macAddress()
Usage 1: WiFi.macAddress()
In obtaining the MAC address, the WiFi.macAddress() function is mainly used
In fact, the macAddress method calls the esp_wifi_get_mac function, and you can view relevant information. Before obtaining the MAC address, we do not need to connect to any WIFI.
But when checking esp_wifi_get_mac , I saw that there was an error message in this function ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init
: WIFI was not initialized.
In actual applications, whether or not the following WIFI initialization code is added, the MAC address can still be obtained in ESP32.
1 | WiFi.mode(WIFI_MODE_STA); // If you can't get a MAC address, try adding this line of code for WIFI initialisation |
Usage 2: WiFi.macAddress(macAddr)
This function has another usage WiFi.macAddress(macAddr), where macAddr is optional. If the parameter macAddr is input, the mac address of the ESP32/ESP8266 development board will be stored in the variable macAddr. macAddr must be an array of uint8_t type, which contains 6 elements.
Sample code:
1 | uint8_t macAddr[6]; |
Get MAC address code
1 | // welcome to lingshunlab.com |
Upload the code, open the serial monitor, set the baud rate to 115200, and you can see the following information:
Modify MAC Address
The MAC address is assigned by the manufacturer. You can modify it, but it will not overwrite the original MAC address. Every time you reset the board or upload new code, it will revert to the default MAC address assigned by the manufacturer. Therefore, if you modify the MAC address, you need to add the code to modify the MAC address in each project code.
1 | // welcome to www.esptutorial.com |
Upload the code, open the serial monitor, set the baud rate to 115200, and you can see the following information:
References:
https://randomnerdtutorials.com/get-change-esp32-esp8266-mac-address-arduino/
http://www.taichi-maker.com/homepage/iot-development/iot-dev-reference/esp8266-c-plus-plus-reference/esp8266wifista/macaddress/