惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Blog — PlanetScale
Blog — PlanetScale
PCI Perspectives
PCI Perspectives
K
Kaspersky official blog
T
Tenable Blog
Help Net Security
Help Net Security
Vercel News
Vercel News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Fortinet All Blogs
罗磊的独立博客
P
Palo Alto Networks Blog
爱范儿
爱范儿
Google DeepMind News
Google DeepMind News
T
Threat Research - Cisco Blogs
Security Archives - TechRepublic
Security Archives - TechRepublic
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
L
LangChain Blog
Recent Announcements
Recent Announcements
有赞技术团队
有赞技术团队
博客园_首页
D
Darknet – Hacking Tools, Hacker News & Cyber Security
H
Help Net Security
S
Secure Thoughts
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Project Zero
Project Zero
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
V
V2EX
Last Week in AI
Last Week in AI
H
Heimdal Security Blog
U
Unit 42
Y
Y Combinator Blog
The GitHub Blog
The GitHub Blog
SecWiki News
SecWiki News
量子位
博客园 - 【当耐特】
Martin Fowler
Martin Fowler
NISL@THU
NISL@THU
S
Securelist
P
Proofpoint News Feed
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
云风的 BLOG
云风的 BLOG
I
Intezer
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园 - Franky
Cisco Talos Blog
Cisco Talos Blog
小众软件
小众软件
C
CXSECURITY Database RSS Feed - CXSecurity.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Anomaly detection on ESP32 with 24 bytes of RAM — no cloud, no malloc
Antoine Port · 2026-05-05 · via DEV Community

The core idea: Welford's online algorithm

The standard way to compute mean and standard deviation requires storing all samples first, then doing two passes. That's fine in Python. On a microcontroller with 320 KB of RAM, it's a non-starter.

John Welford solved this in 1962. His algorithm maintains a running mean and variance in a single pass, using only three values:

typedef struct {
    uint32_t count;           // samples processed
    float    mean;            // running mean
    float    M2;              // sum of squared deviations from mean
    float    threshold_sigma; // alert threshold (e.g. 3.0 = 3σ)
    uint32_t min_samples;     // warm-up period before detection starts
    uint32_t window_size;     // 0 = infinite, N = sliding window
} ArdentZScore;               // sizeof == 24 bytes

Enter fullscreen mode Exit fullscreen mode

The update step is four lines:

bool ard_zscore_update(ArdentZScore* ctx, float sample) {
    ctx->count++;
    float delta  = sample - ctx->mean;
    ctx->mean   += delta / ctx->count;
    float delta2 = sample - ctx->mean;
    ctx->M2     += delta * delta2;

    if (ctx->count < ctx->min_samples) return false;

    float variance = ctx->M2 / (ctx->count - 1);
    float stddev   = sqrtf(variance);
    if (stddev < 1e-9f) return false;

    float zscore = fabsf(sample - ctx->mean) / stddev;
    return zscore > ctx->threshold_sigma;
}

Enter fullscreen mode Exit fullscreen mode

That's it. No history buffer, no second pass, numerically stable over millions of samples.

Why not the naive formula? The naive formula computes variance = (sum_of_squares / n) - mean². That accumulates floating point error over time. On a MCU running for months, the variance goes negative. Welford avoids this entirely.


Why Z-Score isn't enough

Z-Score detects sudden spikes: a value that's 4σ away from the running mean. But it misses slow drift — because the running mean follows the drift.

Imagine a bearing that degrades over three days. At any given moment, the current value is "normal" relative to recent history. Z-Score sees nothing. But a second detector that compares a fast-moving average to a slow reference catches it immediately.

That's EWMA Drift — two exponential moving averages in parallel:

typedef struct {
    float ewma_fast;    // α = 0.1 — follows signal closely
    float ewma_slow;    // α = 0.01 — stable reference
    float alpha_fast;
    float alpha_slow;
    float threshold;
    uint32_t count;
} ArdentDrift;          // sizeof == 24 bytes

bool ard_drift_update(ArdentDrift* ctx, float sample) {
    ctx->count++;
    ctx->ewma_fast = ctx->alpha_fast * sample + (1.0f - ctx->alpha_fast) * ctx->ewma_fast;
    ctx->ewma_slow = ctx->alpha_slow * sample + (1.0f - ctx->alpha_slow) * ctx->ewma_slow;
    if (ctx->count < 10) return false;
    return fabsf(ctx->ewma_fast - ctx->ewma_slow) > ctx->threshold;
}

Enter fullscreen mode Exit fullscreen mode

Run both in parallel on the same data stream:

bool spike = ard_zscore_update(&spike_detector, sample);
bool drift = ard_drift_update(&drift_detector, sample);
if (spike || drift) trigger_alert();

Enter fullscreen mode Exit fullscreen mode

Failure mode Z-Score EWMA Drift
Voltage spike (+5σ, 1 sample) ✅ Detected ❌ Missed
Bearing wear (slow +0.05/sample) ❌ Missed ✅ Detected

Together, they cover the two fundamental failure signatures in industrial signals.


Integrating it in your firmware

Three steps.

Step 1 — Declare at file scope (no heap)

#include "ardent/zscore.h"
#include "ardent/drift.h"

static ArdentZScore spike;
static ArdentDrift  drift;

Enter fullscreen mode Exit fullscreen mode

Step 2 — Init once in setup()

