How to Control an LED with Raspberry Pi Webserver using Apache

Controlling an LED with Raspberry Pi Webserver using Apache

In this tutorial, we will install Apache web server in Raspberry Pi to control the LED from a webpage that can be accessed from anywhere over the internet. This is a basic tutorial with minimum features and it can be further modified to use this method in IoT-based home automation, remote control automation, robotics, etc.

Here we control an LED connected to Raspberry Pi by using Apache web server. For this, we create an HTML/php web page which has two buttons - one for turning on the LED and the second for turning off the LED.

 

Components Required

  1. Raspberry pi board (With Raspbian operating system)
  2. LED
  3. 250-ohm resistor
  4. Jumper Wires

 

An SSH client (Putty) is used to connect the Raspberry pi using a Laptop or computer. For this, the raspberry pi needs to be connected to a network via LAN or Wi-Fi. If you have a separate monitor for your raspberry pi, then it's better to connect raspberry pi with the monitor and you don’t have to use any SSH client.

 

Controlling LED using Raspberry Pi Webserver

Step 1: Connections

Raspberry Pi LED Connection Circuit

The connections in this project are quite simple - the positive pin of LED is connected to GPIO 27 pin and the negative pin to a 270 ohm resistor, the other side of which is connected to GND pin.

 

Step 2: Installing WiringPi Library

WiringPi is a PIN-based GPIO access library written in C for the BCM2835, BCM2836, and BCM2837 SoC devices used in all Raspberry Pi versions. It’s released under the GNU LGPLv3 license and is usable from C, C++, and RTB (BASIC) as well as many other languages with suitable wrappers.

1. First we will update our Pi with the latest versions of Raspbian using the command:

sudo apt-get update

 

2. Now we will install git by using this command:

sudo apt-get install git-core

 

3. Now obtain WiringPi using git by this command:

git clone git://git.drogon.net/wiringPi

 

4. Then install WiringPi library using:

cd wiringP./build

 

Step 3: Installing a Web Server

Apache is a very popular webserver, designed to create web servers that have the ability to host one or more HTTP-based websites. Apache Web Server can be enhanced by manipulating the code base or adding multiple extensions/add-ons. In our project, we are using an HTTP server and its PHP extension.

To Install Apache web server, we will use the following commands:

First, update the available packages:

sudo apt-get update

 

Now, install the apache2 package by using this command in the terminal:

sudo apt-get install apache2 -y

 

To test the web server whether it is working or not, go to your browser and type the Pi’s IP address in the tab.

To find the Pi's IP address, type ifconfig at the command line.

By default, Apache puts a test HTML file in the web folder. This default web page is served when you browse to http://192.168.1.31 (whatever the Pi's IP address is) from another computer on the network.

Browse to the default web page either on the Pi or from another computer on the network and you will see the following:

Apache2 Webserver

This means the Apache web server is working.

 

Now we will see how to change the default web page with your own HTML page

This default web page is just an HTML file on the filesystem. It is located at var/www/html/index.html.

Navigate to this directory in a terminal window and have a look at what's inside:

cd  var/www/html
ls -al
This will show you:
total 12
drwxr-xr-x  2 root root 4096 Jan  8 01:29 .
drwxr-xr-x 12 root root 4096 Jan  8 01:28 ..
-rw-r--r--  1 root root  177 Jan  8 01:29 index.html

 

This shows that by default there is one file in /var/www/html/ called index.html and it is owned by the root user. To edit the file, you need to change its ownership to your own username. Change the owner of the file using:

Sudo chown pi: index.html.

 

You can now try editing this file and then refresh the browser to see the web page change.

 

Install PHP in Raspberry Pi  

Now if we want to use PHP code along with HTML, then we have to further install the PHP extension in Raspberry pi. Using PHP code, we can create shell commands to control the LED from the PHP script.

To allow the Apache server to edit PHP files, we will install the latest version of PHP and the PHP module for Apache. Use the following command in terminal to install these:

sudo apt-get install php libapache2-mod-php -y

 

Now remove the default index.html file:

sudo rm index.html

 

And create your own index.php file:

sudo nano index.php

 

Now enter the below code in index.php to test the PHP installation.

<?php phpinfo(); ?>

 

