求串口读示例
Posted
技术标签:
【中文标题】求串口读示例【英文标题】:Seeking serial port read example 【发布时间】:2013-02-26 06:04:20 【问题描述】:我想在 115200,n,8,1 从 COM1 读取数据(最好是阻塞调用,但我可以添加它。而且我不需要线程)。
我能在 Stack Overflow 上找到的唯一代码是 this question(微软也有 some useful info)。
作者说他的代码有效,我不怀疑他,但是当我运行代码时,即使端口打开正确,我也没有收到任何字符(如果我用终端程序检查,数据是正在发送)。
有人可以发布一些示例 C 代码的 URL 吗?谢谢。
FWIW,这是我的代码:
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
E_boolean OpenCom1(void)
COMMTIMEOUTS timeouts;
comPorthandle = CreateFile("COM1", // Specify port device: default "COM1"
GENERIC_READ | GENERIC_WRITE, // Specify mode that open device.
0, // the device isn't shared.
NULL, // the object gets a default security.
OPEN_EXISTING, // Specify which action to take on file.
0, // default (not overlapped i/o).
NULL); // default (hTemplate must be NULL for COM devices).
if (comPorthandle == INVALID_HANDLE_VALUE)
return False;
deviceControlBlock.DCBlength = sizeof(deviceControlBlock);
if((GetCommState(comPorthandle, &deviceControlBlock) == 0))
// CodeMe: do what?
return False;
deviceControlBlock.BaudRate = CBR_115200;
deviceControlBlock.StopBits = ONESTOPBIT;
deviceControlBlock.Parity = NOPARITY;
deviceControlBlock.ByteSize = DATABITS_8;
deviceControlBlock.fRtsControl = 0;
if (!SetCommState(comPorthandle, &deviceControlBlock))
// CodeMe: do what?
return False;
#if 0
// alternative to GetCommState() and SetCommState()
// both versions succeed
if (!BuildCommDCB("115200,n,8,1", &deviceControlBlock))
// CodeMe: do what?
return False;
#endif
// set short timeouts on the comm port.
timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutMultiplier = 1;
timeouts.ReadTotalTimeoutConstant = 1;
timeouts.WriteTotalTimeoutMultiplier = 1;
timeouts.WriteTotalTimeoutConstant = 1;
if (!SetCommTimeouts(comPorthandle, &timeouts))
// CodeMe: do what?
return False;
return True;
//OpenCom1()
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
void ReadCharacterFromCom1(INPUT char *theCharacter)
DWORD numBytesRead;
numBytesRead = 0;
while (numBytesRead == 0)
ReadFile(comPorthandle, // handle of file to read
theCharacter, // store read data here
sizeof(theCharacter), // number of bytes to read
&numBytesRead, // pointer to number of bytes actually read
NULL);
return;
//ReadCharacterFromCom1()
【问题讨论】:
简单地设置你想要的端口,然后使用常规的read
调用它。
【参考方案1】:
我在这段代码中发现了一个问题:
大小(字符),替换为
大小(字符),因为你要读取一个字节,而sizeof(char*)是4或8。可能还有别的,但你需要显示更多代码。
另外,使用 Portmon 程序 http://technet.microsoft.com/en-us/sysinternals/bb896644.aspx 来查看是否接收到数据 - 您可以将其与您的程序一起运行。
【讨论】:
+1 一个很好的观点(也是我之前犯过的一个错误)。我会尽快检查并回复您。 好的,现在它正在读取字符,但它们看起来像是非 ascii 值,我只是发送文本。明天上午更多。 用 PortMon 验证这一点。 +1 但是,***.com/questions/1356470/… 说“Sysinternals Portman 仅适用于 x86 版本的 Windows。它不支持 x64(可能它的驱动程序未签名)。但是,当我使用另一个终端程序时,我正确接收数据。你用 sizeof() 回答了我的问题,所以我将奖励并提出一个关于接收垃圾的新问题。感谢来自 portmon 主页:运行:客户端:Windows XP(32 位)及更高版本(32-位)。服务器:Windows Server 2003(32 位)及更高版本(32 位)。”以上是关于求串口读示例的主要内容,如果未能解决你的问题,请参考以下文章