|
| 1 | +/* Copyright (c) 2017 Standa Opichal, Gordon Williams. See the file LICENSE for copying permission. */ |
| 2 | +/* |
| 3 | + Module for the MPR121 12-Channel Capacitive Sensor (I2C) |
| 4 | +
|
| 5 | + Based on the http://sonnycruz.blogspot.cz/2014/07/espruino.html code snippet |
| 6 | + and other available libraries https://github.com/adafruit?q=MPR121 libraries |
| 7 | +``` |
| 8 | +I2C1.setup({scl:B6,sda:B7}); |
| 9 | +
|
| 10 | +function ready() { |
| 11 | + setTimeout(function() { |
| 12 | + var keys = mpr.touched(); |
| 13 | + console.log("Touched: " + keys); |
| 14 | + }, 200); |
| 15 | +} |
| 16 | +
|
| 17 | +var mpr = require("MPR121").connect(I2C1, ready); |
| 18 | +// or |
| 19 | +var mpr = require("MPR121").connect(I2C1, ready, { address: 0x5B }); |
| 20 | +
|
| 21 | +``` |
| 22 | +
|
| 23 | +Default address is 0x5A, if tied to 3.3V its 0x5B |
| 24 | +If tied to SDA its 0x5C and if SCL then 0x5D |
| 25 | +*/ |
| 26 | +exports.connect = (i2c, callback, options) => { |
| 27 | + options = options || {}; |
| 28 | + |
| 29 | + let addr = options.address || 0x5A; // default address |
| 30 | + |
| 31 | + let MPR = { |
| 32 | + read: (count) => i2c.readFrom(addr, count), |
| 33 | + write: (data) => i2c.writeTo(addr, data), |
| 34 | + |
| 35 | + touched: () => { |
| 36 | + i2c.writeTo(addr, 0x00); |
| 37 | + var data = i2c.readFrom(addr, 2); |
| 38 | + return (data[1] << 8) || data[0]; |
| 39 | + }, |
| 40 | + |
| 41 | + setThresholds: (touch, release) => { |
| 42 | + for (i=0; i<24; i+=2) { |
| 43 | + i2c.writeTo(addr, 0x41+i, touch); |
| 44 | + i2c.writeTo(addr, 0x42+i, release); |
| 45 | + } |
| 46 | + } |
| 47 | + }; |
| 48 | + |
| 49 | + // disable electrodes |
| 50 | + i2c.writeTo(addr, [0x5E,0x00]); |
| 51 | + |
| 52 | + i2c.writeTo(addr, [0x2B,0x01]); |
| 53 | + i2c.writeTo(addr, [0x2C,0x01]); |
| 54 | + i2c.writeTo(addr, [0x2D,0x00]); |
| 55 | + i2c.writeTo(addr, [0x2E,0x00]); |
| 56 | + |
| 57 | + i2c.writeTo(addr, [0x2F,0x01]); |
| 58 | + i2c.writeTo(addr, [0x30,0x01]); |
| 59 | + i2c.writeTo(addr, [0x31,0xFF]); |
| 60 | + i2c.writeTo(addr, [0x32,0x02]); |
| 61 | + |
| 62 | + // touch, release thresholds |
| 63 | + MPR.setThresholds(15, 8); |
| 64 | + |
| 65 | + // 0x10: 16uA charge current |
| 66 | + // 0x20: 32uA charge current (default) |
| 67 | + i2c.writeTo(addr, [0x5C, options.config1 || 0x20]); |
| 68 | + // 0x20: 0.5us encoding, 1ms period |
| 69 | + // 0x3A: 0.5us encoding, 18 samples, 4ms period (default) |
| 70 | + i2c.writeTo(addr, [0x5D, options.config2 || 0x20]); |
| 71 | + |
| 72 | + // enable all electrodes |
| 73 | + i2c.writeTo(addr, [0x5E,0x8F]); |
| 74 | + |
| 75 | + if (callback) callback(MPR); |
| 76 | + return MPR; |
| 77 | +}; |
| 78 | + |
0 commit comments