Linux设备与STM32 USB串口通讯

保证STM32 USB串口虚拟成功。

复制代码
lsusb  

如果STM32单片机通过USB连接到计算机,你应该能够在输出中看到类似以下的行:

Bus XXX Device YYY: ID 0483:5740 STMicroelectronics

查看USB更多信息

复制代码
sudo dmesg | grep tty

增加了下面类似信息:

cdc_acm 1-1.4:1.0: ttyACM0: USB ACM device

好的,你的STM32设备已经被识别为一个USB ACM(Abstract Control Model)设备,对应的串口设备文件是 ttyACM0。这是一种常见的在Linux系统上与STM32通信的方式。

现在,你可以使用 ttyACM0 这个设备文件进行串口通信。例如,你可以使用 minicom 或 screen 等终端工具,或者通过编程语言(如C语言)来与STM32进行通信。

以下是一个简单的C语言代码示例,用于打开 ttyACM0 设备文件并进行读写操作:

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>

int open_serial_port(const char *port) {
    int fd = open(port, O_RDWR | O_NOCTTY);

    if (fd == -1) {
        perror("open_serial_port: Unable to open port");
    } else {
        fcntl(fd, F_SETFL, 0);
    }

    return fd;
}

void configure_serial_port(int fd) {
    struct termios tty;
    memset(&tty, 0, sizeof(tty));

    if (tcgetattr(fd, &tty) != 0) {
        perror("configure_serial_port: Error from tcgetattr");
        return;
    }

    cfsetospeed(&tty, B9600);
    cfsetispeed(&tty, B9600);

    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;

    tty.c_cflag &= ~PARENB;
    tty.c_cflag &= ~CSTOPB;

    tty.c_cflag &= ~CRTSCTS;
    tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    tty.c_oflag &= ~OPOST;

    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 5;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        perror("configure_serial_port: Error from tcsetattr");
    }
}

int main() {
    const char *port = "/dev/ttyACM0"; // 你的串口设备文件

    int serial_fd = open_serial_port(port);
    if (serial_fd == -1) {
        fprintf(stderr, "Failed to open serial port\n");
        return 1;
    }

    configure_serial_port(serial_fd);

    char buffer[256];
    memset(buffer, 0, sizeof(buffer));

    while (1) {
        int n = read(serial_fd, buffer, sizeof(buffer) - 1);

        if (n > 0) {
            buffer[n] = '\0';
            printf("Received: %s", buffer);
        } else if (n < 0) {
            perror("Error reading from serial port");
            break;
        }

        // 写入串口数据
        // write(serial_fd, "Hello, World!\n", 13);

        usleep(100000); // 100ms延迟
    }

    close(serial_fd);

    return 0;
}
相关推荐
GeW11 小时前
新质生产力路线图Linux、数据库、国产化替代一次讲透
linux
aningx13 小时前
cachyos 从 GRUB 切换到 rEFInd
linux
第404号工位14 小时前
40块钱二手瘦客户端,如何跑满家庭物联网中枢?(拒绝Docker爆盘实录)
linux·架构·node.js
骑着蜗牛撵大象32716 小时前
Linux 进程间通信之管道:从 pipe() 的内核语义到 FIFO 落地排错
android·java·linux·系统编程·fifo·管道·进程间通信
众壹新能源科技16 小时前
逆变器自带无功不够用,加装5MVar SVG后功率因数从0.85回到0.99
运维·人工智能·自动化
..Dauntless..16 小时前
【Linux】一切皆文件和缓冲区
linux·运维·服务器
QMCY_jason16 小时前
x86 ubuntu2204 无gui 安装 openeuler 2203 aarch64版本
linux·运维·服务器
重生之小比特16 小时前
【Linux系统】12 进程程序替换 自定义Shell 命令行解释器
linux·运维·服务器
考拉讲支付17 小时前
母婴亲子服务平台分账架构设计:多场景多方分账与合规清结算实践
大数据·运维·人工智能·微信小程序·架构·微信公众平台
LateFrames17 小时前
“场控软件” 如何容错与运维
运维·容错·led大屏·播控系统·场控软件