Internal Flash Programming and In-Application Update
What You'll Learn
- 1Program and erase flash while the CPU executes from it
- 2Explain wait states and clock versus flash timing
- 3Design a bootloader with verification and rollback
- 4Apply write and read protection correctly
Flash memory is the permanent home of firmware, and writing it is the most dangerous routine in a microcontroller because it is slow, non reversible within a page, and executed from the same memory you are changing. Program operations work at word or halfword granularity, erase works per sector or page, and every access must respect the wait state configuration for the current clock. An in-application update adds power loss recovery, image verification, and a rollback strategy on top of the raw programming operations.
Wait States, Erase, and Program Timing
Flash access time is fixed by silicon, so as the core clock rises the controller inserts wait states to keep up. Setting too few wait states produces faults only at full speed or at temperature, which is a classic bring-up bug. Programming requires unlocked keys, a write of the aligned word or halfword with the correct program parallelism, and a busy flag check until completion.
Erase sets a whole sector to the erased state and takes milliseconds, which means a CPU executing from that same flash stalls or must be moved to RAM. Most parts stall the bus during erase, and the firmware must account for that when timing sensitive interrupts are pending. Erase before program is mandatory because flash bits can only move toward the erased state.
Locks, Protection, and Security
Flash control registers are locked after reset so accidental writes cannot corrupt firmware, and unlocking requires a specific key sequence. Write protection can freeze individual sectors so a bug cannot overwrite the bootloader, and read out protection prevents the debug interface from reading flash contents. Option bytes hold these settings and often survive a normal reset but not a full erase.
Balancing protection against serviceability is a real product decision: full read protection blocks your own factory reprogramming unless a mass erase is performed, and mass erase wipes the firmware. Choose protection levels with the service and manufacturing flow in view, not as an afterthought.
In-Application Update and Bootloader
A robust update splits the device into a small immutable bootloader and an application image. The bootloader checks a new image for a valid vector table, a cyclic redundancy check or a cryptographic signature, and only then marks it valid and swaps the boot address. Interrupt vector relocation through the vector table offset register lets the application run at a different flash address without recompiling.
Power loss during programming is the case that decides whether an update scheme is production grade. The safe pattern writes the image to a staging area, verifies it completely, then writes a validity marker last, with the bootloader falling back to the previous image when the marker is missing. Dual bank parts make this cheaper by allowing one bank to run while the other is written.
Flash Programming Sequence
| Step | Action | Reason |
|---|---|---|
| 1 | Configure wait states for the clock | Match access time to core frequency |
| 2 | Unlock the flash control register | Locked by default after reset |
| 3 | Erase the target sector | Flash can only move to the erased state |
| 4 | Program aligned words | Parallelism and alignment are hardware rules |
| 5 | Verify by reading back | Confirm the data and detect faults |
| 6 | Relock and set protection | Prevent accidental later corruption |
Real-World Examples
- Erase and write a page â Unlock, start sector erase, wait for busy, then program words with read back verification.
- Run code from RAM â Copy a timing critical routine to RAM and map it so interrupts still vector correctly.
- Add a bootloader â Verify the application vector table and checksum, then set the vector table offset and jump to the application reset handler.
- Protect against power loss â Write the image first, verify it, and set the valid flag only at the very end so a failed update falls back safely.
â ī¸Erase Is Slow and Destructive
Common Mistakes
Running at full clock with too few wait states
Fix: Flash reads fail only under load or temperature, which hides the fault during lab testing.
Updating without verifying the image
Fix: A corrupted download bricks the device on the next reset unless the bootloader rejects it.
Erasing from an interrupt context
Fix: Long erase times stall the bus and break timing guarantees, so keep flash work in the main context.
Key Takeaways
- Flash timing requires wait states matched to the core clock.
- Erase is per sector, program is per word or halfword, and bits only go one way.
- Locks, write protection, and read protection have real service trade-offs.
- A production update needs verification, an atomic validity marker, and rollback.
Frequently Asked Questions
Why does my code freeze when writing flash?
The CPU stalls while erasing or programming the same bank, so move timing critical work to RAM or defer it.
Can you write flash while executing from it?
On single bank parts the bus stalls during the operation; on dual bank parts you can run from the other bank.
What makes an update scheme safe?
Staging, full verification, a validity marker written last, and a bootloader that can fall back to the previous image.
Interview Questions
Q1: Describe a power safe firmware update.
Download to staging, verify length and checksum or signature, mark the image valid as the final step, then let the bootloader select it only when valid, otherwise boot the previous image.
Q2: Why do wait states matter for reliability?
Flash access time is fixed, so running the core faster than the access time allows produces fetch errors that appear only at speed or at temperature.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions