#ifndef TSL2561_H #define TSL2561_H #include "Adafruit_TSL2561_U.h" class TSL2561 { Adafruit_TSL2561_Unified tsl; unsigned long last = 0UL; public: const String name; unsigned long intervalMs; explicit TSL2561(String name, const uint8_t address = TSL2561_ADDR_FLOAT, const unsigned long interval_ms = 5000) : tsl(Adafruit_TSL2561_Unified(address)), name(std::move(name)), intervalMs(interval_ms) { // } void setup() { if (tsl.begin()) { Log.info("TSL2561 \"%s\": Initialized.", name.c_str()); } else { Log.error("TSL2561 \"%s\": Failed to initialize.", 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.error("TSL2561 \"%s\": Failed to read.", name.c_str()); setup(); } else { mqttPublishValue(name + "/illuminance", illuminance, "ILLUMINANCE_LUX"); } } }; #endif