0

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);
  • 1
    In what way do you want to "print" it? Converting it to char * just makes the compiler think it's a string, which it isn't. Those aren't the ASCII values of printable characters. – Majenko Jun 7 '16 at 12:49
0

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();
| improve this answer | |
  • A quick Q: Why are you dividing sizeof(data) by sizeof(data[0])? Wont just sizeof(data) suffice? – hpb Jun 8 '16 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. – Johnny Mopp Jun 8 '16 at 20:47
0

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.