ProjekinAja. Embedded Systems Stage 3 · Firmware Lesson 3.2
● Stage 3 · Lesson 3.2

Toolchain and Build: From Source to Flash

The linker decides where your program lives. Understand it and half of the mysterious crashes become geography.

⏱ ~24 min read 🔧 ESP-IDF 5.x 📍 Beacon partition table fixed

🎯 By the end you'll understand

What the compiler, assembler, and linker each actually do to your C, and why the linker is the one that matters on a microcontroller. The four sections every program is made of — .text, .rodata, .data, .bss — and exactly where each lands on the ESP32-C3. How to read the map file and idf.py size as truth instead of guessing. How ESP-IDF's CMake build, sdkconfig, and the partition table combine to decide whether Beacon's firmware fits its OTA slot — and what happens the day it doesn't.

KEY INSIGHTYour program is a set of boxes, and the linker packs them

The build that worked on Tuesday fails on Wednesday after you add one line: ESP_LOGI(TAG, "battery %d mV, humidity %d %%"). The error says the binary no longer fits partition ota_0. Nobody added a feature. A string of forty bytes was the last straw for an image that had been 99.98 % full for a month.

That bench story is the whole lesson. A firmware image is not "the code"; it is a handful of sections — instructions, constants, initialised variables, uninitialised variables — each with a different destination in the memory map from Lesson 3.1, each with a different cost in flash and in RAM. The compiler sorts your source into those sections. The linker assigns them addresses and refuses when they do not fit. Every string literal is a resident of .rodata; every static buffer is a resident of .bss; and the partition table is the landlord that decides how big the building is. When you know which box a thing goes into, "mysterious" size and crash problems turn into a question of geography.

🔑 Hold onto this

Three artefacts tell you the truth about a build, in this order: the partition table (how much flash each thing may occupy), idf.py size (how much each section actually occupies), and the map file (which symbol is responsible). If you cannot answer "how much headroom does the app slot have right now, and what is the largest thing in .rodata", you are not managing the build — you are hoping.

HOW IT WORKSCompile, assemble, link: three programs, three jobs

Typing idf.py build runs hundreds of commands, but they are all instances of three tools from the RISC-V GCC toolchain (riscv32-esp-elf-gcc, -as, -ld), plus Espressif's post-processing.

sht40.c + main.c, lis2dh12.c… gcc -c sht40.c.obj .text .rodata .data .bss addresses = 0, relocations ld beacon.elf all objects + libs merged sections given addresses symbols + debug info + beacon.map (the truth) linker script sections.ld from *.lf fragments esptool beacon.bin segments + header + checksum flash ota_0 slot The .bin must fit the partition. The .bss section is not in the .bin at all — it costs RAM, not flash.
Source to flash. The compiler works one file at a time and knows nothing about addresses; the linker sees everything at once and knows nothing about C. The ELF is for you and the debugger; the .bin is what the bootloader reads.
1

Compile — one file, no addresses

The compiler turns sht40.c into RISC-V assembly, then the assembler turns that into an object file. Every function becomes bytes in .text; every string literal and const table becomes bytes in .rodata; every initialised global becomes bytes in .data; every zero-initialised or uninitialised global becomes a size in .bss with no bytes at all. The object file does not know where any of this will live — it records placeholders ("relocations") wherever one symbol refers to another. This is why a compile error is always local to one file and a link error never is.

2

Link — every file, real addresses

