How to Control an LED with Raspberry Pi Webserver using Apache

Controlling an LED with Raspberry Pi Webserver using Apache

In this tutorial, we will install Apache web server in Raspberry Pi to control the LED from a webpage that can be accessed from anywhere over the internet. This is a basic tutorial with minimum features and it can be further modified to use this method in IoT-based home automation, remote control automation, robotics, etc.

Here we control an LED connected to Raspberry Pi by using Apache web server. For this, we create an HTML/php web page which has two buttons - one for turning on the LED and the second for turning off the LED.

 

Components Required

  1. Raspberry pi board (With Raspbian operating system)
  2. LED
  3. 250-ohm resistor
  4. Jumper Wires

 

An SSH client (Putty) is used to connect the Raspberry pi using a Laptop or computer. For this, the raspberry pi needs to be connected to a network via LAN or Wi-Fi. If you have a separate monitor for your raspberry pi, then it's better to connect raspberry pi with the monitor and you don’t have to use any SSH client.

 

Controlling LED using Raspberry Pi Webserver

Step 1: Connections

Raspberry Pi LED Connection Circuit

The connections in this project are quite simple - the positive pin of LED is connected to GPIO 27 pin and the negative pin to a 270 ohm resistor, the other side of which is connected to GND pin.

 

Step 2: Installing WiringPi Library

WiringPi is a PIN-based GPIO access library written in C for the BCM2835, BCM2836, and BCM2837 SoC devices used in all Raspberry Pi versions. It’s released under the GNU LGPLv3 license and is usable from C, C++, and RTB (BASIC) as well as many other languages with suitable wrappers.

1. First we will update our Pi with the latest versions of Raspbian using the command:

sudo apt-get update

 

2. Now we will install git by using this command:

sudo apt-get install git-core

 

3. Now obtain WiringPi using git by this command:

git clone git://git.drogon.net/wiringPi

 

4. Then install WiringPi library using:

cd wiringP./build

 

Step 3: Installing a Web Server

Apache is a very popular webserver, designed to create web servers that have the ability to host one or more HTTP-based websites. Apache Web Server can be enhanced by manipulating the code base or adding multiple extensions/add-ons. In our project, we are using an HTTP server and its PHP extension.

To Install Apache web server, we will use the following commands:

First, update the available packages:

sudo apt-get update

 

Now, install the apache2 package by using this command in the terminal:

sudo apt-get install apache2 -y

 

To test the web server whether it is working or not, go to your browser and type the Pi’s IP address in the tab.

To find the Pi's IP address, type ifconfig at the command line.

By default, Apache puts a test HTML file in the web folder. This default web page is served when you browse to http://192.168.1.31 (whatever the Pi's IP address is) from another computer on the network.

Browse to the default web page either on the Pi or from another computer on the network and you will see the following:

Apache2 Webserver

This means the Apache web server is working.

 

Now we will see how to change the default web page with your own HTML page

This default web page is just an HTML file on the filesystem. It is located at var/www/html/index.html.

Navigate to this directory in a terminal window and have a look at what's inside:

cd  var/www/html
ls -al
This will show you:
total 12
drwxr-xr-x  2 root root 4096 Jan  8 01:29 .
drwxr-xr-x 12 root root 4096 Jan  8 01:28 ..
-rw-r--r--  1 root root  177 Jan  8 01:29 index.html

 

This shows that by default there is one file in /var/www/html/ called index.html and it is owned by the root user. To edit the file, you need to change its ownership to your own username. Change the owner of the file using:

Sudo chown pi: index.html.

 

You can now try editing this file and then refresh the browser to see the web page change.

 

Install PHP in Raspberry Pi  

Now if we want to use PHP code along with HTML, then we have to further install the PHP extension in Raspberry pi. Using PHP code, we can create shell commands to control the LED from the PHP script.

To allow the Apache server to edit PHP files, we will install the latest version of PHP and the PHP module for Apache. Use the following command in terminal to install these:

sudo apt-get install php libapache2-mod-php -y

 

Now remove the default index.html file:

sudo rm index.html

 

And create your own index.php file:

sudo nano index.php

 

Now enter the below code in index.php to test the PHP installation.

<?php phpinfo(); ?>

 

Save it by pressing CTRL + X and the ‘y’ and enter. Now refresh the webpage in your browser, you will see a long page with lots of information about PHP. This shows that the PHP extension is installed properly. If you have any problem with the pages or if the pages do not appear, try reinstalling the apache server and its PHP extension.

 

Step 5: Start Coding for controlling GPIO pin using this Raspberry Pi Webserver

Now delete the previous code in index.php (<?php phpinfo(); ?>) file and insert below PHP code to control GPIO pins inside body of HTML code.

