启动roscore–>turtlesim–>teleop_key
roscore
rosrun turtlesim turtlesim_node
rosrun turtlesim turtle_teleop_key
① 通过计算图查看话题,启动计算图:
rqt_graph
② 通过 rostopic 列出话题:
rostopic list
③获取消息类型:
rostopic type /turtle1/cmd_vel
④获取消息格式
rosmsg info geometry_msgs/Twist
⑤获取消息类型:
rostopic type /turtle1/cmd_vel
C++:
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
/*
需求:发布速度消息
话题:/turtle1/cmd_vel
消息:geometry_msgs/Twist
1.包含头文件
2.初始化ROS节点
3.创建节点句柄
4.创建发布对象
5.发布逻辑
6.spinOnce
*/
int main(int argc, char *argv[])
{
// 2.初始化ROS节点
ros::init(argc,argv,"my_control");
// 3.创建节点句柄
ros::NodeHandle nh;
// 4.创建发布对象
ros::Publisher pub = nh.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel",10);
// 5.发布逻辑
ros::Rate rate(10); //设置发布频率
//组织被发布的消息
geometry_msgs::Twist twist;
twist.linear.x = 1.0;
twist.linear.y = 0.0;
twist.linear.z = 0.0;
twist.angular.x = 0.0;
twist.angular.y = 0.0;
twist.angular.z = 0.5;
//循环发布
while (ros::ok())
{
pub.publish(twist);
//休眠
rate.sleep();
//回头
// 6.spinOnce();
ros::spinOnce();
}
return 0;
}
输出:小乌龟做圆周运动
Python:
#! usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
"""
发布方:发布速度消息
话题: /turtle1/cmd_vel
消息: geometry_msgs/Twist
1.导包
2.初始化ROS节点
3.创建发布者对象
4.组织数据并发布数据
"""
if __name__ == "__main__":
# 2.初始化ROS节点
rospy.init_node("my_control_p")
# 3.创建发布者对象
pub = rospy.Publisher("/turtle1/cmd_vel",Twist,queue_size=10)
# 4.组织数据并发布数据
#设置发布频率
rate = rospy.Rate(10)
#创建速度消息
twist = Twist()
twist.linear.x = 0.5
twist.linear.y = 0.0
twist.linear.z = 0.0
twist.angular.x = 0.0
twist.angular.y = 0.0
twist.angular.z = 0.5
#循环发布
while not rospy.is_shutdown():
pub.publish(twist)
rate.sleep()
输出: