A smartphone step counter is, at its core, a peak detector with judgment: it reads the accelerometer many times per second, decides when the signal pattern looks like a footfall, and filters out everything that merely resembles one. The practical design is a pipeline—sampling, preprocessing, candidate detection, validation, and counting—where each stage trades sensitivity against false positives. A working implementation can be built in a few hundred lines using only the phone's accelerometer, but making it accurate across pocket, hand, and bag carriage is where the real engineering lies.

This article covers the design reasoning and a concrete implementation approach for an accelerometer-based pedometer. It does not assume access to the phone's hardware step-counter sensor (many Android and iOS devices expose one, but it is often unavailable to third-party apps, inconsistently implemented, or power-managed in ways you cannot control), and it does not address GPS-based stride reconstruction except where it clarifies a distinction.

Understand what the accelerometer actually gives you

A smartphone accelerometer measures proper acceleration along three axes, typically at 20–100 Hz for app-facing APIs (the hardware often samples faster and the OS delivers a downsampled stream). When a person walks, the body rises and falls with each step. The vertical acceleration traces a repeating pattern: a push-off peak, a brief low-gravity phase, a heel-strike impact, and a return. Because the phone's orientation relative to the body changes constantly, the axes themselves are unreliable; what matters is the magnitude of the acceleration vector:

At rest this magnitude equals gravity, roughly 9.81 m/s² (the API may report it in g units, where rest is 1.0). Walking produces oscillations of roughly 0.5–3 m/s² around that baseline, with a dominant frequency of about 1.5–2.5 Hz for normal walking and higher for running. That frequency band is the single most useful fact in step detection: human steps live in a narrow range, and most confounders either fall outside it or fail the shape test.

Orientation-independence is why magnitude is the default signal. It costs you the ability to distinguish a vertical bounce from a horizontal swing, but it makes the algorithm work in a pocket, a swinging hand, or a bag without requiring the phone to know which way is up.

The pipeline in overview

A robust design has five stages:

1: Acquire samples at a fixed rate with timestamps, buffering them so downstream stages see a uniform cadence. 2: Condition the signal: remove the gravity baseline with a high-pass filter, optionally smooth with a low-pass filter, and reject sensor glitches. 3: Detect candidates: find peaks or zero-crossings that could be steps, with hysteresis and minimum spacing. 4: Validate each candidate against timing, amplitude, and rhythm rules. 5: Count and adapt: increment the step total, and adapt thresholds to the user and conditions.

The critical design decision is where to place the "decision boundary." Early-stage detection (peak finding on the raw signal) is cheap but noisy; late-stage validation (rhythm analysis over a window) is robust but adds latency. Most production pedometers use peak detection with strict timing gates plus a short-window rhythm check, because latency matters to users watching a live count and because the rhythm check can be done on a rolling buffer without delaying the displayed total.

Preprocessing: getting a clean signal

Walking accelerometer data has two components you need to separate: the slowly varying gravity/orientation component and the step-frequency oscillation. A high-pass filter removes the first. A simple and effective choice is a first-order high-pass (a "DC blocker"), which is trivial to implement in a streaming context:

This is an IIR filter that removes the constant offset and passes the step-band oscillations. A first-order high-pass has a gentle rolloff, which is acceptable because the step signal is strong; if you want sharper separation, a second-order Butterworth high-pass with a cutoff around 0.5–1 Hz works well, but it requires more state and careful initialization.

Smoothing is optional but helps on noisy devices. A short moving average (3–5 samples) or a low-pass at 5–8 Hz removes high-frequency jitter without attenuating the 1.5–2.5 Hz step band meaningfully. Be careful not to over-smooth: too much low-pass filtering broadens peaks and merges closely spaced steps.

One preprocessing step that is easy to skip and costly to omit is glitch rejection. Accelerometers occasionally emit spikes (from a drop, a bump against a table, or a sensor transient). Reject any sample whose magnitude differs from the running mean by more than, say, 4–5 g, or simply clamp and flag it. A single enormous spike will otherwise create a false peak or corrupt your adaptive thresholds.

Candidate detection: peaks with hysteresis

The workhorse is peak detection with hysteresis, sometimes called a Schmitt trigger. The idea: a step candidate is registered when the filtered signal rises above a high threshold and then falls below a low threshold. The gap between thresholds prevents noise around a single level from generating multiple counts.

A cleaner formulation for walking signals, where the signal oscillates around zero after high-pass filtering, is to detect positive peaks: a sample is a peak candidate if it is greater than its neighbors and greater than a minimum amplitude. Then apply a refractory period—the minimum time between steps—which for humans is roughly 0.25–0.3 seconds (about 200–240 steps per minute, faster than almost anyone walks). A refractory gate alone eliminates most double-counting.

Two refinements matter in practice. First, use a dynamic threshold rather than a fixed one, because signal amplitude varies with gait, device placement, and user. A common approach maintains a running estimate of the signal's peak amplitude over the last few seconds and sets the detection threshold at a fraction of it (e.g., 0.3–0.5 of the recent maximum). Second, require the peak to be a local maximum over a small window (e.g., ±2 samples) rather than just above threshold, which suppresses counting the rising edge of a peak twice.

A useful additional candidate signal is the zero-crossing rate of the filtered signal. Walking produces a fairly regular alternation; counting upward zero crossings with a minimum spacing gives a second, cheap estimator that can cross-check the peak detector. If the two disagree wildly (say, zero crossings double the peak count), you are likely seeing a harmonic or a noisy segment and can suppress counting until they reconverge.

Validation: timing and rhythm rules

Peak detection on clean walking data is nearly perfect. The failures come from activities that produce periodic oscillation in the step band: hand-waving while talking, tapping the phone, riding a bus over expansion joints, pushing a shopping cart, or jiggling a leg while seated. A validation layer distinguishes these from walking.

Timing rules are the first line. Reject candidates that are too close together (refractory period) or too far apart relative to the recent rhythm. If the last four intervals were ~0.55 s and the next candidate arrives 1.4 s later, it is probably not a step in the same bout; either reject it or treat it as the start of a new bout with reset rhythm statistics.

Rhythm consistency is the strongest discriminator. Maintain a short history of accepted step intervals (say, the last 6–10). Compute their coefficient of variation (standard deviation divided by mean). Human walking at a steady pace has intervals that vary by perhaps 5–10%; random device motion tends to be either far more variable or suspiciously perfect (mechanical vibration). If the CV exceeds a threshold (e.g., 0.25), raise the detection bar or pause counting.

Amplitude consistency adds another check: real steps produce peak amplitudes within a fairly stable range over a few seconds. A candidate whose amplitude is 10× the recent median is likely a bump, not a step.

Bout logic ties it together. Pedometers conceptually count "steps taken while walking," so they need to enter and exit walking states. A simple state machine works:

Idle: no recent candidates. Waiting. Candidate bout: 3–5 plausible steps detected within a few seconds. Tentatively count them but do not commit. Walking: rhythm and amplitude are stable; count every validated step. Exit: no valid candidate for ~1.5–2 seconds, or rhythm degrades; return to idle.

The tentative counting in the candidate phase is what lets you avoid reporting a burst of three false steps from setting down the phone, while still capturing the first few steps of a real walk. Some implementations buffer those tentative steps and only commit them once the walking state is confirmed; others display them immediately and correct later. For a live counter, immediate display with confidence gating on committed totals is usually the better user experience.

Counting, calibration, and adaptation

The count itself is trivial once validation passes: increment on each accepted step. The engineering is in adaptation.

Adaptive thresholds should track slowly. Update the amplitude baseline with an exponential moving average (EMA) over accepted steps only, and clamp the threshold to a sensible floor so that a quiet walk is still detected. If thresholds adapt too fast, a few false steps raise the bar and real steps get missed; too slow, and the detector loses sensitivity after the user changes pace.

Sensor rate adaptation matters for battery. Many phones allow accelerometer rates from ~5 Hz to 200 Hz. Step detection needs at least 20–25 Hz to capture the walking waveform adequately (Nyquist for a 2.5 Hz fundamental plus harmonics puts you well above 5 Hz). A practical policy: run at 25–50 Hz while a walking bout is plausible, drop to 5–10 Hz or suspend sampling entirely after a minute of inactivity, and wake on a coarse motion interrupt if the platform supports one. Some platforms expose a hardware "significant motion" or "step detector" interrupt; using it as a wake trigger while doing your own counting on the raw stream gives good battery behavior.

Handling running: running steps are faster (2.5–4 Hz) and higher amplitude. If your refractory period is fixed at 0.3 s, you will cap detection at 200 steps/min and undercount runners. Either widen the band to allow intervals down to ~0.2 s when amplitude and rhythm suggest running, or treat running as a separate regime with its own thresholds. Be explicit about this in your requirements: a pedometer tuned for walking will systematically undercount running unless you account for it.

Multi-device normalization: accelerometer scale factor and noise vary across phones. Avoid absolute thresholds where possible; prefer thresholds relative to the signal's own recent statistics. Where absolute thresholds are unavoidable, allow a per-device calibration offset learned over time.

A reference implementation sketch

The following is a compact, streaming pseudocode that captures the design. It is language-agnostic; the structure maps directly to Swift, Kotlin, or JavaScript.

Several details in this sketch are deliberately simplified but reflect real design choices. The local-maximum test uses a small buffer; the threshold is relative to a running amplitude estimate; the exit timeout resets state after a pause; the rhythm check rejects irregular bursts after enough intervals have accumulated. The idleCounter implements the "confirm a bout before committing" idea in a minimal form—three plausible candidates in quick succession are needed to start counting from idle.

In a production implementation you would also want: timestamp-based interval math (not sample-count-based), handling of dropped samples from the OS, hysteresis on the walking state to avoid flicker, and a persistence layer so the count survives app restarts and sensor pauses.

Testing and tuning

Accuracy claims for pedometers are usually stated in terms of error over a defined activity set, and the numbers vary widely by study design and device. Rather than chasing a specific percentage, build a test harness that measures the failure modes you care about:

Walk a known number of steps at slow, normal, and brisk paces, in pocket and in hand. Count error per condition. Run a known distance and compare against a manual count. Confounder scripts: sit and jiggle a leg, ride a bus, push a cart, tap the phone. Correct output is near zero. Transitions: walk, stop, walk again; the bout logic should not double-count the resumption or lose steps at the boundary.

Tune thresholds against this matrix, and log the raw signal alongside the algorithm's decisions so you can replay and debug. A common mistake is tuning only on walking data and then discovering that the detector fires constantly when the phone is on a vibrating surface; the confounder tests catch this early.

Also be honest about what the algorithm cannot do. A single accelerometer cannot reliably distinguish walking from, say, stepping in place or a slow treadmill shuffle at very low amplitude—these produce the same waveform. And a phone in a loose bag may attenuate the step signal below the noise floor of a cheap accelerometer, causing undercounts that no threshold tuning will fix. Document these limits rather than promising universal accuracy.

Design decisions that matter most

If you take away five points from this design, make them these. Use the acceleration magnitude to get orientation independence, and high-pass filter it to isolate the step band. Detect peaks with a refractory period rather than counting threshold crossings, because crossings double-count. Validate with rhythm and amplitude consistency over a short window, because timing alone cannot separate walking from periodic confounders. Use a bout state machine so you neither count bumps from setting the phone down nor lose the first steps of a walk. And make thresholds relative and adaptive so the algorithm survives different users, paces, and devices without per-device calibration.

The result is not a perfect pedometer—no accelerometer-only pedometer is—but it is a defensible, explainable one whose errors you can characterize and whose behavior you can tune against real data.