rosserial_arduino学习笔记3《example Publisher》

1 Hello World:创建一个Publisher

1.1 程序

我们通过为Arduino创建一个“hello world”程序来开始探索rosserial。(注意:Arduino社区经常将程序的源代码称为“sketch”,我们将使用下面的相同约定)。如果您已经按照Arduino IDE安装教程,您将能够通过从Arduino 示例菜单中选择ros_lib - > HelloWorld来打开下面的sketch。

这应该在IDE中打开以下代码:

/*
 * rosserial Publisher Example
 * Prints "hello world!"
 */

// Use the following line if you have a Leonardo or MKR1000 
//#define USE_USBCON 

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

ros::NodeHandle nh;

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

char hello[13] = "hello world!";

void setup()
{
  nh.initNode();
  nh.advertise(chatter);
}

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

1.2 程序解释

错误:No code_block found Use the following line,如果您有Leonardo或MKR1000或任何其他具有本地USB端口的设备,且该端口与Arduino UNO,MEGA不同。否则您将收到类似于以下内容的错误:

[ERROR] [1524089506.982801]: Unable to sync with device; possible link problem or link software version mismatch such as hydro rosserial_python with groovy Arduino

错误:No code_block found As a part of every ROS Arduino program,您需要包含ros.h头文件和头文件,以用于您将使用的任何消息。

错误:No code_block found Next,我们需要实例化节点句柄,这允许我们的程序创建发布者和订阅者。节点句柄还负责串行端口通信。

错误:No code_block found We need to instantiate the publishers and subscribers that we will be using。这里我们实例化一个主题名称为“chatter”的Publisher。Publisher的第二个参数是对要用于发布的消息实例的引用。

错误:No code_block found In the Arduino setup function,您需要初始化ROS节点句柄,advertise any topics being published, and subscribe to any topics you wish to listen to(太难翻译了)!

错误:No code_block found Finally,在loop函数中,节点发布“Hello World”并调用ros :: spinOnce(),这样所有的ROS回调函数就会被处理。

1.3 编写代码

要编译代码,请使用Arduino IDE中的编译功能。这与上传任何其他sketch没有什么不同。编译完成后,您将收到有关程序存储空间和动态内存使用情况的消息,类似于:

Sketch uses 9,392 bytes (29%) of program storage space. Maximum is 32,256 bytes.
Global variables use 1,356 bytes (66%) of dynamic memory, leaving 692 bytes for local variables. Maximum is 2,048 bytes.

程序存储空间不太重要,只要您使用的存储空间少于可用存储空间,您的代码就可以正常运行。

动态内存使用是你应该注意的事情,因为函数内部的局部变量,未分配的对象,中断和堆栈都可以改变你有多少可用内存。如果内存不足,您的微控制器将冻结,且没有任何的调试信息。

如果你遇到随机冻结或你的Arduino无法与ROS通信而你的代码编译得很好,但动态内存使用率很高,你可能需要减少rosserial使用的内存。有关更多信息,请参阅rosserial LimitationsNodeHandle以及ArduinoHardware

1.4 上传代码

要将代码上传到Arduino,请使用Arduino IDE中的上传功能。这与上传任何其他sketch没有什么不同。

运行代码

现在,在新的终端窗口中启动roscore

roscore

接下来,运行rosserial客户端应用程序,将Arduino消息转发给ROS的其余部分。确保使用正确的串口:

rosrun rosserial_python serial_node.py / dev / ttyUSB0

或者,如果您希望以编程方式重置Arduino,请运行:

rosrun rosserial_arduino serial_node.py _port:= / dev / ttyUSB0

这将自动提供~reset_arduino的服务端点,您可以调用该端点与按Arduino的重置按钮具有相同的效果。

最后,通过启动新的终端窗口并输入以下内容,观看来自Arduino的问候:

rostopic echo chatter

rosserial_arduino学习笔记3《example Publisher》

2 进一步阅读

有关发布者和订阅者的详细信息,请参阅rosserial / Overview。另请参阅有关更复杂数据类型的信息的limitations