<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by FouadRobotics on Medium]]></title>
        <description><![CDATA[Stories by FouadRobotics on Medium]]></description>
        <link>https://medium.com/@ahmedfouadrobotics?source=rss-6e221ebe955a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by FouadRobotics on Medium</title>
            <link>https://medium.com/@ahmedfouadrobotics?source=rss-6e221ebe955a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 16:47:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmedfouadrobotics/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Golden Dome Data Link Signal Processing Algorithm: Part 1]]></title>
            <link>https://medium.com/@ahmedfouadrobotics/golden-dome-data-link-signal-processing-algorithm-part-1-56fadd11f509?source=rss-6e221ebe955a------2</link>
            <guid isPermaLink="false">https://medium.com/p/56fadd11f509</guid>
            <category><![CDATA[radio]]></category>
            <category><![CDATA[xilinx]]></category>
            <category><![CDATA[signal-processing]]></category>
            <category><![CDATA[fpga]]></category>
            <category><![CDATA[radar]]></category>
            <dc:creator><![CDATA[FouadRobotics]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 00:33:21 GMT</pubDate>
            <atom:updated>2026-08-30T00:33:21.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*Vk_QrsHpCodlDyad" /></figure><p>Introduction, Principles, and Transmitter Simulation</p><p>A signal-processing and FPGA-implementation series</p><p>1 — The Golden Dome initiative</p><p>On 27 January 2025, President Donald Trump signed Executive Order 14186, directing the Department of Defense to field a next-generation missile-defense shield for the United States. The program — first titled “The Iron Dome for America” and shortly afterward renamed “Golden Dome for America” — was elaborated in a 20 May 2025 White House announcement that put its projected cost near $175 billion. Unlike a single point-defense battery, Golden Dome is conceived as a layered, continent-scale shield that fuses space-based sensors, ground and sea radars, and a mix of kinetic and non-kinetic effectors into one integrated air- and missile-defense system.</p><p>2 — Why the dome needs a unified data link</p><p>A shield of this scale is not one weapon but a system of systems. Its sensors and effectors are owned and operated by different branches — the Army’s ground radars and interceptors, the Navy’s Aegis ships, the Air Force’s airborne sensors and aircraft, and the Space Force’s overhead tracking layer — and, in coalition scenarios, by allied forces as well. For the dome to detect, track, and engage a fast-moving threat within seconds, every one of these nodes must share the same tactical picture in real time: track updates, sensor cueing, fire-control solutions, and battle-management orders.</p><p>That real-time common picture is only possible over a unified data link — a communications fabric that ties the domains together. The obstacle is heterogeneity: different modulations, message formats, frequency bands, and data rates will inevitably coexist across the branches, arising naturally from their differing tactical operations, operating environments, networking requirements, and weapon- and system-level specifications. A Golden Dome data link must therefore be able to receive and process many different waveform families through one common signal-processing architecture, rather than a separate, stovepiped radio per service.</p><p>3 — What this means for the signal-processing algorithm</p><p>Carrying that diversity through a single processing chain places concrete demands on the algorithm. The receiver architecture has to account for:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8m6pLOSQsE-lRYAmJqmm9g.png" /></figure><p>Size, weight, and power (SWaP) is, of course, a first-order constraint for any deployable data-link terminal — and it is far from the only one. A fielded terminal must also answer to cost, security (anti-jam, low probability of intercept and detection, and cyber-hardening), reliability, thermal management, electromagnetic compatibility, among others. These articles, however, deliberately scope themselves to the signal-processing algorithm and its FPGA implementation; SWaP and these other system-level trade-offs are out of scope here.</p><p>4 — How the transmitter simulation addresses these needs</p><p>To design and validate such a receiver, we first need a realistic stimulus. The transmitter simulation is a MATLAB testbench that synthesizes a single composite RF scene, deliberately built to mimic a contested multiband battlespace: six independent communication systems, spanning four frequency bands, each using a different modulation, data rate, and frame structure, each frequency-hopping within its own band — all summed on a common wideband clock and then hit with jamming and thermal noise. The six systems are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZ4Zp9vNhk5BibQGfry1qA.png" /></figure><p>Modulation, band, and frequency diversity. The composite spectrum places all six systems on one wideband view: distinct spectral signatures sitting at their L/S/C/X carriers, from 1.5 GHz up to 10 GHz. A single receiver front end has to span this entire range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*uq-7HjS5mMou6gb3rL_amA.png" /><figcaption>Figure 1 — Composite spectrum of all six systems across the L, S, C and X bands.</figcaption></figure><p>Data-rate and timing diversity. Viewed in the time domain, one panel per system (before summing), the systems differ in burst duration, activity windows, and hop cadence — the high-rate 16-QAM stream is busy across almost the whole record, while the low-rate links send short, sparse bursts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*0cvZXPQjUKLcnHhU7CPAhQ.png" /><figcaption>Figure 2 — Per-system passband waveforms (before summing), sharing a common time axis.</figcaption></figure><p>Frequency hopping. Each system hops among its own set of channels within its band. A per-system spectrogram makes the hop pattern explicit — shown here for three examples spanning the rate range: the low-rate BFSK link, the mid-rate GMSK link, and the high-rate 16-QAM link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*9tdnr79E830u4k-AFid9Ew.png" /><figcaption>Figure 3 — BFSK hopping across its 4 channels in the L band.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*IE51ni5gImAiq69CAFFe7A.png" /><figcaption>Figure 4 — GMSK hopping across its 6 channels in the C band.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*MCBmlacQEck-9oRvAYkgtQ.png" /><figcaption>Figure 5 — 16-QAM hopping across its 8 channels in the X band.</figcaption></figure><p>Message-structure diversity. Each modulation family carries its own frame layout, and a receiver must match the per-family structure to acquire and decode it. Across the six systems this ranges from front-loaded non-coherent FSK frames (long preamble plus a Barker sync word), to a DQPSK burst led by a unique word and trailed by a network/colour code, to a GSM-style GMSK burst that places its training sequence (midamble) in the middle and guards both ends with tail bits, to a coherent 16-QAM frame that inserts a pilot for phase/gain estimation and forward-error-corrects its payload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OvErS250yRkxpSJyJBVKA.png" /><figcaption>Figure 6 — All six frame structures, illustrating message-format diversity.</figcaption></figure><p>Phase and frequency errors. No real transmitter or channel is ideal, and the testbench bakes the dominant hardware- and propagation-induced impairments into every burst, so the receiver is exercised against realistic, non-ideal signals. Their physical origins matter, because they determine what the receiver must estimate and correct:</p><p>* Carrier frequency offset / Doppler — relative motion between the two ends shifts the received carrier (the Doppler effect), and any error in the frequency reference adds a static offset on top. It is most severe in exactly the high-dynamics scenarios a Golden Dome link must handle: a low-earth-orbit satellite races across the sky and can impose tens of kilohertz of Doppler that sweeps as it passes, while fast targets and airborne platforms add shifts of their own. The X-band 16-QAM link carries a ±100 kHz Doppler term for this reason.</p><p>* Phase noise — the local oscillators (the VCOs and PLLs that set the carrier) are never spectrally pure; their short-term phase fluctuations smear the carrier and randomly rotate the constellation. The effect grows with carrier frequency and with cheaper references, so it bites hardest at X-band.</p><p>* I/Q gain and phase imbalance — an analog quadrature modulator splits the signal into in-phase (I) and quadrature (Q) arms; component tolerances, board layout, and temperature leave the arms slightly mismatched in gain and off an exact 90° split. The result is a skewed constellation and a spectral image of the wanted signal.</p><p>* Symbol-clock jitter — the symbol clock is not perfectly periodic — reference instability, temperature, and ageing move the sampling instants — which blurs symbol boundaries and, on continuous-phase waveforms, warps the phase trajectory.</p><p>* Tone-deviation and BT tolerances (FSK / GMSK) — an FSK link sets its tone spacing with a VCO’s deviation gain; if that gain is mis-set, the mark and space tones land off their nominal frequencies. GMSK’s pulse is defined by a Gaussian bandwidth-time product (BT), and a mistuned shaping filter changes the pulse and its spectral occupancy.</p><p>These are precisely the errors a robust receiver must track out — carrier and timing recovery, I/Q correction, and equalization. The three examples below each place the impaired signal against its own ideal (error-free) reference: the 16-QAM constellation (an ideal grid versus points scattered and skewed by EVM and I/Q imbalance), the DQPSK differential constellation (ideal decision points versus impaired scatter), and the GMSK phase over a few bits (the impaired trajectory pulled off the ideal by deviation error and symbol-clock jitter). The deployed tolerances are deliberately small, so the phase view exaggerates them for legibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*vc0rRwwyRGhcPg05PNQ7yg.png" /><figcaption>Figure 7 — 16-QAM constellation — ideal (nominal) grid vs impaired points (EVM + I/Q imbalance).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*zmNbO2fxmB2i9YK89xb-Mg.png" /><figcaption>Figure 8 — DQPSK differential constellation — ideal decision points vs impaired scatter.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*_T8odv4t0xe8YAF9J3tHJw.png" /><figcaption>Figure 9 — GMSK phase over a few bits — nominal vs impaired (deviation + jitter, exaggerated for clarity).</figcaption></figure><p>Jamming. A configurable barrage noise jammer can be placed on each band. The example below sets the signal-to-jammer ratio to 20 dB: the jammer’s noise floor rises to roughly 20 dB below the signal peaks and blankets every hop channel of the 16-QAM link, so no single channel can hop clear of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*3C8VXCjY7pmVRcBxuZ91vA.png" /><figcaption>Figure 10 — One system’s spectrum overlaid with its barrage jammer at a 20 dB signal-to-jammer ratio.</figcaption></figure><p>Taken together, these features make the transmitter a faithful proxy for the requirements of Section 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7X4CF27ROHX8EqQTEj5Kg.png" /></figure><p>5 — Coming next</p><p>Article 2 turns from stimulus to design. It covers the frequency, data-rate, and decimation planning that underpins the receiver’s clocking; a brief look at the RF front-end simulation (out of scope as a deliverable, but necessary to design a correct processing chain); and the heart of the channelization stage — polyphase channelizers and digital down-converters, with the design of their filter banks and decimating filters.</p><p>Code + docs: <a href="https://github.com/FouadRobotics/Golden-Dome-datalink-algorithm">https://github.com/FouadRobotics/Golden-Dome-datalink-algorithm</a></p><p>References</p><p>* Executive Order 14186, “The Iron Dome for America,” 27 January 2025.</p><p>* Congressional Research Service, “Defense Primer: The Golden Dome for America” (IF13115), congress.gov.</p><p>* CSIS, “America’s Golden Dome Explained,” csis.org.</p><p>* White House announcement of the Golden Dome architecture, 20 May 2025.</p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/golden-dome-data-link-algorithm-ahmed-fouad-hi8ac/"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56fadd11f509" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On Phones as Edge Computer Replacements]]></title>
            <link>https://medium.com/@ahmedfouadrobotics/on-phones-as-edge-computer-replacements-df02be4578ec?source=rss-6e221ebe955a------2</link>
            <guid isPermaLink="false">https://medium.com/p/df02be4578ec</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[apple-silicon]]></category>
            <category><![CDATA[edge-computing]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[FouadRobotics]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 21:30:10 GMT</pubDate>
            <atom:updated>2026-06-29T02:07:27.827Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why the standard “edge PC + cameras + sensors + GPIO-driven actuators” robotics stack is an artifact of when it was designed, and what a phone-centric architecture — a modern smartphone or tablet paired with a small MCU — replaces it with.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txGHxZvyXIrszG5XE3yq4w.jpeg" /></figure><h3>What This Article Covers</h3><p>· Why the traditional edge-PC robotics stack is a 2010s pattern.</p><p>· Peer-reviewed evidence that phone-based VIO beats RealSense, Zed, and embedded-SBC SLAM.</p><p>· A real-world result on a six-year-old iPhone 11 Pro Max.</p><p>· How phone-class compute density and vertical integration beat the traditional stack.</p><p>· The proposed architecture: phone for perception + ML + planning; MCU for low-level motor control; wireless between.</p><p>· The on-device ML that ships free with modern phones.</p><p>· The reasons it hasn’t taken over yet.</p><p>· Why the supply-chain outlook makes the traditional architecture worse.</p><p>· What the architecture enables at the limit — drones, BYO-phone robots, Apple-Silicon-integrated robots.</p><p>I’ve been building autonomous behaviors into an RC car for a while now, and every iteration of my stack has looked roughly the same as the stack you’ll find on almost any small-to-medium robot built today: a <strong>sensor suite</strong> at the front — cameras, IMU, lidar, GPS, whatever the use case calls for — an <strong>edge computer</strong> in the middle running perception, planning, and (through its own GPIO header) the low-level control signals out to the <strong>actuators</strong>. It’s the canonical robotics architecture — a pattern that the modern robotics community settled on in the early 2010s and has been refining ever since.</p><p>The problem is that this pattern was designed for a world that no longer exists. When ROS and ROS 2 took shape, phones were not a credible compute platform for anything that mattered. Their cameras were noisy, their SoCs throttled aggressively, and there was no realistic way to get raw sensor streams out of them. So the entire mapping / SLAM / perception ecosystem — Intel RealSense, Stereolabs Zed, Luxonis OAK-D, NVIDIA Jetson, Raspberry Pi — grew up around dedicated hardware.</p><p>Strip a robot down to its essentials, though, and there are only three jobs to do: <strong>perception</strong> (sense the world), <strong>planning</strong> (decide what to do), and <strong>control</strong> (actually move the actuators). That’s it. The traditional architecture mixes all three onto a Linux SBC with separately-sourced sensors bolted on. But in the meantime modern phone SoCs — Apple Silicon, Qualcomm Snapdragon, Google Tensor — got absurdly good, and almost nobody in robotics noticed that a modern phone, with no modification, now does the perception and planning sides of that triplet extraordinarily well. Both are exactly the kind of compute the consumer phone industry has spent years optimizing for.</p><p>The thing that pushed me to write this was a series of concrete results on my own hardware. I took an iPhone 11 Pro Max — a six-year-old phone — and used the <a href="https://introlab.github.io/rtabmap/">RTAB-Map</a> iOS app to walk the entire perimeter of an apartment complex in one pass. The iPhone produced a drift-corrected odometry trajectory of the loop and a sparse 3D point cloud of the visual features it tracked along the way — all in real time, with no external sensors and no tuning. Visual SLAM at that scale and accuracy, running in real time, is a genuinely demanding workload — and there is nothing in the traditional architecture at the same price point — and I mean <em>nothing</em> — that can do it out of the box; not a Pi 5 with a stereo USB camera, not a Jetson Orin Nano with a RealSense, not anything else in this budget range.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FfHhjl6iUuPM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DfHhjl6iUuPM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FfHhjl6iUuPM%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/441993dd3f9f3e3ddeca56eda58c0c7d/href">https://medium.com/media/441993dd3f9f3e3ddeca56eda58c0c7d/href</a></iframe><p>And here’s what makes the result especially striking: the <strong>iPhone 11 Pro Max has no direct way to perceive depth</strong>. There is no LiDAR — that scanner only arrived on the iPhone 12 Pro and later Pro models. And even though the phone’s three-camera array could in principle be used as a stereo rig, ARKit does not use it that way: ARKit runs <strong>monocular visual-inertial odometry</strong> — a single camera plus the IMU — because it has to work on every iPhone Apple ships, including the ones with only <em>one</em> rear camera. Monocular VIO is the category of SLAM that classically suffers the worst scale ambiguity and drift; it is supposed to be the hard mode. The iPhone is producing a scale-consistent, drift-corrected trajectory plus a sparse 3D point cloud in monocular mode, on a six-year-old chip — while the canonical hardware that the same workload supposedly needs is a dedicated camera module (RealSense, Zed, OAK-D, or similar, $300–$500) paired with an edge computer (a Pi, Jetson, or x86 box, $500+) running an open-source VIO stack in real time. Two boxes, four-figure totals, and <em>worse</em> trajectory accuracy than a single phone.</p><p>Below I’ll walk through the two architectures side by side, lay out where the traditional stack hurts in practice, and then turn to why the better architecture hasn’t taken over yet.</p><h3>The Traditional Architecture</h3><p>This is the shape that almost every hobby robot, every educational platform, and a lot of small commercial robots take today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDWzS67--ffomINHn0S7ug.png" /><figcaption><strong>Figure 1 — </strong><em>Traditional robotics architecture. A use-case-specific sensor suite (cameras, IMU, GPS, lidar, rangefinders, encoders — whichever the application requires) feeds an edge PC that runs perception and planning, and drives the actuators directly through its own GPIO header (PWM, SPI, I²C). Each sensor sits on its own bus; nothing is hardware-synchronized below the user-space layer.</em></figcaption></figure><p>The two subsystems:</p><p>· <strong>Sensor suite</strong> — whatever combination of cameras (RGB, stereo, depth), IMU, GPS, lidar, rangefinders, encoders, and other breakouts the application requires. Each typically connects over its own bus (USB, MIPI, I²C, SPI, UART) and is sampled in user-space on the edge PC.</p><p>· <strong>Edge PC</strong> — a single-board computer (Raspberry Pi, Jetson, BeagleBone) or a small x86 box. Runs Linux, ROS / ROS 2, the perception + planning stack, and — through its 40-pin GPIO header — generates the PWM / SPI / I²C signals that drive the motor controllers and servos directly. No separate MCU in the minimal canonical setup.</p><h3>Why this looks reasonable on paper</h3><p>It’s the modular setup everyone teaches: separation of concerns between perception, planning, and real-time control. ROS 2 nodes are easy to wire up. There’s a giant ecosystem of packages — ORB-SLAM3, VINS-Fusion, RTAB-Map, Nav2 — all assuming exactly this Linux SBC shape.</p><h3>Why it’s frustrating in practice</h3><p>Four things hurt every time I sit down to use it.</p><p><strong>1. Mixing sensors from different vendors means giving up on hardware synchronization.</strong> The moment you pick a camera from one supplier, a lidar from another, and a GPS from a third — which is what almost every real-world robot stack ends up doing, because no single vendor sells exactly the combination of sensors any given application needs — you have given up on a shared hardware clock between them. Each sensor arrives over its own bus on its own clock, each vendor’s driver hands you timestamps in its own frame of reference, and the reconciliation happens in user-space on the edge PC. The jitter that introduces is on the order of 5–20 ms before you have even started filtering. That jitter is the single largest error source for visual-inertial odometry on this kind of stack, and it is structural — you cannot software your way out of it.</p><p><strong>2. And even when you stay inside a single vendor’s hardware-synced module, the sync is still worse than what phones already do — and the phone outperforms the dedicated hardware directly.</strong> The Intel RealSense D435i is widely considered the standard, but its hardware sync between IMU and image is roughly <strong>2.5 ms</strong>, on a module that costs over $400. The Zed and the OAK-D have variants of the same number. Apple, meanwhile, hardware-syncs the cameras and the IMU at the silicon level — well under a millisecond, easily an order of magnitude tighter than the RealSense’s 2.5 ms — and that tighter sync is a direct reason ARKit’s tracking accuracy is what it is. They do it because they need it for ARKit, and they ship it for free inside a phone you may already own. The same pattern holds across the phone industry — hardware-synced cameras and IMU are table stakes on every modern flagship, because every phone maker needs them for AR.</p><p>Three peer-reviewed studies make the gap concrete. The first (Kim et al., <em>Sensors</em>, 2022) benchmarked an iPhone and an Android phone against two of the most popular dedicated robotics cameras on visual odometry across six real-world routes, ending with a <strong>3 km drive through a city</strong>. On that hardest test, the Intel RealSense T265 <em>gave up entirely</em>; the Stereolabs ZED 2 ended up <strong>409 m</strong> away from where it actually was. The iPhone was off by <strong>2.68 m</strong> — better by <strong>two to three orders of magnitude</strong>, at roughly the same retail price.</p><p>A second study (Marino et al., <em>Sensors</em>, 2022) broadened the comparison across eight phones and tablets at different price points, and confirmed that even cheaper phones beat the dedicated camera modules — with the LiDAR-equipped iPad Pro posting the best accuracy of any device tested. A third (Delmerico and Scaramuzza, <em>ICRA</em>, 2018) showed that the open-source tracking software the small-computer ecosystem depends on can’t actually run well on those small computers: most of the leading algorithms either failed outright or had to be slowed down so much they lost accuracy.</p><p>The takeaway across all three papers is the same: at the same price, phones beat the dedicated cameras, and the standard open-source software can’t fully run on the small computers it was meant for. The traditional setup is the bottleneck — and modern phones already sit comfortably outside it.</p><p><strong>3. The bill of materials looks small per part and large in aggregate, and the supply outlook is getting worse.</strong> Edge PC, the sensor modules the use case requires (cameras, IMU, GPS, lidar, encoders, etc.), motor drivers, SSD, cooler, case, cables — the total tends to land somewhere between $1,000 and $1,500 for anything you’d want to put a real perception workload on. And every component sits inside the global semiconductor supply chain, which has been unstable for years. There’s no on-board storage that comes with the SoC for free, and no built-in connectivity beyond Wi-Fi / Bluetooth. Each of those is a separate decision and a separate purchase.</p><p>The strategic outlook makes this materially worse. NVIDIA is increasingly focused on enterprise data-center GPUs and AI accelerators — that’s where the margins are, that’s where the order volumes are, and that’s where the corporate strategy now lives. Consumer GPUs and edge-compute kits like the Jetson Nano line are visibly less of a priority every year. Smaller players — Raspberry Pi, BeagleBone, the educational-tier SBC vendors — are not going to escape the upcoming wave of AI-driven memory and storage bottlenecks; they are going to be the ones who lose the price war for DRAM and NAND when hyperscalers absorb the supply. The hardware you build a robot stack on today may not be the same hardware you can buy at the same price next year. Meanwhile, the phone supply chain — Apple, Samsung, Google, Xiaomi, and the rest of the pack — is the most resilient and best-priced one in consumer electronics.</p><p><strong>4. The software environment on edge SBCs is fragile in a way modern phone stacks are not.</strong> Start integrating a few sensors on an SBC and you quickly discover the real workload isn’t the robot algorithm at all — it is reconciling ROS versions against Ubuntu versions against the specific sensor drivers each vendor ships, each one pinned to a different base image or kernel. The actual day-to-day work becomes editing CMakeLists files, chasing dependency conflicts, and rebuilding workspaces, not writing the perception or planning code you sat down to write. And the moment you try to escape that mess by upgrading the system — run sudo apt update &amp;&amp; sudo apt upgrade on a Jetson and there is a non-trivial chance you have just broken your CUDA / cuDNN / TensorRT stack — JetPack’s dependency tree is notoriously brittle, the L4T base layer pins binary versions that Ubuntu’s package manager doesn’t know about, and any meaningful upgrade can cascade into hours of dpkg debugging. Pi OS isn’t quite as bad, but the same risk shows up the moment you mix vendor binary blobs (camera drivers, NN runtimes, hardware-acceleration libraries) with apt-managed packages. The contrast with the modern phone stack is the entire pitch of vertical integration: one company owns the SoC, the OS, the driver layer, the AR/ML frameworks, and the GPU API. iOS updates don’t break ARKit. Android updates don’t break ARCore. The phone industry — Apple, Google, Samsung, Qualcomm, all of them — has done the integration work that the robotics-SBC ecosystem has been quietly outsourcing to its users for years.</p><p>There’s also a fifth, less obvious cost: <strong>size and weight</strong>. You cannot fit this architecture on a small drone. Whole classes of small mobile robots are simply ruled out by the geometry of this stack.</p><h3>The Phone-Centric Architecture</h3><p>Here’s the architecture I’m proposing instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4Z2SH2b6QfEmAKArAynJQ.png" /><figcaption><strong>Figure 2 — </strong><em>The phone-centric architecture. A modern phone is the entire compute and sensor suite — cameras hardware-synced to the IMU at the silicon level, GPU on-die, GNSS and radios included. A small wireless MCU bridge handles only the deterministic GPIO and motor control that the phone OS is not allowed to do; the MCU in turn drives a motor controller for the actuators.</em></figcaption></figure><p>Two parts. The phone (an iPhone or iPad in my build, but any modern flagship phone or tablet of the same generation works the same way) is the entire compute + sensor suite. A small MCU hangs off it — over BLE or Wi-Fi — and handles the real-time GPIO that the phone OS is physically incapable of exposing to a third-party app. That’s it.</p><h3>What a modern phone gives you for free</h3><p>This is the part that, the more I list it out, the harder it gets to argue with. Every modern flagship phone — iPhone or Android — ships some version of this list, with only minor variation between vendors. A recent flagship typically includes:</p><p>· <strong>Two or three hardware-synchronized cameras</strong> already locked to the IMU clock at the silicon level. The same cameras can also be used together as a stereo pair to give the phone direct depth perception.</p><p>· <strong>A 6-axis IMU plus magnetometer plus barometer</strong> built in.</p><p>· <strong>GNSS</strong> (multi-band L1 + L5 on recent flagships).</p><p>· <strong>A LiDAR scanner</strong> on every Pro iPhone since the iPhone 12 Pro, exposed directly through ARKit; several Android flagships (e.g., Samsung’s Ultra line in earlier generations, current Honor and Huawei Pro models) ship comparable time-of-flight depth sensors as well.</p><p>· <strong>A capable GPU and a multi-core CPU.</strong> Modern phone SoCs — Apple Silicon, Qualcomm Snapdragon, Google Tensor — are designed to run AAA-class games at sustained frame rates for hours. They are categorically capable of the same workload running as a robotics perception loop.</p><p>· <strong>Wi-Fi 6, Bluetooth 5+, LTE / 5G, and UWB.</strong> Everything you need to talk to the robot, the cloud, and yourself — included.</p><p>· <strong>256 GB to 1 TB of NAND storage</strong> built in on modern flagships (iPhone and Android Pro tiers all sit in this range). No add-on storage, no separate purchase.</p><p>· <strong>A thermal envelope tuned for sustained gaming.</strong> Modern flagship phone SoCs are designed to take heavy GPU load for extended periods without thermal throttling, in a chassis the size of a deck of cards. Most edge SBCs throttle in minutes under the same load — which directly caps how long their perception stack can stay at its peak compute rate.</p><p>A natural follow-up objection at this point is: <em>but phone cameras are rolling-shutter, and rolling shutter is genuinely bad for high-motion robotics work.</em> That’s true — a $400 global-shutter machine-vision camera with a hardware-synced exposure is, in pure sensor terms, a better front end. For the phone’s own built-in AR pipeline this isn’t actually an issue, because the platform has <em>already</em> solved it — on the iPhone, for example, ARKit’s tracker models the rolling shutter and produces the corrected pose stream that the rest of the system consumes (ARCore does the equivalent on Android). The point at which it matters is the moment you step <em>outside</em> the platform’s AR framework — a custom SLAM implementation, a high-rate optical-flow loop, a learned-feature tracker, anything where you want raw frames. The answer there is to do the rolling-shutter correction yourself in software: model the per-scanline exposure timing (parameters you can recover with a one-time camera-IMU calibration in <a href="https://github.com/ethz-asl/kalibr">Kalibr</a>) and warp the image back into a global-shutter equivalent on every frame. It’s a known, well-understood algorithm; what it costs is compute. The Pi 5 doesn’t have enough compute to run it in real time alongside SLAM. Modern flagship phone SoCs do, comfortably, on the GPU. This is exactly the kind of tradeoff the architecture makes constantly: <em>use compute density to cancel out cheaper sensor hardware</em>, instead of paying $400 for the sensor in the first place.</p><p>And then the supply chain dimension: the phone industry’s procurement and manufacturing arms — Apple, Samsung, Google, Xiaomi, and the rest of the pack — are <em>categorically</em> better than anything a smaller SBC company can match. The cost per unit of compute, sensor, and connectivity inside a modern phone is the lowest in the world, by a wide margin, and the prices keep falling. A used flagship phone two or three generations old already outperforms most current robotics-dedicated edge hardware at a fraction of the price.</p><p>And the phone’s capabilities are not limited to VIO. The same hardware that runs ARKit (or ARCore on the Android side) also runs dense depth fusion, 3D scene reconstruction, room-scale photogrammetry, real-time semantic segmentation, on-device LLMs, and — increasingly — <strong>survey-grade dimensional measurement</strong>.</p><p>The most striking recent demonstration is <a href="https://youtu.be/dt8khUv_lL0">this video</a> comparing the iPhone 17 Pro against a professional <strong>total station</strong> — the laser-and-theodolite instrument surveyors have used for decades, typically $20,000–$60,000. Paired with an external <strong>RTK GNSS receiver</strong> that streams centimeter-accurate position over Bluetooth, the iPhone produces measurements within a small fraction of the total station’s precision, in a fraction of the setup time, with the result already in a 3D mesh. A consumer phone and an RTK dongle.</p><p>That pairing maps directly onto the architecture this article is proposing: the RTK module hangs off the MCU and forwards its centimeter-accurate fix to the phone, which fuses it with the on-device AR mesh in real time. The whole stack — phone plus RTK module — lands around $4,000, against a total station at <strong>$40,000–$60,000</strong>. Roughly two orders of magnitude, on the same chip already running the robot’s perception, planning, and on-device ML. It is not an add-on, not a separate product you have to buy — it is a feature the consumer-electronics industry already paid for.</p><h3>What modern phones already ship as ready-to-use ML models</h3><p>And the on-device toolkit doesn’t stop at VIO. Free with the OS, modern phones ship ready-to-use APIs for full-body skeletal pose, 2D and 3D hand pose, world-frame 3D body tracking, scene-mesh semantic segmentation, instance segmentation, dense optical flow, animal pose, face landmarks and blendshape face tracking, ball-and-projectile trajectory tracking, text and barcode recognition, sound classification across hundreds of built-in classes, on-device speech recognition, and on-device LLMs — all running on the GPU, all callable from two or three lines of code. On the iPhone these are exposed through the <strong>Vision</strong>, <strong>ARKit</strong>, <strong>Sound Analysis</strong>, <strong>Speech</strong>, and <strong>Core ML</strong> frameworks; on Android the equivalents are <strong>ML Kit</strong>, <strong>ARCore</strong>, <strong>MediaPipe</strong>, and <strong>TensorFlow Lite</strong>. Every one of those capabilities is a multi-week project on the traditional Linux-SBC stack — choose a model, convert it to TensorRT, profile the throughput, write the ROS wrapper. On a phone each one is a single API call. Multiply that gap across the list and the architecture comparison gets lopsided in a way the hardware-only comparison only hints at.</p><h3>What the phone cannot do</h3><p>There’s exactly one thing a phone can’t do, and it’s the one thing a microcontroller is built for: deterministic, sub-millisecond GPIO. A phone has no exposed pins. iOS (and Android, for the same security and power-management reasons) won’t let an app run a tight ISR loop. You cannot bit-bang a motor encoder from a phone app.</p><p>So a small MCU — an ESP32, an RP2040, an STM32 — sits next to the motor driver, handles the low-level motor control, and exposes itself to the phone over BLE or Wi-Fi. The phone sends high-level commands (“drive at 1.2 m/s, turn 15°”) at the rate of perception, and the MCU takes care of everything below that. The traditional Pi-based stack didn’t need this split because the Pi’s own 40-pin GPIO header can drive motors directly; a phone doesn’t have a 40-pin header, so the MCU plays the role those pins played on the Pi. That’s the <em>only</em> reason it’s there.</p><h3>The Real Reasons This Architecture Hasn’t Taken Over</h3><p>If a phone is so obviously better, why is essentially every hobby robot and every educational robotics platform still shaped like the traditional stack? I’ve been chewing on this and I think there are three reasons, in roughly ascending order of how solvable they are.</p><h3>1. The software ecosystem grew up elsewhere</h3><p>This is the real obstacle, and it isn’t an accident. For years, almost every paper, almost every open-source SLAM repository, and almost every reference implementation in robotics has been written for NVIDIA CUDA on x86 or for ARM Linux single-board computers like the Raspberry Pi and the Jetson — because NVIDIA, Intel, and the other dedicated-hardware vendors fund a large fraction of the academic robotics and computer-vision community, and funded groups target the funder’s hardware. When those graduates leave academia for industry, they take their toolchains with them, and the whole field converges on the same handful of stacks.</p><p>The result is that almost nothing of consequence is optimized for the iOS or Android ML backends, even though those backends are perfectly capable of running the same workloads on phone-class silicon. The hardware was ready a long time ago; the software ecosystem wasn’t. It’s the same dynamic that kept the Mac out of the AI/ML conversation for a decade — until Apple Silicon made it impossible to ignore. The Mac Mini’s local-LLM moment is the template for what happens to robotics when phones and tablets get the same treatment.</p><h3>2. Mobile development, the dissolving barrier</h3><p>The most common objection here is that most robotics teams aren’t used to iOS or Android development, and the Swift / Kotlin learning curve is enough to keep them on the familiar ROS-and-Python stack (and as a side note, Embedded Swift now exists, so if you already know Swift you can write the full robotics algorithm on the phone and the real-time code on the MCU in the same language). The objection is fair — but it is collapsing on three fronts at once.</p><p>First, the tooling itself has become genuinely approachable: <strong>Apple’s built-in vision, AR, and machine-learning toolkits</strong> expose state-of-the-art capabilities in two or three lines of Swift, with no CUDA versions to pin and no JetPack to reflash. Second, the development hardware itself is no longer a barrier — a <strong>Mac Mini M4 starts at $599 new</strong>, cheaper than a mid-range Jetson developer kit, and used M-series Macs run $300–$600. Third, LLM-assisted development has erased most of what was left — Claude, Cursor, ChatGPT, and Copilot can scaffold a working iPhone or Android robot app in a single sitting, with the developer reviewing rather than writing from scratch. The “we don’t do Swift” objection presumes a world where every developer learns each new stack the hard way, and the trend is pointing the opposite way.</p><h3>3. Privacy is an underrated advantage</h3><p>Most home robots with cameras today either upload frames to a vendor cloud or do their inference on a low-end on-device chip and still phone home for the “smart” features. Running the entire perception pipeline on the user’s own personal phone — a device they already trust with their entire life, and one whose privacy posture (iOS or Android) is materially more consumer-aligned than any robot vendor’s cloud — is the obvious answer, and nobody is shipping it.</p><h3>What This Buys You at the Limit</h3><p>Three cases where the phone-centric architecture isn’t just cheaper but enables things the traditional architecture can’t. The first is about <em>carrying</em> a phone on a class of robot the traditional stack physically can’t fit on. The second is about <em>attaching</em> a phone the user already owns. And the third — the most important — is about treating phone-class silicon as the right SoM (system-on-module) for <em>every</em> robot, including ones the user never sees a phone in.</p><p><strong>Small drones.</strong> A sub-250 g drone — the DJI Mini class — cannot carry a Jetson + RealSense at all; with carrier board, battery, cables, and mounts the stack pushes well past that limit. Even a 500 g–1 kg airframe carries it barely, at real cost to flight time and agility, which is why most onboard-SLAM research drones still sit in the 1–2 kg class. A modern phone with hardware-synced VIO and phone-class compute, at 150–230 g, is on the table for the first time at the sub-500 g scale.</p><p><strong>Personal robots that borrow the user’s phone.</strong> Imagine the boxing-trainer robot at home, or the kitchen-helper robot. Imagine the price point of each of those if the perception and AI are <em>factored out</em> of the BoM because the customer brings their own phone. The customer’s phone (an iPhone, in the Apple-centric version of this story) slots into a dock on the robot when they want to use it and pops out when they don’t. The robot itself ships with motors, an MCU, a frame, and a battery — nothing else.</p><p><strong>Dedicated robots that integrate phone-class silicon directly.</strong> This is the case I want to make harder than I usually see it made. Even when you are building a robot that ships as a standalone product — no customer phone involved, ever — it is still better to take a phone SoC (Apple’s A-series or M-series, Qualcomm’s Snapdragon, Google Tensor) along with its native cameras, IMU, and radios, and integrate them as the compute core of your robot than it is to build the traditional edge-PC + dedicated-cameras + IMU-breakout stack from discrete parts. The phone industry has spent years and trillions of dollars optimizing exactly this collection of silicon for compute density, sensor sync, and cost. The reason a phone is the best edge computer for robotics isn’t a quirk of consumer ergonomics; it’s that the silicon inside it is the best-engineered package of mobile compute and sensors that human industry has ever produced. The “phone as robot brain” argument is really an argument about <em>silicon</em>, not form factor. And the silicon answer is: use what the phone industry built, whether the user ever sees a phone or not.</p><p>The two cases compound. The customer-brings-the-phone model brings the unit price of consumer personal robots down toward zero compute-side cost. The integrated-phone-silicon model brings the BoM of dedicated robots down to something a startup can actually afford to ship. The current “Jetson + RealSense” baseline is the worst of both worlds: more expensive than either, worse-performing than either.</p><p>And all of this lines up with where the broader AI industry is going. The trend is clearly toward <strong>small, locally-running ML models</strong> — distilled vision and language models that fit on consumer SoCs and run without a network — and away from giant data-center models accessed over an API. At the same time, the most plausible shape for the next generation of consumer robotics is not a single general-purpose humanoid that does everything; it’s many <em>specialized appliances</em> that each do one thing well. A boxing trainer. A kitchen helper. A garden weeder. A patrolling pet companion. The same way the appliance shelf in a home today contains a dozen single-purpose devices — toaster, microwave, blender, washing machine — the robot shelf tomorrow will contain a dozen single-purpose robots. Each of them needs perception, on-device ML, and actuation. None of them needs a data center, a $2,000 SBC, or a $400 stereo camera module. The phone-centric architecture is exactly the shape that both of those trends are converging on.</p><h3>Where I’m Going Next</h3><p>For context, the rig I’m currently running is a textbook traditional stack: a Raspberry Pi 5 (8 GB) + ELP USB stereo + Arduino Nano RP2040 (with built-in IMU) + motor driver. I’m migrating it to an iPhone 11 Pro Max — a six-year-old phone that, on every visual-SLAM benchmark I’ve run, beats the Pi 5 at lower power. The next step is to run mapping and depth perception on the iPhone and use those streams to drive the car. In the new build, the iPhone will run the perception and planning side — real-time mapping, pure pursuit for path following, gap-follow for reactive obstacle avoidance — and stream high-level drive commands to a small microcontroller on the car over Bluetooth. The MCU will handle the low-level motor control and talk to the motor driver directly. The traditional architecture cannot match this stack on cost, on size, on power, or on algorithm quality.</p><h3>Closing Thought</h3><p>The robotics community has been treating “edge computer” and “Linux SBC” as synonyms for so long that we forgot the question. The actual question is: what’s the cheapest, smallest package that has cameras, some sensors, connectivity, storage, and a thermal envelope big enough to run robotic perception, planning, and control sustainably?</p><h3>References</h3><p>· Kim, P., Kim, J., Song, M., Lee, Y., Jung, M., Kim, H.-G. (2022). <em>A Benchmark Comparison of Four Off-the-Shelf Proprietary Visual–Inertial Odometry Systems.</em> Sensors, 22(24), 9873. <a href="https://doi.org/10.3390/s22249873">doi.org/10.3390/s22249873</a></p><p>· Marino, E., Bruno, F., Barbieri, L., Lagudi, A. (2022). <em>Benchmarking Built-In Tracking Systems for Indoor AR Applications on Popular Mobile Devices.</em> Sensors, 22(14), 5382. <a href="https://doi.org/10.3390/s22145382">doi.org/10.3390/s22145382</a></p><p>· Delmerico, J., Scaramuzza, D. (2018). <em>A Benchmark Comparison of Monocular Visual-Inertial Odometry Algorithms for Flying Robots.</em> IEEE International Conference on Robotics and Automation (ICRA).</p><p>· RTAB-Map iOS app — <a href="https://introlab.github.io/rtabmap/">introlab.github.io/rtabmap</a> (and available through App Store)</p><p><em>youtube.com/@FouadRobotics<br>Fouadrobotics.com</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df02be4578ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Extended Kalman Filter, from scratch, on a Cortex-M0+]]></title>
            <link>https://medium.com/@ahmedfouadrobotics/an-extended-kalman-filter-from-scratch-on-a-cortex-m0-88d406fdf151?source=rss-6e221ebe955a------2</link>
            <guid isPermaLink="false">https://medium.com/p/88d406fdf151</guid>
            <category><![CDATA[sensor-fusion]]></category>
            <category><![CDATA[raspberry-pi-pico]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[kalman-filter]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[FouadRobotics]]></dc:creator>
            <pubDate>Thu, 28 May 2026 03:30:29 GMT</pubDate>
            <atom:updated>2026-05-28T03:30:29.049Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Building a 5-state sensor-fusion EKF in C++ on a $25 microcontroller — no matrix library, no OS, no host, full determinism — and learning how Kalman filters actually work along the way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*tfoevOVMDGqNHBi1RX4vtw.png" /></figure><h4><strong>Why bother writing my own?</strong></h4><p>There are dozens of mature Kalman filter implementations out there. robot_localization in ROS, ekfNavINS for INS, Eigen-based teaching codebases, MATLAB toolboxes. If I just wanted “an EKF running on my robot”, I could pick one and configure it.</p><p>I did this differently because <strong>the Kalman filter is one of those algorithms whose intuition only really sticks once you’ve built it yourself.</strong> It’s the same reason people teach themselves to write a compiler, or a TCP stack, or a hash table — the abstractions get in the way of the understanding. And the Kalman filter is one of those algorithms that genuinely matters:</p><p>· It’s running on every mobile robot doing dead reckoning.</p><p>· It’s inside the GPS/INS on aircraft and ships.</p><p>· It’s the math underneath the IMU fusion in your phone.</p><p>· It’s running on the embedded DSP coordinating the gyros and accelerometers on a missile.</p><p>· It’s on satellites doing orbit determination.</p><p>The Kalman filter is one of the few pieces of mathematics that quietly underpins both modern robotics and modern warfare. <strong>Understanding how it weights prediction against measurement — and what it does when sensors disagree, drift, fail, or noise out — isn’t optional knowledge for anyone working with sensors.</strong> It’s the floor, not the ceiling.</p><p>So I built one from scratch. On a $25 Arduino Nano RP2040 Connect (dual-core Cortex-M0+, 133 MHz, 264 KB SRAM). No Eigen. No matrix library at all. No Linux. No ROS. Hand-derived Jacobians, deterministic timing, the whole thing.</p><p>This is the write-up.</p><h4>Goals I held myself to</h4><p>1. Hand-derive the math. Every Jacobian, every covariance propagation step. If I copy a formula, I have to be able to re-derive it on paper.</p><p>2. No matrix library. A 5-state filter is small enough that loops over float A[5][5] are fine. Forcing yourself to write the multiplications by hand teaches you exactly which terms are zero and which aren’t.</p><p>3. Run on the microcontroller. Not a desktop simulation. The filter has to live inside the same __not_in_flash_func budget as everything else.</p><p>4. Determinism. No allocation in the hot path. No locks. No surprise stalls. The IMU fires at 416 Hz, and the EKF has to keep up forever.</p><p>5. Three sensors, three update types. Encoder velocity, magnetometer heading, IMU forward acceleration. Each one a scalar update, each one with its own measurement noise and its own innovation gate.</p><p>The code lives in embedded_ekf_full/ in the GitHub repo. Total: 11 files, around 1,500 lines of C++, all of it built around hand-written sparse matrix math.</p><h4>The journey — built in pieces, not all at once</h4><p>The EKF in this post isn’t the first thing I built. It’s the last thing — the culmination of four sketches, each one focused on a single piece of the puzzle. Each sketch’s failures motivated the next one. The four steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*GOESddH6fFWW7HOy-is-SQ.png" /></figure><h4>Step 1 — IMU + Madgwick, no fusion yet</h4><p><strong>What this teaches:</strong></p><p>· The dual-core architecture: Core 1 owns the IMU bus and the DRDY ISR; Core 0 does everything else.</p><p>· The IMU’s body frame is not the same as the vehicle frame. The six lines at the bottom of imu_decode() are the remap.</p><p>· Madgwick uses the gravity vector to bound pitch/roll drift — but yaw still walks unboundedly because no sensor observes absolute heading yet.</p><h4>Step 2 — Magnetometer calibration</h4><p><em>Repo: github.com/FouadRobotics/mag-calibrate</em></p><p>Add a QMC5883P over the same I²C bus. Rotate the robot through three full circles. The sketch captures hard-iron offsets and soft-iron scales for X and Y and prints them as four float constants you paste straight into the next EKF’s config.h.</p><p>This step was supposed to be a five-minute job and ate three days because of a documentation bug nobody warns you about: the QMC5883P shares the QMC5883L register map but uses different bit assignments inside CTRL1 and CTRL2. The 0x1D value every blog post recommends puts the QMC5883P in an invalid state where DRDY never fires. The MODE bit lives in CTRL2 bit 0, not CTRL1. After the soft reset you have to re-write CTRL2 = 0x01 or the chip stays in standby forever.</p><h4>Step 3 — First EKF: unicycle, gyro direct, mag as a separate update</h4><p><em>Repo: github.com/FouadRobotics/embedded-ekf-with-mag</em></p><p>The first real EKF. State vector [px, py, θ, v, b_gz] — including an explicit gyro bias state. The motion model is unicycle: yaw rate from the gyro feeds the EKF directly as a control input. The magnetometer heading enters as a second scalar measurement update.</p><p><em>This is the textbook EKF you’d find in a robotics course. It works. It also taught me the single most important lesson of the whole project: State observability isn’t automatic. You can add a state to your filter and have it sit at its initial value forever because no measurement update touches it.</em></p><h4>Step 4 — This article: Madgwick before the EKF, Ackermann, robustness features</h4><p><em>Repo: github.com/FouadRobotics/embedded-ekf-cortex-m0</em></p><p>The final architecture. Three structural changes from step 3:</p><p>1. Madgwick moves upstream of the EKF. The EKF never sees the gyro at all — only Madgwick’s fused yaw as a measurement. State drops from [px, py, θ, v, b_gz] to [px, py, θ, v, a].</p><p>2. Ackermann kinematics. Yaw rate in predict is v · tan(δ) / L. The motor controller writes δ; the EKF reads it as a control input.</p><p>3. Five features from robot_localization layered on top — small additions that turn a textbook EKF into a robust one.</p><h4>System architecture</h4><p>Three blocks sit in front of the filter — the IMU/mag driver on Core 1, the Madgwick orientation filter, and the encoder pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*ZdCqlruafz5_ajHxlGpP2g.png" /></figure><p>A few things to call out:</p><p>· Core 1 only does I²C and timestamps. Everything else lives on Core 0. Cross-core communication is a double-buffer plus a single-entry FIFO carrying the IMU sample timestamp. No locks.</p><p>· Madgwick sits between the IMU and the EKF — the EKF never sees the raw gyro. It sees Madgwick’s filtered yaw as a measurement.</p><p>· The encoder pipeline is a project on its own — see my earlier Medium posts on the hardware and the software comparator on the RP2040.</p><h4>The state vector and what each element means</h4><pre>x = [px, py, θ, v, a]ᵀ</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*aL5dUJ2pWXjRpMVBqhzUsw.png" /></figure><p>Three things to notice:</p><p>· No gyro bias state. Earlier iterations had b_gz. Without an absolute heading reference, the bias is unobservable and just sits at its initial value while θ drifts. With a mag → Madgwick → yaw measurement, Madgwick absorbs the bias internally and the EKF state stays leaner.</p><p>· Acceleration is a state, not a control input. The IMU’s forward acceleration becomes a measurement of `a` — letting the filter detect inconsistencies between predicted and measured acceleration (slip, drift, vibration spikes).</p><p>· The motion model is Ackermann, not unicycle. Yaw rate is v · tan(δ) / L where δ is the commanded steering angle and L is the wheelbase. If δ stays at 0 (differential drive or no steering hardware), the predict still works — the heading update from Madgwick picks up the slack.</p><h4>The predict step — where prediction lives</h4><p>Continuous-time Ackermann dynamics:</p><pre>ṗx = v · cos(θ)<br>ṗy = v · sin(θ)<br>θ̇ = v · tan(δ) / L<br>v̇ = a<br>ȧ = 0 (constant-acceleration model - jerk goes into Q)</pre><p>Forward-Euler discretisation:</p><pre>px ← px + v · cos(θ) · dt<br>py ← py + v · sin(θ) · dt<br>θ ← θ + (v · tan(δ) / L) · dt<br>v ← v + a · dt<br>a ← a</pre><p>Now the part that took me longest to internalize: the covariance also has to propagate. The state estimate moves forward in time deterministically; the uncertainty about that estimate has to move too. That’s P — the state covariance matrix.</p><p>For a linear system, P_new = F · P · Fᵀ + Q. For a non-linear system like ours, F is the Jacobian of the dynamics with respect to the state, evaluated at the current estimate. This is the linearisation that makes it an Extended Kalman Filter — we re-linearise at every step.</p><p>For our system, F is mostly zeros — 10 non-trivial entries out of 25. The textbook way to compute F · P · Fᵀ is two nested loops over a 5×5×5 product — roughly 250 multiplies. The hand-written sparse version exploits the structure and does it in about 60. On a Cortex-M0+ with no FPU and softfloat, that’s the difference between 30 µs and 120 µs per predict step. The whole filter runs end-to-end in around 50 µs:</p><pre>// Step (i): T = F · P, exploiting F&#39;s sparsity row by row<br> for (int j = 0; j &lt; N; ++j) {<br> T[0][j] = P[0][j] + Ja * P[2][j] + Jb * P[3][j];<br> T[1][j] = P[1][j] + Jc * P[2][j] + Jd * P[3][j];<br> T[2][j] = P[2][j] + Je * P[3][j];<br> T[3][j] = P[3][j] + Jf * P[4][j];<br> T[4][j] = P[4][j];<br> }<br> // Step (ii): P&#39; = T · Fᵀ, same pattern transposed</pre><p>Finally we add the process noise Q · dt to the diagonal:</p><pre>P[2][2] += EKF_Q_THETA * dt * dyn_scale;<br>P[3][3] += EKF_Q_V * dt * dyn_scale;<br>P[4][4] += EKF_Q_A * dt * dyn_scale;</pre><p>Q is what the filter believes about the noise driving each state. Higher Q means “I don’t trust my prediction much — pay attention to the measurements”. Lower Q means “I trust the model — ignore measurement noise”. This is half of the prediction-vs-measurement weighting question. The other half is R, which we’ll see in a moment.</p><p>The dyn_scale = 1 + DYNAMIC_Q_GAIN · |v| is one of the five features from robot_localization. At high speeds the model breaks down (slip, lateral dynamics, unmodelled forces), so the filter should believe its own predictions less when going fast. Process noise grows linearly with speed.</p><h4>Measurement updates — where the sensors push back</h4><p>Three sensors, three scalar updates. Each follows the same pattern:</p><pre>y = z - H · x // innovation (measurement minus prediction)<br>S = H · P · Hᵀ + R // innovation covariance<br>K = P · Hᵀ / S // Kalman gain<br>x ← x + K · y // update state<br>P ← (I - K · H) · P // update covariance</pre><p>For scalar updates with H = e_kᵀ (a single row of the identity), the Kalman gain is just K[i] = P[i][k] / S. No matrix inverse — just one float division. Here’s the velocity update in full:</p><pre>float EKF::update_velocity(float v_meas) {<br>  const float y = v_meas - x[3]; // innovation<br>  const float S = P[3][3] + EKF_R_V; // 1×1 innovation covariance<br>  const float inv_S = 1.0f / S;<br>  <br>  float K[N];<br>  for (int i = 0; i &lt; N; ++i) K[i] = P[i][3] * inv_S;<br>  for (int i = 0; i &lt; N; ++i) x[i] += K[i] * y;<br>  <br>  // P ← P - K · row_3_of_P<br>  float row3[N];<br>  for (int j = 0; j &lt; N; ++j) row3[j] = P[3][j];<br>  for (int i = 0; i &lt; N; ++i)<br>  for (int j = 0; j &lt; N; ++j)<br>  P[i][j] -= K[i] * row3[j];<br>  return y;<br>}</pre><p>The three updates differ only in which row/column of P is used and which value of R (measurement noise):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*N3Gspw432PpE7_-8hrQzXA.png" /></figure><p>This is the other half of the prediction-vs-measurement weighting. R says how much I trust each sensor. Small R → “trust this sensor — move the state to match it”. Large R → “ignore this sensor — keep the prediction”. The Kalman gain K is the algebraic ratio of how much to listen to the prediction (P) versus the measurement (R):</p><pre>K = P / (P + R)</pre><p>When P &gt;&gt; R (prediction uncertain, sensor confident): K → 1, state snaps to measurement.</p><p>When P &lt;&lt; R (prediction confident, sensor noisy): K → 0, measurement is ignored.</p><p><strong>That single algebraic line is the whole intuition of the Kalman filter.</strong> Everything else is bookkeeping around that ratio.</p><h4>How different sensors play different roles</h4><p>This is where the filter starts feeling less like math and more like an architecture decision.</p><p>· Encoder tells you velocity, not position. Accurate when wheels don’t slip, drifts long-term if they do. Comes every 50 ms in this build (sliding window).</p><p>· Madgwick yaw tells you absolute heading from fused gyro + accel + mag. The EKF doesn’t see the gyro at all — Madgwick has already integrated it and bounded its drift.</p><p>· IMU forward acceleration tells you instantaneous acceleration. Useful between encoder updates (encoder is 20 Hz; IMU is 416 Hz). Heavily corrupted by vibration and gravity coupling — the filter only believes it within a few sigma.</p><p>Each sensor has its own failure mode:</p><p>· Encoder fails on wheel slip. When that happens, Mahalanobis gating drops the bad measurement.</p><p>· Magnetometer fails near metal or motors. Differential mode (capture initial heading as offset) hides static distortion.</p><p>· IMU accel fails on vibration spikes. Same Mahalanobis gate, plus the gravity-removal step using Madgwick’s orientation.</p><h4>The five features I lifted from robot_localization</h4><p>The whole point of robot_localization is robust sensor fusion. It does five specific things on top of the textbook EKF that turn out to matter a lot in practice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*dm87O-aSqTaRc2_YwtkCMQ.png" /></figure><p>All five fit in around 30 extra lines of code. The textbook EKF is maybe 200 lines. The “robust” version is 230. That’s the ratio between the two — most of what makes robot_localization robust is small.</p><h4>What it costs on the MCU</h4><p>Nothing here required heroic optimisation. Sparse Jacobians done by hand instead of Eigen::MatrixXd, RAM-resident hot path (__not_in_flash_func) to avoid XIP flash misses, no allocation, and that’s it. The filter runs 100× faster than the IMU samples.</p><h3>What I actually learned</h3><p>· The Kalman gain is just a ratio. K = P / (P + R). The whole filter is bookkeeping around that one expression. Everything else (Jacobians, covariance propagation, gating) is plumbing.</p><p>· Q is not noise — it’s what you say about the noise. Tuning Q is telling the filter how much to distrust its own dynamics model. Allan variance is the principled way to set it; trial and error is the pragmatic way.</p><p>· State observability is the part nobody teaches you to check. I had a b_gz state for two weeks before realising no measurement update touches it. Adding a state to your model doesn’t make it observable — you need a measurement whose Jacobian has a non-zero entry in that column.</p><p>· Mahalanobis gating is mandatory, not optional. Without it, one wheel slip can spike the encoder velocity to 3.5 m/s and pull the state off truth for a full second of recovery.</p><p>· The architecture matters more than the math. Putting Madgwick before the EKF (instead of feeding the EKF raw gyro) gave a bigger accuracy improvement than any amount of tuning.</p><h3>What’s next</h3><p>Future work:</p><p>· Allan variance characterisation of this unit’s IMU to refit Q properly.</p><p>· Static bias calibration at startup (two-second stillness average) — a simple win.</p><p>· 3-D tumbling-sphere mag calibration (current is 2-D circle, good enough but not great).</p><h3>Code</h3><p>Everything is at github.com/FouadRobotics/embedded-ekf-cortex-m0. Flash the sketch in the Arduino IDE with the earlephilhower arduino-pico core selected, open the Serial Monitor at 921600, drive the robot, and read the serial port output.</p><p>The five robot_localization features are all toggleable through config.h — set DYNAMIC_Q_GAIN = 0, raise MAHA_GATE_SQ to a huge number, set DIFFERENTIAL_YAW_MODE = false, and you’ll see the baseline EKF behaviour the textbooks describe. Then turn them back on one at a time and watch what changes. That comparison was the most instructive part of building this for me, and it’s faster to do interactively than to read about.</p><h4>Preliminary testing</h4><p>In the current setup I have the sensors right above the robot motor, which will miss up the magnetometer measurements due to the motor’s high current. So for now, all testing will be done with the magnetometer flag set to false.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhNxA4NKfzRXOtQuZsPP9g.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMXhyAJSfgIw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMXhyAJSfgIw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMXhyAJSfgIw%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/492aea17d20e83e3f076f2633da65b1c/href">https://medium.com/media/492aea17d20e83e3f076f2633da65b1c/href</a></iframe><p>Based on initial results, distances on the x and y axes as predicted by the Kalman filter are 1.015m and 0.503. I measured the distances using measuring tapes (as shown in the video demo) and they were 1.27m and 30.48m (these are not the most accurate, but still good as an approximation to how good our filter is doing). Obviously, there is more work to be done to debug those difference errors. But this is a good start in my opinion. The Kalman filter is a very complex topic, and it is normal to have difficulties understanding, implementing, and tuning this beast. More articles will be coming soon on my journey working on this. So stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88d406fdf151" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wheel Encoder V3: Software Comparator on RP2040, and Why Timing Determinism Is Non-Negotiable…]]></title>
            <link>https://medium.com/@ahmedfouadrobotics/wheel-encoder-v3-software-comparator-on-rp2040-and-why-timing-determinism-is-non-negotiable-8de7c927d015?source=rss-6e221ebe955a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8de7c927d015</guid>
            <category><![CDATA[sensor-fusion]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[FouadRobotics]]></dc:creator>
            <pubDate>Fri, 15 May 2026 16:36:07 GMT</pubDate>
            <atom:updated>2026-05-15T16:36:07.178Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Wheel Encoder V3: Software Comparator on RP2040, and Why Timing Determinism Is Non-Negotiable Before You Touch an EKF</strong></h3><p><em>A trade study between the LM393 analog comparator and a software-comparator running on the RP2040, why the RP2040 wins here, how the firmware achieves true determinism, and what all of this has to do with Kalman filtering.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zluWgeGYREPZyVXyM9JJw.png" /></figure><p>In <a href="https://medium.com/@ahmedfouadrobotics/building-a-diy-wheel-encoder-for-rc-car-odometry-no-encoder-ic-required-ba96576a02ee">V1</a> I built the encoder using two Hall sensors, 14 magnets, and a <em>software</em> hysteresis comparator running on the Arduino Uno’s ADC. In <a href="https://medium.com/@ahmedfouadrobotics/wheel-encoder-v2-raised-sensors-smarter-firmware-and-the-reality-of-diy-quadrature-6e502c2ff0ee">V2</a> I cleaned up the geometry, raised the sensors, and wrote a proper quadrature state machine — but the front end is still the same: two analog Hall outputs going straight into A0 and A1 on an Uno, with analogRead() plus a software hysteresis comparator deciding when an edge has happened. No external comparator, no Schmitt trigger, no input capture — just the Uno’s ADC and some if statements.</p><p>V3 is where the goal stops being “does it count ticks” and becomes “does it count the <em>right</em> ticks at the <em>right time</em>, every time.” That distinction is everything once you’re planning to fuse this data with an IMU inside an EKF.</p><p><strong>Why the Uno’s ADC is the real problem</strong></p><p>The ATmega328P ADC, at the default Arduino prescaler of 128, runs its clock at 125 kHz. Each conversion takes 13 ADC cycles — 104 µs per channel. Two channels per loop() = ~210 µs just for sensing, before any IMU communication, quadrature decoding, or serial print.</p><p>The cost isn’t just latency. It’s jitter. If a serial print blocks for 600 µs, the encoder is blind for 600 µs. The wheel doesn’t stop just because the MCU got distracted. At 30 rev/s with 14 magnets and 4× quadrature that’s roughly 1700 ticks/s — one transition every ~590 µs. A loop that occasionally stretches to 800 µs <em>will</em> miss edges, and missed edges in quadrature don’t just lose a count, they corrupt direction.</p><p>The obvious fix is an external analog comparator that converts the Hall sensor’s analog output into a clean digital edge, freeing the MCU from ADC polling entirely. I had the LM393 on hand. But before building the circuit I did a quick trade study — and the answer turned out to be more interesting than I expected.</p><h4><strong>Trade study: LM393 analog comparator vs RP2040 software comparator</strong></h4><p>The whole case for the analog comparator rests on one claim: it’s faster and more deterministic than sampling the ADC in software. That’s true on the Uno. It’s not obviously true everywhere.</p><p><strong>LM393 analog comparator</strong></p><p>The LM393 is a classic dual comparator — cheap, widely available, runs on 3.3 V or 5 V. The datasheets shows a typical propagation delay of 1.3 µs at 5 mV of overdrive. But it has an open-collector output, which means the rising edge is set by a pull-up resistor forming an RC with the pin’s input capacitance. In practice that adds another few hundred nanoseconds, and the actual end-to-end delay from a magnet passing to a clean digital edge is around 1.5–2 µs depending on pull-up value. Adjustable hysteresis requires additional resistors. Threshold adjustment requires trimpots, which need to be calibrated against the actual sensor swing and re-checked if the sensor or supply changes.</p><p><strong>RP2040 software comparator (Arduino Nano RP2040 Connect)</strong></p><p>The RP2040’s ADC runs at 48 MHz and completes one conversion in 96 cycles — 2 µs per sample, or 4 µs per channel when round-robining across two channels. With the ADC paced by a hardware clock divider (not the CPU), samples arrive at a perfectly fixed rate: zero jitter from the sampling side. When you move the samples into RAM via DMA and process them on a dedicated core, there is no scheduler, no loop(), and nothing else competing for time.</p><p>At 250 kHz per channel, between consecutive encoder edges at the worst-case speed above, there are roughly 150 ADC samples. The software comparator processes each sample in a handful of cycles. It cannot miss an edge.</p><p><strong>The verdict</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wkfpbOMMt-76TuIGs1MQuA.png" /></figure><p>The LM393’s latency advantage is real but narrow — 1.5 µs vs 4 µs — and it comes with hardware jitter on the rising edge from the RC pull-up that partially closes that gap. More importantly, the LM393’s propagation delay doesn’t help with the actual bottleneck, which was never latency on a single edge but jitter across a stream of edges caused by the Uno’s polling loop. The RP2040 solves that problem better, without any external circuit.</p><p>If the comparator were a fast rail-to-rail type like the NCX2220 (~38 ns propagation, push-pull output), the calculus would be different — that’s genuinely 100× faster than a DMA-paced software loop. But the LM393 isn’t that. The RP2040 wins this trade.</p><p><strong>How the firmware achieves determinism</strong></p><p>Knowing <em>why</em> the RP2040 is a better platform is half the job. The other half is writing firmware that actually exploits it — because the RP2040 running an Arduino-style polling loop() with analogRead() would be just as bad as the Uno. The hardware gives you the capability; the architecture has to realize it.</p><p>Here is what the V3 firmware does, and why each decision matters.</p><p>1- ADC paced by hardware clock divider</p><pre>adc_set_clkdiv(95.0f);<br>adc_set_round_robin((1u &lt;&lt; ADC_CH_A) | (1u &lt;&lt; ADC_CH_B));<br>adc_select_input(ADC_CH_A);<br>adc_fifo_setup(true, true, 1, false, false);</pre><p>The ADC clock divider is a hardware register. Once set, the ADC produces samples at exactly 500 kHz (250 kHz per channel) regardless of what the CPU is doing. There is no software in the sampling path. This is the foundation — without it, every other determinism guarantee is meaningless.</p><p>2- Chained ping-pong DMA — zero CPU, zero gap</p><pre>channel_config_set_chain_to(&amp;cfg_a, g_dma_b);   // A finishes → B starts<br>channel_config_set_chain_to(&amp;cfg_b, g_dma_a);   // B finishes → A starts</pre><p>Two DMA channels are linked in a chain. When channel A fills its buffer half, it automatically triggers channel B on the same clock cycle — no CPU instruction, no IRQ latency in the sample stream. The CPU’s only involvement is an interrupt at the end of each half to record a timestamp and mark the buffer ready for processing. Samples never wait.</p><p>3- Core 1 is dedicated to the sense pipeline</p><pre>multicore_launch_core1(core1_main);</pre><p>The entire sense pipeline — ADC setup, DMA setup, hysteresis, quadrature decoding, publishing — runs on Core 1 and nothing else does. Core 0 handles IMU, EKF, telemetry. There is no scheduler preempting Core 1’s processing loop; the RP2040 has no RTOS on Core 1 in this configuration. The only thing that can interrupt Core 1 is the DMA completion IRQ, which runs for a handful of cycles.</p><p>4- Offset-subtracted hysteresis comparator</p><pre>int val_a = (int)(buf[i] &amp; 0x0FFF) - OFFSET_A;  // center on zero<br>if      (val_a &gt; HIGH_TH) dig_a = 1;<br>else if (val_a &lt; LOW_TH)  dig_a = 0;<br>// else: hold current state</pre><p>This is the Schmitt trigger in software. Subtracting the sensor’s idle-voltage offset first means the thresholds (±100 counts) are symmetric around the sensor’s actual midpoint, not an assumed absolute voltage. This matters in practice because Hall sensor idle voltages shift slightly with temperature and supply variation. A fixed absolute threshold would need frequent recalibration; an offset-relative threshold only needs recalibration if the sensor’s swing amplitude changes — which it doesn’t, since that’s set by the magnetic field strength.</p><p>The hysteresis band (the gap between HIGH_TH and LOW_TH) is what prevents chatter at the threshold. It’s the same role that the positive-feedback resistor plays in an analog comparator circuit.</p><p>5- Phase-alignment delay buffer</p><pre>delay_buf[delay_idx] = dig_b;<br>delay_idx = (delay_idx + 1) % DELAY_LEN;<br>int aligned_b = delay_buf[delay_idx];</pre><p>The two Hall sensors are physically offset from each other by a few millimetres. That mechanical offset means sensor B’s signal is delayed relative to sensor A’s by a fixed number of sample periods. Without compensating for this, the quadrature state machine sees transitions that appear out of order and miscounts direction. The delay buffer holds the last DELAY_LEN states of channel B and feeds the decoder a time-shifted version that aligns with channel A. DELAY_LEN = 3 matched the physical geometry of this encoder.</p><p>6- Quadrature decode via lookup table</p><pre>uint8_t state = (uint8_t)((dig_a &lt;&lt; 1) | aligned_b);<br>if (state != prev_state) {<br>    uint8_t idx = (prev_state &lt;&lt; 2) | state;<br>    if (QDR_INVALID[idx]) {<br>        local_invalid++;           // log it, but do NOT advance prev_state<br>    } else {<br>        local_count += QDR_TABLE[idx];<br>        prev_state = state;        // only advance on a valid transition<br>    }<br>}</pre><p>The 16-entry lookup table replaces a switch statement with a single array access — constant time regardless of which transition occurred. On an invalid transition (a 2-step jump that means an edge was missed), prev_state is deliberately <em>not</em> updated. Holding the previous state lets the decoder resync naturally on the next valid edge rather than compounding the error.</p><p>7- Hardware spinlock for cross-core publish</p><pre>uint32_t save = spin_lock_blocking(g_state_lock);<br>g_encoder_count  = local_count;<br>g_last_edge_us   = local_last_us;<br>spin_unlock(g_state_lock, save);</pre><p>The RP2040 has 32 hardware spinlocks in the SIO peripheral — single-cycle acquire/release, no OS involvement. Core 0 calls encoder_read() which acquires the same lock, copies the four values atomically, and releases it. Core 0 never sees a torn read where count and timestamp belong to different moments.</p><p>8- Real-time primitives: what they do (and what I’m still learning)</p><p>The firmware relies on several RP2040 Pico SDK primitives that go beyond plain Arduino-style code. I am relatively new to these, and I am still experimenting to understand how much each one actually contributes to determinism — or whether some are redundant in this configuration. Here is what they do in principle.</p><p>irq_set_exclusive_handler(DMA_IRQ_0, dma_irq_handler) registers the DMA completion callback as the sole handler for that IRQ line, rather than sharing it with other code through a dispatch table. The exclusive form means the CPU jumps directly to the handler with no indirection overhead. Whether this makes a measurable difference in a design where Core 1 has little else running is something I have not yet quantified.</p><p>irq_set_priority(DMA_IRQ_0, 0) assigns the highest priority level (0) to the DMA interrupt on the Cortex-M0+. In theory this ensures the DMA completion fires immediately even if another interrupt is mid-service, minimising the gap between a buffer fill completing and the timestamp being recorded. In practice, with virtually nothing else running on Core 1, the benefit may be modest — but it costs nothing.</p><p>__not_in_flash_func() is a Pico SDK macro that places the decorated function in SRAM rather than flash. Code normally runs from flash via an XIP (execute-in-place) cache; a cache miss adds an unpredictable number of stall cycles that would appear as jitter. Both the DMA IRQ handler and the Core 1 hot loop carry this attribute. Of the primitives listed here, this one seems the most likely to have a real effect on timestamp accuracy, since a cache miss inside a tight sensor loop directly corrupts the timing math. I have not yet done the scope work to confirm.</p><p>tight_loop_contents() sits inside the busy-wait loops that spin until a DMA half-buffer is flagged ready. It expands to a compiler barrier and a CPU hint, signalling to the toolchain that the loop is intentional rather than an optimisation target. It is unlikely to affect determinism on its own but prevents the compiler from collapsing the loop away.</p><p>In short: I included these because they are the right real-time tools for this kind of firmware and each moves in the correct direction from first principles. But I am still playing with them and have not yet done the systematic measurements that would tell me which ones make a real, quantifiable difference versus which are belt-and-suspenders on top of hardware that is already deterministic by design.</p><p><strong>The result</strong></p><p>After spinning the wheel a few revolutions:</p><pre>-85, 87, 0</pre><p>Count = −85 (negative just means the rotation direction maps to “reverse” — one sign flip in software fixes it). Total edges = 87. Invalid transitions = 0. The hysteresis and delay buffer are doing their jobs.</p><p><strong>Why “constant” matters: timing and determinism in sensor fusion</strong></p><p>If you’ve never built a sensor-fusion stack, it’s tempting to think of latency the way we think of network ping: lower is better, and that’s that. Real-time estimation cares about two different things:</p><p>Latency: how long between the physical event and the sample arriving at the estimator.</p><p>Jitter: how much that latency varies between samples.</p><p>For an EKF — or really any model-based estimator — jitter is the worse one. A constant latency can be modeled or subtracted out. Jittery latency can’t; you don’t know on any given sample how stale the measurement is.</p><p>A third concept is <em>timestamp accuracy</em>: when the filter receives a wheel tick, what time does it think the tick happened? If ticks are sampled in a slow loop() and tagged with millis() at the end, the timestamp is wrong by however long loop() was busy doing other things. That bias shows up directly in the velocity estimate, because velocity is <em>ticks per unit time</em> and we lied about the unit of time.</p><p>The DMA-paced, dedicated-core architecture solves all three at once: near-zero latency from signal to decoded edge, sub-microsecond jitter in the sample stream, and timestamps that are derived from a hardware timer captured at the DMA boundary and offset by sample index — accurate to one sample period (4 µs).</p><p><strong>Why this matters specifically for the EKF</strong></p><p>The prediction step propagates the state forward using a motion model. For a ground robot:</p><pre>x_{k|k-1}  =  x_{k-1}  +  v · cos(θ) · Δt<br>y_{k|k-1}  =  y_{k-1}  +  v · sin(θ) · Δt<br>θ_{k|k-1}  =  θ_{k-1}  +  ω · Δt<br>P_{k|k-1}  =  F · P_{k-1} · Fᵀ  +  Q(Δt)</pre><p>Δt is everywhere. It’s the integration step for position, heading, and the discretized process noise Q(Δt). Jittery Δt means every column of that math is jittery. The estimate drifts, and the covariance grows in a way that reflects what the scheduler did rather than what the world did.</p><p>The update step:</p><pre>y_k  =  z_k  −  h(x_{k|k-1})          // innovation<br>S_k  =  H · P_{k|k-1} · Hᵀ  +  R      // innovation covariance<br>K_k  =  P_{k|k-1} · Hᵀ · S_k⁻¹        // Kalman gain<br>x_k  =  x_{k|k-1}  +  K_k · y_k<br>P_k  =  (I  −  K_k · H) · P_{k|k-1}</pre><p>The measurement z_k must be associated with the predicted state <em>at the same instant the measurement was taken</em>. If a wheel tick happened at t = 12.317 ms but arrives tagged as t = 12.9 ms, then h(x_{k|k-1}) is evaluated at the wrong state, the innovation y_k is wrong, and K_k applies that wrong correction to the estimate.</p><p>It gets worse when you have two sensors at different rates. An IMU running at 200 Hz and a wheel encoder firing at a variable, speed-dependent rate need to be merged in time order. If either stream carries unknown jitter, the filter can’t reconstruct the correct event ordering, and corrections end up being applied in the wrong direction relative to the prediction. That shows up as a slow drift that no amount of Q and R tuning can fix — because the bug isn’t in the noise model, it’s in the timeline.</p><p>The encoder side of that timeline is now clean. Next is the IMU side.</p><p><strong>What’s next</strong></p><p>The encoder is confirmed working: clean quadrature, zero invalid transitions, correct edge count. The deterministic foundation is in place. What remains:</p><p>1- IMU integration using the LSM6DSOX’s DRDY (data-ready) interrupt pin. When the IMU has a fresh sample, an ISR fires on Core 0, performs the SPI burst read, and timestamps the sample at ISR entry — the same philosophy applied to the wheel encoder. Both sensor streams then live in the same time_us_64() timebase.</p><p>2- Time-ordered fusion: a small queue that merges wheel ticks and IMU samples in timestamp order before handing them to the EKF, so the filter never receives a measurement that’s older than the state it’s being applied to.</p><p>3- Real-time EKF: single-precision float, no dynamic allocation, fixed number of multiplies per update step. Core 0 runs the filter; Core 1 continues to own the encoder pipeline uninterrupted.</p><p>If V1 was “can I get a tick out of this,” and V2 was “can I get the <em>right</em> tick,” then V3 is “can I get the right tick at the right time, every time.” The answer is yes. V4 is where we find out if that’s enough to dead-reckon an RC car.</p><p>Github Repo: <a href="https://github.com/FouadRobotics/Wheel-Encoder-Prototype-V3">https://github.com/FouadRobotics/Wheel-Encoder-Prototype-V3</a></p><p>My Website: <a href="https://www.fouadrobotics.com/">https://www.fouadrobotics.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8de7c927d015" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wheel Encoder V2: Raised Sensors, Smarter Firmware, and the Reality of DIY Quadrature]]></title>
            <link>https://medium.com/@ahmedfouadrobotics/wheel-encoder-v2-raised-sensors-smarter-firmware-and-the-reality-of-diy-quadrature-6e502c2ff0ee?source=rss-6e221ebe955a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e502c2ff0ee</guid>
            <category><![CDATA[odometry]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[sensor-fusion]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[FouadRobotics]]></dc:creator>
            <pubDate>Wed, 06 May 2026 02:02:15 GMT</pubDate>
            <atom:updated>2026-05-06T04:27:14.668Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Iteration on a magnetic Hall effect encoder — better hardware geometry, a full quadrature state machine, and an honest look at what “good enough” means in a sensor fusion stack.</em></p><p>In <a href="https://medium.com/@ahmedfouadrobotics/building-a-diy-wheel-encoder-for-rc-car-odometry-no-encoder-ic-required-ba96576a02ee">Part 1</a> of this series I built a magnetic wheel encoder from scratch using two <strong>SS49E linear Hall effect sensors</strong>, 14 neodymium magnets glued inside the wheel spokes, and a software hysteresis comparator on an <strong>Arduino Uno</strong>. It worked — but barely. The raw signals were weak, the thresholds had to be wide to avoid false triggers, and the firmware only reported raw channel states with no direction decoding.</p><p>This article covers Version 2: a physical change to the sensor mount, a significantly improved firmware, and an honest accounting of what happened when I tried to get proper quadrature alignment.</p><h3>What Was Wrong With V1</h3><p>The V1 sensor holder placed the two SS49E sensors at a height that caught only the fringe of the magnetic field from each passing magnet. The signal deflection was small — around ±50 ADC counts at best. That forced a wide hysteresis window just to avoid chatter, which in turn meant the state transitions were sluggish and the phase relationship between channels was hard to evaluate cleanly.</p><p>There was also no direction decoding. V1 output two binary signals and left the counting logic entirely to whatever was reading the serial port.</p><h3>The Hardware Fix: Raise the Sensors</h3><p>The fix was straightforward: bend the SS49E sensor legs upward to elevate the sensing face, positioning it closer to the center of the passing magnets rather than catching only the bottom edge of the field. To lock this in permanently, the 3D-printed holder was epoxy-glued to the car chassis structure, and the female jumper wires were also fixed with epoxy — eliminating any movement that could shift sensor position during operation.</p><p>With the sensors at the correct height, each magnet produces a much larger deflection. The stronger signal has a cascade of benefits for every downstream processing step in the firmware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QbN0gqbMOQjo3Uf6g9h-w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0n10lFg85jesZAihZzT-Tw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0n7Od7kNUQ_vYoBHwO7Zwg.jpeg" /></figure><h3>The Firmware Overhaul</h3><p>With stronger raw signals, every downstream processing step could be tightened. The V2 firmware has five meaningful changes over V1.</p><h3>1 — Per-Channel Hysteresis Thresholds</h3><p>V1 used a <strong>single shared pair</strong> of high/low thresholds applied identically to both sensors. V2 defines <strong>independent threshold pairs</strong> for each channel:</p><pre>const int HIGH_TH_1 = 25;<br>const int LOW_TH_1  = -25;<br><br>const int HIGH_TH_2 = 25;<br>const int LOW_TH_2  = -25;</pre><p>This makes it possible to tune each sensor independently if one produces a weaker signal or sits at a slightly different distance from the magnets — without affecting the other channel. In V1, a single global threshold forced a compromise between the two sensors. With separate thresholds, each channel can be dialled in to the tightest window its signal strength allows, which improves edge-tracking precision and reduces the chance of missed or false transitions.</p><h3>2 — Software Phase Alignment via Delay Buffer</h3><p>Getting two physical sensors to produce a clean 90° quadrature offset requires precise mechanical positioning — the spacing between the two sensors has to correspond exactly to a quarter of the magnet pitch. With 14 magnets hand-placed inside a wheel, that’s nearly impossible to achieve purely through geometry.</p><p>V2 solves this in software: channel 2’s state is held in a circular delay buffer before entering the decoder. Each slot represents one sample period (500 µs at 2 kHz). Delaying by N samples is equivalent to shifting the phase backward by N × 500 µs:</p><pre>#define DELAY_LEN 3   // adjust 0-5 to tune phase<br><br>delayBuffer[delayIdx] = state2;<br>delayIdx = (delayIdx + 1) % DELAY_LEN;<br>int alignedState2 = delayBuffer[delayIdx];</pre><p>Tune DELAY_LEN in the Serial Plotter: if channel 2 leads channel 1, increase the delay; if it lags by more than a quarter cycle, decrease it.</p><h3>3 — Full Quadrature Decoder with State Machine</h3><p>V1 reported raw channel states and left direction decoding to the host. V2 implements the full 4-bit state machine directly on the Arduino:</p><pre>int transition = (prevState &lt;&lt; 2) | currentState;<br><br>switch (transition) {<br>  // Forward: 00-&gt;01, 01-&gt;11, 11-&gt;10, 10-&gt;00<br>  case 0b0001: case 0b0111: case 0b1110: case 0b1000:<br>    encoderCount++;<br>    break;<br><br>  // Reverse: 00-&gt;10, 10-&gt;11, 11-&gt;01, 01-&gt;00<br>  case 0b0010: case 0b0100: case 0b1101: case 0b1011:<br>    encoderCount--;<br>    break;<br><br>  default:<br>    currentState = prevState;  // missed pulse -- discard<br>    break;</pre><p>The valid transitions follow a Gray-code pattern where only one bit changes per step. A two-bit jump means a pulse was missed; the state is held rather than corrupting the count.</p><h3>4 — Non-Blocking 2 kHz Sampling</h3><p>V1 used delay(). V2 uses a micros()-based interval timer so the loop is never blocked:</p><pre>const int SAMPLE_PERIOD_US = 4000;  // 2 kHz<br><br>if (micros() - lastMicros &lt; SAMPLE_PERIOD_US) return;<br>lastMicros = micros();</pre><p>At 2 kHz with 14 magnets, the encoder can track wheel speeds well above the range of an RC car before missing pulses.</p><h3>5 — Serial Output Now Includes Encoder Count</h3><p>All three values stream at 115200 baud:</p><pre>state1, alignedState2, encoderCount</pre><p>Plotting all three in the Arduino Serial Plotter lets you see the raw channel states and the decoded position count climbing or falling in real time.</p><h3>The Alignment Problem</h3><p>Here’s where the honest part comes in.</p><p>Despite the software phase alignment buffer, getting a clean 90° offset between channel A and channel B proved elusive. The physical geometry of this wheel — 14 hand-placed magnets with imperfect spacing, two sensors mounted on a bracket held with epoxy — introduced too much variability for the delay buffer alone to correct fully.</p><p>Both channels rise and fall nearly together rather than with a clean quarter-cycle offset. The decoder still runs and still counts — but it is not in proper quadrature mode.</p><h3>The Experiment: How Many Counts Per Revolution?</h3><p>Rather than chasing perfect alignment, I ran a direct experiment: spin the wheel exactly one full rotation by hand and read the final encoderCount. The result was consistent across multiple trials:</p><p><strong>24 increments per full rotation.</strong></p><p>Compare this to the theoretical ceiling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1KRTmqn7-rqJMIdUlFA97w.png" /></figure><p>24 counts per revolution is below ×2 but above ×1. It reflects the decoder picking up some but not all of the valid transitions due to the near-in-phase signals. The critical observation is that the result is consistent and repeatable — every full rotation produces the same 24-count increment.</p><h3>Why 24 Counts Is Good Enough</h3><p>This encoder does not operate in isolation. It feeds into a sensor fusion stack alongside two other sources:</p><p>- <strong>IMU</strong> — provides angular rate and vehicle attitude at high frequency</p><p>- <strong>Commanded steering angle from the servo</strong> — provides a turn radius estimate from the control signal</p><p>A fusion filter takes all three inputs and produces a pose estimate that is more accurate than any single sensor alone. Each source corrects the drift of the others. In this context, the wheel encoder’s job is to provide a consistent, repeatable measurement of linear displacement — not a perfect one. 24 well-behaved counts per revolution is enough to give the filter a meaningful signal to work with.</p><h3>Video Demo</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzW9HWRnuJOY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzW9HWRnuJOY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzW9HWRnuJOY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/115ce787d6485cc45a5c070b605ab78d/href">https://medium.com/media/115ce787d6485cc45a5c070b605ab78d/href</a></iframe><h3>What’s Next</h3><p>The next steps for this build are:</p><ul><li>Add an analog circuit to do the conditioning and thresholds comparison to avoid using the ADC on board the Arduino (too slow). This is a non-negotiable for later work on sensor fusion with other sensors using a Kalman Filter.</li></ul><h3>References</h3><p>Part 1 — Original Prototype: <a href="https://medium.com/@ahmedfouadrobotics/building-a-diy-wheel-encoder-for-rc-car-odometry-no-encoder-ic-required-ba96576a02ee">Building a DIY Wheel Encoder for RC Car Odometry</a></p><p>Source code and design files: <a href="https://github.com/FouadRobotics/Wheel-Encoder-Prototype-V2">github.com/FouadRobotics/Wheel-Encoder-Prototype-V2</a></p><p><a href="http://fouadrobotics.com/">My Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e502c2ff0ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a DIY Wheel Encoder for RC Car Odometry (No Encoder IC Required)]]></title>
            <link>https://medium.com/@ahmedfouadrobotics/building-a-diy-wheel-encoder-for-rc-car-odometry-no-encoder-ic-required-ba96576a02ee?source=rss-6e221ebe955a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba96576a02ee</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[hall-effect-sensor]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[autonomous-cars]]></category>
            <dc:creator><![CDATA[FouadRobotics]]></dc:creator>
            <pubDate>Fri, 01 May 2026 03:26:41 GMT</pubDate>
            <atom:updated>2026-05-15T16:42:22.546Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I used two Hall effect sensors, 14 magnets, and a software hysteresis comparator to build a quadrature wheel encoder from scratch.</em></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Check improved iterations of this project in:<br><a href="https://medium.com/@ahmedfouadrobotics/wheel-encoder-v2-raised-sensors-smarter-firmware-and-the-reality-of-diy-quadrature-6e502c2ff0ee">https://medium.com/@ahmedfouadrobotics/wheel-encoder-v2-raised-sensors-smarter-firmware-and-the-reality-of-diy-quadrature-6e502c2ff0ee</a></p><p>and the latest version:<br><a href="https://medium.com/@ahmedfouadrobotics/wheel-encoder-v3-software-comparator-on-rp2040-and-why-timing-determinism-is-non-negotiable-8de7c927d015">https://medium.com/@ahmedfouadrobotics/wheel-encoder-v3-software-comparator-on-rp2040-and-why-timing-determinism-is-non-negotiable-8de7c927d015</a></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>When I started building autonomous behaviors into an RC car, the first thing I needed was reliable odometry — the ability to know how far the wheels had traveled. Commercial encoder modules exist, but I wanted to understand the problem from first principles and build something custom that fit my wheel geometry. The result is a magnetic wheel encoder using two <strong>SS49E linear Hall effect sensors</strong> and an <strong>Arduino Uno</strong>, with no dedicated encoder IC anywhere in the circuit.</p><p>This article walks through the full build: the hardware, the firmware, and — importantly — the underlying theory of how quadrature encoders work and why two sensors are better than one.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>What Is a Quadrature Encoder and How Does It Work?</h3><p>Before diving into the hardware, it’s worth understanding the technique this design is based on.</p><p>A <strong>quadrature encoder</strong> uses two sensors to read the same periodic signal, but with the sensors physically offset so their outputs are 90° out of phase. The two output channels are called <strong>A</strong> and <strong>B</strong>. When the wheel spins, both channels produce square waves — but B always lags (or leads) A by a quarter cycle depending on the direction of rotation.</p><h3>The A and B Signal Waveforms</h3><p>The two channels produce square waves as the wheel spins, with B lagging A by 90° during forward rotation — and A lagging B when the wheel reverses. The phase relationship is what encodes direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9TFiVzI0dnpVxcyKV1ZiyQ.png" /></figure><p><em>Channel A and B signals — B lags A by 90° on forward rotation</em></p><p><em>Image courtesy of [US Digital](https://www.usdigital.com/support/resources/reference/technical-docs/white-papers/resolution-accuracy-and-precision-of-encoders/)</em></p><p>This 90° phase offset is what makes quadrature encoding powerful: you get both <strong>position</strong> (from counting edges) and <strong>direction</strong> (from which channel leads).</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>The Quadrature State Transition Table</h3><p>At any instant, the two channels each hold a binary value (0 or 1), giving four possible states. As the wheel turns, it steps through these states in a predictable sequence — a <strong>Gray code</strong> pattern where only one bit changes at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*SuFjttbE30kiVL0_-WRNMg.png" /></figure><p><strong>Forward (CW) rotation</strong> steps through the sequence: 00 → 01 → 11 → 10 → 00</p><p><strong>Reverse (CCW) rotation</strong> steps through it backwards: 00 → 10 → 11 → 01 → 00</p><p>By storing the previous state and comparing it to the current state, your firmware can increment a counter on forward transitions and decrement it on reverse transitions — giving you a signed position tick count that survives direction changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*54CU4wGsrvh_GC88mGHiGQ.png" /></figure><p>Any transition not in this table (e.g., 00 → 11) means you’ve missed a pulse — the wheel moved too fast for your sample rate.</p><h3>Resolution Multiplication: ×1, ×2, and ×4</h3><p>Having two channels doesn’t just give you direction — it also lets you multiply the effective resolution of the encoder without adding more magnets. You choose how many edges to count per cycle depending on how much precision your application needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QElstIxpLxaX16ZWbwqPrQ.png" /><figcaption><em>Quadrature resolution modes — ×1, ×2, and ×4</em></figcaption></figure><p><em>Image courtesy of [US Digital](https://www.usdigital.com/support/resources/reference/technical-docs/white-papers/resolution-accuracy-and-precision-of-encoders/)</em></p><p>· <strong>×1</strong> — count only the rising edge of channel A: 14 ticks/rev with this design</p><p>· <strong>×2</strong> — count rising edges of both A and B: 28 ticks/rev</p><p>· <strong>×4</strong> — count all edges (rising and falling) of both A and B: 56 ticks/rev</p><p>For dead-reckoning odometry on an RC car, ×4 mode gives the finest distance resolution with no hardware changes — just a software update to the edge-counting logic.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Why Not Just Use One Sensor?</h3><p>A single sensor gives you pulse count (distance), but you can’t tell which direction the wheel is turning. The moment the car reverses, your odometry counter keeps incrementing instead of decrementing. Two sensors in quadrature solve this completely.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>The Hardware</h3><h3>The Wheel and Magnets</h3><p>The trigger targets for the encoder are <strong>14 rectangular neodymium magnets</strong> (2 × 3 × 6 mm) glued to the inner face of the RC wheel spokes, evenly distributed around the hub. The magnets are oriented so their largest face (3 × 6 mm) points radially inward toward the axle, where the sensors sit.</p><p>With 14 magnets and two sensors, this gives <strong>28 detectable edges per revolution</strong> — enough resolution for reliable short-distance dead reckoning on an RC car.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkyAMpGg8IoM2KuuwZMjPw.jpeg" /><figcaption><em>Wheel with embedded magnets</em></figcaption></figure><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>The SS49E Hall Effect Sensor</h3><p>The <strong>SS49E</strong> is a linear ratiometric Hall effect sensor. Unlike a digital Hall sensor (which snaps to a high or low rail), the SS49E outputs a voltage proportional to the magnetic field passing through it:</p><p>· <strong>No field present:</strong> output rests at ~2.5 V (mid-supply on a 5 V rail)</p><p>· <strong>North pole:</strong> output rises above 2.5 V</p><p>· <strong>South pole:</strong> output falls below 2.5 V</p><p>This linear output is what allows the software hysteresis comparator to work cleanly — more on that in the firmware section.</p><p>Two sensors are mounted side-by-side in a 3D-printed holder on the axle, their flat sensing faces pointing inward toward the passing magnets. The physical offset between the two sensors is what creates the 90° phase shift between channel A and channel B.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Wiring</h3><p>Each SS49E has three pins: <strong>VCC</strong>, <strong>GND</strong>, and <strong>OUT</strong>. Both sensors share the same 5V and GND rails. No pull-up or pull-down resistors are needed — the SS49E is a ratiometric output sensor, not open-drain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*JfAuGVmrjNxhtAyHorWQuw.png" /></figure><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Physical Setup and 3D-Printed Sensor Mount</h3><p>The sensor holder is a short arc-shaped bracket that wraps around the axle and positions both SS49E sensors at the correct radial distance from the passing magnets. It was designed in OpenSCAD and printed in PLA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*Ye4JubZs8mQeJDDw1S6J_A.png" /><figcaption><em>3D sensor mount preview</em></figcaption></figure><p><strong>Key dimensions:</strong></p><p>In this prototype the holder is attached to the axle hub with <strong>double-sided tape</strong>. The final version will be fixed permanently with epoxy — the same method used to secure the magnets to the wheel spokes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b4C45qXehcZDtRxlceZm9w.jpeg" /><figcaption><em>Sensor mount — front view</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S548EpcrvSXQuFxjSjR1kA.jpeg" /><figcaption><em>Sensor mount — close-up</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCzbIFi1aceGlWGb7gDcug.jpeg" /><figcaption><em>Sensor mount — side view</em></figcaption></figure><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Firmware</h3><p>The firmware has two stages: a one-time calibration to find each sensor’s resting baseline, then the main encoder loop.</p><h3>Step 1 — Find Baseline Offsets</h3><p>The SS49E’s midpoint voltage isn’t exactly 2.5 V — it varies slightly per unit. Before running the encoder, flash <a href="https://github.com/FouadRobotics/Wheel-Encoder-Prototype">`find-baseline.ino`</a> to measure the resting ADC value for each sensor with no magnet nearby.</p><pre>void loop() {<br> int sensor1Value = analogRead(sensor1Pin);<br> int sensor2Value = analogRead(sensor2Pin);<br> <br> Serial.print(sensor1Value - 505);<br> Serial.print(&quot;,&quot;);<br> Serial.println(sensor2Value - 528);<br> <br> delay(100);<br> }</pre><p>Open the <strong>Serial Monitor at 9600 baud</strong> with the wheel stationary. The values should hover near 0. Note the raw resting ADC reading for each sensor and plug those into offset1 and offset2 in the main sketch.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Step 2 — Main Encoder Sketch with Hysteresis</h3><p>The main sketch reads both sensors, zero-centers them using the measured offsets, and applies a <strong>software hysteresis comparator</strong> to produce a clean digital 0 or 1 for each channel.</p><p>const int offset1 = 505; // resting ADC value for sensor 1 — calibrate with find-baseline<br> const int offset2 = 528; // resting ADC value for sensor 2<br> <br> const int HIGH_TH = 50; // switch state → 1 above this<br> const int LOW_TH = -50; // switch state → 0 below this</p><p>The hysteresis window is the key to noise-free output. Without it, when a magnet is right at the edge of the detection zone the output chatters rapidly between 0 and 1, generating dozens of false pulses. The comparator holds its previous state while the reading is inside the dead zone:</p><pre>if (val1 &gt; HIGH_TH) state1 = 1;<br> else if (val1 &lt; LOW_TH) state1 = 0;<br> // else: hold previous state - no chatter</pre><p><strong>Serial output (9600 baud)</strong> shows the two-channel quadrature pattern stepping through the transition table as the wheel turns:</p><p>S1: 0 | S2: 0<br> S1: 0 | S2: 1<br> S1: 1 | S2: 1<br> S1: 1 | S2: 0<br> S1: 0 | S2: 0 ← one full cycle = one magnet passed both sensors</p><p>Each rising edge on S1 or S2 represents one magnet passing the corresponding sensor — <strong>14 pulses per wheel revolution per channel</strong>, or 28 edges total if you count both edges of both channels.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Video Demo</h3><p><a href="https://youtu.be/UBkFUwfwLDY">https://youtu.be/UBkFUwfwLDY</a></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>What’s Next</h3><p>This encoder feeds into a larger RC car autonomy project where wheel odometry is fused with IMU data for dead-reckoning navigation. The next steps are:</p><p>· Permanently mount the sensor bracket with epoxy</p><p>· Wire the encoder into the main autonomy stack</p><p>· Fuse odometry with IMU for a full pose estimate</p><p>The full codebase — OpenSCAD source, STL, Arduino sketches, and calibration tools — is on GitHub: <a href="https://github.com/FouadRobotics/Wheel-Encoder-Prototype/tree/main">FouadRobotics/Wheel-Encoder-Prototype</a></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><em>Follow along with more robotics builds:</em></p><p><em>My YouTube Channel: </em><a href="https://www.youtube.com/@FouadRobotics"><em>https://www.youtube.com/@FouadRobotics</em></a></p><p><em>My Website</em>: <a href="https://fouadrobotics.com/"><em>https://fouadrobotics.com</em></a></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>References</h3><p>· US Digital — <em>Resolution, Accuracy, and Precision of Encoders</em>: <a href="https://www.usdigital.com/support/resources/reference/technical-docs/white-papers/resolution-accuracy-and-precision-of-encoders/">usdigital.com</a></p><p>· Source code and design files: <a href="https://github.com/FouadRobotics/Wheel-Encoder-Prototype/tree/main">github.com/FouadRobotics/Wheel-Encoder-Prototype</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba96576a02ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>