Friday 21 September 2018

node.js + express + serialport, command from a POST does not get written to serialport

I wanna control an Arduino via webinterface which is hosted by an node.js server. The idea is, that I send (POST) a command (String) to the server, which forwards the command via 'serialport' to the Arduino. I use 'express' for the website, so my folder structure is something like. ├── app.js ├── bin │ └── www ├── package.json ├── routes │ └── index.js └── views └── index.pug The website works great and I can make a POST to send a command to the server.Now I wanna forward this command via 'serialport' to the Arduino. So I have in /routes/index.js this:router.post('/', function (req, res, next) { console.log(req.body.command); mySerial.write('I am sending a command!', function(err) { if (err) { return console.log('Error on write: ', err.message); } console.log('message written'); }); }); This cause an error: ReferenceError: mySerial is not definedOk, I think I get why: It's bc the code below about 'serialport' is located in /app.js . If I put mySerial.write() here in this section, node.js will send a String to the Arduino, but here I can't handle the command from the POST. I can't figure out myself what I have to do, to make it possible, that the command from POST is forwarded to the serialport.I am looking for a solution which makes it possible in the future to send a status from Arduino to the Browser.const SerialPort = require('serialport'); const Readline = SerialPort.parsers.Readline; const parser = new Readline(); const mySerial = new SerialPort('COM3', { baudRate: 115200 }); mySerial.on('open', function () { console.log('Opened Serial Port'); }); mySerial.on('data', function (data) { console.log(data.toString()); }); mySerial.on('err', function () { console.log(err.message); }); Thank you!Greetings

Submitted September 21, 2018 at 10:31AM by Iamnotagambler

No comments:

Post a Comment