mcp23008_buttons.lua 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. ---
  2. -- @description Shows how to read 8 GPIO pins/buttons via I2C with the MCP23008 I/O expander.
  3. -- Tested on NodeMCU 0.9.5 build 20150213.
  4. -- @circuit
  5. -- Connect GPIO0 of the ESP8266-01 module to the SCL pin of the MCP23008.
  6. -- Connect GPIO2 of the ESP8266-01 module to the SDA pin of the MCP23008.
  7. -- Use 3.3V for VCC.
  8. -- Connect switches or buttons to the GPIOs of the MCP23008 and GND.
  9. -- Connect two 4.7k pull-up resistors on SDA and SCL
  10. -- We will enable the internal pull up resistors for the GPIOS of the MCP23008.
  11. -- @author Miguel (AllAboutEE)
  12. -- GitHub: https://github.com/AllAboutEE
  13. -- YouTube: https://www.youtube.com/user/AllAboutEE
  14. -- Website: http://AllAboutEE.com
  15. ---------------------------------------------------------------------------------------------
  16. local mcp23008 = require ("mcp23008")
  17. -- ESP-01 GPIO Mapping as per GPIO Table in https://github.com/nodemcu/nodemcu-firmware
  18. local gpio0, gpio2 = 3, 4
  19. ---
  20. -- @name showButtons
  21. -- @description Shows the state of each GPIO pin
  22. -- @return void
  23. ---------------------------------------------------------
  24. local function showButtons()
  25. local gpio = mcp23008.readGPIO() -- read the GPIO/buttons states
  26. -- get/extract the state of one pin at a time
  27. for pin=0,7 do
  28. local pinState = bit.band(bit.rshift(gpio,pin),0x1) -- extract one pin state
  29. -- change to string state (HIGH, LOW) instead of 1 or 0 respectively
  30. if(pinState == mcp23008.HIGH) then
  31. pinState = "HIGH"
  32. else
  33. pinState = "LOW"
  34. end
  35. print("Pin ".. pin .. ": ".. pinState)
  36. end
  37. print("\r\n")
  38. end
  39. do
  40. -- Setup the MCP23008
  41. mcp23008.begin(0x0,gpio2,gpio0,i2c.SLOW)
  42. mcp23008.writeIODIR(0xff)
  43. mcp23008.writeGPPU(0xff)
  44. tmr.create():alarm(2000, tmr.ALARM_AUTO, showButtons) -- run showButtons() every 2 seconds
  45. end