How to move robot forward and backward until the execution is stop in python

There are two question I would like to ask. First, I would like to move the robot forward in 4 seconds and backward in 4 seconds until I stop the program myself. I’ve run this code to move the robot forward and backward and there is no error. But the robot doesn’t move. May I know why and is there anyone can help me with a new coding?

#! /usr/bin/env python

import rospy
from geometry_msgs.msg import Twist
import time

rospy.init_node('lastforward')
rate=rospy.Rate(4)
pub=rospy.Publisher('/cmd_vel', Twist, queue_size=1)

move=Twist()
def move_x_secs(secs):
    move.linear.x = 0.4
    time.sleep(secs)
    move.linear.x = 0.0
    time.sleep(secs)
    move.linear.x = -0.4
    time.sleep(secs)
    move.linear.x = 0.0
    time.sleep(secs)
    return

move_x_secs(4)


while not rospy.is_shutdown():
    pub.publish(move)
    rate.sleep()

But when I remove some code just to test the code, the robot can move forward after waiting for 4 seconds and when I aborting the program, the robot keep moving. May I know why?

#! /usr/bin/env python

import rospy
from geometry_msgs.msg import Twist
import time

rospy.init_node('lastforward')
rate=rospy.Rate(4)
pub=rospy.Publisher('/cmd_vel', Twist, queue_size=1)

move=Twist()
def move_x_secs(secs):
    move.linear.x = 0.4
    time.sleep(secs)

move_x_secs(4)

while not rospy.is_shutdown():
    pub.publish(move)
    rate.sleep()

Hi,

You have to publish /cmd_vel after each time you change the linear speed:

    move.linear.x = 0.4
    pub.publish(move)
    time.sleep(secs)

    move.linear.x = 0.0
    pub.publish(move)
    time.sleep(secs)

    move.linear.x = -0.4
    pub.publish(move)
    time.sleep(secs)

    move.linear.x = 0.0
    pub.publish(move)
    time.sleep(secs)

and change the last part:

while not rospy.is_shutdown():
    move_x_secs(4)
1 Like

See this post:

I got it. Thank you very much @bayodesegun

1 Like

I’ve run this code and it works. Thank you very much @m.haghbeigi