Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

114 lines (97 sloc) 2.619 kb
// IO Expander Class for SX1509
//
// Used as a basis expansion port handler for the Electric Imp Hannah Boards
//
class IoExpander
{
i2cPort = null;
i2cAddress = null;
constructor(port, address)
{
if(port == I2C_12)
{
// Configure I2C bus on pins 1 & 2
hardware.configure(I2C_12);
i2cPort = hardware.i2c12;
}
else if(port == I2C_89)
{
// Configure I2C bus on pins 8 & 9
hardware.configure(I2C_89);
i2cPort = hardware.i2c89;
}
else
{
server.log("Invalid I2C port specified.");
}
i2cAddress = address << 1;
}
// Read a byte
function read(register)
{
local data = i2cPort.read(i2cAddress, format("%c", register), 1);
if(data == null)
{
server.log("I2C Read Failure");
return -1;
}
return data[0];
}
// Write a byte
function write(register, data)
{
i2cPort.write(i2cAddress, format("%c%c", register, data));
}
// Write a bit to a register
function writeBit(register, bitn, level)
{
local value = read(register);
value = (level == 0)?(value & ~(1<<bitn)):(value | (1<<bitn));
write(register, value);
}
// Write a masked bit pattern
function writeMasked(register, data, mask)
{
local value = read(register);
value = (value & ~mask) | (data & mask);
write(register, value);
}
// Set a GPIO level
function setPin(gpio, level)
{
writeBit(gpio>=8?0x10:0x11, gpio&7, level?1:0);
}
// Set a GPIO direction
function setDir(gpio, output)
{
writeBit(gpio>=8?0x0e:0x0f, gpio&7, output?0:1);
}
// Set a GPIO internal pull up
function setPullUp(gpio, enable)
{
writeBit(gpio>=8?0x06:0x07, gpio&7, enable);
}
// Set GPIO interrupt mask
function setIrqMask(gpio, enable)
{
writeBit(gpio>=8?0x12:0x13, gpio&7, enable);
}
// Set GPIO interrupt edges
function setIrqEdges(gpio, rising, falling)
{
local addr = 0x17 - (gpio>>2);
local mask = 0x03 << ((gpio&3)<<1);
local data = (2*falling + rising) << ((gpio&3)<<1);
writeMasked(addr, data, mask);
}
// Clear an interrupt
function clearIrq(gpio)
{
writeBit(gpio>=8?0x18:0x19, gpio&7, 1);
}
// Get a GPIO input pin level
function getPin(gpio)
{
return (read(gpio>=8?0x10:0x11)&(1<<(gpio&7)))?1:0;
}
}
Jump to Line
Something went wrong with that request. Please try again.