Advertisement
MrLunk

Raspberry pi fan controller

Dec 10th, 2020
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import time
  4.  
  5. from gpiozero import OutputDevice
  6.  
  7.  
  8. ON_THRESHOLD = 65 # (degrees Celsius) Fan kicks on at this temperature.
  9. OFF_THRESHOLD = 55 # (degress Celsius) Fan shuts off at this temperature.
  10. SLEEP_INTERVAL = 5 # (seconds) How often we check the core temperature.
  11. GPIO_PIN = 17 # Which GPIO pin you're using to control the fan.
  12.  
  13.  
  14. def get_temp():
  15. """Get the core temperature.
  16. Read file from /sys to get CPU temp in temp in C *1000
  17. Returns:
  18. int: The core temperature in thousanths of degrees Celsius.
  19. """
  20. with open('/sys/class/thermal/thermal_zone0/temp') as f:
  21. temp_str = f.read()
  22.  
  23. try:
  24. return int(temp_str) / 1000
  25. except (IndexError, ValueError,) as e:
  26. raise RuntimeError('Could not parse temperature output.') from e
  27.  
  28. if __name__ == '__main__':
  29. # Validate the on and off thresholds
  30. if OFF_THRESHOLD >= ON_THRESHOLD:
  31. raise RuntimeError('OFF_THRESHOLD must be less than ON_THRESHOLD')
  32.  
  33. fan = OutputDevice(GPIO_PIN)
  34.  
  35. while True:
  36. temp = get_temp()
  37.  
  38. # Start the fan if the temperature has reached the limit and the fan
  39. # isn't already running.
  40. # NOTE: `fan.value` returns 1 for "on" and 0 for "off"
  41. if temp > ON_THRESHOLD and not fan.value:
  42. fan.on()
  43.  
  44. # Stop the fan if the fan is running and the temperature has dropped
  45. # to 10 degrees below the limit.
  46. elif fan.value and temp < OFF_THRESHOLD:
  47. fan.off()
  48.  
  49. time.sleep(SLEEP_INTERVAL)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement