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.

2690 Comments

I in addition to my pals happened to be reviewing the nice secrets on your website and immediately I had a horrible suspicion I never thanked the web blog owner for them. All the people happened to be passionate to read them and already have truly been loving these things. Appreciate your turning out to be very accommodating as well as for making a decision on these kinds of ideal subjects millions of individuals are really desirous to be informed on. My very own sincere regret for not expressing gratitude to you sooner.

Thanks for each of your efforts on this site. Betty really loves conducting investigations and it is obvious why. Most of us know all about the compelling medium you deliver sensible things on the blog and welcome participation from website visitors on the subject then my princess has always been starting to learn a lot. Enjoy the remaining portion of the new year. You are conducting a splendid job.

My spouse and i got delighted that Chris managed to round up his research through your ideas he obtained while using the site. It is now and again perplexing just to possibly be making a gift of hints which often some others might have been selling. And now we acknowledge we have got the writer to be grateful to for this. The most important illustrations you have made, the straightforward site menu, the relationships you can help to create - it is most terrific, and it's really assisting our son in addition to our family feel that this concept is amusing, which is certainly pretty fundamental. Thank you for all the pieces!

A lot of thanks for your entire hard work on this blog. My niece delights in making time for investigation and it's really easy to see why. We all learn all relating to the powerful form you render efficient thoughts on this web site and even attract participation from some others on this topic while our child is now understanding a whole lot. Take advantage of the remaining portion of the new year. You are always performing a glorious job.

My wife and i got so relieved when Albert could finish off his investigation from your precious recommendations he was given while using the web site. It is now and again perplexing to simply always be giving freely guidance many people might have been making money from. Therefore we grasp we need the website owner to thank for that. Most of the illustrations you made, the simple website menu, the relationships you can aid to foster - it's many great, and it is assisting our son and our family understand the subject matter is entertaining, which is rather important. Thanks for everything!

Needed to write you a very small note to be able to say thanks a lot once again relating to the striking tricks you have provided on this website. It has been unbelievably open-handed of people like you to convey openly what a number of us could have marketed for an ebook to earn some cash for their own end, and in particular seeing that you might well have done it if you desired. These tricks likewise served to become a easy way to know that some people have a similar dream just like my personal own to realize a great deal more in respect of this problem. I think there are lots of more fun times ahead for people who scan your website.

I would like to show appreciation to this writer just for bailing me out of this type of issue. Right after researching through the world-wide-web and finding ways which were not pleasant, I believed my life was done. Living minus the strategies to the difficulties you have solved all through your main posting is a critical case, as well as the ones which might have negatively damaged my career if I had not encountered your blog. Your personal talents and kindness in controlling a lot of stuff was useful. I'm not sure what I would have done if I hadn't encountered such a step like this. I can also at this moment relish my future. Thanks a lot so much for the specialized and amazing guide. I won't be reluctant to refer the sites to anybody who should have guide about this area.

I wanted to draft you a little bit of observation to thank you so much once again over the unique suggestions you've shared on this website. This is really pretty open-handed with people like you to deliver unreservedly what exactly a few people might have advertised as an e book to help with making some dough on their own, specifically considering the fact that you could have done it in case you decided. The creative ideas likewise worked like the easy way to fully grasp that most people have the identical dreams just like my very own to grasp way more pertaining to this matter. I know there are several more pleasant sessions up front for people who read carefully your site.

I wish to express some thanks to the writer for bailing me out of this circumstance. Because of looking throughout the search engines and meeting notions which were not productive, I thought my entire life was gone. Living minus the approaches to the issues you have solved all through your main review is a serious case, as well as those that would have in a wrong way affected my entire career if I hadn't discovered your website. Your own talents and kindness in controlling a lot of stuff was important. I am not sure what I would've done if I had not come across such a solution like this. I can now relish my future. Thanks a lot very much for your expert and sensible help. I won't be reluctant to endorse your blog post to anyone who will need guidance about this area.

