Heifer

bh1750-module

Dec 16th, 2023
104
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | Software | 0 0
  1. """
  2. Micropython BH1750 ambient light sensor driver.
  3. """
  4.  
  5. from utime import sleep_ms
  6.  
  7.  
  8. class BH1750():
  9. """Micropython BH1750 ambient light sensor driver."""
  10.  
  11. PWR_OFF = 0x00
  12. PWR_ON = 0x01
  13. RESET = 0x07
  14.  
  15. # modes
  16. CONT_LOWRES = 0x13
  17. CONT_HIRES_1 = 0x10
  18. CONT_HIRES_2 = 0x11
  19. ONCE_HIRES_1 = 0x20
  20. ONCE_HIRES_2 = 0x21
  21. ONCE_LOWRES = 0x23
  22.  
  23. # default addr=0x23 if addr pin floating or pulled to ground
  24. # addr=0x5c if addr pin pulled high
  25. def __init__(self, bus, addr=0x23):
  26. self.bus = bus
  27. self.addr = addr
  28. self.off()
  29. self.reset()
  30.  
  31. def off(self):
  32. """Turn sensor off."""
  33. self.set_mode(self.PWR_OFF)
  34.  
  35. def on(self):
  36. """Turn sensor on."""
  37. self.set_mode(self.PWR_ON)
  38.  
  39. def reset(self):
  40. """Reset sensor, turn on first if required."""
  41. self.on()
  42. self.set_mode(self.RESET)
  43.  
  44. def set_mode(self, mode):
  45. """Set sensor mode."""
  46. self.mode = mode
  47. self.bus.writeto(self.addr, bytes([self.mode]))
  48.  
  49. def luminance(self, mode):
  50. """Sample luminance (in lux), using specified sensor mode."""
  51. # continuous modes
  52. if mode & 0x10 and mode != self.mode:
  53. self.set_mode(mode)
  54. # one shot modes
  55. if mode & 0x20:
  56. self.set_mode(mode)
  57. # earlier measurements return previous reading
  58. sleep_ms(24 if mode in (0x13, 0x23) else 180)
  59. data = self.bus.readfrom(self.addr, 2)
  60. factor = 2.0 if mode in (0x11, 0x21) else 1.0
  61. return (data[0]<<8 | data[1]) / (1.2 * factor)
  62.  
Tags: micropython
Advertisement
Comments
  • Heifer
    2 years
    # Python 0.30 KB | 0 0
    1. Please
    2. If anyone's come across this and is familiar with Micropython (on ESP32) could they have a look at:
    3. Z6rqg7Mk
    4. and let me know if they have any idea why I get:
    5. AttributeError: 'module' object has no attribute 'luminance'
    6.  
    7. from My completely inexpert eye it (the attribute) is there in line 49
Add Comment
Please, Sign In to add comment