How to set to a ROS system a fixed communication frequency?
I have a ROS system with 2 nodes. The first node receives a string of data from a raspberry by using serial port and it uploads on in a topic. The second node subscribes to that topic, it gets the data and after some calculations it sends a string to a microcontroller using another serial port. The calculations include some equations that depend on time.
Let's say that I want to send the data to the microcontroller at a fixed frequency (66.67 Hz), but the calculations depend on data from all the system. How can I achieve that from the moment I run all the nodes the system is going to send the data to the microcontroller with this fixed frequency? Do I have to set the whole system under a common time frame? and if that is the case, how can I do it? I think that by setting only the rate to the second node to match that frequency will not solve my problem. After a small research I found that rospy.rostime might be helpful, but I didn't find any example on how to use it and what exactly can offer. I am new to ROS so I still try to find out how things work. I use ROS Kinetic, in Ubuntu 16.04 LTS and my nodes are in Python 2.7.12. Thank you in advance.
UPDATE:
The code running on my Raspberry Pi is:
#!/usr/bin/env python
import random
import decimal
import time
import serial
ser = serial.Serial(
port = '/dev/ttyAMA0',
baudrate = 115200,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 1
)
time.sleep(2)
counter = 0
while 1: # i while True:
x = float(decimal.Decimal(random.randrange(0, 5010))/10)
y = float(decimal.Decimal(random.randrange(0, 5010))/10)
z = float(decimal.Decimal(random.randrange(0, 5010))/10)
thita = float(decimal.Decimal(random.randrange(0, 5010))/10)
u_x = float(decimal.Decimal(random.randrange(0, 5010))/10)
u_y = float(decimal.Decimal(random.randrange(0, 5010))/10)
string_buffer = str(x)+","+str(y)+","+str(z)+','+str(thita)+','+str(u_x)+','+str(u_y)+'/'+'\n'
print string_buffer
ser.write(string_buffer)
time.sleep(1)
counter += 1
ser.close()
and the code of the first node (receiving from Pi and publishing on topic) is:
#!/usr/bin/python
import rospy
import serial
import time
from std_msgs.msg import String
ser = serial.Serial('/dev/ttyS0', 115200)
print (ser.name)
time.sleep(2)
def camera_node():
pub = rospy.Publisher('real_position', String, queue_size=10) # to$
rospy.init_node('camera_node', anonymous=True)
rate = rospy.Rate(1) #hz, mporei na thelei sygxronismo me ta ypolo$
print("kokos")
if ser.isOpen():
print("in the loop")
camera_str = ser.readline() #... auto p tha diavazei apo serial
#print(camera_str)
rospy.loginfo(camera_str)
pub.publish(camera_str)
rate.sleep()
if __name__ == '__main__':
try:
while not rospy.is_shutdown():
camera_node()
ser.close()
except rospy.ROSInterruptException:
pass