使用ros实现c++与python通信

2023-05-16

想想两个节点直接只需要通过话题通信就可以了,所以一个节点用C++写,一个节点用Python写似乎没有影响啊,只要保证两者之间的通信OK就好了,就有点像通信协议,一个STM32板子和一个FPGA板子,无所谓,只要遵循同一个通信协议就可以进行通信了呀对不对。

转载自:https://blog.csdn.net/qq_41816368/article/details/88046200

使用ros实现c++python通信

河北一帆 2019-02-28 22:29:28 2224 收藏 9

最后发布:2019-02-28 22:29:28首次发布:2019-02-28 22:29:28

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/qq_41816368/article/details/88046200

版权

创建工作空间(选择在桌面创建)

cd ~
$ mkdir -p my_workspace/src

编译工作空间

$ cd my_workspace
$ catkin_make

source一下新生成的setup.bash文件:

$ source devel/setup.bash

每次打开一个终端都要source一下

要想保证工作空间已配置正确需确保ROS_PACKAGE_PATH环境变量包含你的工作空间目录,采用以下命令查看:

$ echo $ROS_PACKAGE_PATH

使用catkin_create_pkg命令来创建一个新的程序包

$ catkin_create_pkg my_pkg std_msgs rospy roscpp

查看程序包依赖关系

$ rospack depends1 beginner_tutorials
~/catkin_test/src$ rospack depends1 beginner_tutorials 
roscpp
rospy
std_msgs

返回工作空间目录

cd ~/my_workspace

编译工作空间

catkin_make

在程序包中的src文件夹中创建talker.py和listener.cpp文件

talker.py中内容为:

#!/usr/bin/env python
import rospy
from std_msgs.msg import String

def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        hello_str = "hello world %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass

listener.cpp中内容为:

#include "ros/ros.h"
#include "std_msgs/String.h"

/**
 * This tutorial demonstrates simple receipt of messages over the ROS system.
 */
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
	ROS_INFO("I lol heard: [%s]", msg->data.c_str());
}

int main(int argc, char *argv[])
{
	/**
	 * The ros::init() function needs to see argc and argv so that it can perform
	 * any ROS arguments and name remapping that were provided at the command line.
	 * For programmatic remappings you can use a different version of init() which takes
	 * remappings directly, but for most command-line programs, passing argc and argv is
	 * the easiest way to do it.  The third argument to init() is the name of the node.
	 *
	 * You must call one of the versions of ros::init() before using any other
	 * part of the ROS system.
	 */
	ros::init(argc, argv, "listener");

	/**
	 * NodeHandle is the main access point to communications with the ROS system.
	 * The first NodeHandle constructed will fully initialize this node, and the last
	 * NodeHandle destructed will close down the node.
	 */
	ros::NodeHandle n;

	/**
	 * The subscribe() call is how you tell ROS that you want to receive messages
	 * on a given topic.  This invokes a call to the ROS
	 * master node, which keeps a registry of who is publishing and who
	 * is subscribing.  Messages are passed to a callback function, here
	 * called chatterCallback.  subscribe() returns a Subscriber object that you
	 * must hold on to until you want to unsubscribe.  When all copies of the Subscriber
	 * object go out of scope, this callback will automatically be unsubscribed from
	 * this topic.
	 *
	 * The second parameter to the subscribe() function is the size of the message
	 * queue.  If messages are arriving faster than they are being processed, this
	 * is the number of messages that will be buffered up before beginning to throw
	 * away the oldest ones.
	 */
	ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);

	/**
	 * ros::spin() will enter a loop, pumping callbacks.  With this version, all
	 * callbacks will be called from within this thread (the main one).  ros::spin()
	 * will exit when Ctrl-C is pressed, or the node is shutdown by the master.
	 */
	ros::spin();

	return 0;
}

将talker.py和listener.cpp转化为可执行文件

chmod +x talker.py
chmod +x listener.cpp

输入ls查看目录中文件talker.py和listener.cpp变为绿色,即转化为可执行文件。

打开my_pkg程序包中的CMakeLists.txt,将以下代码加入:

include_directories(include ${catkin_INCLUDE_DIRS}) 

add_executable(listener src/listener.cpp) 
target_link_libraries(listener ${catkin_LIBRARIES}) 
add_dependencies(listener my_pkg_generate_messages_cpp)

进入工作空间目录

cd ~/my_workspace

编译工作空间

catkin_make

打开新的终端

roscore

打开新的终端,进入工作空间目录

cd ~/my_workspace

source一下

source devel/setup.bash

运行talker节点

rosrun my_pkg talker.py

格式为: rosrun 程序包名 节点文件

打开新的终端,进入工作空间,source一下,运行listener节点

rosrun my_pkg listener

