Publisher and subscriber in one node (Python)
Hello, I new using ROS and I saw a lot of posts but I can't solve my problem.
I have a publisher (1) that sends a random number between 0 and 5 and the next node (2) needs to receive that value and multiply it by 10. After that, the same node (2) needs to send that information to another node. This is the first code
#!/usr/bin/env python
# encoding: utf-8
import rospy
import random
from std_msgs.msg import String
def nodo():
rospy.init_node('nodo_publisher')
pub = rospy.Publisher('example', String, queue_size=10)
rate = rospy.Rate(10)
while not rospy.is_shutdown():
ran = random.randint(0, 5)
mensaje = str(ran)
rospy.loginfo(mensaje)
pub.publish(mensaje)
rate.sleep()
if __name__ == '__main__':
try:
nodo()
except rospy.ROSInterruptException:
pass
And this is my attempt for the second code
#!/usr/bin/env python
# encoding: utf-8
import rospy
from std_msgs.msg import String
rospy.init_node("Mixer_Node")
pub = rospy.Publisher("echo", String)
def callback(mensaje):
mensaje1 = str(int(mensaje.data)*10
pub.publish(mensaje1)
# The message has 2 parts, a header and the data. We only want to use the actual data
sub=rospy.Subscriber("chatter", String, callback)
Asked by EGam on 2022-03-14 12:17:06 UTC
Answers
Hi EGam, can you give more details about your problem? Are you able to run (rosrun) both nodes?
Based on your post, the first node seems be ok. Except for an additional "space" in the beginning of line 15:
rate.sleep()
The second node seems to be missing two important parts:
- The sctructure using if
if __name__ == '__main__':
in order to the python interpreter run your code - Even if your node just do something when a new data is published, it should have at least a
rospy.spin()
that checks and process if any event occurs (new data received on a topic or a timer event). Check this post about rospy.spin and rospy.sleep (https://answers.ros.org/question/332192/difference-between-rospyspin-and-rospysleep/)
To write nodes that only handle with events (like your second one), I like to follow the listener structure presented in the rospy tutorial (http://wiki.ros.org/rospy_tutorials/Tutorials/WritingPublisherSubscriber).
I hope this will help you.
Asked by schulze18 on 2022-03-15 13:17:44 UTC
Comments