Coder Social home page Coder Social logo

fivdi / i2c-bus Goto Github PK

View Code? Open in Web Editor NEW
347.0 347.0 57.0 1.65 MB

I2C serial bus access with Node.js

License: MIT License

Python 0.19% JavaScript 77.27% C 5.71% C++ 16.72% Shell 0.11%
beaglebone beaglebone-black i2c iot javascript nodejs raspberry-pi smbus

i2c-bus's People

Contributors

fivdi avatar imyller avatar johntalton avatar pizzaprogram 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

i2c-bus's Issues

writeFailed Rasp -> Atmega

Hello,

First, thanks for your works, it's very good work, really.
I turned around this problem for couple of days and I try to find a forum to post this message instead of opening an issue but I didn't find any Forum !!!

I have a raspberry connected to a Atmega328P (Arduino on breaboard). I can communicate with I2c with ReadAsync (rasp -> Atmega) without problem.

But when I want to use writeByteSync (or any write function) in nodejs and I have ETIMEOUT. Unfortunately, the I2C interface Rasp is OUT and impossible to use ( search addresse become very slow :i2cdetect -y 1) after executing the code. I must reboot the Rasp. I have the feeling that an issue broke the interface.

When I use :i2cset -y 1 0x08 0x01 0x01 it's working fine my Atmega get the msg.

code:
var i2c = require('i2c-bus'),
i2c1 = i2c.openSync(1);
// Enter one shot mode (this is a non volatile setting)
i2c1.writeByteSync(0x08, 0x01, 0x01); -> ETIMOUT
i2c1.closeSync();

thx,

David

Simplify concurrent asynchronous access to multiple devices

If multiple devices need to be accessed asynchronously and concurrently, the current implementation requires that each device be accessed through it's own unique Bus object.

This is not intuitive.

Make it possible to access multiple devices asynchronously and concurrently through a single Bus object.

i'm getting lots of "Error: , Remote I/O error"

Hello,

lately i created a set of node-red nodes with your library as basis. And everything works very well most of the time. Except i'm getting "Error: , Remote I/O error" error sometimes.
I use node-red on a Raspberry Pi3 connected to a couple of arduino's.

Not sure where the issue is coming from.

What i should use as command code inside readI2cBlockSync?

Hi @fivdi , i'm new about using i2c modules and i'm playing around with my new raspberry pi 2 and hover board from hoverlabs.
I'm trying to translate a python library, that you can view here, in a node.js modules to use inside a project but i don't know what i have to use for this parameter.
Can you say me something about it?
Thanks in advance,
Simone

use case for I2cBlock

**are the I2cBlock read and write methods intended for use with devices like the MCP23017? ** where the cmd argument is the register byte (a chip command in essence) and then the buffer argument would contain either one or two bytes depending on whether one or both pin ports are being accessed at the same time. http://www.futurlec.com/SFMicrochip/MCP23017.shtml

{"errno":55,"code":"EIO","syscall":"write"}

beaglebone black 3.8.13-bone84
node v0.10.38,
i2c-bus version 1.2.1

this is the used sample:

var i2c  = require('i2c-bus');
var i2cbusInst = i2c.openSync(self.bus);
i2cbusInst.sendByteSync(self.id, val);
i2cbusInst.closeSync();

Any hits how to avoid this error?

not able to catch bad arguments error

Tried several ways....but not able to catch the bus call error (when I deliberately send a bad or missing argument) before it terminates the node process.
Note that the console.log('===>',err) is never executed meaning the process terminated before the callback was called.

Is this because the bus call is really a C call and the node process can't control the C call terminating the process?

My process is a socket server and I need to guard against sending one packet with a bad set of arguments crashing the server.

Although I had promisfied the call and catching that I even went back to callback style (below) to make sure that wasn't the issue. But I get the same issue either way

return pify(this.i2cbus.writeByte.bind(this.i2cbus))(args.address, args.cmd, _args.byte)_

  write: function (args) {
    return new Promise((resolve) => {
      this.i2cbus.writeByte.bind(this.i2cbus)(args.address, args.cmd, args.byte,
        (err,res) => {
          console.log('===>',err)
          if (err) resolve({error:err.msg})
          resolve(res ||'success')
        })
    })
  }