listener后面不需要加后缀.cpp

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用ros实现c++与python通信 的相关文章

  • Django:模拟模型上的字段

    如何将模拟对象分配给该模型上的用户字段 无论如何都要绕过 SomeModel user 必须是 User 实例 检查吗 class SomeModel models Model user models ForeignKey User 我不会
  • 即使页面未完全加载,我们也可以使用 Selenium 获取页面源吗(TimeoutException: Message: timeout)?

    即使遇到 TimeoutException Message timeout 也能获取页面源码吗 当我调用 driver page source 时 有时无法加载整页 但我只需要它的部分信息 尚未确定 所以我只想在任何情况下保存页面 是否可以
  • for 循环如何评估其参数

    我的问题很简单 Does a for循环评估它每次使用的参数 Such as for i in range 300 python 是否会为此循环的每次迭代创建一个包含 300 个项目的列表 如果是的话 这是避免这种情况的方法吗 lst ra
  • Python在postgresql表中查找带有单引号符号的字符串

    我需要从 psql 表中查找包含多个单引号的字符串 我当前的解决方案是将单引号替换为双单引号 如下所示 sql query f SELECT exists SELECT 1 FROM table name WHERE my column m
  • 如何使用显式引用转储 YAML?

    递归引用非常适合ruamel yaml or pyyaml ruamel yaml dump ruamel yaml load A A id001 id001 然而 它 显然 不适用于普通引用 ruamel yaml dump ruamel
  • Tweepy StreamListener 到 CSV

    我是 python 新手 我正在尝试开发一个应用程序 使用 Tweepy 和 Streaming API 从 Twitter 检索数据并将数据转换为 CSV 文件 问题是此代码不会创建输出 CSV 文件 也许是因为我应该将代码设置为在实现例
  • 更新 Sqlalchemy 中的多个列

    我有一个在 Flask 上运行的应用程序 并使用 sqlalchemy 与数据库交互 我想用用户指定的值更新表的列 我正在使用的查询是 def update table value1 value2 value3 query update T
  • 根据开始列和结束列扩展数据框(速度)

    我有一个pandas DataFrame含有start and end列 加上几个附加列 我想将此数据框扩展为一个时间序列 从start值并结束于end值 但复制我的其他专栏 到目前为止 我想出了以下内容 import pandas as
  • 更改 Altair 中的构面标题位置?

    如何将方面标题 在本例中为年份 移动到每个图的上方 默认值似乎位于图表的一侧 这可以轻易改变吗 import altair as alt from vega datasets import data df data seattle weat
  • 如何将 self 传递给装饰器?

    我该如何通过self key下面进入装饰器 class CacheMix object def init self args kwargs super CacheMix self init args kwargs key func Cons
  • 更改 python tkinter canvas 中的线坐标

    我画了一条线tkinter Canvas现在我想移动一端 这可能吗 例如和itemconfig import tkinter tk tkinter Tk canvas tkinter Canvas tk canvas pack line c
  • python是带有字符串的运算符行为[重复]

    这个问题在这里已经有答案了 我无法理解以下行为 我正在创建 2 个字符串 并使用 is 运算符来比较它 对于第一种情况 它的工作方式有所不同 对于第二种情况 它按预期工作 当我使用逗号或空格时 它显示是什么原因False与比较is当没有使用
  • Pandas 滚动窗口 Spearman 相关性

    我想使用滚动窗口计算 DataFrame 两列之间的 Spearman 和 或 Pearson 相关性 我努力了df corr df col1 rolling P corr df col2 P为窗口尺寸 但我似乎无法定义该方法 添加meth
  • 动态 __init_subclass__ 方法的参数绑定

    我正在尝试让类装饰器工作 装饰器会添加一个 init subclass 方法到它所应用的类 但是 当该方法动态添加到类中时 第一个参数不会绑定到子类对象 为什么会发生这种情况 举个例子 这是可行的 下面的静态代码是我试图最终得到的示例 cl
  • `list()` 被认为是一个函数吗?

    list显然是内置类型 https docs python org 3 library stdtypes html list在Python中 我看到底下有一条评论this https stackoverflow com a 53645813
  • 如何将回溯/sys.exc_info() 值保存在变量中?

    我想将错误名称和回溯详细信息保存到变量中 这是我的尝试 import sys try try print x except Exception ex raise NameError except Exception er print 0 s
  • 如何使用 Keras ImageDataGenerator 预测单个图像?

    我已经训练 CNN 对图像进行 3 类分类 在训练模型时 我使用 keras 的 ImageDataGenerator 类对图像应用预处理功能并重新缩放它 现在我的网络在测试集上训练得非常准确 但我不知道如何在单图像预测上应用预处理功能 如
  • 对数据帧的每 2 小时数据进行 Groupby

    我有一个数据框 Time T201FN1ST2010 T201FN1VT2010 1791 2017 12 26 00 00 00 854 69 0 87 1792 2017 12 26 00 20 00 855 76 0 87 1793
  • 如何为所有用户安装 Anaconda python?

    Anaconda python 发行版 https store continuum io cshop anaconda 非常方便地部署科学计算环境 SCE 并根据需要切换python版本 默认情况下 安装会将 python 定位到 anac
  • 使用 urllib 编码时保持 url 参数有序

    我正在尝试用 python 模拟 get 请求 我有一个参数字典 并使用 urllib urlencode 对它们进行 urlencode 我注意到虽然字典的形式是 k1 v1 k2 v2 k3 v3 urlencoding 后参数的顺序切

随机推荐