1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ROS2でキーボードを押すとトピックをPublishするPythonコード

Posted at

経緯

キーボード押したときに気軽に何かTopic出したくなりました。
他に方法あると思いますので見つけたら追記します。

コード


import rclpy
from rclpy.node import Node
from geometry_msgs.msg import PoseStamped


class WaypointsPubTest(Node): 
    def __init__(self):
        super().__init__('waypoints_pub_test') 
        self.pose_pub = self.create_publisher(PoseStamped,'goal_pose',10)
        timer_period = 0.01
        self.timer = self.create_timer(timer_period, self.timer_callback)
            
    def timer_callback(self): 
        key = input("f:publish topic <<")
        print("key=", key)
           
        if key == 'f':
            goal_pose = PoseStamped()
            goal_pose.header.frame_id = 'map'
            goal_pose.header.stamp = rospy.get_time()
            goal_pose.pose.position.x = -3.0
            goal_pose.pose.position.y = 0.0
            goal_pose.pose.position.z = 0.0
            goal_pose.pose.orientation.x = 0.0
            goal_pose.pose.orientation.y = 0.0
            goal_pose.pose.orientation.z = 0.0
            goal_pose.pose.orientation.w = 1.0
            
            print("Pressed f")
            self.pose_pub.publish(goal_pose)

def main(args=None):
    rclpy.init(args=args)
    waypoints_pub_test = WaypointsPubTest()
    rclpy.spin(waypoints_pub_test)
    rclpy.shutdown()

if __name__ == '__main__':
    main()

その他

パッケージとして作ってもいいかもしれません。
$ ros2 pkg create --build-type ament_python --node-name waypoints_pub_test waypoints_pub_test_node

実行
ros2 run waypoints_pub_test waypoints_pub_test_node

参考

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?