How to read and write data to a serial port using streams

I am creating a serial port application in which I create two streams: one of them is WRITER THREAD, which will write data to the serial port and READER THREAD, which will read data from the serial port. I know how to open, configure, read and write data to a serial port, but how to do this using streams.

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

+3
source share
3 answers

The way I did this in the past is to configure the port for asynchronous I / O using VMIN 0 and VTIME, say 5 decibeds. The purpose of this was to let the thread notice when it was time to close the application, as it might try to read, time out, check the close flag, and then try to read a little 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 recording function will look as you expected.

In your setup, make sure you install:

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, ...
...
+1
source

I enter a completely similar situation.

My themes work with this code:

HANDLE thandle; 
thandle = (HANDLE) _beginthread(ThreadProc_Read,0,&serial); // create thread
WaitForSingleObject(thandle,INFINITE);

void ThreadProc_Write(void *param)
{

    LONG    lLastError = ERROR_SUCCESS;
    printf("Thread is Running!\n");

    MpHostSendCommandReadBluetoothAddr(param);

    _endthread();

}

, . -, wirte read-thread, . , . .

0

2 , , .

.

, open, tcsetattr .. .

read(), write() . select() .

Closing the file descriptor requires attention, you must do this in a single thread to avoid problems.

0
source

All Articles