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.

3422 Comments

Nice post. I be taught something more difficult on completely different blogs everyday. It would at all times be stimulating to read content from different writers and observe somewhat one thing from their store. I抎 desire to make use of some with the content material on my weblog whether you don抰 mind. Natually I抣l give you a hyperlink in your net blog. Thanks for sharing.

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.

Thanks for each of your hard work on this web site. Gloria enjoys working on research and it is simple to grasp why. We all know all concerning the compelling way you create very useful ideas via your blog and therefore invigorate participation from other people on this point and our child is undoubtedly discovering a great deal. Take pleasure in the remaining portion of the new year. You are doing a brilliant job.

I actually wanted to make a quick note in order to say thanks to you for all the great instructions you are showing at this site. My prolonged internet search has at the end been honored with incredibly good facts to go over with my colleagues. I 'd suppose that many of us website visitors actually are very much blessed to exist in a superb community with many wonderful professionals with interesting principles. I feel pretty blessed to have come across your webpage and look forward to many more pleasurable times reading here. Thanks a lot once again for everything.

I just wanted to compose a small comment to be able to thank you for all the precious information you are sharing here. My time-consuming internet look up has at the end of the day been recognized with incredibly good ideas to share with my neighbours. I 'd suppose that many of us visitors actually are very lucky to be in a remarkable website with so many outstanding professionals with very helpful points. I feel pretty blessed to have seen your web site and look forward to some more awesome moments reading here. Thank you once again for a lot of things.

I'm commenting to make you be aware of of the remarkable experience my wife's princess enjoyed visiting your site. She noticed numerous things, most notably what it's like to possess an ideal coaching mood to get men and women just master several impossible matters. You really surpassed readers' expectations. I appreciate you for delivering the priceless, trustworthy, edifying and also easy tips on the topic to Emily.

I in addition to my pals happened to be reviewing the nice secrets on your website and immediately I had a horrible suspicion I never thanked the web blog owner for them. All the people happened to be passionate to read them and already have truly been loving these things. Appreciate your turning out to be very accommodating as well as for making a decision on these kinds of ideal subjects millions of individuals are really desirous to be informed on. My very own sincere regret for not expressing gratitude to you sooner.

Thanks for each of your efforts on this site. Betty really loves conducting investigations and it is obvious why. Most of us know all about the compelling medium you deliver sensible things on the blog and welcome participation from website visitors on the subject then my princess has always been starting to learn a lot. Enjoy the remaining portion of the new year. You are conducting a splendid job.

My spouse and i got delighted that Chris managed to round up his research through your ideas he obtained while using the site. It is now and again perplexing just to possibly be making a gift of hints which often some others might have been selling. And now we acknowledge we have got the writer to be grateful to for this. The most important illustrations you have made, the straightforward site menu, the relationships you can help to create - it is most terrific, and it's really assisting our son in addition to our family feel that this concept is amusing, which is certainly pretty fundamental. Thank you for all the pieces!

A lot of thanks for your entire hard work on this blog. My niece delights in making time for investigation and it's really easy to see why. We all learn all relating to the powerful form you render efficient thoughts on this web site and even attract participation from some others on this topic while our child is now understanding a whole lot. Take advantage of the remaining portion of the new year. You are always performing a glorious job.

My wife and i got so relieved when Albert could finish off his investigation from your precious recommendations he was given while using the web site. It is now and again perplexing to simply always be giving freely guidance many people might have been making money from. Therefore we grasp we need the website owner to thank for that. Most of the illustrations you made, the simple website menu, the relationships you can aid to foster - it's many great, and it is assisting our son and our family understand the subject matter is entertaining, which is rather important. Thanks for everything!

Needed to write you a very small note to be able to say thanks a lot once again relating to the striking tricks you have provided on this website. It has been unbelievably open-handed of people like you to convey openly what a number of us could have marketed for an ebook to earn some cash for their own end, and in particular seeing that you might well have done it if you desired. These tricks likewise served to become a easy way to know that some people have a similar dream just like my personal own to realize a great deal more in respect of this problem. I think there are lots of more fun times ahead for people who scan your website.

I would like to show appreciation to this writer just for bailing me out of this type of issue. Right after researching through the world-wide-web and finding ways which were not pleasant, I believed my life was done. Living minus the strategies to the difficulties you have solved all through your main posting is a critical case, as well as the ones which might have negatively damaged my career if I had not encountered your blog. Your personal talents and kindness in controlling a lot of stuff was useful. I'm not sure what I would have done if I hadn't encountered such a step like this. I can also at this moment relish my future. Thanks a lot so much for the specialized and amazing guide. I won't be reluctant to refer the sites to anybody who should have guide about this area.

I wanted to draft you a little bit of observation to thank you so much once again over the unique suggestions you've shared on this website. This is really pretty open-handed with people like you to deliver unreservedly what exactly a few people might have advertised as an e book to help with making some dough on their own, specifically considering the fact that you could have done it in case you decided. The creative ideas likewise worked like the easy way to fully grasp that most people have the identical dreams just like my very own to grasp way more pertaining to this matter. I know there are several more pleasant sessions up front for people who read carefully your site.