Save it by pressing CTRL + X and the ‘y’ and enter. Now refresh the webpage in your browser, you will see a long page with lots of information about PHP. This shows that the PHP extension is installed properly. If you have any problem with the pages or if the pages do not appear, try reinstalling the apache server and its PHP extension.

 

Step 5: Start Coding for controlling GPIO pin using this Raspberry Pi Webserver

Now delete the previous code in index.php (<?php phpinfo(); ?>) file and insert below PHP code to control GPIO pins inside body of HTML code.

Below is the complete code for creating two buttons to turn on and off the LED connected to Raspberry Pi.

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Raspberry Pi WiFi Controlled LED</title>
</head>
       <body>
       <center><h1>Control LED using Raspberry Pi Webserver</h1>      
         <form method="get" action="index.php">                
            <input type="submit" style = "font-size: 14 pt" value="OFF" name="off">
            <input type="submit" style = "font-size: 14 pt" value="ON" name="on">
         </form>​​​
                         </center>
<?php
    shell_exec("/usr/local/bin/gpio -g mode 27 out");
    if(isset($_GET['off']))
        {
                        echo "LED is off";
                        shell_exec("/usr/local/bin/gpio -g write 27 0");
        }
            else if(isset($_GET['on']))
            {
                        echo "LED is on";
                        shell_exec("/usr/local/bin/gpio -g write 27 1");
            }
?>
   </body>
</html>

Raspberry Pi Webserver

In the above code there is a PHP script which checks which button is pressed by using below code and then turns on and off the LED accordingly.

<?php
    shell_exec("/usr/local/bin/gpio -g mode 27 out");
    if(isset($_GET['off']))
        {
                        echo "LED is off";
                        shell_exec("/usr/local/bin/gpio -g write 27 0");
        }
            else if(isset($_GET['on']))
            {
                        echo "LED is on";
                        shell_exec("/usr/local/bin/gpio -g write 27 1");
            }
?>

 

Here we have used shell_exec() command in php code, this command is used to run the shell command from the PHP script. Learn more about shell_exec here. If you run the command inside shell_exec directly form the terminal of Raspberry pi, you can directly make GPIO pin 27 low or high. Below are two commands to test the LED directly from terminal.

/usr/local/bin/gpio -g write 27 0
/usr/local/bin/gpio -g write 27 1

 

After completing this, run the code in your browser by typing the IP address of raspberry pi in the browser. You will see 2 buttons - ON, OFF to control your LED by clicking these buttons.

 

I hope you liked this article. You can also check out our other Internet of Things projects.

3420 Comments

Very nice post. I just stumbled upon your weblog and wished to
say that I've truly enjoyed browsing your blog posts.
After all I will be subscribing to your rss feed and I hope you write again very soon!

Woah! I'm really enjoying the template/theme of this site.

It's simple, yet effective. A lot of times it's challenging to get that
"perfect balance" between superb usability and visual appeal.
I must say you've done a superb job with this.
Also, the blog loads very quick for me on Internet explorer.
Exceptional Blog!

Great post. I used to be checking constantly this weblog and I'm inspired!

Very helpful info specifically the remaining part :) I care for such info a
lot. I used to be seeking this certain information for a very long time.
Thank you and best of luck.

Hey there would you mind stating which blog platform you're working with? I'm looking to start my own blog soon but I'm having a hard time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I'm looking for something unique. P.S Sorry for getting off-topic but I had to ask!|

hey i gain lot of knowladge thourgh your article if you are also want gain your knowladge about satta king g then check gurusattaking.com official website

I truly wanted to post a small remark in order to appreciate you for these marvelous recommendations you are sharing at this site. My time consuming internet search has at the end of the day been paid with pleasant content to exchange with my family. I 'd suppose that most of us readers actually are undeniably lucky to live in a perfect site with many perfect professionals with very helpful basics. I feel extremely grateful to have seen the web site and look forward to many more fabulous moments reading here. Thank you once more for everything.

I want to show some thanks to you just for bailing me out of such a issue. Right after surfing throughout the world-wide-web and getting solutions which were not pleasant, I was thinking my entire life was well over. Existing devoid of the solutions to the issues you've solved by way of your entire article content is a serious case, as well as those which may have adversely affected my career if I hadn't encountered your site. Your actual mastery and kindness in dealing with all the details was vital. I am not sure what I would have done if I had not come upon such a stuff like this. I'm able to at this moment look forward to my future. Thank you very much for your specialized and amazing help. I won't hesitate to endorse your web blog to any person who should get guide about this topic.

