Main Content

Get and Set ROS 2 Parameters in Simulink

This example shows how to use ROS 2 parameters in Simulink® and share data over the ROS 2 network.

Create and Get ROS 2 Parameter

Open the model.

modelName = "GetAndSetROS2Parameters";
open_system(modelName)

This model uses the Get Parameter block to create a parameter myparam. The parameter is associated with the ROS 2 node that the Simulink model creates during simulation. You can specify the initial value of myparam in the block parameters for the Get Parameter block.

Get and Set ROS 2 Parameter

To set the parameter associated with the Simulink model during the simulation, you must use programmatic commands to run simulation. Start the simulation.

set_param(modelName,"SimulationCommand","start")

Pause the simulation to obtain the name of the ROS 2 node created by the Simulink model. Create a ros2param object for the node, to access its parameters.

set_param(modelName,"SimulationCommand","pause")

if get_param(modelName,"SimulationStatus") == "paused"
    nodelist = ros2("node","list");
    simNodeArr = strfind(nodelist,modelName);
    simNodeIdx = find(~cellfun(@isempty, simNodeArr));
    simNodeName = nodelist{simNodeIdx};
    paramObj = ros2param(simNodeName);
end

Continue the simulation. At each timestep, get the current value of the parameter by using the get object function on ros2param object. Then, set the new value of the parameter using the set object function. Observe the Scope showing the parameter value increase by 1 every simulation time step.

set_param(modelName,"SimulationCommand","step")
while get_param(modelName,"SimulationStatus") == "paused"
    % Get and set parameter 
    [currParam,status] = get(paramObj,"myparam");
    if status
        set(paramObj,"myparam",currParam+1);
    end
    set_param(modelName,"SimulationCommand","step")
end