Anomaly Detection on Edge Devices: Predictive Maintenance in Practice

How we deployed an LSTM-based anomaly detection model on a Cortex-M4 board to predict motor failures 48 hours in advance — and what we learned.

By

Software Development Experts

UpNext Software is a full-cycle software development company specialising in embedded systems, IoT, mobile, and web development.

Anomaly Detection on Edge Devices: Predictive Maintenance in Practice
Article Contents

A bearing that is about to fail rarely goes quietly. Weeks before it seizes, it starts telling you what is coming: a faint rise in high-frequency vibration energy, a slow drift in the crest factor, a degrees-warmer housing under the same load. The signal is there. The problem is that on most factory floors nobody is listening at a fine enough resolution to hear it, because listening properly means sampling vibration in the kilohertz range on dozens of machines, and nobody wants to stream that to a cloud endpoint over a shop-floor LTE link.

That constraint is what pushes anomaly detection onto the device itself. This article walks through how we approach an LSTM-style anomaly detector running on a Cortex-M4 class board for rotating-machinery monitoring — the sensing choices, the feature pipeline, the memory arithmetic, and the parts that turned out harder than the model. We will also be direct about where this approach does not pay for itself, because that is a real answer for a lot of plants.

What "48 hours in advance" actually means

Lead time is the number everyone fixates on, and it is the number most easily oversold. So let us be precise about it. A 48-hour warning is not a countdown timer. It is a statement about how early an anomaly score crosses a threshold relative to the point where the asset would have to be taken offline — and it only holds for failure modes that degrade gradually.

In practice, that splits motor failures into two buckets:

  • Failure modes with a mechanical precursor — bearing spalling, outer/inner race defects, imbalance from fouling, misalignment, belt wear, progressive lubrication loss. These develop over days to weeks and are where useful lead time exists.
  • Failure modes that are effectively instantaneous — insulation breakdown, a phase loss, a foreign object, a controller fault. No vibration model is going to give you two days of notice on those. Anyone claiming otherwise is selling you something.

So the honest framing we give clients is: for wear-driven failures on a machine with a reasonably steady duty cycle, a day or two of actionable warning is a realistic engineering target. For everything else, the same device still earns its place as a condition monitor and a data recorder — it just is not a crystal ball.

Why the inference runs on the board

There is a version of this system where the microcontroller streams raw samples and a server does the thinking. It is easier to build, and for a pilot on three machines it is genuinely the right call. It stops being the right call quickly.

Raw triaxial vibration at even a modest 3.2 kHz per axis is on the order of tens of megabytes per device per day before compression. Multiply by a plant's worth of assets and you are paying for bandwidth and cloud ingest to transmit data that is, ninety-nine percent of the time, a machine behaving exactly as expected. Run the model locally and you transmit an anomaly score, a handful of summary features, and a raw snapshot only when something interesting happens. Downlink usage drops to something a battery-powered LoRaWAN or NB-IoT node can sustain.

The second reason is operational. Edge inference keeps working when the gateway reboots, when IT changes the VLAN, when the site loses uplink for a day. Maintenance teams stop trusting a system the first time it goes blind during a shift.

The sensing layer is where projects are won or lost

We have seen more predictive maintenance efforts die from bad mounting than from bad models. Before any of the ML matters:

  • Sensor choice. A MEMS accelerometer with a flat response to a few kilohertz is adequate for detecting bearing-defect energy trends on many industrial motors; if you need to resolve high-frequency envelope content precisely, you are in piezo territory with the analog front end that implies.
  • Mounting. Stud-mounted or epoxied to a machined pad, on the bearing housing, in the load direction. Magnet mounts and adhesive pads roll off the high frequencies that carry the earliest signal. This single decision changes how early you can detect anything.
  • Context channels. Temperature at the housing, motor current, and — critically — some indication of load or speed. Vibration amplitude scales with operating state, so without load context your model will confidently flag every shift changeover.
  • Sampling discipline. Fixed sample rate, fixed window length, triggered at the same point in the duty cycle. Non-stationary sampling is the fastest way to teach a model that Tuesdays are anomalous.

From raw vibration to something a Cortex-M4 can hold

A Cortex-M4 gives you a single-precision FPU and DSP instructions, typically running around 80–180 MHz with SRAM measured in tens to a few hundred kilobytes. You are not feeding raw time-series windows into a recurrent network on that budget. The feature pipeline does the heavy lifting.

Our usual shape is: acquire a window, window and FFT it using the CMSIS-DSP real FFT (fast and already tuned for this core), then reduce the spectrum to a compact feature vector per window. What goes into that vector is where domain knowledge beats generic ML:

  • Time-domain statistics: RMS velocity, peak, crest factor, kurtosis. Kurtosis in particular tends to rise early with impulsive bearing defects and then fall again as the defect distributes — a nuance worth knowing before you treat it as monotonic.
  • Band energies around the calculated bearing-defect frequencies (ball pass frequency outer/inner, ball spin, fundamental train), derived from geometry and shaft speed. Also 1×, 2×, 3× running speed for imbalance and misalignment, and line-frequency sidebands for electrical faults.
  • Envelope or demodulated high-frequency energy, which surfaces early-stage bearing damage well before it shows in overall vibration levels.
  • Normalised load/speed context, so the model can learn state-conditional normal behaviour rather than one grand average.

That collapses a window of thousands of samples into a couple of dozen floats. A sequence of those windows over hours is what the recurrent model actually sees — which is the point, because degradation is a trend, not a moment.

The model: reconstruction error over a sequence of feature vectors

We train on healthy data only. That is not a stylistic preference — it is a consequence of reality. Nobody has hundreds of labelled failures per asset class, and if they did, the failures would be spread unevenly across modes. So the architecture is an autoencoder over sequences: a small LSTM (or GRU) encoder compresses a window of feature vectors, a decoder reconstructs it, and the reconstruction error becomes the anomaly score. When the machine drifts away from the behaviour the model has internalised, the error climbs.

A few practical notes we would want a technical buyer to hear:

  • Recurrent layers are awkward on microcontroller runtimes. Support for fused LSTM operators in embedded interpreters has historically been patchy, and stateful inference across invocations needs care. Sometimes the pragmatic answer is a GRU with fewer gates, or a dilated 1D convolutional network that captures the same temporal span with better tooling support and more predictable latency. We benchmark both rather than committing to the acronym in the brief.
  • Hidden sizes stay small. Something in the range of 16–32 units per layer is typically enough once the features are well chosen, and it is what keeps the int8-quantised model and its tensor arena inside the available SRAM alongside your DSP buffers.
  • Quantise, then re-measure. Post-training int8 quantisation with a representative calibration set usually costs very little detection quality here, and the CMSIS-NN kernels make it meaningfully faster. But quantisation compresses the dynamic range of the reconstruction error, so thresholds must be recalibrated on the quantised model, never carried over from the float version.
  • Thresholding is a system design problem, not a model output. We use a rolling baseline per asset, an exponentially weighted moving average of the score, hysteresis, and a requirement for N consecutive anomalous windows before an alert leaves the device. One noisy window should never page a maintenance engineer at 2 a.m.

What surprised us, and what we would do differently

The model was not the hard part. These were.

Normal changes, and the model does not know it

After a bearing replacement, a re-alignment, or a change in product mix, the machine's baseline shifts. The model reads that as anomalous, and it is right — the behaviour genuinely changed — but the alert is useless. You need a first-class "re-baseline" workflow that a maintenance supervisor can trigger without calling an engineer, and you need to log every intervention so the next training run knows what happened.

Cold start is the real deployment cost

A per-asset model needs weeks of healthy operating data across the machine's normal states before its thresholds mean anything. We plan for a data collection phase up front, ship the device in monitoring-only mode, and only enable alerting once the baseline is stable. Skipping this produces a system that cries wolf, and once trust is gone the hardware gets unplugged.

Field firmware needs a way home

Models get retrained. Thresholds get tuned. If you cannot deliver a signed model update over the air with a safe rollback slot, you have built a science project rather than a product. Budget for the update path from day one — it is a bigger chunk of the firmware effort than the inference code.

The output has to fit an existing workflow

An anomaly score between zero and one means nothing to a maintenance planner. What lands is a work order in the CMMS with the asset ID, the suspected mode, the trend chart, and a recommended window. Getting that integration right does more for adoption than another point of model accuracy. If you would like to see how we handle this kind of full-stack embedded plus backend delivery, our recent work gives a sense of the shape.

When you should not do this

We would rather talk a client out of a bad fit than deliver one. Skip edge ML if:

  • The asset is cheap, redundant, or fails safely. A ₹15,000 pump with a spare on the shelf does not need a predictive model. Run it to failure.
  • Simple threshold monitoring already solves it. ISO-style overall velocity RMS bands with a temperature limit catch a genuine share of problems for a fraction of the cost and complexity. Try that first and see what actually slips through.
  • You cannot mount a sensor properly or you have no load context. Fix the physical layer before spending on models.
  • Nobody owns the response. If an alert has no defined owner and no maintenance slack to act on it, all you have built is a more sophisticated way to be surprised.

Where the asset is expensive, unplanned downtime is costly, and the failure mode is wear-driven — that is where a few hundred kilobytes of well-designed inference on a microcontroller pays for itself many times over.

How we tend to structure this work

For most clients this runs as a short discovery on the asset and failure modes, a data collection deployment, a modelling and quantisation phase where we benchmark two or three architectures against the real memory and latency budget, then firmware hardening and integration. Teams that need continuity across firmware, model and backend often bring us on as an embedded and ML pod rather than a fixed-scope build, simply because the retraining loop never really ends. If the model side is where you need depth, that sits within our broader AI and ML engineering practice.

If you have a machine that keeps failing in the same expensive way, we are happy to look at the vibration data you already have and tell you honestly whether an edge model would have caught it. Get in touch and we will start there rather than with a proposal.

Continue Reading
Related Articles