Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Communication between nodes (rospy)

I want to create two nodes that communicate each other. I want that the node1 takes the information from node2 and performs some operations (for example the sum of the information of node1 and node2) and node2 does the same thing (takes the information from node1 and does some operation. How can i implement it? This is the code of my Node1:

#!/usr/bin/env python

import rospy
from std_msgs.msg import String

def callback(msg):
    print '%s' % msg.data


def nodo():
    pub = rospy.Publisher('chatter1', String, queue_size=10)
    rospy.init_node('nodo1', anonymous=True)
    rospy.Subscriber('chatter2', String, callback)
    rate = rospy.Rate(1) # 10hz
    x = 5
    while not rospy.is_shutdown():
        for i in range(0,51):
            pos1 = "%s" % (x)
            rospy.loginfo(pos1)
            pub.publish(pos1)
            rate.sleep()
    rospy.spin()

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

This is the code of my Node2:

#!/usr/bin/env python

import rospy
from std_msgs.msg import String

def callback(msg):
    print '%s' % msg.data


def nodo():
    pub = rospy.Publisher('chatter2', String, queue_size=10)
    rospy.init_node('nodo2', anonymous=True)
    rospy.Subscriber('chatter1', String, callback)
    rate = rospy.Rate(1) # 10hz
    x2 = 4
    while not rospy.is_shutdown():
        for i in range(0,51):
            pos2 = "%s" % (x2)
            rospy.loginfo(pos2)
            pub.publish(pos2)
            rate.sleep()
    rospy.spin()

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