user1965493
user1965493

Reputation: 47

Unexpected characters in the end of Arduino char[]

I have char[] inside an Arduino sketch. Code:

int i = 0;

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

}

void loop(){
  i++;
  Serial.println(i);
  char fff[8] = {'0','0','0','0','0','0','0','0'};
  Serial.println(fff);
  delay(200);
}

Listening to the port i see:

1
00000000²
2
00000000²
3
00000000²
4
00000000²

...

How can i fix this problem with unexpected characters at the end of a printable char?

Upvotes: 2

Views: 1360

Answers (1)

Matthew Murdoch
Matthew Murdoch

Reputation: 31453

The fff string is not null terminated so the Serial.println() function doesn't know when to stop reading characters from memory and sending them to the serial port. It stops as soon as it finds the first null byte in memory - leading to unpredictable behavior.

To fix the problem you will need to put a null character on the end of the string (and make sure you have allocated enough memory to cover it). In a character array the null character can be encoded as either a number (0) or as a character using an escape sequence ('\0').

Therefore, change the definition of fff to:

char fff[9] = { '0', '0', '0', '0', '0', '0', '0', '0', 0 };

or:

char fff[9] = { '0', '0', '0', '0', '0', '0', '0', '0', '\0' };

Upvotes: 4

Related Questions