Raspberry Pi Project 1: Automatic Night Light

A simple project that combines the use of an Ultra Bright LED, a Transistor and a Light Dependant Resistor to create a night light.

In the following project, the ultra bright LED will switch on when the light darkens to a pre-defined level and switch back off when the light brightens above a certain level. It can be tested by covering the photoresistor.

These levels can be changed by altering the values on 13 and 14.

Build the following circuit and ensure that the photoresistor is pointing away from the LED.

Raspberry Pi Project Automatic Night Light Schematic

Open IDLE on your Raspberry Pi (Menu > Programming > Python 2 (IDLE)) and open a new project (File > New File).  Then type the following:

import RPi.GPIO as GPIO
import time

SensorPin=17
TriggerPin=27
LightPin=18
GPIO.setmode(GPIO.BCM)
cap=0.000001
adj=2.130620985
GPIO.setup(LightPin, GPIO.OUT)
GPIO.output(LightPin, False)

switchon=2500
switchoff=2000

def measureresistance(mpin,tpin):
    GPIO.setup(mpin, GPIO.OUT)
    GPIO.setup(tpin, GPIO.OUT)
    GPIO.output(mpin, False)
    GPIO.output(tpin, False)
    time.sleep(0.2)
    GPIO.setup(mpin, GPIO.IN)
    time.sleep(0.2)
    GPIO.output(tpin, True)
    starttime=time.time()
    endtime=time.time()
    while (GPIO.input(mpin) == GPIO.LOW):
        endtime=time.time()
    return endtime-starttime

i=0
t=0
lighton=False
while True:
    
    res=(measureresistance(SensorPin,TriggerPin)/cap)*adj
    i=i+1
    t=t+res
    if i==10:
            t=t/i
            if t>switchon and not lighton:
                lighton=True
                GPIO.output(LightPin, True)
                print("Light On")
            if t

Save your project as nightlight.py (File > Save As) in your Documents folder.

Now open Terminal (Menu > Accessories > Terminal) and type the following command:

python nightlight.py