All writing
Software & Data8 min read

A $50 accelerometer rig for machine health (and what it can't see)

Industrial vibration sensors cost hundreds per point. An ESP32 and a MEMS accelerometer cost less than lunch for the team, and they catch the slow drift that precedes most spindle and pump failures, if you build and use them honestly.

A metal-cased AT1104 accelerometer with its mounting flange, photographed on brown paper

Photo: 155LA3 · CC BY 4.0

Predictive maintenance has a pricing problem. An industrial vibration sensor with a wireless gateway and a dashboard subscription runs hundreds of dollars per measurement point, which is easy to justify on a 500 kW compressor and impossible on the coolant pump that has quietly failed twice this year. So most machines in most shops get no vibration monitoring at all, and failures announce themselves as noise, then smoke, then downtime.

There's a middle ground. An ESP32 microcontroller and an ADXL345 MEMS accelerometer cost a few dollars each; add a magnet, an enclosure, and a cable and you're under $50 per point. It will not replace a vibration analyst's piezo sensor. It will tell you, with numbers, that machine 4's spindle is vibrating 60% more than it did in March. That trend is most of what predictive maintenance is.

<$50
per measurement point, all-in
3,200
samples/s: the ADXL345's maximum output data rate
~1.6 kHz
usable bandwidth ceiling (Nyquist), lower once mounted

The bill of materials

PartApprox. costNotes
ESP32 dev board$6–12Wi-Fi + plenty of RAM for a 5 s capture buffer
ADXL345 breakout$3–18Cheap generic boards work; branded ones have better docs
Neodymium pot magnet (M4/M6)$4–8The sensor's mount; see below, it matters more than the chip
Steel or aluminium puck + epoxy$2–5Rigidly bonds the breakout to the magnet
Shielded 4-core cable, 2–3 m$5SPI over long unshielded wire near VFDs is asking for trouble
Small IP-rated enclosure$5–10Coolant and chips get everywhere
Prices are typical retail ranges in late 2026; the total lands between roughly $25 and $50.

Be honest about what a MEMS sensor can see

This is the section most DIY tutorials skip, and it decides whether your rig is useful or just generates graphs:

  • Bandwidth. At 3,200 samples/s the theoretical ceiling is 1,600 Hz, and the mount's own resonance usually pulls the reliable range lower. Spindle imbalance, misalignment, and looseness (1× and 2× running speed, typically 10–400 Hz) are comfortably in range. Rolling-bearing defect frequencies at high speed, and the kilohertz "envelope" techniques analysts use to catch them early, are not.
  • Noise. The ADXL345 is noisy compared to industrial sensors, so it sees meaningful vibration, not the faint early signature of a bearing that has months left. Low-noise MEMS parts like the ADXL355 cut noise by an order of magnitude, at roughly ten times the price and less bandwidth.
  • Resolution. In full-resolution mode the ADXL345 gives about 3.9 mg per count. Fine for trending a spindle; too coarse for precision balancing.

What it's actually good for

Trending. A cheap sensor read the same way, at the same spot, under the same operating condition, every day, catches change: rising imbalance, a loosening mount, a pump bearing going rough, a spindle that has started to sing. Change is what you act on. Absolute diagnosis still belongs to a proper analyser.

Mounting matters more than the chip

A vibration sensor measures whatever it's attached to, including its own mount. A breakout board dangling on header pins, or stuck down with foam tape, resonates on its own and filters away the high frequencies before the chip ever sees them. Epoxy the breakout flat to a small steel puck, and mount the puck with a strong pot magnet on a clean, flat, bare-metal spot as close to the bearing as you can get: the spindle housing, the pump bearing cap. Then mark that spot with paint. Moving the sensor 30 mm changes the readings more than a month of wear does, so every reading must come from the same place.

Firmware: capture bursts, not streams

Streaming 3,200 samples/s continuously over Wi-Fi is fragile and unnecessary. Health trending needs snapshots: a few seconds of clean data, a few times a day. The ESP32 fills a RAM buffer from the sensor's FIFO (so timing comes from the accelerometer's own clock, not your loop), then ships the whole burst when asked:

// ESP32 + ADXL345 over SPI (Arduino core). VSPI: SCK 18, MISO 19, MOSI 23, CS 5
#include <SPI.h>
const int CS = 5;
const int N = 16384;                 // 16384 samples @ 3200 Hz = 5.12 s, 0.2 Hz bins
int16_t buf[N][3];