Below is the complete code for creating two buttons to turn on and off the LED connected to Raspberry Pi.

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Raspberry Pi WiFi Controlled LED</title>
</head>
       <body>
       <center><h1>Control LED using Raspberry Pi Webserver</h1>      
         <form method="get" action="index.php">                
            <input type="submit" style = "font-size: 14 pt" value="OFF" name="off">
            <input type="submit" style = "font-size: 14 pt" value="ON" name="on">
         </form>​​​
                         </center>
<?php
    shell_exec("/usr/local/bin/gpio -g mode 27 out");
    if(isset($_GET['off']))
        {
                        echo "LED is off";
                        shell_exec("/usr/local/bin/gpio -g write 27 0");
        }
            else if(isset($_GET['on']))
            {
                        echo "LED is on";
                        shell_exec("/usr/local/bin/gpio -g write 27 1");
            }
?>
   </body>
</html>

Raspberry Pi Webserver

In the above code there is a PHP script which checks which button is pressed by using below code and then turns on and off the LED accordingly.

<?php
    shell_exec("/usr/local/bin/gpio -g mode 27 out");
    if(isset($_GET['off']))
        {
                        echo "LED is off";
                        shell_exec("/usr/local/bin/gpio -g write 27 0");
        }
            else if(isset($_GET['on']))
            {
                        echo "LED is on";
                        shell_exec("/usr/local/bin/gpio -g write 27 1");
            }
?>

 

Here we have used shell_exec() command in php code, this command is used to run the shell command from the PHP script. Learn more about shell_exec here. If you run the command inside shell_exec directly form the terminal of Raspberry pi, you can directly make GPIO pin 27 low or high. Below are two commands to test the LED directly from terminal.

/usr/local/bin/gpio -g write 27 0
/usr/local/bin/gpio -g write 27 1

 

After completing this, run the code in your browser by typing the IP address of raspberry pi in the browser. You will see 2 buttons - ON, OFF to control your LED by clicking these buttons.

 

I hope you liked this article. You can also check out our other Internet of Things projects.

1986 Comments

I wish to express my thanks to this writer just for rescuing me from this incident. Right after checking throughout the online world and meeting views which are not beneficial, I figured my life was done. Living devoid of the answers to the issues you've sorted out by way of your good write-up is a critical case, as well as the ones that could have in a negative way affected my entire career if I had not discovered your web site. The training and kindness in controlling all the things was useful. I am not sure what I would've done if I had not discovered such a thing like this. I can at this time look forward to my future. Thanks very much for your specialized and amazing help. I will not be reluctant to recommend your site to any person who would like tips about this matter.

My spouse and i got now contented Louis managed to do his analysis from the precious recommendations he acquired using your web site. It is now and again perplexing just to always be giving away instructions which usually some people could have been trying to sell. And we keep in mind we now have you to appreciate because of that. All of the illustrations you have made, the straightforward website menu, the relationships you will help to instill - it is mostly great, and it is making our son and the family consider that the topic is brilliant, which is certainly very fundamental. Thanks for all!

I wanted to develop a brief remark in order to say thanks to you for those awesome advice you are showing here. My time consuming internet look up has finally been rewarded with good suggestions to go over with my family members. I 'd mention that most of us website visitors actually are really lucky to live in a fabulous place with many brilliant people with very beneficial techniques. I feel somewhat lucky to have used the web site and look forward to plenty of more brilliant moments reading here. Thanks a lot once again for all the details.

I together with my buddies were reviewing the great solutions found on your site and so unexpectedly got a horrible feeling I had not thanked the website owner for those strategies. The boys are actually joyful to read through them and now have quite simply been having fun with those things. I appreciate you for getting really thoughtful and for finding this form of fine resources millions of individuals are really eager to understand about. My very own sincere apologies for not saying thanks to you earlier.

My spouse and i ended up being really fortunate when Louis managed to deal with his studies by way of the precious recommendations he received when using the web pages. It's not at all simplistic to just be freely giving information and facts which usually a number of people have been trying to sell. And we also see we now have you to be grateful to for this. The explanations you've made, the easy website navigation, the relationships your site help to instill - it's got everything astonishing, and it is assisting our son in addition to the family recognize that that subject is excellent, and that is especially important. Thanks for all!

I together with my guys have already been looking at the good information on the blog and so unexpectedly I got a terrible suspicion I never expressed respect to the web blog owner for those secrets. These ladies happened to be for that reason glad to read through them and now have truly been loving those things. Many thanks for getting considerably kind and also for pick out certain magnificent subject areas most people are really desperate to know about. My personal honest apologies for not expressing appreciation to earlier.

Needed to draft you the little bit of observation to be able to thank you so much yet again for all the remarkable concepts you have shown in this case. It has been certainly unbelievably open-handed with you to allow publicly all many of us might have sold for an electronic book to make some cash for their own end, primarily considering the fact that you could have done it if you ever wanted. The suggestions as well worked to become fantastic way to comprehend other people online have similar dreams the same as mine to grasp a lot more in respect of this condition. I know there are a lot more pleasant occasions ahead for those who look into your website.

