簡單測試ROS裏面C++ 和 python 文件獲取參數格式

測試的是從參數文件獲取參數

先看python 文件,test.py文件 從 test.yaml 參數文件獲取參數,

測試的變量爲 base_frame  和 base_frame1,分別獲取的同一個參數。代碼如下:

#test.py

import rospy
from geometry_msgs.msg import Twist


class ArduinoROS():
    def __init__(self):
        # 唯一的節點名 日誌級別爲DEBUG 等級排序爲 DEBUG INFO WARN ERROR FATAL
        rospy.init_node('Arduino', log_level=rospy.DEBUG)
        # self. 變量, 從 .yaml 獲取參數
        self.base_frame = rospy.get_param("~base_frame", 'base_link')
        self.base_frame1 = rospy.get_param("base_frame", 'base_link')

        rospy.on_shutdown(self.shutdown)

        while not rospy.is_shutdown():
            print "param : " + self.base_frame + "  " + self.base_frame1
            rospy.sleep(1)

    def shutdown():
        print "shut down node..."
        
if __name__ == '__main__':
    myArduino = ArduinoROS()
# test.yaml

base_frame: base_footprint

測試結果在最後,

然後再看C++文件,test1.cpp 文件從 test1.yaml 參數文件獲取參數。

測試變量是 port 和 cfg_baud_rate_ ,獲取不同的參數,代碼如下:

// test1.cpp

using namespace std;

int main(int argc, char **argv)
{
    ros::init(argc, argv, "test1");
    ros::NodeHandle nh;
    serial::Serial ser;
    std::string port;
    int cfg_baud_rate_ = 48500;
    std::string imu_frame_id;

    nh.param<std::string>("/test1/port", port, "/dev/tty123");
    nh.param<int>("/test1/imu_baudrate", cfg_baud_rate_, 9600);
    nh.param<std::string>("/test1/imu_frame_id", imu_frame_id, "imu_base");

    ros::Rate r(1);

    while (ros::ok())
    {
        std::cout << "port : " << port << "  ,rate : " << cfg_baud_rate_ 
        << "  ,frame : " << imu_frame_id << std::endl;
        r.sleep();
    }
    return 0;
}
# test1.yaml

port: /dev/ttyIMU
imu_baudrate: 115200
imu_freq: 100
angle_offset: 0.99

測試結果如下截圖:

結論:

python 文件中,

rospy.get_param("~base_frame", "base_link") 會先獲取 test.yaml參數文件裏面的參數

rospy.get_param("base_frame", "base_link")  則會獲取當前代碼中的參數

 

C++文件中

nh.param<std::string>("/test1/port", port, "/dev/tty123"); 先獲取test1.yaml文件裏面的參數

nh.param<int>("/test1/imu_baudrate", cfg_baud_rate_, 9600); 先定義了參數,也會獲取test1.yaml文件裏面的參數。

 

後續有更多測試,再持續更新,先這樣。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章