Communication between nodes (rospy)

asked 2016-05-21 07:27:18 -0500

Angio gravatar image

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
edit retag flag offensive close merge delete

Comments

gvdhoorn gravatar image gvdhoorn  ( 2016-05-21 09:14:58 -0500 )edit

Maybe this answer helps you.

jsanch2s gravatar image jsanch2s  ( 2016-11-21 08:10:05 -0500 )edit