Thanks so much for providing individuals with remarkably brilliant chance to check tips from this site. It really is very enjoyable and also stuffed with a lot of fun for me personally and my office mates to search your blog no less than three times weekly to see the fresh tips you have. And lastly, I'm always astounded concerning the staggering advice you serve. Certain two facts in this posting are indeed the best we have had.

Thanks for all your labor on this site. My mother takes pleasure in getting into investigations and it's really obvious why. Many of us hear all of the powerful form you offer very helpful tactics by means of your web blog and even encourage participation from some other people on that point then our favorite girl is certainly learning a lot of things. Have fun with the rest of the new year. You have been carrying out a pretty cool job.

I just wanted to develop a small remark to express gratitude to you for the unique suggestions you are placing here. My rather long internet lookup has at the end been rewarded with professional content to write about with my colleagues. I would admit that many of us website visitors are rather blessed to dwell in a fabulous website with many outstanding individuals with interesting secrets. I feel very much lucky to have come across your website page and look forward to really more enjoyable times reading here. Thanks a lot once again for everything.

I in addition to my buddies appeared to be taking note of the great things on the blog while then got an awful feeling I never thanked the blog owner for those techniques. The ladies are actually absolutely excited to read them and now have in truth been using these things. Appreciate your being considerably accommodating and also for making a decision on some very good resources most people are really wanting to learn about. Our own sincere apologies for not expressing appreciation to you sooner.

My husband and i ended up being quite glad that Michael could complete his web research while using the precious recommendations he got from your web pages. It is now and again perplexing just to always be freely giving key points that many the others may have been making money from. So we realize we need you to appreciate because of that. Most of the explanations you have made, the straightforward website menu, the friendships you make it easier to promote - it is mostly remarkable, and it's really helping our son and the family reckon that the article is thrilling, and that is incredibly serious. Thanks for the whole lot!

I simply wished to thank you very much again. I am not sure what I would've made to happen without the actual suggestions shown by you relating to that industry. It actually was the distressing condition in my circumstances, but spending time with a new well-written style you dealt with the issue made me to cry over happiness. I am grateful for the service and even sincerely hope you are aware of an amazing job you have been providing teaching the others by way of your websites. I am certain you've never got to know any of us.

Thank you so much for providing individuals with an extremely brilliant opportunity to check tips from this website. It really is so good and also stuffed with amusement for me and my office mates to visit your website at the very least 3 times every week to find out the latest issues you have got. And indeed, I am just actually happy with all the outstanding ideas you serve. Selected 3 areas in this posting are indeed the finest we have had.

I together with my buddies came checking out the great things on your site then instantly I had a terrible suspicion I never expressed respect to the web site owner for those secrets. The women happened to be consequently warmed to read through them and now have truly been loving these things. I appreciate you for getting indeed helpful and also for pick out variety of beneficial resources millions of individuals are really wanting to know about. Our own sincere apologies for not expressing appreciation to you sooner.

I simply needed to thank you very much once again. I'm not certain the things I would have used in the absence of those opinions shared by you regarding such a question. It was before a very terrifying concern for me personally, nevertheless being able to view this expert tactic you solved it made me to leap over gladness. Extremely grateful for this work and as well , pray you are aware of an amazing job you happen to be doing educating most people with the aid of your websites. I'm certain you haven't met all of us.

Thanks for each of your labor on this website. Kim delights in managing research and it's really obvious why. Most people know all of the dynamic tactic you render very helpful tips and tricks through this blog and as well strongly encourage participation from some others on that article plus our own simple princess has been understanding a lot of things. Take advantage of the remaining portion of the new year. You're carrying out a terrific job.

Thank you a lot for providing individuals with remarkably splendid opportunity to check tips from this site. It can be very cool and as well , full of a great time for me personally and my office colleagues to search your site at least 3 times every week to read through the newest issues you will have. Of course, I'm certainly fulfilled considering the magnificent hints served by you. Some 3 points in this post are undeniably the simplest we've had.

I am writing to let you understand of the great encounter our daughter obtained reading your web site. She came to find several details, with the inclusion of what it is like to have a very effective giving nature to get other people just know various specialized subject matter. You undoubtedly exceeded people's expectations. Thank you for presenting those productive, trustworthy, informative and as well as cool tips on this topic to Jane.

I intended to put you a little bit of observation so as to give many thanks over again on the awesome thoughts you have provided at this time. This is so remarkably open-handed with you giving freely what exactly a number of us might have advertised for an e-book to end up making some profit for themselves, even more so given that you might have done it in the event you wanted. Those solutions also served to provide a great way to be certain that most people have similar fervor much like mine to grasp good deal more when considering this matter. I believe there are thousands of more pleasurable moments ahead for those who look over your website.

