Instantly share code, notes, and snippets.

@MaBecker /PCF8574.js Secret
Last active Jan 10, 2019

Embed
What would you like to do?
Espruino module for I2C device PCF8574
/*
Created a module for the GPIO extender PCF8574X.
Like to share it to get some feed back and fixes before it is added to EspruinoDocs as a new device.
```
const SCL = < SCL pin >;
const SDA = < SDA pin>;
const INT = < interrupt pin >;
const IN = 0; // to define device as input
const OUT = 1; // to define device as output
I2C1.setup({sda:SDA,scl:SCL});
// use extender as input device with interrupt
var extenderIn = require("PCF8574X")(I2C1,56, IN, true);
// read value of all pins
console.log("values for all pins:", extenderIn.read());
// read value of a single pin
console.log("value for pin 0:", extenderIn.readPin(0);
// enable interrupt
// extenderIn.enableINT(<callback> ,<interrupt pin>);
extenderIn.enableINT(function(){console.log("value changed");},INT);
// use extender as input device
var extenderOut = require("PCF8574X")(I2C1,32, OUT, true);
extenterOut.write(255);
```
*/
class PCF8574X {
constructor(i2c, i2ca, mode) {
this.i2c = i2c;
this.i2ca = i2ca;
this.mode = ( typeof(mode) === "undefined" ? 1 : mode);
// stuff for watching interrupt
this.watchPin = null;
this.callback = null;
this.id = 0;
}
write(val){
if ( this.mode )
this.i2c.writeTo( this.i2ca, val ^ 255 );
}
writePin(pin, val) {
val = !val + 0;
if ( this.mode ) {
var value = this.i2c.readFrom(this.i2ca,1)[0];
if ( val )
this.i2c.writeTo(this.i2ca, value | 1 << pin );
else
this.i2c.writeTo(this.i2ca, value & ~(1 << pin));
}
}
read(){
var val;
if ( !this.mode ) {
val = this.i2c.readFrom(this.i2ca,1)[0];
return val^255;
}
}
readPin(pin) {
var val;
if ( !this.mode ) {
val = ((this.i2c.readFrom(this.i2ca,1)[0]>>pin) % 2 );
return ! val + 0;
}
}
enableINT(callback, pin) {
if ( !this.mode ) {
this.watchPin = pin;
this.callback = callback;
this.id = setWatch( this.callback,
this.watchPin,
{ repeat : true, edge : 'falling', debounce : 10 }
);
}
}
disableINT() {
if ( !this.mode ) {
if ( this.id ) {
clearWatch( this.id );
this.watchPin = null;
this.callback = null;
this.id = 0;
}
}
}
}
exports = PCF8574X;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment