From 4c58cacc21824986fd77a2576329e267c97c292a Mon Sep 17 00:00:00 2001 From: Gergely Polonkai Date: Fri, 15 Jan 2021 10:11:49 +0100 Subject: [PATCH] Add support for the BH1750 light meter sensor --- WeatherStation.ino | 35 +++++++++++++++++++++++++++++++++++ config.h.sample | 11 +++++++++++ 2 files changed, 46 insertions(+) diff --git a/WeatherStation.ino b/WeatherStation.ino index ba0ff76..6458c9a 100644 --- a/WeatherStation.ino +++ b/WeatherStation.ino @@ -35,6 +35,11 @@ # include #endif // DHT_TYPE +#ifdef HAVE_BH1750 +# include +# include +#endif // HAVE_BH1750 + ESP8266WebServer server(80); unsigned long last_update = 0; @@ -48,6 +53,11 @@ float humidity = 0.0; bool raining = false; #endif // RAIN_PIN +#ifdef HAVE_BH1750 +BH1750 light; +float light_level = 0; +#endif // HAVE_BH1750 + static const char TEXT_PLAIN[] PROGMEM = "text/plain"; void @@ -61,6 +71,7 @@ send_metrics() { static const size_t dht_size = 228; static const size_t rain_size = 86; + static const size_t light_size = 72; size_t message_size = #ifdef DHT_TYPE @@ -69,6 +80,9 @@ send_metrics() #ifdef RAIN_PIN rain_size + #endif // RAIN_PIN +#ifdef HAVE_BH1750 + light_size + +#endif // HAVE_BH1750 1; char message[message_size]; @@ -86,12 +100,20 @@ send_metrics() "# TYPE raining gauge\n" "raining %d\n" #endif // RAIN_PIN +#ifdef HAVE_BH1750 + "# HELP light Ambient light, in lumens\n" + "# TYPE light gauge\n" + "light %.2f\n" +#endif // HAVE_BH1750 #ifdef DHT_TYPE , temperature, humidity #endif // DHT_TYPE #ifdef RAIN_PIN , raining ? 1 : 0 #endif // RAIN_PIN +#ifdef HAVE_BH1750 + , light_level +#endif // HAVE_BH1750 ); server.send(200, "text/plain; version=0.0.4; charset=utf-8", message); @@ -147,6 +169,15 @@ setup() pinMode(RAIN_PIN, INPUT); #endif // RAIN_PIN +#ifdef HAVE_BH1750 + Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN); + + if (!light.begin()) { + Serial.println("Could not find the BH1750 sensor!"); + stop(); + } +#endif // HAVE_BH1750 + Serial.println("All set, starting the loop."); } @@ -165,6 +196,10 @@ read_sensors() raining = (digitalRead(RAIN_PIN) == HIGH); #endif +#ifdef HAVE_BH1750 + light_level = light.readLightLevel(); +#endif // HAVE_BH1750 + // Turn off the LED to indicate work is finished digitalWrite(LED_BUILTIN, HIGH); } diff --git a/config.h.sample b/config.h.sample index eff9a72..7a6b3c5 100644 --- a/config.h.sample +++ b/config.h.sample @@ -53,3 +53,14 @@ // #define RAIN_PIN line #undef RAIN_PIN //#define RAIN_PIN D0 + +// Pins used for I²C communication. You will be instructed below if you need +// to uncomment these +//#define I2C_SDA_PIN D1 +//#define I2C_SCL_PIN D2 + +// If you have a BH1750 light level sensor, remove this #undef line and +// uncomment the #define HAVE_BH1750 line. You will also have to set the SDA +// and SCL pins using the I2C_SDA_PIN and I2C_SCL_PIN defines above. +#undef HAVE_BH1750 +//#define HAVE_BH1750