🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Internal Flash Programming and In-Application Update

Microcontrollers & ARMRTOS and DebugđŸŸĸ Free Lesson

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

StepActionReason
1Configure wait states for the clockMatch access time to core frequency
2Unlock the flash control registerLocked by default after reset
3Erase the target sectorFlash can only move to the erased state
4Program aligned wordsParallelism and alignment are hardware rules
5Verify by reading backConfirm the data and detect faults
6Relock and set protectionPrevent 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

A sector erase takes milliseconds and clears everything in it, so never start one with the bootloader or critical data inside without a recovery path.

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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Microcontrollers & ARM Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement