不接收串行端口 [英] Not Receive Serial Port
本文介绍了不接收串行端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在窗口应用程序中开发串口接收数据软件.
当我手动操作但将其与设备连接时,我的软件可以正常工作.
我正在使用以下代码来接收数据:
I am develop serial port receive data software in window application.
My software working fine when i operate it manually but when i connect it with device.
I am using this code to receive data:
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (comPort.IsOpen == true)
{
//Thread.Sleep(150);
bytes = comPort.BytesToRead;
comBuffer = new byte[bytes];
comPort.Read(comBuffer, 0, bytes);
string mm = ByteArrayToHex(comBuffer);
}
}
我将计时器用于其他用途和功能,并将其设置为1ms.但是当我使用Thread.Sleep(150);然后它将正常工作,所以这意味着我必须等待一些计时器才能读取完整的数据.我如何不使用Thread.Sleep做到这一点.
I am using timer for other use and function and i set it to 1ms. But when i use Thread.Sleep(150); then it will work proper so it means i have to wait for some timer to read complete data. How i do it without using Thread.Sleep.
推荐答案
问题可能是您假设当您获取DataReceived事件时,所有数据都已准备就绪-这不一定是真的.通常,您将获得多个DataReceived事件-每个字符一个,因为它们需要时间才能以位流的形式到达.当第一个角色完全到达时,您将获得第一个事件.添加Thread.Sleep可以使其他破坏者有时间到达,并且可以作为流读取.
您需要存储它们并查看完整的流,而不是仅处理每次到达的字符,这可能是通过查找某种终止符或字节数来实现的-它取决于线路另一端的设备,以及它如何与您的PC通信.
[edit]错别字-OriginalGriff [/edit]
The problem is probably that you are assuming that when you get the DataReceived event all the data is ready for you - this is not necessarily true. You will typically get multiple DataReceived events - one for each character, as they take time to arrive as a bit stream. When the first character has completely arrived, you will get the first event. Adding Thread.Sleep allows the other chatracters time to arrive, and be available to read as a stream.
Instead of processing just the characters that arrive each time, you need to store them, and look at the complete stream, probably by looking for a terminator or bytes count of some kind - it depends on teh device at the other end of the wire, and how it talks to your PC.
[edit]Typos - OriginalGriff[/edit]
这篇关于不接收串行端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文