Guides · 11 min read

ESP32 Read Electricity Meter: Pulse LED, SML and Home Assistant

Read an electricity meter with ESP32: count the pulse LED with a photodiode, decode SML and D0 with an IR read head, imp/kWh maths, Tasmota, ESPHome and HA.

When you use an ESP32 to read your electricity meter, you can follow your home's live consumption in watts and its daily and monthly use in kWh on your phone, without connecting a single wire to the meter. Almost every electronic meter has an LED on the front that blinks for every watt-hour used, or an infrared interface that broadcasts data. The ESP32 reads that light, turns the numbers into power and energy, and sends the result over Wi-Fi to Home Assistant, a web page or your phone.

In this guide you'll first learn how to tell which meter you have, and then three methods: counting LED pulses with a photodiode, decoding the SML and D0 data of smart meters with an IR read head, and doing the same job ready-made with Tasmota or ESPHome. You'll get a table for calculating power from the pulse constant (imp/kWh), working code for each method and, at the end, the connection to the Home Assistant energy dashboard.

ESP32 development board for the electricity meter reader
ESP32: counts pulses with an interrupt, reads SML data over UART and sends the result over Wi-Fi.

Meter types: which one do you have?

The type of meter decides the method. Look at the markings on the front: if there's a small LED labelled imp/kWh (for example "1000 imp/kWh"), pulse counting always works. If you see a metal ring with two small eyes (an infrared transmitter and receiver) next to it, the meter also has an optical data interface, from which you can read the total and usually the live power directly. If an aluminium disc is spinning, you have an old mechanical (Ferraris) meter.

Meter typeHow to recognise itReading methodLive power
Mechanical (Ferraris)Spinning disc, "rev/kWh" marking (e.g. 75 rev/kWh)Count the mark on the disc with a TCRT5000Yes, but slow (per revolution)
Electronic with LEDBlinking LED, "1000 imp/kWh" markingCount pulses with a photodiodeCalculated from the pulse interval
Electronic with D0 optical portIR eye and metal ring, IEC 62056-21IR read head, ASCII text, usually 300 baudDepends on the meter
Smart meter with SMLIR interface; in Germany the modern metering device (mME)IR read head, binary SML data, 9600 baudAfter entering a PIN (OBIS 16.7.0)
Smart meter with wired data portP1 (Netherlands, Belgium), HAN, Linky TIC (France)Serial reading over a cableYes
Sub-meter (DIN rail, S0)"S0+" and "S0−" terminalsConnect the S0 output straight to a GPIOCalculated from the pulse interval
Every method in this article is optical: you don't open any cover, you don't touch the seals and you never come into contact with mains voltage. The meter belongs to the utility; opening it, breaking a seal or connecting anything inside is dangerous and illegal. Attach the reader to the meter only with tape, sticky putty or the magnet of the read head. The only wired connection is on sub-meters with an S0 output, and those terminals are a passive, low-voltage output.

Method 1: counting the LED pulses (imp/kWh)

The LED on an electronic meter blinks once each time a fixed amount of energy has been used. The pulse constant on the meter (N, imp/kWh) tells you how many pulses make up one kilowatt-hour: if it says 1000 imp/kWh, every pulse is 1 Wh. So to get total energy you count pulses, and to get live power you measure the time between two pulses. A pulse usually lasts from a few milliseconds to a few tens of milliseconds, and the ESP32's interrupt input catches it without missing any.

Pulse constant1 pulseInterval at 100 WInterval at 1 kWInterval at 3 kW
500 imp/kWh2 Wh72 s7.2 s2.4 s
800 imp/kWh1.25 Wh45 s4.5 s1.5 s
1000 imp/kWh1 Wh36 s3.6 s1.2 s
2000 imp/kWh0.5 Wh18 s1.8 s0.6 s
10000 imp/kWh0.1 Wh3.6 s0.36 s0.12 s
Ferraris, 75 rev/kWh13.3 Wh (1 revolution)480 s48 s16 s

