An issue we’ve commonly faced while operating our robot is that the servos will keep spinning if the script crashes or if we exit the script via CTRL+C.
I’ve always had the stop_servos.py
script for this exact purpose but it has to be executed manually after exiting the main script, i.e. python3 stop_servos.py
. This script simply opens the servo serial port, sets the first four servos’ speed to zero and closes the port. Wouldn’t it be great if this was done automatically on exit?
Enter the atexit
Python module. It allows you to set a function to run when the script exits. Note that it won’t run if the program is killed by a non-Python signal, when a Python fatal internal error occurs or when os._exit()
is used.
All we need to do is import the module into our script and register the handler:
1 2 | import atexit atexit.register(servo_party.stop) |
servo_party
is an instance of our ServoParty class which is our class for controlling the servos. So in our servo_party.py
our stop function is simply:
1 2 3 4 5 6 | def stop(self): self.sc_dynamixel.set_speed(1, 0) self.sc_dynamixel.set_speed(2, 0) self.sc_dynamixel.set_speed(3, 0) self.sc_dynamixel.set_speed(4, 0) self.sc_dynamixel.close() |
And that’s all there is to it. The servos will all stop spinning when the script ends.
Everything is available in our Github repository, currently in the development branch.
Hi there! Such a good write-up, thanks!