天天看点

Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯

文章目录

  • ​​设备连接​​
  • ​​应用下载​​
  • ​​配置过程​​
  • ​​note​​

设备连接

USB 串口交叉连线即可。

Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯
Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯

应用下载

Win10 应用商店,串口调试助手下载:

Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯

界面如下,当串口连接后,切记打开串口:

Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯

配置过程

  1. ssh 连接到树莓派
  2. ​sudo raspi-config​

    ​​
    Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯
    Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯

选择关闭串口登录功能,打开硬件串口调试功能,后者设置与否无所谓,本次实验采用软件串口进行,重点是关闭串口登录功能,因为涉及到串口的占用问题。

Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯
Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯

重点是下图:

Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯

默认将​​

​cmdline.txt​

​​ 修改保存到 ​

​/boot/​

​​, 但是树莓派4B的启动文件在 ​

​/boot/firmware​

​​ 下,故:将 ​

​/boot/firmware​

​​ 下的 ​

​cmdline.txt​

​​ 先保存到 ​

​/boot/​

​ 下,再经过 ​

​raspi-config​

​​ 配置完毕后,将​

​/boot/​

​​ 中修改后的 ​

​cmdline.txt​

​​ 文件,拷贝到 ​

​/boot/firmware​

​ 下即可。

最终效果如下,等到系统启动一半之后,串口调试工具中显示的输出就会终止,因为我们关闭了串口调试功能。

Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯

3. 配置完毕,构造程序如下:

Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯

使用方式:

  1. 发送数据

    ​​

    ​sudo python3 serial_send.py 123​

    ​​
    Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯
  2. 接收数据
    Python3 + 树莓派4B + ubuntu server ttyS0 实现串口通讯
    循环等待数据。

note

ubuntu@ubuntu:~/Documents$ cat /boot/firmware/cmdline.txt # 配置过后的内容# 原本内容
net.ifnames=0 dwc_otg.lpm_enable=0 console=tty1 root=LABEL=writable rootfstype=ext4 elevator=deadline rootwait fixrtc
ubuntu@ubuntu:~/Documents$ cat /boot/firmware/cmdline_backup.txt # 原本内容
net.ifnames=0 dwc_otg.lpm_enable=0 console=serial0,115200 console=tty1 root=LABEL=writable rootfstype=ext4 elevator=deadline rootwait fixrtc