温馨提示×

怎么用C语言读取串口数据

小亿
144
2023-11-21 21:43:37
栏目: 编程语言

要使用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函数从串口读取数据,将数据存储在buffer中,并返回读取的字节数。可以根据实际情况修改缓冲区大小。

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

请注意,以上示例代码只是一个简单的示例,实际应用中需要根据需求进行适当的修改和错误处理。

0