#ifndef TSL2561_H #define TSL2561_H #include class TSL2561 { Adafruit_TSL2561_Unified tsl; unsigned long last = 0UL; public: const String name; unsigned long intervalMs; explicit TSL2561(const String& name, const uint8_t address = TSL2561_ADDR_FLOAT, const unsigned long interval_ms = 5000) : tsl(Adafruit_TSL2561_Unified(address)), name(name), intervalMs(interval_ms) { // } void setup() { if (tsl.begin()) { Log.printf("TSL2561 \"%s\": Initialized.\n", name.c_str()); } else { Log.printf("TSL2561 \"%s\": Failed to initialize.\n", name.c_str()); } tsl.enableAutoRange(true); tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS); } void loop() { const auto now = millis(); if (last == 0 || now - last >= intervalMs) { last = max(1UL, now); read(); } } private: void read() { uint16_t broadband; uint16_t ir; tsl.getLuminosity(&broadband, &ir); const auto illuminance = tsl.calculateLux(broadband, ir); if (illuminance == 65536) { Log.printf("TSL2561 \"%s\": Failed to read.\n", name.c_str()); setup(); } else { mqttPublish(name + "/illuminance", illuminance, "lux"); } } }; #endif