How to subscribe two topics and publish a topic?
This is my publisher's code, the node is desired.
#!usr/bin/env python
import rospy
from std_msgs.msg import Float32
def desired():
pub = rospy.Publisher('desiredcounts', Float32, queue_size=10)
rospy.init_node('desired', anonymous=True)
rate = rospy.Rate(0.1) # 10hz
while not rospy.is_shutdown():
desiredv = 6000 %rospy.get_time()
rospy.loginfo(desiredv)
pub.publish(desiredv)
rate.sleep()
if __name__ == '__main__':
try:
desired()
except rospy.ROSInterruptException:
pass
This is the subscriber's code that need to subscribe two topics and publish a topic base the receive messages.
#!usr/bin/env python
import rospy
from std_msgs.msg import Float32
def callback(data):
rospy.loginfo('gotdesiredcounts %f', data.data)
rospy.loginfo('currentencodercounts %f', data.data)
def gotdesired():
rospy.init_node('gotdesired', anonymous=True)
rospy.Subscriber('desiredcounts', Float32, callback)
rospy.Subscriber('my_encodermotor', Float32, callback)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
gotdesired()
def gottdesired():
pub = rospy.Publisher('controlvalue', Float32, queue_size=10
rospy.init_node('gotdesired', anonymous=True)
rate = rospy.Rate(0.1) # 10hz
while not rospy.is_shutdown():
kp=1
kd=0.1
dt=10
PDvalue = kp * ( desiredv - encoderv ) + kd *( desiredv - encoderv ) / dt
rospy.loginfo(PDvalue)
pub.publish(PDvalue)
rate.sleep()
if __name__ == '__main__':
try:
gottdesired()
except rospy.ROSInterruptException:
pass
When i run this two code, i can not receive the published message by node gotdeisred. Also error: global name 'desiredv' is not defined. Could you give me some advice or examples? Thanks very much.
Qiaoli Ji
desiredv is referenced in your second node but never given a value = undefined. So that file doesn't run and your callback doesn't run. Maybe I am misunderstanding the question.
Thanks for replying. I will try again.