[ROS] How to write Publisher and Subscriber on one node

Introduction

When using ROS, I wanted to communicate measurement data as a topic from the node functioning as a Subscriber, but I was in trouble because I could not find a way to write Subscriber and Publisher in one program. (There is a high possibility that Google search power is low), I will summarize it to deepen the understanding of ROS. I've just started using it recently, and I think it may be wrong, so if you are familiar with it, please point it out. informative.

What is ROS (Robot Operating System)?

Middleware that provides libraries and tools to support the creation of robot applications. Specifically, it will be possible to easily communicate between robots.

Pub & Sub communication

In ROS, the executable ones connected to the ROS network are called "nodes", and messages called "topics" are exchanged between the nodes. The node that delivers the message is called the Publisher, and the node that receives the message is called the Subscriber. PubSub通信.png

Execution environment

Publisher sample program

talker.py


#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String #Import the data type to use

def talker():
    #Create Publisher('Topic name',Mold,size)
    pub = rospy.Publisher('chatter', String, queue_size=10)
    #Declare node name
    rospy.init_node('talker', anonymous=True)
    #Declare the cycle of the loop
    rate = rospy.Rate(10) # 10hz
    
    while not rospy.is_shutdown():
        #Fill in the data to publish
        hello_str = "hello world %s" % rospy.get_time()
        #Display the data to publish in the terminal
        rospy.loginfo(hello_str)
        #Publish data
        pub.publish(hello_str)
        rate.sleep()

  if __name__ == '__main__':
       try:
         talker()
     except rospy.ROSInterruptException:
         pass

Quoted from Writing a Simple Publisher and Subscriber (Python), supplementary explanation

Subscriber sample program

listener.py


#!/usr/bin/env python
import rospy
from std_msgs.msg import String #Import the data type to use

def callback(data):
    #Display the received data in the terminal
    #Data is data.Received in data
    rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
     
def listener():
    #Declare node name
    rospy.init_node('listener', anonymous=True)
    #Create Subscriber('Topic name',Mold,callback function)
    rospy.Subscriber("chatter", String, callback)
    #Keep calling the callback function
    rospy.spin()

 if __name__ == '__main__':
    listener()

Quoted from Writing a Simple Publisher and Subscriber (Python), supplementary explanation

Publisher and Subscriber programs

Just because I don't use rospy.spin () (because it stops in the callback function standby state), it feels like it's just stuck together, but I was worried about this for about two days. Lol.

controller.py


#!/usr/bin/env python
# coding: utf-8
import rospy
from std_msgs.msg import String

def callback(data):
    #Display the received data in the terminal
    #Data is data.Received in data
    rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
      
def controller():
    #Declare node name
    rospy.init_node('controller', anonymous=True)
    #Create a Subscriber. Load the topic.
    sub = rospy.Subscriber('listener', String, callback)
    #Create Publisher('Topic name',Mold,size)
    pub = rospy.Publisher('talker', String, queue_size=1)
    #Loop period.
    rate = rospy.Rate(10)
    
    while not rospy.is_shutdown():
        #Fill in the data to publish
        hello_str = "hello world %s" % rospy.get_time()
        #Display the data to publish in the terminal
        rospy.loginfo(hello_str)
        #Publish data
        pub.publish(hello_str)
        rate.sleep()
    
if __name__ == '__main__':
    try:
        controller()
    except rospy.ROSInitException:
        pass

reference

Recommended Posts

[ROS] How to write Publisher and Subscriber on one node
How to write pydoc and multi-line comments
How to write urlfetch unittest on GAE / P
How to write async and await in Vue.js
How to define Decorator and Decomaker in one function
How to install Git GUI and Gitk on CentOS
XPath Basics (2) -How to write XPath
How to share OS and Vim clipboard on Ubuntu 18.04.3 LTS
[Python] How to write an if statement in one sentence.
How to integrate Apache httpd 2.4 and Tomcat 9 on Cent OS 8
How to register on pypi
How to install OpenCV on Cloud9 and run it in Python
Repeated @ app.callback in Dash How to write Input and State neatly
How to write code to access python dashDB on Bluemix or local
How to run Jupyter and Spark on Mac with minimal settings
How to install pandas on EC2 (How to deal with MemoryError and PermissionError)
How to display PDF resolution and detailed information on Linux (pdfinfo)
Difference in how to write if statement between ruby ​​and python
How to block ads for free on iPhone and iPad apps
[ROS2] How to describe remap and parameter in python format launch
Set up a node to do MNIST on ROS using Tensorflow
[FSL] How to peel off Atlas one by one and separate them
How to install mysql-connector-python on mac
How to install and use Tesseract-OCR
How to write soberly in pandas
How to use Dataiku on Windows
Flask reuse How to write html
Notes on how to use pywinauto
How to install graph-tool on macOS
How to install VMware-Tools on Linux
How to install pycrypto on Windows
Notes on how to use featuretools
How to install OpenCV on Mac
How to run matplotlib on heroku
How to convert 0.5 to 1056964608 in one shot
How to install PyPy on CentOS
How to use homebrew on Debian
Misunderstanding on how to connect cnn
How to install TensorFlow on CentOS 7
How to install and configure blackbird
How to install CUDA and nvidia-driver
How to install and use Graphviz
How to write Docker base image
How to write Django1.9 environment-independent wsgi.py
Notes on how to use doctest
How to install Maven on CentOS
How to install Go on Ubuntu
How to install music 21 on windows
How to solve slide puzzles and 15 puzzles
How to write the correct shebang in Perl, Python and Ruby scripts
Install ROS and ROS module for Roomba on RaspberryPi3 and try to run it
Try to write python code to generate go code --Try porting JSON-to-Go and so on
How to make only one data register on the Django admin screen
[Linux] How to subdivide files and folders
How to package and distribute Python scripts
How to install aws-session-manager-plugin on Manajro Linux
Qiita (1) How to write a code name
How to read pydoc on python interpreter
How to install drobertadams / toggl-cli on Mac
How to set optuna (how to write search space)
[Kivy] How to install Kivy on Windows [Python]