Infinite loop in callback function
Hi there! I want to subscribe to a topic (real_position) and save these data in a variable (julio) in order to process them later in my code. I've tried to use something similar to the tutorial for the subscriber node: http://wiki.ros.org/ROS/Tutorials/Wri... The problem is that when I run my node, the code stacks in the callback function, repeating it again and again, until I press Ctrl + C. Then it continues with the rest of the code. Is callback function the only way to get subscribed data? and if it is, how can I make it run once per loop and get the data to a variable? I am new to ROS and Python, and I apologize if this sounds trivial. I use Ubuntu 16.04 LTS, Python 2.7.12 and ROS Kinetic. Thank you in advance!
#!/usr/bin/python
import rospy
import serial
import time
from std_msgs.msg import String
rospy.init_node('serial_connection', anonymous = True)
ser = serial.Serial('/dev/ttyUSB0', 9600)
print (ser.name)
time.sleep(2)
x_d = 0 # mm
y_d = 1000
thita_d = 0 # moires i rads
camera = [0, 0, 0]
error = [0, 0, 0]
sending_data = [0, 0, 0]
print(sending_data)
def callback(data):
print("callback")
global camera
camera = data
print(camera)
print("emeina mes to callback kollimeno")
rospy.Subscriber('real_position', String, callback)
rate = rospy.Rate(1) #isws na min xreiazetai
def camera_feedback():
print("camera feedback")
print(camera)
def error_calculation():
print("error caclulation")
error[0] = x_d - camera[0]
error[1] = y_d - camera[1]
error[2] = thita_d - camera[2]
def controller_equations():
print("controller equations")
if error != [0, 0, 0]:
print(error)
global sending_data
print(sending_data)
sending_data[0] = 8
sending_data[1] = 8
sending_data[2] = 0
else:
sending_data = [0, 0, 0]
print(error)
print('kokos')
print(sending_data)
def serial_connection():
print("serial connection")
if not rospy.is_shutdown():
if ser.isOpen():
print ("Port Open")
for i in range(1):
ser.write(bytes(sending_data) + '\n')
time.sleep(0.001)
if __name__ == '__main__':
try:
while not rospy.is_shutdown():
print("in the while loop")
camera_feedback()
error_calculation()
controller_equations()
serial_connection()
rate.sleep()
ser.close()
except rospy.ROSInterruptException:
pass