0
$\begingroup$

Rosanswers logo

Currently learning how to use ROS and arduino. However there's an example in the tutorial that stumps me.

blink

/*   * rosserial Subscriber Example  * Blinks an LED on callback  */

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

ros::NodeHandle  nh;

void messageCb( const std_msgs::Empty& toggle_msg){
  digitalWrite(13, HIGH-digitalRead(13));   // blink the led
}

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

void setup()
{ 
  pinMode(13, OUTPUT);
  nh.initNode();
  nh.subscribe(sub);
}

void loop()
{  
  nh.spinOnce();
  delay(1);
}

ServoControl

/*
 * rosserial Servo Control Example
 *
 * This sketch demonstrates the control of hobby R/C servos
 * using ROS and the arduiono
 * 
 * For the full tutorial write up, visit
 * www.ros.org/wiki/rosserial_arduino_demos
 *
 * For more information on the Arduino Servo Library
 * Checkout :
 * http://www.arduino.cc/en/Reference/Servo
 */

#if (ARDUINO >= 100)
 #include <Arduino.h>
#else
 #include <WProgram.h>
#endif

#include <Servo.h> 
#include <ros.h>
#include <std_msgs/UInt16.h>

ros::NodeHandle  nh;

Servo servo;

void servo_cb( const std_msgs::UInt16& cmd_msg){
  servo.write(cmd_msg.data); //set servo angle, should be from 0-180  
  digitalWrite(13, HIGH-digitalRead(13));  //toggle led  
}


ros::Subscriber<std_msgs::UInt16> sub("servo", servo_cb);

void setup(){
  pinMode(13, OUTPUT);

  nh.initNode();
  nh.subscribe(sub);
  
  servo.attach(9); //attach it to pin 9
}

void loop(){
  nh.spinOnce();
  delay(1);
}

Comparing line 15 of blink and line 35 of ServoControl (basically the line with ros::Subscriber), I noticed that in blink the callback function has a & before it, which is missing from the ServoControl example. Why is this the case? When do I use the & sign, and what is it used for in this case?


Originally posted by Frank Lee on ROS Answers with karma: 5 on 2017-09-05

Post score: 0


Original comments

Comment by gvdhoorn on 2017-09-05:
"& sign" -> "address-of operator".

Comment by jayess on 2017-09-05:
@Frank Lee: You don't need to use the pre tags to format your code. Instead, please use the 101010 to format your code.

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

In both cases, the subscriber constructor is taking a function pointer as the constructor argument.

The address-of operator is optional when using a function's name as a function pointer; http://en.cppreference.com/w/cpp/language/pointer , so both uses are correct and interchangeable.


Originally posted by ahendrix with karma: 47576 on 2017-09-05

This answer was ACCEPTED on the original site

Post score: 1

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.