0
$\begingroup$

Rosanswers logo

I am using a GPS plugin on my model. I know it works as I have tested by using

rostopic echo gps_out

and it continually outputs data in the NavSatFix form.

I am trying to write a script that will ultimately give my robot velocity commands through reading a target and current GPS location.

The python script I'm currently writing is to read in the data and then assign the longitude and latitude to global variables which can be displayed to confirm they are correct. This is the python script currently.

#!/usr/bin/env python
import rospy
from sensor_msgs.msg import NavSatFix
import tf

global longitude
global latitude

latitude='Not re-assigned'
longitude='Not re-assigned'

def callback(data):
    latitude = data.latitude
    longitude = data.longitude

rospy.init_node('topic_reader')

rospy.Subscriber('gps_out', NavSatFix, callback)

print("Longitude:", longitude)
print("Latitude:", latitude)

As can be read from the code, the only output is

Longitude: Not re-assigned
Latitude: Not re-assigned

What am I doing wrong?

From my understanding I am setting longitude and latitude variables to be global, and assigning them the initial conditions. Then assigned the nodes name, then subscribing to the topic and running callback which should assign the values to the variables which will allow them to be printed.


Originally posted by Jord on ROS Answers with karma: 3 on 2021-10-21

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

You might want to look at the subscriber documentation. Essentially you need rospy.spin() so that the callbacks will be called, and your print functions should be called within the callback. I've fixed it here

#!/usr/bin/env python
import rospy
from sensor_msgs.msg import NavSatFix
import tf

global longitude
global latitude

latitude='Not re-assigned'
longitude='Not re-assigned'

def callback(data):
    # Assign the data to variables
    latitude = data.latitude
    longitude = data.longitude
   
    # Print
    print("Longitude:", longitude)
    print("Latitude:", latitude)

rospy.init_node('topic_reader')

rospy.Subscriber('gps_out', NavSatFix, callback)

# Until ctrl + c is pressed, lines after the call to rospy.spin will not be executed. 
rospy.spin()

Originally posted by janindu with karma: 849 on 2021-10-21

This answer was ACCEPTED on the original site

Post score: 0


Original comments

Comment by Mike Scheutzow on 2021-10-22:
@Jord in addition to the rospy::spin(), the global keywords need to be inside the callback function. As it is now, you are creating local variables and assigning to them. Also, make sure that "python" means python3.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.