I am a little puzzled why this code does not work. I am reading the MAC address of the device, storing it as an array of bytes/uint8_t in eeprom and then converting it to a string/char array to use when including in an event message. In the code snippet below, if I declare macAddr as a char array i.e. char macAddr[] = “00:00:00:00:00:00”; Then this works and end of loop macAddr is correct whereas if declare as char* macAddr; it returns the initialised value at the end of loop. Can anyone explain this?
char* macAddr;
uint8_t macA[6];
void setup()
{
macAddr = "00:00:00:00:00:00";
for (int i = 0; i < 6; i++) {macA[i] = 0x0;}
}
void loop()
{
Serial.printlnf("macAddr [start of loop]: %s", macAddr);
getMACaddress();
Serial.printlnf("macAddr [end of loop] : %s", macAddr);
delay(1000);
}
// helper function to get mac address into a string macAddr
void getMACaddress()
{
if ((macA[0] + macA[1] + macA[2] + macA[3] + macA[4] + macA[5]) == 0) //check if eeprom mac address not set
{
byte mac[6]; //define and set to zeros
WiFi.macAddress(mac); //read from wifi module else use stored mac address
if ((mac[0] + mac[1] + mac[2] + mac[3] + mac[4] + mac[5]) > 0) //update mac address stored if not zeros
{
for (int i = 0; i < 6; i++) {macA[i] = mac[i];}
}
}
int j = 0;
for (int i = 0; i < 6; i++)
{
if (i > 0) {macAddr[j] = ':'; j++;}
macAddr[j] = binAscii(macA[i] >> 4);
j++;
macAddr[j] = binAscii(macA[i] & 0x0F);
j++;
}
macAddr[j] = '\n'; //null string terminator
}
// helper function to return ascii from unsigned byte 0x0-F or ? if out of range
char binAscii(uint8_t c)
{
if (c >= 0x0 && c <= 0x9) return (c + '0');
else if (c >= 0xA && c <= 0xF) return (c - 0xA + 'A');
else return '?'; //if out range 0-F
}