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 script for this exact purpose but it has to be executed manually after exiting the main script, i.e. python3 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:

servo_party is an instance of our ServoParty class which is our class for controlling the servos. So in our our stop function is simply:

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.

1 Response

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.