From RevSpace
Jump to navigation Jump to search
Project MainsFrequency
Ali 230v schema.png
A simple mains frequency counter
Status Completed
Contact bertrik, Peetz0r
Last Update 2018-05-21


This page is about creating a simple frequency counter for mains power and publish the frequency over MQTT.

It's based on the Arduino platform, using an ESP8266 to do the wifi/network/MQTT stuff.

The frequency measurement principle is to count the number of mains cycles in a fixed period. To get a resolution of 0.01 Hz, the period is 100 seconds.

To keep the measurement circuit relatively safe, only a part of the electronics is actually connected to mains and the low-voltage side is isolated with an optocoupler.


It works!



The microcontroller is an ESP8266 because it can easily publish the measured value over wifi/MQTT.

The circuit to sense the 50 Hz is this mains module sold on Aliexpress, with a small modification. The modification is that the smoothing capacitor has been removed, resulting in a 100 Hz signal going into the optocoupler.

How it's actually built:

  • Used the modified Aliexpress circuit.
  • Used a nodemcu v3 for the ESP8266 (this was what was available at the hacker space)
  • GND: connected to the GND pin on the mains module
  • pin D5: mains input on the mains module
  • 3.3V: connected to the pull-up on the mains module


The Arduino source is available on the github page, but has not been tested on actual hardware yet.

You can build it with platformio ('pio run').

The working principle is that we count the number of cycles in a 100 second period, this should nominally be 5000. A cycle count is done every second and the result is put in a circular buffer of 100 bins. The average of these 100 bins then provides the frequency over the past 100 seconds. The circular buffer is initialized with a value of 50 for each bin.

The accuracy of the frequency count depends on the accuracy of the crystal (among other things). To get 0.01 Hz error at 50 Hz, we need an time reference with at most 0.01 / 50 = 200 ppm frequency deviation. This is probably doable with the built-in crystal on a typical ESP8266 board (like a Wemos D1 mini).


Other interesting projects/documents: