loading...

How to connect to arduino automatically using node-serialport

mohammedgqudah profile image mohammedgqudah ・1 min read

node-serialport is an awesome module that let you read open... serialports using nodejs. so i am going to show you a very simple example on how to send data from arduino. then i want to share the code that i created which will connect to arduino port automatically without specifying the port.

the example

first install the module

npm install serialport

then create a new js file


var SerialPort = require('serialport');
// open the port
var port = new SerialPort('/dev/ttyACM0');
port.write('hello arduino')

now what if we want to connect to arduino automatically without specifying the port!

i create this code which will read every serialport and check if it is an arduino port.

function getConnectedArduino() {
  SerialPort.list(function(err, ports) {
    var allports = ports.length;
    var count = 0;
    var done = false
    ports.forEach(function(port) {
      count += 1;
      pm = port['manufacturer'];
      if (typeof pm !== 'undefined' && pm.includes('arduino')) {
        arduinoport = port.comName.toString();
        var serialPort = require('serialport');
        sp = new serialPort(arduinoport, {
          buadRate: 9600
        })
        sp.on('open', function() {
          console.log('done! arduino is now connected at port: ' + arduinoport)
        })
        done = true;
      }
      if (count === allports && done === false) {
         console.log('cant find arduino')
      }
    });

  });
}

that's it! now this function will auto connect to arduino.
if you are interested in controlling arduino from your pc download this app

Posted on by:

mohammedgqudah profile

mohammedgqudah

@mohammedgqudah

fullstack web developer living in Jordan. Discord: Hyper#3519

Discussion

pic
Editor guide
 

@mohammedgqudah Very interested in this as I have a project that uses serial and an auto search and connect would be great. Only issue is now SerialPort has changed by removing callbacks.

UnhandledPromiseRejectionWarning: TypeError: SerialPort.list no longer takes a callback and only returns a promise

Also the app link seems dead.

 

Oh this is super cool! I wanted to do something like this but over bluetooth with a Teensy or a Bluefruit, the same rules should apply I assume! This is going to help me a lot, thanks!