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://


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 (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.

<meta name="viewport" content="width=device-width" />
<title>Raspberry Pi WiFi Controlled LED</title>
       <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">
    shell_exec("/usr/local/bin/gpio -g mode 27 out");
                        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");

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.

    shell_exec("/usr/local/bin/gpio -g mode 27 out");
                        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.


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.

Undeniably consider that that you stated. Your favorite reason appeared
to be at the net the easiest factor to take into accout
of. I say to you, I definitely get annoyed even as people consider issues that they
just do not realize about. You managed to hit the nail upon the top as well as defined out the whole thing without having side-effects , other folks could take a signal.
Will probably be back to get more. Thanks

Hey there just wanted to give you a quick heads up.
The words in your post seem to be running off the screen in Chrome.
I'm not sure if this is a format issue or something to
do with browser compatibility but I thought I'd post to
let you know. The design look great though! Hope you get the problem fixed soon. Thanks

I don't even understand how I stopped up here, but I believed this submit was good.
I don't understand who you are but definitely you are going to a famous blogger in case you aren't already.

I know this if off topic but I'm looking into
starting my own weblog and was curious what all is required to get setup?
I'm assuming having a blog like yours would cost a pretty penny?

I'm not very internet savvy so I'm not 100% sure. Any tips or advice would be
greatly appreciated. Thanks

Magnificent items from you, man. I have remember your stuff previous to and you're simply too magnificent.
I really like what you have acquired here, certainly like what you're stating and the best way by which you say it.
You are making it entertaining and you still care for to stay it wise.
I can't wait to learn much more from you. This is actually
a tremendous website.

Having read this I believed it was really enlightening. I appreciate you taking
the time and energy to put this informative article together.
I once again find myself personally spending a lot of time both reading and posting comments.
But so what, it was still worth it!

Nice post. I used to be checking constantly this blog and I'm impressed!
Very helpful information particularly the last phase :) I care for such info a lot.
I used to be looking for this particular information for a
long time. Thank you and best of luck.

We are a group of volunteers and opening a
new scheme in our community. Your site provided us with valuable information to work on. You have done
an impressive job and our whole community will be grateful to you.

Thanks for ones marvelous posting! I seriously enjoyed reading it, you can be a great author.I will ensure that I bookmark your blog
and will come back later on. I want to encourage that you continue your great job,
have a nice holiday weekend!

I'm not sure why but this weblog is loading incredibly slow for me.

Is anyone else having this problem or is it a problem on my end?

I'll check back later and see if the problem still exists.

I think this is one of the such a lot vital information for me.

And i'm glad reading your article. But wanna statement on few basic
things, The website taste is great, the articles is in point of fact excellent : D.

Excellent process, cheers

This is the right blog for anybody who wants to find out about this
topic. You realize so much its almost tough to argue with you (not that I
personally will need to…HaHa). You certainly put
a new spin on a topic that's been written about for
decades. Wonderful stuff, just excellent!

Fantastic website you have here but I was curious
if you knew of any community forums that cover the
same topics discussed in this article? I'd really love to be a part of group where I
can get comments from other knowledgeable individuals that share the same interest.
If you have any recommendations, please let me know. Thanks a lot!

Having read this I thought it was rather informative.

I appreciate you spending some time and effort to put
this information together. I once again find myself
spending a significant amount of time both reading and leaving comments.
But so what, it was still worth it!

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.