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. require ("mcp23008")
  17. -- ESP-01 GPIO Mapping as per GPIO Table in https://github.com/nodemcu/nodemcu-firmware
  18. gpio0, gpio2 = 3, 4
  19. -- Setup the MCP23008
  20. mcp23008.begin(0x0,gpio2,gpio0,i2c.SLOW)
  21. mcp23008.writeIODIR(0xff)
  22. mcp23008.writeGPPU(0xff)
  23. ---
  24. -- @name showButtons
  25. -- @description Shows the state of each GPIO pin
  26. -- @return void
  27. ---------------------------------------------------------
  28. function showButtons()
  29. local gpio = mcp23008.readGPIO() -- read the GPIO/buttons states
  30. -- get/extract the state of one pin at a time
  31. for pin=0,7 do
  32. local pinState = bit.band(bit.rshift(gpio,pin),0x1) -- extract one pin state
  33. -- change to string state (HIGH, LOW) instead of 1 or 0 respectively
  34. if(pinState == mcp23008.HIGH) then
  35. pinState = "HIGH"
  36. else
  37. pinState = "LOW"
  38. end
  39. print("Pin ".. pin .. ": ".. pinState)
  40. end
  41. print("\r\n")
  42. end
  43. tmr.alarm(0,2000,1,showButtons) -- run showButtons() every 2 seconds