Hello, I have been trying to get my robot to make the full square and to my knowledge, my logic is right and the robot should make the full square. However, after it moves straight the first time, for some reason, my code leaves both of the while loops and the success message is posted even though the robot did not make the full square. Any suggestions? Thanks in advance
My code is below:
#! /usr/bin/env python
import rospy
from services_quiz.srv import BB8CustomServiceMessage, BB8CustomServiceMessageResponse
from time import sleep
from geometry_msgs.msg import Twist
def my_callback(request):
my_response = BB8CustomServiceMessageResponse()
distance = request.side
repeat = (request.repetitions + 1)
i = 0
#make sure repetitions are done correctly
while repeat > i:
j = 0
#keep in while loop until square is made
while j < 4:
move.linear.x = 0.3
move.angular.z = 0.0
pub.publish(move)
rospy.sleep(distance)
move.linear.x = 0.0
move.angular.z = 0.0
pub.publish(move)
move.linear.x = 0.0
move.angular.z = 0.05
pub.publish(move)
move.linear.x = 0.0
move.angular.z = 0.0
pub.publish(move)
j+=1
move.linear.x = 0.0
move.angular.z = 0.0
pub.publish(move)
i+=1
move.linear.x = 0.0
move.angular.z = 0.0
pub.publish(move)
my_response.success = True
return my_response
rospy.init_node('bb8_move_custom_server') my_circle_service = rospy.Service('/move_bb8_in_square_custom', BB8CustomServiceMessage , my_callback) # create the Service called my_service with the defined callback
pub = rospy.Publisher( '/cmd_vel', Twist, queue_size = 1)
move = Twist()
rospy.spin() # maintain the service open.
your issue is here. You added the rospy.sleep the first time, but then for the next 3 publishes, you leave the robot no time to react. after each pub.publish, you need a rospy.sleep(). only the first one should be coupled to the distance, the other ones are to stop, to turn and to stop turning. You gonna have to experiment to find the correct values. (only the turning value is really important, as you want to wait long enough for it to turn 90°)
As a little side note, it is cleaner to work with for loops:
repeat = request.repetitions
for n in range(repeat):
for i in range(4):
move.linear.x = 0.3
move.angular.z = 0.0
pub.publish(move)
rospy.sleep(distance)
move.linear.x = 0.0
move.angular.z = 0.0
pub.publish(move)
rospy.sleep(1)
move.linear.x = 0.0
move.angular.z = 0.05
pub.publish(move)
rospy.sleep(1.5)
move.linear.x = 0.0
move.angular.z = 0.0
pub.publish(move)
rospy.sleep(0.5)
note that these sleep values are just random. In case you are not familiar with range():
range(4) == [0, 1, 2, 3]
Lastly, you never initialized your service. What is calling your callback function?