Ubuntu配置ROS2环境 使用串口通信
目录
安装ROS2
配置节点
检验
安装ROS2
Ubuntu安装ROS(2) —— 安装ROS2 humble(最新、超详细图文教程,包含配置rosdep)_ros2安装-CSDN博客
配置节点
首先创建功能包
mkdir -p ~/colcon_ws/src
cd ~/colcon_ws/src
ros2 pkg create --build-type ament_python myserial_pkg
在myserial_pkg中的myserial_pkg文件夹下新建一个myserial_node.py
代码如下:
import serial
import time
def try_open_serial_port():
"""
尝试打开串口的函数。
如果成功返回串口对象,否则返回None。
"""
try:
# 配置串口参数并尝试打开串口
serial_port = serial.Serial(
port="/dev/ttyACM0", # 串口设备文件
baudrate=115200, # 波特率
bytesize=serial.EIGHTBITS, # 数据位
parity=serial.PARITY_NONE, # 校验位
stopbits=serial.STOPBITS_ONE, # 停止位
timeout=1 # 读取超时时间
)
# 如果串口成功打开,返回串口对象
if serial_port.is_open:
print("Serial port opened successfully.")
return serial_port
else:
# 如果串口没有打开,抛出异常
raise serial.SerialException("Serial port is not open.")
except serial.SerialException as e:
# 打印串口打开失败的错误信息
print(f"Unable to open serial port: {e}")
return None
def main():
# 尝试打开串口
ser = try_open_serial_port()
if not ser:
print("Failed to open serial port. Exiting...")
return
try:
while True:
# 发送数据到串口
send_data = "Hello STM32\n".encode('utf-8')
ser.write(send_data)
print(f"Sent: {send_data.decode('utf-8').strip()}")
# 接收来自串口的数据
time.sleep(1) # 等待一段时间以确保数据接收完成
received_data = ser.readline().decode('utf-8').strip()
if received_data:
print(f"Received: {received_data}")
else:
print("No data received.")
except KeyboardInterrupt:
print("\nProgram terminated by user.")
finally:
# 关闭串口
if ser.is_open:
ser.close()
print("Serial port closed.")
if __name__ == '__main__':
main()
在myserial_pkg功能包中,setup.py中的console_scripts的方括号里添加节点
'console_scripts': [
"myserial_node = myserial_pkg.myserial_node:main",
],
配置串口权限
sudo chmod 777 /dev/ttyACM0
在package.xml添加内容
<test_depend>rclpy</test_depend>
<test_depend>std_msgs</test_depend>
构建源环境
cd ~/colcon_ws
colcon build
source ~/colcon_ws/install/setup.bash
编译
colcon build
当前终端运行myserial_node订阅者节点
ros2 run myserial_pkg myserial_node
检验
因为我MCU中运行了一个RTOS的队列串口打印,所以接收到的在windows上串口助手上是
在ROS端接收为: