winform串口读数据不完整问题
同学在做一个读卡器,自告奋勇给人家做个简单的上位机,结果一直出问题。上位机一次接收8004byte数据,我是直接一次读取,可是为什么读事件发生读到的只有4096个数据,还有就是存储到txt中的数据是乱码。
private void initializeSerialPort()
{
m_serialport.PortName = comboBoxSerialPortN.Text;
m_serialport.BaudRate =Convert.ToInt32( comboBoxBuadRate.Text);
m_serialport.DataBits = Convert.ToInt16(comboBoxDataBit.Text);
m_serialport.Parity = Parity.None;
//m_serialport.ReadTimeout = 1000;
switch (comboBoxStopBit.Text)
{
case"1":
m_serialport.StopBits = StopBits.One;
break;
case"1.5":
m_serialport.StopBits = StopBits.OnePointFive;
break;
case"2":
m_serialport.StopBits = StopBits.Two;
break;
}
m_serialport.ReceivedBytesThreshold = 8004;
}
private void m_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
System.Threading.Thread.Sleep(3000);
byte[] receivedData = new byte[m_serialport.BytesToRead];
int count=m_serialport.Read(receivedData,0,m_serialport.BytesToRead);
m_serialport.DiscardInBuffer();//清空接收缓冲区数据
if (count == 8004)
{
for (int i = 0,j=0; i < 8004; i += 4,++j)
{
intData[j] = System.BitConverter.ToUInt32(receivedData, i);
}
}
string serialportrece = Encoding.ASCII.GetString(receivedData);
File.AppendAllText("data.txt", serialportrece);
------解决方案--------------------需要根据协议分包,一次不代表收全,另外不要sleep
------解决方案--------------------估计是编码或者协议的问题,在读取上。我以前也碰到过读到和发生的不一致问题,结果就是编码上的问题!
------解决方案--------------------保存收到的数,判断长度;长度达到了,校验;未到,接着收