resetting turtlesim programmatically in python
I am writing a python code to control the turtlesim (turtlesim_node). I am using ubuntu 18.04 and ROS melodic. I am successfully moving the turtle as per my commands. But after some commands, I wish to reset the turtle. I have tried various options, but cannot find the right one.
Option 1:
from std_srvs.srv import Empty
rospy.wait_for_service('reset')
clear_bg = rospy.ServiceProxy('reset', Empty)
time.sleep(1)
Option 2:
Used this line instead:
clear_bg = rospy.ServiceProxy('/reset', Empty)
Option 3:
Used this line instead:
clear_bg = rospy.ServiceProxy('turtle1/reset', Empty)
The only option that works is:
import os
os.system('rosservice call /reset')
But Ido not like using system call. Is there any better way of resetting the turtle.
Can you try to call your created Object:
resp1 = clear_bg()
Have a look again at the ROS Tutorials here.
I did not create the object. The object is turtle1, created by command "rosrun turtlesim turtlesim_node" This is what I did after your suggestion.
def back_gr():
rospy.wait_for_service('reset')
resp1 = rospy.ServiceProxy('reset', Empty)
back_gr()
But neither it gives any error nor it resets the turtle.
Add
resp1()
at the end ofdef back_gr()
. You are creating the Service Object but are yet to call it.---- here is my full and simplified code, plz tell me what I am doing wrong ---
pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size = 1)
rospy.init_node('turtle_controller', anonymous=True)
twist = Twist()
def back_gr():
rospy.wait_for_service('reset')
clear_bg = rospy.ServiceProxy('turtle1/reset', Empty)
time.sleep(1)
while(True):
atext = raw_input("next mesg: ")
if atext[0]=='q': exit()
if atext[0]=='c': #clear and reset system
resp1 = back_gr()
continue
twist.linear.x = 1; twist.linear.y = 0; twist.linear.z = 0
twist.angular.x = 0; twist.angular.y = 0; twist.angular.z = 0
pub.publish(twist)
You have created a 'Service' but have not called it.
Between
clear_bg = ...
andtime.sleep(1)
add the codeclear_bg()
so the functionback_gr()
looks like this:Thankyou very much. Very good suggestion. It worked very well.
First it did not work. And gave me the error that 'service [/turtle1/reset] unavailable'. I changed the service name from 'turtle1/reset' to 'reset'. Then it worked. I realised that 'reset' is a universal service and resets all turtles instead of just one turtle.
I also learnt, that in this statement clear_bg is not merely a variable. Instead it is a function call (service call) and has to be called to work. Thanks once again.