Embedded Interview Questions


1. Why to use a volatile designator for a variable?

 The volatile keyword is one of the most important concepts in embedded C, and using it incorrectly is a top cause of "impossible to find" bugs in STM32 projects.

In your capacitance meter, variables like capture_done are updated inside an Interrupt Service Routine (ISR)—specifically the HAL_ADC_LevelOutOfWindowCallback—but read in your main loop.

1. The "Smart" Compiler Problem

Compilers are designed to make your code as fast as possible. If a variable is checked in a loop but never modified inside that loop, the compiler assumes its value will never change.

Without volatile:

The compiler looks at your while(!capture_done); loop and thinks: "I see that capture_done is 0. Nothing in this loop changes it to 1. Therefore, I will just load the value '0' into a CPU register once and check that register forever."

Even when your interrupt actually changes capture_done to 1 in the background memory, the CPU keeps checking its local register (which still says 0), and your program hangs forever.

2. What volatile tells the Compiler

By adding volatile, you are giving a direct command to the compiler:

"Hey! Do not trust your local copy of this variable. Something outside your normal view (like an interrupt or hardware) can change this value at any microsecond. Every single time you want to check it, you MUST go and read it fresh from the actual RAM."

3. When must you use it?

In your STM32 projects, always use volatile for:

  1. Shared Flags: Any variable modified in a callback/interrupt and read in the while(1) loop (like capture_done).

  2. Hardware Registers: All the STM32 peripheral registers (like IDR, ODR, CNT) are defined as volatile in the HAL drivers because the hardware can change them independently of your code.

  3. Global Buffer Indexes: If you use a variable to track how many bytes have arrived in a UART interrupt.

Summary Example

Code VersionCompiler BehaviorResult
uint8_t capture_done = 0;Caches the value 0 in a register.Loop hangs even after interrupt.
volatile uint8_t capture_done = 0;Re-reads from RAM every loop cycle.Loop exits correctly when interrupt fires.
2. What many bits long variable is in stm32?
Ans: 32 bit. We can uint32_t also for that.

Comments

Popular posts from this blog

HackRF with srsLTE and openlte

Blinking a LED in STM32F103C8T6 (Blue Pill) Board

Read Continuously from Serial Port in QT