The Official Raspberry Pi Projects Book - Projects_Book_v4

(singke) #1

Tutorial


raspberrypi.org/magpi The Official Raspberry Pi Projects Book 109

DIY SUNRISE ALARM


directory containing the code by using the command
cd rpesk-advanced.

>STEP-05
Run the code
The time has come to run the code and test out the
alarm! After checking that the circuit you have built
is an exact replica of the one shown in the circuit
diagram, and that it is connected to the Pi, run the
command sudo python 01_sunrise_alarm.py. You
can test that the alarm works by shining a torch at the
photoresistor from within a fairly light room. The LEDs
should start to flash, and the buzzer should sound. If
this happens, congratulations!

from Tkinter import *
import RPi.GPIO as GPIO
import time, math

GPIO.cleanup()

GPIO.setmode(GPIO.BCM)

sunrise = 50

a_pin = 18
b_pin = 23

buzzer_pin = 24
red_pin1 = 27
red_pin2 = 22

GPIO.setup(buzzer_pin, GPIO.OUT)
GPIO.setup(red_pin1, GPIO.OUT)
GPIO.setup(red_pin2, GPIO.OUT)

def discharge():
GPIO.setup(a_pin, GPIO.IN)
GPIO.setup(b_pin, GPIO.OUT)
GPIO.output(b_pin, False)
time.sleep(0.01)

def charge_time():
GPIO.setup(b_pin, GPIO.IN)
GPIO.setup(a_pin, GPIO.OUT)
GPIO.output(a_pin, True)
t1 = time.time()
while not GPIO.input(b_pin):
pass
t2 = time.time()
return (t2 - t1) * 1000000

def analog_read():
discharge()
return charge_time()

Sunrise_alarm.py


Language
>PYTHON 2

DOWNLOAD:
magpi.cc/2eCbCtZ

>STEP-06
Make it your own
The default threshold for the alarm’s activation is
when the photoresistor reaches a value of 50, which
works well for testing as described previously.
However, in order to use the alarm to accurately
detect the sunrise in the morning, this value can
be changed by entering the file editor with the
command nano 01_sunrise_alarm.py and then
changing the value found on line 13. We would
recommend that you use 30 for fairly accurate
detection of dawn. Save this change by pressing
CTRL+X, followed by Y, then the ENTER key. This
code can now be run again as in Step 05.

def read_resistance():
n = 20
total = 0 ;
for i in range( 1 , n):
total = total + analog_read()
reading = total / float(n)
resistance = reading * 6.05 - 939
return resistance

def light_from_r(R):
return math.log(1000000.0/R) * 10.0

while True:
GPIO.output(red_pin1, False)
GPIO.output(red_pin2, False)
light = light_from_r(read_resistance())
print light
x = 0
if light > sunrise:
GPIO.output(red_pin1, True)
GPIO.output(red_pin2, False)
while True:
x = x + 1
GPIO.output(buzzer_pin, True)
time.sleep(0.001)
GPIO.output(buzzer_pin, False)
time.sleep(0.001)
if x == 250 :
x = 0
break
GPIO.output(red_pin1, False)
GPIO.output(red_pin2, True)
while True:
x = x + 1
GPIO.output(buzzer_pin, True)
time.sleep(0.001)
GPIO.output(buzzer_pin, False)
time.sleep(0.001)
if x == 250 :
x = 0
break
Free download pdf