I precisely wanted to thank you very much once again. I am not sure the things I would've carried out without those information discussed by you regarding such theme. It had been a troublesome issue for me, but encountering this well-written way you resolved that forced me to jump over contentment. I'm just grateful for your support and thus hope that you find out what an amazing job you were undertaking instructing most people with the aid of your web site. Most probably you've never come across any of us.

I and my buddies happened to be checking out the best tips found on your website while at once I had a horrible feeling I never thanked the blog owner for those tips. All the people became as a result happy to study all of them and now have clearly been loving those things. Thank you for simply being indeed thoughtful as well as for deciding upon some magnificent issues most people are really needing to be aware of. My sincere apologies for not expressing appreciation to earlier.

I must express thanks to the writer for bailing me out of this type of issue. Just after exploring throughout the world wide web and finding ways that were not productive, I was thinking my life was done. Living without the approaches to the problems you've solved as a result of your good website is a crucial case, as well as the ones that might have negatively damaged my career if I hadn't noticed your web page. That ability and kindness in taking care of every part was important. I don't know what I would have done if I had not come across such a thing like this. It's possible to at this time look ahead to my future. Thanks very much for your high quality and effective guide. I will not hesitate to propose your blog to anyone who ought to have recommendations about this topic.

I in addition to my guys ended up viewing the nice recommendations located on your web site and so suddenly came up with a horrible suspicion I never expressed respect to the blog owner for those tips. All of the boys were totally glad to learn them and now have certainly been making the most of those things. We appreciate you really being well accommodating and for picking out such awesome resources millions of individuals are really wanting to learn about. Our sincere regret for not expressing appreciation to you earlier.

I not to mention my pals came looking at the good points located on your website while before long I got a horrible suspicion I had not thanked the blog owner for those tips. Most of the guys appeared to be as a consequence very interested to read all of them and have in effect absolutely been enjoying these things. Appreciate your being indeed accommodating and also for considering such ideal information most people are really desirous to understand about. My sincere apologies for not expressing gratitude to you sooner.

I have to point out my respect for your generosity supporting individuals who really want help on in this niche. Your very own commitment to getting the solution across has been remarkably significant and have always permitted folks just like me to achieve their goals. The important guidelines means much to me and further more to my fellow workers. With thanks; from everyone of us.

Thanks for all of the efforts on this site. My mom really likes getting into research and it is simple to grasp why. We all learn all relating to the lively method you provide reliable tactics via the website and even inspire contribution from visitors about this situation plus our favorite daughter is becoming educated a lot. Enjoy the rest of the new year. You are always carrying out a remarkable job.

I am writing to make you be aware of of the superb discovery my wife's child gained using your webblog. She figured out so many things, including how it is like to have an awesome coaching style to make other folks clearly know just exactly certain impossible things. You actually surpassed our expectations. Many thanks for giving the invaluable, trustworthy, educational and even easy tips about that topic to Gloria.

I and my pals were actually reading the nice strategies from your web page then immediately came up with an awful feeling I had not thanked the blog owner for those strategies. These ladies are already warmed to learn all of them and have in fact been taking advantage of them. Appreciate your turning out to be so considerate and also for utilizing this kind of outstanding subject matter millions of individuals are really needing to discover. My very own honest apologies for not saying thanks to earlier.

Thanks for all of your efforts on this web site. Kim take interest in conducting investigation and it is easy to understand why. I know all regarding the dynamic method you create important tactics via your website and even attract contribution from the others on that area plus our own simple princess is always studying a great deal. Enjoy the rest of the year. You're the one performing a fabulous job.

I actually wanted to post a quick message to say thanks to you for all of the nice tips and hints you are placing at this website. My extensive internet look up has now been recognized with professional details to write about with my relatives. I 'd declare that most of us website visitors are definitely lucky to be in a decent site with so many awesome individuals with very beneficial basics. I feel extremely happy to have used your website page and look forward to many more thrilling times reading here. Thanks once again for everything.