The maths comes down to one formula: P (W) = 3,600,000 / (N × Δt), where Δt is the time between two pulses in seconds. For example, if pulses arrive every 2.4 seconds on a 1000 imp/kWh meter, the home is drawing 3,600,000 / (1000 × 2.4) = 1500 W right now. Total energy is E (kWh) = pulse count / N. As the table shows, on meters with a low constant the power value updates rarely at low consumption: at 1000 imp/kWh a 50 W standby load produces only one pulse every 72 seconds. That's why the code below lowers the power estimate using the elapsed time when the expected pulse is late.

Wiring: photodiode module, IR read head and S0

ConnectionPhotodiode module (pulses)IR read head (SML / D0)S0 output
PowerVCC → 3V3VCC → 3V3Not needed
GroundGND → GNDGND → GNDS0− → GND
DataDO → GPIO 27TX → GPIO 16 (RX2)S0+ → GPIO 27 (internal pull-up)
Request lineNoneRX → GPIO 17 (TX2, D0 only)None
  1. Place an LM393 light sensor module with a photodiode or phototransistor right over the meter's LED. LDR modules also work up to about 1000 imp/kWh, but because they react slowly they can miss pulses on 10000 imp/kWh meters.
  2. Power the module from 3V3 and turn the potentiometer on the board until the module's own LED blinks at the same time as the meter LED.
  3. Shield the sensor with black electrical tape or a short black tube; daylight and the ceiling light cause false pulses.
  4. Fix the module to the meter with sticky putty or double-sided tape, keeping the seals, buttons and display uncovered.
  5. Upload the code, watch the watt value in the Serial Monitor and then check it with a known load.
C++ (Arduino IDE)
1#include <WiFi.h>
2#include <WebServer.h>
3#include <Preferences.h>
4
5const char *WIFI_SSID = "WIFI_ADIN";        // kendi ağın / your network
6const char *WIFI_PASS = "WIFI_SIFREN";
7
8const int PULSE_PIN = 27;                   // fotodiyot modülünün DO çıkışı / DO output of the photodiode module
9const uint32_t IMP_PER_KWH = 1000;          // sayacın üzerindeki sabit / constant printed on the meter
10const double METER_START_KWH = 0.0;         // başlangıçta sayaçta okunan değer / meter reading at start
11const uint32_t MIN_GAP_US = 10000;          // 10 ms'den yakın darbeleri yok say / ignore pulses closer than 10 ms
12
13portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
14volatile uint32_t pulseCount = 0;
15volatile uint32_t lastPulseUs = 0;
16volatile uint32_t pulseGapUs = 0;           // son iki darbe arası / time between the last two pulses
17
18WebServer server(80);
19Preferences prefs;
20uint64_t basePulses = 0;                    // açılışta NVS'ten okunur / read from NVS at boot
21unsigned long lastSaveMs = 0;
22
23void IRAM_ATTR onPulse() {
24  uint32_t now = micros();
25  portENTER_CRITICAL_ISR(&mux);
26  uint32_t gap = now - lastPulseUs;
27  if (gap >= MIN_GAP_US) {                  // parazit ve sekmeleri ele / filter noise and bounce
28    if (pulseCount > 0) pulseGapUs = gap;   // ilk darbede aralık yok / no gap on the first pulse
29    lastPulseUs = now;
30    pulseCount++;
31  }
32  portEXIT_CRITICAL_ISR(&mux);
33}
34
35uint64_t totalPulses() {
36  portENTER_CRITICAL(&mux);
37  uint32_t count = pulseCount;
38  portEXIT_CRITICAL(&mux);
39  return basePulses + count;
40}
41
42double totalKwh() {
43  return METER_START_KWH + (double)totalPulses() / IMP_PER_KWH;
44}
45
46double currentPowerW() {
47  portENTER_CRITICAL(&mux);
48  uint32_t gap = pulseGapUs;
49  uint32_t last = lastPulseUs;
50  portEXIT_CRITICAL(&mux);
51  if (gap == 0) return 0;
52  uint32_t sinceLast = micros() - last;
53  if (sinceLast > gap) gap = sinceLast;     // darbe gecikiyorsa güç düşüyordur / a late pulse means falling power
54  return 3.6e12 / ((double)IMP_PER_KWH * gap);   // W = 3 600 000 / (N × s)
55}
56
57void handleJson() {
58  char json[80];
59  snprintf(json, sizeof(json), "{\"power_w\":%.0f,\"energy_kwh\":%.3f}", currentPowerW(), totalKwh());
60  server.send(200, "application/json", json);
61}
62
63void setup() {
64  Serial.begin(115200);
65  pinMode(PULSE_PIN, INPUT_PULLUP);
66  prefs.begin("meter", false);
67  basePulses = prefs.getULong64("pulses", 0);
68  attachInterrupt(digitalPinToInterrupt(PULSE_PIN), onPulse, FALLING);   // ışıkta LOW / LOW on light
69  WiFi.begin(WIFI_SSID, WIFI_PASS);
70  while (WiFi.status() != WL_CONNECTED) {
71    delay(500);
72    Serial.print(".");
73  }
74  Serial.println();
75  Serial.println(WiFi.localIP());           // tarayıcıda bu adresi aç / open this address in a browser
76  server.on("/", handleJson);
77  server.begin();
78}
79
80void loop() {
81  server.handleClient();
82  static unsigned long lastPrint = 0;
83  if (millis() - lastPrint >= 2000) {
84    lastPrint = millis();
85    Serial.printf("%.0f W | %.3f kWh\n", currentPowerW(), totalKwh());
86  }
87  if (millis() - lastSaveMs >= 600000UL) {  // 10 dakikada bir kaydet / save every 10 minutes
88    lastSaveMs = millis();
89    prefs.putULong64("pulses", totalPulses());
90  }
91}

Every pulse triggers the interrupt function onPulse(); IRAM_ATTR makes it run from fast RAM instead of flash. Because the interrupt and the main loop share the same variables, reads and writes are protected with portENTER_CRITICAL. Pulses closer together than 10 ms are treated as noise; with that limit, even a 10000 imp/kWh meter is counted cleanly up to 36 kW. The total pulse count is written to the ESP32's non-volatile memory (NVS) every ten minutes, so it survives a power cut and at most the last ten minutes of pulses are lost. If you put the reading on the meter's display into METER_START_KWH, the total shown by the ESP32 matches the meter. Open the board's IP address in a browser and you'll see power and energy as JSON; Home Assistant or any other system can read the same address.

Check your reading with a known load: with the other big appliances off, switch on a 2000 W kettle. On a 1000 imp/kWh meter the pulses should come about every 1.8 seconds, and the ESP32 should show the kettle's power plus the small draw of appliances that stay on, such as the fridge. If the value is double, you're double counting; if it's half, pulses are being missed.

A mechanical meter has no LED, but there's a red or black mark on the edge of the spinning disc, and one revolution means 1/U kWh has been used. The infrared reflective sensor TCRT5000 sees the difference between the shiny disc and the dark mark; connect its DO output to the same GPIO 27 and set IMP_PER_KWH in the code to the number on the meter (e.g. 75). Because the disc turns slowly, raise MIN_GAP_US to 1 second (1000000) so jitter at the edges of the mark isn't counted twice. Holding the sensor square to the meter's window and blocking reflections on the glass with a piece of black card makes the reading far more reliable.

Method 2: reading SML data with an IR read head

Germany's modern metering devices (mME) and smart meters in many other European countries broadcast an SML (Smart Message Language) telegram from the infrared interface on the front every few seconds. The data is a binary stream at 9600 baud, 8N1, and every measurement is labelled with an OBIS code. To read it you need an IR read head: a small cap with a phototransistor and an IR LED that sticks to the meter's metal ring with its magnetic ring. Connect the head's TX output to the ESP32's RX2 pin (GPIO 16) and the board picks up every telegram the meter sends.

OBIS codeMeaningUnit
1-0:1.8.0Total energy imported from the gridWh (converted to kWh in the code)
1-0:2.8.0Total energy exported to the grid (solar)Wh
1-0:1.8.1 / 1.8.2Tariff 1 and tariff 2 registersWh
1-0:16.7.0Total live active power (negative when exporting)W
1-0:36.7.0 / 56.7.0 / 76.7.0Power on phases L1, L2 and L3W
1-0:32.7.0Voltage on L1 (only on some meters)V

Out of the box, many mME send only the meter total, and without decimals; to get live power (16.7.0) the meter has to be unlocked with a PIN. You request the four-digit PIN from the metering operator that owns the meter. It's entered with a torch on the meter's optical sensor: for each digit you flash the light that many times and then wait a few seconds; the details are in the meter's manual. After that, switch on the extended data set in the same menu (InF on) and, if you like, turn off the PIN prompt; from then on the telegram includes live power and values with decimals.

C++ (Arduino IDE)
1#include <Arduino.h>
2
3const int RX_PIN = 16;                      // okuma kafasının TX'i / TX of the IR read head
4const int TX_PIN = 17;                      // SML'de kullanılmaz / not used for SML
5
6const uint8_t OBIS_IMPORT[] = {0x07, 0x01, 0x00, 0x01, 0x08, 0x00, 0xFF};   // 1.8.0 çekilen / import
7const uint8_t OBIS_EXPORT[] = {0x07, 0x01, 0x00, 0x02, 0x08, 0x00, 0xFF};   // 2.8.0 verilen / export
8const uint8_t OBIS_POWER[]  = {0x07, 0x01, 0x00, 0x10, 0x07, 0x00, 0xFF};   // 16.7.0 anlık güç / power
9
10uint8_t buf[1024];                          // bir SML telegramı / one SML telegram
11int len = 0;
12unsigned long lastByteMs = 0;
13
14// Bir SML elemanını atlar, sonraki elemanın konumunu döndürür
15// Skips one SML element and returns the index of the next one
16int skipElement(int i) {
17  if (i < 0 || i >= len) return -1;
18  uint8_t tl = buf[i];
19  if (tl == 0x00) return i + 1;             // mesaj sonu / end of message
20  uint8_t type = (tl >> 4) & 0x07;
21  int n = tl & 0x0F;
22  int p = i;
23  while ((buf[p] & 0x80) && p + 1 < len) {  // çok baytlı uzunluk / multi-byte length
24    p++;
25    n = (n << 4) | (buf[p] & 0x0F);
26  }
27  if (type == 0x07) {                       // liste: n eleman / list: n elements
28    int j = p + 1;
29    for (int k = 0; k < n && j >= 0; k++) j = skipElement(j);
30    return j;
31  }
32  return i + n;                             // uzunluk TL baytlarını da içerir / length includes the TL bytes
33}
34
35// İşaretli (5x) ya da işaretsiz (6x) tam sayı okur / reads a signed (5x) or unsigned (6x) integer
36bool readInt(int i, int64_t &out) {
37  if (i < 0 || i >= len) return false;
38  uint8_t type = (buf[i] >> 4) & 0x07;
39  int n = (buf[i] & 0x0F) - 1;              // veri baytı sayısı / number of data bytes
40  if ((type != 0x05 && type != 0x06) || n < 1 || n > 8 || i + n >= len) return false;
41  uint64_t v = (type == 0x05 && (buf[i + 1] & 0x80)) ? ~0ULL : 0;   // işaret genişletme / sign extension
42  for (int k = 1; k <= n; k++) v = (v << 8) | buf[i + k];
43  out = (int64_t)v;
44  return true;
45}
46
47// Telegramda OBIS kodunu bulur, ölçekli değeri döndürür / finds an OBIS code, returns the scaled value
48bool findObis(const uint8_t *obis, double &result) {
49  for (int i = 0; i + 7 < len; i++) {
50    if (memcmp(&buf[i], obis, 7) != 0) continue;
51    int j = i + 7;
52    j = skipElement(j);                     // status
53    j = skipElement(j);                     // valTime
54    j = skipElement(j);                     // unit
55    if (j < 0 || j >= len) return false;
56    int64_t scaler = 0;
57    if (buf[j] != 0x01 && !readInt(j, scaler)) return false;   // 0x01 = boş / empty
58    j = skipElement(j);
59    int64_t raw;
60    if (!readInt(j, raw)) return false;
61    result = raw * pow(10.0, (int)scaler);
62    return true;
63  }
64  return false;
65}
66
67void setup() {
68  Serial.begin(115200);
69  Serial2.begin(9600, SERIAL_8N1, RX_PIN, TX_PIN);   // SML: 9600 baud, 8N1
70}
71
72void loop() {
73  while (Serial2.available()) {
74    uint8_t b = Serial2.read();
75    if (len < (int)sizeof(buf)) buf[len++] = b;
76    lastByteMs = millis();
77  }
78  if (len > 0 && millis() - lastByteMs > 100) {     // 100 ms sessizlik = telegram bitti / 100 ms silence = done
79    double value;
80    if (findObis(OBIS_IMPORT, value)) Serial.printf("1.8.0  %.3f kWh\n", value / 1000.0);
81    if (findObis(OBIS_EXPORT, value)) Serial.printf("2.8.0  %.3f kWh\n", value / 1000.0);
82    if (findObis(OBIS_POWER, value))  Serial.printf("16.7.0 %.0f W\n", value);
83    len = 0;
84  }
85}

The code treats a telegram as finished once no byte has arrived for 100 ms, then searches the buffer for the OBIS codes. In SML every field starts with a TL byte (type and length): 0x5X is a signed integer, 0x6X an unsigned integer, 0x7X a list and 0x0X a byte string. In a measurement entry the OBIS code is followed by status, time, unit and the scaler; the value is multiplied by 10 to the power of the scaler. A scaler of 52 FF, for example, means −1, so if the 8-byte value after 59 is 94775105, the result is 9,477,510.5 Wh, or 9477.511 kWh. This sample code doesn't check the telegram's CRC; for permanent use, the ready-made SML decoder in Tasmota or ESPHome, shown in a moment, is more robust.

The D0 interface (IEC 62056-21): meters that send text

Older electronic meters, and meters in many other countries, are read through their optical port with the IEC 62056-21 (D0) protocol. Here the data consists of readable text lines such as "1.8.0(012345.678*kWh)". Most of these meters don't transmit on their own: first you send the request "/?!" at 300 baud in 7E1 format, the meter answers with an identification line, and after your acknowledgement (ACK) it sends the full data list. That's why for D0 you need to connect both the TX and RX lines of the read head. Some meters, however, broadcast D0 text continuously at 9600 baud without a request; in that case just open Serial2 at that speed and read the lines.

C++ (Arduino IDE)
1#include <Arduino.h>
2
3const int RX_PIN = 16;                      // okuma kafasının TX'i / TX of the read head
4const int TX_PIN = 17;                      // okuma kafasının RX'i / RX of the read head
5
6void setup() {
7  Serial.begin(115200);
8  Serial2.begin(300, SERIAL_7E1, RX_PIN, TX_PIN);    // IEC 62056-21: 300 baud, 7E1
9}
10
11void loop() {
12  while (Serial2.available()) Serial2.read();       // eski baytları at / drop old bytes
13  Serial2.print("/?!\r\n");                          // okuma isteği / request message
14  String line;
15  unsigned long start = millis();
16  while (millis() - start < 20000) {                 // 300 baud yavaştır / 300 baud is slow
17    if (!Serial2.available()) {
18      delay(1);
19      continue;
20    }
21    char c = (char)Serial2.read();
22    if (c == '\r') continue;
23    if (c != '\n') {
24      line += c;
25      continue;
26    }
27    if (line.startsWith("/")) {                      // kimlik satırı / identification line
28      Serial.println(line);
29      Serial2.print("\x06" "000\r\n");               // ACK: 300 baud'da veri oku / data readout at 300 baud
30    } else if (line.indexOf("1.8.0") >= 0 || line.indexOf("2.8.0") >= 0) {
31      Serial.println(line);                          // ör. / e.g. 1.8.0(012345.678*kWh)
32    } else if (line.indexOf('!') >= 0) {
33      break;                                         // veri bloğu bitti / end of the data block
34    }
35    line = "";
36  }
37  delay(60000);                                      // dakikada bir oku / read once a minute
38}

