版本说明
matlab R2021b
ROS noetic
matlab与ROS通信连接
在matlab和ROS连接之前,需要先运行ROS核心,记录ROS端的IP地址。
再查找并记录matlab端(我这里是windows)的IP地址。
在matlab中运行脚本,建立matlab在ROS中的节点:
setenv('ROS_MASTER_URI','http://192.168.1.100:11311/');%ROS核心IP地址
setenv('ROS_IP','192.168.1.200');%matlab端IP地址
rosinit
matlab订阅ROS话题并画图
代码
clear;clc;
close all
tim=0;
%话题订阅,参数1为话题名称,参数2为数据类型
sub=rossubscriber("/MOTOR_STATE","actuatorcontroller_ros/motor_state");
pos=[];
refpos=[];
figure(1);
h1=animatedline('color','b');
h2=animatedline('color','r','marker','.');
while(tim<20)
msg=receive(sub,1000);%接收新数据
tim=msg.Time;
pos(end+1)=msg.Position;
refpos(end+1)=msg.Refposition;
addpoints(h1,tim,msg.Position);%实时添加实际位置
hold on;
addpoints(h2,tim,msg.Refposition);%实时添加参考位置
drawnow; %立刻绘图
end
说明
话题名称:/MOTOR_STATE;
数据类型:actuatorcontroller_ros/motor_state(自定义消息类型,这种数据类型在运行前需要提前编译好,并加载到matlab的ROS工具箱中);
订阅函数:rossubscriber函数官网给的例程有两种调用方式,一种是回调函数操作,一种是使用receive函数接收数据。我都尝试了一下,这两种方式貌似都只能调用一次新数据,所以我这里使用while循环不断调用新数据。