ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
3

Publish on a Topic for a certain time

asked 2017-10-27 09:18:17 -0600

Mobile_robot gravatar image

Hi,

I would like to know if it is possible to publish on a topic for a certain time (fixed before publishing).

For example, I want to publish a linear velocity (geometry_msgs/Twist Message) for 3 seconds and then robot stops.

Thanks,

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
1

answered 2017-10-27 11:45:09 -0600

psammut gravatar image

updated 2022-02-25 08:28:01 -0600

lucasw gravatar image

You should create your own node that will do this. You can do this in c++ or python.

Follow the Writing a Simple Publisher and Subscriber tutorial that teaches you how to make a publisher and subscriber node. You are only concerned with making a publisher node, but if you haven't done these tutorials, you should.

Here's the c++ version: http://wiki.ros.org/ROS/Tutorials/Wri...

Here's the python version: http://wiki.ros.org/ROS/Tutorials/Wri...

Here is an example with UNTESTED CODE of how you would do this in c++:

#include "ros/ros.h"
#include "geometry_msgs/Twist.h"


int main(int argc, char **argv)
{

  ros::init(argc, argv, "talker");

  ros::NodeHandle n;

  // Advertize the publisher on the topic you like
  ros::Publisher pub = n.advertise<geometry_msgs::Twist>("my_topic_name", 1000);

  while (ros::ok())
  {
    /**
     * This is a message object. You stuff it with data, and then publish it.
     */
    geometry_msgs::Twist myTwistMsg

    // Here you build your twist message
    myTwistMsg.linear.x = 1;
    myTwistMsg.linear.y = 2;
    myTwistMsg.linear.z = 3;

    ros::Time beginTime = ros::Time::now();
    ros::Duration secondsIWantToSendMessagesFor = ros::Duration(3); 
    ros::Time endTime = beginTime + secondsIWantToSendMessagesFor;
    while(ros::Time::now() < endTime )
    {
        pub.publish(msg);

        // Time between messages, so you don't blast out an thousands of 
        // messages in your 3 secondperiod
        ros::Duration(0.1).sleep();
    }

  return 0;
}
edit flag offensive delete link more

Comments

1

Thanks a lot for your help!

Mobile_robot gravatar image Mobile_robot  ( 2017-10-30 02:47:41 -0600 )edit
1

Thank you so much bro!

أسامة الادريسي gravatar image أسامة الادريسي  ( 2017-11-04 01:35:32 -0600 )edit

Question Tools

2 followers

Stats

Asked: 2017-10-27 09:18:17 -0600

Seen: 6,065 times

Last updated: Feb 25 '22