订阅与发布
主要参考:https://www.cnblogs.com/flyingjun/p/8933223.html
1.在arduino IDE 输入下列代码:
#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 == 0)
{
digitalWrite(13, LOW);
}
if(cmd_msg.data == 1)
{
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(3000);
}
2.新终端打开:roscore
3.新终端打开:rosrun rosserial_python serial_node.py _port:=/dev/ttyACM0(ACM0或USB0,这是串口)
4.新端口打开:rostopic pub PC2Arduino std_msgs/UInt16 1(输入0使Arduino上13引脚的LED,输入会亮)
简要说明一下代码:Arduino作为ROS的一个节点,订阅ROS发布的消息,从而改变LED的状态。