I’m trying to use an IO Expander with this setup:
And my code:
`// Relay Control Unit
// IO Expander Class for SX1509
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
server.log("booting");
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));
}
}
// Port mapping
// io4 - 1 - k1 off
// io5 - 2 - k1 on
// io6 - 3 - k2 off
// io7 - 4 - k2 on
// io0 - 5 - k3 off
// io2 - 6 - k3 on
// address = 0x20
// RGB LED Class
class Relay extends IoExpander {
// IO Pin assignments
a = [4,5,6,7,0,2];
onPort = [5, 7, 2];
offPort = [4, 6, 0];
constructor() {
base.constructor(I2C_89, 0x20);
//c = 3;
// read(0x00); //should be 0xff
server.log(read(0x00));
write(0x00, 0x00); //RegData - set all pins to low
read(0x00); //should be 0x00
server.log(read(0x00));
write(0x01, 0x00); //Direction - set all as output
}
function relayOn(relay) {
server.log("ON "+relay);
write(0x00, onPort[relay]);
imp.sleep(0.1);
write(0x00, 0x00);
}
function relayOff(relay) {
write(0x00, offPort[relay]);
imp.sleep(0.1);
write(0x00, 0x00);
}
}
// Construct Interface
relay <- Relay();
function test() {
server.log(“test”);
relay.relayOn(0);
relay.relayOn(1);
relay.relayOn(2);
}
// Register with the server
imp.configure(“Relay Control”, [], []);
test();
`
It doesn’t seem to be working, and when I tried the read command, I got an error. Looking at the I2C lines using a logic analyzer I see both pins constantly high and nothing seems to happen. As I have no way to see what the internal I2C code is doing, I don’t know how to proceed with my debugging. Any thoughts?
Reza
p.s. This syntax doesn’t seem to work
c = relay.read(0x00);
system.log(“output=”+c);
it gives me an error like c is undefined or something… it works fine like this…
system.log(“output=”+relay.read(0x00));