Be cool part 3 - Programming the Pi in python
The circuit ready to be tested |
I
have now written the Python code and tidied it up. Basically I want
my PI to become my general purpose computer and as you will see I'll
be adding a hard drive later!
![]() |
PCB version ready to test |
Make
a folder called /scripts in your home folder, either in file manager
or
mkdir
scripts from the terminal.
Open
Python 2 IDLE's editor from the start menu. Paste in the code below
and save it as fanpowercontrol.py to your scripts folder.
Run
the code either by pressing F5 in IDLE, or from the command prompt by
typing
cd
/scripts
sudo
python fanControl.py
Beware
of capitalisation done to make the name more readable. The fan should
run for 5 seconds every time the program is started, this is to show
that the program works regardless of the fan temperature.
Also
the program uses print
statements liberally to show you what the temperature is and if the
fan output is ON or OFF every two seconds, this should make for
easier debugging. There is nothing worse than now knowing what is
supposed to be happening when a program is running. These will not be
visible when we cron the
program later, this is why an LED is useful.
The fanControl.py
code
Use
Python IDLE or a text editor to save this file as fanControl.py Note
Python is very fussy about indents (tabs) and newlines so I have
uploaded all the files to Dropbox you
do not need an account to download them. This will save you having errors due to copying code from the blog.
I
also made a combi fan and power control, however - I am not happy
with this and it needs further work so let's focus on the fan for
now.
You
will also find a program called gpiotest.py, this will allow you to
quickly test and toggle the state of any GPIO output. Great for
identifying pins!
#!/usr/bin/env
python
# coding: latin-1
# By Ralph Beardmore Jan 2017 for PI 3
# this is a temperature control. It runs in Python 2.x so code accordingly
# this is designed for NPN transistor and is normally OFF
# Import the libary functions we need
import RPi.GPIO as GPIO
import time
import subprocess
# Set which GPIO pins the fan output and power switch inputs are connected to
fanOUT = 8 #pin 3 = GPIO channel 8 see mode
fanPower = False
a
# configure the input and output pins
GPIO.setmode(GPIO.BOARD) # GPIO mode - BCM = channel, BOARD= pin number
GPIO.setup(fanOUT, GPIO.OUT) # fan control variable
# Map the on/off state to nicer names for display
dName = {} # make a list
dName[True] = 'ON '
dName[False] = 'OFF'
# CPU temperature monitor, all temperatures in centigrade!
pathSensor = '/sys/class/thermal/thermal_zone0/temp' # File path used to read the temperature
readingMultiplier = 0.001 # Value to multiply the reading by for user display
tempHigh = 60000 # Reading at which the fan(s) will be started (same units as file)
tempLow = 50000 # Reading at which the fan(s) will be stopped (same units as file)
interval = 2 # Time in seconds between readings in seconds
print '\nFAN TURNS ON AT ', int(tempHigh * readingMultiplier)
print '\nFAN TURN OFF AT ', int(tempLow * readingMultiplier)
print '\n interval = ', interval, ' seconds'
# we will use a try loop so that it will exit when 'ctrl' + c is pressed and program ends gracefully, resetting GPIO
try:
# initialise fan by making it switch on for 5 seconds
print '\nFan test 5 seconds'
GPIO.output([fanOUT], GPIO.HIGH)
time.sleep(5)
GPIO.output([fanOUT], GPIO.LOW) # just so we know everything works!
print '\nCPU Fan Control is now ON. Press ctrl+c to exit' # raw_input('Fan Controller is ON Press [Enter] to continue')
while True:
# Read the temperature in C from the operating system
fSensor = open(pathSensor, 'r')
reading = float(fSensor.read())
fSensor.close()
# control CPU fan by comparing temperature with preset variables tempHigh, tempLow
if fanPower:
if reading <= tempLow:
GPIO.output([fanOUT], GPIO.LOW)
fanPower = False
# We have cooled down enough, turn the fans off
else:
if reading >= tempHigh:
GPIO.output([fanOUT], GPIO.HIGH)
fanPower = True
# We have warmed up enough, turn the fans on
temp = reading * readingMultiplier
# display the temperature to the console
print str(temp), dName[GPIO.input(fanOUT)]
# Wait a while
time.sleep(interval)
except KeyboardInterrupt:
# 'CTRL'+c to exit, turn off the drives and release the GPIO pins
#print 'Terminated'
raw_input('\nFan controller is now OFF! \nHit return and power off now')
GPIO.cleanup() #reset the GPIO ports
# coding: latin-1
# By Ralph Beardmore Jan 2017 for PI 3
# this is a temperature control. It runs in Python 2.x so code accordingly
# this is designed for NPN transistor and is normally OFF
# Import the libary functions we need
import RPi.GPIO as GPIO
import time
import subprocess
# Set which GPIO pins the fan output and power switch inputs are connected to
fanOUT = 8 #pin 3 = GPIO channel 8 see mode
fanPower = False
a
# configure the input and output pins
GPIO.setmode(GPIO.BOARD) # GPIO mode - BCM = channel, BOARD= pin number
GPIO.setup(fanOUT, GPIO.OUT) # fan control variable
# Map the on/off state to nicer names for display
dName = {} # make a list
dName[True] = 'ON '
dName[False] = 'OFF'
# CPU temperature monitor, all temperatures in centigrade!
pathSensor = '/sys/class/thermal/thermal_zone0/temp' # File path used to read the temperature
readingMultiplier = 0.001 # Value to multiply the reading by for user display
tempHigh = 60000 # Reading at which the fan(s) will be started (same units as file)
tempLow = 50000 # Reading at which the fan(s) will be stopped (same units as file)
interval = 2 # Time in seconds between readings in seconds
print '\nFAN TURNS ON AT ', int(tempHigh * readingMultiplier)
print '\nFAN TURN OFF AT ', int(tempLow * readingMultiplier)
print '\n interval = ', interval, ' seconds'
# we will use a try loop so that it will exit when 'ctrl' + c is pressed and program ends gracefully, resetting GPIO
try:
# initialise fan by making it switch on for 5 seconds
print '\nFan test 5 seconds'
GPIO.output([fanOUT], GPIO.HIGH)
time.sleep(5)
GPIO.output([fanOUT], GPIO.LOW) # just so we know everything works!
print '\nCPU Fan Control is now ON. Press ctrl+c to exit' # raw_input('Fan Controller is ON Press [Enter] to continue')
while True:
# Read the temperature in C from the operating system
fSensor = open(pathSensor, 'r')
reading = float(fSensor.read())
fSensor.close()
# control CPU fan by comparing temperature with preset variables tempHigh, tempLow
if fanPower:
if reading <= tempLow:
GPIO.output([fanOUT], GPIO.LOW)
fanPower = False
# We have cooled down enough, turn the fans off
else:
if reading >= tempHigh:
GPIO.output([fanOUT], GPIO.HIGH)
fanPower = True
# We have warmed up enough, turn the fans on
temp = reading * readingMultiplier
# display the temperature to the console
print str(temp), dName[GPIO.input(fanOUT)]
# Wait a while
time.sleep(interval)
except KeyboardInterrupt:
# 'CTRL'+c to exit, turn off the drives and release the GPIO pins
#print 'Terminated'
raw_input('\nFan controller is now OFF! \nHit return and power off now')
GPIO.cleanup() #reset the GPIO ports
The # comments should help you, this is good practice in programming as in six months you will have forgotten why you did things this way.
Customising -
you should experiment with these!
tempHigh
= 60000 # Reading at which the fan(s) will be started in Celcius
tempLow
= 50000 # Reading at which fan will turn off in Celcius
interval
= 2 # the loop interval in seconds, if you are not using the power
switch this can be made longer, say 20 seconds. It does cause a delay
on the power switch, but hey!
I
mentioned Python 2.x in the code, quick way to test, print 'hello!'
works in Python 2, print ('hello!') only works in Python3, it is now
a function not a statement.
Have
fun, keep a copy of this original program and try to understand how
it works. Sure hack the program and and learn from it, that is how
most of us got started in programming!
But
wait! We really need this to run every time we start our PI -