Built-in project · ESP32-C3-DevKitM-1

Home Assistant multisensor on an ESP32-C3

Temperature, humidity, light and motion on one ESP32-C3, the room sensor Home Assistant users build first, with each reading printed as the MQTT message it would send. The whole build, an ESP32-C3 and 5 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.

Teaching? Assign it to your class in one click.

Intermediate About 30 minutes to build and run. Runs in your browser. Free, and no account needed.

The parts retail for about $21. On Mokxi they're free.

Home Assistant multisensor · ESP32-C3-DevKitM-1live0.000 s 0.00x
Click to open it in the editor
The circuit itself, running here on the simulator. Press what can be pressed; click anything else to open it in the editor.

What you'll learn

  • Reading a DHT22 and handling a failed read
  • Using I2C with the BH1750 light sensor
  • Reporting changes right away, other readings on a timer
  • Only publishing light when it really changed
  • Serving sensor data as JSON from a web server
  • Difficulty: Intermediate
  • Time: About 30 minutes
  • Board: ESP32-C3-DevKitM-1
  • Parts: 7

How it works

One ESP32-C3 reads four things: a DHT22 for temperature and humidity on pin 3, a BH1750 for light over I2C on pins 4 and 5, and a motion sensor on pin 18. A blue LED on pin 19 lights while motion is seen.

Mokxi's WiFi is simulated and has no MQTT broker. So instead of sending messages, the sketch prints one line for each message a real device would publish, like home/multisensor/temperature.

It also runs a small web server. Open /state for the readings as JSON, the kind of URL Home Assistant can poll, or / for a simple page.

Wiring table

Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.

Part and pinConnects to
Light sensor, BH1750 pin GNDESP32-C3-DevKitM-1 pin GND
Temperature and humidity, DHT22 pin GNDESP32-C3-DevKitM-1 pin GND
Light sensor, BH1750 pin VCCESP32-C3-DevKitM-1 pin 3V3
Temperature and humidity, DHT22 pin VCCESP32-C3-DevKitM-1 pin 3V3
Temperature and humidity, DHT22 pin DATAESP32-C3-DevKitM-1 pin 3
Light sensor, BH1750 pin SDAESP32-C3-DevKitM-1 pin 4
Light sensor, BH1750 pin SCLESP32-C3-DevKitM-1 pin 5
Motion sensor pin VCCESP32-C3-DevKitM-1 pin 5V
Motion sensor pin GNDESP32-C3-DevKitM-1 pin GND
LED, blue pin CESP32-C3-DevKitM-1 pin GND
Motion sensor pin OUTESP32-C3-DevKitM-1 pin 18
Resistor, 220 Ω pin 1ESP32-C3-DevKitM-1 pin 19
LED, blue pin AResistor, 220 Ω pin 2

The code

The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.

sketch.ino · ESP32-C3-DevKitM-1
// Home Assistant multisensor: temperature, humidity, light and motion.
//
// The four readings people put in nearly every room, on one ESP32-C3:
//   DHT22 on GPIO 3     temperature and humidity, read every 10 seconds
//   BH1750 on I2C       light in lux (SDA GPIO 4, SCL GPIO 5)
//   PIR on GPIO 18      motion, reported the moment it changes
//   LED on GPIO 19      lights while the PIR sees motion
//
// On a real device you would most likely flash ESPHome and write YAML instead
// of this sketch. Mokxi runs Arduino code, not ESPHome, so this sketch does by
// hand what ESPHome's dht, bh1750 and gpio binary_sensor components do, and
// the help page shows the YAML side by side.
//
// What reaches Home Assistant. The network here is SIMULATED and has no MQTT
// broker, so the sketch prints each message it would publish, one line per
// topic, and serves the same values as JSON at /state for the Web tab. Home
// Assistant's RESTful sensor can poll a URL like that on a real network.

#include <BH1750.h>
#include <DHT.h>
#include <WebServer.h>
#include <WiFi.h>
#include <Wire.h>

const int DHT_PIN = 3;
const int PIR_PIN = 18;
const int LED_PIN = 19;

const unsigned long CLIMATE_EVERY_MS = 10000;  // a DHT22 wants 2 s at least
const unsigned long LIGHT_EVERY_MS = 5000;
const float LUX_CHANGE = 10.0;  // only report light that has really changed

DHT dht(DHT_PIN, DHT22);
BH1750 lightMeter;
WebServer server(80);

float temperature = 0;
float humidity = 0;
float lux = 0;
float luxSent = -1000;
bool motion = false;
unsigned long lastClimate = 0;
unsigned long lastLight = 0;

// One line per message a real device would publish to its MQTT broker.
void publish(const char *topic, const String &payload) {
  Serial.print("publish home/multisensor/");
  Serial.print(topic);
  Serial.print(' ');
  Serial.println(payload);
}

void readClimate() {
  float t = dht.readTemperature();
  float h = dht.readHumidity();
  if (isnan(t) || isnan(h)) {
    Serial.println("DHT22: no answer, check the data wire and its pull-up");
    return;
  }
  temperature = t;
  humidity = h;
  publish("temperature", String(temperature, 1));
  publish("humidity", String(humidity, 1));
}

void readLight() {
  lux = lightMeter.readLightLevel();
  if (fabs(lux - luxSent) >= LUX_CHANGE) {
    luxSent = lux;
    publish("illuminance", String(lux, 0));
  }
}

void sendState() {
  String json = "{\"temperature\":";
  json += String(temperature, 1);
  json += ",\"humidity\":";
  json += String(humidity, 1);
  json += ",\"illuminance\":";
  json += String(lux, 0);
  json += ",\"motion\":";
  json += motion ? "true" : "false";
  json += "}";
  server.send(200, "application/json", json);
}

void sendPage() {
  String page = "<!doctype html><html><head><meta charset=\"utf-8\">";
  page += "<title>Multisensor</title></head><body><h1>Living room</h1><p>";
  page += String(temperature, 1);
  page += " &deg;C &middot; ";
  page += String(humidity, 0);
  page += "% &middot; ";
  page += String(lux, 0);
  page += " lx &middot; motion ";
  page += motion ? "detected" : "clear";
  page += "</p><p><a href=\"/state\">/state as JSON</a></p></body></html>";
  server.send(200, "text/html", page);
}

void setup() {
  Serial.begin(115200);
  pinMode(PIR_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  dht.begin();
  Wire.begin(4, 5);  // SDA, SCL
  lightMeter.begin();

  Serial.println("Multisensor: simulated WiFi, no MQTT broker in Mokxi.");
  WiFi.begin("Mokxi-Lab", "breadboard");
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
  }
  Serial.print("online at http://");
  Serial.print(WiFi.localIP());
  Serial.println("/state");
  server.on("/", sendPage);
  server.on("/state", sendState);
  server.begin();

  delay(2000);  // the DHT22 needs a moment after power-up
  readClimate();
  readLight();
  publish("motion", "OFF");
  lastClimate = lastLight = millis();
}

void loop() {
  server.handleClient();

  // Motion is the one reading worth sending the instant it changes.
  bool seen = digitalRead(PIR_PIN) == HIGH;
  if (seen != motion) {
    motion = seen;
    digitalWrite(LED_PIN, motion ? HIGH : LOW);
    publish("motion", motion ? "ON" : "OFF");
  }

  unsigned long now = millis();
  if (now - lastClimate >= CLIMATE_EVERY_MS) {
    lastClimate = now;
    readClimate();
  }
  if (now - lastLight >= LIGHT_EVERY_MS) {
    lastLight = now;
    readLight();
  }
  delay(5);
}

Code walkthrough

The key functions of the sketch, and what each one does.

publish sketch.ino

Stands in for sending an MQTT message. It prints the topic and the value on one line. On real hardware this is where a message would go out to the broker.

// One line per message a real device would publish to its MQTT broker.
void publish(const char *topic, const String &payload) {
  Serial.print("publish home/multisensor/");
  Serial.print(topic);
  Serial.print(' ');
  Serial.println(payload);
}

readClimate sketch.ino

Reads temperature and humidity from the DHT22. If either value is not a number, it prints a hint to check the data wire and pull-up and stops. Otherwise it saves both values and publishes them.

void readClimate() {
  float t = dht.readTemperature();
  float h = dht.readHumidity();
  if (isnan(t) || isnan(h)) {
    Serial.println("DHT22: no answer, check the data wire and its pull-up");
    return;
  }
  temperature = t;
  humidity = h;
  publish("temperature", String(temperature, 1));
  publish("humidity", String(humidity, 1));
}

readLight sketch.ino

Reads lux from the BH1750. It only publishes when the reading differs from the last published value by at least LUX_CHANGE (10), so a steady room stays quiet.

void readLight() {
  lux = lightMeter.readLightLevel();
  if (fabs(lux - luxSent) >= LUX_CHANGE) {
    luxSent = lux;
    publish("illuminance", String(lux, 0));
  }
}

loop sketch.ino

Serves web requests, then checks the motion pin. A change is published at once and also switches the LED. Climate is read every 10 seconds and light every 5 seconds.

void loop() {
  server.handleClient();

  // Motion is the one reading worth sending the instant it changes.
  bool seen = digitalRead(PIR_PIN) == HIGH;
  if (seen != motion) {
    motion = seen;
    digitalWrite(LED_PIN, motion ? HIGH : LOW);
    publish("motion", motion ? "ON" : "OFF");
  }

  unsigned long now = millis();
  if (now - lastClimate >= CLIMATE_EVERY_MS) {
    lastClimate = now;
    readClimate();
  }
  if (now - lastLight >= LIGHT_EVERY_MS) {
    lastLight = now;
    readLight();
  }
  delay(5);
}

Troubleshooting

The usual mistakes with this circuit, and the fix for each.

  • Serial says the DHT22 gave no answer. This project
    Check the DATA wire is on pin 3 and that VCC and GND are connected. The sketch only retries after another 10 seconds.
  • Light always reads 0 or never changes. This project
    Check SDA is on pin 4 and SCL on pin 5, matching Wire.begin(4, 5). Swapped wires stop the sensor from answering.
  • The LED never lights. This project
    The LED follows the motion sensor on pin 18, which needs 5V. Check its OUT wire, and the 220 ohm resistor on pin 19.
  • The sensor is not found, or reads 0 or 65535. Light sensor
    Connect SDA and SCL to the right pins and pull them up. The address is 0x23 with ADDR low, or 0x5C with ADDR high. Send the power on and mode commands before you read.
  • The lux value looks off by a factor. Light sensor
    The raw count divided by 1.2 gives lux. Libraries do this for you, so do not divide twice. In high resolution mode, wait about 120 ms after starting a measurement.
  • Readings are NaN or fail, or never appear. Temperature and humidity
    Put a 10 k ohm pull-up between DATA and VCC (bare sensors need it). A 4-pin DHT22 has pin 3 unused. Check the data pin number in your code.
  • Values freeze or errors show up when you read often. Temperature and humidity
    The DHT22 can only be read about once every 2 seconds. Wait between reads, and check for NaN before using the numbers.
  • The sensor reads high for ages after power up. Motion sensor
    A real PIR needs 30 to 60 seconds to settle. Ignore its output during that time, and keep still in front of it until the delay passes.

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.