I have a code which make some calculations using sensor values and provide two comma separated values.
float x;// initialization
float y;// initialization
//some calculations here using sensor values
Serial.print(x);Serial.print(",");Serial.print(y);
but the issue is due to some unstable situations of the sensor readings, I don't receive sensor data in same time intervals (overall delay is 1 second). I send these values to my Android device through a Bluetooth connection. At that stage, android device cannot separate two values due to lack of smoothness of the Serial.print(). Is there any way to make it smooth (like saving to a buffer before serial print or something) ?
2 Answers 2
I bet your problem has nothing to do with "smoothness" (whatever that means), but is entirely due to lack of message framing. The serial and bluetooth links do not transmit messages: they transmit only a stream of bytes, with no built-in notion of where a message ends and the next one starts. Relying on the timing of the received bytes to tell the messages apart is very unwise. You should instead use some kind of delimiter for your messages.
For text-based transmissions like yours, the most natural choice is to
send a line terminator at the end of each message. Typically a CR+LF
pair. The Serial
object has the println()
methods designed precisely
for this purpose: they send their arguments immediately followed by
CRLF:
Serial.print(x); Serial.print(","); Serial.println(y);
At the receiving end, you have to buffer all the incoming characters until you see the line termination. Then you know the message is complete and you can process it.
Are there any way to make it smooth. (like saving to a buffer before serial print or something) ?
you can use sprintf function
char buff[50];
sprintf(buff, "{i:%i,t:%lu,v1:%d,v2:%d,c:%u}", ix, events[ix].timestamp, events[ix].value1, events[ix].value2, events[ix].count);
s.print(buff);
but this will not help you, I think. if you do not print nothing else only those 3 prints, then your next loop will print the first number 'glued' to the last number from the previous loop. use for example prinln to separate them with a newline.
if you have an interrupt in work which can interrupt the execution of the loop and make the prints 'not smooth', it too will be not repaired by printing a buffer. because the interrupt disrupts the Serial too
Explore related questions
See similar questions with these tags.
cannot separate two values due to lack of smoothness
... do not use a word likesmooth
without explaining what it means