A string is a NULL terminated array of chars. red is NOT NULL terminated, so you should not be passing it to a function that expects a string.
Thanks for this. I'll elaborate on the problem that I am having.
In the example below I am expecting R to be 32, G to be 128 and B to be 0. What I get instead is that B is 128 due to the 'blue' char array ending up being loaded with other data. What I cannot understand is how the 'blue' char array ends up with the chars '128' in there as I am only loading it with 3 bytes and it has a size of 3.
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
char receivedChars[10] = " 32128 0";
int R, G, B;
char red[3];
red[0] = receivedChars[0];
red[1] = receivedChars[1];
red[2] = receivedChars[2];
R = atoi(red);
char green[3];
green[0] = receivedChars[3];
green[1] = receivedChars[4];
green[2] = receivedChars[5];
G = atoi(green);
char blue[3];
blue[0] = receivedChars[6];
blue[1] = receivedChars[7];
blue[2] = receivedChars[8];
B = atoi(blue);
Serial.print("red is: ");
Serial.println(red);
Serial.print("red length: ");
Serial.println(strlen(red));
Serial.print("R is: ");
Serial.println(R);
Serial.print("green is: ");
Serial.println(green);
Serial.print("green length: ");
Serial.println(strlen(green));
Serial.print("G is: ");
Serial.println(G);
Serial.print("blue is: ");
Serial.println(blue);
Serial.print("blue length: ");
Serial.println(strlen(blue));
Serial.print("B is: ");
Serial.println(B);
delay(10000);
}void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
char receivedChars[10] = " 32128 0";
int R, G, B;
char red[3];
red[0] = receivedChars[0];
red[1] = receivedChars[1];
red[2] = receivedChars[2];
R = atoi(red);
char green[3];
green[0] = receivedChars[3];
green[1] = receivedChars[4];
green[2] = receivedChars[5];
G = atoi(green);
char blue[3];
blue[0] = receivedChars[6];
blue[1] = receivedChars[7];
blue[2] = receivedChars[8];
B = atoi(blue);
Serial.print("red is: ");
Serial.println(red);
Serial.print("red length: ");
Serial.println(strlen(red));
Serial.print("R is: ");
Serial.println(R);
Serial.print("green is: ");
Serial.println(green);
Serial.print("green length: ");
Serial.println(strlen(green));
Serial.print("G is: ");
Serial.println(G);
Serial.print("blue is: ");
Serial.println(blue);
Serial.print("blue length: ");
Serial.println(strlen(blue));
Serial.print("B is: ");
Serial.println(B);
delay(10000);
}
Output:
red is: 32U
red length: 5
R is: 32
green is: 128 32U
green length: 8
G is: 128
blue is: 0128 32U
blue length: 11
B is: 128