Skip to content

Instantly share code, notes, and snippets.

@idmontie
Created November 23, 2020 17:47
Show Gist options
  • Save idmontie/87340bb0aea18c1e81e229a145495219 to your computer and use it in GitHub Desktop.
Save idmontie/87340bb0aea18c1e81e229a145495219 to your computer and use it in GitHub Desktop.
Run a GPIO pin based on temp
'''
Run an efficient loop that checks on the RP2 temperature every second.
If the tempt exceeds a threshold, turn the fan on until the next check.
pip install gpiozero
'''
from gpiozero import LED
from time import sleep
from subprocess import PIPE, Popen
import logging, sys
SLEEP_DURATION = 10
TEMP_THRESHOLD = 50
fan = LED(17)
fan_state = False
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
def get_cpu_temperature():
"""get cpu temperature using vcgencmd"""
process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
output, _error = process.communicate()
return float(output[output.index('=') + 1:output.rindex("'")])
def main():
global SLEEP_DURATION, TEMP_THRESHOLD, fan, fan_state
while True:
logging.debug('Running loop')
temp = get_cpu_temperature()
logging.info('Temp: %f', temp)
logging.info('Fan State: %r', fan_state)
if temp > TEMP_THRESHOLD:
if fan_state == False:
fan.on()
fan_state = True
else:
fan.off()
fan_state = False
sleep(10)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment