bme280_float.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. # Updated 2018 and 2020
  2. # This module is based on the below cited resources, which are all
  3. # based on the documentation as provided in the Bosch Data Sheet and
  4. # the sample implementation provided therein.
  5. #
  6. # Final Document: BST-BME280-DS002-15
  7. #
  8. # Authors: Paul Cunnane 2016, Peter Dahlebrg 2016
  9. #
  10. # This module borrows from the Adafruit BME280 Python library. Original
  11. # Copyright notices are reproduced below.
  12. #
  13. # Those libraries were written for the Raspberry Pi. This modification is
  14. # intended for the MicroPython and esp8266 boards.
  15. #
  16. # Copyright (c) 2014 Adafruit Industries
  17. # Author: Tony DiCola
  18. #
  19. # Based on the BMP280 driver with BME280 changes provided by
  20. # David J Taylor, Edinburgh (www.satsignal.eu)
  21. #
  22. # Based on Adafruit_I2C.py created by Kevin Townsend.
  23. #
  24. # Permission is hereby granted, free of charge, to any person obtaining a copy
  25. # of this software and associated documentation files (the "Software"), to deal
  26. # in the Software without restriction, including without limitation the rights
  27. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  28. # copies of the Software, and to permit persons to whom the Software is
  29. # furnished to do so, subject to the following conditions:
  30. #
  31. # The above copyright notice and this permission notice shall be included in
  32. # all copies or substantial portions of the Software.
  33. #
  34. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  35. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  36. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  38. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  39. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40. # THE SOFTWARE.
  41. #
  42. import time
  43. from ustruct import unpack, unpack_from
  44. from array import array
  45. # BME280 default address.
  46. BME280_I2CADDR = 0x76
  47. # Operating Modes
  48. BME280_OSAMPLE_1 = 1
  49. BME280_OSAMPLE_2 = 2
  50. BME280_OSAMPLE_4 = 3
  51. BME280_OSAMPLE_8 = 4
  52. BME280_OSAMPLE_16 = 5
  53. BME280_REGISTER_CONTROL_HUM = 0xF2
  54. BME280_REGISTER_STATUS = 0xF3
  55. BME280_REGISTER_CONTROL = 0xF4
  56. MODE_SLEEP = const(0)
  57. MODE_FORCED = const(1)
  58. MODE_NORMAL = const(3)
  59. BME280_TIMEOUT = const(100) # about 1 second timeout
  60. class BME280:
  61. def __init__(self,
  62. mode=BME280_OSAMPLE_8,
  63. address=BME280_I2CADDR,
  64. i2c=None,
  65. **kwargs):
  66. # Check that mode is valid.
  67. if type(mode) is tuple and len(mode) == 3:
  68. self._mode_hum, self._mode_temp, self._mode_press = mode
  69. elif type(mode) == int:
  70. self._mode_hum, self._mode_temp, self._mode_press = mode, mode, mode
  71. else:
  72. raise ValueError("Wrong type for the mode parameter, must be int or a 3 element tuple")
  73. for mode in (self._mode_hum, self._mode_temp, self._mode_press):
  74. if mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
  75. BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
  76. raise ValueError(
  77. 'Unexpected mode value {0}. Set mode to one of '
  78. 'BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4, '
  79. 'BME280_OSAMPLE_8 or BME280_OSAMPLE_16'.format(mode))
  80. self.address = address
  81. if i2c is None:
  82. raise ValueError('An I2C object is required.')
  83. self.i2c = i2c
  84. self.__sealevel = 101325
  85. # load calibration data
  86. dig_88_a1 = self.i2c.readfrom_mem(self.address, 0x88, 26)
  87. dig_e1_e7 = self.i2c.readfrom_mem(self.address, 0xE1, 7)
  88. self.dig_T1, self.dig_T2, self.dig_T3, self.dig_P1, \
  89. self.dig_P2, self.dig_P3, self.dig_P4, self.dig_P5, \
  90. self.dig_P6, self.dig_P7, self.dig_P8, self.dig_P9, \
  91. _, self.dig_H1 = unpack("<HhhHhhhhhhhhBB", dig_88_a1)
  92. self.dig_H2, self.dig_H3, self.dig_H4,\
  93. self.dig_H5, self.dig_H6 = unpack("<hBbhb", dig_e1_e7)
  94. # unfold H4, H5, keeping care of a potential sign
  95. self.dig_H4 = (self.dig_H4 * 16) + (self.dig_H5 & 0xF)
  96. self.dig_H5 //= 16
  97. # temporary data holders which stay allocated
  98. self._l1_barray = bytearray(1)
  99. self._l8_barray = bytearray(8)
  100. self._l3_resultarray = array("i", [0, 0, 0])
  101. self._l1_barray[0] = self._mode_temp << 5 | self._mode_press << 2 | MODE_SLEEP
  102. self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
  103. self._l1_barray)
  104. self.t_fine = 0
  105. def read_raw_data(self, result):
  106. """ Reads the raw (uncompensated) data from the sensor.
  107. Args:
  108. result: array of length 3 or alike where the result will be
  109. stored, in temperature, pressure, humidity order
  110. Returns:
  111. None
  112. """
  113. self._l1_barray[0] = self._mode_hum
  114. self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL_HUM,
  115. self._l1_barray)
  116. self._l1_barray[0] = self._mode_temp << 5 | self._mode_press << 2 | MODE_FORCED
  117. self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
  118. self._l1_barray)
  119. # wait up to about 5 ms for the conversion to start
  120. for _ in range(5):
  121. if self.i2c.readfrom_mem(self.address, BME280_REGISTER_STATUS, 1)[0] & 0x08:
  122. break; # The conversion is started.
  123. time.sleep_ms(1) # still not busy
  124. # Wait for conversion to complete
  125. for _ in range(BME280_TIMEOUT):
  126. if self.i2c.readfrom_mem(self.address, BME280_REGISTER_STATUS, 1)[0] & 0x08:
  127. time.sleep_ms(10) # still busy
  128. else:
  129. break # Sensor ready
  130. else:
  131. raise RuntimeError("Sensor BME280 not ready")
  132. # burst readout from 0xF7 to 0xFE, recommended by datasheet
  133. self.i2c.readfrom_mem_into(self.address, 0xF7, self._l8_barray)
  134. readout = self._l8_barray
  135. # pressure(0xF7): ((msb << 16) | (lsb << 8) | xlsb) >> 4
  136. raw_press = ((readout[0] << 16) | (readout[1] << 8) | readout[2]) >> 4
  137. # temperature(0xFA): ((msb << 16) | (lsb << 8) | xlsb) >> 4
  138. raw_temp = ((readout[3] << 16) | (readout[4] << 8) | readout[5]) >> 4
  139. # humidity(0xFD): (msb << 8) | lsb
  140. raw_hum = (readout[6] << 8) | readout[7]
  141. result[0] = raw_temp
  142. result[1] = raw_press
  143. result[2] = raw_hum
  144. def read_compensated_data(self, result=None):
  145. """ Reads the data from the sensor and returns the compensated data.
  146. Args:
  147. result: array of length 3 or alike where the result will be
  148. stored, in temperature, pressure, humidity order. You may use
  149. this to read out the sensor without allocating heap memory
  150. Returns:
  151. array with temperature, pressure, humidity. Will be the one
  152. from the result parameter if not None
  153. """
  154. self.read_raw_data(self._l3_resultarray)
  155. raw_temp, raw_press, raw_hum = self._l3_resultarray
  156. # temperature
  157. var1 = (raw_temp/16384.0 - self.dig_T1/1024.0) * self.dig_T2
  158. var2 = raw_temp/131072.0 - self.dig_T1/8192.0
  159. var2 = var2 * var2 * self.dig_T3
  160. self.t_fine = int(var1 + var2)
  161. temp = (var1 + var2) / 5120.0
  162. temp = max(-40, min(85, temp))
  163. # pressure
  164. var1 = (self.t_fine/2.0) - 64000.0
  165. var2 = var1 * var1 * self.dig_P6 / 32768.0 + var1 * self.dig_P5 * 2.0
  166. var2 = (var2 / 4.0) + (self.dig_P4 * 65536.0)
  167. var1 = (self.dig_P3 * var1 * var1 / 524288.0 + self.dig_P2 * var1) / 524288.0
  168. var1 = (1.0 + var1 / 32768.0) * self.dig_P1
  169. if (var1 == 0.0):
  170. pressure = 30000 # avoid exception caused by division by zero
  171. else:
  172. p = ((1048576.0 - raw_press) - (var2 / 4096.0)) * 6250.0 / var1
  173. var1 = self.dig_P9 * p * p / 2147483648.0
  174. var2 = p * self.dig_P8 / 32768.0
  175. pressure = p + (var1 + var2 + self.dig_P7) / 16.0
  176. pressure = max(30000, min(110000, pressure))
  177. # humidity
  178. h = (self.t_fine - 76800.0)
  179. h = ((raw_hum - (self.dig_H4 * 64.0 + self.dig_H5 / 16384.0 * h)) *
  180. (self.dig_H2 / 65536.0 * (1.0 + self.dig_H6 / 67108864.0 * h *
  181. (1.0 + self.dig_H3 / 67108864.0 * h))))
  182. humidity = h * (1.0 - self.dig_H1 * h / 524288.0)
  183. if (humidity < 0):
  184. humidity = 0
  185. if (humidity > 100):
  186. humidity = 100.0
  187. if result:
  188. result[0] = temp
  189. result[1] = pressure
  190. result[2] = humidity
  191. return result
  192. return array("f", (temp, pressure, humidity))
  193. @property
  194. def sealevel(self):
  195. return self.__sealevel
  196. @sealevel.setter
  197. def sealevel(self, value):
  198. if 30000 < value < 120000: # just ensure some reasonable value
  199. self.__sealevel = value
  200. @property
  201. def altitude(self):
  202. '''
  203. Altitude in m.
  204. '''
  205. from math import pow
  206. try:
  207. p = 44330 * (1.0 - pow(self.read_compensated_data()[1] /
  208. self.__sealevel, 0.1903))
  209. except:
  210. p = 0.0
  211. return p
  212. @property
  213. def dew_point(self):
  214. """
  215. Compute the dew point temperature for the current Temperature
  216. and Humidity measured pair
  217. """
  218. from math import log
  219. t, p, h = self.read_compensated_data()
  220. h = (log(h, 10) - 2) / 0.4343 + (17.62 * t) / (243.12 + t)
  221. return 243.12 * h / (17.62 - h)
  222. @property
  223. def values(self):
  224. """ human readable values """
  225. t, p, h = self.read_compensated_data()
  226. return ("{:.2f}C".format(t), "{:.2f}hPa".format(p/100),
  227. "{:.2f}%".format(h))