105800 Views
82496 Views
47243 Views
47066 Views
45458 Views
38527 Views
Pi-Apps
Intermediate MicroPython
Arduino Alvik
Raspberry Pi Time machine
Now Ad-Free
Guiding Light
Intermediate level MicroPython
Introduction to FreeCAD for Beginners
Building a Robot Arm with Raspberry Pi and PCA9685
Building User Authentication for Static Sites with FastAPI
Mastering Pydantic for Robust Data Validation
Mastering Markdown for Documentation with Jekyll
KevsRobots Learning Platform
65% Percent Complete
By Kevin McAleer, 3 Minutes
touch my_py_pkg/pub.py chmod -R 777 my_py_pkg
This will create the new empty file, and fix the permissions so we can write to it from VS Code.
Cut and paste the following code into the new file:
import rclpy from rclpy.node import Node from std_msgs.msg import String class Talker(Node): def __init__(self): super().__init__("node_test") self.counter_ = 0 # create_publisher needs 3 parameters: Msg Type, message, and buffer size self.publisher = self.create_publisher(String, "Hello", 10) self._timer = self.create_timer(0.5, self.publish_hello) self.get_logger().info("publishing message") def publish_hello(self): msg = String() msg.data = "Hello World" self.publisher.publish(msg) def main(args=None): rclpy.init(args=args) node = Talker() rclpy.spin(node) rclpy.shutdown() if __name__ == "__main__": main()
We now need to update setup.py to include the entry_point for our code. An entry point is the name of the python scripts that are available to run from with the package, and are shown in the list when you type ros2 run my_py_pkg.
setup.py
entry point
ros2 run my_py_pkg
my_py_pkg
entry_points={ 'console_scripts' : [ "pub = my_py_pkg.pub:main", "talker = my_py_pkg.talker:main" ], },
We can now build out package using colcon build. Do this from the root of the workspace (in this case /ros2/my_py_pkg):
colcon build
/ros2/my_py_pkg
cd /ros2/my_py_pkg
Lets test out our code so far…
source install/setup.bash
ros2 run my_py_pkg pub
The package should now run and you iwll see the logger message [INFO] [1673801367.468008815] [node_test]: publishing message.
[INFO] [1673801367.468008815] [node_test]: publishing message
You can also see the messages themselves by querying the ROS2 topic, via the commandline:
ros2 topic echo Hello
This will show the output from the ROS2 topic Hello, which is the topic we are publishing too.
Hello
< Previous Next >