ROS與Arduino學習(三)訂閱與發佈

ROS與Arduino學習(三)訂閱與發佈html

Tutorial Level:HelloWorldnode

Next Tutorial:用ROS的Cmake編譯程序python

本節介紹如何在arduino中發佈與訂閱消息。他和ROS經過串口進行節點通訊。git

Tips 1 訂閱函數

 

ros::Subscriber<std_msgs::Empty> sub("WWWW",&hhhhh);

 

 其中WWWW是話題的名稱,hhhhh是收到消息後調用的函數函數名稱。sub是實例化訂閱對象的名字,也能夠是別的名字。oop

 

<std_msgs::Empty>是指傳輸的消息類型。也能夠是整形<std_msgs::Int16>或者其餘類型。

 

nh.subscribe(sub);

 

其中nh表明句柄的意思,每個節點有一個句柄。此節點使用sub訂閱對象來訂閱世界中的話題。學習

 

Tips 2 發佈測試

 

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

 

 其中「chat」爲話題名稱,str_msg爲消息內容。chatter是實例化發佈對象的名字。ui

 

nh.advertise(chatter)

 

 其中nh表明句柄的意思,每個節點有一個句柄。此節點使用chatter發佈對象來向世界中的話題發佈消息。spa

 

chatter.publish(&str_msg);

 

 發佈消息

 Tips 3 實例程序(控制燈)

總體思路爲用Arduino訂閱一個主題「PC2Arduino」,而後Ubuntu發佈一個消息到主題中,1表明亮,0表明滅。代碼比較簡答,不解釋。

代碼以下:

 

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

ros::NodeHandle nh;

std_msgs::String str_msg;
//publish and subscribe
//
ros::Publisher pub("Arduino2PC",&str_msg);

void Control(const std_msgs::UInt16& cmd_msg)
{
  if(cmd_msg.data == 1)
  {
      digitalWrite(13, LOW);  
  }
  if(cmd_msg.data == 0)
  {
      digitalWrite(13, HIGH);  
  }

}

ros::Subscriber <std_msgs::UInt16>  sub("PC2Arduino", &Control );

char hello[]="hello world!";




void setup()
{
         pinMode(13, OUTPUT);
	nh.initNode();
	nh.advertise(pub);// publish
	nh.subscribe(sub);// subscribe 

}

void loop()
{
	str_msg.data = hello;
	pub.publish(&str_msg);//publish a message
	nh.spinOnce();
	delay(1000);


}

 

 Tips 4 測試

 

#新終端打開
$ roscore
#新終端打開
$  rosrun rosserial_python serial_node.py _port:=/dev/ttyUSB0
#新終端打開
$ rostopic pub PC2Arduino std_msgs/UInt16 1
相關文章
相關標籤/搜索