Keep the prototype code that is tested, bounded and portable: sensor drivers that read the right registers, calibration math, message formats and the hardware quirks someone already found the hard way. Replace whatever blocks production, however well it works on the bench: credentials compiled into the image, blocking loops with no watchdog, missing error handling, no update path, no secure boot or flash encryption, no manufacturing mode and a build nobody can repeat. Fix them in this order: repeatable build, flash layout and update path, structure and error handling, credentials, security features, factory builds, then the freeze.
Expect to give both answers at once. The parts that touch the physical world are worth keeping. The parts that decide how the device boots, updates, stores secrets and gets built in a factory are rarely worth keeping as they are, because demo code had no reason to solve those problems.
For ESP32 teams the move can be a migration rather than a rewrite. Espressif’s Arduino core runs on ESP-IDF, Espressif’s own development framework, so you can move one module at a time instead of starting over. Fumbar is a Denver firm that writes embedded firmware for hardware startups and builds the over-the-air update path that keeps it improving after devices ship; the test below is the one we apply in a firmware review.
Keep, change or rewrite: a three-question test
Ask three questions of each module, not of the code base as a whole: is it tested, is it bounded, and is it portable. Count “partly” as no. Three yeses mean keep it, one or two mean change it behind a clean interface, and none mean rewrite it.
- Tested. Is there evidence the module works across the conditions the product will see: temperature, low battery, a sensor that does not answer, a network that drops? A demo that worked on the bench for a week is evidence for one condition.
- Bounded. Does the module own one job, behind a small interface, without reaching into global variables or blocking the processor while it waits?
- Portable. Will it survive the move to production hardware and the production framework, or does it depend on a development board’s pin map, an Arduino-only call, or the prototype’s timing?
One override sits above the test. Anything on the list of production blockers in the next chapters has to change even if it passes all three questions. A Wi-Fi connection routine can be tested, bounded and portable and still be unshippable, because the network password is compiled into it.
| Module | Tested | Bounded | Portable | Verdict | What to do |
|---|---|---|---|---|---|
| Calibration math | Yes | Yes | Yes | Keep | Move into its own file and add host-side unit tests |
| Sensor driver (register reads) | Partly | Yes | Partly | Change | Wrap behind an interface; add timeouts and error returns |
| Message format to the cloud | Yes | Yes | Yes | Keep | Add a version field before devices ship |
| Wi-Fi connect from example code | Partly | Yes | No | Rewrite (blocker) | Replace compiled-in credentials with provisioning |
| Main loop with delays | No | No | No | Rewrite | Event-driven state machine with a watchdog |
| Partition layout with no update slots | No | Yes | No | Rewrite (blocker) | Two application slots, sized with growth room |
| Serial print logging | Partly | No | Partly | Change | Log levels, and a quiet setting for shipping builds |
Run the test with the person who wrote the prototype in the room. They know which parts were tested against reality and which parts merely compiled, and that knowledge is not in the code.
What is worth keeping from a prototype
The most valuable things in a prototype are the facts it encodes about your hardware and your product. Keep those even when you replace the code around them.
Hardware facts
The register sequence that wakes your sensor, the delay the datasheet forgot to mention, the pin that needs a pull-up the schematic does not show: these took real time to find. Copy them into the production driver with a comment saying where each came from. If a value is undocumented, write that down too, so nobody “fixes” it later.
Calibration and signal math
Conversion formulas, filters and calibration tables are usually plain arithmetic with no hardware dependencies. That makes them the easiest code to keep and the easiest to test on a laptop. Pull them into their own files, then write unit tests that feed in recorded raw readings and check the outputs against what the prototype produced.
Formats and protocols
The layout of the messages your device sends, and what the cloud or the phone app expects, is a contract with other teams. Keep it, but add a version field before the first unit ships, because a fleet in the field will run several firmware versions at once. Write the units and the timestamp format into the same document, so the cloud team never has to guess what a raw number means.
Measurements and test notes
Every number taken on the prototype is worth keeping with its conditions: sleep current, time awake per reading, radio range, how long a battery lasted on the bench. They become the baseline the production firmware must meet or beat, and they show quickly when a change makes things worse. Record the board revision, firmware commit, supply voltage and instrument next to each number, or it cannot be compared later.
The prototype as a reference
Even a prototype you replace completely stays useful. Keep a few boards running the demo firmware as a reference: when the production firmware reads 3% lower moisture than the demo did, you want to know which one is right. Tag the prototype’s last commit, so the comparison is repeatable.
The production blockers: what must change, however good the code is
Seven gaps block production no matter how clean the rest of the code is: compiled-in credentials, blocking loops with no watchdog, missing error handling, no update path, no secure boot or flash encryption, no manufacturing mode, and a build nobody can repeat. Each is normal in a demo and expensive in a fleet.
Credentials and keys compiled into the image
Prototype code that compiles the Wi-Fi password, the cloud certificate or a private key into the firmware image cannot ship as it is. Espressif’s ESP-Jumpstart guide names the problem directly in its manufacturing chapter: “we have embedded the device certificate within the firmware itself. This is fine when we are developing with a single device, but what do we do when we have to create hundreds of thousands of such devices?” Its answer is a separate factory data partition, written per device on the line.
Network credentials belong to the user, not the firmware. ESP-Jumpstart’s reference product lets an end user “configure their home Wi-Fi network through phone applications (iOS/Android)”, and the same idea applies to any radio: the device starts unconfigured, and a provisioning step run by the user or the installer supplies the network details.
Vendor examples are built for demonstrations. ESP-IDF’s common connection component takes the Wi-Fi SSID and password as build configuration and says it “should be used mainly in examples of ESP-IDF”. Bootloader samples work the same way: MCUboot ships a development signing key, and its imgtool documentation warns that because “this private key is widely distributed, it should never be used for production.”
Rules now reach this far. In the UK, the PSTI security requirements, in force since April 29, 2024 for consumer connectable products, require passwords to be “unique per product” or “defined by the user of the product”. In the EU, Cyber Resilience Act Annex I requires products in scope to ship “with a secure by default configuration” once its main obligations apply on December 11, 2027. This is not legal advice; check which rules apply to your product.
Blocking loops and no watchdog
A prototype’s main loop may read a sensor, wait with a delay call, send data and wait again. That works until something hangs: an I2C bus that never answers, a network call that never returns. Then the device sits frozen until someone pulls the battery.
Production firmware needs two things. The first is structure: an event-driven state machine, or tasks that block on events rather than on fixed delays, so the processor can sleep and respond. The second is a watchdog that resets the device if the main work stops. ESP-IDF’s watchdog documentation says its task watchdog detects “tasks running without yielding for too long”, which “can be an indicator of poorly written code that spinloops on a peripheral, or a task that is stuck in an infinite loop.”
Set the timeout from measurements: the longest legitimate operation, such as a flash sector erase or a network attach, plus a margin. Feed the watchdog only from the healthy path of the main work, never from a timer interrupt, or it will keep a hung device alive. Log the reset reason at every boot, so a field unit that keeps resetting shows up in the data.
Error handling that assumes success
Demo code checks the happy path. Production code has to decide what happens when the sensor returns garbage, the flash write fails, the battery browns out mid-transmission or the server certificate does not match. Every external call needs a timeout, a checked return value and a decision: retry, degrade, report or reset.
Secure connections deserve a specific check. ESP-Jumpstart’s security chapter notes that if a CA certificate is not supplied, “the server validation check is skipped”, and that “It is strongly recommended that for all your TLS connections you specify the trusted CA certificate”. ESP-IDF’s security overview adds that “Disabling of HTTPS and similar security-critical configurations should be avoided.”
No update path
A prototype may not be updatable at all, because its flash holds one application image and nothing else. The Arduino core’s partition table tutorial explains that “The OTA feature requires at least two ota_x partition”, and it lists a “Huge APP (3 MB No OTA/1 MB SPIFFS)” scheme for sketches that outgrow the default. A prototype that switched to that scheme to fit has traded away its update path.
The partition layout, the bootloader and the key it trusts are set in the first units you ship and are hard or risky to change afterward. Decide them before the first production run, and check the arithmetic with the flash budget calculator, which sizes two image slots with room for growth.
No secure boot or flash encryption
Secure boot makes the chip refuse firmware not signed with your key; flash encryption encrypts the contents of off-chip flash so they cannot be read out in plain form. Both are usually off during development, and turning them on is not a menu setting: on the ESP32, the enablement workflow burns one-time eFuses.
ESP-IDF’s security overview says “It is highly recommended that Secure Boot be enabled on all production devices”, recommends “Release Mode for the production use-cases” for flash encryption, and recommends “a unique flash encryption key per device”. Its enablement workflows add an order (flash encryption first, then Secure Boot v2) and a warning that power failures during the process “may cause permanent boot-up failures.” One prototype habit collides with this directly: the partition tutorial notes that “The SPIFFS do not support flash encryption”, so data stored in a SPIFFS partition needs a new home.
No manufacturing mode
A factory needs things a demo never does: a way to write per-device data, a test that checks every part a customer depends on in seconds, a record of what was programmed into which serial number, and a final step that locks the debug port. None of this exists in prototype code. It is a separate build, covered in the chapter on the four builds below, and our manufacturing firmware page describes the station procedure.
A build nobody can repeat
If the prototype builds only on one laptop, with whatever library versions were current when it was set up, you cannot reproduce a shipped image or fix one safely. PlatformIO’s platform option documentation says an unpinned platform does not ensure “builds are repeatable” and states, “We highly recommend pinning the platform to a version.” The Arduino CLI supports “reproducible builds through the use of build profiles” in a sketch project file that pins the core and libraries. In an ESP-IDF project, pin the ESP-IDF release you build with as well.
Arduino, PlatformIO or the vendor SDK: what to build production firmware on
You can ship production firmware from an Arduino-based project, but you must take control of the pieces the Arduino workflow hides: versions, partitions, security settings and the factory flow. For ESP32 products, one practical path is to keep Arduino code while moving the project onto ESP-IDF, then replace Arduino-specific modules where they get in the way.
How the Arduino core relates to ESP-IDF
Espressif maintains the Arduino core for ESP32 on top of ESP-IDF, and each release on the project’s GitHub releases page names the ESP-IDF version it is built on. The component guide describes a middle path: “You can use the Arduino framework as an ESP-IDF component,” which “allows you to use the Arduino framework in your ESP-IDF projects with the full flexibility of the ESP-IDF.” It calls this “recommended for advanced users” and notes the component requires the FreeRTOS tick rate set to 1000 Hz.
That middle path can be the cheapest move. Your sketch keeps running, while partition tables, security settings and the bootloader come under ESP-IDF’s configuration, where they are visible and reviewable.
A migration path for an ESP32 Arduino sketch
The steps below move a working sketch onto ESP-IDF without a rewrite. Each step leaves you with firmware that still runs, so you can stop and test between them.
- Pin what you have. Record the exact core and library versions in an Arduino CLI build profile or a pinned PlatformIO platform, build it in CI, and tag the commit.
- Wrap it in an ESP-IDF project. Add the Arduino component with
idf.py add-dependency "espressif/arduino-esp32^4.0.0"(adjust to your core version), set the FreeRTOS tick rate to 1000 Hz, and keep yoursetup()andloop()as they are. Check the release notes for the ESP-IDF version that core release expects. - Write your own partition table. Include NVS, the OTA data partition, two OTA application slots sized with room to grow, a read-only factory data partition, and storage in a format that supports flash encryption.
- Turn on application rollback. With ESP-IDF’s
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLEset, a newly installed image runs its own checks on first boot and callsesp_ota_mark_app_valid_cancel_rollback()when they pass. According to the ESP-IDF OTA documentation, if a reset occurs before the image confirms itself, “the application is rolled back.” - Move per-device data to the factory partition. ESP-Jumpstart generates that partition per device from a CSV file with ESP-IDF’s
nvs_partition_gen.pyand writes it at the factory. - Replace modules by verdict. Work through the Figure 1 list, starting with the modules the production blockers force you to touch. Arduino calls that cause no harm can stay.
- Enable security features last, on a bench unit first. Follow the vendor’s order, use development mode while you test recovery, and switch to release mode only for production units.
If you build with PlatformIO, keep its platform version pinned through every step.
Versions and support periods
ESP-IDF’s versions page gives the rule for choosing: “For production purposes, use the current stable version,” while the master branch is for “prototyping, experimentation or for developing new ESP-IDF features.” Each major and minor release “is supported for 30 months after the initial stable release date”, split into a 12-month service period and an 18-month maintenance period. The same page asks you to check that the release is compatible with “the chip revision you are going to produce with.”
Thirty months is shorter than the life of many connected products, and shorter than the five-year minimum support period the Cyber Resilience Act sets for products in its scope. Plan at least one framework upgrade into the support budget, and make it routine by pinning versions and testing upgrades in CI.
Licenses
Production firmware ships the licenses of everything linked into it. The Arduino core for ESP32 is distributed under the GNU Lesser General Public License 2.1, according to the repository’s license file, while ESP-IDF uses the Apache License 2.0. Libraries pulled in from a library manager carry their own terms. List every component with its license before the first production run, and read the obligations of each, or ask counsel.
Other chips and frameworks
The same logic applies to vendor example code on other chips: keep the hardware facts, replace the demo scaffolding, and adopt the vendor’s or the RTOS’s production features for boot, update and storage. Go through every configuration file inherited from an example and give each setting a deliberate production value: log levels, debug interfaces, pin assignments made for a development kit’s buttons and lights, and power management options. Whether to stay on the vendor SDK, move to Zephyr or FreeRTOS, or stay bare metal is its own decision; our comparison of Zephyr, FreeRTOS and bare metal walks through it.
The order of work before the first production run
Order matters because some steps make others cheaper and a few cannot be undone. Start with what lets you work safely, settle the decisions that are fixed at the factory, then lock things down last.
- Make the build repeatable. Put the code in a repository your company owns, pin framework and library versions, and build in CI from a fresh checkout. Every later step depends on knowing exactly what you built.
- Write down what the prototype does. Turn its behavior into requirements with a way to verify each one. The firmware requirements worksheet is a format for this. Record reference outputs from the prototype boards.
- Fix the flash layout and the update path. Choose the bootloader, size two image slots, and get a signed image to install and roll back on a bench board. Everything else will be stored inside this layout, so it comes first.
- Restructure the main loop. Move to a state machine or event-driven tasks, add the watchdog, and add timeouts and error handling to every external call. Keep the tested drivers and math from the previous chapters.
- Move credentials out of the image. Per-device data goes into a factory data partition or a secure element; network credentials come from user provisioning. Remove every development key from production configurations.
- Turn on security features on a bench unit. Enable secure boot and flash encryption in the vendor’s documented order, in development mode first where the chip offers one, and test recovery before you try release mode.
- Build the factory flow. Write the manufacturing test firmware, the provisioning step and the factory record, and time them on real boards.
- Freeze the builds. Freeze the manufacturing test build before the pilot production run, then freeze and sign the shipping build.
Steps 3 and 6 are the ones that cannot easily be redone once units ship, so they deserve review by a second engineer.
What goes wrong when the order slips
- Security before layout. Burning secure boot and flash encryption fuses on boards whose partition table is still changing means every layout change becomes a re-flash procedure under encryption, or a scrapped board.
- Features before structure. Adding features to a delay-driven loop and restructuring later means writing every feature twice. The state machine is cheaper while the feature list is short.
- Factory flow last. A manufacturing test build written in the final weeks gets changed during the pilot run, and the factory validates against a moving target.
- Freeze before tests. A shipping build frozen before the update and fault tests pass will need an update in the field on day one, through an update path nobody has exercised.
The production readiness checklist maps these steps to EVT, DVT and PVT gates.
The four builds a product needs, and when each is frozen
A product that ships needs at least four firmware builds from the same code base: a development build, a manufacturing test build, an RF certification test build and the shipping build. They differ in what they enable, who runs them and when they stop changing.
| Build | Who runs it | What it enables | When it is frozen |
|---|---|---|---|
| Development | Your engineers | Verbose logs, debug access, development keys | Never; it follows the main branch |
| Manufacturing test | The factory, on a test fixture | Commands that exercise every part, per-device provisioning, pass or fail output | Before the pilot production run (PVT) |
| RF certification test | The radio test lab | Test modes the lab asks for, such as continuous transmit on a chosen channel | Before the lab session; ask the lab before changing it |
| Shipping | Customers | Production key, locked debug port, quiet logs, update agent | At the end of PVT, then signed and recorded |
Why the manufacturing build freezes first
The factory validates its fixture, its timing and its pass or fail limits against a specific manufacturing test build. If that build changes during PVT, the factory has to validate again, and units built in between were tested against a different standard. Freeze it before the pilot production run, put its version in the factory procedure, and change it afterward only through a written change request.
Why the shipping build freezes last
The shipping build can keep improving through PVT, because it can be updated in the field once the update path works. Freeze it when PVT ends: tag it, sign it with the production key, record its version and hash, and program that exact image at the factory. The first over-the-air update can then follow soon after launch.
The RF test build
Radio test labs need firmware that holds the radio in specific test modes on command, which a shipping build should never expose. Build it from the same code base so its radio settings match the product. Our article on RF certification test firmware covers what labs ask for.
How to tell the production firmware is ready
Production firmware is ready when it passes tests that try to break it, on production hardware, in the shipping configuration. A demo that runs is not evidence; a list of failures you caused on purpose, with the device recovering from each, is.
Break the update path on purpose
- Cut power during the download, during the swap and during the first boot of the new image. Every unit should come back on a working image.
- Offer an image signed with the wrong key, an image for the wrong hardware revision, and an older image. Each should be refused.
- Install an image that fails its own first-boot checks. The device should return to the previous version by itself.
- Update from the oldest version that will be in the field, not only from the last one.
Break the world around the device
- Disconnect each sensor, block the network for a day, present a server certificate that does not match, and fill the storage. Each should produce a defined behavior and a log entry, not a hang.
- Let the supply droop during a flash write and during a radio transmission, then check the stored data.
- Run a dozen boards for several days and count watchdog resets. Every reset needs an explanation.
Measure the shipping build
Measure sleep current and time awake on the shipping build, with debug features off, and compare them with the prototype baseline. Debug options left on can change power figures, so the shipping configuration is the only one that counts.
Rehearse the factory
Run the manufacturing test build and provisioning on real boards, check that every unit’s identity is unique and recorded, and try to connect a debugger to a locked unit. The production readiness checklist adds one more gate worth keeping: field trial units updated over the air at least twice before production.
When a rewrite is the right call
Rewrite when the prototype’s structure fights every production requirement, when the hardware or framework is changing anyway, or when nobody can explain how the code works. Even then, rewrite module by module behind tests rather than all at once.
Signs a rewrite is cheaper
- One loop, global state everywhere. If every function reads and writes shared globals and timing depends on delay calls, adding a watchdog, sleep and error handling means touching every line.
- A platform change is coming. Moving from a development-kit chip to a different production chip, or from a demo framework to an RTOS with a maintained bootloader, means much of the code changes anyway.
- Security features cannot be enabled in the current setup. For example, the storage format does not support encryption, or the build has no way to sign images.
- A license blocks shipping. A library whose terms you cannot meet in a closed product has to be replaced, along with everything built tightly around it.
- Nobody understands it. If the author has left and the code has no tests, its behavior is unknown, and “keeping” it means keeping unknown behavior.
What a rewrite costs that is easy to forget
A rewrite repeats work the prototype already paid for: sensor accuracy has to be validated again, power has to be measured again, and the hardware quirks have to be rediscovered unless someone wrote them down. If radio settings change after a lab has tested the product, ask the lab whether its results still apply. Count these costs before choosing a rewrite on the grounds that the old code is ugly.
How to rewrite without losing what worked
Replace one module at a time, starting with the ones the production blockers force you to touch. Before replacing a module, record its outputs for a set of inputs, then make the new module produce the same outputs. Keep the prototype boards running as a reference until the new firmware matches them on every requirement you wrote down.
A worked example: the Loamwick LW-1 demo firmware
The site’s fictional example shows the test applied to a real-sounding case. The decision was neither keep everything nor throw everything away.
Example (fictional). Loamwick, a two-founder Denver startup, sends its Rev C schematics, a few boards and the demo firmware its contract hardware engineer wrote to a week-1 firmware review. The demo reads both sensors and talks Bluetooth LE to the gateway. It has no bootloader, no image signing and no way to roll back, and one image fills the flash.
The review keeps the sensor read sequences and the gateway message format as reference material, and the demo boards stay on the bench to compare readings. Everything that decides how the probe boots, updates and is built changes: the application is rebuilt on Zephyr, with MCUboot (48 KB), two 448 KB image slots, 32 KB of settings and 48 KB of logs in the probe’s 1 MB of internal flash. The 412 KB application fills 92.8% of its slot, so the team plans to move the second slot to external flash on Rev E.
The requirements are written down with a test for each, such as reading moisture and temperature every 5 minutes, refusing images not signed with the production key, and finishing the factory test in under 60 seconds per probe. The field trial of 40 probes starts in week 8 on v1.0.0. The full walkthrough is on the example project page.
Two choices in the example are worth copying. The reference boards made the new firmware’s readings checkable against the old. And the flash layout was settled before any application code was written, because the update path depended on it.
The flash numbers carry a third lesson. A 412 KB image in a 448 KB slot leaves little room for the features a product gains after launch, and the review found that on the bench, before any probe was in the ground, rather than after the first field update failed to fit. Measuring image size against slot size on the prototype costs an afternoon; finding the limit with probes in the ground costs a hardware revision.
Who should do the work
Whoever does it needs to cover bootloaders, security features and factory flows as well as application code, which is more than a demo ever asked of its author. Some teams hire for it; others bring in help for the production-blocking pieces and keep the application work in-house.
Whichever you choose, ask the person doing the work to show you three things before the first production run: a signed image refused and accepted on a bench unit, a power-cut test during an update with the unit recovering, and a manufacturing test run on real boards with the results recorded. Those three demonstrations cover most of what separates a demo from a product.
If you are weighing those routes, our article on whether to outsource firmware or hire compares them, including what you must own whichever you choose. Fumbar’s firmware development page describes how we write production firmware on bare metal, Zephyr and FreeRTOS, and the engagements page lists the engagement types, from a firmware review to a product firmware build.
What to do before your next board spin
The cheapest moment to settle the production blockers is before the next board revision, while the flash layout and the security fuses are still unwritten.
- Run the three-question test on every module, with the prototype’s author.
- Tag the prototype’s last commit and keep two boards running it as a reference.
- Pin every framework and library version, and build in CI from a fresh checkout.
- Decide the bootloader, the two-slot flash layout and where the production signing key will live.
- List every credential and key compiled into the image, and decide where each will come from instead.
- Enable secure boot and flash encryption on one bench unit, in the vendor’s order, and test recovery.
- Write down the four builds and the date each one freezes.
If you want an outside read before the next spin, request a firmware review: we read the schematics, the current code, the flash layout and the update plan, and you receive a written plan with the risks and the order of work.