/opt/uci/uci-i2c-bus/node_modules/i2c-bus/i2c-bus.js:78
  i2c.setAddrAsync(device, addr, bus._forceAccess, function (err) {
          ^

Error: EINVAL, incorrect arguments passed to setAddr(int fd, int addr, bool forceAccess, function cb)
    at /opt/uci/uci-i2c-bus/node_modules/i2c-bus/i2c-bus.js:78:11
    at FSReqWrap.oncomplete (fs.js:149:20)

Native module doesn't compile against Node.js v10.2.0

v10.1 works fine but both my build server and local machine can't install i2c-bus with v10.2. Log:

$ node --version
v10.2.0
$ npm --version
5.6.0
$ npm install

> [email protected] install /home/user/git/node-i2c-adt7420/node_modules/i2c-bus
> node-gyp rebuild

make: Entering directory '/home/user/git/node-i2c-adt7420/node_modules/i2c-bus/build'
  CXX(target) Release/obj.target/i2c/src/i2c.o
In file included from ../src/i2c.cc:1:0:
/home/user/.node-gyp/10.2.0/include/node/node.h:53:10: fatal error: core.h: No such file or directory
 #include "core.h"  // NOLINT(build/include_order)
          ^~~~~~~~
compilation terminated.
make: *** [i2c.target.mk:97: Release/obj.target/i2c/src/i2c.o] Error 1
make: Leaving directory '/home/user/git/node-i2c-adt7420/node_modules/i2c-bus/build'

node-i2c .writeBytes(cmd, bytes) equivalent with i2c-bus ?

Hello,

I totally rewrote adafruit-i2c-lcd which works with node-i2c, because it seems to be broken with latest version of node.js.
I decided to use i2c-bus, but I don't found equivalent of wire.writeBytes(cmd, bytes);
I tried:

var buf = new Buffer(values);
bus.writeI2cBlockSync(this.ADDRESS, cmd, buf.length, buf);

But data length are over 32 bytes and it doesn't works.
Do you have any idea about how can I fix it ?

Thanks guys.

writeQuick

Hi, I'm trying to make all my I2C communication async in my code and I bumped into the following. Please take a look at it, but it could happen that I'm doing something flat-out wrong.

It's about calling writeQuick, I include the test code:
wqtest.txt
and the output of the program:
output.txt

var wqAsync = function () {
    var bus = i2c.openSync(1);
    bus.writeQuick(0x73, 0, function (err) {
        if (err) {
            console.log("no, failed.")
            throw "writeQuick " + err;
        } else {
            console.log("ok, worked.");
            bus.closeSync();
        }
    });
};

And the result is:

/home/pi/.node-red/node_modules/i2c-bus/i2c-bus.js:282
    i2c.writeQuickAsync(device, bit, cb);
        ^

Error: EINVAL, incorrect arguments passed to writeQuick(int fd, int bit, function cb)
    at Error (native)
    at Bus.<anonymous> (/home/pi/.node-red/node_modules/i2c-bus/i2c-bus.js:282:9)
    at /home/pi/.node-red/node_modules/i2c-bus/i2c-bus.js:83:9

Also this little piece of code is supposed to check the I2C device's presence. It works fine - I used the sync version so far - but I want to make sure I understand it properly what I'm doing.
Could you please validate if this pseudo code is the way?

handle one device starts:
open i2cBus - nicely async and pass the instance on
...
device check: writeQuick/Sync a single bit -> then evaluate the the program's condition
and set true or false accordingly.
...
since the device check went through I can start communicating using the device.
... do some I2c comm ...
...
i2cBus.close()
handle one device ends

The real question is that do I have to do anything else after the writeQuick? Somekind of stop communication is needed there to make the target device abort the comm, and ignore the bit we sent as a probe. --- well, if I'm right.

interrupt event - no access to INT pin like in #16

I have a DIO board that uses an MCP23017 and communicates via I2C.
https://www.controleverything.com/content/Digital-IO?sku=MCP23008_MCP23017_I2CDIO2
I want to use all the pins as pullup/interrupt dry contact closures.

so your suggestion in #16 to wire the INTA/B pin of the 23017 to a RPI interrupt capable gio pin and then use that gpio with your on/off library isn't going to work for me.

I'm new to I2C bus. The serial bus library I use emits an event when something shows up on the RX pin. Then you just register a handler and you're off and running. What happens in your library/i2c-bus. Can ic2 slave devices even send bytes onto the bus without a master doing a read?

So....I can infinite read say the read INTF register, then once high I can read INTCAP and figure out which pin changed. Kinda seems silly, polling an interrupt...

Not your problem but can't find anything that says that when 23017 fires an interrupt it not only brings up INT pin(s) high but also sends something out on the I2C bus. If not I am sunk and must do polling. If so how can your library emit an event for that so I can handle it.

This c code seems to do it (over i2c bus?)
https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library/blob/master/examples/interrupt/interrupt.ino

File descriptors for busy devices are leaked

Busy devices are the ones displayed as UU by i2cdetect:

$ i2cdetect -y -r 2
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: -- -- -- -- UU UU UU UU -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
70: -- -- -- -- -- -- -- --                         

ic2-bus.js written as es6 class with promise methods

I wanted to use your prototype cb methods as promises and with a bit of fiddling I got bluebird promisifyAll to do that.

const i2c = require('i2c-bus'),
      pA = require('bluebird').promisifyAll

class Bus {
       constructor(busnum) {
       this.bus = pA(i2c.open(busnum,()=>{}),{suffix: "_p",multiArgs: true})
     }

// add promisifed i2c-bus methods to the class
scan(){ return this.bus.scan_p()}

// TODO add that same for any any other prototype methods I'll need to use.
}

then

const Bus = require('./lib/class/Bus'),
    _u = require('uci-utils')

let bus1 = new Bus(1)

// console.log('\n',bus1)

bus1.scan().then(devs => {
      console.log('devices: ', devs[0].map(_u.dec2hex))  
     // note: response dev is nested array, probably as a result of promisfy multiArgs? 

  }).catch(err=>{console.log(err)})

As you can see I'm kinda writing a Bus class on top of your Bus class to make this work...seems kinda clunky and nonDRY and I'm having to load the entire BB library to do it and promisfy even your sync methods which is silly.

What I can't live without is your bound C library but I would like to fork the main module (i2c-bus.js) and write it as a proper es6 class (given node now supports that directly) with methods all returning promises and probably dropping the sync methods all together.

So I'm willing to write an alternative class/promise module. Are you willing to give me some input/clarification I will need to do that? For example I'm a bit puzzled by the use of the _peripherals key in the constructor. Initially you have it as an empty array it then gets populated later by the prototype methods?? I'm pretty clueless on the whole binding/gyp/nan...etc. thing so I'd be just trying to use the prototype methods in the existing code more or less as is.

Anyway I could do this a separate file/module/class say i2c-pbus.js/pBus. Users could alternatively load this new module (class) that would keep backward compatibility for those using it now. Normally I'd make just make my own personal fork but I'm happy with your C library and not being a C programmer I'm going to want the advantage of your maintenance on that.

Just so you know I looked into wiring-pi node and the other i2c bus library at npm. The first one is a kitchen sink and not well maintained and the second won't even compile on my RPI3 and is also kinda crusty. So ic2-bus is dakind. Thx.

Module did not self-register

System: OS X 10.12.1 (Sierra) (I'm developing on a Mac and will later use the code on a raspberry pi3)
node tested with v6.9.0 && v.7.2.0 (npm 4.0.3)
ic2 1.1.2

Installation worked without complications. As soon as I require the module:

##Code

i2c = require('i2c-bus');

I get the error:

/Users/MasterG/Projekte/1-NODEJS/pi/node_modules/bluebird/js/release/async.js:61
        fn = function () { throw arg; };
                           ^

  Error: Module did not self-register.
  
  - module.js:598 Object.Module._extensions..node
    module.js:598:18
  
  - module.js:488 Module.load
    module.js:488:32
  
  - module.js:447 tryModuleLoad
    module.js:447:12
  
  - module.js:439 Function.Module._load
    module.js:439:3
  
  - module.js:498 Module.require
    module.js:498:17
  
  - module.js:20 require
    internal/module.js:20:19
  
  - bindings.js:76 bindings
    [pi]/[bindings]/bindings.js:76:44
  
  - i2c-bus.js:4 Object.<anonymous>
    [pi]/[i2c-bus]/i2c-bus.js:4:28
  
  - module.js:571 Module._compile
    module.js:571:32
  
  - module.js:580 Object.Module._extensions..js
    module.js:580:10
  
  - module.js:488 Module.load
    module.js:488:32
  
  - module.js:447 tryModuleLoad
    module.js:447:12
  
  - module.js:439 Function.Module._load
    module.js:439:3
  
  - module.js:498 Module.require
    module.js:498:17
  
  - module.js:20 require
    internal/module.js:20:19
  
  - water-sensor.class.js:14 Object.<anonymous>
    /Users/MasterG/Projekte/1-NODEJS/pi/.tmp/serve/backend/sensor/water-sensor.
    class.js:14:9

Problem running on node 4.2.1 and debian Jessie

When trying to the run a simple code I get stuck with it failing.
Any ideas would be welcome.

So far this is my code

var i2c = require('i2c-bus');

var HTS221_ADDR = 0xBF;
var CMD_TEMP_HIGH = 0x2B;
var CMD_TEMP_LOW = 0x2A;
var CMD_HUMID_HIGH = 0x29;
var CMD_HUMID_LOW = 0x28;

module.exports.get = function(cb) {

var i2c1 = i2c.openSync(1);

var rawTemp = i2c1.readByteSync(HTS221_ADDR, CMD_TEMP_HIGH);
console.log(rawTemp);

i2c1.closeSync();

};


i2c.setAddrSync(peripheral, addr);
^

Error: EINVAL, Invalid argument
at Error (native)
at peripheralSync (/home/pi/dev/node/node_modules/raspberry-sensor-sense-hat/node_modules/i2c-bus/i2c-bus.js:89:46)
at Bus.readByteSync (/home/pi/dev/node/node_modules/raspberry-sensor-sense-hat/node_modules/i2c-bus/i2c-bus.js:162:27)
at Object.module.exports.get (/home/pi/dev/node/node_modules/raspberry-sensor-sense-hat/index.js:13:22)
at Object. (/home/pi/dev/node/app.js:8:7)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)

Error: Cannot find module 'i2c-bus' after running our node.js

We hit a weird error(Error: Cannot find module 'i2c-bus'
) even we have done" npm install i2c-bus", we have also checked:
$npm list|grep i2c-bus
├─┬ [email protected]
│ ├─┬ [email protected]
│ ├── [email protected] deduped
any advice would be appreciated.

Error: Cannot find module 'i2c-bus'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object. (/home/pi/Dexter/GrovePi/Software/NodeJS/libs/grovepi.js:2:19)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object. (/home/pi/Dexter/GrovePi/Software/NodeJS/libs/sensors/base/sensor.js:3:20)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)

Most significant bit issue using i2cReadSync

Seeing a strange issue where the MSB is always set in every byte but the first when using i2cReadSync.

For example, reading the firmware version from a SL030 RFID module results in the buffer: <Buffer 0c f0 80 d3 cc b0 b3 b0 ad b4 ae b0>

Bytes 1 and 2 are correct. Byte 3 should be 00. Bytes 4-12 represent an ASCII string of the firmware version, and the value is correct IF the MSB is removed. The expected buffer is: <Buffer 0c f0 00 53 4c 30 33 30 2D 34 2e 30>

Another example: reading the tag information gives a Buffer of <Buffer 07 81 80 fd d6 f5 ec 81>
Here, byte 1 is correct (the length). Bytes 2 and 3 should be 01 and 00. Byte 4 and 5 are correct because the true values should have the MSB set. The rest of the bits mistakenly have their MSB set.

I'm gonna try to dig into the C++, but no promises.... :)

30 byte read limit

Hi,

A lot of MEMS sensors offer a FIFO buffer to allow retrieval of multiple samples in one read which reduces the bandwidth usage, right?

So to speak, this library enforces the standard allowing to read a max of 30 bytes in one operation. Regarding the FIFO buffer feature, this let's me retrieve 5 samples at a time.

However, in many cases, sensors' FIFO buffer can store up to 32 samples to read at a time (which in my case, equals 192 bytes), which can therefore greatly optimize system efficiency.

Is there any approach, with or without this library, that can be used to read more than 30 bytes sequentially, in order to e.g: utilize the FIFO buffer to the fullest?
Or perhaps, for some reason, it's better not to, and thus the standard limit exists?

Thanks!

installed per instructions but no nodes appear?

After appearing to install i2c-bus, I can´t find the nodes even after turning the Rpi off then on. Any suggestions?
I have node.js v0.10.29 and npm v2.15.11
Here is the log:
i@raspberrypi:~ $ cd .node-red
pi@raspberrypi:~/.node-red $ npm install i2c-bus
\

[email protected] install /home/pi/.node-red/node_modules/i2c-bus
node-gyp rebuild

make: Entering directory '/home/pi/.node-red/node_modules/i2c-bus/build'
CXX(target) Release/obj.target/i2c/src/i2c.o
SOLINK_MODULE(target) Release/obj.target/i2c.node
COPY Release/i2c.node
make: Leaving directory '/home/pi/.node-red/node_modules/i2c-bus/build'
[email protected] node_modules/i2c-bus
├── [email protected]
└── [email protected]
pi@raspberrypi:~/.node-red $

wrong read after a while

Hi @fivdi We found an issue with >=2.0.0 (just tested with 3.0.0).
Quite hard to explain.
I have a sensor on my i2c (edison).

export class HTMeter extends i2cMeter {
    getAddress() { return 0x27 }
    constructor(opts?) {
        super(opts);
    }
    readData = (): Promise<{ humidity: number, temperature: number }> => {
        return new Promise((resolve, reject) => {
            let data = new Buffer(4);
            // console.log('HTMeter', 'readData', this.i2c._busNumber, this.address, 0x11, 4);
            try {
                this.i2c.i2cWriteSync(this.address, 0xA0, 2, new Buffer([0x00, 0x00]));
            } catch (e) {
            }
            var delay = 36.65;
            setTimeout(() => {
                try {
                    this.i2c.i2cWriteSync(this.address, 0x80, 2, new Buffer([0x00, 0x00]));
                } catch (e) {
                }
                this.i2c.readI2cBlock(this.address, 0x11, 4, data, function (err, bytesRead, data) {
                    if (err) {
                        reject(err);
                    } else {
                        // First two bytes for humidity
                        // In the range ( 2^14 - 1 )
                        let raw_humidity = ((data[0] & 0x3f) << 8) | data[1];
                        let humidity = raw_humidity / 16382;
                        // Second two bytes for temperature
                        // In the range ( 2^14 - 1 )
                        // Multiply by 165 and subtract 40
                        // Because that is what the documentation says
                        let raw_temperature = ((data[2] << 8) | data[3]) >> 2;
                        let temperature = (raw_temperature / 16382) * 165 - 40;
                        resolve({
                            temperature: Math.round(temperature * 1000) / 1000,
                            humidity: Math.round(humidity * 1000) / 1000
                        });
                    }
                });
            }, delay);
        });
    }
}

the first read value are wrong. If i refresh quickly then the value gets right. If i keep on in continuous, it works perfectly.
But as soon as i pause and wait to read a new value, it gets wrong again

So:
-read :wrong
-read:good
-read:good
...

And
-read: wrong

  • wait...
    -read :wrong
    -read: good
  • wait....
    -read:wrong
    -read: good
    .....

This does not happen with 1.2.5

EDIT: to help i got the buffer when wrong and good. They represent the same sensor data
wrong: <Buffer 7f ff ff fd>
good: <Buffer 53 56 5f 75>

Use in Node-Red

Hi

In order to test your I2c code (having seen onoff in action thanks to node-red-contrib-opi-gpio)

I thought I'd run a test.... in node red. So in the settings file I did the usual - as you can't REQUIRE in node-red itself....

At the start of settings I added i2c in the same way I add filesystem

var fs = require("fs");
var i2c = require("i2c-bus");

And further down I make it available in the same way I do with filesystem...

functionGlobalContext: {
    os:require('os'),
    moment:require('moment'), 
    fs:require('fs'), 
    i2c:require("i2c-bus"),
    mySettings:mySettings 
},

And all of that is fine - Node-Red starts up wonderfully..

However in taking your example.... and putting it in a function in Node-red

var i2c=global.get("i2c");
i2c1 = i2c.openSync(1);

var DS1621_ADDR = 0x48,
CMD_ACCESS_CONFIG = 0xac,
CMD_READ_TEMP = 0xaa,
CMD_START_CONVERT = 0xee;

function toCelsius(rawTemp) {
var halfDegrees = ((rawTemp & 0xff) << 1) + (rawTemp >> 15);

if ((halfDegrees & 0x100) === 0) {
return halfDegrees / 2; // Temp +ve
}

etc as per your example,,, I get the dreaded permissions issue.

30 Jul 14:01:46 - [info] Started modified nodes
30 Jul 14:01:52 - [error] [function:ded5b043.8072a] Error: EACCES: permission denied, open '/dev/i2c-1'

Looks to me like Node-Red is understanding this just fine - but is not allowed to access it. In the onoff situation - a 99 file was required to ensure access for Node-Red..

Here's what was needed for GPIO. Any idea of an equivalent that might be needed to enable pi access to the I2c???

User setup
To meet these requirements for user pi, run this commands as root: Check if user pi belongs to gpio:

$ groups pi
Otherwise, run this:

$ addgroup gpio
$ usermod -a -G gpio pi
If pi is not allowed to use GPIO now, additional steps are required:

Kernel Setup
Create a new file:

$ touch /etc/udev/rules.d/99-com.rules
copy this text to the file:

KERNEL=="gpio*", RUN="/bin/sh -c 'chgrp -R gpio /sys/%p /sys/class/gpio && chmod -R g+w /sys/%p /sys/class/gpio'"
and do a reboot.

3.0.0 wont build

I can't build 3.0.0
I get those errors:

In file included from ../src/i2c.cc:96:0:
../src/./readbyte.cc: In member function 'virtual void ReadByteWorker::HandleOKCallback()':
../src/./readbyte.cc:34:29: error: 'async_resource' was not declared in this scope
     callback->Call(2, argv, async_resource);

I don't see where async_resource is defined

ramdom bitfilp in data read from bno055 i2c sensor

Hi
I am using raspberry pi zero w (bcm2835) to which i am connecting a bno055 sensor, using readByteSync() to read from the sensor, I experience an odd behavior: somehow in a random way some values have their most significant bit flipped from zero to 1 although the data is being correctly sent from the sensor when I check it using the data analyzer. i am using node 8.x in Raspbian stretch lite 03-2018.

Interrupt based callback?

I am trying to use this for MCP23017. How do I set a interrupt based callback. I need to get the onchange callback .

Installing the i2c-bus on Windows 10

Hi, i try to install this lib on my windows system but i get the following error.
Did you try to install this on a windows system?

C:\...\.node-red\node_modules\i2c-bus>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild ) else (node "" rebuild ) Warning: unrecognized setting VCCLCompilerTool/CompileAsWinRT Warning: unrecognized setting VCCLCompilerTool/CompileAsWinRT De projecten in deze oplossingen worden één voor één opgebouwd. Als u parallelle bouwbewerkingen wilt inschakelen, gebruikt u de schakeloptie /m. MSBUILD : error MSB3428: kan het Visual C++-onderdeel VCBuild.exe niet laden. U kunt dit oplossen door 1) de .NET Framework 2.0 SDK te installeren, 2) Microso ft Visual Studio 2005 te installeren of 3) de locatie van het onderdeel toe te voegen aan het systeempad, als het onderdeel elders is geïnstalleerd. [C:\...\.node-red\node_modules\i2c-bus\bu..ild\binding.sln] gyp ERR! build error gyp ERR! stack Error: C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:276:23)
gyp ERR! stack at emitTwo (events.js:106:13)
gyp ERR! stack at ChildProcess.emit (events.js:191:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:219:12)
gyp ERR! System Windows_NT 10.0.15063
gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\niels.node-red\node_modules\i2c-bus
gyp ERR! node -v v6.11.4
gyp ERR! node-gyp -v v3.4.0
gyp ERR! not ok
npm WARN [email protected] No repository field.
npm WARN [email protected] No license field.
npm ERR! Windows_NT 10.0.15063
npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "install" "i2c-bus"
npm ERR! node v6.11.4
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: node-gyp rebuild
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the i2c-bus package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs i2c-bus
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls i2c-bus
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! C:....\npm-debug.log`

mcp23017 examples

Hi, can you add an example of working with mcp23017?

  1. Recording, reading gpio.
  2. Reading dh11 sensors.

scanSync() - enhancement

like to have two parameter to pass own search range

Bus.prototype.scanSync = function (first_addr,last_addr) {
  var scanBus = openSync(this._busNumber, {forceAccess: this._forceAccess}),
    addresses = [],
    addr;

  var firstAddr = first_addr || FIRST_SCAN_ADDR;
  var lastAddr = last_addr || LAST_SCAN_ADDR;

  for (addr = firstAddr; addr <= lastAddr; addr += 1) {
    try {
      scanBus.receiveByteSync(addr);
      addresses.push(addr);
    } catch (ignore) {
    }
  }

  scanBus.closeSync();
  return addresses;
};

What do you think?

Not sure if you like the var names and code style, so I did not create a pull request.

Installation Issue

Hi
I am trying to install i2c-bus module. But I am getting following error

> [email protected] install /home/pi/Desktop/gg/node_modules/i2c-bus
> node-gyp rebuild

gyp ERR! Completion callback never invoked! 
gyp ERR! System Linux 4.1.14-v7+
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/pi/Desktop/gg/node_modules/i2c-bus
gyp ERR! node -v v0.10.0
gyp ERR! node-gyp -v v3.2.1
gyp ERR! This is a bug in `node-gyp`.
gyp ERR! Try to update node-gyp and file an Issue if it does not help:
gyp ERR!     <https://github.com/nodejs/node-gyp/issues>
npm WARN enoent ENOENT, open '/home/pi/Desktop/gg/package.json'
npm WARN gg No description
npm WARN gg No repository field.
npm WARN gg No README data
npm WARN gg No license field.
npm ERR! Linux 4.1.14-v7+
npm ERR! argv "node" "/usr/local/bin/npm" "install" "i2c-bus"
npm ERR! node v0.10.0
npm ERR! npm  v3.5.3
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 6
npm ERR! 
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the i2c-bus package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs i2c-bus
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls i2c-bus
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:

Communication problem with SHT25 sensor

Hi Brian!
I’m trying to implement your I2C serial bus access for Node.js to communicate with SHT25 sensor on Raspberry PI 3
(https://www.sensirion.com/fileadmin/user_upload/customers/sensirion/Dokumente/2_Humidity_Sensors/Sensirion_Humidity_Sensors_SHT25_Datasheet.pdf)
but I don't understand where i'm doing wrong!

This is my edit version of your original code! The error is already at the call of the writeByteSync method.

var i2c = require('i2c-bus'),
  i2c1 = i2c.openSync(1);

var SHT25_ADDR = 0x40,
  CMD_ACCESS_CONFIG = 0xF3;

function toCelsius(rawTemp) {
  var halfDegrees = ((rawTemp & 0xff) << 1) + (rawTemp >> 15);

  if ((halfDegrees & 0x100) === 0) {
    return halfDegrees / 2; // Temp +ve
  }

  return -((~halfDegrees & 0xff) / 2); // Temp -ve
}

(function () {
  var rawTemp;

  console.log('start writeByteSync:');

  // Enter one shot mode (this is a non volatile setting)
  i2c1.writeByteSync(SHT25_ADDR, CMD_ACCESS_CONFIG, 0x01);

}());

This is the error generated:

/home/pi/Documents/node_js_projects/i2c/i2c-bus/node_modules/i2c-bus/i2c-bus.js:257
  i2c.writeByteSync(peripheralSync(this, addr), cmd, byte);
      ^
Error: , Remote I/O error
    at Bus.writeByteSync (/home/pi/Documents/node_js_projects/i2c/i2c-bus/node_modules/i2c-bus/i2c-bus.js:257:7)
    at /home/pi/Documents/node_js_projects/i2c/i2c-bus/i2c-bus.js:24:8
    at Object.<anonymous> (/home/pi/Documents/node_js_projects/i2c/i2c-bus/i2c-bus.js:26:2)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)

I don't know if this will help or not, this is the python code that works perfectly.
https://github.com/ControlEverythingCommunity/SHT25/blob/master/Python/SHT25.py

I'm hoping you can help me!
Thanks in advance!

write method error

Hi, i'm trying to use you module to connect a raspberryPi with a i2c temperature sensor (sht21)
My problem is that i've got this error when i try to write the first command:

buffer.js:246
switch (encoding && encoding.toLowerCase()) {
^
TypeError: Object 1 has no method 'toLowerCase'

here is my code, it seems that the error is on the length parameter

ar i2c = require('i2c-bus'),
i2c1 = i2c.openSync(1);

var tm = 0x40,
bff = new Buffer(4);
bff = 0xF3;

i2c1.i2cWrite(tm, 1, bff, function(err, bytesWritten,buffer) {
console.log(err);
});

thanks

32 byte limitation

I need to send payloads with more than 32 bytes to a connected peripheral (using raspi-i2c). The peripheral speaks plain I2C, not SMBus.

Unfortunately, the I2C methods provided seem to be hardwired to use the SMBus functions, in particular they all seem to fall back to i2c_smbus_access in the end.

Is it somehow possible to use plain I2C without the 32 byte limitation? According to this post http://stackoverflow.com/a/25984891, the Linux kernel seems to be able to send longer I2C packets when not using SMBus.

What would be the easiest way of sending longer packets using i2c-bus (and raspi-i2c)?

w1_ds28e17 interoperarability issue when using scan or scanSync functions

The DS28E17 chip from Maxim is a 1-Wire to I2C bridge - details here:
https://www.maximintegrated.com/en/products/interface/controllers-expanders/DS28E17.html

A kernel driver for Linux has been created by Jan Kandziora, and we are using this on Raspbian Jessie 4.4.22 with great results - details here: https://github.com/ianka/w1_ds28e17

This presents an additional i2c device in Linux, in our case /dev/i2c-3, which can be addressed using the i2c-bus library. When doing a bus scan, i2c-bus tries a I2C_FUNC_SMBUS_READ_BYTE on each slave address in turn, from 0x03 through to 0x77. The native i2c device /dev/i2c-1 replies with an EIO error code for unoccupied slave addresses, but the w1_ds28e17 replies with ENXIO, which causes the i2c-bus library to throw an exception. I have discussed this with Jan, and agree with him that this is in fact correct behaviour - see the points he makes below:

_"linux/Documentation/i2c/fault-codes says:

ENXIO
Returned by I2C adapters to indicate that the address phase
of a transfer didn't get an ACK. While it might just mean
an I2C device was temporarily not responding, usually it
means there's nothing listening at that address.

Returned by driver probe() methods to indicate that they
found no device to bind to. (ENODEV may also be used.)

So I have to assume returning ENXIO is correct behaviour. I'm pretty sure the other drivers will get patched someday.

The reason why w1_ds28e17 doesn't return EIO on I2C addressing failed is the w1 subsystem returns EIO when addressing the DS28E17 fails. If both returned the same error code, you had no chance to find out if it was the DS28E17 missing or the I2C slave."_

Would you consider amending the i2c-bus library behaviour to ignore returned ENXIO error codes in these circumstances ?

Can't force I2C bus commands

The standard Linux i2cget and i2cset tools (from i2c-tools) includes a -f flag that allows commands to be forced. This is used when the I2C device is managed by a kernel device driver (i2cdetect shows UU for that device). This library doesn't include equivalent functionality, hence some devices are not accessible in the same manner that can be achieved from the command line.

An example use case is a real-time clock (RTC) device at 0x68 which is used by the OS RTC module, but where you might want to set an alarm or read the RTC temperature in your application.

I have determined that this is is handled by the i2cget/i2cset commands by a change to the ioctl command as shown in line 408 of i2cbusses.c from i2c-tools. See
https://fossies.org/dox/i2c-tools-3.1.2/i2cbusses_8c_source.html
The ioctl passes either I2C_SLAVE_FORCE or I2C_SLAVE

I have also identified that the i2c-bus library's SetAddr function in setaddr.cc only passes I2C_SLAVE, no force option exists.

Could the library be extended to include an optional force flag on the i2cWrite / i2cRead set of functions so that full functionality can be achieved ?

I guess that the documentation should also include a suitable warning about fiddling with kernel owned devices if this option is used. The wording in the i2cset/i2cget commands is as follows :

Force access to the device even if it is already busy. By default, i2cset will refuse to access a device which is already under the control of a kernel driver. Using this flag is dangerous, it can seriously confuse the kernel driver in question. It can also cause i2cset to silently write to the wrong register. So use at your own risk and only if you know what you're doing.

Problem installing on node 0.10.38

I am attempting to install i2c-bus on beaglebone black with nodejs v0.10.38 installed. At this stage, I am not able to update nodejs due to product life-cycle.

When running npm install i2c-bus I get the error (as stated in readme) even though nodejs should be working solution.

> [email protected] install /opt/project/node_modules/i2c-bus
> node-gyp rebuild

make: Entering directory `/opt/project/node_modules/i2c-bus/build'
  CXX(target) Release/obj.target/i2c/src/i2c.o
