Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,38 @@ wire.read(length, function(err, res) {


````
## Usage with async/await

```javascript
const i2c = require('i2c');
const address = 0x18;
const wire = new i2c(address, {device: '/dev/i2c-1'});

(async () => {
try {
const data = await wire.scanAsync();
// result contains an array of addresses

await wire.writeByteAsync(byte);

await wire.writeBytesAsync(command, [byte0, byte1]);

const byte = await wire.readByteAsync();
// result is single byte

const bytes = await wire.readBytesAsync(command, length);
// result contains a buffer of bytes

// plain read/write
await wire.writeAsync([byte0, byte1]);

const buffer = await wire.readAsync(length);
// result contains a buffer of bytes
} catch (err) {
// handle errors
}
})();
```

## Raspberry Pi Setup

Expand Down
10 changes: 10 additions & 0 deletions lib/i2c.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const wire = require('../build/Release/i2c');
const { EventEmitter } = require('events');
const { promisify } = require('util');
const tick = setImmediate || process.nextTick;

class i2c extends EventEmitter {
Expand Down Expand Up @@ -36,6 +37,15 @@ class i2c extends EventEmitter {
this.setAddress(this.address);
}
});

this.scanAsync = promisify(this.scan).bind(this);
this.openAsync = promisify(this.open).bind(this);
this.writeAsync = promisify(this.write).bind(this);
this.writeByteAsync = promisify(this.writeByte).bind(this);
this.writeBytesAsync = promisify(this.writeBytes).bind(this);
this.readAsync = promisify(this.read).bind(this);
this.readByteAsync = promisify(this.readByte).bind(this);
this.readBytesAsync = promisify(this.readBytes).bind(this);
}

scan(callback) {
Expand Down