Code Monkey home page Code Monkey logo

duino's Introduction

duino

A framework for working with Arduinos in node.js

arduino

install

npm install duino

usage

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

var board = new arduino.Board({
  device: "ACM"
});

The board library will attempt to autodiscover the Arduino. The device option can be used to set a regex filter that will help the library when scanning for matching devices. Note: the value of this parameter will be used as argument of the grep command

If this parameter is not provided the board library will attempt to autodiscover the Arduino by quering every device containing 'usb' in its name.

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

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
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

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)

Fade the to full brightness then back to minimal brightness in interval ms. Defaults to 2000

###led.bright

Current brightness of the LED

##lcd

This is a port of the LiquidCrystal library into JavaScript. Note that communicating with the LCD requires use of the synchronous board.delay() busy loop which will block other node.js events from being processed for several milliseconds at a time. (This could be converted to pause a board-level buffered message queue instead.)

var lcd = new d.LCD({
  board: board,
  pins: {rs:12, rw:11, e:10, data:[5, 4, 3, 2]}
});
lcd.begin(16, 2);
lcd.print("Hello Internet.");

In options, the "pins" field can either be an array matching a call to any of the LiquidCrystal constructors or an object with "rs", "rw" (optional), "e" and a 4- or 8-long array of "data" pins. Pins will default to [12, 11, 5, 4, 3, 2] if not provided.

###lcd.begin(), lcd.clear(), lcd.home(), lcd.setCursor(), lcd.scrollDisplayLeft(), lcd.scrollDisplayRight()

These should behave the same as their counterparts in the LiquidCrystal library.

###lcd.display(on), lcd.cursor(on), lcd.blink(on), lcd.autoscroll(on)

These are similar to the methods in the LiquidCrystal library, however they can take an optional boolean parameter. If true or not provided, the setting is enabled. If false, the setting is disabled. For compatibility .noDisplay(), .noCursor(), .noBlink() and .noAutoscroll() methods are provided as well.

###lcd.write(val), lcd.print(val)

These take a buffer, string or integer and send it to the display. The .write and print methods are equivalent, aliases to the same function.

###lcd.createChar(location, charmap)

Configures a custom character for code location (numbers 0–7). charmap can be a 40-byte buffer as in the C++ method, or an array of 5-bit binary strings, or a 40-character string with pixels denoted by any non-space (' ') character. These bits determine the 5x8 pixel pattern of the custom character.

var square = new Buffer("1f1f1f1f1f1f1f1f", 'hex');

var smiley = [
  '00000',
  '10001',
  '00000',
  '00000',
  '10001',
  '01110',
  '00000'
];

var random =
  ".  .." +
  " . . " +
  ". . ." +
  " . . " +
  " ..  " +
  ".  . " +
  " .  ." +
  ".. .." ;

lcd.createChar(0, square);
lcd.createChar(1, smiley);
lcd.createChar(2, random);
lcd.setCursor(5,2);
lcd.print(new Buffer("\0\1\2\1\0"));    // NOTE: when `.print`ing a string, 'ascii' turns \0 into a space

##piezo

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

var button = new arduino.Button({
  board: board,
  pin: 13
});

Pin will default to 13.

Buttons are simply EventEmitters. They will emit the events up and down. You may also access their down property.

button.on('down', function(){
  // delete the database!
  console.log('BOOM');
});

setInterval(function(){
  console.log(button.down);
}, 1000);

##ping

See: http://arduino.cc/en/Tutorial/Ping

var range = new arduino.Ping({
  board: board
});

range.on('read', function () {
  console.log("Distance to target (cm)", range.centimeters);
});

##servo

var servo = new arduino.Servo({
  board: board
});

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
  • 97 ping
  • 98 servo
  • 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 [email protected]

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.

duino's People

Contributors

ecto avatar jarretth avatar natevw avatar nulltask avatar pi-uno avatar richkzad avatar rwaldron avatar setola avatar trobrock avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

duino's Issues

servo example not working

Love this framework. led.blink() works fine, but I can't get my servo to respond. The servo sweep example that comes with the arduino software works well so I don't think its the servo. Here is what I'm seeing in the log:

