ROS2实现虚拟串口通信

发布于:2023-01-04 ⋅ 阅读:(569) ⋅ 点赞:(0)

1.下载demo文件

链接:https://github.com/JetsonHacksNano/UARTDemo

1.1安装python3-serial

sudo apt-get install python3-serial

2.下载虚拟串口模拟器socat

sudo apt-get install socat

输入指令,生成虚拟串口

socat -d -d pty,raw,echo=0 pty,raw,echo=0

虚拟端口号并不固定,在使用完之前都须开启,即终端不能关闭,否则端口号可能发生改变。如下图所示,我这次的虚拟端口号为dev/pts/2和dev/pts/3。
在这里插入图片描述

3.串口通信测试

3.1代码修改

由于端口号为dev/pts/2和dev/pts/3,故将其中一个设为发送口一个设为接收口,我将dev/pts/3设为接收口,需要对uart_example.py文件进行修改,修改完如下:

#!/usr/bin/python3
import time
import serial

print("UART Demonstration Program")
print("NVIDIA Jetson Nano Developer Kit")


serial_port = serial.Serial(
    port="/dev/pts/3",
    baudrate=115200,
    bytesize=serial.EIGHTBITS,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
)
#Wait a second to let the port initialize
time.sleep(1)

try:
    # Send a simple header
    serial_port.write("UART Demonstration Program\r\n".encode())
    serial_port.write("NVIDIA Jetson Nano Developer Kit\r\n".encode())
    while True:
        if serial_port.inWaiting() > 0:
            data = serial_port.read()
            print(data)
            serial_port.write(data)
            # if we get a carriage return, add a line feed too
            # \r is a carriage return; \n is a line feed
            # This is to help the tty program on the other end 
            # Windows is \r\n for carriage return, line feed
            # Macintosh and Linux use \n
            if data == "\t".encode():
                # For Windows boxen on the other end
                serial_port.write("\n".encode())


except KeyboardInterrupt:
    print("Exiting Program")

except Exception as exception_error:
    print("Error occurred. Exiting Program")
    print("Error: " + str(exception_error))

finally:
    serial_port.close()
    pass

3.2开启uart_example.py

 sudo python3 uart_example.py

在这里插入图片描述

3.3开启发送端口dev/pts/2

如下:发送的消息为NUIST-YYW

sudo echo NUIST-YYW  > /dev/pts/2 

3.4进入demo文件夹,使用命令运行python文件

sudo python3 uart_example.py

3.5发送端口按回车发送,接收端口接收数据

在这里插入图片描述

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到