I wish to express some thanks to the writer for bailing me out of this circumstance. Because of looking throughout the search engines and meeting notions which were not productive, I thought my entire life was gone. Living minus the approaches to the issues you have solved all through your main review is a serious case, as well as those that would have in a wrong way affected my entire career if I hadn't discovered your website. Your own talents and kindness in controlling a lot of stuff was important. I am not sure what I would've done if I had not come across such a solution like this. I can now relish my future. Thanks a lot very much for your expert and sensible help. I won't be reluctant to endorse your blog post to anyone who will need guidance about this area.

I truly wanted to write a simple message so as to appreciate you for all the precious tactics you are giving on this website. My considerable internet lookup has at the end of the day been paid with pleasant facts and strategies to write about with my guests. I 'd mention that we site visitors are very blessed to live in a notable place with very many marvellous people with valuable tips and hints. I feel quite privileged to have discovered the web page and look forward to so many more awesome moments reading here. Thanks once again for a lot of things.

I wish to express thanks to the writer just for rescuing me from such a matter. As a result of looking out throughout the internet and coming across thoughts that were not productive, I was thinking my life was gone. Living without the presence of strategies to the issues you have resolved through this posting is a serious case, as well as the kind that could have negatively affected my entire career if I had not noticed your blog. Your personal know-how and kindness in dealing with almost everything was very helpful. I am not sure what I would've done if I had not come across such a thing like this. I am able to at this time look forward to my future. Thanks for your time so much for this expert and results-oriented guide. I won't think twice to refer your web page to any individual who requires tips about this issue.

I must point out my affection for your kind-heartedness giving support to folks who absolutely need guidance on in this matter. Your real commitment to passing the solution all over was definitely productive and have surely permitted many people like me to arrive at their endeavors. Your amazing useful useful information entails a lot to me and further more to my office colleagues. Warm regards; from all of us.

I as well as my friends have already been reading the great procedures from the blog and then suddenly developed a terrible suspicion I never thanked the web blog owner for them. The boys happened to be certainly stimulated to study them and have now actually been taking advantage of those things. Many thanks for really being well considerate and for settling on this form of useful areas most people are really desperate to discover. My very own sincere apologies for not saying thanks to sooner.

I want to get across my gratitude for your generosity giving support to folks that absolutely need guidance on the subject. Your special commitment to getting the message all around was rather effective and has in most cases encouraged some individuals just like me to attain their endeavors. Your warm and friendly instruction signifies this much a person like me and even more to my fellow workers. Warm regards; from everyone of us.

I must voice my respect for your kindness supporting those people who require help with the situation. Your personal commitment to getting the message all over was extremely practical and have continually helped somebody like me to attain their targets. Your warm and helpful suggestions entails a lot to me and substantially more to my peers. Thanks a lot; from each one of us.

I want to express my passion for your kind-heartedness giving support to all those that actually need guidance on that question. Your special commitment to getting the solution all-around ended up being really invaluable and have specifically helped others just like me to get to their goals. Your warm and friendly guidelines means so much a person like me and additionally to my mates. Many thanks; from all of us.

Thanks for your own labor on this site. My mom takes pleasure in engaging in research and it's really easy to understand why. Many of us learn all regarding the dynamic mode you convey very important ideas through your web site and therefore improve contribution from others on that concern plus my simple princess is really being taught a lot. Take advantage of the rest of the year. You are performing a brilliant job.

Thank you for all of your hard work on this web page. My daughter really likes working on research and it's easy to understand why. Most of us hear all concerning the lively manner you present worthwhile strategies on the website and as well recommend contribution from people on this topic and our own simple princess is without a doubt studying a lot of things. Take pleasure in the remaining portion of the year. You're carrying out a powerful job.

I not to mention my buddies appeared to be following the excellent ideas on your website then all of a sudden got an awful suspicion I had not expressed respect to the website owner for those tips. Most of the young men became absolutely passionate to read all of them and already have surely been loving those things. We appreciate you genuinely really accommodating as well as for figuring out these kinds of excellent subjects millions of individuals are really needing to discover. My very own honest apologies for not expressing gratitude to you sooner.

I in addition to my friends happened to be viewing the excellent tips located on your web page and so suddenly I got a terrible feeling I had not expressed respect to the blog owner for them. Most of the ladies happened to be consequently thrilled to see all of them and now have simply been enjoying them. Many thanks for truly being really accommodating and then for making a decision on these kinds of good subject areas most people are really eager to understand about. My very own honest regret for not expressing appreciation to you earlier.

I want to get across my gratitude for your kind-heartedness for people who need help on your topic. Your very own commitment to getting the message across ended up being exceptionally important and have without exception permitted professionals just like me to reach their goals. The useful publication denotes much a person like me and much more to my office workers. Thanks a lot; from all of us.

I precisely desired to appreciate you once again. I do not know what I could possibly have gone through in the absence of the type of tricks documented by you relating to this problem. It has been a real scary condition for me personally, nevertheless being able to view a new well-written manner you dealt with the issue took me to weep over fulfillment. I am just thankful for the service and then believe you are aware of an amazing job you happen to be getting into teaching people through your blog. Most probably you haven't got to know any of us.

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.