DEV Community

Azzamjiul
Azzamjiul

Posted on

4 1

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 :)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Neon image

Set up a Neon project in seconds and connect from a Next.js application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →