Building Flash Read/Write Protection Algorithms for Embedded MCUs: A Practical Guide

    This article explains why a flashing tool is incomplete without algorithms for the chip's option bytes, and how to build them. It covers separating configuration space from user flash, core design principles (read/write separation, read-before-write, and reversibility first), a reusable algorithm structure, implementation details for enabling and disabling read protection, keeping online debugging and offline programming consistent, and a validation checklist for production and rework.

    1. Why “Programmable” Does Not Mean “Protection Managed”

    In embedded production and delivery workflows, a programming tool needs two kinds of algorithms. One targets the user program area and handles erasing, writing, and verification. The other targets the chip’s configuration area, commonly called the option bytes, which control the read protection level, write protection ranges, debug interface state, and boot configuration. Many chip vendors publish only the first kind of algorithm file. The second is often missing, so the tool can download firmware normally but cannot enable or disable read protection, nor configure chip state consistently during production.

    The direct consequences are significant. The production line cannot verify after flashing whether protection actually took effect. During rework, a chip may sit at a high protection level with the debug port closed, leaving full-chip erase or scrapping as the only options. Offline programmers and in-circuit debuggers may behave differently, so the same firmware batch behaves differently at different stations. Completing the configuration-area algorithm is therefore a necessary part of a complete programming toolchain, not an optional enhancement.

    2. Why Configuration Space and User Space Must Be Handled Separately

    The user program area is usually organized by sector or page, with a well-defined erase granularity, so the algorithm only needs to handle address mapping, timeouts, and verification. The configuration area is different. It often resides in a separate address space, has a smaller write granularity, contains bits that cannot be programmed repeatedly, and requires a fixed lock/unlock timing sequence. More critically, raising the read protection level may cause the chip to automatically erase the user area or permanently disable the debug channel. Such side effects are irreversible or extremely costly.

    The design must follow three principles. First, separate reads from writes: reading configuration identifies the current state, while writing configuration changes it, and the two must not share the same entry point. Second, read before write: always read back the actual value before any change, rather than making decisions based on a cached value. Third, prefer reversibility: disabling protection should follow a downgrade path recognized by the chip vendor rather than relying directly on a full-chip erase.

    The processing logic can be abstracted as follows:

    1. /* Pseudocode: expresses the flow only, not tied to any specific chip */
    2. bool option_write(uint32_t addr, uint32_t value) {
    3. uint32_t current = option_read(addr);
    4. if (current == value) return true; /* idempotent return */
    5. if (!option_unlock()) return false; /* unlock sequence */
    6. if (!option_program(addr, value)) return false;
    7. if (!option_lock()) return false;
    8. return option_read(addr) == value; /* read-back verification */
    9. }

    3. A Reusable Structure for the Algorithm

    A reusable configuration algorithm typically has five parts: an entry declaration, a capability description, a read channel, a write channel, and a state machine. The capability description tells the upper-layer tool which levels the algorithm supports and whether it can disable protection or only enable it, preventing the tool from issuing illegal commands. The state machine manages the unlock, program, lock, and reset-wait phases, and any phase must be able to roll back safely on failure.

    At the interface level, keep the set minimal: initialize, erase (which may mean “downgrade” for the configuration area), program, verify, and reset. Encapsulate the differences inside the algorithm so the upper layer sees only unified semantics. This lets in-circuit debugging and offline programming share the same call path and reduces behavioral drift between two separate codebases.

    4. Enabling and Disabling Protection

    The enable path is relatively simple: write the target protection level, read back to confirm, then trigger a reset so the configuration takes effect. The difficulty lies in the disable path. A common approach is to first check the current level. If the chip is already at the highest level and does not support downgrade, the only option is a full-chip erase to restore the factory configuration. If downgrade is supported, write the disable marker as required by the vendor and wait for the chip’s internal erase to complete. This can take on the order of hundreds of milliseconds, so the timeout must be relaxed rather than treated as a normal write.

    Three boundary cases also need handling. First, unlock failure before writing the configuration area, usually caused by power-on timing or a clock that is not ready. Second, a read-back value that does not match the written value, typically because a write protection bit is still in effect. Third, poorly timed reset, which the tool may misjudge as a failure. Provide a clear error code for each failure type and log the raw read-back value so the production line can locate issues quickly.

    5. Keeping Online and Offline Scenarios Consistent

    In the online scenario, the debugger shares clock and reset control with the chip, and the algorithm can complete within a debug session. In the offline scenario, the programmer must drive the target chip independently, with stricter timing. To keep them consistent, make the algorithm independent of the transport layer and inject all delays through a unified interface: the offline side implements precise delays, while the online side implements debugger-controlled delays. The offline flow must also perform a power-cycle restart verification after programming to confirm the protection state still holds after a cold start.

    6. Validation Checklist and Risk Control

    Build a fixed validation matrix: a blank chip, a chip with write protection, a chip with read protection, ten repeated toggles, two temperature points, and one round each for online and offline. Record the read-back value, elapsed time, and failure code for each round. On the production side, make “disable protection” an explicit station action, forbid implicit full-chip erase, and retain the final configuration-area value in the flashing log for traceability.

    7. Conclusion

    Completing the configuration-area algorithm is essentially bringing the chip’s state management under the controllable scope of the toolchain. By insisting on read/write separation, read-before-write, and reversibility first, and by encapsulating differences behind a unified interface, you can keep enabling and disabling protection consistent across both the online and offline paths, significantly reducing uncertainty in production and rework.