Node.js and several Arduinos using the serial port

Zápisník experimentátora

Hierarchy: Node.js

In today's article we will connect several Arduinos to the computer using the Node.js serialport package. We will edit the previous example in which we have only one Arduino. In this example, you can choose more COM ports.

Code for Arduino

The code for Arduino is focused on simplicity. That's why it does the only thing. Every 1000 milliseconds send the value of millis() to the serial port. It is important for us. We have Arduino connected to a 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

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. You can choose more ports at a time. Write them in 1, 2, 3 format. If it is possible to connect to the selected serial port, the program will connects it to the 9600 speed and set up the line readings. The resulting listing will resemble what you know from the serial port monitor for Arduino.

Several source code lines need to be explained. Each serial port is written as a list of serial numbers, separated by commas. We transform them into a array with function split, and by using the map and trim function, we cut off whitespaces. The serial port name is saved directly to the parser using the command parser.po=port.path;. This way, I can display the information which Arduino sent the line to the output.

'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 ports (comma separated)> '
});

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) {
    var indexes = line.split(',')
      .map(function(item) {
        return item.trim();
      });
    //console.log(indexes);

    indexes.forEach(function(i) {
      if(i<idx) {
        console.log('Opening ' + ports[Number(i)]);

        const port = new serialport(ports[Number(i)], {
          baudRate: 9600
          });
        const parser = new sp_readline();
        parser.po=port.path;
        port.pipe(parser);  

        parser.on('data', function(data) {
          console.log(this.po + ':' + data);
        });
        
        port.on('error', function(e) {
          console.error(e.message);
          process.exit(0);
        });
        
        port.on('open', function() {
          console.log('Serial port ' + this.path + ' 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\arduinoserialtest3\node
npm install

01.12.2017


Menu