2013-03-23 114 views
3

我试图从串口读取,但总是得到0(零)字符回来。已经阅读了“POSIX操作系统的串行编程指南”,但无法找出程序未等待(阻塞)的原因。 代码:从串口读取linux

#include <stdio.h> /* Standard input/output definitions */ 
#include <string.h> /* String function definitions */ 
#include <unistd.h> /* UNIX standard function definitions */ 
#include <fcntl.h> /* File control definitions */ 
#include <errno.h> /* Error number definitions */ 
#include <termios.h> /* POSIX terminal control definitions */ 

void main() 
{ 
    printf("Hello world\n"); 

    int fd; /* File descriptor for the port */ 
    int n; 
    int bytes; 

    char c; 

    char buffer[10]; 
    char *bufptr; 

    struct termios options; 

    fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY); 

    if (fd == -1) { 
     perror("open_port: Unable to open /dev/ttyUSB0 - "); 
    } 
    else { 
     fcntl(fd, F_SETFL, FNDELAY); 
    } 

    tcgetattr(fd, &options); 

    /* SEt Baud Rate */ 

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

    //I don't know what this is exactly 

    options.c_cflag |= (CLOCAL | CREAD); 

    // Set the Charactor size 

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

    // Set parity - No Parity (8N1) 

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

    // Disable Hardware flowcontrol 

    // options.c_cflag &= ~CNEW_RTSCTS; -- not supported 

    // Enable Raw Input 

    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); 

    // Disable Software Flow control 

    options.c_iflag &= ~(IXON | IXOFF | IXANY); 

    // Chose raw (not processed) output 

    options.c_oflag &= ~OPOST; 

    if (tcsetattr(fd, TCSANOW, &options) == -1) 
    printf ("Error with tcsetattr = %s\n", strerror (errno)); 
    else 
    printf ("%s\n", "tcsetattr succeed"); 

    fcntl(fd, F_SETFL, 0); 

    // Write to the port 
    n = write(fd, "1", 1); 

    if (n < 0) { 
     fputs("write() of 1 bytes failed!\n", stderr); 
    } 

    // Read from the port 

    //fcntl(fd, F_SETFL, FNDELAY); 

    bytes = read(fd, &buffer, sizeof(buffer)); 
    printf("number of bytes read is %d\n", bytes); 
    printf("%s\n", buffer); 
    //perror ("read error:"); 

    close(fd); 
} 

回答

0

您正在使用O_NDELAY

O_NONBLOCK或O_NDELAY

在可能时,该文件被在非阻塞模式下打开。描述符文件 上的open()或后续操作都不会导致调用进程等待 。有关FIFO(命名管道)的处理,另请参阅fifo(7)。对于 ,讨论O_NONBLOCK与必需的 文件锁和文件租约的关系,请参阅fcntl(2)。

编辑:你也在你的fcntl()调用中做同样的事情。

1

此信息最初来自于串行编程指南。

你得到一个0返回值的原因是因为该行的:

fcntl(fd, F_SETFL, FNDELAY); 

如果你想有一个正常的阻塞读,未设置该标志。

1. http://www.easysw.com/~mike/serial/serial.html#2_5_4(现已解散)

+0

这ecigs网站只字未提串行通信/编程。 – josaphatv 2014-06-30 19:21:44

+0

@josaphatv:现在是死链接。您可以尝试[此方法](http://www.netzmafia.de/skripten/buecher/linuxhackz/Programme/Seriell/linux_serial_mini_howto.pdf)。 – jxh 2014-06-30 20:13:36