Communication between Arduino and Node.js using the serial port v. 2

Zápisník experimentátora

Hierarchy: Node.js

This article describes an updated version of the serialport package in version 6. 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 communication port. 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 to us. The examples will be slightly different from the examples we used in the previous article.

Source code for Arduino

The code for Arduino is focused on simplicity. That is why it does the only one thing. Every 1000 milliseconds it will send​ value from function millis() to the serial port. It is important for us. 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);
}

Source code for Node.js

If you have never been running the Node.js program before, you should learn how to use the command line console and control 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 parameter will contains a list of all com ports, and because it is an array of port information objects, they can be easily iterated with function forEach and in this case listed 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);
  });
});

Reading 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.

The difference with version 4.0.7 is that the parser is set differently. In version 6.0.0, you must first select the type of parser using the command const sp_readline = serialport.parsers.Readline;. And then with pair of commands const const = new sp_readline (); and port.pipe (parser); connect it to the serial port object.

'use strict';

const serialport = require('serialport');
const readline = require('readline');
const sp_readline = serialport.parsers.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', function(line) {
    //console.log(line);
    //console.log(ports);
    if(line<idx) {
      console.log('Opening ' + ports[Number(line)]);
     
      const port = new serialport(ports[Number(line)], {
        baudRate: 9600
        });
      const parser = new sp_readline();
      port.pipe(parser); 

      parser.on('data', function(data){
        console.log(data);
      });
       
      port.on('error', function(e) {
        console.error(e.message);
        process.exit(0);
      }); 
       
      port.on('open', function() {
        console.log('Serial Port Opened');
      });

      port.on('close', function(err) {
        console.log('Serial Port Closed: ' + err);
        process.exit(0);
      });
 
    } else {
      console.error('ERROR: Wrong port number');
      process.exit(0);
    }
  });
 
  rl.on('close', function() {
  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\arduinoserialtest2\node
npm install

15.10.2017


Menu