I am working with a microcontroller that sends data to PC’s serial port according to the format below:
Start Byte = 0x7E
Data Bytes ...........
StopByte = 0x7E
So basically I want to read this packets in a byte array. I am trying to do this using the DataReceived event of SerialPort class, but it just fails and never completely receives a good packet of data:
private List<int> _readBuffer = new List<int>();
private void Connection_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
var sp = (SerialPort)sender;
var indata = sp.ReadChar();
if (indata == 0x7E && _readBuffer.Count == 0)
_readBuffer.Add(indata);
if(_readBuffer.Count > 0 && indata != 0x7E)
_readBuffer.Add(indata);
if(_readBuffer.Count > 0 && indata == 0x7E)
{
_readBuffer.Add(indata);
//Dump packet to textbox
Invoke(new EventHandler((o, args) =>
{
foreach(var i in _readBuffer)
{
tbIn.Text += string.Format("{0:X} ", i);
}
_readBuffer = new List<int>(); //Renew the reading buffer array!
}));
}
}
I can’t figure out what can be the problem, I get only the start and end bytes to the textbox, like:
7E 7E
While I know the correct packet is:
7E 0 43 00 FF FF 0 0 7E
Looking forward to your tips/tricks!
Hmm… so let’s look at that code. I’ve added a few comments that I reference below.
You call
sp.ReadChar()at “A”At “B” you test and it equals, presumably, 0x7E and you’ve got an empty list so you add the 7E to the list.
“C” doesn’t evaluate to true because indata does in fact equal 7E
“D” does evaluate to true because indata still equals 7E and you’ve got 1 thing in the list.
So now 7E is in the list twice. You’ve just copied the same byte twice now.
Then you push the two list items into the textbox… 7E twice.
You’ve only called
sp.ReadCharonce. You need to read the rest of the data off the SerialPort if you want to get that data. Do that, and I think you’ll find all the bytes you’re looking for.