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

Thank you so much for providing individuals with an extremely brilliant opportunity to check tips from this website. It really is so good and also stuffed with amusement for me and my office mates to visit your website at the very least 3 times every week to find out the latest issues you have got. And indeed, I am just actually happy with all the outstanding ideas you serve. Selected 3 areas in this posting are indeed the finest we have had.

I together with my buddies came checking out the great things on your site then instantly I had a terrible suspicion I never expressed respect to the web site owner for those secrets. The women happened to be consequently warmed to read through them and now have truly been loving these things. I appreciate you for getting indeed helpful and also for pick out variety of beneficial resources millions of individuals are really wanting to know about. Our own sincere apologies for not expressing appreciation to you sooner.

I simply needed to thank you very much once again. I'm not certain the things I would have used in the absence of those opinions shared by you regarding such a question. It was before a very terrifying concern for me personally, nevertheless being able to view this expert tactic you solved it made me to leap over gladness. Extremely grateful for this work and as well , pray you are aware of an amazing job you happen to be doing educating most people with the aid of your websites. I'm certain you haven't met all of us.

Thank you a lot for providing individuals with such a terrific chance to read from this website. It really is very brilliant plus packed with amusement for me personally and my office friends to search your blog at a minimum thrice every week to see the new items you will have. And lastly, I'm also usually fulfilled with all the spectacular inspiring ideas you give. Selected 4 points in this post are undeniably the most beneficial I have ever had.

There are actually lots of particulars like that to take into consideration. That could be a great level to bring up. I supply the thoughts above as basic inspiration however clearly there are questions just like the one you bring up the place an important thing can be working in honest good faith. I don?t know if finest practices have emerged around things like that, however I am sure that your job is clearly identified as a fair game. Each girls and boys feel the affect of only a second抯 pleasure, for the remainder of their lives.

I and also my buddies have been reading through the good helpful tips found on your web page and then the sudden developed a horrible feeling I never thanked the site owner for them. Most of the young boys had been certainly glad to see all of them and have extremely been enjoying these things. Appreciate your actually being so considerate and then for opting for these kinds of marvelous information most people are really needing to learn about. My personal sincere regret for not expressing appreciation to sooner.

I would like to express my admiration for your generosity supporting individuals who must have help with this important concern. Your real dedication to passing the solution along had become surprisingly powerful and have specifically allowed those much like me to achieve their dreams. Your amazing warm and helpful hints and tips denotes a great deal a person like me and somewhat more to my mates. Many thanks; from everyone of us.

I wish to express my passion for your kind-heartedness giving support to those who really want guidance on your question. Your real dedication to passing the solution throughout had become exceedingly practical and have consistently enabled guys like me to get to their endeavors. Your new warm and helpful publication signifies a lot to me and additionally to my fellow workers. Many thanks; from everyone of us.

I precisely had to appreciate you once more. I'm not certain the things that I might have gone through without those opinions provided by you over that topic. This has been a frightful setting in my circumstances, nevertheless witnessing this professional strategy you processed it forced me to cry for gladness. Now i am happy for your service as well as have high hopes you really know what a great job that you're undertaking instructing some other people using your blog. More than likely you have never got to know any of us.

Thank you for every one of your hard work on this website. My niece take interest in managing research and it's really easy to see why. Almost all know all relating to the lively form you render functional tricks by means of this website and in addition inspire contribution from people about this situation so our favorite child is understanding a whole lot. Enjoy the rest of the year. Your doing a dazzling job.

I in addition to my pals appeared to be going through the excellent thoughts on your site and then quickly came up with a horrible feeling I never thanked the blog owner for those strategies. The people happened to be consequently glad to read all of them and have absolutely been loving those things. Thank you for actually being indeed thoughtful and then for opting for variety of extraordinary issues most people are really needing to discover. Our honest apologies for not expressing gratitude to earlier.

I and my friends happened to be studying the best helpful hints from your web blog while all of the sudden I got a terrible suspicion I had not expressed respect to the web blog owner for those tips. My boys came certainly passionate to study them and now have definitely been tapping into those things. Appreciation for turning out to be well kind and also for going for some useful topics millions of individuals are really needing to learn about. My honest regret for not expressing gratitude to earlier.

