yuffy
yuffy

Reputation: 21

Linux serial port reading in asynchronized mode

I have a trouble in reading datas from serial in Linux system. I am trying to connect a sensor with the linux system by using UART. I can read and write /deve/ttyS1. But the problem is that I dont want to poll the message from UART. Instead, I want to use the asynchronized mode to get the data. As the data comes, the call back function will enter a certain routine and run my code. The problem no is that the sensor sends me different packets and each one contains various bytes of data. They are coming every one second!

For example:

Time              Sensor          MyLinux
1s                        50bytes
                          124bytes
2s                        40bytes
                          174bytes
3s                        60bytes
                          244bytes

My question is how to use the asynch serial programming so that in the call back function, those two packets can be read as two messages

say 50 bytes comes, the call back function can let me read 50 bytes 127 bytes comes, the call back function can let me read 127 bytes

Now, its like, 50 bytes comes, I can only read 27bytes, and the rest 23 are in the next message.

My setting for serial port in POSIX is:

    /* now we setup the values in port's termios */
    serial->tio.c_cflag=baudrate|databits|checkparity|stopbits|CLOCAL|CREAD;
    serial->tio.c_iflag=IGNPAR;
    serial->tio.c_oflag=0;
    serial->tio.c_lflag=0;
    serial->tio.c_cc[VMIN]=28;
    serial->tio.c_cc[VTIME]=6;

    /* we flush the port */
    tcflush(serial->fd,TCOFLUSH);
    tcflush(serial->fd,TCIFLUSH);

    /* we send new config to the port */
    tcsetattr(serial->fd,TCSANOW,&(serial->tio));

Upvotes: 2

Views: 2140

Answers (1)

yegorich
yegorich

Reputation: 4849

Try to set VMIN and VTIME at following values:

serial->tio.c_cc[VMIN]=0;
serial->tio.c_cc[VTIME]=1;

Then you'll come out of select() after reading a complete chunk of data from your sensor. If the number of bytes is less, than you've expected, you can set timeout for select and read the data once more appending to your current buffer. If you get data before the timeout, then you have your complete message.

Upvotes: 1

Related Questions