My wife and i have been absolutely excited when Emmanuel could finish off his reports using the ideas he had using your blog. It's not at all simplistic to just be releasing procedures which people might have been trying to sell. So we figure out we now have the writer to appreciate because of that. These illustrations you've made, the simple site navigation, the relationships you will help instill - it's mostly terrific, and it's really helping our son in addition to us feel that that topic is enjoyable, which is certainly seriously important. Thank you for all the pieces!

I precisely desired to thank you very much once again. I am not sure the things that I might have carried out in the absence of the actual ways documented by you relating to such theme. It became a very terrifying difficulty in my circumstances, but spending time with a new professional technique you solved it forced me to leap for contentment. I am happy for the help as well as pray you really know what an amazing job you are undertaking instructing other individuals by way of a web site. I am sure you have never met all of us.

I happen to be commenting to make you understand what a exceptional encounter my friend's girl undergone reading through your webblog. She discovered such a lot of issues, with the inclusion of what it's like to possess an excellent giving heart to get folks just understand specific problematic topics. You truly exceeded my expected results. Thank you for producing these important, dependable, educational and as well as unique guidance on this topic to Emily.

I and my friends were checking the excellent hints found on the website and suddenly developed an awful suspicion I never thanked the website owner for them. The people appeared to be for this reason excited to see them and have in effect in fact been taking pleasure in them. Appreciation for being very kind and also for getting such smart resources most people are really desirous to know about. My personal sincere regret for not expressing appreciation to earlier.

Thank you so much for providing individuals with an exceptionally spectacular opportunity to discover important secrets from this site. It is always very useful and as well , stuffed with a lot of fun for me and my office colleagues to visit your site more than 3 times in one week to learn the new items you will have. And indeed, I'm certainly astounded considering the magnificent things you serve. Some two areas in this article are surely the most impressive we have ever had.

I enjoy you because of each of your efforts on this website. My aunt delights in getting into investigations and it's really easy to understand why. We all notice all concerning the powerful means you convey efficient tips and tricks by means of this blog and therefore recommend participation from other individuals on the point so our own princess is always understanding a whole lot. Take advantage of the remaining portion of the year. Your performing a really great job.

My husband and i got so lucky when Jordan could finish off his preliminary research while using the precious recommendations he grabbed through your site. It is now and again perplexing to simply find yourself handing out secrets and techniques which usually others might have been trying to sell. And we all take into account we need the blog owner to give thanks to for this. These explanations you've made, the easy blog navigation, the relationships you can make it possible to engender - it's many excellent, and it's facilitating our son and the family feel that the content is cool, and that's particularly vital. Thanks for all!

I'm also commenting to make you understand of the helpful encounter my cousin's princess encountered checking your web page. She picked up several things, which include what it is like to have an incredible coaching style to get a number of people without hassle fully understand chosen grueling topics. You undoubtedly surpassed visitors' expected results. Thanks for showing these effective, safe, informative and cool thoughts on this topic to Jane.

I in addition to my pals happened to be studying the nice procedures located on your website and so immediately I had a horrible feeling I had not expressed respect to the web blog owner for those tips. The men are actually as a result thrilled to read all of them and have in reality been taking pleasure in them. Thank you for indeed being well thoughtful and also for choosing varieties of remarkable useful guides millions of individuals are really needing to know about. Our honest apologies for not expressing gratitude to you earlier.

I simply wanted to thank you so much again. I do not know the things that I would have gone through in the absence of the entire creative ideas shown by you relating to such area. It was actually an absolute daunting dilemma in my position, but considering the very skilled strategy you handled that made me to jump with contentment. I am just happier for the advice and even expect you are aware of a powerful job you were undertaking training many others using a site. Most likely you haven't encountered all of us.

I want to express thanks to this writer for bailing me out of this type of trouble. As a result of surfing around through the the web and finding principles that were not pleasant, I thought my life was well over. Being alive without the solutions to the difficulties you have resolved by means of your good article is a serious case, as well as ones which could have badly affected my career if I had not noticed your web blog. Your good know-how and kindness in dealing with all the details was priceless. I don't know what I would've done if I hadn't come upon such a subject like this. I'm able to at this moment look forward to my future. Thanks a lot very much for this skilled and result oriented guide. I won't hesitate to endorse the website to anyone who needs guidelines about this area.

