用rosserial创建一个subscriber

来源:互联网 发布:热电材料 知乎 编辑:程序博客网 时间:2024/06/07 03:47
在前面的一篇博客中,我们已经使用arduino创建了一个publisher节点,接下来将会创建一个subscriber,打开arduino IDE:
[html] view plaincopy
  1. arduino  

     选择File->Examples->ros_lib->Blink,就可以打开一个示例程序,代码如下:

[html] view plaincopy
  1. /*  
  2.  * rosserial Subscriber Example  
  3.  * Blinks an LED on callback  
  4.  */  
  5.   
  6. #include <ros.h>  
  7. #include <std_msgs/Empty.h>  
  8.   
  9. ros::NodeHandle nh;  
  10.   
  11. void messageCb( const std_msgs::Empty& toggle_msg){  
  12.   digitalWrite(13, HIGH-digitalRead(13));   // blink the led  
  13. }  
  14.   
  15. ros::Subscriber<std_msgs::Empty> sub("toggle_led", &messageCb );  
  16.   
  17. void setup()  
  18. {  
  19.   pinMode(13, OUTPUT);  
  20.   nh.initNode();  
  21.   nh.subscribe(sub);  
  22. }  
  23.   
  24. void loop()  
  25. {  
  26.   nh.spinOnce();  
  27.   delay(1);  
  28. }  

     下面看一下代码解释:
[html] view plaincopy
  1. #include <ros.h>  
  2. #include <std_msgs/Empty.h>  

     像前面的例子一样,我们需要包括ros.h,同样需要包括消息的头文件。
[html] view plaincopy
  1. ros::NodeHandle nh;  

     上面的一行代码创建了一个节点句柄,这允许我们的程序能够创建发布者和订阅者,节点句柄同样和串口通信有关系。
[html] view plaincopy
  1. void messageCb( const std_msgs::Empty& toggle_msg){  
  2.   digitalWrite(13, HIGH-digitalRead(13));   // blink the led  
  3. }  

     我们为subscriber创建了一个回调函数,这个函数必须使用一个消息的常引用作为一个参数。在我们的回调函数messageCb中,消息的类型是std_msgs::Empty,消息的名字是toggle_msg

     在回调函数中,我们可以引用toggle_msg,但是因为它是空的,所以就没有必要了。当收到一次消息时,我们让aduino板子上的LED闪烁一下。

[html] view plaincopy
  1. ros::Subscriber<std_msgs::Empty> sub("toggle_led", &messageCb );  

     上面代码使我们在话题toggle_led上建立了一个subscriber,并且类型是std_msgs::Empty。在使用Subscriber时,必须用上面<std_msgs::Empty>的这种形式,说明消息的类型。它的两个参数是它将要订阅的话题和所使用回调函数。
[html] view plaincopy
  1. void setup()  
  2. {  
  3.   pinMode(13, OUTPUT);  
  4.   nh.initNode();  
  5.   nh.subscribe(sub);  
  6. }  

     在arduino的setup函数中,你需要去初始化ros的节点句柄,告知所有将要订阅的话题,订阅你想收听的任何话题。
[html] view plaincopy
  1. void loop()  
  2. {  
  3.   nh.spinOnce();  
  4.   delay(1);  
  5. }  

     最后在loop函数中,我们调用了ros::spinOnce(),在这个函数中,所有ROS通信的回调函数都被处理。在loop函数中,我们不许要去做任何其它的处理。因为这个函数ros::spinOnce()将会传递消息给subscriber的回调函数。

     在arduino IDE中点击upload按钮,运行程序。接着运行roscore:

[html] view plaincopy
  1. roscore  

     接着运行rosserial客户端应用,它把你的arduino消息转发到ROS系统的其它部分:
[html] view plaincopy
  1. rosrun rosserial_python serial_node.py /dev/ttyACM0  

     最后你可以输入一下命令来查看你的arduino板子上的LED灯的变化情况:
[html] view plaincopy
  1. rostopic pub toggle_led std_msgs/Empty --once  

     上述命令运行一次后LED灯亮了,在运行一下次又灭了,如此反复的运行,挥发生相应的变化。
原创粉丝点击