Best Raspberry Pi home automation tutorial: Web based

Raspberry Pi home automation system

Raspberry Pi home automation system based on Internet of Things

The Internet Of Things is the most trending technology today that stands alongside wearables and robotics. It is a very simple concept where devices in our home or wherever they are , have the capability to communicate with each other via the internet.Usually sensors are used with this technology to pass data to the internet. You can imagine  a sensor installed in your garden which uploads data like temperature, humidity, soil purity ,etc to the internet, and this data will be visible to you from anywhere around the world.Or imagine home automation systems connected to the net , which can be used to control appliances in your home like lights, door locks, air conditioning, etc through a web interface or smartphone application. A lot of technologies are being developed around this concept such as independent light-weight  IoT networks, protocols for passing data,etc. Here, I will show you how you can get started on making a raspberry pi home automation system that is web based using normal HTTP protocols.You will be able to control any appliance in your home from anywhere around the world when your done with this Raspberry Pi home automation tutorial.

What are the stuff required to do this project?

Hardware :

Raspberry Pi home automation system DIY Hacking

Relay circuit components

  1. Raspberry Pi model B with memory card preloaded with an OS.
  2. Bc547 Transistor.
  3. 5V SPDT relay.
  4. 1N4001 diode.
  5. Solder dot prototyping board.
  6. 9V battery
  7. (Optional) WiFi dongle : Edimax EW 7811UN.
  8. USB keyboard.
  9. HDMI monitor.

Software (Programming languages and OS  involved):

  1. PHP.
  2. HTML/CSS.
  3. Python.
  4. Linux/Rasbian.

So how does it work?

You can consider the whole system to be composed of two parts: Server and Client. Here, the server is the web interface consisting of buttons and UI (User Interface) that will allow you to turn ON/OFF a device.It consists of PHP files, Html files and a .txt file (to store data).The server usually stores information regarding the button press on the page (ON/OFF) on a .txt file.An example of this UI is : DIY Hacking IoT Implementation. This is a simple Html file called main.html ,consisting of two buttons.The clicking of the buttons will trigger the execution of a PHP file called button.php. This program serves as an API (Application Programming Interface) to store data on to a text file called buttonStatus.txt.The data is a string : “ON”, if ON button is clicked and “OFF”, if OFF button is clicked.Thus the current button press state is recorded in the text file : buttonStatus.txt.

Raspberry Pi home automation system DIY Hacking

Raspberry Pi home automation Block Diagram

The client side consists of a Raspberry Pi with a relay circuit connected to its GPIO pin.The pi runs a python program which is used to ‘Post’ a url link using urllib2.That is, the pi constantly reads the contents of a url link. Here, the url link is another PHP file called buttonStatus.php. This PHP file serves as an API to read the contents of the text file buttonStatus.txt.After reading the data, the python program checks if the string obtained is “ON” / “OFF” based on which it switches ON/OFF the relay respectively via its GPIO pin.

Raspberry Pi Home Automation system

Step 1: Preparing the html, php files

Here, the server side of the system has to be set up. If you are having your own domain, you can use the file manager service to drop these files into your server and can be used to control your IoT systems from anywhere around the world. The files to be put in your server are : main.html , button.php , buttonStatus.php and buttonStatus.txt , download them from here : DIY Hacking – Raspberry Pi home automation system and extract it. The program raspbi.py is the python program which is to be copied to your raspberry pi.If you are new to html and php , don’t worry. This project will need only a basic understanding of the two languages, spending some time on a few tutorials :HTML for beginners , PHP for beginners and reading the code would be sufficient. The html file consists of a basic UI with two buttons. On button press, it triggers a PHP program which writes a string to a .txt file depending on the button pressed.The .txt file stores information of the last button state.

However, if you don’t have a domain, you can simulate a domain in your local network or wifi using a service called xampp. It is very simple, the instructions for using it are here : Xampp Web Server Emulator Windows and Xampp Web Server Emulator Linux. Using xampp you can use your pc as a local web server. However, the IoT systems gets confined to a control range limited to your home wifi network. Drop the html, php and .txt files into the /htdocs/xampp directory.

 

Step 2: Setting up the relay circuit for the Raspberry Pi home automation system

Raspberry Pi home automation system

Relay Circuit for the Raspberry Pi home automation system

A small relay circuit is to be made , to switch an appliance ON/OFF.It consists of a BC547 transistor, which acts like a switch.The transistor triggers the relay when it receives a voltage at its base from the GPIO pin of raspberry pi.A 1N4001 diode is used to protect the transistor from reverse voltages created in the relay coil. The circuit can be powered either using the 5V supply from the raspberry pi or using an external battery.Use the schematic and pinout diagram below to make the connections for the raspberry pi home automation system :

Raspberry Pi home automation system

BC547 pinout


Raspberry Pi home automation system DIY Hacking

Relay Schematic

Step 3: Setting up the Raspberry Pi

If you have a brand new raspberry pi and are looking for instructions to load the OS into the SD card please follow this tutorial: Installing the OS for raspberry pi.The default OS used with the pi is the raspbian.To use the GUI for pi, use the command “startx” in the terminal. You can use an Edimax wifi dongle for wireless connectivity, use the wifi config application in the desktop of your pi to scan and connect to the wifi network.The raspberry pi is used to continually run a python program called raspbi.py , copy this file to your pi. Before executing this file , open the file using “nano raspbi.py” and edit the line that says : “response=urllib2.urlopen(‘https://diyhacking.com/projects/IOTautomation/buttonStatus.php’)”  by replacing the link within ‘ ‘ , by your own link generated either through xampp or your own domain.On using the command “sudo python raspbi.py”, it will initiate the program.

Raspberry Pi home automation system

Edimax Wifi Dongle EW 7811UN

You can use the raspberry pi without a monitor by using ssh. SSH (Secure Shell) can be used to control the pi remotely from a pc in the same home network, if you know the ip address of your pi. Use “ifconfig” command on your pi to find the ip address. Use “sudo /etc/init.d/ssh start” to initiate the ssh service.Then, from a remote pc using putty software (for windows) , open the terminal and enter the command “sudo ssh ipaddress -l pi” , “ipaddress” is replaced with the actual ip address you obtained for the pi in the range 192.168.1.1 – 192.168.1.254.

Raspberry Pi home automation system

Raspberry Pi home automation system Test Setup

Connect the relay circuit to the raspberry pi. You need to connect GPIO pin no : 5 and 6 (GND) to the circuit as in the schematic. Please note: Raspberry pi uses GPIO pins 5 and 6 to get into safe mode by shorting them together. Hence, please use any other GPIO other than 5 by editing the python program, to prevent booting into the safe mode. The video showing the raspberry pi home automation system in action:

This system can be modified to control anything in your home from anywhere around the world, use it to even collect data from sensors and view them from anywhere.Protocols like MQTT and APIs of thingspeak to name a few can be used for large number of devices/sensors to standardize the communication protocol.

Recommended Posts
Showing 73 comments
  • Deepansh
    Reply

    ​I tried doing some automation using Apache, didn’t really work for me. So I tried using node and it works wonders. I even made a tutorial to help the community: https://github.com/deepanshpahwa/Home-Automation

  • Afeezadal
    Reply

    Pls I need 8 channels arduino board voice and smartphone control, how much and how can I order from Nigeria?

  • saksham malhotra
    Reply

    Where is the python code for this project?

  • homemedia
    Reply

    Home Media Automation provides resources and guides for those taking a do-it-yourself approach to home automation with hardware such as a home automation system that controls home theater lighting, structured wiring, Multi room Audio and video , Surveillance ,climate, multimedia and other areas of the home. CALL Now:- (208)7250075. Best Home Theater Installation Services in Ketchum you can refer.

  • Phan Sreypich
    Reply

    What should I do if I don’t have my own domain name in server?

  • Craig Oie-Lugo
    Reply

    What cables do you need?

  • Ken Lao
    Reply

    Orange Pi PC H3 Development Board Compatible With Raspberry Pi 2 only $18.79 free shipping.

    http://www.shopalieasy.com/index.php/product/orange-pi-pc-h3-development-board-compatible-with-raspberry-pi-2-2/

  • Ustad
    Reply

    Came across this from Google, dirty but good woork, I came across another project at pihome.eu but this project ist available for download :(

  • JAIMIN
    Reply

    easiest tutorial ever…….https://youtu.be/3u45htuQeag

  • steven
    Reply

    i really like your tutorial. it is helping me as am doing my final year project. thank so much man.

  • Shourya
    Reply

    Thanks a lot for this idea. The tutorial is nothing short than great. I’ve even developed an android app using the GET and POST commands used here.

  • Soprano15
    Reply

    Hi,
    Thank you very much for this exceptional tutorial. I really appreciate your passion in taking your time to share your knowledge with us. I went through your tutorial but the only thing that I do not get is this:

    I have run the cmd: nano rasbpi.py and I can see the line of code that I need to change but I don’t know how to get “my own link generated through xampp”.
    I really need your help because I do not have my own domain.
    Thanks.

  • ASHIRWAD A
    Reply

    I couldn’t understand where to connect the 3 pins other than the 2 relay coil pins. If you could elaborate it’d be a great help. Thanks.

    • Soprano15
      Reply

      Hi the 3 pins are the switching pins: the pin labelled: X1-2 is the common pin of the relay: this is where you connect the Live cable coming from the light ceiling rose (depending on your country wiring installation)

      The pin labelled: X1-1 is the NO (Normal Open contact of the relay): this is the contact pin where the Tube Live is connected.

      The other pin is not connected and is the NC (Normal Closed).

      Now how the relay work or switch: when the RPi is not driving the GPIO pin 5, the relay is not energized and no current will flow through the NO pin X1-1 and the tube is OFF.

      When the RPi drive the GPIO 5, the signal will flow through the transistor and will energize the relay and the relay will switch the contact X1-1 and the tube will light up.

      I think this is clear. If you still do not understand please give me your email and I will draw in on paper clearly and email it to you.

      Now my question to you: I am struggling to generate my own link through xmpp in order to paste it on the ‘rasbpi.py’ code. because I do not have my own domain. I you have done this, can you help me please.

      I really need to get this project work because I have spent lot of hours on it.

      Thanks

  • ASHIRWAD A
    Reply

    I couldn’t understand where to connect the 3 other tha the 2 relay coil pins. If you could elaborate it’d be a great help. Thanks.

  • deeraj
    Reply

    Hi,problem is the xampp sofware works in internet explorer but not in crome why?

  • Prasad
    Reply

    Can you explain , how the relay is connected to the tube light switch?

    • prathap
      Reply

      when i ran sudo rasbpi.py on my rpi the following was shown
      Traceback (most recent call last):
      File “rasbpi.py”, line 1, in
      import RPi.GPIO as GPIO
      RPi.GPIO.SetupException: This module can only be run on a Raspberry Pi!
      can u plz tell me the solution

      Thanks in Advance.

  • 7core
    Reply

    hi , can you please write me – i need your help with a similar project please it’s important

  • Faiz
    Reply

    Hi. its an amazing tutorial. One quick question; Can we use something more secure than using a file, like an API call or other things that can effectively do the job. If so, please provide some details or links for guidance. Thanks.

  • sachit
    Reply

    Can you please provide me the circuit configuration?

    • rohit
      Reply

      sir ji , can u tell where should i save these file given by u …. in raspberry pi or in pc

  • Zanib
    Reply

    Hi! Could you tell me if it is possible to control 4-5 lights through different buttons on the site instead of just one light? What major changes will I have to make?

  • Raghav Dinesh
    Reply

    I am using for only one switch.. http://www.aliexpress.com/item/1PCS-8-Channel-5V-relay-isolation-control-Relay-Module-Shield-250V-10A-for-MCU-AVR-51/719670342.html

    Software part looks working fine, but unable to light up one 15w bulb.
    I am not getting any type of error with code. Circuit which I followed includes (Raspberry Pi 2)GPIO pin5 to > Base of Transistor(BC557) and Emitter of transistor is connected to GPIO ground pin6. Collector is connected to the positive end of diode(IN4007). Diodes negative end is connected to the input one of the relay board(Model: BTE 13-005). Now In the relay boards Ground is connected to the negative of the 9V battery and VCC is connected to the positive of the 9V battery. In relay board There are three slots for giving output to 250v to circuit where Outer(not middle one) connection are used to use relay as a switch. I am absolutely new to IOT stuff. I can’t figure out where is the possible problem. Thanks

    • Arvind Sanjeev
      Reply

      When you run the code, what status do you see? ON/OFF? And are you using xampp to simulate the server?

      • Raghav Dinesh
        Reply

        Not showing any status, screen runs blank and GPIO is able to send signals!

  • ferry
    Reply

    My raspberry status ‘off’ constantly even though I pressed the button ‘on’ , how to overcome them
    to be known , I use the program rasbpi.py exactly as exemplified

    thanks

    • Arvind Sanjeev
      Reply

      Try checking the connections and pin number, try shorting the GPIO pin directly with VCC/GND and see if that changes anything.

      • ferry
        Reply

        it still the same, when i short the gpio pin with vcc, it reboot but when i short to the gnd nothing’s happen

        • Arvind Sanjeev
          Reply

          Hey, are you using xampp to simulate the server?

          • ferry
            Reply

            finally it’s solved, its the matters of root privilege, thanks very much arvind, btw can’t i ask your email

            • Arvind Sanjeev
              Reply

              Cool :) My email is ars@diyhacking.com
              But if you have any doubts on these projects, please post it as comments on the page, so that it will also help others.

  • Ichikawa
    Reply

    Hi there….
    thank you for your great tutorial…it’s very useful..
    I am going to use it for sensing a contact of a device and controlling it via web…but the problem is I want to control it from a long distance So it wont be enough if I use a wifi signal and local host like xampp webserver emulator…I want to replace WiFi dongle Edimax EW 7811UN because it’s unavailable in Indonesia..do you have any recomendation?and I wanna ask, is it possible to buy a domain without a hosting?I still don’t understand how the system send data to the Internet..
    I’m a newbie at this, so can you help me to build a system that can really sense and control things from far away?!?
    thanks

    • Arvind Sanjeev
      Reply

      Hi, you will have to do some research on port forwarding. You will be able to use the same method to control stuff via the internet and not just wifi.
      Also, any wifi dongle would do.

  • ferry
    Reply

    what a great tutorial

    can i expand the relay, what do i need if it can

    thanks b4

  • Andrea
    Reply

    Hi,
    thank you very much for your great tutorial!!
    I am going to use it for switching on a led on my internet controled robot.
    I am totally new in programming.
    Can I ask you how I can modify your code for not having a confirmation web page of switch on or off?
    I would like to have only a button status change ( color transition for example).

    Thank you
    Andrea

    • Arvind Sanjeev
      Reply

      Hello Andrea, you can learn the basics of Html from w3 schools or other sites. Its pretty easy, and then edit the code here to suit your needs :)

  • Sumod Kulkarni
    Reply

    I’m thinking of buying a raspberry pi for this project and any future projects I might take up since I don’t already have one. Which one would you suggest? Model B+ or the new raspberry pi 2?

  • hardy
    Reply

    output voltage of the Raspberry pi is 3.3V and the control signal voltage of the relay board is 5V, we need to change the 3.3V signal to 5V signal..how were u able to achieve that here?
    Could you elaborate.

    • Arvind Sanjeev
      Reply

      Hey, if you go carefully through the tutorial, you will notice that I used a transistor with the pi. The transistor acts like a switch and passes 9V from a battery to the relay when the pi gives a 3.3V signal to the transistor’s base.

      • Gokul
        Reply

        When i execute the python code..im getting
        404
        Traceback (most recent call last):
        File raspi.py ,line 17,in
        print status
        NameError: name ‘status’ is not defined

        Could you help me with this?

        • Arvind Sanjeev
          Reply

          Seems like your: response = urllib2.urlopen is not working. Put the line “status = 0” after the line “true = 1” and initialize it.

        • Prashant
          Reply

          Hey, I am also getting the same error.
          Have you solved it out?
          Plzz tell me how to remove this error..

          • Soprano15
            Reply

            Hi there, I am having the same problem and I don’t know what is the problem:

            I have edited the line as: response = urllib2.urlopen(‘http://192.168.0.44/xampp/buttonStatus.php’)
            I have downloaded this DIYhackingIoT (which contains:main.html, button.php, buttonStatus.php, buttonStatus.txt and rasbpi.py)in my PC document directory. I then copied these files main.html, button.php, buttonStatus.php, buttonStatus.txt to my PC C:/ drive in xampp and I have copied the rasbpi.py in my raspberry Pi desktop using WinSC.

            I have been able to test my xampp control panel by launching the control panel and click start. I then opened a new web browser and got to see the xampp server.

            But i am still having a problem to run the system,
            please help.

            Thanks

  • Sree
    Reply

    I couldnt find the relay you mentioned in local store.. can you tell me where i can find one ??

    i found this one online http://potentiallabs.com/cart/relay-6v?search=5V%20RELAY&description=true

    can i use this one ??

  • Alfred
    Reply

    Hi,
    Your tutorial is very useful. I’m kinda stuck at the creating-relay circuit part.I have bought,
    1. Bc547 Transistor.
    2. 5V SPDT relay.
    3. 1N4001 diode.
    4. Solder dot prototyping board.

    as you said. is all these things enough for relay circuit ?? I’m a Noob in electronics. Please can you please elaborate on creating relay circuit. Thanks in advance.

    • Arvind Sanjeev
      Reply

      Its pretty simple, can you read the schematic diagram on step 2 of this tutorial? Just follow that, if you are new to schematics, check this out: https://learn.sparkfun.com/tutorials/how-to-read-a-schematic it will make it easier for you to read.

      • Rajesh Panicker
        Reply

        Superb project. Thank you so much. Will be my first experiment. One question before I begin – where does the battery fit in? I’m presuming that the negative of the battery will be connected to the Ground in the circuit (which will also be connected to the Ground of the RPi) and the positive of the battery will be connected to the joint of the Collector and the Diode in the schematic. A confirmation would be helpful.

  • dhruv
    Reply

    First of all thanks for such good tutorial.

    May i use this

    https://m.ebay.in/mobinweb/itm/161393844135?_mwBanner=1&_trksid=p3984.m1497.l2649

    Instead of 5v spdt relay?

  • nithin
    Reply

    Hi,
    I am working with home automation project using cloud with raspberry Pi B+. After several hours of googling I can able to figure out one which will be helpful for my project. Here it is: https://developer.ibm.com/iot/. I had simulated the IOT concept from this site and I can find that they are actually providing the sensor values from RPi(just reading values from the RPi to cloud), but there is no option for sending commands to RPi. What I want is to control the relays(home automation) by cloud. So I want to send the commands to RPi. Can I make the home automation project with IBM concept?

    • Arvind Sanjeev
      Reply

      I am not familiar with the IBM tools, but here I am simply using http GET & POST to control stuff. Will this work out for you?

      • nithin
        Reply

        Hi Aravind,
        Actually I am only familiar with embedded c programming.That is why I had chosen IBM concept.There I can get the stuff in C programming itself. What I am looking for is sample codes for home automation in Linux C for RPi or protocol stack in Linux C for connecting RPi to cloud

        Best regards,
        Nithin

  • Abdillah
    Reply

    Thanks bro..
    This tutorial very helpful

  • Shollix
    Reply

    OK. This is it….Its all about smart-home automation. But am to major on lightening control system in which i want to control various lights in the home making use of my mobile phone running an app which i will build. Also making use of arduino, webserver, system-apps and so on. please lead me so it will be a success.

  • Shollix
    Reply

    Hello bro,
    Am embarking on my final year project topic “Developing a lighting control system using a mobile app”. Have gone through all your tutorials but its seems am not getting it well. Please lead me through.

  • hardy
    Reply

    Is there any project regarding Rfid reader using Rpi

  • hardy
    Reply

    How much does the above project cost overall in INR ?
    Im planning to implement a IoT based Home automation project using a Rpi.

    • Arvind Sanjeev
      Reply

      Below Rs.4000. Raspberry pi and the wifi dongle are the only major investments.

  • Sanjith
    Reply

    Will it work with 230V Indian condition

  • lipitor claims
    Reply

    When I originally commented I seem to have clicked on the -Notify me when new comments are added-
    checkbox and from now on every time a comment is added I get four emails with
    the exact same comment. Is there an easy method you are able to remove me from that service?
    Appreciate it!

    • Arvind Sanjeev
      Reply

      Hello,
      I am very sorry you are facing this issue. I have tried fixing it, please let me know if you continue to receive such emails.

pingbacks / trackbacks

Leave a Comment

7 + 2 =

Start typing and press Enter to search