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.

3194 Comments

Its like you learn my mind! You appear to know so much about this, like
you wrote the ebook in it or something. I think that you just could
do with a few p.c. to force the message home a bit, but instead of that, this is magnificent blog.
An excellent read. I will definitely be back.

Heya! I just wanted to ask if you ever have any problems with
hackers? My last blog (wordpress) was hacked and I ended up
losing months of hard work due to no back up. Do you have any
solutions to protect against hackers?

I loved as much as you'll receive carried out right here.
The sketch is tasteful, your authored subject matter stylish.
nonetheless, you command get bought an edginess over that you wish be delivering the following.

unwell unquestionably come more formerly again as exactly the same nearly a lot often inside case you
shield this increase.

hi!,I really like your writing very so much!
share we be in contact extra approximately your
article on AOL? I need an expert in this house
to unravel my problem. Maybe that's you! Taking a look forward to see you.

Hi there! I know this is kinda off topic but I was wondering which
blog platform are you using for this website? I'm getting tired of Wordpress because I've
had problems with hackers and I'm looking at alternatives for another platform.

I would be great if you could point me in the direction of a good platform.

Good post. I learn something totally new and challenging on websites I stumbleupon every
day. It will always be interesting to read through content
from other writers and practice a little something from other sites.

Good day! I know this is somewhat off topic but I was
wondering if you knew where I could find a captcha plugin for my comment form?

I'm using the same blog platform as yours and I'm having problems finding
one? Thanks a lot!

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

Thank you, I've just been searching for info approximately this subject for a
while and yours is the greatest I have found out till now.
But, what concerning the bottom line? Are you certain concerning the source?

Heya just wanted to give you a quick heads up and let you know a few of
the images aren't loading correctly. I'm not sure
why but I think its a linking issue. I've tried it in two
different internet browsers and both show the same
outcome.

This design is steller! You obviously know how to keep a reader entertained.

Between your wit and your videos, I was almost
moved to start my own blog (well, almost...HaHa!) Great job.
I really enjoyed what you had to say, and more than that, how
you presented it. Too cool!

certainly like your website but you have to check the spelling on quite a few of your
posts. A number of them are rife with spelling issues
and I in finding it very troublesome to
inform the truth then again I'll definitely come back again.

Can I simply say what a comfort to find an individual who genuinely understands what
they are discussing on the web. You actually understand how to bring a problem to light and make it important.
A lot more people need to check this out and understand this
side of the story. I can't believe you aren't more popular since you definitely possess the gift.

Have you ever considered writing an e-book or guest authoring on other sites?
I have a blog based on the same ideas you discuss and would
really like to have you share some stories/information. I know my audience would appreciate your
work. If you're even remotely interested, feel free to send me an e-mail.

Fantastic goods from you, man. I've understand your stuff previous to and you are just too great.
I actually like what you've acquired here, really like what you are saying
and the way in which you say it. You make it entertaining and you still take care of to keep it smart.
I cant wait to read much more from you. This is really a wonderful website.

Hi there, i read your blog from time to time and i own a
similar one and i was just curious if you get a lot of spam responses?
If so how do you reduce it, any plugin or anything you can advise?
I get so much lately it's driving me crazy so any help
is very much appreciated.

I would like to thank you for the efforts you have put in writing this site.
I'm hoping to see the same high-grade blog posts from you
later on as well. In fact, your creative writing abilities has motivated me to get my very own website now ;
)

Do you have a spam problem on this website; I also am a
blogger, and I was wanting to know your situation; we have created some
nice methods and we are looking to swap solutions with others, please shoot
me an email if interested.

Howdy! This post couldn't be written any better! Reading this post reminds me of my old room mate!
He always kept talking about this. I will forward this page to him.
Pretty sure he will have a good read. Thank you for sharing!

I do not even know how I finished up here, however I thought this put up was
good. I don't recognise who you are however certainly you're
going to a well-known blogger when you aren't already.
Cheers!

I know this if off topic but I'm looking into starting my own weblog and was curious what all is required to get set up?
I'm assuming having a blog like yours would cost a pretty penny?
I'm not very web savvy so I'm not 100% certain. Any recommendations or advice would be greatly appreciated.
Thanks

Do you mind if I quote a few of your posts as long as I provide
credit and sources back to your site? My website is in the exact
same area of interest as yours and my visitors would really benefit from a lot of the information you present here.
Please let me know if this ok with you. Many thanks!

I loved as much as you will receive carried out right here.
The sketch is tasteful, your authored material stylish.
nonetheless, you command get got an shakiness over that you wish be delivering the following.
unwell unquestionably come further formerly again since exactly the same nearly a lot often inside case you shield
this hike.

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.