void wr(uint8_t reg, uint8_t v) { digitalWrite(CS, LOW); SPI.transfer(reg); SPI.transfer(v); digitalWrite(CS, HIGH); }
uint8_t rd(uint8_t reg) { digitalWrite(CS, LOW); SPI.transfer(reg | 0x80); uint8_t v = SPI.transfer(0); digitalWrite(CS, HIGH); return v; }

void readEntry(int16_t *xyz) {       // one FIFO entry = 6 bytes, must be read together
  digitalWrite(CS, LOW);
  SPI.transfer(0x32 | 0xC0);          // DATAX0, read + multi-byte
  for (int a = 0; a < 3; a++) { uint8_t lo = SPI.transfer(0), hi = SPI.transfer(0); xyz[a] = (int16_t)(hi << 8 | lo); }
  digitalWrite(CS, HIGH);
  delayMicroseconds(5);               // datasheet: >=5 us between FIFO reads
}

void setup() {
  Serial.begin(921600);
  pinMode(CS, OUTPUT); digitalWrite(CS, HIGH);
  SPI.begin();
  SPI.beginTransaction(SPISettings(5000000, MSBFIRST, SPI_MODE3));   // ADXL345: mode 3, <=5 MHz
  wr(0x31, 0x0B);                     // DATA_FORMAT: full resolution, +/-16 g
  wr(0x2C, 0x0F);                     // BW_RATE: 3200 Hz output data rate
  wr(0x38, 0x80 | 16);                // FIFO_CTL: stream mode
  wr(0x2D, 0x08);                     // POWER_CTL: start measuring
}

void capture(uint32_t &elapsed) {
  int16_t junk[3];
  for (uint8_t e = rd(0x39) & 0x3F; e > 0; e--) readEntry(junk);   // flush stale samples
  uint32_t t0 = micros();
  for (int n = 0; n < N; ) {
    uint8_t entries = rd(0x39) & 0x3F;                            // FIFO_STATUS
    while (entries-- && n < N) readEntry(buf[n++]);
  }
  elapsed = micros() - t0;
}

void loop() {
  if (Serial.read() == 'C') {         // PC asks for a capture
    uint32_t elapsed;
    capture(elapsed);
    Serial.write((const uint8_t *)"ADXL", 4);
    Serial.write((const uint8_t *)&elapsed, 4);
    Serial.write((const uint8_t *)buf, sizeof(buf));
  }
}

Two details are easy to miss. The FIFO must be flushed before each capture, or the first samples are stale. And the actual output data rate of a MEMS part can differ from its nominal value by a few percent, so the firmware times the capture and the PC computes the real sample rate. A 3% frequency error moves a 1× peak at 200 Hz by 6 Hz, which is enough to mislabel it.

Analysis: velocity RMS, the number to trend

Machinery vibration standards (ISO 10816, now ISO 20816) judge overall severity by velocity RMS in mm/s, typically over 10–1,000 Hz. Velocity is the right quantity for most rotating-machinery faults, and it's easy to get from acceleration in the frequency domain: divide each FFT bin by 2πf. (The FFT post covers windowing and peaks in detail; this builds on it.)

import struct
import numpy as np
import serial   # pip install pyserial numpy

N, G = 16384, 9.80665

def capture(port="COM5"):
    with serial.Serial(port, 921600, timeout=15) as s:
        s.reset_input_buffer()
        s.write(b"C")
        if s.read(4) != b"ADXL":
            raise IOError("bad header")
        (elapsed_us,) = struct.unpack("<I", s.read(4))
        raw = np.frombuffer(s.read(N * 6), dtype="<i2").reshape(N, 3)
    fs = N / (elapsed_us / 1e6)                 # measured, not nominal
    return raw * 0.0039 * G, fs                 # counts -> m/s^2

def band_velocity_rms(a, fs, lo=10.0, hi=1000.0):
    """Velocity RMS in mm/s over [lo, hi] Hz from an acceleration record in m/s^2."""
    a = a - a.mean()
    w = np.hanning(len(a))
    A = np.fft.rfft(a * w)
    f = np.fft.rfftfreq(len(a), 1 / fs)
    band = (f >= lo) & (f <= min(hi, fs / 2))
    v2 = np.abs(A[band]) ** 2 / (2 * np.pi * f[band]) ** 2      # integrate: V = A / (j*2*pi*f)
    ms = 2 * v2.sum() / (len(a) ** 2 * np.mean(w ** 2))         # Parseval, Hann-corrected
    return np.sqrt(ms) * 1000

def peak_near(a, fs, freq, tol=0.03):
    """Acceleration amplitude (m/s^2) of the largest peak within +/-3% of freq."""
    w = np.hanning(len(a))
    A = 2 * np.abs(np.fft.rfft((a - a.mean()) * w)) / (len(a) * w.mean())
    f = np.fft.rfftfreq(len(a), 1 / fs)
    sel = (f > freq * (1 - tol)) & (f < freq * (1 + tol))
    return A[sel].max() if sel.any() else 0.0

acc, fs = capture()
rpm = 6000
for axis, name in enumerate("XYZ"):
    print(f"{name}: {band_velocity_rms(acc[:, axis], fs):5.2f} mm/s RMS, "
          f"1x = {peak_near(acc[:, axis], fs, rpm / 60):.3f} m/s^2 (fs = {fs:.0f} Hz)")

The trick that makes cheap sensors work: a repeatable condition

Vibration depends heavily on what the machine is doing: speed, load, temperature, the tool in the spindle. Compare a reading taken mid-cut to one taken at idle and you're measuring the job, not the machine's health. So don't measure whatever happens to be running. Create a standard condition and measure that:

  1. 1Write a short health-check program: no tool (or always the same balanced holder), spindle at three fixed speeds, for example 2,000, 6,000, and 10,000 rpm, 20 seconds each.
  2. 2Run it at the same point every day, at warm-up time or before the first job, and trigger a capture at each speed (a spare M-code relay into an ESP32 input works nicely, or just time it).
  3. 3Store overall velocity RMS and the 1× amplitude per speed, per axis, with the date.
  4. 4Alert on change from baseline, not on absolute thresholds: for example, flag when a value exceeds 1.5× its median over the first month, and investigate at 2×.

ISO zones are a reference, not your alarm limit

ISO 20816 publishes velocity zones (A–D) by machine class, and they're a sensible sanity check for pumps, fans, and motors. Machine-tool spindles usually have tighter, builder-specific limits, and a DIY sensor's absolute calibration is approximate anyway. Use your own baseline for alarms; use ISO zones to tell whether a machine was already rough on day one.

Where the data goes

A daily health check produces a handful of numbers per machine, which fits perfectly in the machine_sample table from the Grafana machine dashboard: one series per machine, axis, and speed, with an alert rule on the baseline ratio. Six months in, you'll have something most shops never get: a record of how every spindle and pump has aged, and an early warning when one starts aging faster.

A $50 sensor won't tell you which bearing race is cracked. It will tell you that something changed in March, while there's still time to plan the repair instead of reacting to it.

Frequently asked questions

Can an ADXL345 be used for machine vibration monitoring?+

Yes, for trending overall vibration and running-speed faults (imbalance, misalignment, looseness) up to several hundred hertz. Its 3,200 samples/s maximum rate and relatively high noise make it unsuitable for high-frequency bearing-defect analysis, which needs a low-noise, wide-bandwidth sensor.

How do I convert acceleration to velocity for vibration analysis?+

In the frequency domain, divide each FFT bin of the acceleration spectrum by 2πf, then sum the squared magnitudes over the band of interest (commonly 10–1,000 Hz) with proper window correction to get velocity RMS, usually reported in mm/s.

What sample rate do I need to monitor a CNC spindle?+

At least twice the highest frequency you care about, with margin. For 1× and 2× running speed on a 12,000 rpm spindle (200 and 400 Hz), 3,200 samples/s is adequate. Bearing-defect and gear-mesh monitoring often needs 10 kHz or more.

Why do my vibration readings vary so much day to day?+

Usually because operating conditions differ (speed, load, temperature, tooling) or the sensor was moved. Measure at a marked spot, with a rigid mount, during a standard health-check program at fixed spindle speeds, and compare against your own baseline.

Muerus Rodrigues

Applications Engineer

Get in touch

Keep reading

Home
Projects
Blog
Tools
Code
Stepsmith
Contact
LinkedIn
Request Résumé