This repository has been archived on 2024-01-30. You can view files and clone it, but cannot push or open issues or pull requests.
trev/nodejs/ar-com/arduino.js

105 lines
2.6 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var events = require('events'),
child = require('child_process'),
util = require('util'),
serial = require("serialport");
var Arduino = function (debug, baudrate) {
this.baudrate = baudrate && baudrate || 9600;
this.debug = debug && debug || false;
this.writeBuffer = [];
}
util.inherits(Arduino, events.EventEmitter);
Arduino.prototype.HIGH = '255';
Arduino.prototype.LOW = '000';
Arduino.prototype.setup = function () {
var self = this;
child.exec('cd ../arduino && ino build && ino upload', function(err, stdout, stderr){
if(err){
console.log('Please install the ino utility and connect arduino!\nIf there are other open programs that communicate with the arduino, close them!');
if(self.debug) {console.log(err.message);}
return;
}
var buff = stdout.slice(stdout.indexOf('Guessing serial port ... ')+25);
buff = buff.slice(0, buff.indexOf('\n'));
console.log('Guessing serial port ... ' + buff);
self.serial = new serial.SerialPort(buff, {
baudrate: self.baudrate,
parser: serial.parsers.readline('\n')
}, false);
self.serial.open(function (error) {
if ( error ) {
console.log('Please check arduino!');
return;
}
});
self.serial.on('open', function () { setTimeout(function () {
self.serial.write(new Buffer('00000000'));
self.serial.write(new Buffer('Zn000000', 'ascii'));
if(self.debug) { self.serial.write(new Buffer('P0000000', 'ascii')); }
self.emit('success');
self.serial.on('data', function(data){
if(self.debug) { console.log(data) };
self.emit('data', data);
});
self.processWriteBuffer();
}, 5000);});
});
}
Arduino.prototype.write = function (message) {
if (this.serial) {
console.log('sending '+message);
this.serial.write(message);
} else {
this.writeBuffer.push(message);
console.log('Board isn\'t available (yet?).')
}
}
Arduino.prototype.processWriteBuffer = function () {
while (this.writeBuffer.length > 0) {
this.write(this.writeBuffer.shift());
}
}
// Helpers
Arduino.prototype.valueToLastFour = function(val) {
var encodedVal = "";
for (var i = 3; i >= 0; i--) {
encodedVal += String.fromCharCode(val/(Math.pow(2,8*i)));
val = val % Math.pow(2,8*i);
}
return encodedVal;
};
Arduino.prototype.valueToFirstTwo = function(val) {
var encodedVal = "";
for (var i = 1; i >= 0; i--) {
encodedVal += String.fromCharCode(val/(Math.pow(2,8*i)));
val = val%Math.pow(2,8*i);
}
return encodedVal;
};
module.exports = Arduino;