Smart Lighting System - Using LED's, LDR and Raspberry Pi

Updated: Apr 13

Street lights play a major role in increasing the safety of people working late nights like drivers. Lighting accounts for 10-38% of the total electrical energy consumption across the globe. Initially, operation of lights was done manually. As people getting busy day by day in their daily routine activities, they keep forgetting to switch OFF the lights even when there is ample amount of sunlight present and switch ON when there is a need for lights. This lead to heavy wastage of electricity. Later, engineers came up with the timer circuits in which the circuit allows the light to function for a pre-defined time interval. But, this idea also had its drawbacks due to the seasons, weather conditions and at times during special occasions when the need for lighting differs from the usual periods.


Our project comes up with an easy solution for the above-mentioned drawbacks from the previous models. In this concept, we use an LDR sensor to sense the amount of sunlight present in the environment. With the help of these LDR values switching of lights will be done automatically. It automatically switches OFF the lights in the presence of illumination and switch ON the lights in a case when the sunlight goes below the visible region of eyes.


Hardware Requirements:


1. Breadboard:

Breadboard
Breadboard

A #breadboard is a flat piece of wood that is provided with holes that allow users to build a circuit including the components and connections without the need for soldering due to which it is reusable and finds its best usage for the students who are new to build circuits. The holes in any horizontal line will be in series whereas the vertical holes remain at an equipotential state. There are different sizes of breadboards available in the market which include "full size", "half size" and, "mini size" breadboards.

2. Connecting wires:


Connecting wires
Connecting wires

Jumper wires are used to establish connections between different components in the circuit.


3. USB Cable: This USB cable is used to connect the Raspberry Pi to the power supply. It also helps in the transmission of data.


USB Cable
USB Cable

4. LDR Sensor:


LDR- Light Dependant Resistor Sensor
LDR- Light Dependant Resistor Sensor

LDR- Light Dependent Resistor. This is a cadmium-sulfide cell works based on the principle of Photoconductivity. It is a resistor whose resistance value changes depending upon the intensity of light falling on it. When the light falls on the surface of the senor, material conductivity varies as a result of which resistance also varies.


5.Raspberry Pi 4 Model-B:


Raspberry Pi 4 Model-B
Raspberry Pi 4 Model-B

We are using #Raspberrypi to connect with the LEDs, the #LDR sensor, and display the output. It contains several I/O pins using which we can connect the module and then by coding the Raspberrypi, we will receive the commands/signals that are sent from the mobile. This powerful credit-card-sized single-board computer can be used for many applications and supersedes the original Raspberry Pi Model.


6. Ceramic Capacitor:


0.1 uF ceramic capacitor
0.1uF ceramic capacitor

Luminous intensity is inversely proportional to the resistance. The resistance of the LDR changes with respect to the change in intensity. This value of the resistance will be sensed by using the time constant concept. Based on the value of the time constant (i.e., the time taken to charge the capacitor is resistance multiplied by the value of capacitance.) resistance of the LDR can be found accordingly. In this project, we use a 0.1uF ceramic capacitor.


7. 16*2 LCD: LCD- Liquid Crystal Display is an electronic module that uses liquid crystal to produce a visible image. It is the basic module that is generally used in DIY and circuits. The display segments are affordable and simply programmable.

16*2 LCD
16*2 LCD

8.LED's: LED is a semiconductor light source that emits light when a current passes through it. Electrons in the semiconductor combine with holes by passing through the gap which inturns release energy in the form of photons. In this project, we use 4 LEDs of any desired color.

LED's
LED's

9. LCD Backpack: To reduce the number of I/O pins, an I2C module is used to interface the 16*2 LCD with the raspberry pi module.

10. SD Card:

SD card
SD Card

SD card is the key part of a Raspberry Pi, It provides the initial storage for the Operating System and files.

Software Requirements:


1. SSH Terminal: The SHH Terminal is used in this project to connect the Raspberry Pi module to the terminal of another computer or peripheral device. Encrypted data transfer between two computers is supported by this terminal.

SSH Terminal
SSH Terminal

