The code uses the port A on MCP, sets the port to output and sends values from 0 to 255.
Thanks to gerardwr for pointing out the reset problem - if the for-loop is running too long, the watchdog kicks in and reboots the whole ESP.
Here is the code for steps from 0 to 255:
id=0
sda=8
scl=9
-- initialize i2c, set pin1 as sda, set pin0 as scl
i2c.setup(id,sda,scl,i2c.SLOW)
-- user defined function: read from reg_addr content of dev_addr
function read_reg(dev_addr, reg_addr)
i2c.start(id)
i2c.address(id, dev_addr ,i2c.TRANSMITTER)
i2c.write(id,reg_addr)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr,i2c.RECEIVER)
c=i2c.read(id,1)
i2c.stop(id)
return c
end
function write_reg(dev_addr, reg_addr, reg_val)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, reg_addr)
i2c.write(id, reg_val)
i2c.stop(id)
end
-- get content of register 0xAA of device 0x77
write_reg(0x20, 0x00, 0x00) -- set bank A to output
for i=0,255 do
print("Setting bank A to value " .. i)
write_reg(0x20, 0x12, i)
tmr.delay(100000)
tmr.wdclr()
end
Just for fun, I made a small K.I.T.T. animation using timer function - fair warning, you will have to reset the device to get out of the loop
id=0
sda=8
scl=9
-- initialize i2c, set pin1 as sda, set pin0 as scl
i2c.setup(id,sda,scl,i2c.SLOW)
-- user defined function: read from reg_addr content of dev_addr
function read_reg(dev_addr, reg_addr)
i2c.start(id)
i2c.address(id, dev_addr ,i2c.TRANSMITTER)
i2c.write(id,reg_addr)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr,i2c.RECEIVER)
c=i2c.read(id,1)
i2c.stop(id)
return c
end
function write_reg(dev_addr, reg_addr, reg_val)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, reg_addr)
i2c.write(id, reg_val)
i2c.stop(id)
end
-- get content of register 0xAA of device 0x77
write_reg(0x20, 0x00, 0x00) -- set bank A to output
i = 1
dir = 1
print("")
tmr.alarm(250,1,function()
write_reg(0x20, 0x12, i)
print("I = " .. i)
dir = (i == 1) and (dir == -1) and 1 or (i == 128) and (dir == 1) and -1 or dir
i = (dir == 1) and i * 2 or i / 2
end
)
The electrical connection for MCP23017:
Pin 9 (VDD) to 3v3
Pin 10 (VSS) to GND
Pin 12 (SCL) to ESP GPIO2
Pin 13 (SDA) to ESP GPIO0
Pin 15 (A0) to GND
Pin 16 (A1) to GND
Pin 17 (A2) to GND
Pin 18 (nRESET) to 3v3
Enjoy!