Array problem

I want to set the array item but it doesn't work. Who can say to me why ?

Code : byte receivedMessage[65]; int index = 0; String inputString = "";

void setup() { Serial.begin(9600); inputString.reserve(200); }

void loop() { }

void serialEvent() { while (Serial.available()) { /* It doesn't work. Why ? */ receivedMessage[index] =; index = index + 1;

/* It doesn't work */ // byte receivedByte =; // receivedMessage[index] = receivedByte ; // index = index + 1;

// receivedMessage[0] =; -> It works.

// receivedMessage array always empty even if i set the field.

// inputString += (char); -> It works! } }

I want to learn why because I like to work with arrays.

From that code, how can you know "it doesn't work"? You're not terminating your string ; that could be a problem.

there is no guard to protect out of range error. index can become > 64 ...

I have lcd screen so that I can check the result.
When I use the string type, I can see the result on lcd screen.

I know it isn’t safe but I just send 10 bytes, not more.

Code :
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 8, 5, 4, 3, 2);

byte receivedMessage[65];
int index = 0;

void setup() {
// put your setup code here, to run once:


void loop() { }

void serialEvent() {
while (Serial.available()) {
/* It doesn’t work */
receivedMessage[index] =;
index = index + 1;


/* It works */
// char test = (char)
// lcd.print(test);

You're not terminating your string ; that will be a problem.


Think very carefully about what you did immediately before this.


There is no possible way that casting a byte to a String is going to work. The cast is not only unnecessary, it is wrong (I almost typed stupid, but I thought better of it). The array type should be char, and the array should be NULL terminated, as has been pointed out twice.

      receivedMessage[index] =;
      index = index + 1;
      receivedMessage[index] = '\0';

Drop the usage of the String type, as the overhead and memory usage make the "pros" of using it not worth the "cons". You can cast an array of bytes to a "string" (chars are signed bytes, after all) but you're trying to cast a single byte to a string. Unless that byte is 0, you're going to get a lot of garbled non-sense.

You can use a variable of type char to store the return value of and it will be more specific to what you're trying to do. You need to have an idea of how long the string you want to read is going to be, otherwise you're going to run into problems with buffer overflows. Always allocate one extra character for your array to contain your null terminator, so that your string will be able to be displayed properly.