Go Down

Topic: Serial.readBytes length issue (Read 2024 times) previous topic - next topic

STRLTech

Hello there,
I am using my Duemilanove (ATMEGA 328) with IDE v.1.05-r2
I am trying to read my serial buffer and store 12 bytes of data into 3 variables (4 bytes each, converted into single integers. However, the read function is not stopping at the correct length.

Example:
input 123456789012
output:
123456789012
56789012
9012
from the three variables, respectively. If i set the read length to anything other than 4 (i tried 3 and 2), it works fine.

any suggestions?
Thanks

Quote

void datachk() {
 if(Serial.available() > 11) {
    Serial.readBytes(grn, 4);
    Serial.readBytes(ylw, 4);
    Serial.readBytes(rd, 4);
    int green = atoi(grn);
    int yellow = atoi(ylw);
    int red = atoi(rd);
    if((green < 6000) && (green >= 0) && (yellow >= 0) && (red >= 0) && (yellow < green) && (red < yellow)) {
      countdown(green, yellow, red);
    } else {
      Serial.println(grn);
      Serial.println(ylw);
      Serial.println(rd);
      Serial.println("Invalid Times.");
    }
  } 
}


Robin2

Write a short sketch that just reads the 3 chunks into three character variables and prints them out. If it is not working properly post the full sketch - and please post the sketch within code tags (the # button) rather than quote tags.

...R
Two or three hours spent thinking and reading documentation solves most programming problems.

STRLTech

My mistake on the quote tags (long night).
Interesting, if i put:
Code: [Select]
char grn[4];
char ylw[4];
char rd[4];

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

void loop() {
if(Serial.available() > 11) {
    Serial.readBytes(grn, 4);
    Serial.readBytes(ylw, 4);
    Serial.readBytes(rd, 4);
    Serial.println(grn);
    Serial.println(ylw);
    Serial.println(rd);
  }
}

and enter: 123456789012
it reads back:
123456789012123456789012
56789012123456789012
9012123456789012

Robin2

You need to declare each of the colours as 5 chars and the last byte must be 0. That's how C/C++ defines strings. At the moment Serial.print has no means of knowing the end of the any of the colour variables.

...R
Two or three hours spent thinking and reading documentation solves most programming problems.

STRLTech

Aha. That worked perfectly. Thank you very much

Go Up