Go Down

Topic: serial - read line (Read 4921 times) previous topic - next topic

goaran

Hello,

i want to receive a line of text, with variable length into a string on the arduino.
Is there a easy way to read a whole line into a string or do i have to make a loop and read it byte per byte till LF is detected?



AWOL

No, there is no single way.
It depends how you send the string too.
If you send something from the serial monitor, there is no automatic delimiter, like CR sent.
"Pete, it's a fool (who) looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.
I speak for myself, not Arduino.

robtillaart

What does a typical line looks like?
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

goaran

i send it from a python script, so i can include a LF at the end, that should not be a problem.
a typical line looks like this:

M104 P200

where the M104 stands for the command and 200 is the value to the command.

robtillaart


blocking version of getline()
Code: [Select]

void getline(char * buffer)
{
  uint8_t idx = 0;
  char c;
  do
  {
    while (Serial.available() == 0) ; // wait for a char this causes the blocking
    c = Serial.Read();
    buffer[idx++] = c;
  }
  while (c != '\n' && c != '\r');
  buffer[idx] = 0;
}

to be expanded with max chars param

drawback of this version is that it blocks, a nonblocking version is more difficult as a function as it needs to hold state.
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

goaran

thanks for the source.

the blocking should not be a problem.
i'll put a query for serial available in the loop then the function will only be executed if there is somthing to read.


robtillaart

If your strings are allways size 8 you can do:

if (Serial.available() >=8)
{
  b = getLine(buffer);
}
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Go Up