diff --git a/README.md b/README.md index f3d84d2..827e992 100644 --- a/README.md +++ b/README.md @@ -1,239 +1,48 @@ -# duino +# [rf]duino -A framework for working with Arduinos in node.js +This fork of [ecto's duino library](https://github.com/ecto/duino) replaces the servo library with a RF receiver and transmitter. -![arduino](http://i.imgur.com/eFq84.jpg) - -# install +## install npm install duino -# usage +Make sure to upload src/du/du.ino to your arduino + +## receiver usage ````javascript var arduino = require('duino'), board = new arduino.Board(); -var led = new arduino.Led({ - board: board, - pin: 13 -}); - -led.blink(); -```` - -# what ಠ_ಠ - -The way this works is simple (in theory, not in practice). The Arduino listens for low-level signals over a serial port, while we abstract all of the logic on the Node side. - -1. Plug in your Arduino -2. Upload the C code at `./src/du.ino` to it -3. Write a simple **duino** script -4. ????? -5. Profit! - -# libraries - -##board - -Right now, the board library will attempt to autodiscover the Arduino. I'm going to make it configurable, don't worry. - -````javascript -var board = new arduino.Board({ - debug: true -}); -```` - -Debug mode is off by default. Turning it on will enable verbose logging in your terminal, and tell the Arduino board to echo everthing back to you. You will get something like this: - -![debug](http://i.imgur.com/gBYZA.png) - -The **board** object is an EventEmitter. You can listen for the following events: - -* `data` messages from the serial port, delimited by newlines -* `connected` when the serial port has connected -* `ready` when all internal post-connection logic has finished and the board is ready to use - -````javascript board.on('ready', function(){ - // do stuff -}); - -board.on('data', function(m){ - console.log(m); -} -```` - -###board.serial - -Low-level access to the serial connection to the board - -###board.write(msg) - -Write a message to the board, wrapped in predefined delimiters (! and .) - -###board.pinMode(pin, mode) - -Set the mode for a pin. `mode` is either `'in'` or `'out'` - -###board.digitalWrite(pin, val) - -Write one of the following to a pin: - -####board.HIGH and board.LOW - -Constants for use in low-level digital writes - -###board.analogWrite(pin,val) - -Write a value between 0-255 to a pin - -##led - -````javascript -var led = new arduino.Led({ - board: board, - pin: 13 -}); -```` - -Pin will default to 13. - -###led.on() - -Turn the LED on - -###led.off() - -Turn the LED off - -###led.blink(interval) - -Blink the LED at `interval` ms. Defaults to 1000 -###led.fade(interval) + var rfReceiver = new arduino.RFReceiver({ + board: board, + pin: '02' + }); -Fade the to full brightness then back to minimal brightness in `interval` ms. Defaults to 2000 - -###led.bright - -Current brightness of the LED - -##piezo - -````javascript -var led = new arduino.Piezo({ - board: board, - pin: 13 -}); -```` -Pin will default to 13. - -###piezo.note(note, duration) - -Play a pre-calculated note for a given duration (in milliseconds). - -`note` must be a string, one of `d`, `e`, `f`, `g`, `a`, `b`, or `c` (must be lowercase) - -###piezo.tone(tone, duration) - -Write a square wave to the piezo element. - -`tone` and `duration` must be integers. See code comments for math on `tone` generation. - -##button - -````javascript -var button = new arduino.Button({ - board: board, - pin: 13 + rfReceiver.on('read', function(err, data){ + console.log("data", data); + }); }); ```` -Pin will default to 13. -Buttons are simply EventEmitters. They will emit the events `up` and `down`. You may also access their `down` property. +## transmitter usage ````javascript -button.on('down', function(){ - // delete the database! - console.log('BOOM'); -}); +var arduino = require('duino'), + board = new arduino.Board(); -setInterval(function(){ - console.log(button.down); -}, 1000); -```` +board.on('ready', function(){ -##servo + var rfTransmitter = new arduino.RFTransmitter({ + board: board, + pin: '03' + }); -````javascript -var servo = new arduino.Servo({ - board: board + rfTransmitter.send("hey there delilah"); }); - -servo.write(0); -servo.write(180); ```` -Pin will default to 9. (Arduino PWM default) - -###servo.sweep() - -Increment position from 0 to 180. - -###servo.write(pos) - -Instruct the servo to immediately go to a position from 0 to 180. - -##motor - -##potentiometer - -# protocol - -Each message sent to the Arduino board by the **board** class has 8 bytes. - -A full message looks like this: - - !0113001. - -`!` Start -`01` Command (digitalWrite) -`13` Pin number -`001` Value (high) -`.` Stop - -I was drunk. It works. - -##command - -What is implemented right now: - -* `00` pinMode -* `01` digitalWrite -* `02` digitalRead -* `03` analogWrite -* `04` analogRead -* `99` debug - -##pin - -Pins can be sent as an integer or a string(`1`, `2`, `"3"`, `"A0"`) - -##value - -* `board.LOW`(`0`) -* `board.HIGH`(`255`) -* integer/string from `0`-`255` for PWM pins - -# license - -(The MIT License) - -Copyright (c) 2011 Cam Pedersen - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +Note that the transmitter can only send up to 26 characters at a time. +Messages may be dropped if messages are sent at high rates. \ No newline at end of file diff --git a/examples/servo.js b/examples/servo.js deleted file mode 100644 index eb732ab..0000000 --- a/examples/servo.js +++ /dev/null @@ -1,56 +0,0 @@ -var arduino = require('../'), - board, led, servo; - -// Construct instances -board = new arduino.Board({ - debug: true -}); - -led = new arduino.Led({ - board: board, - pin: 13 -}); - -servo = new arduino.Servo({ - board: board, - pin: 9 -}); - -// Once servo is attached: -// - "read" -// - log position -// - "aftersweep" -// - blink the led -// - read the position -// - detach the servo -// - "detached" -// - log detach message -// -// - execute full sweep - -servo.on('attached', function(err) { - console.log('attached'); - - this.on('read', function(err, pos) { - console.log(pos); - }); - - this.on('detached', function(err) { - console.log('detached'); - }); - - this.on('aftersweep', function(err) { - led.blink(); - - this.read(); - this.detach(); - }); - - this.sweep(); -}); - -// To test, use the following: -// http://arduino.cc/en/uploads/Tutorial/sweep_BB.png -// -// More information: -// http://www.ladyada.net/learn/sensors/pir.html diff --git a/index.js b/index.js index a30f8f9..683d548 100644 --- a/index.js +++ b/index.js @@ -4,8 +4,9 @@ module.exports = { Led: require('./lib/led'), Piezo: require('./lib/piezo'), Button: require('./lib/button'), - Servo: require('./lib/servo'), Sensor: require('./lib/sensor'), Ping: require('./lib/ping'), - PIR: require('./lib/pir') + PIR: require('./lib/pir'), + RFReceiver: require('./lib/rfReceiver'), + RFTransmitter: require('./lib/rfTransmitter') }; diff --git a/lib/board.js b/lib/board.js index a1acf89..5c7e8ac 100644 --- a/lib/board.js +++ b/lib/board.js @@ -12,6 +12,7 @@ var events = require('events'), var Board = function (options) { this.log('info', 'initializing'); this.debug = options && options.debug || false; + this.device = options && options.device || 'usb'; this.baudrate = options && options.baudrate || 115200; this.writeBuffer = []; @@ -53,7 +54,7 @@ var Board = function (options) { self.processWriteBuffer(); } - self.emit('ready'); + self.emit('ready'); }, 500); } }); @@ -72,7 +73,7 @@ util.inherits(Board, events.EventEmitter); Board.prototype.detect = function (callback) { this.log('info', 'attempting to find Arduino board'); var self = this; - child.exec('ls /dev | grep usb', function(err, stdout, stderr){ + child.exec('ls /dev | grep "' + self.device + '"', function(err, stdout, stderr){ var usb = stdout.slice(0, -1).split('\n'), found = false, err = null, @@ -205,6 +206,24 @@ Board.prototype.analogRead = function (pin) { this.write('04' + pin + this.normalizeVal(0)); } +/* + * Tell the board to read from RF receiver + */ +Board.prototype.rfRead = function (pin) { + pin = this.normalizePin(pin); + this.log('info', 'rfRead from pin ' + pin); + this.write('05' + pin + this.normalizeVal(0)); +} + +/* + * Tell the board to send RF message + */ +Board.prototype.rfTransmit = function (pin, msg) { + pin = this.normalizePin(pin); + this.log('info', 'rfTransmit from pin ' + pin, 'with message: ' + msg); + this.write('06' + pin + msg); +} + /* * Utility function to pause for a given time */ diff --git a/lib/rfReceiver.js b/lib/rfReceiver.js new file mode 100644 index 0000000..8d13d1a --- /dev/null +++ b/lib/rfReceiver.js @@ -0,0 +1,26 @@ +var events = require('events'), + util = require('util'), + Sensor = require('./sensor'); + +/* + * Main RF Receiver constructor. + */ +var RFReceiver = function (options) { + Sensor.call(this, options); +}; + +/* + * Extends from Sensor. + */ +util.inherits(RFReceiver, Sensor); + +/** + * Overrides the read method + */ +RFReceiver.prototype.read = function () { + setInterval(function () { + this.board.rfRead(this.pin); + }.bind(this), this.throttle); +}; + +module.exports = RFReceiver; diff --git a/lib/rfTransmitter.js b/lib/rfTransmitter.js new file mode 100644 index 0000000..e1c8ba3 --- /dev/null +++ b/lib/rfTransmitter.js @@ -0,0 +1,21 @@ +/* + * Main RF Receiver constructor. + */ +var RFTransmitter = function (options) { + if (!options || !options.board) throw new Error('Must supply required options to Sensor'); + this.board = options.board; + this.pin = options.pin || '03'; +}; + +/** + * Overrides the read method + */ +RFTransmitter.prototype.send = function (msg) { + if(msg.length > 26) { + throw new Error('Message must be less than or equal to 26 characters'); + } + + this.board.rfTransmit(this.pin, msg); +}; + +module.exports = RFTransmitter; diff --git a/lib/sensor.js b/lib/sensor.js index a1883fc..b029699 100644 --- a/lib/sensor.js +++ b/lib/sensor.js @@ -10,12 +10,10 @@ var Sensor = function (options) { if (!options || !options.board) throw new Error('Must supply required options to Sensor'); this.board = options.board; this.pin = options.pin || 'A0'; + this.throttle = options.throttle || 50; this.board.pinMode(this.pin, 'in'); - // Poll for sensor readings - setInterval(function () { - this.board.analogRead(this.pin); - }.bind(this), options.throttle || 50); + this.read(); // When data is received, parse inbound message // match pin to instance pin value @@ -28,7 +26,7 @@ var Sensor = function (options) { return; } - pin = m[0] + pin = m[0]; data = m.length === 2 ? m[1] : null; if (pin === this.pin) { @@ -37,6 +35,13 @@ var Sensor = function (options) { }.bind(this)); }; +Sensor.prototype.read = function () { + // Poll for sensor readings + setInterval(function () { + this.board.analogRead(this.pin); + }.bind(this), this.throttle); +}; + /* * EventEmitter, I choose you! */ diff --git a/lib/servo.js b/lib/servo.js deleted file mode 100644 index de61334..0000000 --- a/lib/servo.js +++ /dev/null @@ -1,142 +0,0 @@ -var events = require('events'), - util = require('util'); - -/* - * Main Servo constructor - * Process options - * Tell the board to set it up - */ -var Servo = function (options) { - if (!options || !options.board) throw new Error('Must supply required options to Servo'); - this.board = options.board; - this.pin = this.board.normalizePin(options.pin || 9); - - var types = { - attached: true, - detached: true, - read: true, - moved: true - }; - - this.board.on('ready', function () { - console.log('board ready, attaching servo', this); - this.attach(); - }.bind(this)); - - this.board.on('data', function (message) { - var m = message.slice(0, -1).split('::'), - err = null, - pin, type, data; - - if (!m.length) { - return; - } - - pin = m[0] - type = m[1]; - data = m.length === 3 ? m[2] : null; - - if (pin === this.pin && types[type]) { - this.emit(type, err, data); - } - }.bind(this)); -}; - -util.inherits(Servo, events.EventEmitter); - -Servo.prototype.command = function () { - var msg = '98' + this.pin + ([].slice.call(arguments).join('')); - - // this.board.log( 'info', 'command', msg ); - this.board.write(msg); -}; - -Servo.prototype.detach = function () { - this.command('00'); -}; - -Servo.prototype.attach = function () { - this.command('01'); -}; - -Servo.prototype.write = function (pos) { - pos = this.board.lpad(3, '0', pos); - this.board.log('info', 'moving to: ' + pos); - this.command('02' + pos); -}; - -Servo.prototype.read = function () { - this.command('03'); -}; - -// Servo.prototype.writeMilliseconds = function () {}; -// Servo.prototype.attached = function (callback) { -// this.callbacks.attached.push(callback); -// }; - -Servo.prototype.sweep = function (options) { - // Ensure no missing options object - options = options || {}; - - var timeout = { - inner: null, - outer: null - }, - moves = 0, - // sweep settings - lapse = options.lapse || 2000, - to = options.to || 180, - from = options.from || 1, - // sweep handlers - doSweep = function doSweep(pos) { - // this.board.log('info', 'current position: ', pos); - var moveTo, - posint = +pos; - - // this.board.log('info', 'current pos int: ', posint); - - if (posint === 93) { - moveTo = 1; - } else { - - // this.board.log('info', 'posint not 93.....'); - - if (posint < to) { - moveTo = to; - } else if (posint == to) { - moveTo = 90; - } else { - moveTo = from; - } - } - - this.write(moveTo); - - moves++; - }; - - this.on('read', doSweep); - - // Initialize sweep; wait for for stack unwind. - timeout.outer = setTimeout(function loop() { - // Read the current position, will trigger - // 'read' event with position data; - if (moves < 2) { - this.read(); - - timeout.inner = setTimeout(loop.bind(this), lapse); - } else { - // this.board.log('info', 'info', 'clearing'); - - clearTimeout(timeout.inner); - clearTimeout(timeout.outer); - - loop = null; - - this.removeListener('read', doSweep); - this.emit.call(this, 'aftersweep'); - } - }.bind(this), 0); -}; - -module.exports = Servo; diff --git a/src/du.ino b/src/du/du.ino similarity index 70% rename from src/du.ino rename to src/du/du.ino index 2427435..5a2d4a7 100644 --- a/src/du.ino +++ b/src/du/du.ino @@ -1,27 +1,31 @@ -#include - +#include bool debug = false; int index = 0; -char messageBuffer[12]; +char messageBuffer[36]; char cmd[3]; char pin[3]; char val[4]; char aux[4]; +char msg[27]; // 26 max characters + 1 for null byte -Servo servo; +boolean rxStarted = false; void setup() { - Serial.begin(115200); + Serial.begin(9600); + vw_set_ptt_inverted(true); // Required for DR3100 + vw_setup(2000); // Bits per sec } void loop() { while(Serial.available() > 0) { char x = Serial.read(); - if (x == '!') index = 0; // start - else if (x == '.') process(); // end + if (x == '!') { + memset(&messageBuffer[0], 0, sizeof(messageBuffer)); + index = 0; // start + } else if (x == '.') process(); // end else messageBuffer[index++] = x; } } @@ -36,8 +40,11 @@ void process() { cmd[2] = '\0'; strncpy(pin, messageBuffer + 2, 2); pin[2] = '\0'; - - if (atoi(cmd) > 90) { + + if (atoi(cmd) == 6) { + strncpy(msg, messageBuffer + 4, 26); + msg[26] = '\0'; + } else if (atoi(cmd) > 90) { strncpy(val, messageBuffer + 4, 2); val[2] = '\0'; strncpy(aux, messageBuffer + 6, 3); @@ -54,10 +61,17 @@ void process() { } int cmdid = atoi(cmd); - // Serial.println(cmd); - // Serial.println(pin); - // Serial.println(val); - // Serial.println(aux); + if (cmdid == 4) { + + pinMode(8, OUTPUT); + digitalWrite(8, HIGH); + + } +// Serial.println(cmd); +// Serial.println(pin); +// Serial.println(val); +// Serial.println(aux); +// Serial.println(msg); switch(cmdid) { case 0: sm(pin,val); break; @@ -65,8 +79,9 @@ void process() { case 2: dr(pin,val); break; case 3: aw(pin,val); break; case 4: ar(pin,val); break; + case 5: rfr(pin,val); break; + case 6: rft(pin,msg); break; case 97: handlePing(pin,val,aux); break; - case 98: handleServo(pin,val,aux); break; case 99: toggleDebug(val); break; default: break; } @@ -150,6 +165,51 @@ void aw(char *pin, char *val) { analogWrite(p,atoi(val)); } + +/* + * Digital RF read + */ +void rfr(char *pin, char *val) { + + if (debug) Serial.println("rfr"); + int p = getPin(pin); + if(p == -1) { if(debug) Serial.println("badpin"); return; } + + if(!rxStarted){ + vw_set_rx_pin(p); + vw_rx_start(); // Start the receiver PLL running + rxStarted = true; + } + + uint8_t buf[VW_MAX_MESSAGE_LEN]; + uint8_t buflen = VW_MAX_MESSAGE_LEN; + + if (vw_get_message(buf, &buflen)) // Non-blocking + { + int i; + + Serial.println("Got"); + Serial.println((char*)buf); + + char m[VW_MAX_MESSAGE_LEN]; + sprintf(m, "%02d::%s", p, (char*)buf); + Serial.println(m); + } +} + +/* + * Digital RF transmit + */ +void rft(char *pin, char *msg) { + if (debug) Serial.println("rft"); + int p = getPin(pin); + if(p == -1) { if(debug) Serial.println("badpin"); return; } + + vw_set_tx_pin(p); + vw_send((uint8_t *)msg, strlen(msg) + 1); // +1 to include null byte + vw_wait_tx(); // Wait until the whole message is gone +} + int getPin(char *pin) { //Converts to A0-A5, and returns -1 on error int ret = -1; if(pin[0] == 'A' || pin[0] == 'a') { @@ -202,51 +262,3 @@ void handlePing(char *pin, char *val, char *aux) { delay(50); } } - -/* - * Handle Servo commands - * attach, detach, write, read, writeMicroseconds, attached - */ -void handleServo(char *pin, char *val, char *aux) { - if (debug) Serial.println("ss"); - int p = getPin(pin); - if(p == -1) { if(debug) Serial.println("badpin"); return; } - Serial.println("signal: servo"); - - // 00(0) Detach - if (atoi(val) == 0) { - servo.detach(); - char m[12]; - sprintf(m, "%s::detached", pin); - Serial.println(m); - - // 01(1) Attach - } else if (atoi(val) == 1) { - // servo.attach(p, 750, 2250); - servo.attach(p); - char m[12]; - sprintf(m, "%s::attached", pin); - Serial.println(m); - - // 02(2) Write - } else if (atoi(val) == 2) { - Serial.println("writing to servo"); - Serial.println(atoi(aux)); - // Write to servo - servo.write(atoi(aux)); - delay(15); - - // TODO: Experiment with microsecond pulses - // digitalWrite(pin, HIGH); // start the pulse - // delayMicroseconds(pulseWidth); // pulse width - // digitalWrite(pin, LOW); // stop the pulse - - // 03(3) Read - } else if (atoi(val) == 3) { - Serial.println("reading servo"); - int sval = servo.read(); - char m[13]; - sprintf(m, "%s::read::%03d", pin, sval); - Serial.println(m); - } -}