LED control using Web Technologies(HTML, Node.js, Express.js)

Today Let's take the first step to rule the web world with things....

LED, the first thing ever in the world of IoT and controlling it is the "hello-world" in the world of electronics...

In this blog, what you can learn ? 
1.Connecting things(LED) to the web
2.Controlling things(LED) from the web
3.Use of Node js and Express js in ruling the web world.
4.Understanding some basic HTTP methods and how they can be used with things 

Assumption
Here I have assumed that you have installed node js,npm and express js and git in your raspberry pi. If you need more information on installation of node js and npm, pls follow this link http://www.instructables.com/id/Install-Nodejs-and-Npm-on-Raspberry-Pi/

To install express just type npm install -g express to install express globally
To install git type sudo apt-get install git

Requirements
1. An LED and 1K ohm resistor
2. Raspberry Pi 2,3
3.Bread board and Connecting wires

Github Repository:

https://github.com/apvenkat/led_control_web

Required Node modules:
express
path                                          //you can check the package.json file for the used modules
rpi-gpio

Connection diagram

Connect the led to the raspberry pi as per the connection diagram, you can use any of the gpio as per your choice, Here I have connected my led to GPIO 4(Pin 7).

Now let's make our hands a bit dirty by doing some interesting stuffs...!!

Before actuating our led let's learn some basics about HTTP methods and express js 

Web and the Things
In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what action is needed based on the URL pattern and possibly associated information contained in POST data or GET data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.

Mostly used http methods are GET,POST,PUT,DELETE 
GET - to retreive data
POST - to submit an entity to a resource( here resource is our LED)
PUT - update the resource
DELETE - delete a resource

In our case, we are going to use HTTP POST method to submit an entity(ON/OFF)to actuate an LED  from a html web page. once you make a post request the server will respond with the action making led on and off. 

A small glimpse about express js
Express provides methods to specify what function is called for a particular HTTP verb (GETPOSTSET, etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response.Here we don't use any templates like ejs,jade, since it is for beginners we will use html directly. But using ejs,jade like engines will easily render html for us and reduce the coding.

In our case   
Method : POST
URL : http://ip address of your raspberry pi/
View engine : html              

Now lets get into action...clone the git repository into your raspberry pi using the following command and change to the directory 

sudo git clone https://github.com/apvenkat/led_control_web      // clone the git repository in your pi

cd led_control_web/                                                                   

Inside the folder you can see the folders node_modules,images,views,index.js file and package.json file
node_modules       // have all the modules and mainly we need rpi-gpio, path, express for our case.
views                     // html file will be inside this view
images                   // all your required images
index.js                  // Node js file having server and route functions

Now let's see how this index.js file works, below is the code of index.js

var express = require('express');           ///Requires the Express framework and necessary modules
var app = express();                             ///Creates an application with the Express framework;
var path = require('path');
var gpio = require('rpi-gpio');

gpio.setup(7, gpio.DIR_OUT);        // pin number 7( GPIO 4)




app.use(express.static(path.join(__dirname, 'public')));

console.log(path.join(__dirname, 'public'));

app.get('/', function(req, res){                          //simple GET request
 res.sendFile(path.join(__dirname + '/views/index.html'));
});

app.post('/led/on', function(req, res){                                            //Make POST request to ON
gpio.write(7, true, function(err) {                                                  //writes true to gpio pin 
        if (err) throw err;
        console.log('Written True to pin');
console.log(path.join(__dirname, 'public'));
return res.sendFile(path.join(__dirname + '/views/index.html')); //respond with index.html
    });

});


app.post('/led/off', function(req, res){                                             // Make POST request to OFF
gpio.write(7, false, function(err) {                                                  //write false to gpio pin       
        if (err) throw err;                                                                              
        console.log('Written False to pin');
console.log(path.join(__dirname, 'public'));
return res.sendFile(path.join(__dirname + '/views/index.html'));          //respond with index.html
    });

});


app.listen(3000, function () {
  console.log('Simple LED Control Server Started on Port: 3000!')  //app running on default port 3000
})

to know more about rpi-gpio module and how to use it, kindly see below

Now let's come to our /views/index.html code

<html>
<body>
<meta name="viewport" content="width=500, initial-scale=1"> <!--This line of code is for mobile responsive -->
<div class="BorderMargin">
  <image src = '/images/LED.png' alt="LED" style="width:180px;height:180px;">

  <form action="/led/on" method="post">
    <button type="submit" onclick="alerton()" class="button">LED On </button>
      <button type="submit" onclick="alertoff()" formmethod="post" formaction="/led/off" class="button button3">LED Off</button>

  </form>

</div>
<script>
function alerton() {
alert("Led is ON now");                              //make an alert on the status
}
function alertoff() {
 alert("Led is OFF now");
}
</script>
</body>
</html>

Now just execute sudo node index.js from your project main folder, the server will start running on port 3000 as specified on the index.js file, you can change the port number if you need. 


Now open your browser and type 
http://192.168.x.x:3000                  // ip of your raspberry pi

you can see the simple html page which we have coded and you can send post requests to the server resource(LED) by clicking ON and OFF and see the response on your browser and your raspberry pi console......!!


In my next blog, I will explain you the use of web technologies in controlling a real world IoT thing(A Smart Bulb) . Keep reading my blogs for cool stuffs and don't forget to give your valuable comments and feedback !!!

    







Comments

Post a Comment