Communication between Arduino and Node.js using the serial port

Zápisník experimentátora

Hierarchy: Node.js

In a few articles, we introduced the introduction to Node.js and today we look at the first interesting topic. We will be using the serial port to communicate with Arduino. You can not use the serial port on your local computer in javascript in your browser. This deficiency in Node.js is not, and therefore you can fully use the serial port to communicate. This article explains two examples. First we get a list of serial ports and in the second one we will read the rows that Arduino will send us.

This article uses the package serialport v. 4.0.7 for Node.js. This package is outdated. In newer packages, the use of a parser is changed. Example for v. 6.0.0 you can see in the updated version of the article.

Code for Arduino

The code for Arduino is focused on simplicity. That is why it does the only one thing. Every 1000 milliseconds will send​ value from function millis() to the serial port. For us, he does an important job. First, we have Arduino on the serial port and we have a periodic data source that we can read.

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println(millis());
  delay(1000);
}

Code for Node.js

If you have never run the Node.js program before, you should learn how to use the command line console and the npm program that is used to install related libraries. You will find an example of use at the end of this article.

List of connected serial ports (list.js)

A serialport library is used. The function list needs a two-parameter function as a parameter callback. The port parameters will contain a list of all com ports, and because it is an array of port information objects, they can easily iterate with forEach and in this case list on the console. Run the program in the command line console by using the command node list.js.

'use strict';

var serialport = require('serialport');

serialport.list(function (err, ports) {
  ports.forEach(function(port) {
    console.log(port.comName);
    console.log(' - pnpId: ' + port.pnpId);
    console.log(' - manufacturer: ' + port.manufacturer);
    console.log(' - serialNumber: ' + port.serialNumber);
    console.log(' - vendorId: ' + port.vendorId);
    console.log(' - productId: ' + port.productId);
  });
});

Read from the serial port via Node.js (index.js)

The serialport library and the readline library are used. The program works as follows. It first lists the connected serial ports and you must select the one on which your Arduino is. If it is possible to connect to the selected serial port, the program will connect it to the 9600 and set up the line readings, which corresponds to how you know from the serial port monitor for Arduino.

The error and open events are attached, and if the program gets into the open event handler, the event will be attached to the data event and each row will begin to appear on the console. Run the program in the command line console by using node index.js command. You can stop the program by pressing the Ctrl-C shortcut key.

'use strict';

var serialport = require('serialport');
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'select port> '
});

var idx = 0;
var ports = [];

console.log('COM port list:');
serialport.list(function (err, p) {
  p.forEach(function(p) {
    ports.push(p.comName);
    console.log(' [' + idx + '] ' + p.comName);
    idx++;
  });

  rl.prompt();
 
  rl.on('line', (line) => {
    //console.log(line);
    //console.log(ports);
    if(line<idx) {
      console.log('Opening ' + ports[Number(line)]);
     
      var port = new serialport(ports[Number(line)], {
        baudRate: 9600,
        parser: serialport.parsers.readline('\n')
        });
       
      port.on('error', function(e) {
        console.error(e.message);
        process.exit(0);
      }); 
       
      port.on('open', function() {
        console.log('Serial Port Opened');
        port.on('data', function(data){
          console.log(data);
        });
      });
 
    } else {
      console.error('ERROR: Wrong port number');
      process.exit(0);
    }
  });
 
  rl.on('close', () => {
  console.log('Bye!');
  process.exit(0);
});
 
});

Source code

All source codes are located on the​ GitHub server.

If you have git installed, you can install the source code as follows. If you do not have it, you can also download zip archives. Run the command line console. Important is the last line that installs all the related libraries that are in package.json.

cd d:
mkdir arduino
cd arduino
git clone https://github.com/roboulbricht/arduinoslovakia
cd arduinoslovakia\node.js\arduinoserialtest\node
npm install

14.10.2017


Menu