// arduino_serial.js // kll node + serial // start with: node arduino_serial.js // or: node arduino_serial.js /dev/ttyACM0 'use strict'; const serialport = require('serialport');// include the library const SerialPort = serialport.SerialPort; // make a local instance of it // get port name from the command line / or use default var portName = "/dev/ttyACM0"; var portNameCLI = process.argv[2]; console.log("port from command line:" + portNameCLI); if ( portNameCLI > "") { portName = portNameCLI; console.log(" used "); } else { console.log(" use default "); } var serialData = 0; // latest data saved from the serial port /* // good for test, but it not say if in use or not // list serial ports: serialport.list(function (err, ports) { ports.forEach(function(port) { console.log(port.comName); }); }); */ var myPort = new SerialPort(portName, { baudRate: 9600, parser: serialport.parsers.readline("\n") // look for return and newline at the end of each data packet: }); // these are the definitions for the serial events: myPort.on('open', showPortOpen); myPort.on('data', saveLatestData); myPort.on('close', showPortClose); myPort.on('error', showError); // the functions called when the serial events occur: function showPortOpen() { console.log('port open:' + portName +' Data rate: ' + myPort.options.baudRate); } function saveLatestData(data) { console.log(data); // show while develop serialData = data; } function showPortClose() { console.log('port closed.'); } function showError(error) { console.log('Serial port error: ' + error); }