Having a tough time ensuring I receive the entire message sent by a device via Serial Port

So I'll preface this by saying that I don't have a ton of experience with C# or Serial Port communication.

I've created a simple Form app in VS2015 that eventually will do much more, but for now it is just a series of buttons that send predefined hex commands to a UHF RFID reader module, and then it displays the hex responses in a text box. This is mostly for debugging purposes at this point.

The problem I'm having, is that when I send the final command to the reader to trigger a single tag read, I don't reliably receive the entire response (I end up getting chunks of the tail-end of the correct response usually, but occasionally its chunks of the beginning. Never just a random middle bit though).

Here is the data received event:

 private void Receive(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { //serialPort1.DtrEnable = true; //serialPort1.RtsEnable = true; DateTime t = DateTime.Now; DateTime tf = DateTime.Now.AddSeconds(1); while (t < tf) { t = DateTime.Now; } int bytes = serialPort1.BytesToRead; byte[] rec = new byte[bytes]; serialPort1.Read(rec, 0, bytes); String RxString = BitConverter.ToString(rec).Replace("-", " "); SetText(RxString); } 

Here is the button that sends the command to take a tag reading:

private void btnInventory_Click(object sender, EventArgs e) { string TakeInventory = "01 00 00 F0 0F 00 00 00"; byte[] bytes = TakeInventory.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray(); serialPort1.Write(bytes, 0, bytes.Length); ; } 

(I dont really think there is any issue here)

This is my receive data event:

private void SetText(string RxString) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (this.txtReceive.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { RxString }); } else { this.txtReceive.Text = RxString; } } 

I don't need specific code fixing the issue, but any pointers would be greatly appreciated. The issue must be something with either how I'm reading from the buffer, or with how I'm actually entering the text into the text box I think.

Thanks!

by Hexane6 via /r/csharp

Leave a Reply