v26g7l 发表于 2024-2-29 15:35

C语言串口通信的示例代码

串口通信的基本原理相对通用,而具体的实现方式可能因使用的硬件、编程语言或通信协议而异。基本的串口通信的示例代码,使用的是C语言:

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

int main() {
    // 打开串口设备
    int serial_port = open("/dev/ttyUSB0", O_RDWR);
    if (serial_port == -1) {
      perror("无法打开串口");
      return -1;
    }

    // 配置串口
    struct termios tty;
    memset(&tty, 0, sizeof(tty));
    if (tcgetattr(serial_port, &tty) != 0) {
      perror("获取串口属性失败");
      return -1;
    }

    // 设置波特率
    cfsetospeed(&tty, B9600);
    cfsetispeed(&tty, B9600);

    // 设置数据位、停止位和校验位等
    tty.c_cflag |= (CLOCAL | CREAD);
    tty.c_cflag &= ~PARENB;
    tty.c_cflag &= ~CSTOPB;
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;

    // 应用设置
    if (tcsetattr(serial_port, TCSANOW, &tty) != 0) {
      perror("设置串口属性失败");
      return -1;
    }

    // 串口通信
    char buffer;
    memset(buffer, 0, sizeof(buffer));

    // 读取数据
    int n = read(serial_port, buffer, sizeof(buffer));
    if (n < 0) {
      perror("读取数据失败");
      return -1;
    }

    // 打印读取的数据
    printf("接收到的数据:%s\n", buffer);

    // 关闭串口
    close(serial_port);

    return 0;
}


FranklinUNK 发表于 2024-3-11 10:43

这是Linux操作系统的吗
页: [1]
查看完整版本: C语言串口通信的示例代码