DEV Community

Azzamjiul
Azzamjiul

Posted on

How to automatically connecting Arduino using serial-port in NodeJS

serial-port package in NodeJS is an awesome tool. You can communicate with hardware like Arduino only with JavaScript. Here, i will show you how to automatically connected with plugged Arduino without specify the port that used. All you need is node installed application with serial-port package.

const SerialPort = require('serialport')

let path = ''
let ArduinoPort = ''

// Promise approach
SerialPort.list().then(ports => {
  let done = false
  let count = 0
  let allports = ports.length
  ports.forEach(function(port) {
    count = count+1
    pm  = port.manufacturer

    if (typeof pm !== 'undefined' && pm.includes('arduino')) {
      path = port.path
      ArduinoPort = new SerialPort(path, { baudRate: 115200 })
      ArduinoPort.on('open', function(){
        console.log(`connected! arduino is now connected at port ${path}`)
      })
      done = true
    }

    if(count === allports && done === false){
      console.log(`can't find any arduino`)
    }
  })
})

i wrote the code in portList.js file in enose-desktop-application node application directory. So, if i want to run it i typed commad

node portList.js

Here the result

Results

That's all. I hope it will help you to solve the problem. any suggestion are welcome :)

Top comments (0)