温馨提示×

c语言串口通信怎么实现

小亿
128
2023-11-21 20:53:26
栏目: 编程语言

在C语言中,可以使用相应的库函数来实现串口通信。以下是一个简单的串口通信的C代码示例:

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

int main() {
    int serial_port;
    struct termios tty;

    // 打开串口
    serial_port = open("/dev/ttyUSB0", O_RDWR);
    if (serial_port < 0) {
        perror("打开串口失败");
        return -1;
    }

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

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

    // 设置数据位、停止位和校验位
    tty.c_cflag &= ~PARENB;  // 不使用奇偶校验
    tty.c_cflag &= ~CSTOPB;  // 1个停止位
    tty.c_cflag &= ~CSIZE;  // 清除字符大小的位
    tty.c_cflag |= CS8;  // 设置字符大小为8位

    // 设置为原始模式
    tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);

    // 禁用软件流控制
    tty.c_iflag &= ~(IXON | IXOFF | IXANY);

    // 禁用硬件流控制
    tty.c_cflag &= ~CRTSCTS;

    // 保存设置
    if (tcsetattr(serial_port, TCSANOW, &tty) != 0) {
        perror("保存串口配置失败");
        return -1;
    }

    // 从串口读取数据
    char buffer[255];
    memset(buffer, '\0', sizeof(buffer));
    int bytes_read = read(serial_port, buffer, sizeof(buffer) - 1);
    if (bytes_read > 0) {
        printf("接收到的数据:%s\n", buffer);
    } else {
        perror("读取串口数据失败");
        return -1;
    }

    // 向串口写入数据
    char *message = "Hello, Serial Port!";
    int bytes_written = write(serial_port, message, strlen(message));
    if (bytes_written > 0) {
        printf("成功写入 %d 字节的数据\n", bytes_written);
    } else {
        perror("向串口写入数据失败");
        return -1;
    }

    // 关闭串口
    close(serial_port);

    return 0;
}

在代码中,首先使用open()函数打开串口设备文件(例如/dev/ttyUSB0),然后使用tcgetattr()tcsetattr()函数获取和设置串口的配置参数。配置参数包括波特率、数据位、停止位、校验位等。接下来,使用read()函数从串口读取数据,并使用write()函数向串口写入数据。最后,使用close()函数关闭串口。

请注意,上述代码仅为简单示例,并未进行错误处理和完整的数据读写操作。在实际应用中,需要根据具体需求进行修改和完善。

0