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

Simultaneous rosserial_arduino publisher and subscriber at different rates?

asked 2021-07-07 01:20:10 -0500

Chandra_jaoming gravatar image

Hello everyone,

Thank yuo for taking the time to read and answer my question. I am fairly new to both ROS and arduino so please pardon me if my question is simplistic. I am trying to make a ROS robot using an MCU for the low level hardware handling and I followed the rosserial_arduino tutorial to combine the publisher and subscriber into one node that can both publish and subscribe:

#include <ros.h>
#include <std_msgs/Empty.h>
#include <std_msgs/String.h>

ros::NodeHandle nh; 

std_msgs::String str_msg; 
char hello[6] = "hello"; 

ros::Publisher chatter("chatter", &str_msg); 

void messageCb(const std_msgs::Empty& toggle_msg){ 
  digitalWrite(PC13, HIGH-digitalRead(PC13));
}

ros::Subscriber<std_msgs::Empty> sub("toggle_led", &messageCb); 

void setup(){
  nh.initNode(); 
  nh.advertise(chatter); 
  nh.subscribe(sub); 
  pinMode(PC13, OUTPUT); 
  str_msg.data = hello; 
}

void loop(){
  chatter.publish(&str_msg); 
  nh.spinOnce();
  delay(1000);
}

With the delay(1000) function in loop(), both the subscribing and publishing occur at 1hz. Is there a way for the subscriber to subscribe at a higher rate, while keeping the publisher publishing at 1hz?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-07-08 11:38:20 -0500

abhishek47 gravatar image

For exactly such situations blocking delays are unadvisable. Instead, using millis will get you the delay effect without blocking loop().

Try this (code is untested):

unsigned long timeFrom = 0;
const unsigned long timeInterval = 5000;

void loop()
{
    // stuff that should be occurring every `timeInterval` milli-seconds
    if (millis() - timeFrom >= timeInterval)
    {
        chatter.publish(&str_msg);
        timeFrom = millis();
    }

    // stuff that should be occurring at loop frequency
    nh.spinOnce();
}
edit flag offensive delete link more

Comments

Now I see...thanks!

Chandra_jaoming gravatar image Chandra_jaoming  ( 2021-07-12 02:41:42 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2021-07-07 01:20:10 -0500

Seen: 139 times

Last updated: Jul 08 '21