zoukankan      html  css  js  c++  java
  • ROS与Arduino学习(三)订阅与发布

    ROS与Arduino学习(三)订阅与发布

    Tutorial Level:HelloWorld

    Next Tutorial:用ROS的Cmake编译程序

    本节介绍如何在arduino中发布与订阅消息。他和ROS通过串口进行节点通信。

    Tips 1 订阅

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

     其中WWWW是话题的名称,hhhhh是收到消息后调用的函数函数名称。sub是实例化订阅对象的名字,也可以是别的名字。

    <std_msgs::Empty>是指传输的消息类型。也可以是整形<std_msgs::Int16>或者其他类型。
    nh.subscribe(sub);
    

    其中nh代表句柄的意思,每一个节点有一个句柄。此节点使用sub订阅对象来订阅世界中的话题。

    Tips 2 发布

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

     其中“chat”为话题名称,str_msg为消息内容。chatter是实例化发布对象的名字。

    nh.advertise(chatter)
    

     其中nh代表句柄的意思,每一个节点有一个句柄。此节点使用chatter发布对象来向世界中的话题发布消息。

    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
    
  • 相关阅读:
    爬虫再探之mysql简单使用
    python3爬虫再探之EXCEL(续)
    python3爬虫再探之EXCEL
    python3爬虫初探(五)之从爬取到保存
    python3爬虫初探(四)之文件保存
    python3爬虫初探(三)之正则表达式
    python3爬虫初探(二)之requests
    HDU5399——贪心——Too Simple
    ZOJ2829——贪心——Known Notation
    DOS命令
  • 原文地址:https://www.cnblogs.com/flyingjun/p/8933223.html
Copyright © 2011-2022 走看看