Skip to content

Instantly share code, notes, and snippets.

@NicolSpies
Created February 23, 2016 10:05
Show Gist options
  • Select an option

  • Save NicolSpies/a7468ca6939a4839d3ba to your computer and use it in GitHub Desktop.

Select an option

Save NicolSpies/a7468ca6939a4839d3ba to your computer and use it in GitHub Desktop.
GPIO Test Code
pin=2
local function i2cInit()
-- init MCP23008 GPIO expander for led & pushbutton control
i2c.setup(0,4,3,i2c.SLOW) --i2c init
i2cWrite(0x00,0xe0) --0x00 IODIR, 0xf8 = 1110 0000 sets GPIO inputs and outputs
i2cWrite(0x06,0xe0) --0x06 GPPU, 0xf8 = 1110 0000 sets GPIO pull up resistors
i2cWrite(0x09,0xe0) --0x09 GPIO, 0xf8 = 1110 0000 inputs pins high, outputs pins low
i2cWrite(0x02,0xe0) --0x02 GPINTEN, 0xe0 = 1110 0000 1=pin enable for interrupts
i2cWrite(0x03,0xe0) --0x03 DEFVAL, 0xf8 = 1110 0000 values with no buttons pushed
i2cWrite(0x04,0xff) --0x04 INTCON, 0xe0 = 1111 1111 compared against DEFVAL on interrupt
--i2cWrite(0x05,0x28) --0x05 IOCON, 0xe8 = 0000 1000
end
local function i2cRead(registerAddress)
--Reads byte from register
local id=0
i2c.start(id)
i2c.address(id,32,i2c.TRANSMITTER) -- send MCP's address and write bit
i2c.write(id,registerAddress)
i2c.stop(id)
i2c.start(id)
-- Read the data form the register
i2c.address(id,32,i2c.RECEIVER) -- send the MCP's address and read bit
local data = 0x00
data = i2c.read(id,1) -- we expect only one byte of data
i2c.stop(id)
return string.byte(data) -- i2c.read returns a string e convert to it's int value
end
function i2cWrite(registerAddress, data)
--Writes one byte (data) to a register, return void
local id=0
i2c.start(id)
i2c.address(id,32,i2c.TRANSMITTER) -- send MCP's address and write bit
i2c.write(id,registerAddress)
i2c.write(id,data)
i2c.stop(id)
end
local function IOInit()
print("I/O Init")
gpio.mode(pin, gpio.INT) -- GPIO 4 configured for interrupt mode
end
local function readi2c(level)
local val = i2cRead(0x07)
i2cRead(0x09)
print(val)
end
i2cInit()
IOInit()
gpio.trig(pin, "low" , function(level) readi2c(level) end)
--gpio.trig(pin, "low" , function(level) print("low") end)
--gpio.trig(pin, "down" , function(level) print("down") end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment