IoT Controlled LED using Node.js Web server and Raspberry Pi

IoT Controlled Led using Node.js Web server and Raspberry Pi

Earlier we have controlled Raspberry Pi with different languages like Python, and Embedded C. In this tutorial we are using Node.js for controlling a LED using Raspberry Pi. Node.js is a very popular JavaScript-based environment, originally developed for the Google Chrome browser but now it is open source. This language runs on various platforms like Windows, Linux, Unix, Mac OS X, etc.

In this project, we are going to control a led using Pi and Node.js Webpage. For this, we will create an HTML page that has two buttons, one for turning led on and second for turning led off and a JavaScript file. Using this HTML page we can control led using any web browser.

 

Components Required

  • Raspberry Pi 
  • LED
  • Breadboard
  • 250-ohm resistor
  • Jumper Wires

 

Circuit Diagram

Circuit Diagram for Controlling LED using Node.js Web server and Raspberry Pi

 

Node.js Webserver Setup with Raspberry Pi

Start with installing Node.js on your Raspberry Pi using the below command, if you have not installed yet.

sudo apt-get update
sudo apt-get install nodejs
sudo apt-get install build-essential

 

After installing Node.js successfully, now create a new directory and enter into the directory using the below command

mkdir ledwebserver
cd ledwebserver

 

Now open a new file for your JavaScript code

Sudo nano led.js

 

Copy and paste the below given code inside this file

var express = require('express'); 
var app = express();
var path = require('path');
var gpio = require('rpi-gpio');
gpio.setup(12, gpio.DIR_OUT);
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
console.log(path.join(__dirname, 'public'));
app.get('/', function(req, res){ 
            res.render('index',{status:"Press Button To change Status of Led !!"});
});
app.post('/led/on', function(req, res){
gpio.write(12, true, function(err) {
        if (err) throw err;
        console.log('Written True to pin');
            console.log(path.join(__dirname, 'public'));
            return res.render('index', {status: "Led is On"});
    });
});
app.post('/led/off', function(req, res){
gpio.write(12, false, function(err) {
        if (err) throw err;
        console.log('Written False to pin');
            console.log(path.join(__dirname, 'public'));
            return res.render('index',{status: "Led is Off"});
    });
});
app.listen(3000, function () {
  console.log('Simple LED Control Server Started on Port: 3000!')
})

 

Now make another folder inside the ledwebserver directory and go inside the folder:

mkdir page 
cd page

 

Now, open a new file in this folder, to create an HTML page:

Sudo nano webpage.ejs

 

Then, paste the following HTML code inside this file:

<meta name="viewport" content="width=500, initial-scale=1"> <!--This line of code is for mobile responsive -->
<div class="BorderMargin">
<h1>Welcome to Nodejs Server</h1>

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

  </form>
  <a>Led Status: <%=status %></a>
</div>
<!-- The below code is only for look and styling -->
<style>
.button {
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}

.button2 {background-color: #008CBA;} /* Blue */
.button3 {background-color: #f44336;} /* Red */ 
.button4 {background-color: #e7e7e7; color: black;} /* Gray */ 
.button5 {background-color: #555555;} /* Black */
.BorderMargin {

   margin: 10px;
   padding: 10px;
   max-width: 300px;
   height: 300px;
   border: 1px solid black;
}   
</style>

 

Explaining HTML Code

The complete code for controlling LED using node.js and Pi is given above. Below commands are used to create a box and a heading for the webpage.

<meta name="viewport" content="width=500, initial-scale=1"> <!--This line of code is for mobile responsive -->
<div class="BorderMargin">
<h1>Node.js Controlled Led</h1>

 

These commands are used to form two buttons to turning on and off led.

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

 

These commands are used to change the buttons color and dimension.

<!-- The below code is only for look and styling -->
<style>
.button {
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}
.button2 {background-color: #008CBA;} /* Blue */
.button3 {background-color: #f44336;} /* Red */ 
.button4 {background-color: #e7e7e7; color: black;} /* Gray */ 
.button5 {background-color: #555555;} /* Black */
.BorderMargin {

   margin: 10px;
   padding: 10px;
   max-width: 300px;
   height: 300px;
   border: 1px solid black;
}   
</style>

 

Installing Packages for Node.js in Pi

Now go to the ledwebserver directory and install packages for Node.js using the following command:

npm install

 

If this command shows an error then try installing the packages using their names:

npm install ‘package name’

 

For example npm install expression, npm install rpi-gpio etc.

 

Now after installing all the packages, run the JavaScript code:

sudo node led.js

 

If it gets connected to the server successfully then your pi terminal should look like this:

Successfully Connected Pi with Node.js Server

 

Now, navigate to your browser and search for the web page using 192.168.1.31:3000. Where 192.168.1.31 is Pi’s IP address that you should replace with your Pi’s IP address and 3000 is port number.

Controlling LED via-Node.js Webserver

 

Hence, we have successfully controlled the LED using Node.js and Raspberry Pi. Also, check out our Other IoT projects using Raspberry Pi:

 

 

Code

var express = require('express');

var app = express();

var path = require('path');

var gpio = require('rpi-gpio');

gpio.setup(12, gpio.DIR_OUT);

app.set('view engine', 'ejs');

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

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

app.get('/', function(req, res){

            res.render('index',{status:"Press Button To change Status of Led !!"});

});

app.post('/led/on', function(req, res){

gpio.write(12, true, function(err) {

        if (err) throw err;

        console.log('Written True to pin');

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

            return res.render('index', {status: "Led is On"});

    });

});

app.post('/led/off', function(req, res){

gpio.write(12, false, function(err) {

        if (err) throw err;

        console.log('Written False to pin');

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

            return res.render('index',{status: "Led is Off"});

    });

});

app.listen(3000, function () {

  console.log('Simple LED Control Server Started on Port: 3000!')

})

1 Comments

Hello I am new in this.

I am having some problems with this project.

When I try to open the port:3000, it gaves me the next error:

Error: Failed to lookup view "index" in views directory "/home/pi/ledwebserver/views"    at Function.render (/home/pi/ledwebserver/node_modules/express/lib/application.js:580:17)    at ServerResponse.render (/home/pi/ledwebserver/node_modules/express/lib/response.js:1012:7)    at /home/pi/ledwebserver/led.js:10:17    at Layer.handle [as handle_request] (/home/pi/ledwebserver/node_modules/express/lib/router/layer.js:95:5)    at next (/home/pi/ledwebserver/node_modules/express/lib/router/route.js:137:13)    at Route.dispatch (/home/pi/ledwebserver/node_modules/express/lib/router/route.js:112:3)    at Layer.handle [as handle_request] (/home/pi/ledwebserver/node_modules/express/lib/router/layer.js:95:5)    at /home/pi/ledwebserver/node_modules/express/lib/router/index.js:281:22    at Function.process_params (/home/pi/ledwebserver/node_modules/express/lib/router/index.js:335:12)    at next (/home/pi/ledwebserver/node_modules/express/lib/router/index.js:275:10)

 

Someone could help me?

Thanks.