mcp23017_example.lua 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. --[[
  2. This example demonstrates how to use the different functions of the mcp23017 lua module.
  3. @author Marcel P. | Plomi.net
  4. @github https://github.com/plomi-net
  5. @version 1.0.0
  6. ]]
  7. --[[
  8. initialize and setup
  9. ]]
  10. -- initialize module
  11. local mcp23017 = require "mcp23017"
  12. local address = 0x20 -- the address for MCP23017 (between 0x20 and 0x27)
  13. local cSCL = 1 -- SCL pin = 1 = D1 / GPIO 5 (ESP8266)
  14. local cSDA = 2 -- SDA pin = 2 = D2 / GPIO4 (ESP8266)
  15. local i2cId = 0 -- i2c id
  16. -- setup i2c bus and create instance for mcp23017 (assigned to mcp)
  17. i2c.setup(i2cId, cSDA, cSCL, i2c.SLOW)
  18. local mcp = mcp23017(address, i2cId)
  19. --[[
  20. set output and input channels
  21. ]]
  22. -- set pin 7 and 8 to output (GPA7 and GPB0) and GPB1 to input
  23. mcp:setMode(mcp.GPA, 7, mcp.OUTPUT)
  24. mcp:setMode(mcp.GPB, 0, mcp.OUTPUT)
  25. mcp:setMode(mcp.GPB, 1, mcp.INPUT)
  26. --[[
  27. set output channels to high and low
  28. ]]
  29. -- set pin 7 to high (GPA7)
  30. mcp:setPin(mcp.GPA, 7, mcp.HIGH)
  31. -- set pin 8 to low (GPB0)
  32. mcp:setPin(mcp.GPB, 0, mcp.LOW)
  33. --[[
  34. toggle pin 6 channel state every second (blinking)
  35. ]]
  36. local currentPin = 6
  37. local currentReg = mcp.GPA
  38. local currentState = false
  39. mcp:setMode(currentReg, currentPin, mcp.OUTPUT)
  40. tmr.create():alarm(1000, tmr.ALARM_AUTO, function()
  41. if currentState == true then
  42. -- print("set to low")
  43. mcp:setPin(currentReg, currentPin, mcp.LOW)
  44. currentState = false
  45. else
  46. -- print("set to high")
  47. mcp:setPin(currentReg, currentPin, mcp.HIGH)
  48. currentState = true
  49. end
  50. end)
  51. --[[
  52. read input channels and display every 7 seconds
  53. ]]
  54. -- read input register
  55. tmr.create():alarm(7000, tmr.ALARM_AUTO, function()
  56. local a = mcp:readGPIO(mcp.GPA)
  57. if a ~= nil then
  58. print("GPIO A input states: " .. a)
  59. else
  60. print("GPIO A unreadable, check device")
  61. end
  62. local b = mcp:readGPIO(mcp.GPB)
  63. if b ~= nil then
  64. print("GPIO B input states: " .. b)
  65. else
  66. print("GPIO B unreadable, check device")
  67. end
  68. print(" ")
  69. end)