Close

Measuring Mains Frequency (Software) — Raspberry Pi + pigpio + WebSocket

A project log for Electric time

Vintage pressure gauge hacked into a frequency meter, sensing the 50 Hz electrical grid tremors; time wavers, bends, and fades away.

dtournerDétourner 10/31/2025 at 08:550 Comments

In a previous log, I covered the hardware part of measuring mains frequency — this time it’s all about the software.

The goal: measure the local 50 Hz mains frequency in near real time, using a Raspberry Pi, a zero-crossing detector, and the pigpio library for precise timing. The Pi counts the signal edges, keeps timestamps in a circular buffer, corrects time drift using a 1 Hz PPS reference from a GPS receiver, and streams the calculated frequency over WebSocket.

The source code is on Github

How It Works

The core idea is simple:

  1. Each zero-crossing from the mains signal generates an interrupt on a GPIO pin.
  2. pigpio gives us a timestamp (in microseconds) for every edge.
  3. We store the last N timestamps (e.g. 1000 samples).
  4. Once per second (triggered by the GPS PPS), we compute:
  1. The result (current_frequency) is broadcast as JSON via a WebSocket server.


Core Components

Key Details


Real-Time Streaming

The script starts a WebSocket server (ws://0.0.0.0:8765) and sends an update once per second:

{

  "time_stamp": 1730362540.12,

  "last_update_time": 1730362539.89,

  "frequency": "50.013"

}

Any WebSocket client (Python, Node.js, browser dashboard, etc.) can subscribe to display or log the frequency over time.

Example Console Output

Base time: 1.000001 seconds (from GPS PPS)

Frequency: 50.012345 Hz (at 1730362540.123456 seconds) [1000 samples; Measured: 100.024690 Hz]

WebSocket server started at ws://0.0.0.0:8765

Client connected from IP: 192.168.1.42

(Measured: 100 Hz = zero-crossings/sec → divide by 2 → ~50 Hz mains frequency.)


Summary

This small Python script combines hardware-level timing from pigpio with a GPS-disciplined PPS reference and asynchronous streaming via WebSocket. It’s a neat way to visualize how the power grid frequency fluctuates in real time — and a solid foundation for any GPS-synchronized power-quality or IoT monitoring setup.

Discussions