supla-device
Loading...
Searching...
No Matches
bh1750.h
1// SPDX-FileCopyrightText: AC SOFTWARE SP. Z O.O.
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4// Dependency: Please install "BH1750" by Christopher Laws library in Arduino:
5// https://github.com/claws/BH1750
6
7#ifndef SRC_SUPLA_SENSOR_BH1750_H_
8#define SRC_SUPLA_SENSOR_BH1750_H_
9
10#include <supla/sensor/general_purpose_measurement.h>
11
12#include <math.h>
13#include <BH1750.h>
14#include <supla/log_wrapper.h>
15
16namespace Supla {
17namespace Sensor {
19 public:
20 explicit Bh1750(int i2cAddress = 0x23)
21 : GeneralPurposeMeasurement(nullptr, false), sensor(i2cAddress) {
23 getChannel()->setDefaultIcon(14);
24 }
25
26 void initializeSensor() {
27 if (sensor.begin()) {
28 SUPLA_LOG_DEBUG("BH1750[%d]: initialized", getChannelNumber());
29 } else {
30 SUPLA_LOG_WARNING("BH1750[%d]: not found or other error",
32 }
33 }
34
35 void onInit() override {
36 initializeSensor();
37
38 channel.setNewValue(getValue());
39 }
40
41 protected:
42 double getValue() override {
43 double value = sensor.readLightLevel();
44 if (isnan(value) || value < 0) {
45 invalidCounter++;
46 if (invalidCounter < 4) {
47 return lastValue;
48 } else {
49 // try to init again
50 invalidCounter = 0;
51 initializeSensor();
52 }
53 lastValue = NAN;
54 return lastValue;
55 }
56 invalidCounter = 0;
57 lastValue = value;
58 return value;
59 }
60
61 BH1750 sensor;
62
63 double lastValue = NAN;
64 int invalidCounter = 0;
65};
66
67} // namespace Sensor
68} // namespace Supla
69
70#endif // SRC_SUPLA_SENSOR_BH1750_H_
void setDefaultIcon(uint8_t iconId)
Sets default icon.
Definition channel.cpp:1529
int getChannelNumber() const
Returns channel number.
Definition element.cpp:179
Definition bh1750.h:18
double getValue() override
Method used to obtain new value for channel.
Definition bh1750.h:42
void onInit() override
Third method called on element in SuplaDevice.begin()
Definition bh1750.h:35
void setDefaultUnitAfterValue(const char *unit)
Sets default unit which is displayed after value.
Definition general_purpose_channel_base.cpp:197
Definition general_purpose_measurement.h:11