Skip to content

Instantly share code, notes, and snippets.

@Servuc
Last active September 29, 2017 21:55
Show Gist options
  • Save Servuc/4d80d59655857365ee0ef26d7f0b7ef3 to your computer and use it in GitHub Desktop.
Save Servuc/4d80d59655857365ee0ef26d7f0b7ef3 to your computer and use it in GitHub Desktop.
Teaching :) - Example of Express server with SerialPort reading

Express server and serial port reading

This JS file demonstrate how open a serial port to read it, and display read value over HTTP server.

Copy/Paste the script will display value at : http://localhost:3000 enjoy.

Install

yarn add serialport
yarn add express

Or

npm install serialport
npm install express

Run

node yourFile.js
//Define requires
const express = require('express')
const serialport = require('serialport');
//Store Arduino data
var myData = 0;
//Setup and start web server on :3000
const app = express()
app.get('/', function (req, res) { res.send('Hello World! - Valeur : ' + myData) });
app.listen(3000, function () { console.log('Example app listening on port 3000!') });
//Setup and start serial port reading
const Readline = serialport.parsers.Readline;
const parser = new Readline();
var mySerialPort = new serialport("/dev/ttyUSB0", {
baudRate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false,
});
mySerialPort.pipe(parser);
parser.on('data', function(input) {
console.log("Data :", input);
myData = input;
});
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(random(-5,15));
delay(5000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment