mpr121.lua 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. ---------------------------------------------------------------
  2. -- MPR121 I2C module for NodeMCU
  3. -- Based on code from: http://bildr.org/2011/05/mpr121_arduino/
  4. -- Tiago Custódio <tiagocustodio1@gmail.com>
  5. ---------------------------------------------------------------
  6. local moduleName = ...
  7. local M = {}
  8. _G[moduleName] = M
  9. -- Default value for i2c communication
  10. local id = 0
  11. --device address
  12. local devAddr = 0
  13. --make it faster
  14. local i2c = i2c
  15. function M.setRegister(address, r, v)
  16. i2c.start(id)
  17. local ans = i2c.address(id, address, i2c.TRANSMITTER)
  18. i2c.write(id, r)
  19. i2c.write(id, v)
  20. i2c.stop(id)
  21. end
  22. function M.init(address)
  23. devAddr = address
  24. M.setRegister(devAddr, 0x5E, 0x00) -- ELE_CFG
  25. -- Section A - Controls filtering when data is > baseline.
  26. M.setRegister(devAddr, 0x2B, 0x01) -- MHD_R
  27. M.setRegister(devAddr, 0x2C, 0x01) -- NHD_R
  28. M.setRegister(devAddr, 0x2D, 0x00) -- NCL_R
  29. M.setRegister(devAddr, 0x2E, 0x00) -- FDL_R
  30. -- Section B - Controls filtering when data is < baseline.
  31. M.setRegister(devAddr, 0x2F, 0x01) -- MHD_F
  32. M.setRegister(devAddr, 0x30, 0x01) -- NHD_F
  33. M.setRegister(devAddr, 0x31, 0xFF) -- NCL_F
  34. M.setRegister(devAddr, 0x32, 0x02) -- FDL_F
  35. -- Section C - Sets touch and release thresholds for each electrode
  36. for i = 0, 11 do
  37. M.setRegister(devAddr, 0x41+(i*2), 0x06) -- ELE0_T
  38. M.setRegister(devAddr, 0x42+(i*2), 0x0A) -- ELE0_R
  39. end
  40. -- Section D - Set the Filter Configuration - Set ESI2
  41. M.setRegister(devAddr, 0x5D, 0x04) -- FIL_CFG
  42. -- Section E - Electrode Configuration - Set 0x5E to 0x00 to return to standby mode
  43. M.setRegister(devAddr, 0x5E, 0x0C) -- ELE_CFG
  44. tmr.delay(50000) -- Delay to let the electrodes settle after config
  45. end
  46. function M.readTouchInputs()
  47. i2c.start(id)
  48. i2c.address(id, devAddr, i2c.RECEIVER)
  49. local c = i2c.read(id, 2)
  50. i2c.stop(id)
  51. local LSB = tonumber(string.byte(c, 1))
  52. local MSB = tonumber(string.byte(c, 2))
  53. local touched = bit.lshift(MSB, 8) + LSB
  54. local t = {}
  55. for i = 0, 11 do
  56. t[i+1] = bit.isset(touched, i) and 1 or 0
  57. end
  58. return t
  59. end
  60. return M