Custom Flash Read/Write Protection Algorithms for PC-Connected and Standalone Programming

    Learn how to implement MCU Flash read/write protection through option-byte configuration and integrate it into PC-connected and standalone programming workflows. This article covers configuration models, protection enablement and removal, script-based implementation, verification, and risk controls for production and maintenance.

    1. Why Custom Flash Protection Algorithms Are Needed

    In embedded production and maintenance, the boundaries between writable and readable internal Flash often determine whether a product can be delivered securely. MCU Flash support typically involves two distinct types of algorithms:

    • Internal Flash programming algorithms erase, program, and verify application firmware. They provide the basic functionality that programmers and debuggers need to download firmware.
    • Read/write protection algorithms, also called option-byte algorithms, modify device security settings, such as read protection levels and write-protected page ranges. They control whether external tools can read firmware and whether protected regions can be overwritten.

    Many MCU vendors provide internal Flash programming algorithms without supplying complete read/write protection algorithms. Developers can therefore program firmware but may lack a reliable workflow for automatically enabling protection afterward or removing it during maintenance.

    This gap matters on production lines, where devices must leave programming in a state that prevents unauthorized reads and accidental erasure or modification. During repair or upgrades, protection may need to be temporarily removed.

    Two programming modes make these requirements especially important:

    • PC-connected programming: A host PC connects to the target through a debug interface and can interactively read status, configure parameters, and execute protection operations. The host tool must be able to invoke the protection algorithm as needed.
    • Standalone programming: The programmer operates without a PC. Firmware and algorithms must be loaded into it beforehand. Without a protection algorithm, a standalone task can erase and program Flash but cannot automatically apply protection afterward.

    A reusable, verifiable protection algorithm is therefore an important part of an embedded programming toolchain.

    2. How Flash Read/Write Protection Works

    Flash protection is generally configured through a separate nonvolatile configuration area rather than by modifying the main Flash contents. This area is commonly called the option-byte area and stores security settings such as:

    • Read protection level: Controls whether external debuggers or programmers can read Flash. Different levels impose different access restrictions, with higher levels generally having stricter conditions for removal.
    • Write protection range: Identifies pages or sectors that cannot be erased or programmed, helping prevent accidental overwrites or tampering.
    • Other security options: These may include boot-region settings, debug-port controls, and access restrictions.

    Although option bytes are nonvolatile, their access sequence differs from ordinary Flash programming. Devices commonly require an unlock sequence before accessing or modifying option bytes, followed by locking and a reset to activate the new configuration. The exact requirements must be checked in the target device documentation.

    Some devices also validate option-byte data using complemented values, CRC checks, or a combination of mechanisms. Incorrect validation data can cause the device to reject the configuration or behave unexpectedly.

    The essential workflow is:

    Read the configuration → parse it → modify it → recalculate validation data → write it back → reset to apply it.

    This sequence must follow the target MCU’s documentation. A generic Flash erase/program sequence is not an adequate substitute.

    3. Implementing a Custom Protection Algorithm

    3.1 Gather Device Documentation and Build a Configuration Model

    Start by confirming the following information in the device manual:

    • The starting address and size of the option-byte area.
    • The meaning of each byte or bit field, especially read protection levels and write protection start/end pages.
    • The option-byte validation algorithm.
    • Unlock and lock command sequences.
    • Whether removing protection requires a mass erase.
    • The minimum write protection granularity: a single page, a pair of pages, or a sector.

    Represent this information in a configuration table instead of hard-coding every detail into the algorithm. Supporting another device in the same family can then require changes to the table rather than a complete rewrite of the workflow.

    3.2 Read the Current Protection State

    The first operation is usually to read the current configuration. Where required by the device, this includes unlocking access, reading the option bytes, and locking access again.

    Parse the raw data into a readable protection level and write-protected range. This serves two purposes:

    • PC-connected tools can display the current device state.
    • Standalone tasks can check the existing configuration before applying protection, avoiding unnecessary writes or unintended changes.

    3.3 Enable Read/Write Protection

    A typical protection-enablement sequence is:

    1. Read the current option-byte contents.
    2. Update the configuration structure with the requested protection level and write protection start/end pages.
    3. Recalculate the validation data according to the device specification.
    4. Unlock the option-byte area.
    5. Program the complete option-byte data.
    6. Lock access and reset the target to activate the configuration.

    Skip programming when the current configuration already matches the requested settings. This avoids unnecessary erase/write operations, reduces risk, and improves production efficiency.

    3.4 Remove Read/Write Protection

    Removing protection is more complicated because devices generally restrict reductions in security level. A common process is to select the unprotected state, clear the write protection range, and perform a mass erase. The erase ensures that previously protected sensitive data is not exposed after protection is removed.

    The exact sequence and erase requirements must follow the device manual.

    Treat protection removal as a potentially destructive operation. Before invoking it, the tool must clearly explain the risk and instruct developers to back up firmware or data beforehand where possible.

    If a standalone workflow must remove protection and then reprogram firmware, package both actions as one complete task. This reduces the risk of leaving the device unprotected and without firmware if the process is interrupted, although power-loss behavior still needs validation.

    3.5 Use Scripts to Reduce Maintenance Overhead

    Traditionally, protection algorithms are compiled into separate algorithm files and registered with a programming tool. Each newly supported device may then require another file to compile, release, and maintain.

    Where the tool platform provides a scripting extension, protection logic can instead be implemented as an interpreted script. The script accesses the platform’s device read/write functions to read and modify option bytes.

    Adding device support then requires a new or updated script rather than recompiling the main application, without changing existing functionality.

    The following illustrative pseudocode shows the core idea:

    1. // Read the current protection configuration (illustrative)
    2. option_byte_t read_option_status() {
    3. unlock_flash();
    4. option_byte_t ob = read_option_byte_area();
    5. lock_flash();
    6. return parse_option_byte(ob);
    7. }
    8. // Enable read/write protection (illustrative)
    9. void enable_protection(uint8_t level, uint16_t start_page, uint16_t end_page) {
    10. unlock_flash();
    11. option_byte_t ob = read_option_status();
    12. ob.level = level;
    13. ob.wrp_start = start_page;
    14. ob.wrp_end = end_page;
    15. ob.checksum = calc_checksum(ob);
    16. program_option_byte_area(ob);
    17. lock_flash();
    18. reset_target();
    19. }
    20. // Remove protection (illustrative)
    21. void disable_protection() {
    22. unlock_flash();
    23. option_byte_t ob = read_option_status();
    24. ob.level = NO_PROTECTION;
    25. ob.wrp_start = 0;
    26. ob.wrp_end = 0;
    27. ob.checksum = calc_checksum(ob);
    28. program_option_byte_area(ob);
    29. lock_flash();
    30. mass_erase(); // Confirm erase requirements in the device manual
    31. reset_target();
    32. }

    This is a conceptual example, not a device-specific programming sequence. The script expresses the protection logic, while the platform supplies the underlying access interfaces and handles device-specific timing requirements.

    4. Integration with PC-Connected and Standalone Programming

    4.1 PC-Connected Programming

    When a PC tool connects directly to the target, its interface should provide two categories of operations:

    • View protection status: Read and display the current read protection level and write-protected page range.
    • Enable or remove protection: Accept the requested level and range, invoke the protection algorithm, and read the status again afterward to verify the result.

    PC-connected operation is flexible and well suited to development and debugging. Developers can test protection configurations and investigate problems interactively, subject to the device’s permitted transitions.

    However, operations that depend on manual confirmation are less suitable as the default workflow for large-scale production.

    4.2 Standalone Programming

    A standalone programmer cannot depend on a PC during execution. Its task package must therefore include:

    • The protection algorithm.
    • The firmware image.
    • The target protection settings.

    A typical task can follow this sequence:

    1. Erase the main Flash area.
    2. Program the firmware.
    3. Verify the firmware data.
    4. Configure the read protection level and write protection range.
    5. Read the protection status to confirm successful configuration.
    6. Display the programming result.

    The programmer must execute the protection algorithm locally, without host-side interaction. Task files should also record the algorithm version and configuration parameters to prevent the use of outdated algorithms in production.

    Standalone programming offers efficiency and consistency, but provides less room for interactive recovery than PC-connected operation. Validate edge cases carefully, particularly power loss during protection configuration and retries after verification failures.

    5. Risk Controls and Best Practices

    5.1 Make Destructive Protection Removal Explicit

    Many devices require a mass erase when lowering the read protection level. The tool should clearly warn that continuing will erase all Flash contents.

    In automated workflows, combine protection removal and firmware reprogramming into a single controlled task, with the aim of minimizing uncontrolled intermediate states. This does not eliminate the need to test interruptions and recovery.

    5.2 Select Write Protection Ranges Carefully

    If write protection covers an application update region, subsequent firmware updates or maintenance may be unable to erase or program it.

    Before applying protection, confirm that the selected range covers only regions intended to remain fixed, such as boot code, parameter storage, or security data. Avoid protecting application regions that require frequent updates.

    5.3 Do Not Omit Option-Byte Validation

    Calculate option-byte validation values exactly as specified in the device manual. Some devices use complemented values, others use CRCs, and some require particular bits to retain fixed values.

    A single incorrect bit can prevent the intended protection configuration from taking effect.

    Before release, validate each supported protection level and page-range combination with a sequence such as:

    Write → read → reset → read again.

    5.4 Build Automated Regression Tests

    Protection algorithms carry too much risk to validate with only a few manual operations. Create automated tests covering:

    • Transitioning from no protection to level 1.
    • Transitioning from level 1 to level 2.
    • Removing protection from a higher level, where the device permits it.
    • Configuring different write-protected page ranges.
    • Correctly rejecting invalid ranges.
    • Confirming that standalone tasks produce the expected protection state.

    Test transitions according to the device’s documented restrictions. Automated regression tests improve development efficiency and help identify problems introduced by later algorithm updates.

    5.5 Validate on a Small Scale Before Production Rollout

    Do not deploy support for a new MCU directly to a production line.

    First, complete functional validation on development boards. Then run a small production trial to confirm that the protection algorithm works correctly with the firmware programming workflow.

    Once validated, include the algorithm in the released tool version and maintain version control for the associated task files.

    6. Conclusion

    A Flash read/write protection algorithm may be a small toolchain component, but it directly affects product security and maintainability. When the MCU vendor does not provide one, firmware programming alone is not enough: the toolchain also needs a reliable way to configure the device’s security boundaries.

    The core implementation involves reading, parsing, modifying, validating, and programming option bytes, then resetting the device to apply the settings. The same logic must support both PC-connected and standalone programming workflows.

    Reliable deployment depends on careful validation of destructive protection removal, write protection ranges, option-byte integrity, and interrupted operations. With these controls in place, Flash protection becomes a dependable part of production delivery and maintenance.