ROS2实现虚拟串口通信

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发送端口按回车发送,接收端口接收数据

在这里插入图片描述

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值