C言語でシリアルポートデータをどのように読み込むか

シリアルポートデータをC言語で読み取るには、次の手順に従います。

  1. ヘッダーファイルのインクルード
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
  1. シリアルポートを開く
int serial_fd = open("/dev/ttyS0", O_RDWR);
if (serial_fd == -1) {
    perror("无法打开串口");
    exit(1);
}

ここでは、/dev/ttyS0がシリアルデバイスのパスで、Linuxシステムでは通常、/dev/ttyS0または/dev/ttyUSB0です。実際的情況に応じて変更する必要があります。

  1. シリアルポートを設定する
struct termios options;
tcgetattr(serial_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(serial_fd, TCSANOW, &options);

この設定は、ボーレート 9600、パリティなし、ストップビット 1、データビット 8 で設定されています。必要に応じて設定を変更してください。

  1. データの取得
char buffer[255];
int length = read(serial_fd, buffer, sizeof(buffer));
if (length > 0) {
    printf("读取到了%d个字节的数据:%s\n", length, buffer);
}

シリアルポートからread関数を使用してデータをバッファーに格納し、読み込んだバイト数を返します。バッファーのサイズはアプリケーションのニーズに合わせて変更できます。

  1. シリアルポートを閉じる
close(serial_fd);

完全なサンプルコードは以下の通りです。

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>

int main() {
    int serial_fd = open("/dev/ttyS0", O_RDWR);
    if (serial_fd == -1) {
        perror("无法打开串口");
        exit(1);
    }

    struct termios options;
    tcgetattr(serial_fd, &options);
    cfsetispeed(&options, B9600);
    cfsetospeed(&options, B9600);
    options.c_cflag |= (CLOCAL | CREAD);
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    tcsetattr(serial_fd, TCSANOW, &options);

    char buffer[255];
    int length = read(serial_fd, buffer, sizeof(buffer));
    if (length > 0) {
        printf("读取到了%d个字节的数据:%s\n", length, buffer);
    }

    close(serial_fd);

    return 0;
}

上記のサンプルコードは単なる簡単なサンプルであるため、実際には独自の要件に適宜変更を加えて、エラー処理を行う必要があることに注意してください。

bannerAds