I'm using nodejs "v0.10.28" and npm "1.4.9", downloaded from http://nodejs.org.
I've installed serialport through npm
npm install serialport
My program is running on a Raspberry-pi and needs to keep sending updated values quickly through serialport, so I've created this test program.
var serialPort = require("serialport");
var SerialPort = require("serialport").SerialPort;
var sp = new SerialPort("/dev/ttyAMA0", {
baudrate: 9600
}, false);
console.log("Starting up serial host...");
var message = "Num: ";
var counter = 1000000;
function write()
{
message= counter.toString();
counter+=1;
sp.open(function(err)
{
console.log("Writing serial data: " + message);
sp.write(message, function(err, res)
{
if (err)
{
console.log(err);
}
sp.close();
});
});
}
setTimeout(write, 10); //wait 10 ms for everything to initialize correctly
setInterval(write, 50); //write data every 50 ms
The program runs ok for exactly 1012 writes, then crashes.
Program output towards the end:
...
Writing serial data: 1001011
Writing serial data: 1001012
Writing serial data: 1001013
[Error: Serialport not open.]
events.js:72
throw er; // Unhandled 'error' event
^
Error: Serialport not open.
at SerialPortFactory.SerialPort.close (/home/pi/node_modules/serialport/serialport.js:476:17)
at /home/pi/serialTest.js:25:7
at SerialPortFactory.SerialPort.write (/home/pi/node_modules/serialport/serialport.js:290:9)
at /home/pi/serialTest.js:19:13
at /home/pi/node_modules/serialport/serialport.js:224:11
Why is it crashing? Is there any buffer overflow in memory somewhere? And why exactly 1012 writes? Very close to 1024, is it a coincidence?
A friend just helped with answering this privately so I'll share findings here.
Code:
If you look closely you'll notice that now sp.open() is used once and in the beginning of write function sp.isOpen() is used to check if port is open. Also setInterval(write, 50); is gone and now only use setTimeout(write, 10);
Code now works, but that still doesn't answer the question why did it use to crash when opening and closing the port in the previous code.