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.

1943 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 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 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.

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.

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 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.

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.

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

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

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

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.

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.

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.