Skip to content

Instantly share code, notes, and snippets.

@royalgraphx
Created September 26, 2023 10:22
Show Gist options
  • Save royalgraphx/f9fb4c6646581a065edd607c04e48c38 to your computer and use it in GitHub Desktop.
Save royalgraphx/f9fb4c6646581a065edd607c04e48c38 to your computer and use it in GitHub Desktop.
FanController.py - A Python Script for enabling the Fan on my RPI4
import time
import subprocess
import RPi.GPIO as GPIO
from board import SCL, SDA
import busio
import adafruit_ssd1306
from PIL import Image, ImageDraw, ImageFont
import netifaces as ni
# GPIO pinout
LED1 = 19
LED2 = 13
LED3 = 6
LED4 = 5
FAN = 14
# Function to get local IP address
def get_local_ip():
ni.ifaddresses('eth0')
local_ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
return local_ip
def get_local_ip_new():
try:
ni.ifaddresses('eth0')
local_ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
except (ValueError, KeyError, IndexError):
local_ip = "None"
return local_ip
# Function to get the CPU temperature in Celsius
def get_cpu_temp():
with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
temp = float(f.readline().strip()) / 1000.0
return round(temp, 1)
# Function to get the system uptime
def get_uptime():
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
uptime_minutes, uptime_seconds = divmod(uptime_seconds, 60)
uptime_hours, uptime_minutes = divmod(uptime_minutes, 60)
uptime_days, uptime_hours = divmod(uptime_hours, 24)
uptime_str = "{:.0f}d {:.0f}h {:.0f}m".format(uptime_days, uptime_hours, uptime_minutes)
return uptime_str
# Initialize OLED display
i2c = busio.I2C(SCL, SDA)
disp = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c)
disp.fill(0)
disp.show()
# Font setup for OLED display
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 8)
# Set LED and fan GPIO pins as output
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED1, GPIO.OUT)
GPIO.setup(LED2, GPIO.OUT)
GPIO.setup(LED3, GPIO.OUT)
GPIO.setup(LED4, GPIO.OUT)
GPIO.setup(FAN, GPIO.OUT)
# Turn on all LEDs and set fan speed to 100%
GPIO.output(LED1, GPIO.HIGH)
GPIO.output(LED2, GPIO.HIGH)
GPIO.output(LED3, GPIO.HIGH)
GPIO.output(LED4, GPIO.HIGH)
fan = GPIO.PWM(FAN, 100)
fan.start(100)
uptime_count = 0
while True:
# Display local IP, CPU temperature, and uptime on OLED display
local_ip = get_local_ip_new()
cpu_temp = get_cpu_temp()
if uptime_count == 0:
uptime = get_uptime()
image = Image.new('1', (disp.width, disp.height))
draw = ImageDraw.Draw(image)
draw.text((0, 0), "Local IP: {}".format(local_ip), font=font, fill=255)
draw.text((0, 10), "CPU Temp: {}C".format(cpu_temp), font=font, fill=255)
draw.text((0, 20), "Uptime: {}".format(uptime), font=font, fill=255)
disp.image(image)
disp.show()
time.sleep(1)
uptime_count += 1
if uptime_count == 30:
uptime_count = 0
# Turn off LEDs and fan
GPIO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment