Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env python3
- import os
- import RPi.GPIO as GPIO
- import time
- import datetime
- import sys
- # 5 * * * * sudo python /home/pi/fan.py
- # A crontab will run every hour and check the temp. If the temp is > 49 the script will start the fan
- # until the temperature goes down to 28. When it does, the script will end, shutting down the fan as well.
- # If the script executes again while a previous script is running, the latter will exit
- # ... meaning the pi is in hell, and will never get below FAN_END value :P
- # Configuration
- FAN_PIN = 3 # Pin controlling the relay
- FAN_START = 53 # Start the fan if temperature > 49C
- FAN_END = 50 # Stop the fan if temperature < 28C
- # Get manual action from command line
- action = sys.argv.pop() if len(sys.argv) > 1 else None
- def GPIOsetup():
- GPIO.setwarnings(False)
- GPIO.setmode(GPIO.BCM)
- GPIO.setup(FAN_PIN, GPIO.OUT)
- def fanON():
- GPIOsetup()
- GPIO.output(FAN_PIN, 0) # Fan on (relay closed)
- def fanOFF():
- GPIOsetup()
- GPIO.output(FAN_PIN, 1) # Fan off (relay opened)
- GPIO.cleanup()
- def get_temp_from_system():
- res = os.popen('vcgencmd measure_temp').readline()
- return res.replace("temp=", "").replace("'C\n", "")
- def check_fan(pin):
- GPIOsetup()
- return GPIO.input(pin)
- def run(pin):
- current_date = datetime.datetime.now()
- temp = float(get_temp_from_system())
- if temp >= FAN_START:
- print(f"{temp}C @ {current_date}")
- if check_fan(pin) == 1: # Fan is OFF
- print('Fan is Off... Starting Fan')
- fanON()
- else:
- print('Fan is already ON')
- elif temp <= FAN_END:
- print(f"{temp}C @ {current_date}")
- if check_fan(pin) == 0: # Fan is ON
- print('Fan is on... Shutting it Down')
- fanOFF()
- return 1 # Exit script, Pi has cooled down
- else:
- print('Fan is already OFF')
- # Handle manual actions
- if action == "on":
- print('Turning fan on')
- fanON()
- sys.exit(0)
- elif action == "off":
- print('Turning fan off')
- fanOFF()
- sys.exit(0)
- # First check if the script is already running by checking fan state
- fan_state = check_fan(FAN_PIN)
- if fan_state == 0:
- print('Fan is on, script must be running from another instance...')
- sys.exit(0)
- else:
- temp = float(get_temp_from_system())
- if temp < FAN_START:
- print(f"Pi is operating under normal temperatures: {temp}C")
- fanOFF()
- sys.exit(0)
- else:
- try:
- while True:
- tmp = run(FAN_PIN)
- if tmp == 1: # Fan turned off because the temperature dropped
- break
- time.sleep(5) # Sleep to prevent excessive CPU usage
- except KeyboardInterrupt:
- fanOFF()
- finally:
- fanOFF()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement