我学习C#串行。 我编写此代码来接收数据。 当我运行此代码时,另一个设备仅发送一次数据,但该程序接收数据两次或三次以上。 我该如何解决这个问题?
还有很多事情我不知道。请简单解释一下。 我花了一周的时间,因为我无法解决这个问题......:(
private void MainForm_Load(object sender, EventArgs e)//main form
{
serialPort1.DataReceived += new SerialDataReceivedEventHandler(EventDataReceived);
CheckForIllegalCrossThreadCalls = false;
........
........
........
}
........
........
........
void EventDataReceived(object sender, SerialDataReceivedEventArgs e)//this is receiving data method
{
int size = serialPort1.BytesToRead;// assign size of receive data to 'int size'
byte[] buff = new byte[size];// array who assign receiving data(size = int size)
serialPort1.Read(buff, 0, size);//assign receive data to 'buff'
string hexData = BitConverter.ToString(buff).Replace("-", " ");//Convert the received data into hexadecimal numbers and store to 'string hexdata'
for (int i = 0; i < size; i++)
{
tb_rx.Text = tb_rx.Text + " \r\n " + hexData;
Thread.Sleep(1000);//When I first encountered the problem, I added it because I thought the interval was too short. But I don't think this is the solution.
}
}
最佳答案
这段代码有问题:
string hexData = BitConverter.ToString(buff).Replace("-", " ");//Convert the received data into hexadecimal numbers and store to 'string hexdata'
for (int i = 0; i < size; i++)
{
tb_rx.Text = tb_rx.Text + " \r\n " + hexData;
Thread.Sleep(1000);//When I first encountered the problem, I added it because I thought the interval was too short. But I don't think this is the solution.
}
BitConverter.ToString(byte[])
已将字节数组转换为十六进制字符串序列。然后,在 for 循环中,针对收到的每个字节,将此 hexData
字符串添加到 tb_rx
(可能是一个文本框)。因此,根据您一次收到的字节数,您确实会得到重复的输出。只需将其更改为:
string hexData = BitConverter.ToString(buff).Replace("-", " ");//Convert the received data into hexadecimal numbers and store to 'string hexdata'
tb_rx.Text = tb_rx.Text + " \r\n " + hexData;
关于C# 串行数据丢失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70301287/