仿真环境中键盘控制turtlebot3运动
- 准备工作
- 1. 监听键盘敲击:key_publisher.py
- 2. 控制turtlebot3运动:keys_to_twist_using_rate.py
- 3. 测试
- 4. 数据监视
准备工作
名称 | 版本 |
---|---|
ROS | Noetic |
Gazebo | 11.11.0 |
python | 3.8.10 |
turtlebot3的安装与仿真环境搭建请看上一篇帖子。
在此基础上,我们需要2个python脚本:key_publisher.py
和keys_to_twist_using_rate.py
,第一个用于创建节点用来监听键盘敲击并在/key
话题上发布类型为std_msgs/String
的信息;第二个用于创建节点并发送类型为Twist
的名为/cmd_vel
消息。
创建新的文件夹/scripts
用来防止python脚本,具体内容如下:
1. 监听键盘敲击:key_publisher.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""监听键盘"""
import sys, select, tty, termios
import rospy
from std_msgs.msg import String
if __name__ == "__main__":
key_pub = rospy.Publisher("key", String, queue_size=1)
rospy.init_node("keyboard_driver")
rate = rospy.Rate(100)
old_attr = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
print(f"publishing keystrokes. press ctrl-c to exit ...")
while not rospy.is_shutdown():
if select.select([sys.stdin], [], [], 0)[0] == [sys.stdin]:
key_pub.publish(sys.stdin.read(1))
rate.sleep()
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_attr)
2. 控制turtlebot3运动:keys_to_twist_using_rate.py
本文采用的是常用的键盘控制方式,即:w
:前进,
x
:后退,a
:左转,d
:右转,s
:停止。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""监视键盘,然后发送/cmd_vel,且发送频率稳定"""
import rospy
from std_msgs.msg import String
from geometry_msgs.msg import Twist
key_mapping = {"w":[0, 1], "x":[0, 1],
"a":[-1, 0], "d":[1, 0],
"s":[0, 0]}
g_last_twist = None
def keys_cb(msg, twist_pub):
global g_last_twist
if len(msg.data)==0 or msg.data[0] not in key_mapping:
return
vels = key_mapping[msg.data[0]]
g_last_twist.angular.z = vels[0]
g_last_twist.linear.x = vels[1]
twist_pub.publish(g_last_twist)
if __name__ == "__main__":
rospy.init_node("key_to_twist")
twist_pub = rospy.Publisher("cmd_vel", Twist, queue_size=1)
rospy.Subscriber("key", String, keys_cb, twist_pub)
rate = rospy.Rate(10)
g_last_twist = Twist() # initializes to zero
while not rospy.is_shutdown():
twist_pub.publish(g_last_twist)
rate.sleep()
3. 测试
打开4个terminal分别运行以下的命令
roscore
roslaunch turtlebot3_gazebo turtlebot3_world.launch
python scripts/keys_to_twist_using_rate.py
python scripts/key_publisher.py
在这个terminal内敲击键盘可以控制turtlebot3在gazebo中运动,如下图所示:
4. 数据监视
此外,我们可以来监视turtlebot3运动时产生的数据:
rostopic echo cmd_vel
rqt_plot cmd_vel/linear/x cmd_vel/angular/z