My spouse and i were so relieved Emmanuel managed to round up his reports while using the ideas he acquired while using the web page. It's not at all simplistic to just always be giving for free guides which usually the rest have been selling. So we fully grasp we have you to appreciate because of that. All the illustrations you have made, the simple web site navigation, the friendships your site aid to foster - it is most remarkable, and it's aiding our son in addition to us consider that this article is exciting, which is certainly seriously important. Thank you for everything!

I as well as my pals came reading the great strategies from your web blog then immediately I got an awful feeling I never thanked you for those tips. All the young men became as a consequence stimulated to study all of them and already have pretty much been taking advantage of these things. Appreciate your truly being very considerate and for obtaining these kinds of awesome things millions of individuals are really wanting to learn about. My personal sincere apologies for not expressing gratitude to you earlier.

I happen to be commenting to make you know of the great discovery my cousin's child obtained reading through your webblog. She mastered a lot of things, most notably how it is like to possess an awesome giving nature to make a number of people smoothly learn a number of problematic things. You really did more than people's expectations. Many thanks for producing such good, healthy, informative as well as fun guidance on your topic to Ethel.

I want to show my gratitude for your kindness for men who absolutely need guidance on the area of interest. Your very own dedication to getting the solution around appears to be unbelievably effective and has in most cases empowered somebody just like me to get to their ambitions. The warm and friendly tips and hints indicates a great deal a person like me and additionally to my office colleagues. Warm regards; from everyone of us.

Needed to send you the very small word to help thank you yet again just for the incredible basics you have provided on this website. It's really incredibly generous of you to grant publicly precisely what a few people might have distributed as an electronic book to get some dough on their own, even more so seeing that you might have done it in the event you considered necessary. The good tips likewise served as the fantastic way to be sure that many people have the same eagerness just as my very own to figure out significantly more around this matter. I believe there are many more fun occasions up front for people who read your site.

I'm just writing to let you know what a really good discovery our princess developed checking your site. She noticed numerous details, which included what it's like to possess an awesome coaching heart to get certain people with ease know just exactly a variety of extremely tough topics. You undoubtedly did more than our expected results. Thanks for delivering those interesting, trustworthy, educational and even fun tips on this topic to Evelyn.

I have to show appreciation to this writer just for bailing me out of this condition. After surfing around throughout the world wide web and seeing techniques which were not productive, I figured my entire life was gone. Living without the presence of approaches to the difficulties you have resolved all through your main write-up is a serious case, and ones which might have badly affected my career if I had not noticed your site. The training and kindness in maneuvering all things was invaluable. I'm not sure what I would have done if I hadn't encountered such a solution like this. I can at this time look forward to my future. Thanks so much for your specialized and amazing guide. I won't be reluctant to propose your blog to any person who would need assistance on this matter.

I am only writing to make you understand what a incredible experience my wife's princess had checking your webblog. She came to find a lot of things, which included what it's like to possess an awesome giving character to make the others completely know precisely a number of extremely tough issues. You actually surpassed her desires. I appreciate you for churning out these productive, trusted, revealing and even easy tips on the topic to Sandra.

Thank you a lot for giving everyone an exceptionally terrific chance to read critical reviews from here. It's usually so pleasurable and jam-packed with a good time for me and my office acquaintances to visit your blog minimum 3 times every week to find out the latest secrets you have got. And of course, we are usually happy considering the brilliant information you serve. Certain 2 facts in this posting are surely the simplest we have had.

I must point out my respect for your kindness supporting folks who should have assistance with this important subject matter. Your very own commitment to passing the message all through had been especially advantageous and has frequently allowed women much like me to arrive at their dreams. Your entire useful advice means a lot to me and much more to my peers. Thank you; from each one of us.

I actually wanted to write down a note to express gratitude to you for all the unique points you are posting on this site. My extensive internet search has at the end been rewarded with reputable suggestions to talk about with my visitors. I 'd assume that many of us visitors actually are really blessed to live in a decent website with very many brilliant professionals with insightful principles. I feel quite privileged to have used the web page and look forward to plenty of more enjoyable minutes reading here. Thank you again for a lot of things.

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.