I want to express some appreciation to this writer just for bailing me out of such a issue. Just after researching through the the net and seeing techniques that were not helpful, I assumed my entire life was done. Living minus the strategies to the problems you have solved by way of this short post is a critical case, as well as those that could have adversely affected my entire career if I had not noticed the blog. The competence and kindness in taking care of a lot of things was very helpful. I don't know what I would've done if I hadn't discovered such a stuff like this. I can also at this moment look forward to my future. Thanks a lot very much for this specialized and results-oriented guide. I will not hesitate to refer your web site to any individual who wants and needs guidelines on this subject matter.

I wanted to post you that bit of remark so as to thank you so much once again considering the spectacular techniques you've contributed on this site. This has been certainly surprisingly generous of you to supply unreservedly what a lot of people could possibly have sold for an e book to generate some profit on their own, mostly given that you might have tried it in case you decided. These smart ideas likewise worked like a easy way to know that most people have a similar passion really like mine to figure out great deal more in regard to this problem. I am sure there are millions of more enjoyable instances up front for people who check out your blog.

I wish to express some appreciation to the writer for bailing me out of this crisis. After surfing through the internet and coming across opinions which were not pleasant, I assumed my life was well over. Living devoid of the strategies to the problems you have fixed through this blog post is a crucial case, and ones which may have adversely damaged my entire career if I had not noticed your web site. Your primary expertise and kindness in maneuvering all the pieces was crucial. I'm not sure what I would have done if I had not encountered such a solution like this. I can also at this moment look forward to my future. Thanks so much for your reliable and sensible guide. I will not hesitate to endorse the website to anyone who should receive guidance about this problem.

I wish to express my affection for your kind-heartedness supporting men and women that actually need guidance on that study. Your very own commitment to getting the solution all-around had become really insightful and have usually helped girls much like me to attain their endeavors. Your insightful guideline can mean this much to me and additionally to my office colleagues. With thanks; from everyone of us.

Thanks a lot for giving everyone an exceptionally spectacular opportunity to read from this website. It is often very good plus full of fun for me and my office acquaintances to visit your blog a minimum of thrice in 7 days to see the newest guides you have. And of course, I am always contented with all the superb strategies you give. Certain two tips on this page are unequivocally the best we have all ever had.

I actually wanted to type a simple remark to say thanks to you for all of the amazing tips you are posting on this site. My time consuming internet search has at the end been paid with reliable facts and techniques to talk about with my family members. I 'd believe that we site visitors are very blessed to be in a really good network with very many awesome individuals with very helpful tips and hints. I feel pretty privileged to have come across your webpages and look forward to so many more cool times reading here. Thanks once again for a lot of things.

Thanks for each of your labor on this website. Kim delights in managing research and it's really obvious why. Most people know all of the dynamic tactic you render very helpful tips and tricks through this blog and as well strongly encourage participation from some others on that article plus our own simple princess has been understanding a lot of things. Take advantage of the remaining portion of the new year. You're carrying out a terrific job.

Thank you a lot for providing individuals with remarkably splendid opportunity to check tips from this site. It can be very cool and as well , full of a great time for me personally and my office colleagues to search your site at least 3 times every week to read through the newest issues you will have. Of course, I'm certainly fulfilled considering the magnificent hints served by you. Some 3 points in this post are undeniably the simplest we've had.

I just wanted to construct a remark to say thanks to you for those magnificent guidelines you are giving on this website. My extensive internet search has at the end of the day been honored with really good suggestions to talk about with my visitors. I would admit that many of us readers are very much blessed to live in a useful community with so many marvellous individuals with very helpful basics. I feel pretty grateful to have seen your weblog and look forward to many more exciting minutes reading here. Thanks a lot once more for everything.

I am writing to let you understand of the great encounter our daughter obtained reading your web site. She came to find several details, with the inclusion of what it is like to have a very effective giving nature to get other people just know various specialized subject matter. You undoubtedly exceeded people's expectations. Thank you for presenting those productive, trustworthy, informative and as well as cool tips on this topic to Jane.

I intended to put you a little bit of observation so as to give many thanks over again on the awesome thoughts you have provided at this time. This is so remarkably open-handed with you giving freely what exactly a number of us might have advertised for an e-book to end up making some profit for themselves, even more so given that you might have done it in the event you wanted. Those solutions also served to provide a great way to be certain that most people have similar fervor much like mine to grasp good deal more when considering this matter. I believe there are thousands of more pleasurable moments ahead for those who look over your website.

