How to continuously publish to a topic using classses?
Hello I have the working code below. It basically gets an input from my joystick button to act as a on and off switch (a single press will turn it on and the second press will turn it off). However, the output I get from this code are the following:
1st press:
data: True
data: False
2nd press:
data: False
data: False
I want to continuously see the output of the topic and not only when I press the button. Here is my code:
#include <ros/ros.h>
#include <std_msgs/Float32.h>
#include <sensor_msgs/Joy.h>
#include <std_msgs/Bool.h>
class Override
{
public:
Override();
private:
void joyCallback(const sensor_msgs::Joy::ConstPtr& joy);
ros::NodeHandle nh_;
ros::Publisher override_pub;
ros::Subscriber joy_sub_;
bool currentReading;
bool lastReading;
bool flag;
};
Override::Override()
{
override_pub = nh_.advertise<std_msgs::Bool>("override_status", 1);
joy_sub_ = nh_.subscribe<sensor_msgs::Joy>("joy", 10, &Override::joyCallback, this);
}
void Override::joyCallback(const sensor_msgs::Joy::ConstPtr& joy)
{
std_msgs::Bool override_status;
if (joy->buttons[4] == 0.0){
currentReading = false;
}else currentReading = true;
if (currentReading && !lastReading) {
flag=!flag;
if (flag) {
override_status.data = true;
}
else {
override_status.data = false;
}
}
lastReading = currentReading;
override_pub.publish(override_status);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "override_node");
Override override;
ROS_INFO("Running");
ros::spin();
}
I tried putting while(ros::ok()) but I don't know where to insert it.
You mean that you have the output only when the button is pressed ? Normally a joystick is continously publishing its data, can you tell us what is the publishing rate of the topic joy ? (
rostopic hz /joy
)But what you can do is :
Create a thread in the constructor of the class
boost::thread t = boost::thread(boost::bind(&spinthread));
Use the thread to spin
void spinthread() { ros::spin() }
Create a global variable in the callback and publish it in the main
(publishing inside a while(ros::ok()) loop)
I can see joy publishing perfectly with rostopic echo joy. But I want to continuously output the state of the button where it is pressed once (ON state = True) or pressed a second time (Off state = False).