44: Read line from USB
I'm not fond of C++ so try to pretend it's just C. So the supplied readline() doesn't fit. Doing a readline that worked for me took a few tries. So, I'll share it. (I'm sure it could be better)
#define spr(x) Serial.print(x)
#define spl(x) Serial.println(x)
char Buffer[80];
int readline(char *buffer, int len)
{
int pos = 0;
int tries = 0;
char ch;
while(tries < 200) { // arb. time out
if(pos >= len) return -1;
ch = Serial.read();
if(ch > 0) {
switch (ch) {
case '\n': // Ignore new-lines
break;
case '\r': // Return on CR
return pos;
default:
if (pos < len-1) {
Buffer[pos++] = ch;
Buffer[pos] = 0;
}
}
} else { // no input ready
delay(50);
}
++tries;
}
// No end of line has been found, so return -1.
return -1;
}
void setup() {
Serial.begin(9600);
delay(3000);
Serial.println("Read line");
}
void loop() {
int ct;
if (readline(Buffer, 80) > 0) {
spr("L:");spl(Buffer);
} else {
spl("timed out");
}
}
No comments:
Post a Comment