// arduino_serial.js // kll node + serial // start with: node arduino_serial.js // or: node arduino_serial.js /dev/ttyACM0 // see http://www.dyn-web.com/tutorials/php-js/json/parse.php // see http://www.w3schools.com/json/json_eval.asp '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 "); } /* // list serial port info: serialport.list(function (err, ports) { ports.forEach(function(port) { if ( port.comName == portName ) { console.log("port: " + port.comName + " manuf: " + port.manufacturer + " lets try that one"); } }); }); */ 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); myPort.flush(); } function saveLatestData(data) { var channel = 0; if (isValidJSON(data)) { let serialData = JSON.parse(data); // convert to JSON console.log("string:" + data); // show full string for better understanding console.log("channels: " + serialData.CHANNELS); console.log("time: " + serialData.TIME); for ( channel = 0; channel < serialData.CHANNELS; channel++ ) { console.log(serialData.DESC[channel] + " : " + serialData.AIN[channel]); } // console.log(serialData.A0 + " mul 2.5 " +serialData.A0 * 2.5); } else { console.log(data); } // show all } function showPortClose() { console.log('port closed.'); } function showError(error) { console.log('Serial port error: ' + error); } function isValidJSON(jsonOBJ) { try { JSON.parse(jsonOBJ); return true; } catch (e) { return false; } }