You should decide on a format that works for you.
The first choice you have is to decide between a
binary or
ASCII protocol.
Both have their pros and cons, but simply put
- ASCII is more readable, easier to debug and good if you want to hook your device up with HyperTerminal.
It is a bit more difficult to create a parser for a text based protocol, though. - A binary protocol is more compact, good if you need to transfer large BLOBs, such as images, and easier to parse.
It requires a well defined spec and for small data transfers the overhead can be large comapred to the data.
In your case where you seem to only receive data from your device and the data is numeric, I would go for an ASCII protocol.
This is an
example built on your data. If I understand correctly you have three axis with three values each.
Axis start | [ (left square bracket) | I used this character due to HTML formatting. |
Axis end | ] (right square bracket) | |
Value separator | , (comma) | |
End of line char | \n (LineFeed) | This is the default value for the NewLine property in SerialPort |
[10.333,11.444,12.555][10.333,11.444,12.555][10.333,11.444,12.555]\n
Sending data:
ACCEL_in_radian();
printf("[%6.3f,%6.3f,%6.3f]", ACCEL_XOUT, ACCEL_YOUT, ACCEL_ZOUT); printf("[%6.3f,%6.3f,%6.3f]", ACCEL_XOUT, ACCEL_YOUT, ACCEL_ZOUT); printf("[%6.3f,%6.3f,%6.3f]", ACCEL_XOUT, ACCEL_YOUT, ACCEL_ZOUT); printf('\n');
Not sure how your micro controller works. Can you print a whole string?
On the c# side you can now use the method ReadLine in order to get all data in one chunk.
For interpreting your received string you can can use this regular expression.
Regex protocolExpression = new Regex(@"\[(?<x>\d+\.\d+),(?<y>\d+\.\d+),(?<z>\d+\.\d+)\]");</z></y></x>
bool stopReading = false;
string strRecieve = "";
double x = 0.0;
double y = 0.0;
double z = 0.0;
while (!stopReading)
{
strRecieve = serialPort1.ReadLine();
MatchCollection mc = protocolExpression.Matches(strRecieve);
foreach (Match m in mc)
{
x = double.Parse(m.Groups["x"].Captures[0].Value);
y = double.Parse(m.Groups["y"].Captures[0].Value);
z = double.Parse(m.Groups["z"].Captures[0].Value);
}
}