4

I want to print my string variable using printf method:

id = 6415F1BF713C

  Serial.printf("id: %s\n\n", id);
  Serial.print(id);

The result that I got was:

id: ⸮⸮⸮?
6415F1BF713C

is there any thing that's wrong?

Thanks.

Update :

//get device id
String getDeviceID() {
  uint64_t chipid = ESP.getEfuseMac(); // The chip ID is essentially its MAC address(length: 6 bytes).
  uint16_t chip = (uint16_t)(chipid >> 32);

  char devID[40];
  snprintf(devID, 40, "%04X%08X", chip, (uint32_t)chipid);

  return devID;
}
String id = getDeviceID();

Serial.printf("id: %s\n\n", id);
Serial.print(id);
William Santoso
  • 43
  • 1
  • 1
  • 4

1 Answers1

8

You didn't offer enough code to properly debug this, but I'm guessing what you mean is

String id = "6415F1BF713C";

Serial.printf("id: %s\n\n", id);
Serial.print(id);

The %s format in the printf() method expects to take a C/C++ char *, not a String. When you passed it a String, it printed the memory address of the String object - four characters which would appear as garbage, as you saw.

C and C++ use char * (pointers to characters) and char [] (arrays of characters) to represent strings. These are different from the Arduino String class, and people often confuse them.

To use the printf() method with a String you need to get its C string pointer, like this:

Serial.printf("id: %s\n\n", id.c_str());

The reason that this:

Serial.print(id);

works is that the print() method has a form that specifically expects to take a String object as an argument.

romkey
  • 6,218
  • 3
  • 16
  • 12