1 분 소요

Hits

ROS2 Parameter

파라미터 전역변수

cat /opt/ros/foxy/share/rcl_interfaces/msg/ParameterType.msg

/*
uint8 PARAMETER_NOT_SET=0

uint8 PARAMETER_BOOL=1
uint8 PARAMETER_INTEGER=2
uint8 PARAMETER_DOUBLE=3
uint8 PARAMETER_STRING=4
uint8 PARAMETER_BYTE_ARRAY=5
uint8 PARAMETER_BOOL_ARRAY=6
uint8 PARAMETER_INTEGER_ARRAY=7
uint8 PARAMETER_DOUBLE_ARRAY=8
uint8 PARAMETER_STRING_ARRAY=9
*/

패키지 만들기

cd robot_ws/src에서

ros2 pkg create param_tutorial --build-type ament_python --dependencies rclpy

cd param_tutorial/param_tutorial 안에 turtle_by_param.py에

import rclpy, sys
from rclpy.node import Node
from rclpy.qos import QoSProfile

from geometry_msgs.msg import Twist
from rclpy.exceptions import ParameterNotDeclaredException
from rcl_interfaces.msg import ParameterType

class ByParam(Node):
    def __init__(self):
        super().__init__('move_by_param')
        qos_profile = QoSProfile(depth=10)
        self.pub = self.create_publisher(Twist, '/turtle1/cmd_vel', qos_profile)
        self.tw = Twist()
        timer_period = 1  # seconds
        self.timer = self.create_timer(timer_period, self.move_turtle)

        self.declare_parameter('go_turtle', 'stop')

    def move_turtle(self):
        param = self.get_parameter('go_turtle').get_parameter_value().string_value
        if param =='go':
            self.tw.linear.x = 0.5
            self.tw.angular.z  = 0.25
        elif param =='stop':
            self.tw.linear.x = 0.0
            self.tw.angular.z  = 0.0
        else:
            pass
        self.pub.publish(self.tw)

        self.get_logger().info('turtle %s!' % param)
        """
        
        self.set_parameters([rclpy.parameter.Parameter(
                        'go_turtle',
                        rclpy.Parameter.Type.STRING,
                        'go'
                    )])
        """

def main():
    rclpy.init()
    node = ByParam()
    node.move_turtle()
   
    rclpy.spin(node)

if __name__ == '__main__':
    main()

cd .. 해서 setup.py에 ‘turtle_by_param = param_tutorial.turtle_by_param:main’,

entry_points={
        'console_scripts': [
            'turtle_by_param = param_tutorial.turtle_by_param:main',
        ],
    },

cd robot_ws에서 당연히 빌드 소스 하고 실행

1번 터미널

ros2 run turtlesim turtlesim_node 

2번 터미널

ros2 run param_tutorial turtle_by_param

3번 터미널

ros2 param list

/*
/move_by_param:
  go_turtle
  use_sim_time
/turtlesim:
  background_b
  background_g
  background_r
  use_sim_time
*/
ros2 service list

/*
/clear
/kill
/move_by_param/describe_parameters
/move_by_param/get_parameter_types
/move_by_param/get_parameters
/move_by_param/list_parameters
/move_by_param/set_parameters
/move_by_param/set_parameters_atomically
/reset
/spawn
/turtle1/set_pen
/turtle1/teleport_absolute
/turtle1/teleport_relative
/turtlesim/describe_parameters
/turtlesim/get_parameter_types
/turtlesim/get_parameters
/turtlesim/list_parameters
/turtlesim/set_parameters
/turtlesim/set_parameters_atomically
*/
ros2 service type /move_by_param/get_parameters

/*
rcl_interfaces/srv/GetParameters
*/

3번 터미널
현재 상황을 get으로 가져옴

ros2 param get /move_by_param go_turtle 
String value is: stop

3번 터미널
set을 해서 파라미터 설정함
파라미터로 go를 해서 거북이가 움직인다.

ros2 param set /move_by_param go_turtle go
Set parameter successful

set_param_ex.py

터미널에서 파라미터를 설정하는 것이 아니라 파이썬 코드에 os를 사용해보자.

import rclpy, os
from rclpy.node import Node
from std_msgs.msg import String
from .getchar import Getchar


class SetParamEx(Node):

    def __init__(self):
        super().__init__('set_param_ex')
        
def main(args=None):
    rclpy.init(args=args)

    node = SetParamEx()
    kb = Getchar()

    try:
        while rclpy.ok():
            key = kb.getch()

            if key == '1':
                print("go")
                os.system("ros2 param set /move_by_param go_turtle go")
            elif key == '0':
                print("stop")
                os.system("ros2 param set /move_by_param go_turtle stop")
            else:
                pass

    except KeyboardInterrupt:
        node.destroy_node()
        rclpy.shutdown()


if __name__ == '__main__':
    main()

setup.py랑 빌드 소스도 당연히

entry_points={
        'console_scripts': [
            'turtle_by_param = param_tutorial.turtle_by_param:main',
            'set_param_ex = param_tutorial.set_param_ex:main',
        ],
    },

실행

1번 터미널

ros2 run turtlesim turtlesim_node 

2번 터미널

ros2 run param_tutorial turtle_by_param

3번 터미널

ros2 run param_tutorial set_param_ex 

1 또는 0 키보드를 누르면 아래와 같이 나옴

go
Set parameter successful
stop
Set parameter successful

태그:

카테고리:

업데이트:

Comments