In this tutorial, we will describe a small project in NodeJS viz Serial Terminal using nodeJS. I am assuming that you have basic knowledge of nodeJS. This project can be done with some simple procedure. This is also useful for communicating with the Arduino or any other microcontroller using serial.

Requirements

  1. NodeJS should be installed in your system.
  2. serialport node module.
  3. commander node module.
  4. readline node module.

Environment Setting

You can set up the environment by using these simple command. Run these command sequentially(for Mac and Linux user only) and follow the instruction for each command. After completing, you can see a package.json file inside your workspace directory.

So now the question is Why package.json?

Package.json includes the dependencies required for the project with the version number. it makes it easy to install dependencies when require using “npm install”

$ mkdir <your-directroy-name>
$ cd <your-directory-name>
$ npm init
$ npm install serialport --save
$ npm install commander --save
$ npm install readline --save4
$ touch yourfilename.js

For windows user, create a directory and open command prompt inside that directory and start from “npm init“. Touch command won’t work in windows so open your favorite text editor and save it as “yourfilename.js”.

Code

So Below you can see all the code. First, let’s have a look at this code.

var SerialPort = require('serialport');
var program = require('commander');
const readline = require('readline');

version = "0.0.1"

program
    .version(version)
    .usage('[options] command {args...}')
    .option('-p, --port [port path]', 'path address')
    .option('-b, --baud [siteid]', 'baud rate')
    .option('-r, --read [siteid]', 'flag for read serial')
    .option('-w, --write [siteid]', 'flag for write serial')
    .option('-m, --message [siteid]', 'message')
    .parse(process.argv);

if(!program.port) {
	console.log('[ERR] Port not defined\nExample: node index.js -p /dev/ttyUSB0 -b 115200 -r')
	program.outputHelp();
	process.exit()
}

if(!program.baud) {
	console.log('[ERR] baud not defined\nExample: node index.js -p /dev/ttyUSB0 -b 115200 -r')
	program.outputHelp();
	process.exit()
}

var PORT = program.port
var BAUDRATE = parseInt(program.baud)
var port = new SerialPort(PORT, {baudRate: BAUDRATE});
console.log(PORT +" port is open with baudRate "+ BAUDRATE)


if(program.read){
	//console.log("Receving........")
	port.on('data', function (data) {
	  console.log(data.toString());
	});	
}

if(program.write) {
	const rl = readline.createInterface({
	  input: process.stdin,
	  output: process.stdout,
	  prompt: 'Serial> '
	});
	rl.prompt();
	rl.on('line', (line) => {
		port.write(line, function(err, resp) {
			console.log("data write")
			rl.prompt();
		})
	});
	
}

port.on ('error', function(error) {
  console.log('error: %s', error);
});

port.on('close', function() {
  console.log('port closed');
})

The program is divided into three parts-

  • Module definition – in the first three lines we defined all the required module for this project.
  • Define Variables – After defining modules, next, we define variables in which first we have defined the option parser used to parse port number, baud rate, read and write modes.
  • Programming condition – Logic and conditions of the code.

So as described in points, we required 3 modules for this project. In these modules,

  • serial port – This module is used to initialize a serial port and start a connection with that serial port.
  • commander – This module is used to provide option parser in argument to provide the serial port, baud rate, etc. required for the program.
  • readline – This module is used to get input in nodeJS program.

Moving forward to program, We will find two condition there program.read and program.write which will check the read or write or both flag is active or not and then it will start the program accordingly.

Execution of the Program

Now you can run the program. Before running the program with the serial device first you should check its help. Here index.js is my program name 

bhosin01@a040563-lin:~/workspace/nodeSerialComm$ node index.js -h
Usage: index [options] command {args...}

Options:
  -V, --version           output the version number
  -p, --port [port path]  path address
  -b, --baud [siteid]     baud rate
  -r, --read [siteid]     flag for read serial
  -w, --write [siteid]    flag for write serial
  -m, --message [siteid]  message
  -h, --help              output usage information

So from above help now you can Open you serial terminal by three ways. you can use anyone as per your requirement.

  1. <node index.js -p /dev/ttyUSB0 -b 115200 -r> – only in read mode
  2. <node index.js -p /dev/ttyUSB0 -b 115200 -w> – only in write mode
  3. <node index.js -p /dev/ttyUSB0 -b 115200 -r -w> -only in read and write mode

Here, /dev/ttyUSB0 is a serial port and 115200 is baud rate for the communication.

Conclusion

Wow! so we are now done with that. If you have any question feel free to comment here. You can also a look on my GitHub project here

 

Share This