I'm trying to convert this array uint8_t data[]
in the code below to a character array to be printed in the serial monitor. However, when I run this code I see a blank screen. What am I doing wrong?
Serial.begin(115200);
uint8_t data[] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x00,0x01,0x02,0x03,0x04,0x05};
Serial.println((char*)data);
2 Answers 2
When you cast as char *
, println
thinks you are passing it a string. It will try to print it as a string and stop on the first 0x00
.
You can use Serial.write
to send the array as integers (no conversion):
Serial.write(data, sizeof(data));
If you want to send the ASCII representation of these numbers, use a loop. Serial.print
will convert:
int count = sizeof(data) / sizeof(data[0]);
for (int i = 0; i < count; i++) {
Serial.print(data[i]);
}
Serial.println();
-
A quick Q: Why are you dividing
sizeof(data) by sizeof(data[0])?
Wont justsizeof(data)
suffice?hpb– hpb2016年06月08日 20:13:29 +00:00Commented Jun 8, 2016 at 20:13 -
sizeof(data) gives you the size of the array in bytes. What I did gives the number of items in the array.001– 0012016年06月08日 20:47:05 +00:00Commented Jun 8, 2016 at 20:47
To print numbers, integers have to be converted to ASCII code. To accomplish this add 0x30 to each value. Note, this (only) works for numbers between 0 and 9 as the ASCII value for zero is 0x30. Good code will check to make sure only the values 0 through 9 are being processed.
When creating a character string you need to identify the end using the NULL character. Before using an array of characters, set the array position after the last desired character equal to NULL or 0x00. Terminating the string is explained further in this article.
char *
just makes the compiler think it's a string, which it isn't. Those aren't the ASCII values of printable characters.