How to create ROS message header time stamp?

15 views (last 30 days)
Trying to write a Matlab Function to retrieve ROS time and then write this time in Sec and Nsec in a ROS message. Matlab function intended to run as part of a larger Simulink model.
Tried this function:
function msg = assignString(blankMessage)
coder.extrinsic ('rostime');
coder.extrinsic ('now');
t=rostime('now'); %get rostime
blankMessage.Header.Stamp.Sec = t.Sec; %populate blank header
blankMessage.Header.Stamp.Nsec = t.Nsec; %populate blank header
msg = blankMessage;
But get error: Attempt to extract field 'Sec' from 'mxArray'.
Function 'MATLAB Function' (#260.161.162), line 7, column 33: "t" Launch diagnostic report. Component:MATLAB Function | Category:Coder error Attempt to extract field 'Nsec' from 'mxArray'.
Function 'MATLAB Function' (#260.224.225), line 8, column 34: "t" Launch diagnostic report. Component:MATLAB Function | Category:Coder error
Any help would be great! Apologies, I am fairly new to Matlab and Simulink...

Accepted Answer

Sebastian Castro
Sebastian Castro on 9 Oct 2017
Edited: Sebastian Castro on 9 Oct 2017
I got this working with 2 updates.
1. The error message you have is because the ROS time object is being returned as this mxArray format, which is a bridge between interpreted calls and C/C++ code. I had success sticking the whole unpacking of time into a separate function
coder.extrinsic ('getTime');
[s,ns] = getTime; %get rostime
where the getTime function is defined in a separate file as
function [s,ns] = getTime
t = rostime('now');
s = t.Sec;
ns = t.Nsec;
end
2. I had to explicitly define the input/output data types for the MATLAB Function block. If you look at the toolstrip while you have the MATLAB Function code open, there will be an "Edit Data" option. Here, you can set data types for the inputs and outputs.
For example, I tried your code on a message type of geometry_msgs/TwistStamped, which creates a Bus object in the workspace. The data type you have to use is then Bus: SL_Bus_testRosMsg_geometry_msgs_TwistStamped, which you can select as shown in the screenshot below. (If you don't see the bus data types created by the "Blank Message" block, hit the "Refresh data types" option in the drop-down).
- Sebastian
  2 Comments
GL
GL on 9 Oct 2017
Thank you Sebastian. I will give this a try. An chance you can share your Simlink model file? Thank you.
Sebastian Castro
Sebastian Castro on 9 Oct 2017
Sure. These are R2017b models, but you can change your Simulink preferences to open models from newer versions if needed.

Sign in to comment.

More Answers (0)

Categories

Find more on Publishers and Subscribers in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!