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.

3420 Comments

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.

Thank you so much for providing individuals with remarkably nice possiblity to read articles and blog posts from here. It really is so useful and packed with amusement for me and my office co-workers to visit your website minimum three times per week to read through the fresh tips you have got. And of course, I'm just at all times motivated considering the astonishing things you serve. Certain 3 ideas on this page are surely the best I have had.

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.

I simply had to thank you very much once more. I am not sure the things that I might have tried in the absence of these aspects shared by you on my problem. It actually was a very horrifying crisis for me, nevertheless considering the very specialised style you treated it made me to jump with happiness. I am just happier for the guidance and as well , believe you comprehend what a great job your are providing instructing many people by way of a blog. More than likely you've never got to know any of us.

I as well as my buddies have already been analyzing the best tactics located on the website and at once developed a horrible suspicion I had not expressed respect to the web blog owner for those tips. Those young men ended up totally joyful to read them and have in effect really been tapping into these things. Appreciation for truly being so kind and for figuring out this form of remarkable resources millions of individuals are really desperate to be informed on. My sincere apologies for not expressing gratitude 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 have to show my thanks to this writer for bailing me out of this setting. As a result of surfing around through the the net and getting methods that were not powerful, I was thinking my entire life was well over. Living minus the solutions to the difficulties you have sorted out by way of your good blog post is a critical case, and those that might have badly damaged my career if I hadn't encountered your website. Your own knowledge and kindness in maneuvering the whole thing was valuable. I am not sure what I would've done if I hadn't come across such a thing like this. I can also at this moment look ahead to my future. Thanks very much for your high quality and effective help. I will not hesitate to recommend the website to anybody who ought to have support on this situation.

I not to mention my friends happened to be checking the good guidelines found on your web blog and suddenly I got a terrible feeling I never thanked the website owner for those tips. All of the men had been absolutely glad to read through all of them and now have pretty much been using them. Thanks for simply being considerably kind and then for having certain perfect topics millions of individuals are really wanting to be aware of. My very own sincere apologies for not saying thanks to sooner.

I truly wanted to post a comment in order to appreciate you for some of the superb secrets you are placing at this website. My incredibly long internet search has now been recognized with beneficial information to share with my best friends. I would point out that many of us visitors are very much blessed to live in a wonderful website with many perfect individuals with useful techniques. I feel really privileged to have seen the web pages and look forward to some more thrilling times reading here. Thank you once again for a lot of things.

I together with my friends were reviewing the excellent strategies from the blog and so then I had a horrible suspicion I never thanked the website owner for those secrets. Those ladies happened to be as a result stimulated to read through all of them and have undoubtedly been loving them. We appreciate you simply being well thoughtful and then for choosing this form of magnificent things most people are really eager to understand about. My personal sincere regret for not expressing gratitude to you sooner.

Can I just say what a reduction to find somebody who really knows what theyre talking about on the internet. You undoubtedly know tips on how to bring a difficulty to mild and make it important. More individuals need to learn this and understand this facet of the story. I cant believe youre not more fashionable since you positively have the gift.

I needed to post you that very little observation to help thank you again relating to the pleasant solutions you've shown on this page. This has been simply incredibly open-handed with you to give without restraint all that most of us would've offered for an e book to earn some money on their own, notably since you could have done it if you ever considered necessary. These smart ideas also served to be a fantastic way to fully grasp other individuals have the same dream just like my personal own to figure out very much more with respect to this condition. Certainly there are numerous more pleasant times in the future for those who read your website.

I precisely needed to thank you so much again. I do not know what I would have handled in the absence of the methods discussed by you on my area. This has been an absolute hard circumstance in my view, nevertheless spending time with a new well-written fashion you resolved that made me to leap for joy. Now i am happier for your help and in addition have high hopes you find out what an amazing job you are always undertaking instructing men and women via your webpage. Most probably you've never met any of us.

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.

I have to show thanks to you just for bailing me out of this type of condition. After scouting throughout the online world and meeting advice which were not pleasant, I was thinking my entire life was done. Being alive minus the solutions to the issues you have resolved by way of your entire posting is a critical case, as well as ones that might have negatively damaged my entire career if I had not encountered your web blog. Your own personal ability and kindness in dealing with every item was very helpful. I don't know what I would've done if I hadn't encountered such a subject like this. It's possible to now look forward to my future. Thank you very much for your expert and effective help. I will not hesitate to recommend your blog to anyone who should receive support about this situation.