In file included from ../src/i2c.cc:2:0:
../node_modules/nan/nan.h:330:47: error: ‘REPLACE_INVALID_UTF8’ is not a member of ‘v8::String’
make: *** [Release/obj.target/i2c/src/i2c.o] Error 1
make: Leaving directory `/opt/project/node_modules/i2c-bus/build'
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/share/node-gyp/lib/build.js:267:23)
gyp ERR! stack     at ChildProcess.emit (events.js:98:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:820:12)
gyp ERR! System Linux 3.8.13-bone68b
gyp ERR! command "nodejs" "/usr/bin/node-gyp" "rebuild"
gyp ERR! cwd /opt/project/node_modules/i2c-bus
gyp ERR! node -v v0.10.38
gyp ERR! node-gyp -v v0.12.2
gyp ERR! not ok 
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

Note that I am running node v0.10.38 which is stated should work.

Reset i2c data address

I am new to i2c communication protocol and am still getting the hang of it so sorry if this question is simple.

I have a Angstrom device where my team finally got the EEPROM working correctly. I am able to use i2cdetect, i2cset and i2cget perfectly. From my understanding i2cget will only read one byte from the current data address you are at and will increment the data address with every call. i2cset will reset the data address to where ever you write to. So for example 'i2cset -y 2 0x01 0x00 0x00 i' will reset the data address to the beginning where ic2get can be used. This seems completely different than the implementation of i2c-bus where you are able to give the command code (which is what I am assuming is the data address?). When I try those it doesn't work at all and seems to read from unknown data address. If I reset the data address with i2cset before running the node process it works better but still skips the first byte for some reason. This happens with both bus.readI2cBlock and bus.readByte.

If I use bus.i2cRead though I am able to read correctly from the start of the EEPROM data. My main question though is how do I reset the data address to the beginning programmatically without having to call i2cset before running the node process.

Remove substring "i2c" from names

old name new name
i2cFuncs funcs
i2cFuncsSync funcsSync
i2cRead read
i2cReadSync readSync
i2cWrite write
i2cWriteSync writeSync
readI2cBlock readBlock
readI2cBlockSync readBlockSync
writeI2cBlock writeBlock
writeI2cBlockSync writeBlockSync
I2cFuncs funcs

Use of CMD parameter

Hi,

I had a few questions which are unclear from the documentation. I was hoping you could help clarify.

  1. What is the command parameter used for in functions such as bus.writeByte(addr, cmd, byte, cb)
  2. What is the difference between sendByte and writeByte
  3. What is the difference between plain i2c and SMBus?

Refactor Error objects

Currently Error objects generated by i2c-bus only contain a message property. This can result in code that needs to examine the message strings in order to determine what to do. Code like this:

      scanBus.receiveByte(addr, function (err) {
        if (err) {
          if (err.message !== 'Remote I/O error' &&
              err.message !== 'Input/output error' &&
              err.message !== 'Device or resource busy') {
            return cb(err);
          }
        } else {
          addresses.push(addr);
        }

        next(addr + 1);
      });

and this:

    try {
      scanBus.receiveByteSync(addr);
      addresses.push(addr);
    } catch (e) {
      if (e.message !== 'Remote I/O error' &&
          e.message !== 'Input/output error' &&
          e.message !== 'Device or resource busy') {
        throw e;
      }
    }

Error objects should contain message, errno, code, and syscall properties in order to make it possible to write code like this:

      scanBus.receiveByte(addr, function (err) {
        if (err) {
          if (err.errno !== EIO &&
              err.errno !== EREMOTEIO &&
              err.errno !== EBUSY) {
            return cb(err);
          }
        } else {
          addresses.push(addr);
        }

        next(addr + 1);
      });

and this:

    try {
      scanBus.receiveByteSync(addr);
      addresses.push(addr);
    } catch (e) {
      if (e.errno !== EIO &&
          e.errno !== EREMOTEIO &&
          e.errno !== EBUSY) {
        throw e;
      }
    }

What am I doing wrong with this code.

I am trying to write 2 bytes to the beaglebone black via the johnny-five plugin beaglebone-io.
I am getting an error I don't understand. Converting the array of numbers to an array of strings results in the same error.

// at the top of the file I have:
var i2c = require('i2c-bus'),
    i2c1 = i2c.openSync(1);

// my i2c write function
BeagleBone.prototype.sendI2CWriteRequest = function(address, bytes) {

  console.log("i2c write bytes: address = " + address + " bytes = " + bytes) ;
  console.log("element type = " + typeof bytes[0]);

  i2c1.i2cWriteSync(address, bytes.length, bytes);

  return this;
};



And here is the error output I am getting:

>> i2c write bytes: address = 30 bytes = 0,112
element type = number

buffer.js:246
  switch (encoding && encoding.toLowerCase()) {
                               ^
TypeError: Object 2 has no method 'toLowerCase'
    at Function.Buffer.isEncoding (buffer.js:246:32)
    at assertEncoding (fs.js:112:27)
    at Object.fs.writeSync (fs.js:525:5)
    at Bus.i2cWriteSync (/home/debian/node_modules/i2c-bus/i2c-bus.js:261:13)
    at BeagleBone.sendI2CWriteRequest (/home/debian/node_modules/beaglebone-io/lib/beaglebone.js:367:8)
    at Compass.<anonymous> (/home/debian/node_modules/johnny-five/lib/compass.js:79:13)
    at Array.forEach (native)
    at new Compass (/home/debian/node_modules/johnny-five/lib/compass.js:78:9)
    at Board.<anonymous> (/home/debian/compass.js:14:13)
    at Board.EventEmitter.emit (events.js:95:17)

Native module does not compile against node 10.4.1

Relevant logs (i think?) from trying to npm install:

> node-gyp rebuild

make: Entering directory '/home/rektide/src/hearty-wonder-light/node_modules/i2c/build'
  CXX(target) Release/obj.target/i2c/src/i2c.o
In file included from ../../nan/nan.h:190:0,
                 from ../src/i2c.cc:3:
../../nan/nan_maybe_43_inl.h: In function ‘Nan::Maybe<bool> Nan::ForceSet(v8::Local<v8::Object>, v8::Local<v8::Value>, v8::Local<v8::Value>, v8::PropertyAttribute)’:
../../nan/nan_maybe_43_inl.h:88:15: error: ‘class v8::Object’ has no member named ‘ForceSet’
   return obj->ForceSet(GetCurrentContext(), key, value, attribs);
               ^~~~~~~~

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.