ROS小练习——话题发布

目录

一、话题与消息获取

1、话题

2、消息

二、代码编写

1、C++

2、python

三、编译运行


一、话题与消息获取

打开小乌龟案例

1、话题

rqt_graph

rostopic list

2、消息

获取消息类型:

复制代码
rostopic type /turtle1/cmd_vel

获取消息格式:

复制代码
rosmsg info geometry_msgs/Twist

二、代码编写

1、C++

cpp 复制代码
//包含头文件
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"

int main(int argc, char *argv[])
{
    //初始化 ROS 节点
    ros::init(argc,argv,"control");
    ros::NodeHandle nh;
    //创建发布者对象
    ros::Publisher pub = nh.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel",1000);
    
    geometry_msgs::Twist msg;
    msg.linear.x = 1.0;
    msg.linear.y = 0.0;
    msg.linear.z = 0.0;
    msg.angular.x = 0.0;
    msg.angular.y = 0.0;
    msg.angular.z = 2.0;

    ros::Rate r(10);

    while(ros::ok())
    {
        //循环发布运动控制消息
        pub.publish(msg);
        ros::spinOnce();
    }

    return 0;
}

2、python

python 复制代码
#! /usr/bin/env python
# -*- coding:UTF-8 -*-

#导包
import rospy
from geometry_msgs.msg import Twist

if __name__ == "__main__":
    #初始化 ROS 节点
    rospy.init_node("control_circle_p")
    #创建发布者对象
    pub = rospy.Publisher("/turtle1/cmd_vel",Twist,queue_size=1000)
    
    rate = rospy.Rate(10)
    msg = Twist()
    msg.linear.x = 1.0
    msg.linear.y = 0.0
    msg.linear.z = 0.0
    msg.angular.x = 0.0
    msg.angular.y = 0.0
    msg.angular.z = 0.5
    
    while not rospy.is_shutdown():
        pub.publish(msg)
        rate.sleep()

三、编译运行

相关推荐
AI探索者13 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者13 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh15 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅15 小时前
Python函数入门详解(定义+调用+参数)
python
端平入洛15 小时前
delete又未完全delete
c++
曲幽16 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时19 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django