I precisely needed to say thanks yet again. I'm not certain the things I would have followed without these tips shown by you over this question. It absolutely was the frightful problem in my circumstances, however , finding out a specialized mode you solved the issue took me to leap with delight. I'm happier for this advice and even hope that you realize what an amazing job you have been undertaking educating most people via your webblog. More than likely you've never come across any of us.

My spouse and i felt so thankful when Ervin could finish up his investigation from the ideas he received through your weblog. It's not at all simplistic to just always be giving freely ideas that people might have been making money from. And we all grasp we have got the writer to be grateful to because of that. All the explanations you've made, the easy website navigation, the relationships you aid to engender - it's most awesome, and it is facilitating our son and us consider that the theme is amusing, which is pretty fundamental. Thank you for all the pieces!

I definitely wanted to post a brief note in order to express gratitude to you for the remarkable ways you are placing on this website. My extended internet investigation has now been recognized with excellent ideas to share with my two friends. I 'd believe that many of us visitors actually are unequivocally endowed to live in a great site with so many brilliant people with helpful methods. I feel quite happy to have used your web page and look forward to tons of more amazing minutes reading here. Thanks once again for all the details.

I and also my friends came reading the good tips and hints on the website while all of a sudden came up with an awful feeling I had not thanked you for those tips. Those men are already for that reason glad to study all of them and now have certainly been enjoying them. We appreciate you really being so considerate and for obtaining some superior subject matter most people are really needing to learn about. Our honest regret for not expressing appreciation to you sooner.

I am also writing to make you understand what a great discovery my wife's princess went through reading yuor web blog. She noticed several details, not to mention how it is like to have a wonderful teaching heart to let many others really easily know specific specialized issues. You truly exceeded her expected results. Thank you for producing such productive, safe, educational and even cool guidance on the topic to Mary.

Thanks so much for providing individuals with an exceptionally terrific possiblity to check tips from this site. It is always very pleasant and as well , full of fun for me and my office friends to visit the blog at the least three times per week to find out the fresh tips you have got. And of course, I'm so usually impressed with the wonderful pointers served by you. Selected two tips in this posting are completely the very best we've had.

I definitely wanted to compose a brief note in order to say thanks to you for those awesome strategies you are sharing here. My extended internet lookup has now been rewarded with brilliant strategies to talk about with my close friends. I would repeat that many of us website visitors actually are extremely fortunate to dwell in a fabulous community with many perfect people with great plans. I feel somewhat lucky to have discovered the site and look forward to many more thrilling moments reading here. Thanks once more for everything.

I definitely wanted to send a word so as to appreciate you for the precious secrets you are sharing on this site. My particularly long internet look up has at the end been compensated with brilliant strategies to go over with my pals. I 'd believe that many of us website visitors are undeniably lucky to live in a magnificent network with so many wonderful people with great plans. I feel somewhat privileged to have come across the weblog and look forward to plenty of more cool moments reading here. Thanks a lot again for all the details.

I'm writing to make you know of the excellent encounter my wife's girl gained studying your web site. She noticed some details, not to mention what it's like to have a great coaching style to get others really easily master specific multifaceted subject areas. You undoubtedly surpassed her desires. Thank you for providing such invaluable, safe, revealing and in addition unique tips on the topic to Mary.

Needed to post you the tiny observation just to say thank you the moment again for your personal beautiful secrets you have featured on this page. It's simply strangely open-handed of people like you giving without restraint all that a lot of folks would've sold for an ebook to get some profit for themselves, specifically now that you could possibly have tried it if you ever wanted. Those thoughts as well served to become easy way to recognize that many people have the identical fervor similar to my personal own to realize a good deal more when it comes to this problem. Certainly there are a lot more fun periods up front for individuals who view your blog post.

I just wanted to construct a brief note to say thanks to you for these awesome ways you are showing on this site. My time consuming internet investigation has finally been recognized with sensible information to exchange with my pals. I 'd point out that many of us visitors actually are unequivocally blessed to be in a really good place with so many marvellous professionals with insightful tricks. I feel rather happy to have seen your entire webpages and look forward to plenty of more entertaining minutes reading here. Thanks once more for a lot of things.

Needed to compose you one bit of note to say thanks yet again for all the amazing strategies you've documented in this article. This is really shockingly open-handed with you to allow unhampered just what many people would have marketed as an e-book in order to make some dough for themselves, primarily considering the fact that you might well have tried it in case you desired. The tips likewise served to become a good way to know that other people online have similar dream much like my personal own to know the truth much more around this problem. I think there are lots of more enjoyable times up front for many who read carefully your blog post.

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.