使用rosserial创建一个publisher

在arduino开发人群中,经常把源代码称为“sketch”,之后,我们就会使用这个惯例。打开一个终端,启动arduino:
[html]  view plain copy
  1. arduino  

     将arduino开发板连接到电脑的usb口,在arduino IDE中进行设置。选择Tools->Board,选择你所使用的arduino开发板的类型,笔者所使用的arduino开发板是arduino UNO。设置好开发板之后,继续选择Tools->Serial Port->/dev/ttyACM0。在这个设置过程中汇出先一个问题,就是Serial Port不能选择,这是因为在Ubuntu下,默认按装的软件 brltty 
与arduino IDE有冲突。只需要将之进行卸载即可:
[html]  view plain copy
  1. sudo apt-get remove brltty  

     之后重启计算机,可以看到就可以选择了。设置完成以后,在arduino IDE中,选择File->Examples->ros_lib->HelloWorld,就打开了如下的代码:
[html]  view plain copy
  1. /*  
  2.  * rosserial Publisher Example  
  3.  * Prints "hello world!"  
  4.  */  
  5.   
  6. #include <ros.h>  
  7. #include <std_msgs/String.h>  
  8.   
  9. ros::NodeHandle nh;  
  10.   
  11. std_msgs::String str_msg;  
  12. ros::Publisher chatter("chatter", &str_msg);  
  13.   
  14. char hello[13] = "hello world!";  
  15.   
  16. void setup()  
  17. {  
  18.   nh.initNode();  
  19.   nh.advertise(chatter);  
  20. }  
  21.   
  22. void loop()  
  23. {  
  24.   str_msg.data = hello;  
  25.   chatter.publish( &str_msg );  
  26.   nh.spinOnce();  
  27.   delay(1000);  
  28. }  

     下面来看一下代码的解释:
[html]  view plain copy
  1. #include <ros.h>  
  2. #include <std_msgs/String.h>  

     上面的两行代码是任何ROS arduino 程序的一部分。你需要包含ros.h和其它可能会用到的消息的头文件。
[html]  view plain copy
  1. ros::NodeHandle nh;  

     接下来,我们创建了一个节点的句柄,它允许我们用来创建发布者和订阅者。这个节点的句柄同样与串口通信有关。
[html]  view plain copy
  1. std_msgs::String str_msg;  
  2. ros::Publisher chatter("chatter", &str_msg);  


     我们需要创建一个将要使用的发布者和订阅者。在上面的两行代码中,我们在话题chatter上创建了一个发布者。第二个参数是被发布者将来用于发布消息的一个消息的引用。
[html]  view plain copy
  1. void setup()  
  2. {  
  3.   nh.initNode();  
  4.   nh.advertise(chatter);  
  5. }  

     在arduino的setup函数中,需要去初始化节点句柄,告知那些话题将会有发布,以及订阅你想收听的话题。
[html]  view plain copy
  1. void loop()  
  2. {  
  3.   str_msg.data = hello;  
  4.   chatter.publish( &str_msg );  
  5.   nh.spinOnce();  
  6.   delay(1000);  
  7. }  

     最后在loop函数中,节点在chatter话题上发布了消息“hello world”,并且调用了ros::spinOnce(),也就是说所有ROS通信的回调都被处理。

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

[html]  view plain copy
  1. roscore  

     运行ros_serial客户端程序来把arduino发送的信息转发到ROS系统的其它部分:
[html]  view plain copy
  1. rosrun rosserial_python serial_node.py /dev/ttyACM0  

     最后,在一个终端中输入如下命令来查看你的arduino发送的消息:
[html]  view plain copy
  1. rostopic echo chatter  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值