开发者

How can I stop my program from reading the serial port buffer?

I have a working program to read data coming from the terminal. The problem is that when, for example, a data come and stop, my program keep reading from the buffer. How can I stop it from reading things that already came through the port?

Here is my code, which can also be found at pastebin

#include <ncurses.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <signal.h>
#include <unistd.h>
#include <iostream>
#include <signal.h>


int open_port(void);

int main()
{
    char dato[1];
    int fd = 0;
    fd = open_port();
    while(1)
    {
        read(fd,dato,1);
        //~ if(dato == "B")
        //~ return 0;
        printf(dato);
    }
}

int open_port(void)
{
    int fd; /* File descriptor for the port */  

    //~ fd = open("/home/tomas/ttySV1", O_RDWR | O_NOCTTY | O_NDELAY);
    fd = open("/dev/ttyUSB0", O_RDWR | O_NDELAY);
    //~ fd = open("/dev/ttyUSB0", O_RDWR);

    if (fd == -1)
    { 
        perror(开发者_运维百科"open_port: No se pudo abrir el puerto: ");
    }
    else
    {
        struct termios options;

        /*
         * Get the current options for the port...
         */

        tcgetattr(fd, &options);

        /*
         * Set the baud rates to B9600...
         */

        cfsetispeed(&options, B9600);
        cfsetispeed(&options, B9600);

        /*
         * Enable the receiver and set local mode...
         */

        options.c_cflag |= (CLOCAL | CREAD);

        /*
         * Set the new options for the port...
         */

        tcsetattr(fd, TCSANOW, &options);

        options.c_cflag &= ~CSIZE; /* Mask the character size bits */
        options.c_cflag |= CS8;    /* Select 8 data bits */

        options.c_cflag &= ~PARENB;
        options.c_cflag &= ~CSTOPB;
        options.c_cflag &= ~CSIZE;
        options.c_cflag |= CS8;

        //~ fcntl(fd, F_SETFL, 0);
        return (fd);
    }
}


O_NDELAY prevents the read from blocking. You should always check return codes. Read will return -1 and set errno to EWOULDBLOCK.

So play with return codes and errno to figure out what to do -- example:

ssize_t retval=1;
int doit=1;
while(doit)
{
 while( retval==1)
 {
    retval=read(fd, &ch, 1);
 }
 if(retval == -1)
 {
  if (errno == EWOULDBLOCK)
  {
      sleep 1;    
  }
  else
     doit=0;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