MCU Flash Read/Write Protection: Custom Scripts for PC-Connected and Standalone Programming

    Learn how Lua-based scripts can configure MCU Flash protection when vendor SDKs lack option-byte programming algorithms. This article covers the option-byte workflow, a typical script structure, protection verification, and practical considerations for consistent PC-connected and standalone production programming.

    1. Background: The Gap in Flash Protection Support

    Firmware security matters throughout embedded development and production. Most MCUs provide hardware-level read and write protection, typically configured through special settings called option bytes.

    Read protection prevents the debug interface from directly reading Flash contents. Write protection causes the hardware to reject unauthorized writes to protected regions. These mechanisms help protect firmware against copying and modification.

    However, many chip vendors supply only an internal Flash programming algorithm, such as an FLM file, with their SDKs. They do not provide a corresponding algorithm for configuring option bytes. A general-purpose programmer may therefore download firmware successfully but offer no convenient way to enable read or write protection.

    Developers must then write host-side scripts or use vendor-specific tools, reducing workflow flexibility.

    This gap is particularly inconvenient on production lines that require standalone programming: the programmer operates independently of a PC. If protection cannot be configured in standalone mode, every board needs an additional connection to a debugger or host computer. That extra step reduces throughput and makes consistent execution harder to maintain.

    2. The Approach: Script-Based Protection Routines

    One practical approach is to use a programming tool that supports scripting extensions. A lightweight language such as Lua can drive option-byte register operations to enable or disable protection.

    The approach rests on three principles:

    1. Avoid dependence on a vendor-supplied option-byte algorithm. Protection configuration is essentially a device-specific sequence of register writes and waits that a script can perform.
    2. Reuse the tool’s debug interface support. The programmer already implements SWD or JTAG read/write operations. The script calls the tool’s higher-level APIs rather than implementing the debug protocol.
    3. Use the same script in connected and standalone modes. A compatible tool can run the script while connected to a PC or store it on the standalone programmer, keeping the workflow consistent.

    2.1 A Typical Option-Byte Workflow

    Register definitions vary by vendor and MCU family, but the configuration process generally follows this pattern:

    1. 1. Unlock: Write the required keys to the unlock register in sequence
    2. (for example, 0x45670123 / 0xCDEF89AB).
    3. 2. Wait until ready: Poll the busy flag in the status register.
    4. 3. Configure protection: Write the option-byte fields for RDP, WRP, SEC, etc.
    5. 4. Commit the changes: Set the option-byte update start bit.
    6. 5. Wait for completion: Poll until the busy flag clears.
    7. 6. If required, reset or power-cycle the device to activate the configuration.
    8. 7. Lock the option-byte interface again.

    Disabling read protection commonly triggers a device-wide erase. This is a hardware security measure intended to prevent someone from removing protection and then extracting the firmware.

    The script and programming workflow should therefore clearly identify protection removal as a destructive operation and require confirmation before batch execution.

    2.2 A Typical Lua Script Structure

    A device configuration script for a Lua-capable programming tool might have the following structure. The register identifiers, helper functions, and protection values shown here are illustrative and must match the target device and tool.

    1. -- Device resource configuration
    2. function config_cpu(void)
    3. CHIP_TYPE = "SWD" -- Debug interface type
    4. AlgoFile_FLASH = "device.FLM" -- Internal Flash algorithm file
    5. FLASH_ADDRESS = 0x08000000 -- Flash base address
    6. FLASH_SIZE = 512 * 1024 -- Override the algorithm's capacity setting
    7. RAM_ADDRESS = 0x20000000 -- RAM base address
    8. end
    9. -- Enable protection
    10. function protect_enable(void)
    11. unlock_option_bytes()
    12. write_option_byte(RDP_REG, 0xAA) -- Write the protection level
    13. set_option_update_start()
    14. wait_option_ready()
    15. lock_option_bytes()
    16. end
    17. -- Disable protection
    18. function protect_disable(void)
    19. unlock_option_bytes()
    20. write_option_byte(RDP_REG, 0xA5) -- Restore the unprotected state
    21. set_option_update_start()
    22. wait_option_ready()
    23. system_reset()
    24. end

    Once integrated into the tool’s device library, these routines can be associated with graphical options such as “Enable read protection” or “Enable write protection.” The tool can then execute the selected protection routine automatically after firmware programming, without manual intervention.

    3. Practical Engineering Considerations

    3.1 Verify That Protection Actually Took Effect

    Successful script execution does not necessarily mean that protection is active.

    A reliable workflow reads back the option bytes after configuration and compares them with the expected values. It also attempts to read the Flash base address through the debug interface. Depending on the device, active read protection may cause an access error or return zero-filled data.

    This write–read–verify loop helps detect configuration failures before a board leaves the programming station. The expected readback behavior must be interpreted according to the target MCU, rather than treating any particular response as universal.

    3.2 Keep Standalone Behavior Consistent

    Standalone programmers have limited resources. Scripts should avoid dependencies on PC-side functionality or host filesystem paths.

    A common approach is to download the device configuration script into the programmer’s internal storage together with the programming project. This keeps the configuration available when the programmer operates without a PC.

    In standalone mode, LEDs or a display should clearly report the combined result: firmware programmed successfully and protection enabled. Programming success alone is not sufficient when protection is part of the production requirement.

    3.3 Manage Script Versions and Device Libraries

    Maintain separate scripts for different MCU families and use consistent naming and documentation conventions. Each script should identify its filename, version, date, and supported Flash capacity.

    This reduces the risk of selecting the wrong script during production.

    For variants within the same family, parameter overrides such as FLASH_SIZE may allow a shared base script to cover different capacities.

    3.4 Common Pitfalls

    • Wait for hardware readiness before and after option-byte writes. Issuing operations too early can cause writes to be lost.
    • Check whether paired byte and complement writes are required. Some devices reject option-byte configurations when these pairs are inconsistent.
    • Handle SEC page protection separately. Security-region protection and read/write protection are distinct configuration items and must be set according to the application’s requirements.
    • Prevent accidental read-protection removal. The resulting mass erase is irreversible, so the workflow must guard against unintended execution.

    4. Conclusion

    Missing option-byte programming algorithms create a gap between vendor deliverables and production requirements. Script-based protection routines provide a low-cost way to close that gap by reusing a programming tool’s debug interface and standalone execution support.

    A compact configuration script can integrate the complete sequence: download firmware, configure protection, and verify that protection is active.

    For teams that regularly switch MCU platforms while maintaining production efficiency and firmware security, custom protection routines backed by scripting support are a practical workflow to standardize.