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.

3150 Comments

I got the webserver running the buttons refresh correctly.
I have an LED connected to pin 16(on the pi) or 24 (mapped) and I can control it using a python script.
When I press the button in browser the state changes text shows correctly but LED doesn't light up.
When I try username@raspberrypi:~$ shell_exec() /usr/local/bin/gpio -g write 24 1 it gives:
-bash: syntax error near unexpected token `/usr/local/bin/gpio'

Does anyone know why this happens?

I would like to show thanks to this writer for rescuing me from such a issue. Right after looking throughout the the net and obtaining things that were not pleasant, I was thinking my life was over. Living minus the approaches to the problems you have sorted out through the blog post is a serious case, as well as those that might have badly affected my entire career if I hadn't noticed your site. That competence and kindness in handling all things was crucial. I don't know what I would have done if I had not encountered such a thing like this. I am able to at this time look ahead to my future. Thanks very much for the professional and amazing guide. I won't be reluctant to recommend your web sites to anybody who wants and needs assistance about this subject matter.

Thank you for your whole effort on this site. Kim really likes going through investigations and it is easy to understand why. My spouse and i notice all concerning the powerful mode you convey effective secrets on your website and improve participation from website visitors on the idea and our child is always discovering a great deal. Have fun with the remaining portion of the year. You are performing a splendid job.

I simply wanted to thank you so much once more. I do not know the things I would have gone through in the absence of the actual basics shown by you on such area. Completely was an absolute difficult problem in my view, nevertheless spending time with your professional way you handled the issue forced me to cry for joy. I'm happier for the work and sincerely hope you comprehend what a great job that you are carrying out instructing people today through the use of your website. I am certain you've never met any of us.

I am glad for commenting to let you be aware of what a excellent experience my cousin's girl found going through your web site. She came to find so many pieces, which included what it is like to have a marvelous giving mood to have a number of people without difficulty completely grasp specified hard to do subject areas. You truly did more than people's desires. Thank you for showing these warm and helpful, healthy, edifying as well as unique guidance on this topic to Evelyn.

My spouse and i have been very delighted that Ervin managed to complete his homework through the entire ideas he discovered through the web site. It's not at all simplistic to just possibly be giving out secrets and techniques that many others have been trying to sell. And we fully understand we have the blog owner to appreciate for that. The main illustrations you've made, the simple blog navigation, the relationships you will give support to create - it's got all impressive, and it's facilitating our son in addition to us consider that this concept is excellent, which is certainly rather serious. Thank you for the whole thing!

I want to show my respect for your kindness supporting all those that require assistance with that idea. Your special commitment to passing the message all over ended up being quite useful and has in every case permitted girls much like me to realize their ambitions. The insightful guidelines signifies a lot to me and a whole lot more to my office workers. Best wishes; from all of us.

I want to show my passion for your generosity supporting folks that need guidance on that area of interest. Your real commitment to passing the message throughout had been incredibly interesting and have consistently permitted others much like me to attain their endeavors. The important help and advice can mean a whole lot a person like me and extremely more to my office colleagues. Regards; from each one of us.

I would like to show my appreciation to the writer for bailing me out of such a situation. Just after surfing throughout the online world and getting proposals that were not beneficial, I believed my entire life was over. Being alive without the presence of answers to the issues you've resolved through this article is a crucial case, as well as those which could have badly affected my career if I had not encountered your web page. The ability and kindness in maneuvering almost everything was very useful. I'm not sure what I would have done if I had not come across such a stuff like this. It's possible to at this time look ahead to my future. Thanks for your time very much for your high quality and result oriented guide. I will not hesitate to suggest your web page to anyone who should have support about this topic.

I wish to express thanks to this writer just for rescuing me from this crisis. Because of browsing throughout the world wide web and getting strategies that were not helpful, I thought my life was gone. Existing devoid of the answers to the problems you have fixed through your blog post is a critical case, as well as the ones which may have badly damaged my entire career if I had not discovered the blog. Your main mastery and kindness in controlling a lot of things was useful. I don't know what I would have done if I hadn't encountered such a step like this. I can also at this moment look ahead to my future. Thanks a lot very much for your reliable and result oriented guide. I will not be reluctant to propose your blog post to anybody who should receive recommendations on this problem.

I definitely wanted to type a quick note to thank you for all the stunning information you are writing at this website. My particularly long internet investigation has at the end of the day been recognized with useful ideas to share with my relatives. I would express that many of us readers actually are undoubtedly fortunate to exist in a decent place with so many wonderful professionals with good concepts. I feel really privileged to have encountered your entire web site and look forward to really more fabulous moments reading here. Thank you again for all the details.

I definitely wanted to write a quick comment to be able to thank you for these awesome points you are giving out at this website. My time intensive internet search has finally been compensated with high-quality ideas to talk about with my relatives. I 'd assume that we website visitors are extremely endowed to live in a useful community with many perfect professionals with helpful ideas. I feel extremely grateful to have come across the weblog and look forward to tons of more awesome times reading here. Thanks a lot again for all the details.

I intended to draft you this little note just to thank you very much once again for the splendid thoughts you have featured at this time. This has been quite surprisingly generous with you to deliver easily what numerous people could possibly have marketed for an ebook to generate some dough for themselves, certainly now that you might have done it if you desired. The points as well acted to become easy way to know that the rest have the same zeal just like my personal own to know significantly more with regard to this problem. I'm sure there are lots of more enjoyable periods in the future for individuals that browse through your site.

I am just writing to let you understand of the remarkable discovery our princess went through reading through your blog. She discovered a lot of things, including what it is like to possess a great teaching style to make most people with no trouble master a variety of very confusing matters. You truly exceeded people's desires. Thank you for giving these productive, safe, explanatory and even easy thoughts on this topic to Lizeth.

I wish to express appreciation to you for bailing me out of this particular matter. After exploring throughout the internet and finding tricks that were not productive, I assumed my life was gone. Living minus the solutions to the issues you have solved by way of the posting is a crucial case, as well as the kind that could have in a negative way damaged my career if I had not come across your website. Your own know-how and kindness in playing with all the pieces was vital. I am not sure what I would've done if I hadn't encountered such a thing like this. I am able to now look ahead to my future. Thanks for your time so much for this skilled and effective guide. I won't hesitate to refer your web blog to any person who requires assistance about this subject.

My wife and i got so lucky that Michael could finish off his studies using the ideas he got through the weblog. It is now and again perplexing to just find yourself giving away facts which other folks have been making money from. And we also take into account we've got you to thank because of that. All the illustrations you have made, the straightforward site navigation, the friendships you can assist to promote - it's got all sensational, and it's leading our son and our family reckon that the theme is thrilling, and that is truly mandatory. Many thanks for all!

I happen to be commenting to make you be aware of what a terrific encounter our girl obtained reading through yuor web blog. She mastered plenty of issues, not to mention how it is like to possess an excellent coaching style to make others without problems master selected specialized issues. You really exceeded our desires. Thank you for providing these insightful, trusted, educational and cool thoughts on your topic to Janet.

I wanted to post you one little word so as to say thank you over again for your beautiful strategies you have shown here. It was really strangely open-handed of you to convey unhampered just what many people might have advertised for an ebook to help make some bucks on their own, primarily considering the fact that you could possibly have tried it in case you decided. The techniques also acted to be the fantastic way to fully grasp that most people have the identical keenness just like mine to know a lot more on the topic of this condition. I know there are numerous more pleasant sessions ahead for individuals who read carefully your website.

I and also my friends happened to be reading through the great guidelines located on your website and then all of the sudden came up with a terrible suspicion I had not thanked the web blog owner for those tips. The young boys came as a result warmed to learn them and already have honestly been tapping into them. Many thanks for getting so accommodating and also for figuring out this kind of helpful areas most people are really eager to be informed on. My very own honest regret for not expressing gratitude to earlier.

I really wanted to send a note in order to appreciate you for all of the stunning items you are writing on this website. My time-consuming internet search has now been honored with beneficial facts and techniques to exchange with my visitors. I 'd repeat that many of us readers are rather lucky to exist in a very good site with many awesome individuals with beneficial pointers. I feel pretty happy to have encountered your web page and look forward to plenty of more enjoyable moments reading here. Thanks once more for everything.

Thank you a lot for providing individuals with an exceptionally memorable opportunity to read in detail from this site. It's always very excellent and as well , stuffed with amusement for me personally and my office friends to visit your site particularly 3 times weekly to read the new secrets you have. Of course, I am also always pleased for the impressive tricks you serve. Selected two points on this page are clearly the most effective we have all ever had.

I simply needed to thank you very much all over again. I do not know the things I might have tried without the aspects contributed by you concerning such situation. It actually was a real horrifying difficulty for me, but taking note of the very professional strategy you processed the issue forced me to cry over joy. I will be thankful for this support and then expect you really know what an amazing job you happen to be accomplishing training the rest through the use of your site. Probably you have never met any of us.

I simply wanted to make a quick message to be able to say thanks to you for these unique items you are giving on this website. My considerable internet search has finally been recognized with good quality know-how to exchange with my company. I would say that we site visitors are definitely lucky to be in a very good website with very many wonderful people with helpful secrets. I feel pretty grateful to have come across your entire site and look forward to plenty of more excellent times reading here. Thank you once again for a lot of things.

I want to express my thanks to you for rescuing me from such a incident. Because of scouting throughout the world-wide-web and meeting notions which are not helpful, I thought my life was well over. Being alive without the presence of answers to the difficulties you've sorted out by means of the write-up is a crucial case, and the kind that would have negatively damaged my entire career if I hadn't discovered your website. Your understanding and kindness in touching all things was helpful. I am not sure what I would've done if I hadn't encountered such a step like this. I'm able to now look forward to my future. Thank you so much for your expert and sensible help. I won't hesitate to endorse the sites to anybody who needs to have care about this subject.

I simply wanted to thank you very much all over again. I am not sure the things I could possibly have implemented in the absence of the entire tips shown by you on such a problem. It was a very difficult problem in my opinion, but looking at a specialized approach you resolved it made me to weep with joy. I am just grateful for your advice and as well , hope you find out what a great job you're getting into instructing many others using your website. Probably you've never got to know all of us.

I precisely wanted to appreciate you once more. I am not sure what I might have done without those creative concepts discussed by you directly on this industry. Certainly was an absolute fearsome dilemma in my circumstances, however , seeing your expert form you processed that forced me to leap with joy. Extremely grateful for this work and as well , hope you realize what a great job your are carrying out training the mediocre ones through the use of your webblog. I know that you have never met all of us.

I precisely wished to say thanks once again. I am not sure the things that I might have used without those tactics documented by you on that area. It had been the troublesome situation for me, nevertheless being able to view this professional way you handled it took me to cry for gladness. Now i'm thankful for your advice and as well , pray you comprehend what an amazing job that you're getting into teaching the others through the use of your web site. I'm certain you've never got to know all of us.

Thank you so much for providing individuals with such a pleasant chance to read from this blog. It's always very superb and stuffed with a good time for me and my office peers to search the blog minimum 3 times weekly to see the latest guides you have got. Of course, I'm at all times fascinated with your mind-boggling information you give. Certain 2 ideas on this page are easily the finest I've ever had.

Thanks so much for providing individuals with remarkably special possiblity to read critical reviews from this website. It's always very pleasing and as well , packed with a lot of fun for me and my office mates to search your site nearly three times in one week to read the new issues you have. And of course, I am always satisfied with all the very good information you give. Certain 2 facts on this page are essentially the most beneficial we have ever had.

Thanks so much for giving everyone remarkably pleasant possiblity to read critical reviews from this web site. It is usually so ideal plus jam-packed with amusement for me and my office co-workers to visit the blog at a minimum three times in 7 days to read the latest issues you will have. Not to mention, I'm just at all times pleased for the splendid methods served by you. Certain 2 facts in this posting are truly the most effective I have had.

My spouse and i felt so more than happy Peter managed to conclude his preliminary research from the ideas he made through the web page. It is now and again perplexing to just continually be giving for free things which many others might have been selling. And we all fully grasp we now have you to be grateful to for this. The most important explanations you made, the simple website menu, the relationships you can aid to engender - it is all extraordinary, and it is aiding our son and us reason why this content is satisfying, which is certainly exceptionally mandatory. Thank you for all!

Thanks so much for giving everyone such a special opportunity to read critical reviews from this website. It is usually so superb and packed with a lot of fun for me personally and my office peers to visit your site at the least three times every week to learn the fresh tips you have. And indeed, we are actually contented with your astounding inspiring ideas served by you. Selected 4 areas in this post are certainly the most suitable we've had.

I have to point out my respect for your generosity giving support to those people who have the need for assistance with this one concept. Your personal commitment to getting the message all over appears to be rather functional and has frequently allowed most people much like me to achieve their goals. This useful guide indicates this much a person like me and even further to my peers. Regards; from all 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.