2. Python IDLE: Programming is done in #Python language in an IDE (Integrated Development Environment) which is a platform where we can not only write the code but also run, and test the working.

Python Idle
Python Idle

Circuit Connection:


Circuit diagram of smart lighting system using Raspberry Pi
Circuit diagram of smart lighting system using Raspberry Pi

Hardware Circuit:


Smart lighing system using Raspberry Pi - Circuit diagram
Smart lighing system using Raspberry Pi - Circuit diagram

What goes where??


Circuit Connection involves the following steps:

  • Both the terminals of the LDR sensor are connected to the GPIO pins of the Raspberry Pi and one terminal of the capacitor is connected to the LDR sensor terminal and the other terminal is connected to the ground.

  • All the 4 LEDs are connected in parallel between Vss and the ground.

  • 16*2 display is connected using the backpack.

  • Ground and Vcc and of the I2C module are connected to the ground and Vcc of the Raspberry pi.

  • Similarly, SDA and SCL pins of I2C pins are connected to the corresponding pins of Raspberry pi as shown in the circuit diagram.

  • USB cable is used to power up the Raspberry Pi.

Code Description:


ldr_pr_value.txt:

import RPi.GPIO as GPIO
import time

For GPIO pins set up and output declaration RPi.GPIO library is imported. Importing the time library will give access to using time functions like providing delay.

def LDR(cpin,lpin):
        GPIO.setmode(GPIO.BOARD)
        cap=0.0000001
        adj=2.130620985

We take the pin numbers connected to the LDR as the arguments. Now, we set the GPIO mode as the GPIO.board which represents the connections placed on the board. We have given the value of capacitance as 0.1uF and the value of the adjustable voltage is given.

GPIO.setup(cpin, GPIO.OUT)
        GPIO.setup(lpin, GPIO.OUT)
        GPIO.output(cpin, False)
        GPIO.output(lpin, False)

We initialize the GPIO pins and them as output pins and them as low.

        time.sleep(0.2)
        GPIO.setup(cpin, GPIO.IN)
        time.sleep(0.2)
        GPIO.output(lpin, True)
        starttime=time.time()
        endtime=time.time()
        while (GPIO.input(cpin) == GPIO.LOW):
             endtime=time.time()
        measureresistance=endtime-starttime
        res=(measureresistance/cap)*adj
        return(res/10)

Once we start charging the capacitor, we note the start time and initialize the end time. Once the capacitor is charged completely, the end time is noted. Now, the interval is found by subtracting the start time from the end time. Now, since the time constant is obtained. We can find the value of the resistance from the obtained time constant.


Smart lighting main program:

import RPi.GPIO as GPIO
from ldr_pr import LDR
import I2C_LCD_driver

For GPIO pins set up and output declaration RPi. GPIO library is imported. The next command imports the LDR values from the ldr_pr function file. The next command is used to import the I2C_LCD_driver library for the functioning of LCD.

mylcd = I2C_LCD_driver.lcd()

mylcd.lcd_clear()
mylcd.lcd_display_string('Smart Lighting',1,2)
mylcd.lcd_display_string('Mode: ON',2,4)

mylcd will be the variable which will have the initial commands. Clear the LCD before printing any line. Now the string is printed, row and column numbers are mentioned accordingly in the code. 1st string corresponds to 1st row, 2nd column and 2nd string corresponds to 2nd row, 4th column.

while True:
    try:
        GPIO.setmode(GPIO.BOARD)
        GPIO.setwarnings(False)
        GPIO.setup(18,GPIO.OUT)
        p=0
        for i in range(0,5):
            p=p+LDR(11,13)
        p_avg = p/5
        p_diff = 500 - p_avg

GPIO mode is set and the warnings are set as false. we set the GPIO mode as the GPIO.board which represents the connections placed on the board. We initialize the 18th pin as an output pin. We run through a lot of values where there might be a lot of fluctuations. so, we try to normalize the values by taking the average value. we calculate the average value of 5 samples here.

 if p_diff >= 0:
            GPIO.output(18, GPIO.HIGH)
            mylcd.lcd_clear()
            mylcd.lcd_display_string('LDR value:',1)
            mylcd.lcd_display_string(str(round(p_avg)),1,10)
            mylcd.lcd_display_string('LED ON',2,4)