I precisely needed to say thanks yet again. I'm not certain the things I would have followed without these tips shown by you over this question. It absolutely was the frightful problem in my circumstances, however , finding out a specialized mode you solved the issue took me to leap with delight. I'm happier for this advice and even hope that you realize what an amazing job you have been undertaking educating most people via your webblog. More than likely you've never come across any of us.

My spouse and i felt so thankful when Ervin could finish up his investigation from the ideas he received through your weblog. It's not at all simplistic to just always be giving freely ideas that people might have been making money from. And we all grasp we have got the writer to be grateful to because of that. All the explanations you've made, the easy website navigation, the relationships you aid to engender - it's most awesome, and it is facilitating our son and us consider that the theme is amusing, which is pretty fundamental. Thank you for all the pieces!

I definitely wanted to post a brief note in order to express gratitude to you for the remarkable ways you are placing on this website. My extended internet investigation has now been recognized with excellent ideas to share with my two friends. I 'd believe that many of us visitors actually are unequivocally endowed to live in a great site with so many brilliant people with helpful methods. I feel quite happy to have used your web page and look forward to tons of more amazing minutes reading here. Thanks once again for all the details.

I and also my friends came reading the good tips and hints on the website while all of a sudden came up with an awful feeling I had not thanked you for those tips. Those men are already for that reason glad to study all of them and now have certainly been enjoying them. We appreciate you really being so considerate and for obtaining some superior subject matter most people are really needing to learn about. Our honest regret for not expressing appreciation to you sooner.

I am also writing to make you understand what a great discovery my wife's princess went through reading yuor web blog. She noticed several details, not to mention how it is like to have a wonderful teaching heart to let many others really easily know specific specialized issues. You truly exceeded her expected results. Thank you for producing such productive, safe, educational and even cool guidance on the topic to Mary.

I just wanted to make a quick message to be able to thank you for some of the great hints you are posting here. My particularly long internet lookup has at the end of the day been compensated with excellent points to write about with my relatives. I would declare that many of us visitors are very fortunate to exist in a notable site with so many awesome people with good concepts. I feel quite fortunate to have seen your weblog and look forward to some more amazing times reading here. Thanks a lot once again for everything.

Nice post. I learn one thing more difficult on totally different blogs everyday. It can all the time be stimulating to read content from other writers and apply a little bit one thing from their store. I抎 favor to make use of some with the content material on my blog whether or not you don抰 mind. Natually I抣l provide you with a hyperlink in your web blog. Thanks for sharing.

Thanks so much for providing individuals with an exceptionally terrific possiblity to check tips from this site. It is always very pleasant and as well , full of fun for me and my office friends to visit the blog at the least three times per week to find out the fresh tips you have got. And of course, I'm so usually impressed with the wonderful pointers served by you. Selected two tips in this posting are completely the very best we've had.

I'm also commenting to let you be aware of of the fantastic encounter my cousin's daughter encountered viewing your web site. She learned several details, which included what it is like to possess a marvelous helping character to make other people clearly know a variety of grueling issues. You really did more than her expectations. I appreciate you for coming up with such helpful, trustworthy, informative as well as fun tips about your topic to Janet.

Youre so cool! I dont suppose Ive learn anything like this before. So nice to find any person with some original ideas on this subject. realy thanks for starting this up. this website is something that is needed on the internet, someone with slightly originality. helpful job for bringing one thing new to the internet!

I just wanted to write down a simple remark to say thanks to you for these superb tips and tricks you are placing at this website. My long internet research has at the end of the day been paid with incredibly good points to exchange with my best friends. I would say that many of us readers are extremely endowed to be in a great site with so many awesome people with helpful principles. I feel very grateful to have used your web site and look forward to plenty of more fabulous times reading here. Thank you once more for a lot of things.

I definitely wanted to compose a brief note in order to say thanks to you for those awesome strategies you are sharing here. My extended internet lookup has now been rewarded with brilliant strategies to talk about with my close friends. I would repeat that many of us website visitors actually are extremely fortunate to dwell in a fabulous community with many perfect people with great plans. I feel somewhat lucky to have discovered the site and look forward to many more thrilling moments reading here. Thanks once more for everything.

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.