1337133106943 duino info attempting to find Arduino board
1337133106947 duino info set pin 13 mode to out
1337133106947 duino info serial not ready, buffering message: 0013001
Express server listening on port 3000 in development mode
1337133106957 duino info found board at /dev/tty.usbmodem411
1337133106957 duino info binding serial events
1337133107459 duino info board ready
1337133107459 duino info sending debug mode toggle on to board
1337133107465 duino write 9900001
1337133107467 duino info processing buffered messages
1337133107467 duino info writing buffered message
1337133107467 duino write 0013001
board ready, attaching servo { board:
{ debug: true,
writeBuffer: [],
_events: { ready: [Function], data: [Function] },
serial:
{ port: '/dev/tty.usbmodem411',
fd: 7,
readStream: [Object],
_events: [Object] } },
pin: '09',
_events: { attached: [Function] } }
1337133107469 duino write 980901


And then it stops. Thoughts? This is my code (pretty much straight from your example):

var arduino = require('duino'),
board = new arduino.Board({debug:true});

var led = new arduino.Led({
board: board,
pin: 13
});

var servo = new arduino.Servo({
board: board,
pin: 9
});

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();
});

du.ino process() incorrectly parses servo messages

To narrow this down, I added the following to handleServo:

  Serial.println(atoi(val));
  Serial.println(atoi(aux));

An example of the output:

1331739178315 duino receive 98A00265
1331739178315 duino receive ss
1331739178315 duino receive got signal
1331739178315 duino receive 26  /* atoi(val) */
1331739178315 duino receive 5   /* atoi(aux) */

If the message being parsed is 98A00265, then the expected values are:

1331739178315 duino receive 2    /* atoi(val) */
1331739178315 duino receive 65  /* atoi(aux) */

Otherwise, this block:

  } else if (atoi(val) == 2) {
    Serial.println("writing to servo");
    Serial.println(atoi(aux));
    servo.write(atoi(aux));
  }

...While never be entered.

The issue is here:

  strncpy(val, messageBuffer + 4, 3);
  val[3] = '\0';
  strncpy(aux, messageBuffer + 7, 3);
  aux[3] = '\0';

By changing this to:

  strncpy(val, messageBuffer + 4, 2);
  val[3] = '\0';
  strncpy(aux, messageBuffer + 6, 3);
  aux[3] = '\0';

... The servo values are written.

I will test this against all of the other modules + hardware and submit a patch when complete.

Duino doesn't work with 2 servos?

Hi--,
I attached 2 servo motors on my arduino (declaring servo1, servo2 in node server with different pin).
It always only works with the 2nd motor I attach, duino seems to ignore the first one?
Do you know how to fix this?

Thanks,

GHSL-2020-118

Hello,