Whenever the average value is greater than 500, the difference will be greater than zero. In this case, we set the GPIO as high, clear the LCD and update the status. Corresponding LDR values along with the p_avg that we are getting, round here will put a rounding condition, p_avg which is a float value will be rounded and 'str' is used to convert the float object into a string object so that we will be able to display it on the LCD. And we pint the status of the LED, in this case, it is "ON".

else:
            GPIO.output(18, GPIO.LOW)
            mylcd.lcd_clear()
            mylcd.lcd_display_string('LDR value: ',1)
            mylcd.lcd_display_string(str(round(p_avg)),1,10)
            mylcd.lcd_display_string('LED OFF',2,4)

Now the else condition corresponds to the case when the value of p_avg is less than 500 or the difference is less than zero. In this case, we set the GPIO as low, clear the LCD and update the status. Corresponding LDR values along with the p_avg that we are getting, round here will put a rounding condition, p_avg which is a float value will be rounded and 'str' is used to convert the float object into string object so that we will be able to display it on the LCD. And we pint the status of the LED, in this case, it is "OFF".

except KeyboardInterrupt:
        mylcd.lcd_clear()
        mylcd.lcd_display_string('Smart Lighting',1,2)
        mylcd.lcd_display_string('Mode: OFF',2,4)
        break

GPIO.cleanup()

Whenever the keyboard interrupt is given in this case it is 'Ctrl+C'. LCD will be cleared initially. The strings will be printed accordingly and come out of the loop and the last line of code will clean up the GPIO.


Complete code:

import RPi.GPIO as GPIO
from ldr_pr import LDR
import I2C_LCD_driver

mylcd = I2C_LCD_driver.lcd()

mylcd.lcd_clear()
mylcd.lcd_display_string('Smart Lighting',1,2)
mylcd.lcd_display_string('Mode: ON',2,4)

while True:
    try:
        GPIO.setmode(GPIO.BOARD)
        GPIO.setwarnings(False)
        GPIO.setup(18,GPIO.OUT)
        p=0
        for i in range(0,5):
            p=p+LDR(11,13)
        p_avg = p/5
        p_diff = 500 - p_avg
        if p_diff >= 0:
            GPIO.output(18, GPIO.HIGH)
            mylcd.lcd_clear()
            mylcd.lcd_display_string('LDR value:',1)
            mylcd.lcd_display_string(str(round(p_avg)),1,10)
            mylcd.lcd_display_string('LED ON',2,4)

        else:
            GPIO.output(18, GPIO.LOW)
            mylcd.lcd_clear()
            mylcd.lcd_display_string('LDR value: ',1)
            mylcd.lcd_display_string(str(round(p_avg)),1,10)
            mylcd.lcd_display_string('LED OFF',2,4)

    except KeyboardInterrupt:
        mylcd.lcd_clear()
        mylcd.lcd_display_string('Smart Lighting',1,2)
        mylcd.lcd_display_string('Mode: OFF',2,4)
        break

GPIO.cleanup()


Download the complete code here:

Smart Lighting with normal logic code
.tx
TX • 1KB
ldr_pr_value
.txt
TXT • 630B

Smart Lighting with Inverse Logic code
.t
T • 1KB

I2C_LCD_driver_function
.txt
TXT • 5KB








Note: All these files should be converted to the python file format (i.e., .py format) before uploading the code to the Raspberry Pi board.


Working:

In the program, we have set the LDR value threshold - 500. So, whenever the value goes above 500, the Raspberry Pi would turn all the LEDs connected ON and if the value is below 500 then the LEDs are OFF.


Output 1 - Starting the Project

Output 2 - LDR value below the threshold

Output 3 - LDR value above the threshold


Check the practical implementation of the above-explained project and see how it works before you try it yourself.


Video by- Sai Parimal



See Also:

1.Interfacing I2C - LCD with Raspberry Pi

2.Using Telegram Bot with Raspberry Pi - Sharing Text and Files

3.IoT - Distance measurement using Ultrasonic Sensor & Raspberry Pi