问题描述
我是 C# 的初学者,想要一些有关如何解决以下问题的建议:
我的主要代码包括 2 个线程,第一个线程用于发送数据,第二个线程用于从串行通信中读取数据。当我按下开始按钮时,通信开始在两个 while 循环中工作。
private void btn_Click(object sender,EventArgs e)
{
beri_podatke = true;
Thread read_thr = new Thread(read);
read_thr.Start();
}
第一个线程(发送数据):
private void read()
{
while (read_data_on)
{
if (sinh == 1 )
{
serialPort1.Write(new byte[] { 0x55,0x40,0x05 },3);
serialPort1.Write(new byte[] { 0x55,0x1c },2);
sinh = 2;
}
if (sinh == 3 )
{
serialPort1.Write(new byte[] { 0x55,0x65 },2);
sinh = 4;
}
}
第二个线程(接收数据):
private void serialPort1_DataReceived(object sender,SerialDataReceivedEventArgs e)
{
while (read_data_on)
{
if (sinh == 2 )
{
byte[] input1 = new byte[3];
int st_bajtov1 = serialPort1.Read(input1,3);
vrednost1 = (input1[2] << 16) | (input1[1] << 8) | (input1[0]);
sinh = 3;
}
if (sinh == 4 )
{
byte[] input2 = new byte[3];
int st_bajtov2 = serialPort1.Read(input2,3);
vrednost2 = (input2[2] << 16) | (input2[1] << 8) | (input2[0]);
sinh = 1;
}
}
}
问题是设备和电脑之间的通信速度太慢了。我使用的是 115200 波特率,我得到的最大发送数据频率为 300 Hz - 350 Hz。
我想要两倍甚至更多的速度,因为我正在读取测量设备的寄存器并且我需要更多的样本来获得我的硕士学位。我禁用了所有其他代码,如计算、字符、标签等,并且对发送速度没有影响。程序在酷睿 i9 PC 上运行。可能有什么问题或有解决方案吗?
解决方法
“支配约束”很明显是硬件。