-2
I’m starting in the programming area and I’m developing a serial communication application, where, I receive data strings with some information in which I need to separate them by categories, for example:
A connection string : STX8abcdefETX<CRC>
A string of Parameters: STXNabcdefETX<CRC>
where, the CRC has two characters.
What I need to do is monitor the serial port and when the string arrives, identify the start (STX), continue reading the same until you find the (ETX), count two more characters and insert into one listbox, the content read.
Strings come all together, for example:
STX8abcdefETX<CRC>STXNabcdefETX<CRC>
Which method to use ? Because I have already used Substring
, split
, but as sizes may vary, sometimes I get the content wrong.
Follow modified code (SOLVED).
while (true)
{
posicaoSTX = bufferRx.IndexOf("STX");
if (posicaoSTX != -1)
{
posicaoETX = bufferRx.IndexOf("ETX");
if (posicaoETX != -1 && (bufferRx.Length >= (posicaoETX + 5)))
{
posicaoETX += 3;
stringFinal = bufferRx.Substring(posicaoSTX, (posicaoETX - posicaoSTX) + 2);
bufferRx = bufferRx.Remove(0, posicaoETX);
trataProtocolo(stringFinal);
}
else break;
}
else break;
}
you are receiving this STX as string, or the STX char ?
char STX = '\u0002';
??– Rovann Linhalis
Good afternoon Francisco. I receive serial data as string.
– Lapnasc
you have an example string of a complete communication cycle ?
– Rovann Linhalis
The best way to do this is with the
Regex.Split
, since I’m a bit of a layman with regex, I won’t risk making an answer just yet, but here’s the tip.– Francisco
So that means that after the whole string has 2 characters left?
– Lucas
Yes, after all ETX, it has two characters, however, they are part of the protocol and should be considered.
– Lapnasc