How to run a ros publisher without a while loop?
I am writing tkinter python program for turning on and off the publisher. I need to turn on and off the publisher using a button. If am writing using while loop, the entire gui freezes, I am unable to operate anything. Please give me some suggestions.
dummy = Button(master, text="dummy", relief='groove', command=self.pub_values)
def pub_values(self):
self.pub = rospy.Publisher('/gateway', Int32MultiArray, queue_size=10)
rospy.init_node('talker_int', anonymous=True)
rate = rospy.Rate(1) # 10hz
self.var = Int32MultiArray()
self.var.data = []
ls = self.extract_values()
self.var.data = ls
self.on = True
while self.on == True:
rospy.loginfo(self.var)
self.pub.publish(self.var)
rate.sleep()
UPDATE: New code after feedback
import rospy, numpy, threading, time
from std_msgs.msg import Int32MultiArray
if __name__ == '__main__':
x = Simulat()
try:
x.t.start()
except rospy.ROSInterruptException:
pass
I need to stop or cancel and restart the above program from console. @PeteBlackerThe3rd
Update 2:
Final working code after suggestions
import rospy, numpy, threading, time
from std_msgs.msg import Int32MultiArray
class Simulat:
def __init__(self):
rospy.init_node('talker_int', anonymous=True)
self.pub = rospy.Publisher('/gateway', Int32MultiArray, queue_size=10)
self.rate = rospy.Rate(0.5) # 10hz
self.var = Int32MultiArray()
self.var.data = []
self.t = threading.Timer(2.0, self.talker_int)
self.on = True
def talker_int(self):
rate = rospy.Rate(1) # 10hz
var = Int32MultiArray()
var.data = []
ls = range(6000, 6041)
#while not rospy.is_shutdown():
while self.on == True:
k = [x+1 for x in ls]
var.data = k #% rospy.get_time()
rospy.loginfo(var)
self.pub.publish(var)
rate.sleep()
ls = k
if __name__ == '__main__':
x = Simulat()
try:
t = rospy.Timer(rospy.Duration(2), x.talker_int)
except rospy.ROSInterruptException:
pass
Just so you know, your
rospy.Rate
object is not operating at 10Hz, it's operating at 0.5Hz.