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

Nice post. I be taught something tougher on totally different blogs everyday. It can all the time be stimulating to read content material from other writers and follow just a little one thing from their store. I抎 want to use some with the content material on my weblog whether or not you don抰 mind. Natually I抣l provide you with a hyperlink on your internet blog. Thanks for sharing.

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 happen to be commenting to make you be aware of of the notable discovery my cousin's princess gained reading through your site. She learned so many pieces, with the inclusion of how it is like to have a wonderful coaching spirit to get other folks quite simply comprehend several problematic topics. You actually exceeded her desires. Thank you for imparting those powerful, healthy, edifying and also unique tips about that topic to Kate.

A formidable share, I simply given this onto a colleague who was doing a bit analysis on this. And he in actual fact bought me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to debate this, I really feel strongly about it and love studying more on this topic. If attainable, as you become expertise, would you mind updating your blog with more details? It is highly helpful for me. Massive thumb up for this blog publish!

I'm just commenting to make you understand of the useful experience my cousin's princess went through studying your web page. She realized several things, not to mention what it's like to possess an awesome coaching style to have other people without hassle gain knowledge of specified tortuous issues. You truly exceeded readers' expected results. Thank you for showing those valuable, trustworthy, educational and even fun tips on that topic to Ethel.

I simply needed to thank you very much all over again. I do not know the things I might have tried without the aspects contributed by you concerning such situation. It actually was a real horrifying difficulty for me, but taking note of the very professional strategy you processed the issue forced me to cry over joy. I will be thankful for this support and then expect you really know what an amazing job you happen to be accomplishing training the rest through the use of your site. Probably you have never met any of us.

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 have to convey my passion for your kindness supporting men and women that need help with in this situation. Your very own commitment to passing the message up and down appears to be unbelievably productive and have regularly enabled women much like me to realize their targets. The interesting facts implies much a person like me and even further to my mates. Many thanks; from each one of us.

I definitely wanted to send a small note to say thanks to you for these fabulous techniques you are placing here. My time intensive internet investigation has at the end of the day been rewarded with sensible content to exchange with my friends. I 'd admit that many of us visitors are undoubtedly fortunate to exist in a useful network with very many marvellous professionals with great hints. I feel quite happy to have seen your entire site and look forward to many more entertaining moments reading here. Thanks a lot 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.

I precisely wanted to appreciate you once more. I am not sure what I might have done without those creative concepts discussed by you directly on this industry. Certainly was an absolute fearsome dilemma in my circumstances, however , seeing your expert form you processed that forced me to leap with joy. Extremely grateful for this work and as well , hope you realize what a great job your are carrying out training the mediocre ones through the use of your webblog. I know that you have never met all of us.

I really wanted to jot down a brief message to be able to say thanks to you for all of the pleasant concepts you are writing at this website. My long internet research has finally been recognized with good concept to talk about with my pals. I would express that most of us visitors are definitely fortunate to dwell in a great place with so many awesome people with useful tricks. I feel rather happy to have used the web pages and look forward to so many more exciting moments reading here. Thanks again for all the details.

An impressive share, I simply given this onto a colleague who was doing a bit of analysis on this. And he in truth bought me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to debate this, I really feel strongly about it and love reading extra on this topic. If potential, as you grow to be expertise, would you mind updating your blog with more details? It is extremely useful for me. Huge thumb up for this blog submit!

I precisely wished to say thanks once again. I am not sure the things that I might have used without those tactics documented by you on that area. It had been the troublesome situation for me, nevertheless being able to view this professional way you handled it took me to cry for gladness. Now i'm thankful for your advice and as well , pray you comprehend what an amazing job that you're getting into teaching the others through the use of your web site. I'm certain you've never got to know all of us.

I happen to be commenting to let you know what a impressive discovery my child went through browsing yuor web blog. She picked up numerous pieces, which included what it's like to have an excellent coaching mood to have a number of people very easily thoroughly grasp specified complicated matters. You truly exceeded people's desires. Many thanks for offering these priceless, dependable, explanatory and as well as cool tips about your topic to Julie.

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.

I'm writing to make you be aware of of the fantastic discovery my cousin's princess gained viewing your web page. She noticed a lot of pieces, not to mention what it is like to have an incredible coaching character to let most people without hassle learn various hard to do subject matter. You really exceeded people's expected results. Thank you for showing the useful, trusted, informative and even unique guidance on your topic to Sandra.

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.

I have to point out my respect for your generosity giving support to those people who have the need for assistance with this one concept. Your personal commitment to getting the message all over appears to be rather functional and has frequently allowed most people much like me to achieve their goals. This useful guide indicates this much a person like me and even further to my peers. Regards; from all of us.

I wish to express my thanks to this writer just for rescuing me from this incident. Right after checking throughout the online world and meeting views which are not beneficial, I figured my life was done. Living devoid of the answers to the issues you've sorted out by way of your good write-up is a critical case, as well as the ones that could have in a negative way affected my entire career if I had not discovered your web site. The training and kindness in controlling all the things was useful. I am not sure what I would've done if I had not discovered such a thing like this. I can at this time look forward to my future. Thanks very much for your specialized and amazing help. I will not be reluctant to recommend your site to any person who would like tips about this matter.

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!

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.