I truly wanted to write a simple message so as to appreciate you for all the precious tactics you are giving on this website. My considerable internet lookup has at the end of the day been paid with pleasant facts and strategies to write about with my guests. I 'd mention that we site visitors are very blessed to live in a notable place with very many marvellous people with valuable tips and hints. I feel quite privileged to have discovered the web page and look forward to so many more awesome moments reading here. Thanks once again for a lot of things.

I wish to express thanks to the writer just for rescuing me from such a matter. As a result of looking out throughout the internet and coming across thoughts that were not productive, I was thinking my life was gone. Living without the presence of strategies to the issues you have resolved through this posting is a serious case, as well as the kind that could have negatively affected my entire career if I had not noticed your blog. Your personal know-how and kindness in dealing with almost everything was very helpful. I am not sure what I would've done if I had not come across such a thing like this. I am able to at this time look forward to my future. Thanks for your time so much for this expert and results-oriented guide. I won't think twice to refer your web page to any individual who requires tips about this issue.

I must point out my affection for your kind-heartedness giving support to folks who absolutely need guidance on in this matter. Your real commitment to passing the solution all over was definitely productive and have surely permitted many people like me to arrive at their endeavors. Your amazing useful useful information entails a lot to me and further more to my office colleagues. Warm regards; from all of us.

I as well as my friends have already been reading the great procedures from the blog and then suddenly developed a terrible suspicion I never thanked the web blog owner for them. The boys happened to be certainly stimulated to study them and have now actually been taking advantage of those things. Many thanks for really being well considerate and for settling on this form of useful areas most people are really desperate to discover. My very own sincere apologies for not saying thanks to sooner.

I want to get across my gratitude for your generosity giving support to folks that absolutely need guidance on the subject. Your special commitment to getting the message all around was rather effective and has in most cases encouraged some individuals just like me to attain their endeavors. Your warm and friendly instruction signifies this much a person like me and even more to my fellow workers. Warm regards; from everyone of us.

I must voice my respect for your kindness supporting those people who require help with the situation. Your personal commitment to getting the message all over was extremely practical and have continually helped somebody like me to attain their targets. Your warm and helpful suggestions entails a lot to me and substantially more to my peers. Thanks a lot; from each one of us.

I want to express my passion for your kind-heartedness giving support to all those that actually need guidance on that question. Your special commitment to getting the solution all-around ended up being really invaluable and have specifically helped others just like me to get to their goals. Your warm and friendly guidelines means so much a person like me and additionally to my mates. Many thanks; from all of us.

Thanks for your own labor on this site. My mom takes pleasure in engaging in research and it's really easy to understand why. Many of us learn all regarding the dynamic mode you convey very important ideas through your web site and therefore improve contribution from others on that concern plus my simple princess is really being taught a lot. Take advantage of the rest of the year. You are performing a brilliant job.

Thank you for all of your hard work on this web page. My daughter really likes working on research and it's easy to understand why. Most of us hear all concerning the lively manner you present worthwhile strategies on the website and as well recommend contribution from people on this topic and our own simple princess is without a doubt studying a lot of things. Take pleasure in the remaining portion of the year. You're carrying out a powerful job.

I not to mention my buddies appeared to be following the excellent ideas on your website then all of a sudden got an awful suspicion I had not expressed respect to the website owner for those tips. Most of the young men became absolutely passionate to read all of them and already have surely been loving those things. We appreciate you genuinely really accommodating as well as for figuring out these kinds of excellent subjects millions of individuals are really needing to discover. My very own honest apologies for not expressing gratitude to you sooner.

I in addition to my friends happened to be viewing the excellent tips located on your web page and so suddenly I got a terrible feeling I had not expressed respect to the blog owner for them. Most of the ladies happened to be consequently thrilled to see all of them and now have simply been enjoying them. Many thanks for truly being really accommodating and then for making a decision on these kinds of good subject areas most people are really eager to understand about. My very own honest regret for not expressing appreciation to you earlier.

