Linux シリアルポート 非同期読み書きを実装する方法

Linuxシステムでは、ファイルIOを使用してシリアルポートの読み書き操作を実行できます。手順は次のとおりです。

  1. 開く
int fd = open("/dev/ttyS0", O_RDWR);
if (fd < 0) {
perror("Failed to open serial port");
return -1;
}
  1. tcgetattr()
  2. tcsetattr()
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600); // 设置波特率为9600
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD); // 使能接收器和本地模式
options.c_cflag &= ~PARENB; // 无奇偶校验位
options.c_cflag &= ~CSTOPB; // 1位停止位
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8; // 数据位为8位
tcsetattr(fd, TCSANOW, &options);
  1. ネイティブに選択する
  2. ファイルディスクリプタ群
  3. セット(FD_SET())
  4. セレクトする
  5. 読みます
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(fd, &readfds);
struct timeval timeout;
timeout.tv_sec = 1; // 设置超时时间为1秒
timeout.tv_usec = 0;
int ret = select(fd + 1, &readfds, NULL, NULL, &timeout);
if (ret <= 0) {
perror("Failed to read data");
return -1;
}
if (FD_ISSET(fd, &readfds)) {
char buf[256];
int len = read(fd, buf, sizeof(buf));
if (len < 0) {
perror("Failed to read data");
return -1;
}
// 处理读取到的数据
printf("Received data: %s\n", buf);
}
  1. 書く
char buf[] = "Hello, world!";
int len = write(fd, buf, sizeof(buf));
if (len < 0) {
perror("Failed to write data");
return -1;
}
  1. 閉じる
close(fd);

シリアルポートのファイルディスクリプタを非ブロッキングモードに設定してfcntl() 関数を使用して、非同期の読み取り書き込み操作を実行できることに注意してください。これにより、データを読み取ることができない場合にブロックされないようになります。

int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);

以上の、データの解析や処理、エラー処理などの考慮が必要となる場合があります。

bannerAds