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:
#!/usr/bin/python
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",""))
GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.OUT)
GPIO.setwarnings(False)
p=GPIO.PWM(18,100)
p.start(100)
time.sleep(1)
while True:
CPU_temp = getCPUtemp()
if CPU_temp > 70.0:
p.ChangeDutyCycle(100)
elif CPU_temp > 60.0:
p.ChangeDutyCycle(60)
elif CPU_temp > 50.0:
p.ChangeDutyCycle(40)
elif CPU_temp > 45.0:
p.ChangeDutyCycle(30)
elif CPU_temp > 40.0:
p.ChangeDutyCycle(20)
elif CPU_temp > 35.0:
p.ChangeDutyCycle(15)
elif CPU_temp > 30.0:
p.ChangeDutyCycle(10)
else:
p.ChangeDutyCycle(0)
time.sleep(60)
p.stop()
GPIO.cleanup()
The bottom two lines are the ones which I would like to run before the Pi gets shut down.
gpio.cleanup
at shutdown (because rebooting the Pi will reset all your GPIO pins in any case). Your process will probably receive aSIGTERM
signal at shutdown time, so potentially you could catch that and call your cleanup functions.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.