The linker takes every object file and static library, reads a linker script that says which input sections go into which output region at which address, concatenates them, resolves every placeholder to a real address, and writes the ELF. It also writes the map file. If a region overflows the script's declared size, it stops: region `dram0_0_seg' overflowed by 1240 bytes. If a symbol is referenced and never defined, it stops: undefined reference to `sht40_read'. Both are geography, not logic.

3

Post-process — from ELF to something the ROM can load

esptool.py elf2image extracts the loadable segments, prepends an image header (entry point, flash mode and frequency, chip ID), appends a checksum and a SHA-256 digest, and produces the .bin. ESP-IDF's build then checks the .bin against the partition table and prints the line you should read every single build: beacon.bin binary size 0x10a3f0 bytes. Smallest app partition is 0x1c0000 bytes. 0xb5c10 bytes (41%) free.

CORE CONCEPTSections and where they land on the ESP32-C3

Here is the table to memorise. It answers "does this cost flash or RAM, and does it survive a reset" for every line of C you will write.

SectionWhat goes thereLives in (ESP32-C3)Costs flash?Costs SRAM?Initialised by
.textFunctions (machine code)Flash, mapped at 0x4200_0000 via cache. IRAM_ATTR functions → SRAM instead.YesOnly IRAM_ATTR partsNothing — executed in place
.rodataString literals, const arrays, lookup tables, log format stringsFlash, mapped at 0x3C00_0000 via cache. DRAM_ATTR const → SRAM.YesOnly DRAM_ATTR partsNothing — read in place
.dataGlobals/statics with a non-zero initialiserSRAM (DRAM), 0x3FC8_xxxxYes (initial values)Yes (same size again)Bootloader copies values from the image
.bssGlobals/statics that are zero or uninitialised (buffers!)SRAM (DRAM)NoYesStartup code zeroes it
.rtc.data / .rtc.bssRTC_DATA_ATTR / RTC_NOINIT_ATTR variablesRTC FAST memory, 0x5000_0000Yes for .rtc.dataRTC RAM (8 KB)Once at cold boot; kept across deep sleep
heapEverything from malloc, task stacks created at runtime, BLE host buffersWhatever SRAM is left after .data + .bss + static IRAMNoYes, at runtimeAllocator, on demand

Two rows deserve a second look. .data is paid for twice — the initial values sit in flash inside the .bin and get copied into SRAM at load, so a 12 KB initialised table costs 12 KB of flash and 12 KB of RAM. If the table never changes, declare it const and it moves to .rodata, costing flash only. That single keyword is the cheapest RAM optimisation on the chip. .bss costs no flash at all, which is why a 40 KB static buffer does not move the "binary size" line by a byte and yet can push the heap below what the BLE host needs at runtime. Flash-fit and RAM-fit are separate questions with separate evidence.

sections_demo.cwhich box does each line go in?
static const char *TAG = "beacon";                  // pointer: .data (4 B); the chars "beacon": .rodata
static const uint16_t rh_lut[2048] = { 0, 3, 7, /*…*/ };  // const → .rodata, 4 KB of flash, 0 B of SRAM
static uint16_t rh_lut_rw[2048] = { 0, 3, 7, /*…*/ };     // no const → .data, 4 KB flash AND 4 KB SRAM
static uint8_t sample_ring[40 * 1024];                 // zero-init → .bss, 0 B flash, 40 KB SRAM
static int boot_count;                                 // .bss — and zero after every deep-sleep wake
RTC_DATA_ATTR static uint8_t adv_seq;                   // .rtc.data — survives deep sleep (3.1)

void IRAM_ATTR motion_isr(void *arg)                      // .iram0.text — runs even with flash cache off
{
    // ESP_LOGI here would touch a .rodata string → forbidden in an ISR (3.4)
}

void app_main(void)                                    // .text in flash, fetched through the cache
{
    ESP_LOGI(TAG, "battery %d mV, humidity %d %%", mv, rh);   // this string: ~32 B of .rodata
}

That highlighted line is the Wednesday failure from the top of the lesson. Each ESP_LOGx call contributes its format string to .rodata, plus the tag, plus the code that calls the formatter. Individually trivial; collectively, in a project with a thousand log lines, tens of kilobytes of flash that also has to fit the OTA slot. The ESP-IDF option CONFIG_LOG_MAXIMUM_LEVEL removes calls above that level at compile time, strings and all — a different thing from the runtime esp_log_level_set(), which keeps the strings and only silences them.

IN PRACTICEThe map file and idf.py size are the truth source

ESP-IDF writes build/beacon.map on every link. It is a few megabytes of text and almost nobody opens it, which is a shame, because it answers three questions no other tool can: what is the address of any symbol, how big is any function or table, and which object file dragged an unexpected library in. The friendlier front ends are worth learning first:

terminalidf.py size · size-components · size-files
$ idf.py size
Total sizes:
Used static DRAM:   31284 bytes ( 296908 remain, 9.5% used)
      .data size:   12240 bytes
      .bss  size:   19044 bytes
Used static IRAM:   62732 bytes (  68340 remain, 47.9% used)
      .text size:   61705 bytes
   .vectors size:    1027 bytes
Used Flash size :  831510 bytes
      .text     :  627962 bytes
      .rodata   :  203292 bytes
Total image size:  907505 bytes (.bin may be padded larger)

$ idf.py size-components        # which component owns the bytes: bt, esp_wifi, lwip, your app…
$ idf.py size-files             # which object file — the one that says sht40.c.obj is 40 KB is a bug report

The numbers above are illustrative of a NimBLE-plus-drivers build, not a measurement of Beacon. Read the structure: Used static DRAM is .data + .bss and its "remain" is roughly the heap the BLE host and your tasks will fight over. Used static IRAM is code that had to be in SRAM (ISRs, flash-write-safe paths, and whatever IDF options put there); its remain matters because IRAM and DRAM are the same physical SRAM on the C3 and every byte of IRAM code is a byte the heap does not get. Used Flash size is the number to compare against the app partition, and .rodata is the part that grows with logging.

When a component number surprises you, open the map. Search for the symbol name; the map lists it under its output section with an address and a size, followed by the object file it came from. Search for .rodata entries above a few kilobytes and you will find the tables. Search for a library you did not expect — libesp_http_client in a firmware that should not do HTTP — and the map tells you which of your objects referenced a symbol in it. That is how "why is my image 300 KB bigger than yesterday" gets answered in five minutes instead of an afternoon.

💡 Read the size line on every build, and write it down at milestones

The build prints the app's free-space percentage every time. Note it in the commit message at each Beacon milestone. When Stage 4 adds Wi-Fi and the OTA HTTP client — several hundred kilobytes of .text — you want to already know that firmware v0 sits at 41 % free in a 1792 KB slot, not discover at the end of 4.9 that the slot was sized for a demo.

SEE ITBuild pipeline visualizer: watch the sections grow until one addition breaks the build

Start from Beacon's firmware v0 baseline and add features in the order the course will add them. Each addition grows specific sections. Pick a partition table and watch the image against its app slot and the static RAM against SRAM. The build log names the exact addition that tipped the image over — and the partition choice that "fixes" it by quietly giving up OTA is the trap.

⚙ Interactive · ESP-IDF build size visualizer

Section sizes are illustrative round numbers for an ESP32-C3 NimBLE build, not measurements. Additions are applied in the order you tick them; the log identifies the first one that no longer fits.

App image vs app partition—
Static SRAM (.data + .bss + IRAM) vs 384 KB — the remainder is heap, and Wi-Fi + TLS + BLE need ~180 KB of it—

■ .text · ■ .rodata · ■ .data · ■ .bss / IRAM

Image size
—
Slot free
—
Heap left (est.)
—
R7 (OTA + rollback)
—

Two lessons are hiding in the log. First, the addition that "breaks the build" is rarely the big one — tick Wi-Fi and the ML weights first and the build still passes; it is the MQTT client — 182 KB of flash, modest beside the 400 KB of weights already sitting there — that produces the error, and the engineer who added it gets the blame for someone else's bloat. Second, the single-factory table makes every error disappear and violates R7: a Beacon that cannot be updated in the field is a Beacon whose first firmware bug becomes a site visit to 25 units. The partition table is a requirement decision, not a build setting.

HOW IT WORKSESP-IDF's build system: CMake, components, and sdkconfig

ESP-IDF 5.x builds with CMake driving Ninja, wrapped by the idf.py front end. Three concepts are enough to be productive.

Components. A project is a tree of components — directories with a CMakeLists.txt calling idf_component_register(SRCS "sht40.c" INCLUDE_DIRS "include" REQUIRES driver). ESP-IDF itself is a few hundred components (driver, bt, esp_wifi, nvs_flash, app_update…). Only components reachable from your main through REQUIRES get built and linked — which is why the map file sometimes shows a library you never asked for: a component you did ask for required it.

sdkconfig. Every tunable in IDF is a Kconfig option, edited with idf.py menuconfig and stored in the sdkconfig file as CONFIG_xxx=y lines. Options change what gets compiled (CONFIG_BT_NIMBLE_ENABLED), how (CONFIG_COMPILER_OPTIMIZATION_SIZE), and with what limits (CONFIG_ESP_MAIN_TASK_STACK_SIZE). Commit sdkconfig.defaults to version control, never the generated sdkconfig; the defaults file is the reproducible statement of what the build is.

Targets. idf.py set-target esp32c3 selects the chip, which selects the toolchain (RISC-V vs Xtensa), the linker scripts, and the SoC headers from 3.1. Forget it and you get an ESP32 build that flashes to a C3 and prints nothing — the ROM checks the image header's chip ID and refuses, but the error scrolls past in a wall of esptool output.

sdkconfig.defaultsBeacon firmware v0 · the size-relevant lines
# Target and flash
CONFIG_IDF_TARGET="esp32c3"
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_beacon.csv"

# Size: optimise for size, cap log strings at INFO in release builds
CONFIG_COMPILER_OPTIMIZATION_SIZE=y
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
CONFIG_LOG_MAXIMUM_LEVEL_INFO=y          # DEBUG/VERBOSE calls compiled out: strings gone

# Radio: NimBLE host, no Bluedroid (smaller), Wi-Fi only for OTA (4.9)
CONFIG_BT_ENABLED=y
CONFIG_BT_NIMBLE_ENABLED=y

# OTA rollback (R7): new image must call esp_ota_mark_app_valid_cancel_rollback()
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y

# Console over the native USB Serial/JTAG (GPIO18/19), not UART0
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y

CORE CONCEPTPartition tables: carving 4 MB into things with different rules

The flash is one 4 MB address space, but its contents have different owners with different write patterns, and the partition table is the contract between them. It is a CSV compiled into a 3 KB binary and flashed at offset 0x8000 by default; the second-stage bootloader reads it first thing (3.1), and every IDF API that touches flash — NVS, OTA, SPIFFS — looks up its partition by name and type rather than by address.

Type / subtypeWhat it is forWrite patternSizing rule
data, nvsKey-value store: Wi-Fi credentials, calibration, Beacon's device ID and boot countersSmall, frequent, wear-levelled by the NVS library≥ 0x3000; 0x4000–0x6000 typical. Must be erased when its layout changes.
data, ota (otadata)Two sectors recording which OTA slot is active and its validation stateOne write per update and per rollback decisionExactly 0x2000
data, phyRF calibration dataRarely0x1000
app, factoryThe one app slot in a non-OTA design; also a "known good" fallbackWritten by the programmer onlyMust start on a 0x10000 boundary
app, ota_0 / ota_1Alternating slots: the running image and the one being downloadedOne full erase + write per updateBoth the same size, 0x10000 aligned, each ≥ the largest image you will ever ship
data, spiffs / fat / nvsFiles or logsWhatever your code doesWhatever is left — and it is never as much as you want

The arithmetic is unforgiving. Take 4 MB (0x400000). The bootloader takes the first 0x8000, the table itself and the small data partitions take up to 0x10000. Two OTA slots must be equal and each large enough for the biggest image you will ever ship including the future Wi-Fi OTA client. Whatever is left becomes storage. The tension is that a bigger app slot means a smaller log store, and the day you discover the slot is too small is the day you need OTA most — you cannot ship a firmware update that shrinks the slot, because the update itself has to fit the old slot first. Size the slots for the largest plausible image on day one and treat storage as the residual.

📖 How the bootloader uses otadata, and where rollback lives

With CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE, an update goes like this. The running app writes the new image into the other slot and marks it in otadata as ESP_OTA_IMG_NEW. On reboot the bootloader boots the new slot once and marks it PENDING_VERIFY. The new app must run its self-test (Beacon's SELF_TEST state in 3.7) and call esp_ota_mark_app_valid_cancel_rollback(). If it crashes, hangs, or fails to make that call before the next reset, the bootloader sees a pending image that was never confirmed, marks it invalid, and boots the previous slot. That is R7 satisfied by the bootloader and the partition table together; the application's only job is to be honest in its self-test.

IN PRACTICEFlashing over native USB-JTAG, and the serial monitor

The ESP32-C3 has a USB Serial/JTAG peripheral on GPIO18 (D−) and GPIO19 (D+) — no external UART bridge chip needed, which is one line off Beacon's BOM and one less thing to leak in sleep. Plug the dev kit in and the host sees a CDC serial device (/dev/ttyACM0 on Linux, /dev/cu.usbmodem… on macOS) and a JTAG interface on the same cable. esptool.py, which idf.py flash calls, uses the USB Serial/JTAG controller to pull the chip into the ROM download mode from 3.1 automatically, so you rarely need to hold the boot button — rarely, because a firmware that has crashed the USB peripheral's clock, or a board where GPIO18/19 were repurposed, takes that convenience away, and then you are back to holding GPIO9 low during reset by hand. On Beacon Rev A that button is the user button, which is the good news; the bad news is Lesson 3.3.

terminalthe four commands that matter
$ idf.py set-target esp32c3                 # once per project; picks toolchain + linker scripts
$ idf.py build                              # prints the "Smallest app partition… free" line
$ idf.py -p /dev/ttyACM0 flash monitor      # bootloader @0x0, table @0x8000, app @ota_0; then attach
$ idf.py -p /dev/ttyACM0 erase-flash        # when NVS layout or partition table changed

# the flash step, as esptool reports it:
Writing at 0x00000000... (bootloader)
Writing at 0x00008000... (partition table)
Writing at 0x0000d000... (otadata — erased so the bootloader picks ota_0)
Writing at 0x00010000... (beacon.bin → ota_0)
Hash of data verified.

The monitor is more than a terminal. Because it has the ELF, it decodes crash backtraces into file and line numbers as they scroll by, which is the difference between 0x4200a3f2 and sht40.c:88. It also recognises the ROM's boot banner, so the first thing you see after every reset is the reset reason and the strapping-pin state — read it, because "the device rebooted" and "the device brownout-reset" are different bugs. Keep the monitor output from every bench session; Lesson 3.9 turns it into evidence.

BEACONBeacon's partition table: two OTA slots and a bug log

The canon fixes the shape — two OTA app partitions with rollback — and this lesson fixes the numbers. They are sized for the largest image the course will produce: firmware v0 plus the Stage 4 Wi-Fi OTA client, with headroom for logging, in a 4 MB module.

partitions_beacon.csv4 MB · two OTA slots · fixed for Stages 3–6
# Name,     Type, SubType,  Offset,    Size,      Notes
nvs,        data, nvs,      0x9000,    0x4000,    # 16 KB: device id, boot counter, calibration
otadata,    data, ota,      0xD000,    0x2000,    # which slot, and its verify state
phy_init,   data, phy,      0xF000,    0x1000,    # RF calibration
ota_0,      app,  ota_0,    0x10000,   0x1C0000,  # 1792 KB slot A
ota_1,      app,  ota_1,    0x1D0000,  0x1C0000,  # 1792 KB slot B
buglog,     data, nvs,      0x390000,  0x70000,   # 448 KB: reset reasons, self-test results (3.9, 6.7)
# 0x390000 + 0x70000 = 0x400000 = 4 MB. Both app slots start on 0x10000 boundaries.

Why these numbers. A NimBLE-only firmware v0 is on the order of 900 KB; adding Wi-Fi station mode, TLS, and the HTTPS OTA client in 4.9 adds several hundred kilobytes of .text. A 1792 KB slot leaves comfortable room for both plus the logging Stage 6 will want. Two slots of that size consume 3584 KB, leaving 448 KB for a second NVS partition used as a ring of postmortem records — reset reasons, the last self-test verdict, the last measured battery voltage — that survives an OTA because it is a separate partition from the app. There is no factory partition: with otadata erased, the bootloader boots ota_0, and the rollback rule protects every later update. Anyone who wants a factory slot has to take it out of the bug log, and that is a design review conversation, not a CSV edit.

🔑 Beacon firmware v0: what this lesson fixes

(1) The partition table above is the one every later lesson assumes; 4.9's OTA writes into whichever slot is not running and relies on the rollback rule. (2) Release builds use -Os with CONFIG_LOG_MAXIMUM_LEVEL_INFO; debug builds may raise it, and the size line is checked before either is committed. (3) Every milestone commit message records the "free" percentage from the build. (4) The console is the native USB Serial/JTAG, so the pilot boards need no UART bridge and GPIO18/19 are reserved for it on the schematic.

WEAKNESSWhere this bites

✗ Sizing the OTA slot for today's image

A slot that fits firmware v0 with 10 % spare is a slot that cannot receive the Wi-Fi OTA build in Stage 4, and by then the table is already in the field on 25 units. You cannot grow the slot with an update, because the update must fit the old slot to be installed at all. Nor can you repartition remotely without a bootloader that understands two tables — which stock ESP-IDF does not. Size for the largest image you can imagine shipping, then add margin for the logging you will add while debugging it. If that leaves too little storage, buy the 8 MB module variant now, not later.

✗ Trusting the binary size as the whole story

.bss is invisible in the binary. A firmware can be at 40 % flash free and still fail at runtime because a 100 KB static buffer left the heap too small for the BLE host's allocations — esp_nimble_hci_init returns ESP_ERR_NO_MEM, or worse, a later malloc returns NULL in a path nobody checks. The flash question and the RAM question need separate evidence: the size line for one, idf.py size's DRAM row plus a runtime esp_get_free_heap_size() log at boot for the other.

✗ Changing the partition table without erasing

The table is data at 0x8000; the partitions are just regions. Move the NVS partition, flash the new table, and the NVS library now reads the bytes of whatever used to live at the new offset — typically the tail of an app image — and reports a corrupt store, or silently "finds" nonsense values for your keys. The same applies to an otadata partition that moved: the bootloader may boot a slot that contains half of an old image. After any table change: idf.py erase-flash, then flash everything. On pilot units in the field, a table change is a recall.

KEY INSIGHTHow this connects

  • Inside a Microcontroller (3.1) — the memory map is the destination; this lesson is the delivery. Each section lands in one of 3.1's regions, and IRAM_ATTR / RTC_DATA_ATTR are the linker being told which one.
  • GPIO, Timers, and PWM (3.3) — next: the strapping-pin download mode that idf.py flash relies on, and the GPIO9 button that shares it.
  • Debugging Firmware (3.9) — the ELF and map file built here are what OpenOCD, GDB, and the monitor's backtrace decoder consume; the bug-log partition defined here is where postmortem evidence lands.
  • OTA (4.9) — writes into the other slot of the table fixed here and depends on the rollback flag in sdkconfig.defaults.

The build system is not plumbing you configure once and forget. Every later lesson adds bytes to a section, and every byte has a destination with a limit. Keep the size line in view, keep the map file within reach, and the day the build fails you will already know which box overflowed and why.

GLOSSARYKey terms introduced

Section
A named chunk of an object file or image with one kind of content and one destination: .text (code), .rodata (constants), .data (initialised variables), .bss (zero-initialised variables).
Linker script
The file (ESP-IDF generates sections.ld from linker fragments) that tells the linker which input sections go to which memory region at which address and how large each region is.
Map file
The linker's report of every symbol's address, size, section, and originating object file. The definitive answer to "what is in my image and why".
Partition table
A CSV compiled to a binary at flash offset 0x8000 that divides the flash into named regions (NVS, otadata, app slots, storage) with types the bootloader and IDF libraries look up by name.
OTA slot
One of two equal-sized app partitions (ota_0, ota_1). Updates are written into the inactive slot; otadata records which is active and whether it has been verified.
sdkconfig
ESP-IDF's generated configuration file of Kconfig options; sdkconfig.defaults is the version-controlled statement of intent that produces it.
USB Serial/JTAG
The ESP32-C3's built-in USB peripheral on GPIO18/19 providing a CDC serial console and a JTAG debug port without an external bridge chip.
Rollback
The bootloader behaviour, enabled by CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE, that reverts to the previous slot if a newly booted image does not confirm itself valid before the next reset.

ACTIVE RECALLCheck your understanding

Answer in your own words first, then reveal.

1You change static uint16_t rh_lut[2048] = {…} to static const uint16_t rh_lut[2048] = {…}. What changes in the build output, and why does it matter for Beacon?›

The table moves from .data to .rodata. Flash usage is nearly unchanged — the initial values were already in the image — but 4 KB of SRAM is freed, because .data is copied into DRAM at load while .rodata is read in place from the flash cache window. idf.py size shows "Used static DRAM" drop by 4096 bytes and the heap available to the BLE host grow by the same. For Beacon this is the cheapest RAM you will ever recover, and it is why the driver lessons insist on const for every register table and calibration constant. The one caveat from 3.1: a const table that an ISR must read during a flash write needs DRAM_ATTR, which puts it back in SRAM on purpose.

2The build says "0x1c0000 bytes smallest app partition, 3 % free". A colleague proposes switching to a single 3 MB factory partition to "fix" it. What do you say?›

That it makes the number green and the product fail R7. A single factory partition means no second slot to download an update into, so no OTA and no rollback; the first field bug on 25 pilot units becomes 25 site visits with a USB cable — and Beacon's USB port is behind an IP54 enclosure. The real options are: cut the image (compile out DEBUG/VERBOSE log strings with CONFIG_LOG_MAXIMUM_LEVEL, use -Os, drop components pulled in by an over-broad REQUIRES, check the map for a library nobody needs), or, if the image is legitimately that big, move to the 8 MB flash variant of the module before Rev A is ordered. Shrinking the partition table's promises is the one fix that is not a fix.

3After an OTA, a Beacon boots the new image, the image crashes in its I2C init, and the device reboots. Trace what the bootloader does next and name the sdkconfig line and the application call that make it work.›

On the first boot of the new slot the bootloader marked it ESP_OTA_IMG_PENDING_VERIFY in otadata. The image crashed before calling esp_ota_mark_app_valid_cancel_rollback(), so on the next boot the bootloader finds a slot that is still pending, marks it ESP_OTA_IMG_INVALID, and boots the other slot — the previous, known-good firmware. The device is back on the air one reset later with no human involved. The sdkconfig line is CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y; without it the bootloader would keep booting the broken image forever. The application's obligation is to call the confirm function only after a real self-test — Beacon's SELF_TEST state must actually talk to both sensors before confirming, or a firmware that boots but cannot sense will be marked valid.

4Flash is 41 % free but nimble_port_init() fails with ESP_ERR_NO_MEM after you add a feature. Which two lines of idf.py size output explain it, and what is the likely cause?›

The Used static DRAM row (specifically its .bss size) and the Used static IRAM row. The binary size only counts flash; a large zero-initialised static buffer or a big IRAM-resident function costs SRAM without touching the .bin, and on the ESP32-C3 IRAM and DRAM share the same 384 KB. The BLE host allocates its buffers from the heap at init; when .data + .bss + IRAM grew past the point where enough contiguous heap remained, init fails. Likely cause: a new static array (a 40 KB ring buffer, an oversized task stack declared statically) or a component that puts a lot of code in IRAM. Confirm with idf.py size-files to find the object, and log esp_get_free_heap_size() at boot before and after the change.

Next: every pin has a history — and GPIO9's is the boot mode →