ROS实战(六)|串口通信

利用Jetson Xavier和传感器模块进行串口通信

硬件连接

默认情况下,Jetson Xavier NX分配I2C和UART引脚,所有其他引脚(电源和接地除外)均分配为GPIO,建议使用下面标有其他功能的引脚。

这里我们用的是UART1,设备地址/dev/ttyTHS0.

其中,第8和10引脚就是我们需要的TXD和RXD引脚。

注意:和电脑连接调试时需要注意,USB转TTL的RXD引脚需和板子的TXD引脚连接,USB转TTL的TXD引脚需和板子的RXD引脚相连。两者的GND引脚也要连起来。

相关代码

安装相关依赖

1
pip3 install pyserial

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/python3
import time
import serial

print("UART Demonstration Program")


serial_port = serial.Serial(
port="/dev/ttyTHS1", #串口设备地址
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())
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 == "\r".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

参考资料:

https://www.jetsonhacks.com/2019/10/10/jetson-nano-uart/

https://github.com/JetsonHacksNano/UARTDemo

https://github.com/pyserial/pyserial