C#串行端口-奇怪的行为
本文关键字:串行端口 | 更新日期: 2023-09-27 18:22:17
我正在尝试使用串行端口与相机接口。现在,该相机有了自己的专有协议,该协议相当简单,使用6字节的命令和确认。
现在,我正在使用C#编写与相机接口的程序,因为这允许我使用WPF,而且我对C#很满意。
当我试图设置相机来检索图像时,我的问题就出现了。当我逐步完成程序时,Serial Port对象可以很好地执行此操作。然而,一旦我全速运行它,由于某种原因,我最终会发现端口上的消息被严重读取,甚至被遗漏。我到了设置过程的末尾,就在我开始检索实际数据之前,仍然有命令和东西在端口的缓冲区中。
现在,无可否认,这个解决方案只是一个非常巧妙的尝试,目的是学习协议并使其在当前发挥作用,我完全打算稍后对其进行改进,但我不明白它为什么会这样做。在我确认最后一个数据包之前,相机不应该发送下一个数据,所以我只能假设串行端口对象有问题,而不是相机或我对协议的处理。
可能是因为我(懒洋洋地,是的)在UI线程上获得了这个函数吗?
这是代码:
private void retreivePhoto()
{
progressBar1.Visibility = Visibility.Visible;
photo = new FileStream(Environment.CurrentDirectory + @"/photos/" + (photoNum++) + ".jpg", FileMode.OpenOrCreate);
port.Open();
progressBar1.Value = 0.5;
setup.theMessage = setup.JPEG();
port.Write(setup.theMessage, 0, setup.theMessage.Length);
while (port.BytesToRead < 0) ;
port.Read(received.theMessage, 0, received.theMessage.Length);
setup.theMessage = setup.Package();
port.Write(setup.theMessage, 0, setup.theMessage.Length);
while (port.BytesToRead < 0) ;
port.Read(received.theMessage, 0, received.theMessage.Length);
setup.theMessage = (byte[])Message.SNAPSHOT.Clone();
port.Write(setup.theMessage, 0, setup.theMessage.Length);
while (port.BytesToRead < 0) ;
port.Read(received.theMessage, 0, received.theMessage.Length);
setup.theMessage = (byte[])Message.BLANK.Clone();
setup.theMessage[1] = (byte)Message.MessageTypes.GETPICTURE;
setup.theMessage[2] = (byte)Message.PictureType.SNAPSHOT;
port.Write(setup.theMessage, 0, setup.theMessage.Length);
while (port.BytesToRead < 0) ;
port.Read(received.theMessage, 0, received.theMessage.Length);
while (port.BytesToRead < 0) ;
port.Read(received.theMessage, 0, received.theMessage.Length);
int length = (received.theMessage[5] << 16) + (received.theMessage[4] << 8) + received.theMessage[3];
length /= data.theMessage.Length-6;
byte[] temp = {0xaa, 0x0e, 0x00, 0x00, 0x00, 0x00};
port.DiscardInBuffer();
port.Write(temp, 0, temp.Length);
int next = 0;
int bytes;
for (int i = 0; i < length; i++)
{
if ((bytes = port.BytesToRead) > 0)
{
port.Read(data.theMessage, 0, data.theMessage.Length);
if (bytes < data.theMessage.Length)
{
photo.Write(data.theMessage, 4, bytes - 6);
}
else
{
photo.Write(data.theMessage, 4, data.theMessage.Length - 6);
}
photo.Flush();
}
next = ((data.theMessage[1] << 8) + data.theMessage[0]) + 1;
byte[] nextBytes = System.BitConverter.GetBytes(next);
if (length - i == 1)
{
temp[4] = temp[5] = 0xf0;
}
else
{
temp[4] = nextBytes[0];
temp[5] = nextBytes[1];
}
port.Write(temp, 0, temp.Length);
}
progressBar1.Value = 1.0;
photo.Flush();
photo.Close();
port.Close();
progressBar1.Visibility = Visibility.Hidden;
}
这是相机的数据表,其中描述了协议。http://www.4dsystems.com.au/downloads/micro-CAM/Docs/uCAM-DS-rev7.pdf
while (port.BytesToRead < 0) ;
port.Read(received.theMessage, 0, received.theMessage.Length);
并不意味着您将读取received.theMessage.Length
字节。它可以是介于1&CCD_ 2。您应该检查返回值