Reverse engineeringguide
Patching an nRF52840 gaming mouse's firmware
I patched my nRF52840 gaming mouse, which runs firmware V3.05, and left its 8K dongle on stock V2.25. The mouse now retries a failed USB motion-report enqueue, has a unique USB serial number, and exposes opt-in diagnostic commands that read raw sensor frames, one at a time or as a slow live stream over USB. Sensor settings written from the PC now survive the stock firmware’s re-initialisation, and on the cable the mouse reads its sensor just before the PC polls instead of just after the frame starts. An earlier patch bricked a related nRF52840 mouse, so this work started with recovery and validation rather than features.
This guide records what I changed, which checks caught bad patches, and what the hardware and USB captures actually establish. I could rebuild update packages that the stock updater accepts. Package cryptography and byte-level patch recipes are outside this guide; the process and evidence are the useful parts.
Prerequisites for this kind of work are an exact stock image for the hardware revision, a recovery image and boot path tested on that same unit, a disassembler, and a way to capture USB traffic. A successful flash shows that the updater accepted the package, not that the new firmware boots. Do not use another model’s firmware, addresses, or recovery assumptions.
Architecture
Section titled “Architecture”| Component | State | Role |
|---|---|---|
| Mouse | Patched V3.05, nRF52840 | Sensor reads, click processing, wired USB, and wireless radio |
| Wired USB | Stock full-speed path | One 1 ms USB frame limits interrupt reports to 1 kHz |
| 8K dongle | Stock V2.25 | Radio receiver plus high-speed USB to the PC |
| Patch specification | Declarative, per image | Names the stock image, protected ranges, relocations, and register contracts |
| Offline gate | Run before every flash | Rebuilds the image and checks the patch in its whole-image context |
| Recovery path | Tested on this mouse before patching | Boot mode plus a known-good stock package |
| Measurement | USBPcap at the PC | Shows host-visible report timing, with capture and buffering caveats |
| In-mouse timing probe | Opt-in, patched V3.05 | Hardware timestamps of USB frame starts, report loads and host acknowledgements inside the mouse |
The stock application is a bare-metal main loop on Nordic’s nRF5 SDK with the S113 v7.2.0 SoftDevice underneath (identified from the flash dump: every byte of Nordic’s released S113 7.2.0 image matches). The SVCall, PendSV and SysTick vectors all point at branch-to-self traps, so no scheduler or RTOS switches tasks, and the wired and wireless paths are two separate loops. The dongle’s two chips are bare-metal too. That made patching simpler: nothing preempts added code except interrupts.
The patch gate can establish that code is structurally sound. It cannot decide whether a change preserves the firmware’s intended behaviour. I used headless Ghidra decompilation as a second opinion for that separate question.
Part 1: prove recovery before patching
Section titled “Part 1: prove recovery before patching”The earlier brick
Section titled “The earlier brick”The earlier failure came from a defective patch on the correct stock base. Its added guard code occupied bytes that belonged to a live interrupt handler used for SoftDevice dispatch. The patch also branched into the middle of two instructions. The result still entered boot mode and displayed its normal boot banner, but USB, motion, and buttons never started.
The vector table led to the damaged handler, and a byte comparison against stock established the rest. Boot mode accepted the stock package and recovered the mouse in about 15 seconds. The flash path had worked; the generated image was bad.
That distinction drove the current process. I reconstructed the brick as an offline regression case, then treated protected live code, instruction boundaries, and whole-image references as release requirements.
The recovery rehearsal
Section titled “The recovery rehearsal”Before changing my nRF52840 mouse, I entered its boot mode and installed a rebuilt stock V3.05 package. The stock updater accepted it and the mouse returned to normal operation. That proved the recovery path on the unit I was about to modify, including the package format and boot-entry route.
Every later experiment kept a matching stock recovery image ready. Changes to boot-entry code or settings loaded before USB stayed out of scope until a lower-level hardware recovery method exists.
Part 2: validate the whole image
Section titled “Part 2: validate the whole image”Each patch describes its changes against one exact stock image. The gate rebuilds the output and checks the final firmware rather than inspecting an isolated assembly fragment.
| Check | What it establishes |
|---|---|
| Entry-point provenance | The interrupt table and boot entry change only where the specification explicitly allows |
| Protected ranges | Stock handlers and other live code stay byte-identical |
| Free-space references | A claimed unused region has no code or data references pointing into it |
| Static RAM use | Added state does not collide with known RAM users; a complete dynamic RAM map is still a separate burden of proof |
| Relocation | Displaced instructions still encode correctly at their new location |
| Decode round trip | The intended instructions survive assembly, and decoding the final image produces the same instruction stream |
| Branch boundaries | Control flow lands on instruction starts, including computed and literal-target branches |
| Call contracts | Stack depth and alignment, argument registers, callee-saved registers, and flags survive each wrapper and return path |
| Literal pools | Constants resolve to the intended aligned pool entries, including references reached through helper branches |
The failures behind the checks
Section titled “The failures behind the checks”| Patch or candidate | Failure | Disposition |
|---|---|---|
| Earlier brick | A patch overwrote a live interrupt handler and entered instructions at invalid boundaries | Recovered with stock firmware; retained as a regression case |
| Retry v1 | Changing cbz r0 into an unconditional branch left the stack depth and a live register wrong for the enqueue-failure path | The original failed the offline contract harness and the corrected version passed; v1 never shipped |
| Normal-gate candidate | Its initial review treated text references as proof that 14 changes were safe | Full caller and reference analysis replaced that claim; I did not flash the candidate |
| F3 sensor access | A literal resolved into nearby data rather than an aligned pool entry | This reached hardware before literal checking existed and hung the mouse; I reverted it and replaced the feature |
| R3 counter wrappers | A wrapper loaded the stock callee into r1, clobbering the callee’s second argument | The gate’s literal-target check caught it before I flashed that version |
The F3 failure matters because it crossed the same structural gate that had passed offline. The fix was to make the gate follow and resolve the literal, then add a fixture that distinguishes the bad image from the corrected one. A passing gate says the image is structurally sound; whether a change is a good idea is a separate review.
Part 3: identify the changes on the mouse
Section titled “Part 3: identify the changes on the mouse”The current image contains a small set of changes. The dongle remains stock.
| Change | Current behaviour | Evidence and limit |
|---|---|---|
| USB enqueue retry | The motion-report builder checks whether enqueue succeeded and retries on the failure path instead of clearing the report | Static analysis found the loss window; the patched mouse works normally. I have not induced a controlled queue-full condition, so the benefit is unmeasured |
| Unique USB serial | The descriptor uses a unique per-unit string rather than the same hardcoded string on every mouse | Verified in Windows Device Manager; pairing does not use this string |
| Diagnostic command framework | Opt-in host commands queue work to the main loop, with bounded waits, watchdog feeding, and reset-safe arming | Framework and command replies ran on hardware. The interrupt handler stays short and sensor work runs outside it |
| Raw sensor frame | A single-shot command reads the 36 x 36 pixel array and returns 1,296 bytes in 100 thirteen-byte chunks; a stream mode pushes the chunks unasked, about 3.8 frames per second. USB only | Repeat captures and a 10-frame stream completed on hardware; this is a diagnostic view, not a tracking-quality test |
| Diagnostic counters | One counter records USB enqueue failures; two others record entries to specific dispatcher and pairing-loop call sites | The enqueue-failure label is direct. The other two are event counters, not RF retransmit or 8K-slot counters |
| Sensor overrides | An opt-in table of up to eight sensor register writes, re-applied every time the stock firmware rewrites its sensor configuration | A frame-rate value and a downshift value survived a DPI change and a capture power-up on hardware; clearing the table restored the stock values |
| USB timing probe | Opt-in hardware timestamps of USB frame starts, report loads and host acknowledgements | Read from the PC as histograms; changes no stock behaviour |
| Wired late read | On the cable, the main loop waits until shortly before the next poll before it reads the sensor and loads the report | Switches itself on after every reset and can be switched off from the PC until power is removed. Measured below in Part 7 |
The counter block is not initialised at boot. It counts as valid only while a magic word sits next to it in RAM; on first use without that word, the code zeroes the counters and stores the word, so leftover RAM after a reset never shows up as counts. I initially labelled the two event counters as radio retransmits and slots. Tracing their call sites disproved that interpretation, and the current names describe only what the code increments.
The diagnostic RAM range sits above the initial stack and avoids known static users. No complete RAM ownership map proves that every dynamic firmware path leaves it unused. Normal operation and the diagnostic runs passed within that narrower limit.
The sensor frame
Section titled “The sensor frame”The pixel-read sequence was adapted from a public PAW3395 driver, then integrated with the stock firmware’s own sensor read and write helpers so each transfer retained the expected chip-select cycle and timing.1 My sensor is PAW3950-class, so the public PAW3395 sequence was a lead to test, not proof of compatibility. The first integration attempt aborted during capture; using the stock helpers and preserving state across helper calls produced the complete frame below.

