串口高波特率丢失字符
void DataReceived(object sender, SerialDataReceivedEventArgs e) { try { if (!serialPort.IsOpen) { return; } Byte[] receivedData = new Byte[serialPort.BytesToRead]; //创建接收字节数组 serialPort.Read(receivedData, 0, receivedData.Length); //读取数据 serialPort.DiscardInBuffer(); serialPort.DiscardOutBuffer(); string read = Encoding.ASCII.GetString(receivedData); read = read.Replace("\0", ""); } catch (Exception ex) { } }
在DataReceived方法里,使用上面的方式,在大波特率,比如115200会出现read丢字符的现象。使用下面的方式,没有出现。
void DataReceived(object sender, SerialDataReceivedEventArgs e) { try { if (!serialPort.IsOpen) { return; }
int n = serialPort.BytesToRead; byte[] buf = new byte[n]; int readLength = 0; int offset = 0; while (offset < n) { readLength = serialPort.Read(buf, 0, n - offset); if (readLength < 0) { return; } offset = offset + readLength; }
string read = Encoding.ASCII.GetString(buf); } catch (Exception ex) { } }