gy49.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include "gy49.h"
  2. // MAX44009 I2C address is 0x4A/0x4B
  3. #define GY49_ADDR 0x4A
  4. /* Private variables */
  5. static bool isPresent;
  6. static Timer dataTimer;
  7. static uint32_t Luminance;
  8. /* Private Fuctions */
  9. void _read_data(void);
  10. /**
  11. * @brief Initialization
  12. */
  13. void GY49_Init(void) {
  14. // Start I2C Transmission
  15. Wire.beginTransmission(GY49_ADDR);
  16. // Select configuration register
  17. Wire.write(0x02);
  18. // Continuous mode, Integration time = 800 ms
  19. Wire.write(0x40);
  20. // Stop I2C transmission
  21. if (Wire.endTransmission()) {
  22. Serial.println("GY-49: Sensor not respond!");
  23. isPresent = false;
  24. return;
  25. }
  26. isPresent = true;
  27. // start polling sensors - once per two seconds
  28. dataTimer.initializeMs(1000, _read_data).start();
  29. }
  30. void _read_data(void) {
  31. if (!isPresent) { return; }
  32. unsigned int data[2] = {0};
  33. // Start I2C Transmission
  34. Wire.beginTransmission(GY49_ADDR);
  35. // Select data register
  36. Wire.write(0x03);
  37. // Stop I2C transmission
  38. Wire.endTransmission();
  39. // Request 2 bytes of data
  40. Wire.requestFrom(GY49_ADDR, 2);
  41. // Read 2 bytes of data
  42. // luminance msb, luminance lsb
  43. if (Wire.available() == 2) {
  44. data[0] = Wire.read();
  45. data[1] = Wire.read();
  46. } else {
  47. Serial.println("GY-49: No data from sensor.");
  48. return;
  49. }
  50. // Convert the data to microLux
  51. uint32_t exponent = 1 << ((data[0] & 0xF0) >> 4);
  52. uint32_t mantissa = ((data[0] & 0x0F) << 4) | (data[1] & 0x0F);
  53. Luminance = exponent * mantissa * 45;
  54. // Output data to serial monitor
  55. Serial.print("Ambient Light luminance :");
  56. Serial.print(Luminance/1000);
  57. Serial.print(",");
  58. Serial.print(Luminance%1000);
  59. Serial.println(" lux");
  60. }
  61. uint32_t GY49_GetData(void) {
  62. return Luminance;
  63. }