小乌龟控制实现
1. 创建package(创建过可省略)¶
ros2 pkg create --build-type ament_python turtlesim_topic --dependencies geometry_msgs
可以修改
package.xml
文件如下信息<description>C++ client server tutorial</description> <maintainer email="you@email.com">Your Name</maintainer> <license>Apache License 2.0</license>
2. 编写代码¶
2.1 节点代码¶
- 在package的
turtlesim_topic
文件夹下创建turtlesim_topic_obj.py
文件,代码如下
import sys
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist
from PyQt5.QtWidgets import QApplication,QWidget,QFormLayout,QLineEdit,QPushButton
class MainWindow(QWidget):
def __init__(self,node):
super(MainWindow, self).__init__()
self.node = node
self.publisher = node.create_publisher(Twist,'/turtle1/cmd_vel',10)
self.resize(400,120)
self.setWindowTitle('小乌龟控制')
# 布局
layout = QFormLayout()
self.setLayout(layout)
# 控件
self.editLinear = QLineEdit()
layout.addRow("线速度", self.editLinear)
self.editAngular = QLineEdit()
layout.addRow("角速度", self.editAngular)
btnSend = QPushButton("发送")
layout.addRow('',btnSend)
# 事件
btnSend.clicked.connect(self.send_twist)# 布局
def send_twist(self):
x = float(self.editLinear.text())
y = float(self.editAngular.text())
data = Twist()
data.linear.x = x
data.angular.z = y
self.node.get_logger().info('send topic')
self.publisher.publish(data)
def main():
rclpy.init()
node = Node('turtlesim_control')
app = QApplication(sys.argv)
window = MainWindow(node)
window.show()
result = app.exec_()
node.destroy_node()
rclpy.shutdown()
sys.exit(result)
if __name__ == '__main__':
main()
2.2 添加配置¶
- 打开
setup.py
文件,在console_scripts
节点下添加配置
'turtlesim_topic_obj = turtlesim_topic.turtlesim_topic_obj:main',
3. 编译工程¶
colcon build
4. 运行节点¶
source install/setup.bash
ros2 run turtlesim_topic turtlesim_topic_obj