Node Js communication with Arduino via serialport

suggest change

Node js code

Sample to start this topic is Node.js server communicating with Arduino via serialport.

npm install express serialport

--save has been the default since npm 5. Current serialport exports { SerialPort } and uses baudRate, not baudrate.

Sample app.js:

const express = require('express');
const app = express();
var { SerialPort } = require("serialport");

var port = 3000;

var arduinoCOMPort = "COM3";

var arduinoSerialPort = new SerialPort({
 path: arduinoCOMPort,
 baudRate: 9600
});

arduinoSerialPort.on('open',function() {
  console.log('Serial Port ' + arduinoCOMPort + ' is opened.');
});

app.get('/', function (req, res) {

    return res.send('Working');
 
})

app.get('/:action', function (req, res) {
    
   var action = req.params.action;

    if(action == 'led'){
        arduinoSerialPort.write("o");
        return res.send('Led light is on!');
    }
    if(action == 'off') {
        arduinoSerialPort.write("f");
        return res.send("Led light is off!");
    }
    
    return res.send('Action: ' + action);
 
});

app.listen(port, function () {
  console.log('Example app listening on port http://0.0.0.0:' + port + '!');
});

Starting sample express server:

node app.js

Arduino code

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.

  Serial.begin(9600); // Begin listening on port 9600 for serial
  
  pinMode(LED_BUILTIN, OUTPUT);

  digitalWrite(LED_BUILTIN, LOW);
}

// the loop function runs over and over again forever
void loop() {

   if(Serial.available() > 0) // Read from serial port
    {
      char ReaderFromNode; // Store current character
      ReaderFromNode = (char) Serial.read();
      convertToState(ReaderFromNode); // Convert character to state  
    }
  delay(1000); 
}

void convertToState(char chr) {
  if(chr=='o'){
    digitalWrite(LED_BUILTIN, HIGH);
    delay(100); 
  }
  if(chr=='f'){
    digitalWrite(LED_BUILTIN, LOW);
    delay(100); 
  }
}

Starting Up

  1. Connect the arduino to your machine.
  2. Start the server

Control the built-in LED from the Express server. Open these URLs on the machine that is running the server. 0.0.0.0 is a bind address, not a host you browse to.

To turn the LED on:

http://localhost:3000/led

To turn the LED off:

http://localhost:3000/off

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents