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

How to pass the message as a non-string value for publisher and subscriber

asked 2021-03-01 20:48:10 -0500

Jefferson gravatar image

updated 2021-04-22 11:21:35 -0500

miura gravatar image

Hi,

I have been referring to a lot of Ros tutorials as I wanted to learn regarding ros. However, I saw that most of the tutorials have use the variable as string for publisher and subscriber. However, I would like to know on how to pass a float value into the message and subscribe from it.

For example, this is one of the ros finding i found online:

//Publisher
        std_msgs::String bmsg;
        std::stringstream ss;
        if (frame_checked) //Modbus receive and CRC16 check OK!!
        {
            if(bytes_read == 7)
            {
                int battery_points = (int)(frame_bytes[4]);
                float battery_percentage = battery_points * 0.4f;

            ss << "Battery " << battery_percentage << "%";
            printf("Battery: %f\n", battery_percentage);


            bmsg.data = ss.str();
            ROS_INFO("%s", bmsg.data.c_str());

            battery_pub_.publish(bmsg);
        }

        last_ctime=ros::Time::now();
        cdt=(last_ctime-current_ctime).toSec();
        printf("OK: trans_step=%d, frame_checked:ctime=%+3.3f\n",trans_step, cdt);

        frame_resend_cnt=0;
        trans_step = 0;
        //trans_step=trans_next;
        frame_sent=0;
        cdt=0;
    }
}



//Subscriber

void chatterCallBattery(const std_msgs::String::ConstPtr& msg)
    {


     ROS_INFO("I heard the information: [%f]", msg->data.c_str());

    agv_battery = msg->data.c_str();



}

ros::init(argc, argv, "agv_modbus_link_node");
ros::NodeHandle n;
ros::Subscriber battery_sub_;
    battery_sub_ = n.subscribe<std_msgs::String>("agv_battery_level", 1000, chatterCallBattery);


}

Any help would be greatly appreciated. Thank you!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-03-02 01:02:28 -0500

mgruhler gravatar image

simply change the message type to whatever you need. Check the std_msgs docs and the common_msgs docs on the wiki.

std_msgs contains Float32 and Float64 messages, among others

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2021-03-01 20:48:10 -0500

Seen: 168 times

Last updated: Mar 02 '21