How to pass a variable to my callback function through rossubscriber

35 views (last 30 days)
Hey guys. so i'm trying to create a call back function which looks like this:
odomCallback function
function [] = odomCallback(~,odomMsg, fig, varargin)
figure(fig);%set figure
title('callbackfigure');%set figure title
clf;
hold on;
[ x1, y1, ~ ] = OdometryMsg2Pose( odomMsg ); % convert odom message to pose vector
plot(x1,y1,'--rx');%plot figure
% plot pose vector with quiver
end
main
fig = 3;%figure 3
odomSubCallback = rossubscriber('/odom', {@odomCallback,odomMsg,fig},"DataFormat","struct");%wrong definition % doesn't work
clear odomSubCallback; %clear var
Suddenly the way i called my function in the main and how i passed my variables was wrong could someone tell me how to do it correctly.
thanks in advance

Answers (1)

Cam Salzberger
Cam Salzberger on 19 Apr 2022
Edited: Cam Salzberger on 19 Apr 2022
Hello Zakaria,
If you were to assign the NewMessageFcn subscriber property to just a callback function:
odomSub.NewMessageFcn = @odomCallback;
then the expected signature would look like:
function odomCallback(src, msg)
In this, the "src" is the subscriber and the "msg" is the ROS message that has been sent by the publisher.
You are using a cell array to pass additional arguments. For example:
odomSub.NewMessageFcn = {@odomCallback, arg1, arg2};
then the expected signature would look like:
function odomCallback(src, msg, arg1, arg2)
But you are passing "odomMsg" as "arg1" here. So your function is getting:
function odomCallback(odomSub, msgSentFromPub, originalProbablyBlankMsg, figureNumber)
I believe you should just be setting the callback to:
{@odomCallback,fig}
unless you really need that original blank message to operate on. I personally prefer to use anonymous functions to make it clear what the function signature is expected to be (also removing the "src" argument if not necessary):
odomSub.NewMessageFcn = @(~, msg) odomCallback(msg, fig);
with signature:
function odomCallback(msg, fig)
Other advice:
  • Consider passing a figure handle rather than a number. It's more guaranteed.
  • Consider specifying the message type when setting up subscribers and publishers. This helps if you run this code before setting up your publishers. It also is required for codegen, if you're interested in that.
  • It'll be more efficient to plot the location market once and then update its location in the figure, rather than clearing the figure each time and replotting.
-Cam

Products


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by