开发者

how to read and write data on serial port using threads

开发者 https://www.devze.com 2023-02-17 17:23 出处:网络
I am creating a serial port applica开发者_如何转开发tion in which i am creating two threads one is WRITER THREAD which will write data to serial port and a READER THREAD which will read data from seri

I am creating a serial port applica开发者_如何转开发tion in which i am creating two threads one is WRITER THREAD which will write data to serial port and a READER THREAD which will read data from serial port.I know how to open, configure,read and write data on serial port but how to do it using threads.

I am using LINUX(ubuntu) and trying to open ttyS0 port programming in C.


The way I have done this in the past is to set up the port for asynchronous I/O using a VMIN of 0 and a VTIME of, say, 5 deciseconds. The purpose of this was to allow the thread to notice when it was time for the application to shut down, as it could try to read, time out, check for a quit flag, and then try to read some more.

Here is an example read function:

size_t myread(char *buf, size_t len) {
    size_t total = 0;
    while (len > 0) {
        ssize_t bytes = read(fd, buf, len);
        if (bytes == -1) {
            if (errno != EAGAIN && errno != EINTR) {
                // A real error, not something that trying again will fix
                if (total > 0) {
                    return total;
                }
                else {
                    return -1;
                }
            }
        }
        else if (bytes == 0) {
            // EOF
            return total;
        }
        else {
            total += bytes;
            buf += bytes;
            len -= bytes;
        }
    }

    return total;
}

The write function would look as you would expect.

In your setup function, make sure to set:

struct termios tios;
...
tios.c_cflag &= ~ICANON;
tios.c_cc[VMIN] = 0;
tios.c_cc[VTIME] = 5; // You may want to tweak this; 5 = 1/2 second, 10 = 1 second, ...
...


Using of a serial port from 2 threads is simple, if only one thread reads and other thread only writes.

You should use one file descriptor for the serial port.

Open and initialize it in one thread by using normal open, tcsetattr, etc functions. Then deliver the file descriptor to the other thread(s).

Now the reader thread can use read() function, and the writer can use write() function without any extra synchronization. You can also use select() in both threads.

Closing of the file descriptor needs attention, you should do it in one thread for avoiding problems.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号