
Real Interview Questions for the Embedded Software Engineer at STMicroelectronics
NewInterview Q&A
Q&A-1Explain the concept of Falcon signature and its application in your work?
Reported in STMicroelectronics Embedded Engineer Interview Questions 2026
The 90-second answer
Falcon is a lattice based digital signature from the NIST post quantum standardisation. It is a hash and sign scheme built on the NTRU lattice, using Fast Fourier Sampling to produce a short signature that can be verified with only integer arithmetic. The two parameter sets are Falcon-512, aimed at NIST security level 1, and Falcon-1024, aimed at level 5.
In embedded work I would use it asymmetrically. The private key stays off the device, in an HSM or signing server that signs a firmware image. The STM32 verifies that signature before it installs or boots the image. Verification is the cheap operation, signing is not, and that split fits a microcontroller perfectly.
How it works
Falcon signs a digest of the message, not the message itself. The signer samples a lattice point close to the target using a Gaussian distribution over the NTRU lattice, then encodes the difference compactly. The verifier reconstructs the lattice point from the signature and the public key and checks that it is close enough and hashes to the message digest. That check gives existential unforgeability under chosen message attack, assuming the hash and the lattice problem hold.
Two properties matter on a Cortex-M. Verification needs no floating point and no secret data, so it is comparatively easy to make constant time. Signing needs high quality randomness and, in the reference design, floating point Gaussian sampling. On a Cortex-M33 or M7 without an FPU that signing code is slow, hard to audit for timing leaks, and a poor fit for on device signing. Keep signing off device.
| Scheme | Public key | Signature | Verify on MCU |
|---|---|---|---|
| Falcon-512 | 897 bytes | about 690 bytes | integer only, fast |
| Falcon-1024 | 1793 bytes | about 1793 bytes | integer only, fast |
| ECDSA P-256 | 65 bytes | about 71 bytes | needs ECC accelerator or software |
| ML-DSA-65 (Dilithium) | 1952 bytes | 3309 bytes | integer only, larger messages |
Falcon wins on signature size against ML-DSA, which helps when a bootloader has to receive the signature over a slow link or store it in internal flash. It loses on implementation risk. ML-DSA signing is deterministic in its standardised form and avoids floating point entirely. If a product must sign on device, that is a strong reason to pick ML-DSA instead.
Application: signed OTA update on STM32
/* Verification side, pseudocode against a Falcon implementation
such as liboqs or a vendor PQC library. Checked against the
Falcon specification, draft FIPS 206 parameter sets. */
int install_update(const uint8_t *image, size_t len,
const uint8_t *sig, size_t siglen,
const uint8_t *pk)
{
uint8_t digest[32];
/* Hash the exact bytes that will be written to the inactive
bank, including header and version fields. */
sha256(image, len, digest);
if (falcon_verify(digest, 32, sig, siglen, pk) != 0)
return -1; /* reject, keep old bank running */
if (version <= running_version)
return -1; /* rollback check, separate from signature */
write_inactive_bank(image, len);
set_boot_bank();
return 0;
}The public key is provisioned at manufacture, ideally fused or stored in a protected region so a compromised update cannot replace it. On STM32 parts with secure boot support, the same pattern applies at first boot: the ROM or bootloader verifies the next stage before jumping to it.
Failure modes I would name in the interview
Randomness failure during signing leaks the private key. Falcon signing is probabilistic, and a repeated or biased Gaussian sample can expose enough information to recover the key. That is another reason signing belongs in an HSM with a tested RNG, not in application firmware.
Fault injection and timing attacks target the sampler. A glitch that skips a rejection check can produce a signature that leaks key material. Verification code has a smaller secret surface, but it still needs to reject non canonical encodings and oversized signatures, or an attacker can exploit parser differences between signer and verifier.
A valid signature does not stop rollback or a downgrade to an older vulnerable version. The version check in the code above, backed by monotonic counters in flash or OTP where available, has to be enforced separately. It also does not authenticate the transport. Pair the signature with authenticated encryption for the download if confidentiality matters, and bind the hash to the full image header so metadata cannot be swapped.
On a real design I would budget flash for the library and the larger signature, measure verify time on the target core (expect tens of milliseconds on a 200 MHz Cortex-M7 for Falcon-512 in software, and measure rather than trust that figure), and confirm the implementation is constant time on the verify path and has been tested against the official test vectors before it goes near a release build.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2How do you choose allocation and buffering under resource constraints?
Reported in STMicroelectronics Embedded Engineer Interview Questions
The 90-second answer
I start from the budget, not from malloc. On a part like the STM32L476 (128 KB SRAM, 1 MB flash, 80 MHz Cortex-M4) I list four numbers before writing code: worst-case producer rate, consumer rate, deadline, and SRAM left after stacks and globals. Allocation follows from those numbers.
Take a concrete case: a UART at 115200 baud, 8N1, feeding a control task that must run every 10 ms. The wire carries 11520 bytes/s. A 256-byte DMA buffer fills in about 22 ms, so a single buffer plus a slow consumer guarantees overruns. Double buffering at 512 bytes total costs 0.4% of SRAM and buys one full fill period of slack. That arithmetic, repeated for every stream, decides buffer size. If the consumer can keep up on average but not in bursts, size for the burst, not the average.
Default choice on STM32 firmware is static allocation. Buffers live in .bss or a named linker section, sized at compile time, with a static assert on the total. No fragmentation, no failure at runtime, and the map file tells me exactly what I spent. I reach for a fixed pool only when messages vary in size but have a hard maximum, for example a pool of eight 64-byte CAN frames. I avoid the general heap in production paths. heap_4 in FreeRTOS reduces fragmentation compared with heap_1 to heap_3, but it still makes timing and exhaustion data-dependent, and a failed allocation in an ISR or a high-priority task is hard to recover from cleanly.
/* Ring buffer for a DMA-fed UART, checked against STM32Cube HAL 1.17 */
#define RX_SIZE 256u /* power of two */
#define RX_MASK (RX_SIZE - 1u)
typedef struct {
uint8_t buf[RX_SIZE];
volatile uint16_t head; /* written by consumer */
volatile uint16_t tail; /* written by DMA callback */
uint32_t dropped;
} rx_ring_t;
static rx_ring_t rx; /* static: 256 bytes in .bss, visible in map file */
static inline uint16_t rx_free(const rx_ring_t *r)
{
return (uint16_t)(RX_SIZE - ((r->tail - r->head) & RX_MASK));
}The consumer checks rx_free() before reading, the DMA callback advances tail, and on overflow I increment dropped and overwrite or drop the oldest data by policy, never block. Blocking in a callback stalls the peripheral and can starve lower-priority interrupts.
| Strategy | SRAM cost | Worst-case time | Failure mode | Use when |
|---|---|---|---|---|
| Static buffer | Fixed, in map file | Bounded, no search | Compile-time overflow of budget | Fixed-size streams, DMA, ISRs |
| Fixed pool | Fixed, n times block size | Bounded, O(1) free list | Pool exhausted | Variable payload, hard maximum |
Heap (heap_4) | Dynamic, fragmented | Data-dependent | Fragmentation, NULL at runtime | Rare, non-critical, cold paths only |
| Stack buffer | Per call, counted in stack analysis | Bounded | Stack overflow, hard to detect | Small, short-lived, measured worst case |
Trade-offs I state out loud. SRAM spent on buffering is SRAM not available for stacks, and stack depth on Cortex-M is easy to underestimate because of interrupt nesting and HAL call chains. I measure with stack watermarking (uxTaskGetStackHighWaterMark in FreeRTOS, or a pattern fill checked at runtime) and keep at least 20% headroom on the deepest task. Flash cost matters too: a large lookup table or a second copy of a buffer in flash for DMA scatter-gather trades flash for SRAM, which is right when SRAM is the tighter budget.
Energy changes the answer on low-power parts. On an STM32L4 in Stop 2, waking the CPU for every byte costs far more than waking it per DMA half-transfer. I would move from a byte ring to block transfers, batch processing, and let the DMA run while the core sleeps. That trades latency, up to one block period, for current. If the deadline forbids that latency, the energy budget has to give.
Failure modes and how I detect them. DMA overrun shows up as a gap in sequence numbers or a rising dropped counter, which I expose as a diagnostic and assert in test builds. Heap exhaustion on a path I kept dynamic shows up as a NULL return, so I wrap allocation in a function that logs and enters a safe state instead of dereferencing. Stack overflow on Cortex-M4 with the MPU enabled faults on guard region access; without an MPU it corrupts adjacent memory silently, which is why I prefer static stacks with watermarks over hope. Priority inversion appears when a low-priority task holds a pool block a high-priority task needs, so pools shared across priorities get priority inheritance or are partitioned per task.
When I would not use this approach. If the stream is truly unbounded, for example a network stack with variable MTU, a fixed ring sized for the average will drop under attack or misconfiguration. Then I need flow control at the protocol level, backpressure, or a hard cap with explicit drop accounting, and I say so rather than sizing a bigger buffer. If SRAM is plentiful and the part has an MMU, the calculus changes, but on a bare-metal STM32 the static-first rule holds.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Tell me how you approach debugging complex hardware-software integration issues in embedded systems?
Reported in Debugging hardware-software integration
The 90-second answer
I treat the board and the firmware as two systems meeting at a contract: electrical levels, timing, clocking, pin muxing and reset state. I first reproduce the failure on a known-good board with a fixed binary, then I bisect that contract from the outside in. Power and clocks first, then pin and peripheral configuration, then bus traffic, then DMA and interrupts, then application logic. At each layer I need an observable signal that proves the layer works before I move inward. If I cannot name that signal, I add instrumentation before I change code.
On STM32 parts that order matters. A peripheral that never sees a clock, a pin left in the wrong alternate function, or a DMA buffer the DMA engine cannot reach will all look like a driver bug in a log. Checking the register dump against the reference manual saves hours of guessing.
Isolation in practice
-
Freeze the setup. Record board revision, schematic revision, firmware commit, compiler flags, and whether the fault follows the board or the binary when I swap them. A fault that follows the binary points to configuration or timing. A fault that follows the board points to solder, power, or a component variant.
-
Check power, reset and clocks. Measure the rail at the device pin under load, not just at the regulator. On an STM32F4 or H7, confirm HSE or HSI selection, PLL source and multipliers, and the APB prescaler for the peripheral in question. A 168 MHz core with a 42 MHz APB1 timer clock doubling rule is a classic source of a UART running at half rate.
-
Check the pin and the peripheral registers. Dump the relevant registers through SWD and compare them to the reference manual, not to the HAL initialisation code. HAL can hide a missing clock enable or a wrong alternate function.
/* STM32F4 example: dump I2C1 state before touching the driver */
void dump_i2c1(void)
{
printf("RCC_APB1ENR=0x%08lx I2C1EN=%lu\r\n",
RCC->APB1ENR, (RCC->APB1ENR & RCC_APB1ENR_I2C1EN) != 0);
printf("GPIOB_MODER=0x%08lx AFR0=0x%08lx\r\n",
GPIOB->MODER, GPIOB->AFR[0]); /* PB6/PB7 must be AF4 for I2C1 */
printf("I2C1_CR1=0x%04lx CR2=0x%04lx CCR=0x%04lx TRISE=0x%04lx\r\n",
I2C1->CR1, I2C1->CR2, I2C1->CCR, I2C1->TRISE);
printf("I2C1_SR1=0x%04lx SR2=0x%04lx\r\n", I2C1->SR1, I2C1->SR2);
}That dump answers four questions in seconds: is the clock on, is the pin muxed, are the timing registers sane for 100 kHz or 400 kHz, and which error flag did hardware set.
- Observe the wire. A logic analyser on SCL and SDA, or on TX and RX, settles arguments about software. I decode the bus and compare start, address, acknowledge and stop against the sensor datasheet. If the wire is correct and the device still misbehaves, the problem moves to device state, timing between transactions, or power during the transaction.
Worked trace: I2C sensor returns no data
Assume an STM32F4 at 168 MHz, APB1 at 42 MHz, sensor on I2C1 at 400 kHz, address 0x76.
| Check | Expected | Observed | Conclusion |
|---|---|---|---|
| RCC APB1ENR I2C1EN | 1 | 1 | Clock enabled |
| GPIOB PB6/PB7 MODER, AFR0 | AF, AF4 | AF, AF4 | Pin mux correct |
| I2C1 CCR, TRISE | CCR 105, TRISE 13 for 400 kHz on 42 MHz APB1 | CCR 210, TRISE 13 | Timing set for 200 kHz, sensor still ACKs but analyser shows 200 kHz |
| Analyser decode | START, 0xEC, ACK, register, repeated START | Same, at 200 kHz | Bus protocol correct |
| Sensor register read | Data bytes after ACK | 0xFF on every byte | Device in reset or wrong register, check power pin and reset timing |
In this trace the first fault is a timing mismatch that only matters when the sensor requires a minimum SCL frequency or a shorter timeout. The second fault, all 0xFF, is a device state issue that no amount of driver rewriting fixes. Both were found without changing application code.
Failure modes I check explicitly
DMA on H7 parts cannot always reach every SRAM region, and data cache can make a buffer look correct to the CPU while DMA reads stale memory. I place DMA buffers in the SRAM the DMA engine can access and clean or invalidate cache by address range around the transfer. Interrupts are the other common trap: a priority that preempts a time-critical ISR, a shared interrupt flag cleared in the wrong order, or a callback that blocks. I trace with a GPIO toggled at ISR entry and exit and measure the interval on the analyser. If the interval grows under load, the issue is preemption or a critical section, not the peripheral.
I also distrust a fix that only works at room temperature or with a debugger attached. A debugger can mask a reset or timing fault by holding NRST or by slowing execution. I retest standalone, across supply voltage within the datasheet range, and with the exact clock source the product will use. When the fault disappears under those conditions, I can explain which layer was wrong and why the earlier symptom appeared where it did.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Explain the role of interrupts and how you prioritize them in an embedded system design?
Reported in Interrupts in system design
The 90-second answer
Interrupts let hardware pull the CPU out of a low-power or polling loop the moment an event needs service, instead of burning cycles checking a flag. In a design I start from deadlines, not from the peripheral list. Every source gets a worst-case latency budget: how late can it be serviced before data is lost, a control loop misses its period, or a safety function fails. Priority then follows that budget.
On STM32 Cortex-M parts that maps directly onto the NVIC. I use Priority Group 4, so all four priority bits are preemption priority and there is no subpriority splitting. A higher preemption priority can interrupt a lower one. Sources at the same preemption level cannot preempt each other, so I never put two unrelated sources at the same level and hope the order works out.
A concrete STM32G4 / H7 style allocation I have used for a motor and comms controller:
| Source | Preemption priority | Why there |
|---|---|---|
| HardFault, MemManage | 0 (fixed) | Cannot be masked or reprioritised |
| TIM1 break / overcurrent | 1 | Must stop PWM within microseconds, no jitter tolerance |
| TIM1 update (current loop) | 2 | Fixed 20 kHz period, jitter directly becomes torque ripple |
| CAN1 RX / error | 3 | Frame deadline in milliseconds, but a missed frame stalls the bus |
| USART RX (DMA idle) | 4 | Byte loss only if DMA buffer fills, DMA does the bulk work |
| SysTick | 5 | RTOS tick, late by a few microseconds is harmless |
| EXTI button / encoder | 6 | Human timescale, debounce in software |
The rule I defend in review: rate alone does not set priority. A 1 kHz encoder that can tolerate 5 ms jitter sits below a 100 Hz CAN error that can corrupt a bus if handled late. Deadline and consequence set it, rate only breaks ties.
What the ISR is allowed to do
Keep it short and bounded. Clear the hardware flag, capture the timestamp or sample, push the data into a lock-free ring buffer or set a flag for a task, exit. No HAL calls that can block, no printf, no waiting on a mutex. On STM32 HAL that means calling the IRQ handler the HAL expects and letting it clear flags, or writing the register-level handler when I need the cycle count.
/* STM32G4, Priority Group 4: priority value is preemption priority */
HAL_NVIC_SetPriority(TIM1_UP_IRQn, 2, 0);
HAL_NVIC_SetPriority(CAN1_RX0_IRQn, 3, 0);
HAL_NVIC_SetPriority(USART2_IRQn, 4, 0);
void TIM1_UP_IRQHandler(void)
{
__HAL_TIM_CLEAR_FLAG(&htim1, TIM_FLAG_UPDATE);
uint32_t now = __HAL_TIM_GET_COUNTER(&htim1);
ring_push(¤t_loop_q, now); /* fixed size, no allocation */
__DSB();
}If the ISR work grows, the design is wrong. Move parsing, filtering and protocol handling to a task or the main loop, signalled by the ring buffer or an RTOS semaphore given from the ISR with xSemaphoreGiveFromISR.
Latency arithmetic, worked example
Worst-case latency for the CAN interrupt is not its own execution time. It is the longest time the CPU spends with interrupts masked or in a higher priority handler.
Assume a 170 MHz core, a 40-cycle critical section around a shared SPI transfer (about 0.24 us), and a TIM1 update ISR of 340 cycles (2.0 us). CAN latency worst case is roughly 0.24 + 2.0 + entry overhead, about 2.5 us. Against a 1 ms CAN deadline that is comfortable. If the current loop ISR grew to 200 us because someone added a Clarke transform inside it, CAN jitter would grow by the same amount and the budget would need revisiting. I measure this with a GPIO toggled on ISR entry and a scope, not by trusting the estimate.
Failure modes I check
Priority inversion through a shared resource: a low priority task holds the I2C bus while a high priority ISR waits for it. The ISR must never block on a mutex. Use a queue, or protect the bus with a priority ceiling protocol in the RTOS.
Starvation: a chatty UART at priority 4 can starve EXTI at 6 indefinitely if it never idles. That is acceptable only if the button really is lowest consequence. If not, raise it or use DMA with idle line interrupt so the UART ISR fires per block, not per byte.
Missed flag clear: on STM32, some peripherals need the status register read after clearing, and EXTI needs the pending bit cleared explicitly. A handler that returns without clearing re-enters immediately and the system looks hung at 100% CPU in the ISR. I check the pending bit in the debugger when a board behaves that way.
Stack and tail chaining: nested preemption means the stack must hold the deepest nesting path, not just the deepest single ISR. I size it from the priority map and verify with stack watermarking in development.
So my answer in the room: interrupts are for bounded, time-critical capture and wakeup, priority is assigned from a latency budget per source on the NVIC preemption level, ISRs stay to capture and enqueue, and I verify the budget with a scope trace and a worst-case sum, not with a claim that it should be fine.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Discuss your experience with real-time operating systems (RTOS) versus bare-metal programming?
Reported in STMicroelectronics Embedded Engineer Interview Questions 2026
The 90-second answer
I have shipped both on STM32 parts, and I choose based on how many independent timing domains the firmware has to keep. On a Cortex-M4 STM32F4 at 168 MHz, a bare-metal superloop with interrupts is enough when the work is one control loop plus a few ISRs. Once I have blocking communication, logging, and a control task that cannot slip, I move to FreeRTOS and give each domain its own task and priority.
Bare metal gives me the lowest and most predictable latency. An ISR entry on that part is a few cycles, and a timer ISR that toggles a PWM or captures an encoder can run in under 2 microseconds. There is no tick, no scheduler, and no context switch to account for. The cost is that I own every interleaving. If a UART receive ISR and the main loop both touch a buffer, I need volatile, critical sections, or a ring buffer, and I have to prove the loop period by hand.
FreeRTOS costs a little of that determinism to buy structure. A 1 kHz tick ISR of about 2 microseconds consumes roughly 0.2% of the CPU, and a context switch on an M4 is typically in the 5 to 10 microsecond range depending on how many registers are stacked. In return, a task blocked on a queue or a semaphore consumes no CPU, and a high priority control task preempts a low priority comms task without me writing the preemption logic.
| Dimension | Bare metal | FreeRTOS |
|---|---|---|
| Worst case response | ISR latency plus longest non-interruptible section, often under 5 microseconds if sections are short | Tick plus context switch, commonly 10 to 20 microseconds before the ready task runs |
| Blocking I/O | Polling, or an ISR plus flag that the loop checks | Task blocks on a queue, the CPU runs other tasks meanwhile |
| RAM overhead | No scheduler structures | TCB plus stack per task, a few hundred bytes of TCB and typically 512 bytes to 2 KB of stack per task on STM32 |
| Failure mode I watch | Loop overrun, ISR and loop racing on shared state | Priority inversion, stack overflow, a task missing its period |
| Best fit | Single loop, tight timing, small memory | Several tasks with different periods and blocking drivers |
How I decide in practice
I start by listing periods and deadlines. A motor current loop at 20 kHz, a 100 Hz sensor task, and a Modbus RTU exchange that blocks for tens of milliseconds cannot share one superloop without the comms delaying the current loop. That split is a FreeRTOS design. A single sensor node that wakes from STOP, reads an ADC, and sleeps is bare metal, and adding an RTOS there only adds RAM and a tick I have to justify.
// FreeRTOS on STM32, control task keeps its period with vTaskDelayUntil
void control_task(void *arg) {
TickType_t next = xTaskGetTickCount();
for (;;) {
read_encoder_and_current();
run_pid();
update_pwm();
vTaskDelayUntil(&next, pdMS_TO_TICKS(1)); // 1 kHz, 1 ms period
}
}
void comms_task(void *arg) {
for (;;) {
// Blocks here, control_task still runs at its priority
xQueueReceive(uart_queue, &frame, portMAX_DELAY);
process_modbus(frame);
}
}The same split in bare metal would need a timer ISR for the 1 kHz loop, a UART ISR filling a ring buffer, and a flag the main loop polls. That works, and I have done it, but every new driver adds another flag and another place where the loop period can be disturbed.
Failure modes I check before I call either design done
With FreeRTOS, priority inversion is the classic one. If a low priority task holds a mutex that a high priority task needs, the high priority task waits behind a medium priority task that has nothing to do with either. I use mutexes, which inherit priority on FreeRTOS, rather than binary semaphores for that case, and I keep critical sections short. I also size stacks from measured high water marks with uxTaskGetStackHighWaterMark, not from a guess, and I enable stack overflow detection and the MPU where the part has one.
With bare metal, the equivalent failure is a long non-interruptible section or a polling loop that waits on a peripheral. A while (HAL_UART_Transmit(...) != HAL_OK) in the main loop can stall the control ISR timing if interrupts are masked, and a shared variable updated in an ISR and read in the loop without volatile or a critical section gives intermittent faults that are hard to reproduce on the bench.
In both cases I measure rather than assume. I toggle a GPIO at task or loop entry and scope the period and jitter, I log worst case execution time for the control path, and I run the watchdog with a window so a missed deadline resets the part instead of running with stale outputs. On STM32 I also check the clock tree and DMA setup first, because a surprising number of timing faults I have chased turned out to be a timer running from the wrong clock or a DMA buffer the CPU was still writing to.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Describe how you handle memory management in resource-constrained environments?
Reported in STMicroelectronics Embedded Engineer Interview Questions 2026
The 90-second answer
On an STM32 part I treat SRAM as a budget I can account for byte by byte, not something I discover at runtime. Production code on a part like the STM32F407 (192 KB SRAM, 1 MB Flash) or a smaller STM32G0 (8 KB SRAM) gets no malloc in interrupt handlers, control loops, or DMA paths. I allocate statically at compile time, size stacks from measured worst case, and keep any unavoidable dynamic allocation behind a fixed pool with a hard failure path.
That gives me three properties an interviewer should probe: no fragmentation, deterministic worst-case memory use, and a failure I can detect before it corrupts something else.
How I lay it out
| Region | What lives there | How I size it |
|---|---|---|
| Stacks | One per task, plus main stack | Measured high-water mark plus 25% margin, checked in test |
| Static objects | Buffers, queues, state machines | Exact struct size, placed in .bss or a named linker section |
| DMA buffers | ADC, UART, SPI buffers | Fixed size, 4-byte aligned, in SRAM not CCM-only regions unless the DMA can reach them |
| Heap pool | Rare, bounded allocations only | One fixed block, never the default heap |
Arithmetic makes the budget concrete. Hypothetical but typical for an F407 motor controller: 6 FreeRTOS tasks at 512 to 1024 bytes of stack each is about 5 KB, a 4 KB DMA ring buffer, 2 KB for a CAN queue, and 1 KB for logging leaves roughly 180 KB free. On a G0 with 8 KB total, the same design does not fit, so I cut the log buffer, shrink queues to 256 bytes, and move to a single super-loop task instead of six tasks. The decision follows the map file, not a guess.
Code I would actually ship
/* Fixed pool: no fragmentation, allocation is O(1) and bounded. */
#define POOL_BLOCKS 16
#define POOL_BLOCK_SIZE 64
static uint8_t pool_storage[POOL_BLOCKS][POOL_BLOCK_SIZE] __attribute__((aligned(4)));
static uint8_t pool_used[POOL_BLOCKS];
void *pool_alloc(void)
{
for (unsigned i = 0; i < POOL_BLOCKS; i++) {
if (!pool_used[i]) {
pool_used[i] = 1;
return pool_storage[i];
}
}
return NULL; /* caller must handle this, not retry forever */
}
void pool_free(void *p)
{
if (p == NULL) return;
unsigned idx = (unsigned)((uint8_t *)p - &pool_storage[0][0]) / POOL_BLOCK_SIZE;
if (idx < POOL_BLOCKS) pool_used[idx] = 0;
}For FreeRTOS I use the static variants, xTaskCreateStatic and xQueueCreateStatic, and set configTOTAL_HEAP_SIZE to 0 when I can. If a library forces malloc, I route it to that pool and implement vApplicationMallocFailedHook to log the caller, freeze the offending task, and enter a safe state. A silent NULL return in a control loop is how a drone falls out of the sky.
Failure modes I check for
Fragmentation is the classic one. Repeated malloc(100), free, malloc(50) on a 1 KB heap leaves holes no single block fits, even though total free memory looks fine. The pool above cannot fragment that way because every block is the same size, at the cost of internal waste if I ask for 65 bytes and get 64 plus a failure. I accept that waste deliberately.
Stack overflow is the second. I fill stacks with a known pattern at startup, read uxTaskGetStackHighWaterMark after a soak test that exercises worst-case call depth, and enable stack overflow detection in FreeRTOSConfig.h. On bare metal I add a canary word at the top of the main stack and check it in the idle loop. A HardFault handler that dumps the program counter and stack pointer to SWO has saved more debug time than any log.
The third is DMA and cache coherence on parts with a data cache, such as STM32H7. A buffer the CPU writes and DMA reads needs cache maintenance or placement in a non-cacheable region, otherwise the DMA sends stale data. I place DMA buffers in a dedicated linker section, align them to the cache line size (32 bytes on H7), and call SCB_CleanDCache_by_Addr before starting a transfer.
I verify the whole thing with the linker map file after every build. If .bss grows by 2 KB after a library update, I want to see that in review, not discover it when the stack collides with the heap in the field.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Describe a challenging project you managed and the specific technical hurdles you overcame?
Reported in STMicroelectronics Embedded Engineer Interview Questions 2026
The 90-second answer
I led firmware for a battery powered vibration monitor on an STM32H743. It sampled three accelerometers at 4 kHz, ran an FFT on device, and sent summaries over CAN FD every 100 ms. The difficult part was holding sample timing, alert latency and sleep current together. Changing one tended to break another.
Three hurdles dominated: gaps between DMA bursts, alerts delayed behind periodic frames, and corrupt samples after wake from Stop1.
1. Gaps between DMA bursts
The first build used TIM2 to trigger the ADC, but DMA in normal mode with a 512 sample buffer. The ADC complete callback rearmed DMA for the next burst. That callback is software, so if a CAN interrupt delayed it, DMA sat idle and sampling stopped until the callback ran. The timer itself was accurate. The gap was in the rearm path.
On a logic analyser the trigger stayed at 250 microseconds, while DMA activity showed idle gaps of up to 40 microseconds after some bursts. Those gaps smeared the 1.2 kHz bearing tone.
I switched DMA to circular mode. The callback then only sets a flag for the completed half buffer. It no longer rearms anything, so its latency affects processing, not sampling.
/* STM32H743, STM32CubeH7 v1.12 */
volatile uint8_t half_ready = 0;
void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef *hadc)
{
half_ready = 1; /* no rearm, no copy, no FFT here */
}
void monitor_task(void)
{
if (half_ready) {
half_ready = 0;
process_half_buffer(); /* FFT in task context */
}
}After the change, DMA ran continuously and the 1.2 kHz peak stopped wandering between FFT bins on our bench unit.
2. Alerts delayed behind periodic frames
The node used one FDCAN transmit mailbox for both periodic summaries and alerts. The periodic task ran every 100 ms. If the mailbox was still busy, HAL_FDCAN_AddMessageToTxFifoQ returned busy and the alert code dropped the frame until the next cycle. Under load from other nodes on the bus, that meant alerts arrived 100 to 200 ms late.
The arithmetic ruled out our own traffic as the cause. A 64 byte CAN FD frame is roughly 700 bits on the wire including overhead and stuff bits. At 1 Mbit/s data phase that is about 0.7 ms, and at 10 frames per second it is under 1 percent of bus capacity. The rest of the bus, mainly a gateway sending diagnostics, sat near 82 percent. Our frames lost arbitration repeatedly while the single mailbox stayed occupied.
I gave alerts a dedicated mailbox with the lowest CAN identifier, put summaries in a second mailbox, and configured the FDCAN TX buffers in priority order rather than FIFO order. I also cut the summary from 64 to 32 bytes, sending RMS and peak per axis instead of a spectrum. Our contribution fell from about 0.8 percent to 0.4 percent, which is small, but the alert no longer depended on the periodic mailbox being free. Worst case alert latency in our trace fell from about 180 ms to under 5 ms, roughly one frame time plus arbitration.
| Metric | Before | After |
|---|---|---|
| DMA mode | Normal, rearmed in ISR | Circular, flag only |
| Alert mailbox | Shared with summaries | Dedicated, lowest ID |
| Our bus use at 10 Hz | About 0.8 percent | About 0.4 percent |
| Alert latency, worst case in trace | About 180 ms | Under 5 ms |
| Average current, Stop1 plus run | 8.4 mA | 3.1 mA |
3. Corrupt samples after wake from Stop1
The node slept in Stop1 between bursts. On wake, the first half buffer contained garbage. The wake sequence restarted the ADC and DMA before the PLL lock flag was set, so early conversions ran with an unstable clock. I reordered wake to wait for PLL lock, restore the saved DMA configuration, start TIM2, and discard the first half buffer unconditionally. That throws away 128 ms of samples, which the host already expected, and removed the false alerts caused by the corrupt burst.
If I started again I would capture the DMA and mailbox busy traces in the first week. Both faults were visible on the analyser in an afternoon, but we spent two weeks debating them from code alone because nobody had recorded the timing.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8How do you manage your time when balancing multiple technical tasks or tight project deadlines?
Reported in STMicroelectronics Embedded Engineer Interview Questions 2026
The 90-second answer
I treat time as a resource I allocate like RAM or CPU on an STM32, not as a vague effort to "work harder." I list every open task, estimate it in hours, mark the hard deadline, and then protect the work that blocks hardware or other people first. On a typical week with a board bring-up, a driver bug, and a release deadline, I would put the bring-up on the scope in the morning, because a silent UART or a wrong clock tree blocks everything downstream, and I would timebox the bug hunt to 90 minutes before escalating with a trace and a hypothesis.
The rule I use in the interview loop at STMicroelectronics is simple: blocking work gets calendar time, non-blocking work gets gaps, and nothing gets an open-ended "when I finish." If a task slips past its box, I re-plan that day instead of borrowing silently from the next deadline.
How I triage in practice
I keep a single list with four columns: task, estimate, deadline, and who is blocked. I re-score it every morning in 10 minutes. A task that blocks a lab booking, a hardware spin, or a customer sample goes first even if it is not the most interesting code.
| Task (hypothetical week) | Estimate | Hard deadline | Blocked party | Slot |
|---|---|---|---|---|
| STM32H7 clock and UART bring-up on new board | 4 h | Lab slot Tue 10:00 | Whole team | Tue 09:00-13:00 |
| CAN FD timing fault at 500 kbit/s | 2 h | Wed integration build | Firmware integration | Tue 14:00-16:00 |
| HAL I2C DMA transfer stalls under load | 6 h | Fri release candidate | Release | Wed-Thu, 3 h/day |
| Update register map doc for errata | 1 h | Fri 17:00 | Support | Fri 15:00-16:00 |
That table is the plan I show my lead. If the CAN fault turns out to be a bit timing register error, it finishes in 30 minutes and the freed time goes to the I2C DMA issue. If it is a transceiver problem, I stop at the timebox, capture the scope trace, and hand it to hardware with evidence instead of spending a second day guessing.
Protecting real-time work from context switching
Embedded deadlines fail differently from office work. An interrupt or a DMA callback does not care that I am in a meeting. I therefore separate work by preemption level, much like tasks in FreeRTOS:
/* Checked against FreeRTOS 11 on STM32H743, CMSIS-RTOS2 */
/* Priority 5: release-critical driver fix, runs in short slices */
/* Priority 2: documentation and non-urgent refactoring */
void vDriverFixTask(void *arg) {
for (;;) {
fix_dma_stall(); /* bounded: one hypothesis per slice */
vTaskDelay(pdMS_TO_TICKS(50));
if (dma_stall_reproduced()) break;
}
xTaskPrioritySet(NULL, 2); /* yield CPU once reproduced */
}The point is not the code. It is that a low-priority task never starves a high-priority one, and a high-priority task is written to finish in slices so it can be interrupted by a lab slot or a field failure. I also add a 25% buffer to any estimate that depends on hardware I have not measured yet. A 6 h DMA estimate becomes 7.5 h in the plan. That buffer is where scope creep and a second board revision land, not in the release date.
Failure modes I watch for
The first is silent borrowing. I finish a driver task late and quietly take Friday from documentation, then miss the release because the doc was the customer-facing errata note. I detect it by checking the list at 16:00 against the morning plan. If a task moved, I tell the lead the same day.
The second is debugging without a stopping rule. On a CAN or I2C fault I set a timer, record the last known good configuration, and change one variable at a time: clock source, then timing register, then DMA channel. If two changes are in flight I cannot tell which one fixed it, and the fix does not survive the next board spin.
The third is estimating in days. "Two days for the driver" hides whether that is two days of coding or two days waiting for a logic analyzer. I estimate in hours and name the dependency: waiting for lab, waiting for hardware, or actively coding. That makes a slip visible a day earlier, while there is still time to cut scope, for example shipping the polling fallback for I2C and deferring DMA to the next release.
When deadlines collide I do not rank by urgency alone. I rank by cost of delay. A one-day slip on a customer sample costs more than a one-day slip on internal refactoring, even if the refactoring feels more urgent because I started it first. Stating that trade-off explicitly is what lets a lead reassign the lab slot or drop a feature without me having to ask for permission to miss a date.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9Are you comfortable with the flexibility required for site-based collaboration and travel in a global semiconductor environment like STMicroelectronics?
Reported in Site-based collaboration and travel
The 90-second answer
Yes, and I would ask two specifics before I treat that as settled: how often the team travels, and how much notice a trip normally gets. I have worked on hardware bring-up where the board, the probe and the customer unit were in three different labs, so site-based work is normal for me. I can travel for a bring-up week, a customer debug session or a design review, and I am comfortable being based at a site for a few months if the project needs it. What I would want to agree early is the pattern, so travel does not become ad hoc and exhausting.
In embedded work at a semiconductor company, a lot of the job cannot move to a video call. A fault that only appears on a specific silicon revision, at temperature, or under a particular power sequence has to be reproduced on the bench. You need the logic analyser, the oscilloscope, the current probe and the actual board in front of you. That is why I expect trips to sites such as Grenoble, Catania, Agrate, Noida or a customer lab in China or the US, depending on where the product line sits.
| Work | Remote from my desk | Needs me on site |
|---|---|---|
| Code review, driver design, test planning | Yes | No |
| Reproducing a timing or signal integrity fault | Log analysis first | Yes, bench and probes |
| Silicon or board bring-up, first boot | Preparation and scripts | Yes, hardware present |
| Customer evaluation on their system | Triage and data review | Yes, their hardware and firmware |
| Long design review with applications team | Yes, with pre-reads | Sometimes, for whiteboard sessions |
How I make the travel useful
I do not fly out to "have a look." Before a trip I ship a plan to the host site: the hypothesis, the exact board and revision, the probes and fixtures I need booked, and the measurements I will take on day one. That avoids the common failure where an engineer arrives, the bench is booked by someone else, and the right connector is missing.
The practical constraints I would discuss
Time zones shape collaboration more than willingness does. Grenoble to Bangalore is about 3 hours 30 minutes ahead, so a 09:00 start in Grenoble gives a 12:30 start in Bangalore and only about four hours of overlap before Bangalore finishes. I plan that overlap for decisions and live debugging, and I write the handover note before I log off, with the trace files attached and the next measurement stated. Without that note, the next site repeats the same test.
Travel load also needs a number. If a quarter involves, say, six trips of three days, that is 18 days away plus recovery time. I can sustain that, but I would want trips grouped rather than scattered as single days, and I would not schedule a lab session that needs full concentration the morning after a long-haul flight. Fatigue in a lab is a safety issue around power supplies and high current boards, not just a comfort issue.
Two failure modes I have seen: a team that assumes the travelling engineer will be available for their normal meetings while also on the bench, which splits attention and slows both; and a team with no local owner at the host site, so knowledge leaves when the visitor leaves. I avoid both by agreeing a local counterpart, a daily 30 minute sync, and a short report at the end of the trip that the host team can act on without me.
So my answer is yes, with the pattern made explicit. If you can tell me the typical cadence for this team, I can tell you how I would plan the first quarter around it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Tell us about a time you had to explain a complex technical concept to a non-technical stakeholder?
Reported in STMicroelectronics Embedded Engineer Interview Questions 2026
The 90-second answer
On a battery-powered sensor node built around an STM32L4, product management wanted continuous sampling every second and a five-year battery life from a CR2032. Those two requirements cannot both hold, and my job was to make that visible without a datasheet lecture.
I started with the outcome they cared about, not the mechanism. I said the cell holds about 220 mAh, the sensor and MCU draw roughly 8 mA while awake, and at that rate the cell is empty in about a day. Then I reframed sleep as the normal state, not an off state. The device wakes, samples, transmits, and goes back to sleep. Battery life is decided by how often it wakes.
I put three numbers on one slide, all from the same measurement setup, and let them pick the sampling interval. That ended the argument in one meeting, because we were choosing a product behaviour, not debating my firmware.
What I actually showed them
Assumptions, stated up front: CR2032 at 220 mAh nominal, 25 °C, active current 8 mA for 50 ms per wake-up including sensor warm-up and radio, sleep current 2 µA in Stop 2. Self-discharge and cold temperature ignored, which flatters every option equally.
Average current is sleep current plus active current times duty cycle:
| Sampling interval | Duty cycle | Average current | Estimated life on 220 mAh |
|---|---|---|---|
| Continuous (no sleep) | 100% | 8,000 µA | About 27 hours |
| Every 1 s | 5% | 402 µA | About 23 days |
| Every 10 s | 0.5% | 42 µA | About 218 days |
| Every 60 s | 0.083% | 8.7 µA | About 2.9 years |
The jump that landed was 10 s to 60 s. Six times fewer wake-ups, roughly thirteen times the life, because sleep current stops dominating. I also showed the sleep modes behind the 2 µA figure, so nobody thought I had invented it:
| STM32L4 mode | What is retained | Typical current at 25 °C |
|---|---|---|
| Sleep | CPU and SRAM | Tens of µA, depends on clock gating |
| Stop 2 | SRAM and registers, PLL off | About 1 to 2 µA |
| Standby | SRAM lost, wake from pin or RTC | Under 1 µA |
The firmware change behind the table was small. The main loop became a wake, sample, transmit, sleep cycle driven by the RTC, with the sensor powered from a GPIO only during the 50 ms window:
/* STM32L4, checked against HAL for STM32L4 series */
for (;;) {
sensor_power_on();
HAL_Delay(5); /* sensor warm-up */
sample_and_transmit(); /* about 45 ms total */
sensor_power_off();
enter_stop2_until_rtc(); /* wakes after the chosen interval */
}How the conversation went
I used a phone analogy for the first minute only. A phone that never sleeps dies by evening. Then I dropped the analogy and stayed on their numbers: cost of a field battery swap, warranty returns, and the sampling rate the customer actually needed for the use case. Event-driven wake on a threshold crossing gave them most of the value of 1 s sampling without paying for it all night, which became the compromise.
The failure mode I watch for in these conversations is agreement without understanding. The stakeholder nods, then asks for continuous sampling again in the next review. I avoided that by making them state the choice back: at 60 s we get about three years, at 10 s we get about seven months. I also measured the prototype on a current analyser and brought the trace, because a measured 8.7 µA average is harder to argue with than a datasheet calculation. When the measured figure disagreed with the estimate by 15% on the first build, the cause was the sensor left powered during Stop 2, which the trace showed immediately.
If I repeated it, I would bring the analyser trace earlier and skip the analogy sooner. The analogy opened the door, but the decision was made on the table and the trace.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Why do you want to contribute to the semiconductor industry specifically at STMicroelectronics?
Reported in Motivation to work at STMicroelectronics
The 90-second answer
I want to work where firmware is the product, not a feature on top of it. In my last role I shipped a battery-powered sensor node on an STM32L4. The hardware team could pick a cheaper MCU, but the 10-year battery target only held if the firmware used STOP2 correctly, woke on the RTC and the I2C interrupt in the right order, and kept the radio off for 99.9% of the cycle. That constraint chain, from datasheet current tables to a HAL call at 2 a.m., is the work I want to do more of. ST is where I can do it at scale.
Semiconductors specifically, because the abstraction leaks in ways that matter. A cloud API can retry. A motor driver cannot. When STSPIN32 or a STM32G4 timer update lands late, a MOSFET switches hard, the supply rail dips, and the part fails in the field. I like that the software answer has to respect physics, and that a good driver or low-power library saves customers months of board spins.
ST specifically for three concrete reasons. First, breadth I have already used: STM32CubeMX generated the clock tree and DMA setup for that L4 node, LL drivers let me drop HAL overhead in the hot loop, and ST-LINK plus the STM32CubeMonitor gave me the trace I needed when STOP2 wake-up missed the first I2C byte. Second, the portfolio maps to where embedded demand is growing: STM32WB for wireless, STM32H7 and STM32G4 for motor control and power conversion, STSAFE secure elements, and SiC and GaN power devices where firmware has to coordinate protection thresholds tightly. Third, the 10-year longevity commitment. Industrial and automotive customers design a board once and expect the same MCU, same package, same errata handling for a decade. That forces disciplined HAL and LL maintenance, which is the kind of engineering I want to be accountable for.
What I would contribute in the first year
I would aim at the STM32Cube firmware packages and application notes, not just a single product line. The highest-leverage work there is unglamorous: low-power examples that actually measure, errata workarounds documented with the silicon revision they apply to, and LL code for peripherals where HAL is too heavy for a 32 KB part like the STM32G0.
A hypothetical but typical target I would own: a G0-based node that must average under 5 uA. The arithmetic decides the design before any code.
| State | Current (hypothetical, from datasheet tables) | Duty cycle | Contribution |
|---|---|---|---|
| STOP2, RTC on | 1.2 uA | 99.5% | 1.19 uA |
| Run at 16 MHz, sensor read | 2.8 mA | 0.4% | 11.2 uA |
| Radio TX burst | 8 mA | 0.1% | 8.0 uA |
That budget fails, so the firmware work is to cut the run state: batch sensor reads, keep DMA running while the core sleeps, and move the TX window. The code pattern is simple, the discipline is not:
// STM32G0, HAL, checked against STM32CubeG0 and RM0444
void enter_stop2(void)
{
__HAL_RCC_PWR_CLK_ENABLE();
HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);
}Getting that call right means the regulator stays in low-power mode, wake-up sources are armed before WFI, and no peripheral clock is left running. I have debugged the failure where a UART clock kept the part in a higher STOP state and the battery life halved. That is the level I want to work at, with the ST application engineering team who see the same failure across dozens of customers.
Why not a pure software company, or another chip vendor
I considered pure software roles. I left that path because I missed the feedback loop from a logic analyser and a current probe. I considered other MCU vendors, and I would still interview there, but ST's combination of MCU, power, analog and MEMS in one house means a firmware engineer can follow a signal from the STM32 timer to the gate driver to the MOSFET. At a vendor that only sells MCUs, that investigation stops at the board edge. At ST, the person who wrote the motor control library and the person who characterised the SiC device sit in the same company, sometimes in the same building in Agrate or Grenoble or Noida. That is where I want to learn, and where I think I can contribute fastest.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Walk me through how you would implement a driver for a new peripheral?
Reported in STMicroelectronics Embedded Engineer Interview Questions 2026
The 90-second answer
I start from the datasheet, not from code. For a new peripheral on an STM32, I read the reference manual sections for the peripheral, the clock tree in RCC, and the GPIO alternate function table, then I check the errata sheet for that exact part number and silicon revision. Only then do I decide whether to use HAL, LL, or direct register access, and I write the driver in layers: a hardware abstraction that touches registers, and a small application interface that hides it.
Assume a concrete case: a new I2C peripheral, say a sensor, on STM32F401. The steps are clock, pins, peripheral configuration, transfer mechanism, error handling, and a test on real hardware with a logic analyser.
1. Clock and pins
The peripheral is useless if its clock is off or the pins are wrong. I enable the bus clock in RCC, set the GPIO pins to alternate function open-drain with pull-ups for I2C, and confirm the AF number from the datasheet table for that package. A common failure is choosing the right AF for the wrong package pin.
/* STM32F401, I2C1 on PB6/PB7, checked against RM0368 */
void i2c1_init(void)
{
RCC->APB1ENR |= RCC_APB1ENR_I2C1EN;
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN;
GPIOB->MODER = (GPIOB->MODER & ~((3U<<12)|(3U<<14))) | (2U<<12) | (2U<<14);
GPIOB->OTYPER |= (1U<<6) | (1U<<7); /* open-drain */
GPIOB->OSPEEDR |= (3U<<12) | (3U<<14); /* very high */
GPIOB->PUPDR |= (1U<<6) | (1U<<7); /* pull-up */
GPIOB->AFRL |= (4U<<24) | (4U<<28); /* AF4 = I2C1 */
I2C1->CR1 = I2C_CR1_PE;
I2C1->CR2 = (36U<<0) | (0U<<8); /* 36 MHz PCLK1, no stretch */
I2C1->CCR = 180U; /* 100 kHz from 36 MHz */
I2C1->TRISE = 37U; /* max rise time + 1 */
}I use LL or direct registers here rather than HAL when I need deterministic timing and no hidden state. HAL is faster to bring up, but its timeout and DMA handling are harder to audit. The choice depends on whether the team already standardises on HAL for the product line.
2. Transfer mechanism
For short register reads I poll with a timeout. For anything above a few hundred bytes, or where the CPU must stay free, I use DMA and an interrupt to signal completion. The driver exposes blocking and non-blocking entry points, and the interrupt handler only sets a flag and records the error code. It never does protocol work.
3. Worked trace
A register read of 2 bytes from device address 0x48, register 0x00, at 100 kHz:
| Step | Action | What I check |
|---|---|---|
| 1 | START, send 0x90 (write) | ACK received, else NACK error |
| 2 | Send register 0x00 | ACK received |
| 3 | Repeated START, send 0x91 (read) | ACK received |
| 4 | Read byte 0, ACK | Data matches expected pattern |
| 5 | Read byte 1, NACK, STOP | STOP sent, bus returns to idle |
If step 1 NACKs, I do not retry blindly. I check whether the device is powered, whether its address straps are set, and whether SDA is held low by a stuck slave. A stuck SDA is recovered by clocking SCL manually 9 times before re-initialising the peripheral.
Failure modes I design for
Bus lockup from a slave holding SDA low, clock stretching beyond the timeout, and DMA buffer overrun when the application reuses a buffer before completion. Each gets a distinct error code, a counter in a diagnostics struct, and a recovery path: bus recovery, peripheral reset via RCC, and a guard flag on the DMA buffer. I test with a logic analyser on SDA and SCL, a fault injection build that forces NACKs, and a loop test that runs the transfer 100,000 times overnight while watching for missed interrupts. A driver that only works on the bench supply, at room temperature, with one board, is not done.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13What are the trade-offs between using a RTOS and a super-loop architecture in this specific application?
Reported in STMicroelectronics Embedded Engineer Interview Questions 2026
The 90-second answer
I would not pick by preference. I would pick by deadline structure. On an STM32 part, say an STM32G474 at 170 MHz with 128 KB SRAM running a motor drive, a sensor loop and a UART or CAN interface, the question is whether every job can meet its worst-case latency in one sequential pass.
A super-loop is one thread: while(1){ read_sensors(); control(); comms(); housekeeping(); }. Its latency for any job is the sum of all other jobs in the loop. An RTOS splits that into preemptive tasks with priorities, so a 20 kHz current loop does not wait for a 50 ms flash write. The cost is RAM, stack analysis, and failure modes you do not have in a super-loop: priority inversion, stack overflow, and a tick that can jitter a timer you should have left to hardware.
State the assumption first in the interview: if the application is a single sensor, one actuator and no hard deadline below about 10 ms, a super-loop wins on simplicity and certifiability. If you have two or more deadlines an order of magnitude apart, or blocking communication, an RTOS or a hybrid wins.
Super-loop: where it holds
/* STM32G474, bare metal, checked against HAL 1.6.x */
while (1) {
uint32_t now = HAL_GetTick();
if (now - last_ctrl >= 1) { /* 1 kHz control */
last_ctrl = now;
control_step();
}
if (now - last_sens >= 10) { /* 100 Hz sensor */
last_sens = now;
sensor_update();
}
comms_poll(); /* must never block */
housekeeping();
}This works only if comms_poll() and housekeeping() are non-blocking and bounded. The failure mode is classic: a UART transmit of 256 bytes at 115200 baud takes about 22 ms on the wire. If that call blocks, a 1 kHz control step misses 22 deadlines and the current loop sees a 22 ms gap. You detect it with a GPIO toggle around control_step() on a scope or a cycle counter, not with a log after the fact.
RAM cost is near zero beyond the stack for the single thread, typically 1 to 2 KB if you keep locals small. Timing analysis is a single worst-case loop sum, which an assessor can check by hand.
RTOS: where it pays
With FreeRTOS on the same part, I would put the current loop on a hardware timer and DMA, not on a task tick, and use tasks only for the softer work:
/* FreeRTOS 11.x, STM32G474 */
void vControlTask(void *arg) {
TickType_t next = xTaskGetTickCount();
for (;;) {
vTaskDelayUntil(&next, pdMS_TO_TICKS(1)); /* 1 kHz */
control_step();
}
}
void vCommsTask(void *arg) {
for (;;) {
xQueueReceive(comms_q, &frame, portMAX_DELAY);
comms_handle(&frame); /* may block 20 ms, control unaffected */
}
}A context switch on a 170 MHz Cortex-M4 with FreeRTOS is roughly 5 to 10 microseconds, and each task control block plus a minimum stack is about 1 to 2 KB if you size stacks from measured high-water marks with uxTaskGetStackHighWaterMark(). Four tasks therefore cost roughly 6 to 10 KB of SRAM, about 5 to 8 percent of 128 KB, before queues and heap fragmentation. Use static allocation (xTaskCreateStatic, xQueueCreateStatic) so that cost is fixed at link time and heap_4 fragmentation does not become a field failure.
The trade is jitter and inversion. A 1 ms tick gives you plus or minus 1 ms of release jitter unless you use vTaskDelayUntil() as above, and even then a higher priority task that blocks on a mutex held by a low priority task can invert priorities. FreeRTOS mutexes implement priority inheritance, which fixes the classic case, but a binary semaphore used as a mutex does not. That distinction is a common interview follow-up and a real bug source.
| Dimension | Super-loop | RTOS (FreeRTOS) |
|---|---|---|
| Worst latency for control | Sum of all other jobs, e.g. 22 ms if comms blocks | Bounded by priority and blocking time of higher tasks, typically under 0.1 ms plus switch time |
| RAM overhead | One stack, 1 to 2 KB | 6 to 10 KB for 4 tasks plus queues on this part |
| Timing analysis | One loop sum, auditable | Per-task WCET plus priority and inheritance analysis |
| Blocking I/O | Forbidden, must poll or use DMA plus interrupts | Allowed in low priority tasks |
| Failure mode | Silent deadline miss across the whole loop | Stack overflow, priority inversion, heap exhaustion |
| Change cost | Adding a job slows every other job | Adding a task costs RAM and a priority decision |
The hybrid I would actually propose
Hard real-time work stays in a timer interrupt or DMA, never in a task that depends on the scheduler. The RTOS handles sequencing, queues and blocking I/O. If the product later drops the comms requirement, I can delete the RTOS and keep the same interrupt structure, which limits rework.
I would close by naming the measurement that decides it: instrument the worst-case loop time on the target with a logic analyser for a week of soak testing. If the super-loop worst case stays under half the tightest deadline with margin for flash writes and error paths, ship the super-loop. If it does not, the RTOS cost in RAM and analysis is the cheaper option.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Design a firmware update distribution system that ensures data integrity and minimal downtime for millions of deployed edge devices?
Reported in STMicroelectronics Software Engineer Interview Questions
The 90-second answer
Assume an STM32H7-class part with dual-bank flash, 2 MB total, running a 512 KB application, and a fleet of 10 million devices that cannot be recalled. I would split the problem into three parts that fail independently: distribution, verification, and activation. Distribution gets the image to the device in resumable chunks. Verification proves those chunks are the image we signed. Activation swaps to it only after the new firmware proves it can boot, and rolls back if it cannot.
Distribution at fleet scale
The server publishes a manifest, not a monolithic binary. The manifest lists version, target hardware revision, image size, chunk hashes, and a signature. Devices fetch the manifest over HTTPS, then fetch chunks they do not already have. That gives resume for free: a device that loses power or connectivity at chunk 87 of 128 restarts at 87, not at zero.
Rollout is staged by device cohort, not by time alone. A typical wave plan for 10 million devices:
| Wave | Devices | Purpose | Hold condition |
|---|---|---|---|
| --- | --- | --- | --- |
| 1% | 100,000 | Catch early boot failures | Boot success below 99.5% stops the wave |
| 10% | 1,000,000 | Catch hardware-revision issues | Failure rate above baseline for that revision |
| 50% | 5,000,000 | Main rollout | CDN error rate or rollback rate rises |
| 100% | 10,000,000 | Remainder, including long-offline devices | Devices check in over weeks, not hours |
Bandwidth is the constraint that decides chunking and delta updates. A full 512 KB image for 10 million devices is 5.12 TB of egress. A delta against the previous version, say 80 KB, drops that to about 800 GB. I would ship deltas for routine releases and keep a full image as fallback when the delta base version does not match. Devices with metered links get the delta only, and only when the application is idle.
Integrity, checked before any byte runs
Each chunk carries its own SHA-256. The device verifies a chunk as it lands in the inactive bank and marks it good in a bitmap stored in a separate flash sector. A bad chunk is refetched, not the whole image. After all chunks pass, the bootloader verifies the manifest signature before it will consider the slot bootable. On STM32 parts this sits on top of the hardware secure boot chain, so a signed image that fails verification never reaches the application entry point.
/* Bootloader check, run before jumping to the trial slot. */
int verify_slot(const manifest_t *m, const uint8_t *image, size_t len)
{
if (m->version <= installed_version) return -1; /* anti-rollback */
if (sha256(image, len, digest) != 0) return -1;
if (memcmp(digest, m->image_sha256, 32) != 0) return -1;
if (ecdsa_p256_verify(pubkey, m->manifest_hash, m->signature) != 0) return -1;
return 0;
}The anti-rollback check matters as much as the signature. Without it, an attacker who captures an old signed image with a known bug can replay it. The installed version lives in a monotonic counter the application cannot decrement, ideally backed by the STM32's secure storage or a monotonic HSEM-protected register. Signing keys stay in an HSM on the build server. The device holds only the public key, fused or in the bootloader.
Minimal downtime and safe rollback
With dual banks, the running application is never overwritten. The new image goes to the inactive bank. On first boot of the new slot, the bootloader sets a trial flag and starts the independent watchdog at a short timeout, for example 30 seconds. The new firmware must, inside that window, initialise its drivers, pass a self-test (flash CRC of its own config, sensor sanity check, network stack up), and write a confirm flag. If the watchdog fires or the self-test fails, the bootloader clears the trial flag and boots the old slot on the next reset. Downtime is one reset, roughly 200 ms on this class of part, not a reflash.
Two failure modes need explicit handling. Power loss during chunk write leaves a partially written chunk. The per-chunk hash catches it, and the bitmap never marked it good, so it is fetched again. Power loss during the trial boot is handled the same way: the trial flag is set before the jump, so an interrupted first boot still counts as unconfirmed and the old slot remains bootable. A device that never confirms and never rolls back, because it is stuck in a loop before the watchdog starts, is prevented by starting the watchdog in the bootloader, before the application runs.
What I would watch in production
Devices report back a small status record on next check-in: version installed, slot confirmed or rolled back, chunks refetched, and reset reason. A spike in rollbacks concentrated in one hardware revision points to a timing or driver bug in the new image, not to distribution. A spike in refetches points to a bad CDN edge or a flash wear issue. That telemetry is what lets the 1% wave mean something. Without it, staged rollout is just slow rollout.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15How would you architect a telemetry collection service that aggregates performance data from diverse hardware sensors while minimizing the impact on device power consumption?
Reported in STMicroelectronics Software Engineer Interview Questions
The 90-second answer
I would put one aggregator on the MCU, not a thread or task per sensor. Each sensor registers a descriptor: bus, address, conversion time, minimum sample period, unit and scale. A single scheduler wakes the part from the RTC or a sensor interrupt, reads only the sensors that are due, timestamps and packs the samples into a ring buffer, then returns the MCU to STOP2. Transmission is batched and aligned to that wake. On a battery device the wake, the sensor conversion and the radio dominate energy. Packing code in between costs almost nothing if it runs in milliseconds.
Assumptions I would state first: an STM32U5 class MCU, battery power, mixed I2C, SPI and UART sensors, and uplink over BLE or sub-GHz every 1 to 5 minutes. If the device is mains powered, I would sample faster and flush more often, because the trade-off changes.
How the pieces fit
The descriptor table is the portability layer. Adding a new sensor means adding a descriptor and a read function, not rewriting the scheduler. The scheduler keeps a next-due time per sensor and, on wake, computes the due set in one pass. Sensors that share a bus are read back to back so the bus and the MCU wake once for several conversions.
DMA matters for power, not just CPU load. The MCU can issue a transfer and sleep while the peripheral moves data, instead of staying awake in a polling loop. Interrupts are used for completion and for sensors that can only signal readiness, such as a data-ready pin. Polling a sensor every 100 ms to check a flag would keep the part out of STOP2 and defeat the design.
The ring buffer lives in SRAM that retains contents in STOP2. Samples are stored as fixed-size records with a monotonic millisecond timestamp from a timer that survives sleep, plus a sequence number. If the buffer fills before a radio window, the aggregator drops the oldest raw samples but keeps the per-window aggregates. That choice preserves trend data at the cost of raw resolution, which is the right loss for telemetry.
| Sensor class | Wake source | Sampling tactic | Power tactic |
|---|---|---|---|
| Slow environmental, 1 Hz or slower | RTC | Sample on the RTC tick, convert once | Long STOP2 intervals, batch uplink |
| Fast electrical, current or voltage | Timer or ADC trigger | Sample in a short burst, then aggregate | Burst then sleep, do not stream raw |
| Event driven, motion or switch | GPIO interrupt | Wake on event, debounce in hardware or with a timer | No periodic wake at all |
| Radio adjacent, RSSI or link quality | Radio stack callback | Read after each connection event | Piggyback on a transmission already paid for |
Worked power arithmetic, hypothetical figures
Take a 60 second cycle. Sensor conversion: 4 ms at 6 mA. MCU processing: 2 ms at 3 mA. Radio: 80 ms at 12 mA. Sleep: 60 s at 2 uA.
Charge per cycle is roughly 4 x 6 + 2 x 3 + 80 x 12 + 60000 x 0.002 = 24 + 6 + 960 + 120 = 1110 mA ms. Average current is 1110 / 60000 = 0.0185 mA, about 18.5 uA. The radio is 86 percent of the active charge. Polling the sensor every second instead would add 60 x 24 = 1440 mA ms per cycle and more than double the average, before any extra radio cost. That is why batching and aligned wakes come first, and why a faster MCU clock is a minor lever by comparison.
/* Checked against STM32U5 HAL style APIs, simplified */
#define RING_SIZE 256
typedef struct {
uint32_t t_ms;
uint16_t sensor_id;
int32_t value;
uint16_t seq;
} sample_t;
static sample_t ring[RING_SIZE];
static volatile uint16_t head, tail;
bool ring_push(sample_t s) {
uint16_t next = (head + 1) % RING_SIZE;
if (next == tail) return false; /* full: caller keeps aggregates only */
s.seq = next;
ring[head] = s;
head = next;
return true;
}Failure modes I would design for
An I2C sensor that holds SDA low will wedge the bus and every later read on that bus. Detection is a transfer timeout plus a bus-busy check. Recovery is a GPIO bit-bang clock sequence to release the bus, then a sensor reset, and the sensor is marked unhealthy after three failed cycles so the scheduler stops paying wake energy for it.
RTC drift and timer rollover corrupt timestamps if the code assumes a free-running counter. I would use a 32-bit millisecond counter with wrap-safe subtraction, and store both the device timestamp and a sequence number. The gateway can then order samples even when the device clock drifts by seconds over a long sleep.
A radio retry storm is the worst energy failure. If the gateway is unreachable, the firmware must back off exponentially, cap retries per wake, and stop transmitting until the next scheduled window. Without that cap, a device in a dead zone can drain a battery in days while trying to send a few hundred bytes.
Finally, sensor warm-up time is easy to miss. Some gas and particulate sensors need tens of seconds before a reading is valid. The descriptor carries a warm-up field, and the scheduler marks early samples as invalid instead of sending plausible-looking noise to the gateway.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Identify and fix the race condition in code that manages a buffer for incoming sensor data and occasionally crashes under high load?
Reported in STMicroelectronics Software Engineer Interview Questions
The 90-second answer
Assume the classic STM32 setup: a sensor ISR or DMA callback produces bytes, a task consumes them, and both share a ring buffer. The crash under load is almost never the buffer itself. It is the shared state between producer and consumer being read and written without a rule for who owns what.
The buggy pattern I would point to first is a shared count or a shared head/tail pair updated by both sides:
/* Buggy: checked against STM32F4, HAL, C11 */
#define N 256
static uint8_t buf[N];
static volatile uint16_t head, tail; /* ISR writes head, task writes tail */
static volatile uint16_t count; /* BOTH sides update count */
void Sensor_ISR(void) {
buf[head] = read_sensor();
head = (head + 1) % N;
count++; /* task may be mid count-- here */
}
void consume(void) {
if (count > 0) {
uint8_t b = buf[tail];
tail = (tail + 1) % N;
count--;
process(b);
}
}count++ in the ISR and count-- in the task is a read-modify-write on a 16-bit variable. On a Cortex-M4 it compiles to load, add, store. If the ISR fires between the load and the store in the task, one update is lost. Under light load the window is rarely hit. Under high load, with the ISR firing every 100 us, it is hit constantly. The count drifts from the real head-to-tail distance, the consumer reads stale or unwritten slots, or it reads past the tail and the system eventually HardFaults or feeds garbage to the control loop.
Worked trace
| Step | Task context | ISR context | count | Result |
|---|---|---|---|---|
| 1 | loads count = 5 | 5 | ||
| 2 | count++ : 5 to 6, stores 6 | 6 | ||
| 3 | decrements its stale copy: 5 to 4, stores 4 | 4 | one sample lost | |
| 4 | repeats | drifts low | consumer under-reads, then over-reads after wrap |
The fix is to give each index a single writer and make the other side read-only, or to protect the shared update.
/* Fixed: single producer, single consumer, no lock needed */
static volatile uint16_t head, tail;
void Sensor_ISR(void) {
uint16_t next = (head + 1) % N;
if (next == tail) { overrun++; return; } /* drop, do not overwrite */
buf[head] = read_sensor();
head = next; /* written last, after the data */
}
void consume(void) {
while (tail != head) {
uint8_t b = buf[tail];
tail = (tail + 1) % N;
process(b);
}
}Only the ISR writes head, only the task writes tail. Each side reads the other index as a snapshot. On Cortex-M, aligned 16-bit loads and stores are atomic, and volatile stops the compiler caching them. The data write must complete before head moves, which this ordering guarantees in practice for a single core. The explicit drop on full matters: overwriting unread data silently corrupts a frame, dropping and counting it lets you size the buffer.
When this is not enough
If more than one producer writes, for example two sensor ISRs or a DMA channel plus an ISR, the single-writer rule breaks. Then I would not add a hand-rolled lock around the buffer. On FreeRTOS I would use xQueueSendFromISR with a fixed-size queue, which already handles the critical section and wakes the consumer with portYIELD_FROM_ISR. On STM32 with a UART or SPI sensor at high throughput, I would move the producer to DMA in circular mode and read __HAL_DMA_GET_COUNTER to compute the write position, which removes the ISR from the data path entirely. A mutex is the wrong tool here because the ISR cannot take it.
How I would prove the fix
I would add an overrun counter and a high-water mark for occupancy, expose them over SWO or a debug UART, and run a soak test that floods the sensor at maximum rate while the consumer is artificially delayed. Before the fix, count disagrees with (head - tail + N) % N within seconds. After the fix, that invariant holds for hours and the only symptom under overload is a rising overrun counter, which tells me to enlarge the buffer or raise the consumer priority. I would also check the fault registers on the crash build: a BFAR pointing into buf confirms the out-of-bounds read rather than a stack overflow.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Implement a function to validate a sequence of state transitions for a hardware component, ensuring no illegal transitions occur based on a provided transition matrix?
Reported in STMicroelectronics Software Engineer Interview Questions
The 90-second answer
I would treat the transition matrix as the single source of truth, stored in flash as const, and validate each step with a bounds check before the lookup. The function takes the current state, the next state, and the matrix, and returns a status instead of silently accepting a bad transition. On a microcontroller that distinction matters, because a corrupted state variable should not be allowed to index memory out of bounds.
Assume N states numbered 0 to N-1, and the matrix is allowed[from][to]. For a peripheral such as a power controller or a CAN controller on an STM32, I would use a bitmask per state when N is small, since it fits in one register read and is easy to audit in a debugger.
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#define NUM_STATES 5u
typedef enum {
ST_IDLE = 0,
ST_READY,
ST_BUSY,
ST_ERROR,
ST_SLEEP
} state_t;
typedef enum {
TRANS_OK = 0,
TRANS_ILLEGAL,
TRANS_BAD_STATE,
TRANS_BAD_ARG
} trans_status_t;
/* Bit i of row s set means s -> i is legal. Stored in flash. */
static const uint32_t kAllowed[NUM_STATES] = {
[ST_IDLE] = (1u << ST_READY) | (1u << ST_SLEEP),
[ST_READY] = (1u << ST_BUSY) | (1u << ST_IDLE) | (1u << ST_SLEEP),
[ST_BUSY] = (1u << ST_READY) | (1u << ST_ERROR),
[ST_ERROR] = (1u << ST_IDLE),
[ST_SLEEP] = (1u << ST_IDLE)
};
trans_status_t validate_transition(state_t from, state_t to)
{
if ((uint32_t)from >= NUM_STATES || (uint32_t)to >= NUM_STATES) {
return TRANS_BAD_STATE;
}
return (kAllowed[from] & (1u << to)) ? TRANS_OK : TRANS_ILLEGAL;
}
trans_status_t validate_sequence(const state_t *seq, size_t len)
{
if (seq == NULL || len < 2u) {
return TRANS_BAD_ARG;
}
for (size_t i = 1u; i < len; i++) {
trans_status_t s = validate_transition(seq[i - 1u], seq[i]);
if (s != TRANS_OK) {
return s;
}
}
return TRANS_OK;
}That is O(len) time and O(1) extra space, with no allocation. The caller decides the policy on failure. In a test harness I return the status and log the index. In production firmware I would not just log an illegal transition from a safety relevant state machine. I would route it to the fault handler or a safe state, depending on the ASIL or IEC 61508 context for that product.
Worked trace
| Step | From | To | Lookup | Result |
|---|---|---|---|---|
| 1 | IDLE (0) | READY (1) | bit 1 in row 0 set | OK |
| 2 | READY (1) | BUSY (2) | bit 2 in row 1 set | OK |
| 3 | BUSY (2) | SLEEP (4) | bit 4 in row 2 clear | ILLEGAL |
| 4 | BUSY (2) | ERROR (3) | bit 3 in row 2 set | OK |
| 5 | ERROR (3) | IDLE (0) | bit 0 in row 3 set | OK |
The sequence IDLE, READY, BUSY, SLEEP fails at step 3, which is the point. The function stops there instead of continuing to validate a sequence that the hardware could never reach.
Choices and failure modes
| Representation | Cost | When I pick it |
|---|---|---|
bool allowed[N][N] | N squared bytes | N under about 32, clarity matters most |
uint32_t bitmask per row | N times 4 bytes | N up to 32, fast check, easy to dump |
| Sparse list of pairs | O(edges) search | N large, edges sparse, table generated from a spec |
For N above 32 I would switch to uint64_t rows or a generated sparse table, and I would generate the table from the same document that describes the hardware state diagram. Hand editing a matrix in two places is how a firmware state machine drifts from the datasheet.
Three failure modes come up in practice. First, a state value read from RAM or from a register is outside 0 to N-1 after a bit flip or a bad cast. The bounds check catches that before the array access. Second, the matrix is correct but the initial state is wrong, for example after a reset the code assumes READY while the peripheral is still in RESET. I validate the first state against the set of legal entry states separately, rather than assuming seq[0] is trustworthy. Third, a transition is legal in the matrix but illegal in the hardware at that moment, such as entering SLEEP while a DMA transfer is active. The matrix encodes the design intent. Runtime guards for DMA busy, clock status, or voltage rail readiness sit on top of it, and the validator is only the first gate.
In an interview I would also mention testing. I would generate the matrix from a Python or spreadsheet model, then run property tests over all N squared pairs on the host, and keep the same test vectors in the target test suite. That gives coverage of every legal and illegal edge without needing hardware in the loop for each case.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18What specifically draws you to the intersection of embedded software and hardware-level optimization in the semiconductor industry compared to pure software-as-a-service roles?
Reported in STMicroelectronics Software Engineer Interview Questions
The 90-second answer
I want the feedback loop to end at a register, not a dashboard. In a SaaS role I would ship a change, watch p99 move in a log, and iterate. In embedded work the same change has to survive a datasheet, a 64 KB RAM budget, and a battery that cannot be recharged. That constraint is what draws me in. When I cut a wake-up path from 12 ms to 900 us, or drop a node from 180 uA average to 42 uA, the effect is physical and measurable on a bench supply the same afternoon. I like that the software, the clock tree, and the peripheral state machine are one system I have to reason about together.
A concrete example from a sensor node I built on an STM32L4 (Cortex-M4 at 80 MHz, hypothetical figures from that project): the firmware polled an I2C sensor every 100 ms, woke the CPU fully, and averaged about 180 uA. Profiling showed the CPU spent most of that time waiting on the bus. I moved the transfer to DMA, let the CPU sleep in Sleep mode while the bus clocks kept running, and only entered Stop 2 after the transfer finished and the result was processed. Average current fell to roughly 42 uA, which on a 2,400 mAh cell moves projected life from about 1.5 years to over 6 years, before self-discharge dominates. That trade, code complexity against years of field life, is the kind of decision SaaS rarely forces.
| Change | Mechanism | Measured effect (hypothetical, that build) |
|---|---|---|
| Polling to DMA | CPU sleeps in Sleep mode during I2C transfer, bus clocks stay on | Wake latency 12 ms to under 1 ms |
| Stop 2 between samples | Clocks gated, SRAM retained, RTC wakes the node | Average current 180 uA to 42 uA |
| Fixed buffers, no heap in loop | No fragmentation, bounded stack | Worst-case stack use known, 1.8 KB of 8 KB |
The code pattern that made the difference was small:
/* STM32L4, checked against STM32CubeL4 HAL examples */
volatile uint8_t done = 0;
HAL_I2C_Mem_Read_DMA(&hi2c1, sensor_addr, reg, I2C_MEMADD_SIZE_8BIT,
buf, sizeof(buf));
__WFI(); /* Sleep mode: CPU clock gated, I2C and DMA clocks keep running */
/* HAL_I2C_MemRxCpltCallback sets done = 1 */
if (done) {
process(buf);
HAL_PWR_EnterSTOP2Mode(PWR_STOPENTRY_WFI, PWR_REGULATOR_VOLTAGE_1_7);
}What I would not claim
Hardware-level optimization is not always the right call. Every DMA channel, low-power mode, and clock switch adds a state to verify. Entering Stop 2 during an I2C transfer would stop the clocks the transfer needs, so the mode choice has to match the peripheral in use. A Stop 2 wake path that misses a UART byte because the USART clock was gated is a field failure, not a clever saving. I have learned to budget verification time for each mode transition and to keep a fallback polling path behind a compile-time flag during bring-up. If the optimization does not show up on the bench supply or the logic analyser, I drop it.
Why ST specifically
ST publishes the level I want to work at. The reference manual names the exact register, the errata sheet names the silicon revision it applies to, and STM32CubeMX plus the LL drivers let me generate a starting point and then read what was generated. That is a better fit for me than a closed module where the optimisation is hidden. I want to keep working where I can open the manual, find the bit, and defend why it is set the way it is.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19What are the tool models that you have used?
Reported in STMicroelectronics Engineer Interview (No Offer): Hiring manager first then HOD level interview
The 90-second answer
I treat "tool models" as two things: the toolchain I build and debug with, and the models I use before I write C. On STM32 work that has mostly been STM32CubeMX plus STM32CubeIDE, with Keil MDK and IAR Embedded Workbench on safety related projects, and Simulink with Stateflow for control and state logic. For debug I use ST-LINK GDB server, OpenOCD, Segger Ozone, and a logic analyser or oscilloscope when the fault is electrical rather than logical.
The split matters because the model decides what code I am allowed to hand write. If I generate peripheral init from CubeMX, I keep my code in the USER CODE sections and never edit generated files. If I model a motor controller in Simulink, I generate C with Embedded Coder and test that generated code on the target, rather than reimplementing the same logic by hand and hoping the two match.
| Tool | What I use it for | When I pick it | Limit I watch for |
|---|---|---|---|
| STM32CubeMX | Pin mux, clock tree, DMA, HAL init generation | New STM32 board bring up | Regeneration overwrites anything outside USER CODE sections |
STM32CubeIDE (GCC 12.2, arm-none-eabi-gcc) | Build, edit, ST-LINK debug | Day to day STM32 firmware | Eclipse builds get slow on large trees, optimisation flags must be explicit |
| Keil MDK / IAR EWARM | Compiler, linker, static analysis, safety qualified libraries | IEC 61508 or ISO 26262 work | Licence cost, different __attribute__ and pragma dialects |
| Simulink / Stateflow | Plant model, control law, state machine, MIL/SIL test | Motor control, power conversion, protocol state machines | Generated code needs a fixed point and stack audit before it goes on a 512 KB flash part |
| STM32CubeProgrammer, STM32CubeMonitor | Flashing, RTT and fault dump capture | Factory programming, field returns | RTT drops bytes above roughly 1 MB/s on a shared SWD link |
How I choose between them
For a bare metal STM32F4 sensor node (512 KB flash, 192 KB RAM), CubeIDE with -O2 and -ffunction-sections -Wl,--gc-sections was enough. Switching the same code to -Os saved about 9% flash in one build I measured, at a cost of roughly 6% more cycles in the filtering loop. That trade is fine for a logger and wrong for a 20 kHz current loop, so I set optimisation per file, not globally: -O2 for the control ISR, -Os for UI and logging.
For a safety project I moved the same peripheral code to IAR because the customer required a qualified compiler and MISRA checking in the IDE. The code did not change, but the linker map did. IAR placed .data differently and my startup file assumption about the load address broke. I caught it by comparing the .map files and checking __etext against the flash base in the linker script, not by reading source.
/* Checked against arm-none-eabi-gcc 12.2, STM32F407, -O2 */
/* Linker check I run after every toolchain switch */
#include <stdint.h>
extern uint32_t __etext; /* end of initialised data in flash */
#define FLASH_BASE 0x08000000u
#define FLASH_SIZE (512u * 1024u)
_Static_assert((uint32_t)&__etext > FLASH_BASE, "etext below flash");
_Static_assert((uint32_t)&__etext < FLASH_BASE + FLASH_SIZE, "image overflows flash");Modelling before coding
A concrete example: a state machine for a bootloader and application handoff. In Stateflow I could force the illegal transition, application jumps to bootloader while flash is being written, and see the guard fail in simulation in seconds. On hardware that same test needs a power supply, a debugger, and a spare board. The model did not replace hardware testing. It removed the class of bug that hardware testing finds slowly.
Failure modes I have hit with these tools
CubeMX clock generation is correct for the pins you set, but it will happily generate a 168 MHz SYSCLK with a UART baud rate that is off by 2% because the APB divider changed. I check the generated SystemClock_Config against the datasheet clock tree and measure the UART with a scope before blaming the driver.
GCC and IAR also disagree on volatile access to memory mapped registers in one case I worked on. Code that compiled to a single LDR under GCC generated a load, store pair under IAR after an optimisation pass, which broke a clear on read status register. The fix was a compiler barrier and a read of the generated assembly, not a source change that looked correct in review.
If I joined your team I would start with the existing CubeMX .ioc file and the current IDE, reproduce the build bit for bit, and only then propose a toolchain change. A new tool that saves 10% build time but invalidates the existing test evidence costs more than it saves.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20Explain the role of the linker script in embedded development?
Reported in Embedded C Interview Questions & Answers (2026)
The 90-second answer
The linker script tells ld how to turn relocatable object files into one loadable image for a specific chip. It defines where each section goes in memory, what address it runs at versus where it is stored, and which symbols the startup code and C runtime depend on. Without it, the compiler knows a function is 200 bytes, but nothing guarantees that function lands in Flash at 0x08000000, that .data is copied to SRAM at boot, or that the stack has room left.
On an STM32F407, for example, I would describe three jobs in one file: place the vector table and code in Flash, place initialized data in SRAM with a load image in Flash, and reserve space for stack and heap so they do not collide.
/* stm32f407.ld, GNU ld, checked with arm-none-eabi-gcc 13 */
ENTRY(Reset_Handler)
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K
SRAM (rwx) : ORIGIN = 0x20000000, LENGTH = 192K
CCM (rwx) : ORIGIN = 0x10000000, LENGTH = 64K
}
_estack = ORIGIN(SRAM) + LENGTH(SRAM);
_Min_Heap_Size = 0x2000;
_Min_Stack_Size = 0x400;
SECTIONS
{
.isr_vector :
{
KEEP(*(.isr_vector))
} > FLASH
.text :
{
*(.text*)
*(.rodata*)
} > FLASH
.data :
{
_sdata = .;
*(.data*)
_edata = .;
} > SRAM AT> FLASH
.bss (NOLOAD) :
{
_sbss = .;
*(.bss*)
*(COMMON)
_ebss = .;
} > SRAM
.ccmram :
{
*(.ccmram*)
} > CCM
.heap :
{
. += _Min_Heap_Size;
} > SRAM
.stack :
{
. += _Min_Stack_Size;
} > SRAM
/DISCARD/ : { *(.note*) *(.comment*) }
}> SRAM AT> FLASH is the line interviewers probe. .data runs from SRAM, so variables are writable, but its initial values must be stored in Flash. The linker sets the VMA in SRAM and the LMA in Flash. Reset_Handler in startup_stm32f407xx.s then copies _sdata to _edata from the LMA and zeroes .bss before main() runs. If that copy is missing or the symbols are misspelled, the program compiles and links, then starts with garbage globals.
What the script controls, section by section
| Section | VMA | LMA | Why it matters on STM32 |
|---|---|---|---|
.isr_vector | 0x08000000 | same | Cortex-M reads initial SP and Reset_Handler from here. Wrong address means HardFault on reset. |
.text, .rodata | Flash | same | Code and constants execute from Flash. |
.data | SRAM | Flash | Initialized globals. Needs the startup copy. |
.bss | SRAM | none | Zero-initialized globals. NOLOAD keeps them out of the binary. |
.ccmram | 0x10000000 | Flash if initialized | Tightly coupled RAM on F4, no wait states, good for ISRs or DMA buffers that must stay resident. |
.heap, .stack | end of SRAM | none | Prevents silent overlap with .bss. |
I check the result with arm-none-eabi-objdump -h firmware.elf and the .map file, not by trusting the script. A typical check: .text at 0x0800xxxx with size 0x1A3C0, .data VMA 0x20000000 LMA 0x081A3C0, _estack at 0x20030000. If .data LMA overlaps .text, the copy at boot corrupts code.
Failure modes I have seen
Stack and heap collision. The default _estack at the top of SRAM looks fine until a deep call chain plus an ISR pushes the stack into .bss. Detection: fill the stack region with 0xA5 at boot and inspect how far the watermark moved, or set a guard variable after .bss and check it in a fault handler. Fix: reserve .stack explicitly and move _estack accordingly, as above.
Orphan sections. A library puts code in .init_array or a custom section like .ccmram that the script never mentions. GNU ld places orphans by heuristic, often in Flash, and the function runs slower or the DMA buffer lands in a region the DMA cannot reach. Detection: search the map file for the section name. Fix: name it in SECTIONS or discard it deliberately.
Linker script out of sync with the chip. Changing from STM32F407 (512K Flash, 192K SRAM) to STM32F401 (256K Flash, 96K SRAM) without updating MEMORY gives a clean link and a device that fails to boot past the vector table. Detection: compare MEMORY against the datasheet memory map and run arm-none-eabi-size against both limits in CI. Fix: generate the script from the CubeMX or ST linker template for the exact part, then diff it.
Bootloader offset. When a bootloader occupies the first 32K of Flash, the application vector table must start at 0x08008000, not 0x08000000. That needs ORIGIN = 0x08008000 for Flash in the application script and SCB->VTOR set to that address early in SystemInit(). Forgetting VTOR leaves interrupts pointing at the bootloader table.
The script is also where I would put a ASSERT() check. For example, ASSERT(. <= _estack - _Min_Stack_Size, "SRAM overflow") turns a silent overlap into a build failure, which is the only place it is cheap to catch.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21Explain the difference between static and dynamic memory allocation in embedded C?
Reported in Embedded C Interview Questions & Answers (2026)
The 90-second answer
Static allocation reserves memory at compile or load time and the address is known before the program runs. Dynamic allocation asks the heap for memory at runtime with malloc and returns it with free. On a microcontroller that distinction is mostly about determinism and failure mode. Static memory cannot fragment and its cost is visible in the linker map. Dynamic memory can fail at any call, its timing depends on heap state, and a fragmented heap can fail even when total free bytes look sufficient.
In embedded C I default to static allocation for anything with a fixed upper bound, which is most buffers, queues and driver state. I use dynamic allocation only when the size genuinely varies and the caller can handle NULL, for example parsing a variable length configuration record on a gateway class STM32H7 with megabytes of SRAM. On a small STM32F1 or STM32L0 I would avoid the heap entirely.
Where each one lives
Static objects declared at file scope, or with static, and globals, go in .bss if uninitialised or .data if initialised. The linker script places those sections in SRAM and the size is fixed in the .map file. A local array inside a function is different. It lives on the stack, which on STM32Cube is sized in the startup file and grows down from _estack. That is still static in the sense that no heap is involved, but its lifetime ends when the function returns and deep call chains can overflow it silently.
Dynamic allocation uses the heap managed by the C library. With STM32Cube and newlib, malloc eventually calls _sbrk, implemented in sysmem.c. That implementation moves a heap end pointer upward and fails when it would cross the current stack pointer, which is bounded by _estack at the top of SRAM. There is no _heap_size symbol in sysmem.c to tune. The linker script symbol _Min_Heap_Size is a reservation check, it asserts at link time that at least that much heap space remains between the static sections and the stack, it does not cap the heap. The heap can therefore grow until it meets the stack, which is why heap and stack sizing have to be reviewed together.
/* Checked against GCC 12 / STM32Cube for STM32F4, C11 */
#include <stdint.h>
#include <stdlib.h>
#define RX_BUF_SIZE 256u
static uint8_t rx_buf[RX_BUF_SIZE]; /* .bss, fixed cost, no fragmentation */
typedef struct {
uint8_t *data;
uint16_t len;
} packet_t;
int packet_init(packet_t *p, uint16_t len)
{
if (len == 0u || len > RX_BUF_SIZE) {
return -1;
}
p->data = (uint8_t *)malloc(len); /* heap, runtime size */
if (p->data == NULL) {
return -1; /* caller must handle this path */
}
p->len = len;
return 0;
}
void packet_release(packet_t *p)
{
free(p->data);
p->data = NULL;
p->len = 0u;
}Comparison that matters in review
| Property | Static (.bss / .data / stack) | Dynamic (heap) |
|---|---|---|
| Address known | At link time for globals, at call time for stack | Only after a successful malloc |
| Size | Fixed at compile time | Chosen at runtime |
| Fragmentation | None | Yes, free blocks split and coalesce imperfectly |
| Worst case time | Constant for the allocation itself | Depends on heap state and free list search |
| Failure mode | Link fails if SRAM is exceeded, stack overflow corrupts adjacent memory | malloc returns NULL, or heap metadata corruption |
| Cost visibility | .map file, size output | Runtime watermark only, easy to underestimate |
Failure mode I would name in the interview
Fragmentation is the one candidates understate. Take a 4 KB heap made of 16 repeating pairs of a 128 byte allocated block and a 128 byte free block. That is 16 x 256 bytes = 4096 bytes in total, with 16 x 128 bytes = 2048 bytes free. The largest contiguous free block is still only 128 bytes, so a later malloc(256) fails despite 2 KB being free in total. I have seen this on a sensor node where a telemetry task allocated a packet, sent it, and freed it in a loop. After hours the allocation started failing intermittently. The fix was a static pool of fixed size packets, which also removed the NULL check from the hot path.
Detection is concrete. Track heap usage with xPortGetFreeHeapSize in FreeRTOS or by wrapping malloc and free to record high water mark and failure count. Check stack usage with stack fill patterns or uxTaskGetStackHighWaterMark. In a linker map review, compare .bss plus .data plus heap plus stack against the SRAM size in the device datasheet, leaving margin for interrupt stacks, which on Cortex-M share the main stack.
When dynamic is defensible
Use it when the number or size of objects is data driven and bounded by a protocol limit I can enforce, when the allocation happens during initialisation rather than in an ISR or control loop, and when every malloc result is checked and freed on all error paths. Avoid it in interrupt handlers, in hard real time tasks with a deadline under a millisecond, and in code headed for safety certification where a fixed memory map is far easier to argue about. That is the trade I would defend at STMicroelectronics: static by default, dynamic as a deliberate exception with a measured heap budget.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: