So I have recently created a VPN server on a raspberry Pi 2 Mobel B, and I would like to create a script that will read the CPU temperature and change the PWM signal that is fed into a transistor to control the speed of the fan.

The script itself works. As you can imagine, I would also like this to run at startup, but I would like it to shutdown cleanly and use the GPIO.cleanup() command before the Pi is shut down. is there any way for me to do this automatically? Here is my python script so far:

import RPi.GPIO as GPIO
import time
import os

  # Return CPU temperature as float
def getCPUtemp():
    cTemp = os.popen('vcgencmd measure_temp').readline()
    return float(cTemp.replace("temp=","").replace("'C\n",""))

while True:
    CPU_temp = getCPUtemp()
    if CPU_temp > 70.0:
    elif CPU_temp > 60.0:
    elif CPU_temp > 50.0:
    elif CPU_temp > 45.0:
    elif CPU_temp > 40.0:
    elif CPU_temp > 35.0:
    elif CPU_temp > 30.0:

The bottom two lines are the ones which I would like to run before the Pi gets shut down.

  • 2
    There doesn't seem to be much point in calling gpio.cleanup at shutdown (because rebooting the Pi will reset all your GPIO pins in any case). Your process will probably receive a SIGTERM signal at shutdown time, so potentially you could catch that and call your cleanup functions.
    – larsks
    Nov 2, 2017 at 14:26
  • Sorry that was just there to demonstrate the kind of thing I'd want to do! And thanks, I will look into SIGTERM signals! Nov 2, 2017 at 14:27
  • 1
    As @larsks says there is no point. The Pi remembers no state over reboot and I doubt your added hardware does.
    – joan
    Nov 2, 2017 at 18:04
  • @joan So I don't need to do a GPIO cleanup I can just let the code exit wherever? Nov 2, 2017 at 22:27
  • You never need to call GPIO.cleanup. That's a convenience method to return the pins to their power-on state. If you want to do that at the end of your program, then call it. If you don't want to or don't care, then don't call it. You get the power-on state after reboot anyway, so you don't need to do it your case, as others have mentioned. It's not like closing a file where there are resources open (e.g. buffers not yet flushed) that might lost if you don't close gracefully.
    – Brick
    Nov 3, 2017 at 0:26

1 Answer 1


Answered in comments: The GPIO.cleanup() doesn't need to be called as this is done as part of the boot/restart cycle. The code can just be left in a while loop and the Pi booting after a shutdown will take care of the rest. Thanks everyone!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.