Hi,
I have an Ultrasonic Sensor that outputs it's data as cms, this is then sent over a bluetooth serial port.
I have an app on my Android phone that requests bluetooth data in x bytes, then display it on screen.
I am requesting 3 bytes as the max distance can be XXXcms, and the smallest Xcms.
How can I always ensure that the data I am sending over the serial port is 3 characters long?
eg:
1cms = "1 "
123cms = "123"
45cms = "45 "
I am using the URM libray:
urm.requestMeasurement(DISTANCE);
if(urm.hasReading())
{
int value;
switch(urm.getMeasurement(value))
{
case DISTANCE:
Serial.print(value); // Need to make this 3 bytes, regardless of value.
}
}
Any ideas?
Thanks!
That's a pain with the Arduino Serial.print, have a look at the standard C function sprintf(), you can use that to format data into a string in memory then print the string.
Rob
I have found:
case DISTANCE:
char dvalue[3];
sprintf(dvalue, "%3d", value);
Serial.println(dvalue);
Seem to be getting somewhere.
How can I always ensure that the data I am sending over the serial port is 3 characters long?
Sending 3 characters in every packet does NOT translate to receiving 3 characters in every packet. You should not expect that every byte sent will be received. You should find another way to indicate the end of the packet, and learn to deal with variable length packets.
From memory "%03d" will pad with 0s which can be useful.
I'd also add some delimiting characters so you can sync on the data. Getting something like "<002>" makes it much easier to detect errors.
Rob