Node.js is the most popular server at this time. Due to its asynchronous and non-blocking nature, Node is the obvious choice for real-time web applications like chat rooms, single-page applications, video streaming, etc. For the same reasons, Node is attracting IoT engineers. As web applications developed on Node operate in real-time, these are best suitable for implementing time-critical web-controlled embedded operations. Plus, with express.js added to Node, you can program both the back end and front end of the network application in the same language, i.e., JavaScript.
A popular framework called “Johny-five” is used to control microcontrollers from backend JavaScript. “Johny-five” is JavaScript Robotics & IoT Platform created by Rick Waldron in 2012. It is maintained by a community of passionate software developers and hardware engineers, with over 75 developers contributing to the framework. The framework can be used to control a variety of Arduino-compatible microcontrollers and SoC platforms, including Arduino, Raspberry Pi, Tessel 2, Particle Photon, Intel Edison, etc. For non-Arduino boards, platform-specific IO plugins are available. The IO plugin can make “johny-five” communicate with any hardware platform.
In this project, we will first set up a Node server and implement a backend JavaScript code to control Arduino directly. A “johny-five” backend JavaScript can be run on a Node server to directly control Arduino and Arduino-compatible, boards. This is demonstrated by blinking an LED on Arduino UNO by running JavaScript on a Node server.
Next, we expand the Node server with the help of Express.js and Socket.io to host a webpage and use the JavaScript SerialPort library to communicate data directly from a webpage to the Arduino. The Arduino will be programmed to read serial data directly from the webpage and fade an LED according to the received data stream.
Components required
- Arduino UNO x1
- LED x1
- Resistor 470Ω x1
- Breadboard x1
- Jumper wires x1
- USB cable to connect Arduino with computer x1
Setting up the Node server
First of all, we need to install Node.js on a computer. You can download Node.js for Microsoft Windows and mac OS from this link. Simply download and run the setup for Node.js on your computer. After installation is finished, you can check the current version of Node.js installed by executing the following command in the command prompt in the case of Windows or Terminal in the case of Linux/macOS.
node -v
Next, create a folder and name it “Arduino Control”. In the same folder, open the command prompt/Terminal and install the johny-five library by executing the following command.
npm install johny-five
After installing the johny-five library in the given folder, the folder will have files and folders, as shown in the image below.
This folder is now a Node.js project. Next, install express.js in the Node project by executing the following command in the command prompt/Terminal in the same folder.
npm install express
Next, install socket.io in the Node project by executing the following command in the command prompt/Terminal in the same folder.
npm install socket.io
Next, install the JavaScript serialport library in the Node project by executing the following command in the command prompt/Terminal in the same folder.
npm install serialport
Now, our Node.js server is ready with johny-five, express, socket.io, and serialport packages installed in the Node project. All these modules are stored in the folder “node_modules”.
Preparing Arduino for communicating with the host computer
To make Arduino communicate with a host computer, we need to implement an intermediate protocol between Arduino and the host computer. Such a protocol is called the Firmata protocol. Fortunately, a Firmata library is available that implements the Firmata protocol on Arduino.
For this project, we simply need to upload a standard Firmata sketch to Arduino, so Arduino is receptive to what we send from our computer. Open Arduino IDE, navigate to File-> Examples->Firmata-> StandardFirmata. Compile and upload the example sketch to Arduino.
Now, Arduino is ready to receive commands from the host computer and dance on the JavaScript code we will run from the Node server.
Blinking LED on Arduino using “johny-five”
We can literary do anything on the Arduino board using JavaScript “johny-five” library. After uploading Firmata to Arduino, we have full control of Arduino from the host computer. Let us exercise this control by blinking a LED on Arduino through JavaScript coding. Interface a LED to any GPIO of Arduino. The following circuit diagram shows a LED interfaced to pin 3 of Arduino.
Now, create a file with the name “blink.js” in the folder “Arduino Control” and open it in any code editor of your choice, like Visual Studio Code, Atom, NotePad++, etc. Copy and paste the following code into the editor and save the file.
const {Board, Led} = require(“johnny-five”);
const board = new Board();
board.on(“ready”, () => {
const led = new Led(5);
led.blink(500);
});
To execute the project, open the command prompt/Terminal in the same folder and execute the following command to run the “blink.js” on the Node server.
Node blink.js
As the Javascript file “blink.js” executes, the LED connected to Arduino will start blinking, as shown in the following video.
[Link to demonstration video P34-DV01]
Creating a websocket server on Node
We have already seen how to control Arduino from JavaScript code running on a Node server. Now, let us create a web server that hosts a webpage and allows sending data from the webpage to Arduino. In this project, we will use the webpage to fade a LED on Arduino.
To build a web server, create a file named “fade.js” in the folder “Arduino Control”. Copy and paste the following code in fade.js.const express = require(‘express’);
const app = express();
const http = require(‘http’);
const server = http.createServer(app);
app.get(‘/’, (req, res) => {
res.sendFile(__dirname + ‘/public/index.html’);
})
server.listen(8080, () => {
console.log(‘listening on *:8080’);
});
console.log(“Web Server Started go to ‘http://localhost:8080’ in your Browser.”);
This is a simple web server on Node.js built using express.js. The server simply fetches index.html from the “/public/” folder and publishes the webpage as a response when port 8080 is opened on localhost.
The JavaScript code for the express web server starts by importing express.js. A new application is instantiated using the express module. The HTTP module is imported to handle HTTP requests. A server object is instantiated by calling http.createServer() method on the express object “app”. To send index.html from the “public” folder as http response, the app.get() method is called. The IP address and port are set to localhost and port 8080 for the Node server to listen from by calling the server.listen() method. The callback also prints a message to the console. Finally, it is notified that the server is running on localhost:8080 by printing another message to the console. These messages will be printed in the command prompt/Terminal from where the server application will be run.
Create a folder “public” within the folder “Arduino Control” and create a file with the name “index.html”. The index.html contains a slider to control the brightness of the LED. It uses socket.io to send or emit (in socket.io terminology) slider values from the browser to the Node server. Open index.html in a code editor of your choice and paste the following HTML code.
Save and close index.html. Note how the socket.io object is instantiated using the connect.io() method, and a listener function “led” is defined using the socket.on the () method to communicate slider value from the browser to the Node server.
The HTML page can be better presented by adding some CSS. Open style.css in any code editor of your choice and paste the following stylesheet code. In the same “public” folder containing “index.html”, create a file with the name “style.css”.
Save and close style.css. Now the webpage looks like the following.
Preparing Arduino to receive serial data
We are not directly fading LED from JavaScript running on the Node server. Instead, the Node server hosts a webpage at localhost:8080. The webpage takes input from the user and communicates the input data from the browser to the Node server. Then Node server wraps received data into a buffer object and communicate to the serial port Arduino is connected to on the host computer. So, Arduino must be programmed to read serial data from the host computer and fade LED by generating a PWM signal at the respective pin. Instead of Firmata, now upload the following sketch to Arduino.
void setup()
{
Serial.begin(9600);
pinMode(3, OUTPUT);
}
void loop()
{
while(!Serial.available());
analogWrite(3, Serial.read());
}
The LED is connected to pin 3 of Arduino, as shown in the circuit diagram above. The GPIO3 is also a PWM pin, so it can fade LED using the analogWrite() method.
Fading LED on Arduino from Node.js server
For fading LED on Arduino, we need to send data from the serial port of the host computer to Arduino. For this, JavaScript serialport library is used. The library is already installed in the node project during the setup of the Node server.
Now, add the following lines to “fade.js” to instantiate a serial port in the backend script.
const { SerialPort } = require(‘serialport’);
const port = new SerialPort({
path: ‘COM4’,
baudRate: 9600,
});
In our case, Arduino is connected to a Windows PC’s serial port, “COM4”. The port can be different in your case. Replace the port name after the path variable according to your system, whether it be Linux or macOS or a different communication port on Windows PC. In Microsoft Windows, you can find the port Arduino is connected to by opening “Device Manager” and navigating to “Ports”. Expand the port showing Arduino.
In macOS and Linux, to know which port Arduino is connected to, open Terminal and execute the following command.
ls /dev/tty*
Look for /dev/tty.usbmodem* or /dev/tty.usbserial* in the case of macOS or /dev/ttyUSB* or /dev/ttyACM* in the case of Linux.
Create a global variable “brightness” to store LED brightness. Finally, use socket.io to communicate slider value from the Node server to the serial port of the host computer. Add the following JavaScript code to fade.js to instantiate a socket.io object.
Note how the same backend script is hosting a webpage on localhost, receiving input from the webpage on a browser, transferring the data to the server, and communicating the data from the server to the serial port of the host computer.
To execute the project, open the command prompt/Terminal in the same folder, “Arduino Control” and execute the following command to run the “fade.js” on the Node server.
Node fade.js
As the Javascript file “fade.js” will execute, open the URL “localhost:8080” in a web browser and move the slider to control the brightness of the LED connected to Arduino. The project execution is demonstrated in the following video.
You can download the complete project files from the following link.
Arduino-Control.ZIP
You may also like:
Filed Under: Arduino., Electronic Projects
Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.
Tell Us What You Think!!
You must be logged in to post a comment.