为了实现小车在开机后能自动启动相关功能模块需要解决两个问题
1.准备启动脚本文件加载对应的rosnode和roslaunch,整合相关节点按需要顺序进行,防止报错
2.设置开启启动脚本相关内容
既然是自启动,不能避免USB数据传输的一些问题:(后续如果出现可看这篇博客解决方法)
ubuntu工控机固定设备usb串口号(详细)_ubuntu固定串口号-CSDN博客
1.1 修改bashrc文件
1.##打开bashrc文本
sudo gedit ~/.bashrc
2.在文件末尾加入需要sourece的工作空间
source ~/xxx/devel/setup.bash
3.保存bashrc设置,若不操作则无效
source ~/.bashrc1.2 调用rosnode和roslaunch文件,注意先后顺序
1.2.1 方式1采用launch运行(参考我的如下:)
按格式进行修改
<include file="$(find “你功能包名”)/“这里填写功能包下的位置”/“你的文件名”.launch" />其中(launch-prefix="gnome-terminal --")这一串代码是将对应的功能模块单独用终端显示
注意如果你脚本是python记得加上.py,C++编译的节点不影响
<launch>
    <include file="$(find tayo01_model)/launch/tayo01_model.launch" />
     <!-- 等待第一个launch文件的节点发布某个话题 -->
    
    <include file="$(find nav_demo)/launch/demo1_navigation.launch" />
    <!-- 显示雷达避障状态 -->
    <node pkg="tayo01_model" type="scan_test.py" name="scan_test" output="screen" 
        launch-prefix="gnome-terminal --" />
    <!-- 显示键盘控制 -->
    <node pkg="tayo01_model" type="key_topic.py" name="key_topic" output="screen" 
        launch-prefix="gnome-terminal --" />
    <!-- 加载路网 -->
    <node pkg="waypoint_saver" name="marker_publisher_node" type="marker_publisher_node" />
</launch>然后直接运行该launch文件
1.2.1 方式2(没特殊要求直接采用方式1),采用python或者其他脚本运行(这里有点问题,只运行了第一个launch就是后续多个launch文件没有延时运行,代码有点问题),提前地方不变替换主函数中的对应的 launch_process(["roslaunch", "tayo01_model", "start_nav.launch"])即可,(文件类型,功能包名,文件名)
#!/usr/bin/env python
import subprocess
import time
def launch_process(command, wait=True):
    """启动一个子进程"""
    try:
        print(f"启动: {' '.join(command)}")
        process = subprocess.Popen(command)
        if wait:
            process.wait()
            if process.returncode != 0:
                print(f"命令失败: {' '.join(command)},退出码: {process.returncode}")
                exit(process.returncode)
        return process
    except Exception as e:
        print(f"启动失败: {' '.join(command)}\n错误: {e}")
        exit(1)
if __name__ == "__main__":
    try:
        # 启动第一个 launch 文件,不等待
        launch_process(["roslaunch", "tayo01_model", "start_nav.launch"])
        print("启动第一个节点")
        # 等待 5 秒(如需要)
        # time.sleep(5)
        # 启动第二个节点
        #launch_process(["roslaunch", "nav_demo", "demo1_navigation.launch"])
        # 等待 3 秒(如需要)
        #time.sleep(3)
        # 启动第三个 launch 文件
        #launch_process(["roslaunch", "package3", "third.launch"])
        print("所有任务已完成!")
    except Exception as main_error:
        print(f"脚本运行出错: {main_error}")
        exit(1)
1.3.按顺序启动节点
由于部分节点运行依赖于其他节点,所以要注意启动的顺序按自己需要进行,可以一次加入一部分分步进行测试
2. 设置开机自启动
2.1 编写run.sh自启动文件
将代码中source和launch修改为自己的,将工作和系统空间的变量source加入
#!/bin/bash
source /opt/ros/noetic/setup.bash 
source ~/learn_ws/devel/setup.bash 
roslaunch nav_pkg nav.launch
sleep 5
exit 02.2 给test.sh设置权限
#这一步必须进行(对应自己的test.sh位置)
sudo chmod +x  /home/ply1/learn_ws/run.sh
2.3 添加到系统进程
gnome-session-properties

名称随便命名,命令为该test.sh的位置,注释方便自己了解就行,修改后关闭设置
 
2.4 测试
到此完成了整个ros节点的自启动,可以重启系统测试是否可行(前面代码中加了sleep 5 会等待几秒)



















