Heng30的博客
搜索 分类 关于 订阅

在Linux用户态如何使用UART?

2025-03-21

用户态使用串口进行通信也是比较常用的功能。下面的例子就实现了如何使用raspi3b串口进行收发数据?

实验环境

raspberry pi3b

Linux raspberrypi 6.1.21-v8+ #1642 SMP PREEMPT Mon Apr  3 17:24:16 BST 2023 aarch64 GNU/Linux

测试代码

// simple.c

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

int main(int argc, char *argv[]) {
    char text[256];
    struct termios options;
    int status = 0;

    int fd = open("/dev/serial0", O_RDWR | O_NDELAY | O_NOCTTY);
    assert(fd >= 0);

    options.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
    options.c_iflag = IGNPAR;
    options.c_oflag = 0;
    options.c_lflag = 0;

    // 获取参数
    // tcgetattr(fd, &options);

    tcflush(fd, TCIFLUSH);
    tcsetattr(fd, TCSANOW, &options);

    strcpy(text, "Hi from rpi3b\r\n");
    int len = strlen(text);
    int wlen = write(fd, text, len);

    printf("Wrote %d bytes over UART\n", len);
    printf("You have 5s to to send some input data over UART\n");

    sleep(5);

    memset(text, 0, sizeof(text));
    int rlen = read(fd, text, sizeof(text));
    printf("Recv %d bytes\n", len);
    printf("Recv string: %s\n", text);

    close(fd);
    return status;
}

编译脚本

#!/bin/sh

all: simple.c
        gcc -g -o simple simple.c

clean:
        -rm simple

测试

  • 安装依赖:sudo apt install screen

  • 配置树莓派串口选项:sudo raspi-config

    • Interface Options->Serial Port
    The serial login shell is disabled                       │
    The serial interface is enabled
    
  • 重启:sudo reboot

  • 查看串口信息:ls /proc/device-tree/soc/serial*

  • 通过USB连接到raspi3b,使用主机连接raspi3b:sudo screen /dev/ttyUSB0 9600

  • 编译程序:make

  • 运行程序:sudo ./simple

  • 查看screen的输出,并且在screen终端输入内容,查看simple程序输出。