Arduino / Homeduino met ESP8266 aansturen pinnen op Arduino

Here’s what I wrote this evening (also for an BH1750, connected to an ESP8266):

#define MY_DEBUG
#define MY_GATEWAY_ESP8266
#define MY_GATEWAY_MQTT_CLIENT
#define MY_BAUD_RATE                    115200
#define MY_WIFI_SSID                    "XXX"
#define MY_WIFI_PASSWORD                "YYY"
#define MY_MQTT_CLIENT_ID               "esp-lightsensor"
#define MY_MQTT_PUBLISH_TOPIC_PREFIX    "my/" MY_MQTT_CLIENT_ID "/pub"
#define MY_MQTT_SUBSCRIBE_TOPIC_PREFIX  "my/" MY_MQTT_CLIENT_ID "/sub"
#define MY_CONTROLLER_IP_ADDRESS        192, 168, 23, 8
#define MY_PORT                         1883

#include <ESP8266WiFi.h>
#include <MySensors.h>
#include <Wire.h>
#include <BH1750.h>

BH1750    lightMeter;
MyMessage message (0, V_LEVEL);

void setup() {
  Wire.begin(D3, D4);
  if (lightMeter.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) {
    Serial.println(F("BH1750 Advanced begin"));
  } else {
    Serial.println(F("Error initialising BH1750"));
  }
}

void presentation() {
  sendSketchInfo("LightSensor", "1.0");
  present(0, S_LIGHT_LEVEL);
}

void loop() {
  float lux = lightMeter.readLightLevel();
  Serial.println("Measured level: " + String(lux) + " lux.");
  send(message.set((int32_t) lux));
  delay(2000);
  ESP.deepSleep(30e6);
}

It uses the MySensors library, which does most of the heavy lifting with regards to WiFi and MQTT. I use the MQTT Broker app to provide the MQTT server.

There is a MySensors app for Homey, but I don’t think it’s being maintained anymore. I didn’t feel like using it, and instead opted for a quick-and-dirty solution:

  • use the Virtual Devices app to create a sensor with the capability “Helderheid/Luminance”
  • use the MQTT Client app to watch for updates from the light sensor node (it updates every 30 seconds) and set the measure_luminance capability of the virtual sensor device:

(the full topic used is my/esp-lightsensor/pub/0/0/1/0/37, where my/esp-lightsensor/pub is a sort of prefix, and the numbers are the MySensors encoding of the sensor type/data).