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);
}
4

2 に答える 2

1

この情報は、最初はシリアル プログラミング ガイド1からのものです。

0戻り値を取得する理由は、次の行のためです。

fcntl(fd, F_SETFL, FNDELAY);

通常のブロッキング読み取りが必要な場合は、そのフラグを設定解除します。

1. http://www.easysw.com/~mike/serial/serial.html#2_5_4 (現在は廃止)

于 2013-03-23T16:19:32.737 に答える
0

O_NDELAY を使用しています

O_NONBLOCK または O_NDELAY

可能な場合、ファイルはノンブロッキング モードで開かれます。open() も、返されたファイル記述子に対する後続の操作も、呼び出しプロセスを待機させません。FIFO (名前付きパイプ) の処理については、fifo(7) も参照してください。O_NONBLOCK の影響と強制ファイル ロックおよびファイル リースとの関連については、fcntl(2) を参照してください。

編集: fcntl() 呼び出しでも同じことをしています。

于 2013-03-23T16:18:16.313 に答える