si7021.lua 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. -- ***************************************************************************
  2. -- SI7021 module for ESP8266 with nodeMCU
  3. -- Si7021 compatible tested 2015-1-22
  4. --
  5. -- Written by VIP6
  6. --
  7. -- MIT license, http://opensource.org/licenses/MIT
  8. -- ***************************************************************************
  9. local moduleName = ...
  10. local M = {}
  11. _G[moduleName] = M
  12. --I2C slave address of Si70xx
  13. local Si7021_ADDR = 0x40
  14. --Commands
  15. local CMD_MEASURE_HUMIDITY_HOLD = 0xE5
  16. local CMD_MEASURE_HUMIDITY_NO_HOLD = 0xF5
  17. local CMD_MEASURE_TEMPERATURE_HOLD = 0xE3
  18. local CMD_MEASURE_TEMPERATURE_NO_HOLD = 0xF3
  19. -- temperature and pressure
  20. local t,h
  21. local init = false
  22. -- i2c interface ID
  23. local id = 0
  24. -- 16-bit two's complement
  25. -- value: 16-bit integer
  26. local function twoCompl(value)
  27. if value > 32767 then value = -(65535 - value + 1)
  28. end
  29. return value
  30. end
  31. -- read data from si7021
  32. -- ADDR: slave address
  33. -- commands: Commands of si7021
  34. -- length: bytes to read
  35. local function read_data(ADDR, commands, length)
  36. i2c.start(id)
  37. i2c.address(id, ADDR, i2c.TRANSMITTER)
  38. i2c.write(id, commands)
  39. i2c.stop(id)
  40. i2c.start(id)
  41. i2c.address(id, ADDR,i2c.RECEIVER)
  42. tmr.delay(20000)
  43. c = i2c.read(id, length)
  44. i2c.stop(id)
  45. return c
  46. end
  47. -- initialize module
  48. -- sda: SDA pin
  49. -- scl SCL pin
  50. function M.init(sda, scl)
  51. i2c.setup(id, sda, scl, i2c.SLOW)
  52. --print("i2c ok..")
  53. init = true
  54. end
  55. -- read humidity from si7021
  56. local function read_humi()
  57. dataH = read_data(Si7021_ADDR, CMD_MEASURE_HUMIDITY_HOLD, 2)
  58. UH = string.byte(dataH, 1) * 256 + string.byte(dataH, 2)
  59. h = ((UH*12500+65536/2)/65536 - 600)
  60. return(h)
  61. end
  62. -- read temperature from si7021
  63. local function read_temp()
  64. dataT = read_data(Si7021_ADDR, CMD_MEASURE_TEMPERATURE_HOLD, 2)
  65. UT = string.byte(dataT, 1) * 256 + string.byte(dataT, 2)
  66. t = ((UT*17572+65536/2)/65536 - 4685)
  67. return(t)
  68. end
  69. -- read temperature and humidity from si7021
  70. function M.read()
  71. if (not init) then
  72. print("init() must be called before read.")
  73. else
  74. read_humi()
  75. read_temp()
  76. end
  77. end;
  78. -- get humidity
  79. function M.getHumidity()
  80. return h
  81. end
  82. -- get temperature
  83. function M.getTemperature()
  84. return t
  85. end
  86. return M