I must voice my admiration for your kindness giving support to visitors who absolutely need guidance on in this niche. Your very own commitment to passing the solution all over was exceedingly helpful and have without exception helped ladies just like me to attain their objectives. Your new important advice implies a great deal a person like me and somewhat more to my peers. Thanks a ton; from each one of us.

I and my pals were actually checking the nice solutions from the website and so then I got an awful suspicion I never thanked the web blog owner for those secrets. All the women ended up totally passionate to see them and already have honestly been taking advantage of those things. Many thanks for being so accommodating and then for deciding on such superior topics millions of individuals are really desirous to discover. My very own sincere regret for not expressing appreciation to you earlier.

I happen to be writing to make you know what a fabulous encounter my friend's girl experienced viewing your blog. She came to understand a lot of things, which include how it is like to have an amazing coaching nature to let certain people without problems learn about several tortuous things. You undoubtedly surpassed our own expected results. I appreciate you for churning out such warm and friendly, trustworthy, explanatory and in addition easy tips about that topic to Janet.

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.

I would like to express thanks to this writer for rescuing me from this particular situation. Just after searching throughout the the web and coming across opinions which are not pleasant, I thought my entire life was done. Living without the presence of answers to the problems you have fixed by means of the guide is a critical case, as well as those that could have negatively affected my career if I hadn't come across your site. Your personal capability and kindness in touching the whole thing was very helpful. I am not sure what I would have done if I hadn't come upon such a thing like this. I am able to at this time look ahead to my future. Thank you very much for the professional and effective guide. I will not think twice to recommend the sites to any individual who would need assistance on this situation.

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.

I simply desired to thank you so much yet again. I'm not certain what I could possibly have carried out without the entire secrets contributed by you on such a situation. Previously it was the traumatic issue in my position, but considering your specialized avenue you solved it forced me to leap over fulfillment. Extremely happier for this advice and even pray you know what a great job you're undertaking instructing other individuals all through a site. I am certain you haven't come across any of us.

I needed to send you that very little remark to be able to say thank you yet again with the nice ideas you've featured at this time. This is so strangely open-handed with you to give easily exactly what a lot of folks might have offered for sale for an e-book to generate some bucks on their own, specifically now that you could possibly have tried it if you ever decided. Those good ideas likewise served to become fantastic way to be certain that most people have the identical passion much like mine to grasp a great deal more pertaining to this problem. I think there are many more pleasant times in the future for people who scan your blog post.

Thank you so much for providing individuals with a very superb possiblity to read from this site. It is often so pleasant and packed with fun for me and my office colleagues to visit your web site the equivalent of three times in 7 days to read through the latest tips you will have. And of course, I am just usually pleased with your remarkable information you serve. Selected 4 ideas on this page are definitely the most effective we have had.

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.

I would like to get across my respect for your kind-heartedness supporting folks who require help on this particular concept. Your personal dedication to getting the solution along turned out to be remarkably good and have without exception made some individuals just like me to arrive at their targets. Your entire warm and friendly guideline means much to me and a whole lot more to my colleagues. With thanks; from each one of us.

I in addition to my pals have already been checking the good suggestions from the website while unexpectedly I got an awful suspicion I never thanked the site owner for those techniques. Those boys are actually consequently warmed to read through all of them and already have simply been enjoying those things. We appreciate you getting considerably accommodating and also for going for some perfect topics most people are really wanting to discover. Our honest apologies for not expressing gratitude to you earlier.

I and also my pals have been analyzing the nice guides on your site then at once got a terrible suspicion I had not thanked the website owner for those techniques. These people ended up totally very interested to learn them and have unquestionably been taking advantage of those things. Appreciation for genuinely indeed helpful and also for utilizing varieties of helpful guides millions of individuals are really needing to be aware of. My personal honest regret for not expressing appreciation to earlier.

Can I simply say what a aid to search out somebody who really is aware of what theyre talking about on the internet. You positively know how one can convey a difficulty to mild and make it important. More people need to read this and perceive this aspect of the story. I cant consider youre not more fashionable because you positively have the gift.

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.