Ready-made solutions with Tasmota and ESPHome

If you'd rather get results without writing code, Tasmota's Smart Meter Interface supports SML, D0 and pulse meters. Flash a Tasmota build with scripting and SML enabled onto the ESP32 (read heads with a built-in Tasmota ESP are also sold). Then open Tools > Edit Script, paste the script below, tick Script enable and save. The 16 in the line starting with +1 is the RX pin; @1000 divides the Wh value to give kWh. Tasmota shows the values on its main page and can send them to Home Assistant over MQTT.

Code
1>D
2>B
3=>sensor53 r
4>M 1
5+1,16,s,0,9600,SML
61,77070100010800ff@1000,Import,kWh,Total_in,3
71,77070100020800ff@1000,Export,kWh,Total_out,3
81,77070100100700ff@1,Power,W,Power_curr,0
9#

If you use Home Assistant, the cleanest route is ESPHome: its SML component decodes the telegram with a CRC check, and every OBIS code shows up in Home Assistant as a separate sensor. If you're setting up ESPHome for the first time, follow the steps in Getting started with ESPHome, then add these sections to the device's YAML file:

Code
1uart:
2  id: meter_uart
3  rx_pin: GPIO16              # okuma kafasının TX'i / TX of the read head
4  baud_rate: 9600
5  data_bits: 8
6  parity: NONE
7  stop_bits: 1
8
9sml:
10  id: meter
11  uart_id: meter_uart
12
13sensor:
14  - platform: sml
15    sml_id: meter
16    name: "Grid import"
17    obis_code: "1-0:1.8.0"
18    unit_of_measurement: kWh
19    accuracy_decimals: 3
20    device_class: energy
21    state_class: total_increasing
22    filters:
23      - multiply: 0.001       # Wh -> kWh
24  - platform: sml
25    sml_id: meter
26    name: "Grid export"
27    obis_code: "1-0:2.8.0"
28    unit_of_measurement: kWh
29    accuracy_decimals: 3
30    device_class: energy
31    state_class: total_increasing
32    filters:
33      - multiply: 0.001
34  - platform: sml
35    sml_id: meter
36    name: "Power"
37    obis_code: "1-0:16.7.0"   # verirken eksi / negative when exporting
38    unit_of_measurement: W
39    accuracy_decimals: 0
40    device_class: power
41    state_class: measurement

The LED pulse method is just as easy with ESPHome. The pulse_meter sensor measures the pulse interval and reports pulses per minute; to turn that into watts, multiply by 60,000 / N (60 for 1000 imp/kWh, 6 for 10000 imp/kWh). The total counter divides the pulse count by N to give kWh:

Code
1sensor:
2  - platform: pulse_meter
3    pin:
4      number: GPIO27
5      inverted: true          # modül ışıkta LOW verir / module outputs LOW on light
6      mode:
7        input: true
8        pullup: true
9    name: "Power"
10    unit_of_measurement: W
11    device_class: power
12    state_class: measurement
13    accuracy_decimals: 0
14    internal_filter: 10ms
15    timeout: 5min
16    filters:
17      - multiply: 60          # darbe/dk × 60000 / 1000 imp/kWh / pulses per min × 60000 / 1000 imp/kWh
18    total:
19      name: "Energy"
20      unit_of_measurement: kWh
21      device_class: energy
22      state_class: total_increasing
23      accuracy_decimals: 3
24      filters:
25        - multiply: 0.001     # 1 / 1000 imp/kWh

The Home Assistant energy dashboard

Home Assistant's energy dashboard turns consumption into hourly, daily and monthly charts and, if you enter your kWh price, calculates the cost too. For the dashboard to accept a sensor, three things are required: the unit kWh, device_class energy and state_class total_increasing. The ESPHome examples above already include them; if you connect your own Arduino code over MQTT, don't forget to add these fields to the discovery message. For the MQTT side, see ESP32 with MQTT and Home Assistant.

  1. In Home Assistant, open Settings > Dashboards > Energy.
  2. Under Electricity grid, choose to add consumption and select the 1.8.0 sensor (or the pulse total).
  3. If you have solar panels, add the 2.8.0 sensor as energy returned to the grid.
  4. Enter a fixed price per kWh or pick an entity that holds the price.
  5. Save and be patient: the dashboard works with hourly statistics, so the first bars appear after an hour or two.

