[SOLVED]Cast Spark Mac address to const char*

I am able to read the mac address of the spark into a byte array and then print that to the serial line in hex format Using this Code:

byte mac[6];

void setup() {
  Serial.begin(9600);
  while (!Serial.available()) Spark.process();

  WiFi.macAddress(mac);

  Serial.print(mac[5],HEX);
  Serial.print(":");
  Serial.print(mac[4],HEX);
  Serial.print(":");
  Serial.print(mac[3],HEX);
  Serial.print(":");
  Serial.print(mac[2],HEX);
  Serial.print(":");
  Serial.print(mac[1],HEX);
  Serial.print(":");
  Serial.println(mac[0],HEX);
}

However how would I write these hex formatted bytes to a const char* which I will use to transmit across the network? Sorry I am still learning the casting protocols a bit.

char smac[18]; // 2*6 + 5 '.' + nul
sprintf( smac,
         "%2X.%2X.%2X.%2X.%2X.%2X", 
         mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
2 Likes

@IOTrav Here is a function I wrote for that -

char _strMacAddress[18];
char *MacAddress2Str(byte *_mac)
{
	sprintf(_strMacAddress, "%02x:%02x:%02x:%02x:%02x:%02x",
	        _mac[5], _mac[4], _mac[3], _mac[2], _mac[1], _mac[0]);
	return _strMacAddress;
}

Here is how you use it -

Serial.print("Mac : ");
byte mac[6];
WiFi.macAddress(mac);
Serial.println(MacAddress2Str(mac));
3 Likes

Thank you @mtnscott and @psb777

Both of your methods work. I am using @mtnscott method though since the string is cleaner.

@psb77 method prints " 8. 0.28.XX.XX.XX". Which is to be expected with specified format.

@mtnscott method prints “08:00:28:XX:XX:XX” Which is better for my use.

(XX;XX:XX) above to protect my device mac address.

Thank you Both and have a great day

1 Like