The capture path is off at boot, runs once when armed, feeds the watchdog during long operations, and gives up after bounded timeouts. Those are recovery properties. I have not measured a latency or tracking benefit from exposing the image.
The first version worked once per power cycle. After one frame, every later capture timed out waiting for the first pixel, while tracking carried on. The mouse keeps the last good frame in RAM, and my first host tools showed that stale frame as a new one, which looked like a sensor that never changed; both tools now refuse a capture that did not finish. A small diagnostic command that reads sensor registers from the PC showed the cause: after a grab, the pixel-status and pixel-data registers read zero on every poll. The sensor produces no more pixels until it is powered up again. The stock firmware powers the sensor up at boot and on every wake from sleep, which is why a few captures had worked mid-session. The capture now ends by calling that stock power-up routine, and repeat captures work.
The power-up re-applies the stock sensor settings for the mode the mouse is in. On USB that is the configuration the stock firmware itself chooses when it starts on the cable, so a capture does not leave the sensor in a state the stock code never uses.
The reference sequence also overwrote the sensor’s mode register with a fixed value, which dropped the stock performance-mode bits. Keeping those bits and setting only the grab bit cut the grab from 450 ms to 104 ms per frame, timed with a hardware timer the stock firmware leaves unused. With my hand off the mouse, consecutive frames in a 15-frame run differed by 0.9 to 1.2 raw pixel units on average, apart from one step right after the start. The slower mode gave 0.9, so the faster grab did not add noise.
For a live view, the mouse now pushes the 100 chunks of each frame on its own, one per 1 ms main-loop pass, through the stock report-sending routine and only when no stock reply is waiting. A 10-frame run arrived complete at 3.8 frames per second. The power-up after each grab (57 ms) and the register reads set most of the remaining time, and the mouse cannot track while the sensor is sending pixels.
The view works only over USB. I patched the mouse’s wireless command path to accept these commands too, but the dongle answers them itself: it replied in under a millisecond with the same rejection when the mouse was switched off. A wireless view needs a dongle firmware change, which I have not made.
Sensor settings that survive re-initialisation
Section titled “Sensor settings that survive re-initialisation”A sensor vendor’s blog has published a few PAW3950 registers that the datasheet does not describe, among them the frame rate and two ways to disable DPI downshift.2 Writing those registers from the PC worked, but only until the next DPI change. To test that, I wrote a frame-rate value and a downshift value that differ from stock, read them back, pressed the DPI button, and read again: both were back to the stock values. The stock firmware rewrites its whole sensor configuration on every DPI change, polling-rate change and wake, and after each raw-frame capture.
The rewrite has two entry points. The settings routine runs for rate changes, wakes and the capture power-up; the DPI handler calls the full table write directly and skips the settings routine. My first override hook sat only at the end of the settings routine, and one DPI press undid it. A second hook at the end of the table write fixed that. The overrides now survive DPI changes and captures, and clearing the table re-runs the stock routine, which restores the stock values.
On this mouse the stock code selects the 20,000 fps setting when Turbo is on or the DPI is high, and 12,000 fps otherwise. Downshift stays enabled, with its threshold at the 4,000 DPI value from the published register table, and the anti-jitter timeout stays off. The community source has not published the registers for smoothing or set-down behaviour, so the override table cannot reach those. One value I sent by mistake, a frame-rate register of zero, stopped the sensor from delivering raw pixels; clearing the table recovered it.
Part 4: rule out suspected defects
Section titled “Part 4: rule out suspected defects”Several attractive patch targets survived review unchanged.
| Suspected flaw | Finding | Evidence |
|---|---|---|
| Click debounce is hardcoded | The main buttons read the user-facing Debounce setting on both press and release | Static trace plus Ghidra review |
| Debounce 0 still waits for a fixed counter | With Debounce 0, an ordinary press is accepted on the first qualifying scan | Static trace of the threshold and state transition |
| Wired scans add an unknown long delay | The wired button loop waits for USB start-of-frame and scans once per 1 ms frame | Code-derived period; mode scaling makes Debounce N correspond to N ms wired |
| The dongle corrupts motion by clearing an accumulator | The suspected clear in V2.25 resets channel-scoring state, not motion | Dongle disassembly and caller trace |
| Other suspect dongle regions need preventive patches | Their boot-table placement and reference checks found no live corruption to fix | Static whole-image review; no patch flashed |
| Wired USB can reach 8K with a firmware change | The mouse’s nRF52840 USB controller is full-speed; the separate high-speed dongle provides 8K wireless reporting | Hardware architecture and measured USB cadence |
| Wired start-of-frame pacing is broken | Both stock and current images measured a 999.9 us median wired report interval | USBPcap, one 30-second motion run per image |
For wired clicks with Debounce 0, the scan period and following 1 kHz poll give a computed roughly 0.5-2 ms path under the traced conditions. That is an estimate from the code and USB schedule, not a click-latency measurement. The wireless scan timing is less completely traced, so I do not apply the same conversion there.
The stock slam-click filter
Section titled “The stock slam-click filter”Ghidra caught a behavioural mistake that the structural gate had accepted. I had added a patch that forced debounce to zero while the sensor reported lift. The stock code instead forces an eight-scan debounce during lift, independent of the user’s ordinary setting. After landing, a mode-scaled countdown of 20, 40, 80, or 160 scans suppresses a second transition; at the wired 1 ms scan period, those values correspond to an 8 ms lift threshold and a 20 ms landing window.
A hard set-down can produce a short pulse without producing eight consecutive qualifying scans. Removing the lift override disabled that protection on both main buttons. I removed the patch and flashed the corrected image, and ordinary clicks still work with the user setting. I have not run a controlled lift-and-slam test on it, so the filter’s effect rests on the code reading.
The gate checked where the patch went, and Ghidra showed what the replaced stock code did.
Part 5: measure report cadence
Section titled “Part 5: measure report cadence”I captured 15 seconds idle followed by 30 seconds of hand-driven circles and side-to-side motion for each image. The dongle stayed on stock V2.25. The patched image at that point contained only the enqueue retry and the unique serial. These were single runs without a repeatable motion rig.
| Image and path | Reports in motion phase | Median interval | P99 interval | Maximum gap |
|---|---|---|---|---|
| Stock, wired | 30,028 | 999.9 us | 1012.8 us | 8477.9 us |
| Current, wired | 30,027 | 999.9 us | 1012.1 us | 4394.1 us |
| Stock, wireless | 239,870 | 124.9 us | 133.0 us | 33150.9 us |
| Current, wireless | 240,319 | 124.9 us | 133.0 us | 3517.2 us |
The medians establish the expected host-visible cadence: 1 ms wired and 125 us wireless. The smaller maximum gaps on the patched runs are not evidence that the patch improved them. Hand motion differed, there was one run per condition, and the retry acts only when the USB queue is full.
My first wireless loss estimate was also wrong. It assumed that delayed motion would return as one unusually large catch-up report. The dongle instead places records into a 96-entry ring, so delayed motion can emerge as a run of ordinary-sized reports or be tail-dropped when that ring fills. I withdrew the wireless loss percentages rather than compare them across images.
Wired gaps remain ambiguous too. A stopped host poll followed by an ordinary report could mean undelivered motion, but missed USBPcap records can look the same. Resolving that needs sensor, radio, and USB observations at the same time, plus repeatable motion and several runs per image.
Part 6: bound the remaining latency claims
Section titled “Part 6: bound the remaining latency claims”The PC capture shows all eight 125 us wireless slots populated during motion. That does not show how old a sample was when the mouse sent it to the dongle.
The mouse-side radio trace found an eight-entry ring of 125 us motion samples. The transmit callback takes one buffered entry for each follow-up slot. A sample can therefore be up to about 1 ms old when sent, computed from the buffer depth and sample period. The PC still sees evenly spaced reports because the dongle has its own buffering and USB schedule. A fix would change this mouse-side slot path; I have not built or flashed one, and no latency gain has been measured.
SensorLock is the useful comparison for a more complete solution. Published measurements report 37 us from sensor-frame capture to USB on one wired PAW3950 mouse and 80 us on its wireless sibling, achieved by phase-locking sensor frames, SPI reads, radio traffic where present, and USB polls. The same article reports 205 us wired and 285 us wireless for another vendor’s Frame Sync implementation.3 Those are the authors’ reported measurements, not measurements I reproduced.
The exact SensorLock sensor-timing method has not been published. Having a PAW3950-class sensor does not supply that missing mechanism. Motion Sync is a different feature: the same article describes per-read motion rescaling that adds most of one polling interval of latency, and the vendor already exposes it as a toggle. My raw-frame command and evenly populated PC traces do not implement or demonstrate SensorLock.
Part 7: read the sensor just before the poll
Section titled “Part 7: read the sensor just before the poll”Published work describes the lowest-latency way to time a mouse that cannot synchronise its sensor frames: read the sensor and load the report as late as possible before the USB poll, not right after the frame starts, because any gap between the load and the poll is added latency.4 The stock wired loop on this mouse does the opposite. It waits for the start of each 1 ms USB frame, runs its button, wheel and sensor work, loads the report, and then waits for the next frame.
Measuring inside the mouse
Section titled “Measuring inside the mouse”PC-side timing cannot show when a report was loaded, so I measured inside the mouse. The nRF52840’s programmable peripheral interconnect can route a USB event straight to a timer’s capture register, so the timestamp is taken by hardware at the event with no interrupt code involved. I routed three USB events to a timer the stock firmware never uses: the start of each frame, an endpoint buffer being handed to the USB block (the report load), and the host acknowledging the data. Code in the idle loop reads the captures and fills histograms that the PC reads back. Every register offset came from Nordic’s published register description, and the stock code never touches the interconnect channels or the timer I used.
On stock firmware, the PC polled 0 to 63 us after each frame start in 98 % of frames, and 98 % of reports were loaded 128 to 255 us after the frame start. So almost every report had just missed its frame’s poll: 97.8 % waited 768 to 895 us for the next one.
The fix and its tuning
Section titled “The fix and its tuning”The change holds the wired loop after each frame start until a delay D has passed, then lets the stock work run, so the sensor read and the report load happen late in the frame. The first fixed-delay runs showed the effect directly:
| Delay D | Reports | Report loaded after frame start | Wait for the poll | Waited a whole extra frame |
|---|---|---|---|---|
| Stock | 675 | 128-255 us (98 %) | 768-895 us (97.8 %) | - |
| 500 us, fixed | 5,548 | 640-703 us (99.8 %) | 256-383 us (100 %) | 1 |
| 700 us, fixed | 10,260 | 832-895 us (99.8 %) | 128-255 us (99.7 %) | 14 |
Like other work in this area, the shipped version adapts D: a report loaded after the next frame start counts as a miss and lowers D by 10 us, and 100 on-time reports raise it by 5 us, up to a cap of 900 us. Getting that controller right took four attempts on hardware, and each failure walked D down to zero, which is the stock timing:
- A fixed threshold on the wait called on-time reports late once D moved the load past it.
- Treating “not taken by this frame’s poll” as a miss counted transfers that the USB interrupt starts on other endpoints after the poll.
- Treating any frame the delay code did not see as an overrun fired constantly while the mouse was idle.
- The delay first ran from a hook inside the wait loop. The frame-start flag was often set between that hook and the loop’s own check, so about 45 % of frames went through with no delay at all.
The final version sits at the one point every pass of the wired loop reaches after the wait, and it judges a miss only by the newest report having been loaded after the current frame started. With continuous motion over 29,332 reports, D settled near 545 us. The PC took 79.2 % of reports within 0 to 127 us of the load and 17.5 % within 128 to 255 us. About 1.9 % waited a whole extra frame or more; a similar share of host polls also arrived late in the frame in stock runs, so part of that is the PC rather than the mouse.
To see what limits D, I built a measurement-only image that stamps the time at the start of each of the 32 calls in the loop body. Two calls do almost all the work: the sensor motion burst read takes about 38 us and the button processing about 41 us; each of the other calls costs a few microseconds. In that run D sat near 690 us: the loop resumed at about 690 us after the frame start and called the report send at about 857 us, with the sensor read near the start of that work. In the longer adaptive run above, D settled lower, near 545 us, while reports still loaded 896 us or later; I have not explained the gap between those two numbers yet.
The mean is short; the variation is what holds D back. Most of it comes from a second idle call in the middle of the loop, which sometimes takes up to about 55 us, and from one other routine that occasionally takes about 30 us. The controller has to leave room for those slow passes, so on a typical pass the report is loaded with margin to spare. From these means, motion is roughly 190 us old when the PC polls; that is an estimate, not an end-to-end measurement. Swapping the button and sensor calls would make motion about 40 us fresher and clicks about 36 us staler, so I left the order alone. Two other limits remain: status requests from the PC count as misses and pull D down slightly, and the slow passes have not been explained yet.
This applies only to the cable. On the dongle the mouse sends motion over its own radio schedule, and the equivalent change is the 8K slot path described in Part 6.
User-space timing versus bus timing
Section titled “User-space timing versus bus timing”A browser-based plot of the same dongle traffic showed over a thousand intervals per minute off the 125 us grid and 15 gaps over 1 ms per minute. A USB bus capture of the current image, taken the same day, showed 2 gaps over 1 ms per minute, against 12 for the earlier patched image and 28 for stock in their single runs. Published work makes the same point: jitter of hundreds of microseconds in tools that time reports in user space comes from the operating system and says little about the firmware.4 Firmware timing has to be measured with a USB bus capture or timestamps inside the mouse.
Part 8: run the mouse on another model’s dongle
Section titled “Part 8: run the mouse on another model’s dongle”The 8K dongle has the same hardware across mouse families: one CH32V305 for USB and flash storage, and one nRF52820 for the radio. But plugging one family’s mouse into another family’s dongle does not work out of the box, because the radio firmware differs per family.
The CH32 also stores a pairing identity record (vendor id, model id, and a checksum) in its last flash pages, and I first assumed that record was the lock. I tested on a second dongle that belongs to a different mouse model, with both chips dumped first so the original state is recoverable.
CID-only pair: the mouse paired successfully and the dongle reported paired state, but no cursor movement followed. The identity record stayed on the original model id.
CID+MID pair with the mouse’s actual model id: same result - paired, no data. The static code trace had predicted the CH32’s SetCidMid handler would rewrite the identity, but the hardware showed otherwise. A later full read of the CH32 code explained it: the identity writer runs only when the vendor id the mouse reports matches one of five accept slots filled from the host’s pair request, and the CID+MID form of that request leaves all five slots zero.
Forced model id in the CH32’s identity loader with a one-instruction patch: the handshake reported the target model id, pairing succeeded, but still no data. So the stored identity is not the only difference between the two dongle firmware lines.
Full cross-flash: the target family’s firmware on both chips (nRF and CH32), with the same one-instruction identity patch. The mouse moved the cursor.
Two follow-up tests split it. Mixed flashes: the target family’s radio firmware on the nRF with the original CH32 firmware worked; the original radio firmware with the target family’s CH32 firmware paired but carried no data. Then a small CH32 patch added a command that writes the identity record through the firmware’s own routine. On the mouse’s own dongle, with the record set to the other family’s model id, and even with the dongle in pairing mode for a model id no mouse uses, the mouse paired fresh and worked.
So the model id is a label: it decides what the dongle reports to configuration apps, not which mouse it accepts. The only real difference between the two families’ dongles is the nRF52820 radio image. A family switch is one radio flash and a re-pair.
A read of every place the CH32, both radio images and both mouse images touch the identity then showed what does tie a dongle to a mouse:
| What | Decides |
|---|---|
| Which mouse | A 32-bit key the radio builds from its own factory device id (FICR DEVICEID0). It goes out in the pair response, the mouse stores it, and both sides use it as the link address. The pairing checks compare only those four bytes |
| Which mouse family | The radio image’s packet handling. The two families’ radio images share pairing and radio setup; the five functions that differ build, receive and parse the packets |
| One check in the CH32 | The vendor id only: after pairing, a mouse whose vendor id is not one the host’s pair request allowed has every report dropped. All mice in this family share one vendor id, so it never triggered here |
| The model id | Nothing on the devices. No code in the CH32, the radio or either mouse compares it; the mouse only rejects 0x00 and 0xFF. The vendor’s configuration app uses it to choose the device’s name, settings and offered firmware |
That explains each result above: the original radio image paired the mouse because pairing code is shared, then dropped its packets because it parses the other family’s format.
A community developer had already dumped both chips of the 8K dongle before I attempted any of these cross-model flashes, using the same technique I later applied to the mouse: patch the device’s own app with a bounded read-memory command, flash through the normal update path, and read every byte over USB. That method and its preconditions are covered in Dumping a locked nRF52840’s flash over USB with a patched app.
Part 9: write new patch code in C
Section titled “Part 9: write new patch code in C”The first patches were hand-written Thumb assembly, about 2,950 lines. Buffer sizes, register allocation, literal pools and branch encodings were all counted by hand, and that is where the defects came from: a read handler that copied 13 bytes into a 13-byte buffer that also held a status byte, and earlier branches into the middle of an instruction. New features are now C, and the compiler owns those details.
The setup is small because the stock firmware already owns startup, clocks, the radio stack and USB. A feature is one C function that the existing command framework calls:
| Piece | Role |
|---|---|
| Board header | Stock function entries and RAM addresses for one exact image. A second mouse on the same chip gets its own header; the feature code does not change |
| SDK headers | Register definitions and CMSIS from the nRF5 SDK release that ships the same SoftDevice version as the mouse (S113 v7.2.0). No SDK code is linked |
| Linker script | Places one feature in one fixed slot of the image. A feature that declares RAM data fails the link, so it cannot land on memory the stock firmware uses |
| Gates | The same as for assembly: the patch gate on the final image, a decompiler read of the built code, and a differential test when C replaces an assembly feature |
The first port was the memory-read handler. Run in an emulator against the assembly version, it gave the same result on 133 inputs around every range edge, and the same test flagged a planted copy of the old 13-byte bug. The first new feature in C streams flash reads, one block per main-loop pass, numbered so the host can re-read any it misses; it worked on the mouse the first time it was flashed: a full 1 MB read in 88 seconds per pass instead of 524 (dump guide).
Verification
Section titled “Verification”| Claim | Verification performed | Remaining limit |
|---|---|---|
| Stock recovery works on this mouse | Boot-mode stock-package rehearsal before patching | Does not make an unrelated model recoverable by the same procedure |
| Current image is functional | Flashed, enumerated, and checked motion and buttons | No long power-cycle and sleep soak has been completed |
| Unique serial is visible | Checked in Windows Device Manager | Identity change only; no performance effect |
| Raw capture and live view work | 11 repeat captures and a 10-frame stream over USB, all complete | Not over the dongle; the mouse stops tracking during each grab; not a sensor-performance result |
| Counter command works | Exercised the command and explicit clear | Two counters describe local call-site entries; they are not radio-slot measurements |
| Stock slam filter is active | Decompile review; the overriding patch was removed and the stock code is byte-identical | No controlled lift-and-slam test yet |
| Wired and wireless cadence | USBPcap medians and percentiles in the table above | One hand-driven run per image; no click or sensor-to-USB latency result |
| Enqueue retry helps under back-pressure | Failure path exists statically and the corrected patch is functional | No controlled back-pressure experiment has quantified its benefit |
| Sensor overrides persist | Marker values read back after a DPI press and a capture power-up; clear restored stock values | Only a frame-rate and a downshift register were exercised; their effect on tracking is unmeasured |
| Wired late read lowers report wait | In-mouse hardware timestamps, stock and fixed-delay runs plus a 29,332-report adaptive run | Wait for the poll, not end-to-end motion latency; hand-driven motion; cable only |
| The firmware has no RTOS | Vector table and SoftDevice call sites in both images | Static evidence only |
Gotchas and lessons learned
Section titled “Gotchas and lessons learned”- Prove recovery on the same unit first. A working flasher and a successful write say nothing about whether the new application can boot.
- Keep structural and semantic review separate. The literal and register checks caught broken code; Ghidra caught a validly installed change that removed a useful stock behaviour.
- Treat each image as a new target. The two nRF52840 mouse models share a family resemblance, but their handlers, addresses, and behaviour cannot be carried across without fresh evidence.
- Name counters after their call sites. A counter near radio code can still count dispatcher entries rather than retransmissions.
- Measure the boundary you care about. PC report cadence cannot reveal sample age inside the mouse or dongle. The separate Windows host-side investigation is in Fixing merged reports from an 8 kHz mouse on Windows.
- Keep a negative result when the method collapses. The invalid wireless loss estimate was more useful as a correction than as a flattering before-and-after number.
- Check that a setting survives the firmware’s own re-initialisation. A register write that reads back correctly can still be gone after the next DPI press.
- Put timing code where every pass goes. A hook that runs only while the loop is idle missed the frame start in almost half the frames.
- Judge a feedback loop on the event it controls. Three of the four controller failures came from proxies for a miss, and each one drove the delay back to stock.
- Flags kept in RAM survive a reflash that is not a power cycle. A “switched off” flag from a test session kept the late read off after I flashed the daily image back.
File reference
Section titled “File reference”The patched image is installed from the browser with tikus, which refuses a modified package without its gate record. The records behind this guide, by local file name:
| Artifact | Role |
|---|---|
stock.bin | Matching stock image and recovery baseline |
next.bin | Current mouse image |
next.spec.json | Declarative patch and protected-range specification |
next.bin.patchgate.json | Whole-image gate result for the flashed image |
raw-20261118-204350-00.png | Real sensor frame shown above |
stream-session.jsonl | Every report of the 10-frame live-stream run |
baseline.ps1 | USBPcap capture script used for the cadence runs |
usb-probe.sh | Reads the in-mouse timing histograms and switches the late read |
results.md | Late-read measurements, including the failed controller versions |
Related docs
Section titled “Related docs”- Dumping a locked nRF52840’s flash over USB with a patched app - the USB dump technique used on both the mouse and the dongle’s CH32V305 and nRF52820
- tikus: a browser configurator and firmware updater for vendor mice - how the browser app installs the patched firmware
References
Section titled “References”-
“PAW3395_Arduino_ESP32,” public PAW3395 Arduino/ESP32 driver, including the
Pixel_Burst_Readsequence. https://github.com/kirltrz/PAW3395_Arduino_ESP32 ↩ -
XBAB Tech blog, “Investigating and fixing PAW3950 DPI downshifts,” including the frame-rate register found by comparing the low and high DPI Corded Gaming register tables, and the downshift and anti-jitter registers. https://xbabtech.com/blog/downshift/ ↩
-
XBAB Tech blog, “SensorLock - minimizing timing jitter and latency simultaneously,” including the frame-to-USB measurements and the distinction between Motion Sync and sensor-frame phase locking. https://xbabtech.com/blog/sensorlock/ ↩
-
XBAB Tech blog, “Firmware (part 1),” on reading the sensor just before the USB poll, missed polls, and why user-space timing tools show jitter the firmware does not cause. https://xbabtech.com/blog/firmware ↩ ↩2