Strange behaviour with serial

When I input data through the serial monitor it works fine for the first set of characters, everything you input after that gives you jibbrish back in the monitor.

Can anyone else try this piece of code and input a few series of letters and numbers in different lenghts and see what happens?

I'm trying to make a program that can recieve 3 digit directions for a servo.

char char_in[4]; int index = 0;

void setup() { Serial.begin(4800);

}

void loop() { while(Serial.available() > 0) { char_in[index++] = Serial.read(); } Serial.println(char_in);

index = 0; delay(500); }

(deleted)

char_in is a character array, not a C string. You need a null at the end if you want to treat it as a string:

  while(Serial.available() > 0) 
  {
    char_in[index++] = Serial.read();
    char_in[index] = 0 ;
  }
  Serial.println(char_in);

But you also need to bounds-check that array, as its only 4 characters long it can only hold upto 3 characters as a C string. You need to always do bounds checking with C arrays, the language doesn't do it for you.

Good input spycatcher. But shouldn't this be possible as well? Even though it only catches one char at a time it still should loop through it and catch them all? MarkT - Shouldn't index = 0; do the same as reseting the index inside the array? The code should still start adding from 0 all over again on the next loop?

The array is 4 char long, but when I input 4 chars I get jibbrish. Same thing happens if I input consequitive 3 char inputs.

You get gibberish because you're using a function that expects to be given a string, but you're not giving it a string, because you don't terminate the string.

Even though it only catches one char at a time it still should loop through it and catch them all?

No, because serial is very slow.

Have a look at the examples in Serial Input Basics - simple, reliable ways to receive data.

...R

char char_in[4] is initially filled with zeros, which coincidentally is also the special character that indicates the end of a string. So Serial.println(char_in) will work so long as you have put in 3 chars or fewer.

But as soon as you fill it with 4 chars, the println() function doesn’t know where it ends, and it will go marching through your program’s memory until it does find a zero. There’s no additional data stored alongside char_in that lets println() know how long it is.

Serial.write() will accept an additional parameter to tell it how many chars to write. But don’t just do Serial.write(char_in, 4) because at some time in the future you are going to change the size of this array and then you have to do a search-replace on all the "4"s in your code. Define a constant and give it a name, that way you can use this value everywhere.

const int char_in_length = 4;
char char_in[char_in_length];

...
  while(Serial.available() > 0 && index < char_in_length) {
    char_in[index++] = Serial.read();
  }
  Serial.write(char_in, index);