用C进行串口读写 [英] Serial port reading and writing with C
问题描述
我正在编写一个C程序,该程序将在串行端口中进行读写操作.每次写操作之后都会有一个读操作,该读操作将包含基于写操作的数据.我将执行大约16种不同的写操作,每个写操作之后都会进行读操作.
I am writing a C program that will read and write from/to a serial port. Each write will be followed by a read which will contain data based on the write. I will have about 16 different writes to perform, each followed by a read.
我对串行编程还是陌生的,并且正在尝试确定如何实现此目的.程序是否应该在每次写/读期间阻塞(基本上是一个大的while(1)读和写循环)?
I am still new to serial programming and am trying to determine how to approach this. Should the program block during each write/read (basically having a big while(1) loop of writes and reads)?
是否有可能一个线程发送写操作而另一个线程执行读操作?可以创建一个回调来允许线程知道何时可以从串行端口读取数据吗?
Is it possible to have one thread sending writes while another thread performs the reads? Can a callback be created for allowing a thread to know when data is available to be read from the serial port?
感谢您的帮助.
操作系统:Linux
OS: Linux
推荐答案
这听起来像一个简单的循环,只需进行读取和写入即可.如果您想要更多控制权(例如,在X秒钟无输入后编写保持活动状态),请使用 select
或 poll
;它们允许您在有数据可用的情况下感知",因此 read
不会阻塞(但是,如果select和read之间发生某些情况,则您仍应非阻塞地读取).在这种情况下,多线程没有意义.
It sounds like a simple loop with a read and a write will be enough. If you want more control (like writing a keep-alive after X seconds of no input) use select
or poll
; they allow you to "sense" if data is available, so a read
will not block (however, you should still read non-blocking in case something happens between the select and the read). Multithreading doesn't make sense in this case.
select
和 poll
还可让您测试写入是否会阻塞;再次,请确保写非阻塞.通常,除了 select
或 poll
之外,您通常都不希望进程挂在某些阻塞的系统调用中.(至少我没有)
select
and poll
also allow you to test if writing will block; again, write non-blocking just to be sure. You generally don't want your process to be hanging in some blocking system call, ever, apart from select
or poll
, that is. (at least, I don't)
使用 ioctl
在串行线路上设置各种参数.使用
Use ioctl
to set various parameters on the serial line. Use
$ strace -o /tmp/strace.minicom -f minicom
启动minicom(或任何其他终端程序),并查看它们如何使工作正常(如果您遇到问题).和往常一样,请参阅 man select/poll/read/ioctl
了解更多信息.
to launch minicom (or any other terminal program) and see what they do to get things working, if you're stuck. And as always, see man select/poll/read/ioctl
for more information.
这篇关于用C进行串口读写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!