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

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 and my guys came reviewing the best pointers from the website and then unexpectedly I got a horrible feeling I never thanked the web site owner for them. The men came as a result happy to study all of them and now have sincerely been tapping into them. Thank you for simply being indeed kind and for utilizing some excellent subject matter millions of individuals are really desperate to know about. My very own sincere regret for not saying thanks to you sooner.

I抦 impressed, I need to say. Actually rarely do I encounter a weblog that抯 each educative and entertaining, and let me tell you, you may have hit the nail on the head. Your idea is excellent; the problem is one thing that not enough people are talking intelligently about. I'm very completely satisfied that I stumbled across this in my seek for something regarding this.

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.

I intended to draft you that little bit of word to finally thank you very much again for those fantastic opinions you've discussed on this page. This has been simply extremely generous with people like you to present freely just what a number of people would've offered for sale as an e book in making some dough on their own, most importantly since you could possibly have tried it in the event you wanted. Those tips as well worked as the good way to realize that some people have the identical dreams much like my own to find out lots more on the topic of this condition. I believe there are some more pleasurable times in the future for folks who scan your blog.

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 really wanted to write down a simple note so as to thank you for all of the splendid secrets you are writing at this website. My time intensive internet research has at the end of the day been compensated with wonderful details to share with my great friends. I 'd tell you that we site visitors are truly blessed to live in a very good community with very many lovely people with helpful concepts. I feel rather grateful to have come across your web page and look forward to many more brilliant minutes reading here. Thanks a lot once more for all the details.

Thanks so much for providing individuals with remarkably memorable chance to read from this blog. It is always very enjoyable and also full of amusement for me personally and my office acquaintances to visit your site at a minimum thrice in 7 days to find out the new things you have. Of course, we are certainly pleased with your astounding techniques you give. Some 4 ideas in this article are ultimately the best we have ever had.

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 just wanted to write down a brief remark to be able to appreciate you for these remarkable tips you are placing on this website. My prolonged internet look up has at the end of the day been paid with useful facts and techniques to exchange with my contacts. I 'd state that that we website visitors actually are undeniably blessed to be in a magnificent site with very many awesome professionals with good ideas. I feel very happy to have come across your webpage and look forward to tons of more fun minutes reading here. Thank you once more for everything.

I and my friends have already been viewing the excellent tips found on your website while all of a sudden I had a terrible feeling I never thanked the web blog owner for those tips. All the women are already certainly glad to read them and now have certainly been taking advantage of those things. We appreciate you being indeed kind and then for having some amazing subject areas most people are really wanting to know about. My personal sincere regret for not expressing gratitude to earlier.

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 and also my friends appeared to be viewing the nice strategies from your web site then all of the sudden came up with an awful suspicion I had not thanked the blog owner for those tips. All the young men appeared to be absolutely glad to read them and have in effect in truth been using them. We appreciate you really being so accommodating and also for getting some smart resources millions of individuals are really eager to understand about. Our sincere regret for not saying thanks to you sooner.

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.

I have to express my gratitude for your kindness supporting those people who have the need for help with the area of interest. Your personal dedication to getting the message all over was definitely productive and have permitted girls much like me to attain their ambitions. Your entire warm and friendly hints and tips signifies so much to me and especially to my office workers. Many thanks; from each one of us.

Needed to write you one very small observation to be able to say thank you as before for those remarkable things you've provided on this website. This has been certainly surprisingly generous with you to offer openly all that most people could have made available as an electronic book to generate some profit for their own end, most importantly since you might have done it if you ever decided. The solutions in addition served to be the easy way to be sure that most people have the identical dreams much like my very own to know whole lot more in terms of this matter. Certainly there are millions of more pleasurable moments in the future for folks who looked over your site.

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.