I am a member of the GitHub Security Lab (https://securitylab.github.com).

I've attempted to reach a maintainer for this project to report a potential security issue but have been unable to verify the report was received. Please could a project maintainer could contact us at [email protected], using reference GHSL-2020-118?

Thank you,
Kevin Backhouse
GitHub Security Lab

Push 0.0.9 to npmjs

The title says it all.
Current version in npmjs is 0.0.8, which doesn't have the device name fix.
Just for reference, i'm using 0.0.9 on a raspberry pi and it works perfectly
Thankyou

Button events are backwards

In lib/board.js:

// 1 is up
// 0 is down
if (m[1] == '1' && self.down) {
  self.down = false;
  self.emit('up');
}
if (m[1] == '0' && !self.down) {
  self.down = true;
  self.emit('down');
}

...which is backwards; button "up/unpressed" will be LOW/0/gnd and button "down/pressed" will be HIGH/1/5v

Move to newline parser

There is no need to parse on the JavaScript level at 115k baud when C can do it for us inside node-serialport.

events.js:2725: Uncaught Error: Cannot open /dev/usbdev5.1

Hi,

just installed duino module

Here is my script

var arduino = require('duino'),
    board = new arduino.Board();

var led = new arduino.Led({
  board: board,
  pin: 13,
  debug: true
});

led.blink();

Here is the output

$ node duino-1.js
events.js:2725: Uncaught Error: Cannot open /dev/usbdev5.1

My Env: Ubuntu 12.04 LTS on MK803 mini PC (ARM), Node v0.8.14

How can I fix this?

Cannot use on Windows: `board.js` hard-coded *nix paths

Since board.js is trying to open a device from the *nix /dev folder, this library cannot possibly work on Windows.

On Windows, the path (the first argument to SerialPort constructor) is simply COM1, COM2 etc., which is the name of the COM port that the driver is using (also see this related thread on using CreateFile to open a serial port communication channel).

Once the path is correct, things work as expected. Very awesome!

In the long term, I would recommend a general-purpose config that allows for the path to be user-selected, or, if supported on the system, to be looked up automatically.

Hi, need an especific port

1345814061925 duino info attempting to find Arduino board
1345814061952 duino info found board at undefined
1345814061953 duino info binding serial events

events.js:48
throw arguments[1]; // Unhandled 'error' event

                   ^

Error: EACCES, open '/dev/usbmon0'

Hi, mi arduino its connect on /dev/ttyACM0, but duino can't open that.

Don't throw Errors

When no board is found, the board initialization routine throws an error inside an internal callback (board.js:88).

I propose emitting an "error" event instead of throwing.

Update: Sorry I didn't make a pull request initially, just didn't think that I'd implement it that quickly.

Bug in analogRead

Hi, there is a little bug in your board.analogRead, the code should be:

Board.prototype.analogRead = function (pin) {
    pin = this.normalizePin(pin);
    this.log('info', 'analogRead from pin ' + pin);
    this.write('04' + pin + this.normalizeVal(0));
}

I'm sorry I haven't created a pull request, but my repository is too messed up right now :D

Define is not defined

Following the instructions I just keep getting a "define not defined" message. Example:

$ node examples/led.js
/Users/ruben/projects/arduino/noduino/node_modules/duino/lib/board.js:1
(function (exports, require, module, __filename, __dirname) { define(function(
                                                          ^
ReferenceError: define is not defined
    at Object.<anonymous> (/Users/ruben/projects/arduino/noduino/node_modules/duino/lib/board.js:1:63)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)
    at Object.<anonymous> (/Users/ruben/projects/arduino/noduino/node_modules/duino/index.js:3:11)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)

Raspberry Pi

Hi,

has anyone tried to use duino with an Raspberry Pi (with Raspbian)?

The communication using duino is working perfectly on my Mac but if I use my app on the pi the serial communication does not work properly as you can see as follows:

1359682670868 duino info binding serial events
1359682670888 duino receiveA#C� >�2 $$$�
1359682671387 duino info board ready

What could be wrong? I tried baud rates of 9600 and 115200.

Refactor serial binding

Sometimes signals will be sent from the Arduino before we bind for data events. To fix this, we'll have to refactor the autoconnection.

Error: Serialport not open

I am running example sensor.js and getting following error:

`1458988219328 duino info attempting to find Arduino board
1458988219400 duino info set pin A0 mode to in
1458988219403 duino info serial not ready, buffering message: 00A0000
1458988219455 duino debug attempting to open serial conn.: ttyACM0
1458988219462 duino info found board at /dev/ttyACM0
1458988219464 duino info binding serial events
1458988219471 duino info analogRead from pin A0
1458988219472 duino write 04A0000

Error: Serialport not open.
at SerialPortFactory.SerialPort.write (/home/pi/SmartHome/node_modules/duino/node_modules/serialport/serialport.js:288:17)
at Board.write (/home/pi/SmartHome/node_modules/duino/lib/board.js:163:17)
at Board.analogRead (/home/pi/SmartHome/node_modules/duino/lib/board.js:235:7)
at null. (/home/pi/SmartHome/node_modules/duino/lib/sensor.js:17:16)
at wrapper as _onTimeout
at Timer.listOnTimeout as ontimeout`

I will appreciate your help

How do I access the examples?

Seems like it should be really easy, but I'm finding it confusing. How the heck do I access the examples?

It also isn't clear what needs to be running in order for the examples to work. Does srv.web.js need to be listening whilst srv.app.js is also running? I'm not sure.

I've tried:

node srv.web.js
info  - socket.io started
Listening on http://localhost:8080

http://localhost:8080/examples/walkLED.html //404

and this:

node srv.app.js

define(['kickstart', 'module', 'path', 'fs'], function (kickstart, module, pat
^
ReferenceError: define is not defined
    at Object.<anonymous> (/Users/joshuamcginnis/Dropbox/Joshua/sandbox/node-js-projects/noduino/srv.app.js:11:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.