ROS Subscriber not updating values with callback data [closed]
Hi,
I am trying to write a subscriber which subscribes to the /cf<id>/pose
topic (of the Crazyswarm ROS package) to retrieve the pose of my Crazyflie quadcopter, where <id>
is the index of the Crazyflie, which is 1 in my case since I am testing it with only one quadcopter for now. However, only the variable initialization (np.ones(3)
; np.ones(4)
) gets returned and not the updated value from the callback function. I have tried checking the contents of the topic's message with rostopic echo /cf<id>/pose
, and seem to be getting the correct real-time position of the robot. I have also tried using the global keyword within the callback function with no luck. Plus, initializing p
and theta
with None
returns the error:
TypeError: 'NoneType' object is not subscriptable.
What could I be doing wrong? I have pored over robotics.stackexchange and ROS Answers and tried every solution I could find, and am still getting the same results, so there is definitely something wrong with my code.
Here's my code:
import numpy as np
import math
import rospy
from geometry_msgs.msg import Pose
import tf
p = np.ones(3)
theta = np.ones(4)
def allPoseCallback(data):
global p
global theta
p = np.array(data.position)
theta = np.array(data.orientation)
def cfPoseSubscriber():
rospy.Subscriber('/cf1/pose', Pose, allPoseCallback)
allcfpose = {} #Initialize empty dictionary
allcfrpy = np.zeros((1,3)) #Array to hold roll pitch yaw values of one CF
if __name__ == '__main__':
rospy.init_node('cflistener', anonymous=True)
k = 0
while not rospy.is_shutdown():
cfPoseSubscriber()
allcfrpy[k,:] = np.array(tf.transformations.euler_from_quaternion(theta)) #Populate allcfrpy using rpy angles
allcfpose[f'cf{k+1}'] = np.array(p) #Populate dictionary using pose data
# k+=1
print(allcfpose)
print('\n----------------------------------\n')
print(allcfrpy)
Any help will be appreciated. Many thanks.
Since you have a main function it makes sense that all your global variables be defined under main, dont define anything outside it or it will be a confusion.
Thanks, I've shifted the variables around, but usually run into a scoping problem outside the main environment. I've had to use a built-in method from the Crazyswarm package for my needs temporarily. See my comment below. Thank you for the help.