I want to get across my gratitude for your kind-heartedness for people who need help on your topic. Your very own commitment to getting the message across ended up being exceptionally important and have without exception permitted professionals just like me to reach their goals. The useful publication denotes much a person like me and much more to my office workers. Thanks a lot; from all of us.

I precisely desired to appreciate you once again. I do not know what I could possibly have gone through in the absence of the type of tricks documented by you relating to this problem. It has been a real scary condition for me personally, nevertheless being able to view a new well-written manner you dealt with the issue took me to weep over fulfillment. I am just thankful for the service and then believe you are aware of an amazing job you happen to be getting into teaching people through your blog. Most probably you haven't got to know any of us.

I not to mention my pals happened to be checking the nice thoughts from your web site while then got a terrible feeling I had not thanked the site owner for those secrets. All of the young men had been absolutely happy to read them and have in actuality been tapping into these things. Appreciation for indeed being considerably helpful and also for deciding upon this form of really good ideas millions of individuals are really eager to learn about. My very own sincere regret for not expressing gratitude to you sooner.

Thanks so much for giving everyone such a breathtaking possiblity to check tips from this web site. It's usually so excellent and as well , full of fun for me and my office peers to visit your site not less than 3 times every week to learn the latest tips you have got. And lastly, I'm also usually astounded with the fantastic ideas served by you. Selected 3 areas on this page are truly the most impressive we have all had.

I would like to express thanks to the writer for bailing me out of this particular problem. Because of searching through the the net and coming across concepts which are not pleasant, I believed my entire life was over. Being alive without the strategies to the problems you've solved as a result of your entire website is a critical case, as well as ones that could have in a wrong way damaged my career if I hadn't come across your web blog. Your own capability and kindness in maneuvering the whole lot was crucial. I don't know what I would have done if I had not encountered such a step like this. I can also at this time relish my future. Thanks a lot very much for this skilled and effective help. I won't hesitate to suggest your web site to any person who needs and wants direction about this subject matter.

I truly wanted to write a simple comment so as to appreciate you for the magnificent secrets you are sharing here. My prolonged internet investigation has at the end of the day been compensated with reputable insight to exchange with my classmates and friends. I would believe that we website visitors are really endowed to exist in a useful place with many outstanding people with insightful techniques. I feel very much happy to have discovered the web pages and look forward to tons of more enjoyable minutes reading here. Thanks again for everything.

I not to mention my guys happened to be looking at the nice tips and tricks located on your web blog and instantly developed a horrible feeling I never thanked the website owner for those strategies. My guys came for this reason excited to read them and have unquestionably been making the most of them. Appreciation for indeed being so considerate and also for settling on these kinds of really good things most people are really desirous to be aware of. My personal honest regret for not saying thanks to sooner.

I truly wanted to write a brief note in order to appreciate you for all of the stunning tricks you are showing at this site. My time intensive internet investigation has now been compensated with reliable knowledge to write about with my partners. I 'd assume that many of us visitors actually are undoubtedly fortunate to dwell in a perfect site with very many marvellous professionals with beneficial things. I feel truly lucky to have come across the weblog and look forward to really more exciting times reading here. Thanks again for a lot of things.

I and my pals have already been examining the excellent information and facts located on the website while suddenly I got an awful suspicion I never thanked the blog owner for those tips. All of the ladies came consequently excited to see them and now have really been making the most of these things. Thanks for being really thoughtful as well as for selecting this sort of incredible subject areas millions of individuals are really wanting to discover. Our sincere apologies for not expressing appreciation to you sooner.

Weight Vest Training: Benefits of Weighted Vests | iamazonsurmountwayweightedvest_2021 What are the best weighted vests for CrossFit, running, hiking, and walking? ... Best Budget Weighted Vest for Home Gym Training And Calisthenics.Using weighted vests or backpacks to increase intensity to a standard flat.This Weighted Vest To Let You Increase The Difficulty Of Your Wods And Bodyweight Exercises.his is simply hiking with additional weight other than your body weight.

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.