Skip to content

Instantly share code, notes, and snippets.

@benjamind
Last active July 30, 2016 19:14
Show Gist options
  • Save benjamind/94e972dc697049a3ebd4c8402cd8cabb to your computer and use it in GitHub Desktop.
Save benjamind/94e972dc697049a3ebd4c8402cd8cabb to your computer and use it in GitHub Desktop.
Sending LED data over Serial with NodeJS
var serialport = require("serialport"),
SerialPort = serialport.SerialPort;
// first list the serial ports available so we can figure out which is the arduino
serialport.list(function (err, ports) {
var port = null;
ports.forEach(function(p) {
// this should work on windows and maybe osx
if (p.manufacturer.indexOf('Arduino')!==-1) {
port = p.comName;
} else {
// this will work on raspberry pi / linux
if (p.hasOwnProperty('pnpId')){
// FTDI captures the duemilanove //
// Arduino captures the leonardo //
if (p.pnpId.search('FTDI') != -1 || p.pnpId.search('Arduino') != -1) {
port = p.comName;
}
}
}
});
// port should now contain a string for the com port
// open the port
var serialPort = new SerialPort(port, {
baudrate: 115200
});
// hook up open event
serialPort.on("open", function () {
// port is open
console.log('port ' + port + ' opened');
// hook up data listener to echo out data as its received
serialPort.on('data', function(data) {
console.log('data received: ' + data);
});
// here's an array of LED color values, 3 bytes per LED.
var LEDS = [
255,0,0,
0,0,0,
0,0,0,
0,0,0,
0,0,255
];
// create a Buffer object to hold the data
var buffer = new Buffer(LEDS);
// write it on the port
serialPort.write(buffer, function(err, results) {
if (err) {
console.log('err ' + err);
}
console.log('wrote bytes : ' + results);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment