从Linux串口读取数据

3

我正在尝试从串口读取数据,但始终返回0个字符。已经阅读了“POSIX操作系统串行编程指南”,但无法找出程序为什么不等待(阻塞)。

代码:

#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);
}
2个回答

1

这些信息最初来自串行编程指南1

你得到0的返回值是因为这一行代码:

fcntl(fd, F_SETFL, FNDELAY);

如果您希望进行普通的阻塞读取,请取消该标志。
1. http://www.easysw.com/~mike/serial/serial.html#2_5_4 (现已停用)

那个电子烟网站上没有关于串行通信/编程的任何信息。 - josaphatv
@josaphatv:这个链接已经失效了。你可以尝试使用这个教程 - jxh

0

你正在使用 O_NDELAY

O_NONBLOCK 或 O_NDELAY

尽可能以非阻塞模式打开文件。返回的文件描述符上的open()或任何后续操作都不会导致调用进程等待。对于FIFO(命名管道)的处理,另请参见fifo(7)。有关O_NONBLOCK与强制性文件锁和文件租约相结合时的影响的讨论,请参见fcntl(2)。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接