题
我想使用事件/中断从串行中读取和写入。 目前,我有一个while循环,它不断读取和写入序列。我希望它只在某些东西来自串口时读取。我如何在C ++中实现它?
这是我目前的代码:
while(true) { //read if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL)){ //error occurred. Report to user. } //write if(!WriteFile(hSerial, szBuff, n, &dwBytesRead, NULL)){ //error occurred. Report to user. } //print what you are reading printf("%s\n", szBuff); }
解决方案
使用 select
语句,它将检查读取和写入缓冲区而不会阻塞并返回其状态,因此您只需要在知道端口有数据时读取,或者在知道端口有数据时写入输出缓冲区中的空间。
http://www.developerweb.net/forum的第三个例子/showthread.php?t=2933 和相关评论可能会有所帮助。
编辑:select的手册页在结尾附近有一个更简单,更完整的示例。您可以在 http://linux.die.net/man/2/select找到它。 a>如果 man 2 select
在您的系统上不起作用。
注意:掌握 select()
将允许您使用串行端口和套接字;它是许多网络客户端和服务器的核心。
其他提示
对于Windows环境,更原生的方法是使用异步I / O 。在这种模式下,你仍然使用对ReadFile和WriteFile的调用,但不是阻塞你传入一个将在操作完成时调用的回调函数。
尽管掌握所有细节是非常棘手的。
以下是在c / C ++中发布的文章的副本用户期刊几年前。它详细介绍了Win32 API。
这里是一个使用Windows中断读取串行传入数据的代码 你可以看到等待中断时间过去的时间
int pollComport(int comport_number, LPBYTE buffer, int size)
{
BYTE Byte;
DWORD dwBytesTransferred;
DWORD dwCommModemStatus;
int n;
double TimeA,TimeB;
// Specify a set of events to be monitored for the port.
SetCommMask (m_comPortHandle[comport_number], EV_RXCHAR );
while (m_comPortHandle[comport_number] != INVALID_HANDLE_VALUE)
{
// Wait for an event to occur for the port.
TimeA = clock();
WaitCommEvent (m_comPortHandle[comport_number], &dwCommModemStatus, 0);
TimeB = clock();
if(TimeB-TimeA>0)
cout <<" ok "<<TimeB-TimeA<<endl;
// Re-specify the set of events to be monitored for the port.
SetCommMask (m_comPortHandle[comport_number], EV_RXCHAR);
if (dwCommModemStatus & EV_RXCHAR)
{
// Loop for waiting for the data.
do
{
ReadFile(m_comPortHandle[comport_number], buffer, size, (LPDWORD)((void *)&n), NULL);
// Display the data read.
if (n>0)
cout << buffer <<endl;
} while (n > 0);
}
return(0);
}
}
不隶属于 StackOverflow