Recently, serial communication programming is involved in the project. When my teammates are working on this module, they encounter a problem that many people may encounter, that is, receiving data conflicts or loss. It took nearly two hours for my teammates to solve the problem when I asked him to debug it. Now I think it is necessary to summarize it to give a thought to a friend who encountered similar problems ~
The problem is that a 15-byte data is sent every two seconds from the corresponding hardware device, storing hexadecimal data, each data entry starts with 7E and ends with 7E. Example: 7E 09 01 1A... 7E. However, the PC end encountered a problem when accepting the display. For example, if the first five data items were accepted normally, the next step would be to fill them with 00, the remaining 10 data items are displayed in the next data display position. As follows:
7E 09 01 1A 5C 00 00 00 00 00 00 00 00 00 00 // 03 06 1A 2C 3D 09 6C 32 12 7E 00 00 00 00 00 00 00 // /////........
In short, it feels wrong. By the way, paste the PC code first:
Public partial class Form1: Form
{
/// <Summary>
/// Serial port for receiving data
/// </Summary>
SerialPort spReceive;
Delegate void upload data (byte [] bytes );
Public Form1 ()
{
Form1.checkforillegalcrossthreadcils = false;
InitializeComponent ();
SpReceive = new SerialPort ("COM5", 57600, Parity. None, 8, StopBits. One );
SpReceive. Open ();
// Set the threshold value that triggers the DataReceived event. This parameter does not work during debugging ~
SpReceive. ReceivedBytesThreshold = 15;
SpReceive. DataReceived + = new System. IO. Ports. SerialDataReceivedEventHandler (spReceive_DataReceived );
}
/// <Summary>
/// Update the received data to the UI display
/// </Summary>
/// <Param name = "bytes"> <