Electricity meter reader project ideas

  • Run appliances on solar surplus: when 16.7.0 goes negative (you're exporting), switch on a water heater or charger with a relay.
  • Desk consumption display: show the live watts and today's cost on an OLED display.
  • Standby hunter: log the lowest power at 3 a.m.; that's your home's always-on base load, and its share of the yearly bill can be surprising.
  • Telegram alert: if power stays above 3 kW for a long time, have a Telegram bot message your phone.
  • Per-appliance comparison: compare the meter total with a PZEM-004T measuring a single circuit and find out which appliance uses how much.
  • Spreadsheet log: write hourly consumption to Google Sheets and get the monthly report automatically.

Common mistakes and how to fix them

SymptomLikely causeFix
No pulses counted at allThe sensor isn't over the LED or the threshold is wrongTurn the pot until the module LED blinks with the meter LED
Power reads doubleBounce on the pulse edge or ambient lightDarken the sensor, check MIN_GAP_US
Extra pulses during the daySunlight or lamp light leaking inCover the sensor completely with black tape
Not a single byte from SMLRead head upside down or TX and RX swappedAlign the head correctly, connect the head's TX to GPIO 16
Bytes arrive but no valuesWrong speed or format (looking for SML on a D0 meter)Try 9600 8N1 for SML and 300 7E1 for D0
Only the total, no live powerPIN not entered, InF offRequest the PIN from the metering operator, set InF on
Value wrong by a factor of 10 or 1000Scaler not applied or Wh and kWh mixed upApply the scaler, check the unit
Sensor missing from the energy dashboardstate_class or device_class missingAdd total_increasing, energy and kWh
The read head's orientation matters: the transmitter and receiver in the head have to face the meter's eyes, and on most heads the cable points down. If no data arrives at all, look at the meter's interface through your phone camera; if you see a purplish light flickering every few seconds, the meter is transmitting and the problem is the head or the wiring.

Reading your electricity meter is the first step to saving energy: it's hard to cut the bill without seeing what uses how much, and when. In the BlueGrays app you'll find step-by-step projects with circuit diagrams and code for reading light levels with an LDR module on the ESP32, detecting reflections with a TCRT5000, connecting to Wi-Fi, running a web server and a WebSocket counter; together they're every building block of a meter reader.

Frequently asked questions

Is it legal to read my electricity meter with an ESP32?

Reading the LED or the optical interface from the outside is generally allowed because you're not tampering with the meter; these interfaces exist so customers can see their own consumption. What's forbidden is opening the cover, breaking a seal or connecting anything inside. If you're unsure, ask your utility.

What does imp/kWh mean on an electricity meter?

It's how many times the LED blinks for every kilowatt-hour used. At 1000 imp/kWh one pulse is 1 Wh, at 10000 imp/kWh it's 0.1 Wh. Live power is P = 3,600,000 / (N × pulse interval in seconds).

Why doesn't my smart meter show live power?

Many smart meters send only the meter total until they're unlocked with a PIN. Request the four-digit PIN from your metering operator, enter it with a torch and switch on the extended data set (InF); the telegram then also contains the live power value 16.7.0.

Which IR read head should I buy for an ESP32?

A head that runs on 3.3 V and has a TTL output (TX/RX) connects straight to the ESP32, and a magnetic ring makes mounting easy. Heads with a built-in Tasmota ESP are a no-code solution. For D0 meters the head needs both a transmitter and a receiver, because you have to send a request.

Can I read an electricity meter with an LDR?

On meters with a low pulse constant such as 1000 imp/kWh, an LDR module usually works. Because an LDR reacts slowly, it can miss pulses at high power on 10000 imp/kWh meters; a photodiode or phototransistor module is more reliable.

Is the count lost after a power cut?

The ESP32 in the sample code saves the total to non-volatile memory (NVS) every ten minutes, so a power cut loses at most the last few minutes of pulses. With SML and D0 nothing is lost at all, because the value is read straight from the meter itself.

See all projects
Reading Light Intensity with the ESP32 LDR Module
ES-11Beginner

Reading Light Intensity with the ESP32 LDR Module

Real-time monitoring of the LDR module's raw ADC value and relative light percentage calculated from dark and light reference values in the Serial Monitor. This percentage is not a lux measurement. Teaches the module’s calibration logic. It is ideal to complete this before Project 10, as it is used to determine the threshold value.

4.6(36)
56
ESP32 Night Light with LDR
ES-10Beginner
Premium

ESP32 Night Light with LDR

Night light where the LED automatically turns on in the dark and off in the light. The D0 (digital out) pin of the LDR Sensor Module is used - the dark threshold is set with the small potentiometer on the module, the module itself generates the HIGH/LOW output. ESP32 just reads this signal with digitalRead(), the code is very simple.

4.7(18)
30
Reading Reflection (Proximity) with TCRT5000
AR-77Intermediate
Premium

Reading Reflection (Proximity) with TCRT5000

With a small sensor that sends out invisible light and measures how much bounces back, you can detect the surface in front of it.

4.6(33)
43
ESP32 Wi-Fi STA Connection (with LCD Screen)
ES-25Advanced

ESP32 Wi-Fi STA Connection (with LCD Screen)

In this project, we connect the ESP32 to the home Wi-Fi network in Station (STA) mode in a secure, fault-tolerant manner. We store the SSID and password in a separate secrets.h file to prevent leaking to Git, set up an auto-reconnect mechanism, and display the RSSI signal level and IP address on an I2C LCD screen. The internal LED works as a status indicator. It is a production-grade connection manager.

4.4(21)
40
ESP32 Asynchronous Web Server (with IP Display on LCD)
ES-27Advanced

ESP32 Asynchronous Web Server (with IP Display on LCD)

In this project, we’re turning the ESP32 into an asynchronous web server that you can control from your phone or computer on the same Wi-Fi network. Thanks to the ESPAsyncWebServer library, the server can process multiple requests simultaneously (unlike the classic WebServer.h, which blocks on a single request). You’ll be able to open the ESP32’s IP address in a browser and click the ON/OFF buttons (the /on and /off routes) to turn the LED connected to GPIO 5 on and off.

4.8(16)
27
ESP32 WebSocket Counter (2 Buttons + LCD + Real-Time Web)
ES-28Advanced
Premium

ESP32 WebSocket Counter (2 Buttons + LCD + Real-Time Web)

In this project, two buttons wired to the ESP32 (GPIO 5 counts up, GPIO 4 counts down) change a counter. The value updates instantly both on a 16x2 I2C LCD and, through the WebSocket support of ESPAsyncWebServer, in every connected browser without reloading the page. Instead of HTTP polling a single persistent connection is used, and the ESP32 sends the new value to everyone with ws.textAll().

4.5(14)
23
Real-Time Clock from the Internet via ESP32 NTP
ES-26Advanced
Premium

Real-Time Clock from the Internet via ESP32 NTP

The ESP32 connects to Wi-Fi and fetches the real time from NTP (Network Time Protocol) servers with millisecond precision. configTzTime() applies the Turkey time zone (TRT, UTC+3) automatically, and in countries with daylight saving time the DST switch is handled by a POSIX TZ string. The time is printed both to the Serial Monitor and to an optional I2C LCD.

4.5(13)
22
ESP32 OTA Update — Wireless Firmware Installation (With LCD Screen)
ES-30Advanced
Premium

ESP32 OTA Update — Wireless Firmware Installation (With LCD Screen)

In this project you'll learn to upload new firmware to the ESP32 over Wi-Fi, without a USB cable. With the ArduinoOTA library the ESP32 becomes visible on the network and shows up automatically as bluegrays-ota under "Network port" in the Arduino IDE. The first upload goes over USB; after that every update is wireless, a key feature for devices out in the field.

4.6(14)
22