ard_zscore_init(&spike, 3.0f, 30);          // 3σ threshold, 30-sample warm-up
ard_drift_init(&drift, 0.1f, 0.01f, 0.5f); // fast α, slow α, threshold

Enter fullscreen mode Exit fullscreen mode

Step 3 — Call in loop()

float sample = (float)analogRead(SENSOR_PIN);
bool anomaly = ard_zscore_update(&spike, sample)
            || ard_drift_update(&drift, sample);

if (anomaly) {
    digitalWrite(LED_PIN, HIGH);
    // or publish to MQTT, trigger relay, log to SD card...
}

Enter fullscreen mode Exit fullscreen mode

That's the entire integration. The detectors are zero-allocation, thread-safe (no globals except the structs you declare), and have no side effects.


Validating on PC before touching hardware

One of the hard constraints I set from day one: every algorithm must compile and run on a desktop with GCC. No hardware required to run the test suite.

cd edge-core/tests
make

Enter fullscreen mode Exit fullscreen mode

Running test suite: zscore
  [PASS] init: mean=0, stddev=0 before warmup
  [PASS] warmup: no alerts during first 30 samples
  [PASS] spike: +5σ detected on sample 100
  [PASS] spike: -5σ detected on sample 101
  [PASS] no false positive: 1000 normal samples, 0 alerts
  ...
Running test suite: drift
  [PASS] ramp +0.05/sample detected at sample 67
  ...
391/391 tests passed — 0 failing

Enter fullscreen mode Exit fullscreen mode

391 tests across 13 suites. If you change something, you know immediately whether it still works — before you pick up a USB cable.


Running on real hardware

Hardware: ESP32-CAM + MPU-6050 accelerometer. Wiring:

MPU-6050 → ESP32-CAM
VCC      → 3.3V
GND      → GND
SDA      → GPIO13
SCL      → GPIO14
AD0      → GND   (I2C address 0x68)

Enter fullscreen mode Exit fullscreen mode

One gotcha worth saving you an hour: if you're using a CH340 USB-UART adapter, never use board=esp32cam in platformio.ini. The PSRAM initialization it triggers crashes silently before setup() runs — nothing appears in the serial monitor. Use board=esp32dev instead. The WiFi, I2C, and GPIO work identically.

Flash:

cd edge-core/examples/esp32/imu_zscore
cp src/config.h.example src/config.h   # fill WiFi + MQTT credentials
pio run --target upload
pio device monitor --baud 115200

Enter fullscreen mode Exit fullscreen mode

Serial output:

[ARDENT] Pulse initialized
[ARDENT] WiFi connected — 192.168.1.42
[ARDENT] MQTT connected
[ARDENT] accel: 9.82 (NORMAL, z=0.31)
[ARDENT] accel: 9.79 (NORMAL, z=0.18)
[ARDENT] ANOMALY DETECTED — value=23.47 z=4.82
[ARDENT] ANOMALY DETECTED — value=21.13 z=4.11
[ARDENT] accel: 10.02 (NORMAL, z=0.44)

Enter fullscreen mode Exit fullscreen mode

Shake the sensor, the anomaly appears. Put it down, it goes back to NORMAL.


The third detector: MAD

For completeness, the SDK also includes a MAD (Median Absolute Deviation) detector. MAD uses the median instead of the mean, which makes it robust to outliers by construction. The median doesn't get pulled by extreme values the way the mean does.

It's more expensive (sliding window with insertion sort, ~200 bytes), but it's the right tool for signals that aren't Gaussian — vibration, ECG, pressure sensors in turbulent flow.

#include "ardent/mad.h"

static ArdentMAD vibration;
ard_mad_init(&vibration, 32, 2.5f);  // window=32, threshold=2.5 MAD units

bool anomaly = ard_mad_update(&vibration, sample);

Enter fullscreen mode Exit fullscreen mode


What this is

The SDK (called Ardent Pulse) is open source under LGPL v3 on GitHub: github.com/Antoine005/ardent

If you want the full package with the test suite, ESP32 examples (smoke test, MPU-6050 integration, camera-based fire detection, person detection with TFLite), and the Quick Start Guide PDF, it's available on Gumroad for $39: ardentai.gumroad.com/l/ugmrvk?utm_source=devto

The repository also includes Ardent Forge (Python AutoML pipeline to calibrate detector parameters on your real sensor data) and Ardent Watch (Next.js dashboard with MQTT ingestion, live anomaly visualization, fleet supervision). The Full Stack bundle is $149.


The constraint list

If you're thinking about adapting this for your own MCU or use case, these are the constraints I designed around:

  • Zero malloc — every struct is stack or static. valgrind confirms no heap allocations.
  • < 4 KB RAM per detector — Z-Score and EWMA Drift are 24 bytes each.
  • < 1 ms per sample at 80 MHz — measured at ~0.04 µs. 25× margin.
  • C99 pure — no C++, no POSIX, no OS. Compiles with -std=c99 -pedantic -Wall -Wextra -Werror.
  • HAL mandatory — algorithms never call registers directly. Every MCU port implements the same hal_*.h interfaces.
  • Testable on PC — if you can't test it without hardware, you can't iterate.

These aren't arbitrary. On a field-deployed industrial sensor or a defense system that can't be recalled, a single malloc failure or a portability assumption can be a production incident.


Questions? Drop them below or open an issue on GitHub. Happy to explain the drift detection tuning in more detail — it's surprisingly sensitive to the α values.