MCU Internal Flash Read and Write Protection: Algorithm Design and Implementation
A reliable MCU Flash protection algorithm must coordinate security policy, option-byte programming, reset timing, and production workflows. This article explains how to model protection states, implement enable and removal sequences, share core logic between host-connected and standalone programmers, and verify results with diagnostic logs and regression tests.
Protecting on-chip nonvolatile memory requires more than adding another erase routine. It means combining security policy, programming sequences, and production procedures into a repeatable algorithm.
Many device manuals document programming and erasing the main Flash array but provide limited guidance on unlocking, programming, reloading, and verifying option bytes or equivalent configuration areas. Some provide only register bit definitions. Without a protection algorithm, production tools cannot reliably determine protection status before programming or remove protection during authorized servicing.
A practical implementation therefore maintains two separate algorithms: the main Flash algorithm handles code-memory erase, programming, and verification; the protection algorithm handles enabling protection, removing it, and reading back its state.
What Read and Write Protection Must Address
Read protection restricts access through debug interfaces or unauthorized readout, helping prevent complete firmware extraction. Write protection locks selected pages, sectors, or configuration areas against accidental erasure and field tampering.
Both mechanisms often use the same option bytes or configuration words, but they serve different purposes. Read protection primarily establishes a security boundary; write protection primarily establishes a reliability boundary.
Production workflows commonly need three capabilities:
- Start with an unprotected device, program the firmware, and then enable read protection according to product policy, optionally adding write protection for selected regions.
- Allow development and service teams to remove protection under controlled conditions, reprogram the device, and lock it again.
- Allow a standalone programmer, without host interaction, to execute the same sequence: identify the device, erase, program, verify, lock, and read back the protection state.
If only the main Flash algorithm is implemented, debugging may appear normal until the option bytes enter a protected state. Subsequent mass erases, readback verification, or reprogramming can then fail. These failures are often misdiagnosed as incompatible algorithm files or unstable power.
Making protection operations explicit steps allows failures to be traced to unlocking, programming, reset or reload, or readback mismatches.
Algorithm Boundaries and the State Model
A deployable protection algorithm should cover at least four states:
- Unknown: Used after an initial connection, power loss, or failed configuration readback verification. Protection settings must not be written directly in this state. First check the connection and read the configuration area.
- Unprotected: Main Flash programming is permitted, and the device may transition to the protected state according to policy.
- Protected: Main-memory readout or unauthorized erase and programming operations are rejected by default. Returning to the unprotected state requires a successful, explicit protection-removal procedure.
- Transitioning: Option-byte programming has started, but configuration reload has not yet been confirmed. This state requires a timeout and a retry limit to prevent endless loops and repeated writes that could damage the device.
Use a fixed transition sequence:
- Connect, read the device identifier and raw configuration values, and calculate a checksum.
- If firmware programming is requested and the device is protected, remove protection before erasing and programming the main memory.
- After main-memory verification passes, enable protection if the policy requires it.
- Apply the configuration, usually through a system reset or dedicated reload operation, then read it again and compare it with the expected values.
- If any step fails, stop subsequent writes. Preserve the original values, expected values, and failed step number in the log.
This separation lets host-connected and standalone programming share one decision table. In host-connected mode, the host supplies the current policy. In standalone mode, the task description stores it—for example, “enable read protection after programming; do not enable write protection.”
The algorithm should not depend on a particular debugger interface. It should consume standardized read, write, reset, and delay primitives.
General Sequences for Enabling and Removing Protection
Although register names vary widely across MCU cores, the engineering sequence is similar. The following pseudocode expresses the control flow without tying it to specific addresses:
function set_protection(target):cfg = read_option_area()if crc(cfg) mismatch and retry_exhausted:return FAIL_READif current_state(cfg) == target:return OK_ALREADYunlock_sequence() # Write unlock keys in the documented ordernew_cfg = merge(cfg, target)program_option(new_cfg) # Program halfwords/words; observe erase prerequisitesreload_or_reset()wait_until_ready(timeout)cfg2 = read_option_area()if cfg2 != new_cfg:return FAIL_VERIFYreturn OK
Four implementation details are especially important.
Unlocking Is a Sequence, Not a Single Register Write
Many devices require consecutive writes of specified key values. Intervening bus accesses can cause the unlock sequence to fail. Disable unnecessary background reads during this operation, and proceed promptly with programming after unlocking.
Rebuild Complementary and Redundant Configuration Values
Option bytes often include complementary values or redundant copies. Changing only a protection bit without generating its required complement can cause the device to treat the configuration as invalid after reset and fall back to defaults. The result looks like a successful write that did not actually enable protection.
The merge function must regenerate the complete configuration word according to the device rules, rather than patching individual bits and writing the result back unchanged.
Programming Completion Does Not Mean the Configuration Is Active
Some devices require a software reset, others require a power cycle, and some still need time for internal loading after reset. Verification must occur after the configuration has taken effect. Otherwise, an unloaded configuration may be mistaken for a successful operation.
Removing Protection May Erase Main Memory
This is a security feature, not an algorithm defect. It prevents an attacker from removing read protection and then extracting the existing firmware.
The workflow should warn the operator that data will be lost. After protection removal succeeds, perform a fresh download rather than assuming the previous image remains intact.
Sharing Logic Between Host-Connected and Standalone Programming
Host-connected programming supports interaction. A connection failure can prompt the operator to power-cycle the device, while an abnormal protection state can let an engineer choose between removing protection only and removing protection followed by reprogramming.
Standalone programming provides consistent cycle timing and is well suited to production fixtures. These modes should not use separate protection implementations. Otherwise, a policy change can produce a device that locks correctly in the laboratory but not on the production line.
Keep the differences in adapter layers:
- Host-connected adapter: Handles operator confirmation, log display, and optional single-step execution.
- Standalone adapter: Reads the target protection level, retry count, and cycle timeout from the task file.
- Core layer: Implements only the state machine, configuration-area merging, programming, and readback.
A standalone task should record at least:
- Expected device identifier
- Firmware image checksum
- Target protection settings
- Whether automatic protection removal is allowed
- Whether a full-chip erase is mandatory after removal
If the device identifier does not match, fail immediately. This prevents an algorithm from being applied to a pin-compatible device with a different configuration-area layout.
Verification, Failure Classification, and Production Constraints
The quality of a protection algorithm depends largely on how well its failures can be diagnosed. Return codes should distinguish six categories:
- Read failure
- Unlock failure
- Programming timeout
- Readback mismatch
- Device identifier mismatch
- Policy rejection
For readback mismatches, save the raw configuration words from before and after programming. Comparing them with the device manual helps distinguish incorrect complementary values from a reset that did not apply the new configuration.
Production workflows should also enforce three constraints.
Never lock directly from an unknown state by default. A failed read must not lead to incorrect values being written into the configuration area.
Limit consecutive protection-removal attempts on the same device. Isolate abnormal boards rather than repeatedly erasing and programming them.
Confirm protection through post-reset readback. A programming-complete flag alone is not evidence that protection is active.
For products with higher security requirements, application firmware can perform an additional configuration self-check early in startup and enter a safe shutdown state if protection bits have been unexpectedly cleared. This is a firmware policy, however, and must not replace programmer-side readback verification.
Use structured logs containing timestamps, step names, expected and actual configuration summaries, and elapsed time. There is no need to record the complete firmware image. Checksums are sufficient for summaries and help prevent debugging logs from becoming a firmware disclosure channel.
Regression Testing
When adding support for a new MCU family, a small sample set with tests across independent conditions can cover most risks:
- Programming an unprotected device
- Enabling protection after programming
- Reprogramming a protected device, which should invoke protection removal
- Verifying that main memory is erased or unreadable after protection removal
- Rejecting execution when the device identifier is incorrect
- Checking whether reconnection after a timeout and power interruption restores a determinable state
Keep power and reset timing fixed for each test case so that poor electrical contact is not mistaken for an algorithm defect.
Once these tests pass, use the same state machine in standalone tasks and compare the final configuration words from both programming modes.
Small scripts are well suited to these workflows: protection sequences are short, contain multiple branches, and often require timing adjustments based on the device manual. When the script is packaged into a tool, users should only need to select “enable” or “remove,” without handling key values or addresses.
For maintainers, scripts should retain step comments and failure codes so that manual errata can be incorporated easily. Timing logic should not be scattered throughout the user interface.
Conclusion
Reliable MCU Flash read and write protection treats the option area as an independent programming target with its own state machine: read before deciding, program complete configuration words after unlocking, verify after the configuration takes effect, and stop on failure.
Host-connected and standalone programmers should share the core workflow, with adapter layers handling interaction and cycle timing. This closes the gap between having only a main Flash algorithm and supporting protection properly, while keeping accidental locking, unintended protection removal, and production inconsistencies within a testable process.
Specific key values, addresses, and timing requirements must come from the relevant device manual. The algorithm framework itself can be reused across multiple MCU families.
