Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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);
share|improve this question
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 at 12:49
up vote 0 down vote accepted

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();
share|improve this answer
    
Thanks Johnny! This helps. – hpb Jun 8 at 15:51
    
A quick Q: Why are you dividing sizeof(data) by sizeof(data[0])? Wont just sizeof(data) suffice? – hpb Jun 8 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 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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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