串行通信中的事件/中断
我想使用事件/中断从串行读取和写入。 目前,我将它置于 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); }
I want to read and write from serial using events/interrupts.
Currently, I have it in a while loop and it continuously reads and writes through the serial. I want it to only read when something comes from the serial port. How do I implement this in C++?
This is my current code:
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); }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
select
语句,它将无阻塞地检查读取和写入缓冲区并返回其状态,因此您只需在知道端口有数据时进行读取,或者在知道端口有空间时进行写入输出缓冲区。第三个示例位于 http://www.developerweb.net/forum/showthread。 php?t=2933 和相关的评论可能会有所帮助。
编辑: select 的手册页在末尾处有一个更简单、更完整的示例。 您可以在 http://linux.die.net/man/2/select 如果
man 2 select
在您的系统上不起作用。注意:掌握
select()
将允许您使用串行端口和套接字; 它是许多网络客户端和服务器的核心。Use a
select
statement, which will check the read and write buffers without blocking and return their status, so you only need to read when you know the port has data, or write when you know there's room in the output buffer.The third example at http://www.developerweb.net/forum/showthread.php?t=2933 and the associated comments may be helpful.
Edit: The man page for select has a simpler and more complete example near the end. You can find it at http://linux.die.net/man/2/select if
man 2 select
doesn't work on your system.Note: Mastering
select()
will allow you to work with both serial ports and sockets; it's at the heart of many network clients and servers.对于 Windows 环境,更原生的方法是使用 异步输入/输出。 在此模式下,您仍然使用对 ReadFile 和 WriteFile 的调用,但不是阻塞,而是传入一个回调函数,该函数将在操作完成时调用。
不过,要确保所有细节都正确是相当棘手的。
For a Windows environment the more native approach would be to use asynchronous I/O. In this mode you still use calls to ReadFile and WriteFile, but instead of blocking you pass in a callback function that will be invoked when the operation completes.
It is fairly tricky to get all the details right though.
这是发表在 c/C++ 用户期刊 a 上的文章的副本几年前。 它详细介绍了 Win32 API。
Here is a copy of an article that was published in the c/C++ users journal a few years ago. It goes into detail on the Win32 API.
这是在 Windows 上使用中断读取串行传入数据的代码
您可以看到等待中断时间内经过的时间
here a code that read serial incomming data using interruption on windows
you can see the time elapsed during the waiting interruption time