Embedded C interview questions and answers

Embedded C interview questions and answers

A Comprehensive Guide to Embedded C Interview Questions for Microcontroller Systems

Welcome to this detailed guide on Embedded C interview questions, tailored specifically for microcontroller systems! Whether you’re preparing for a job interview or looking to deepen your understanding of Embedded C, this blog post covers key concepts across fundamentals, memory handling, interrupts, communication protocols, RTOS, and advanced topics like optimization and debugging. Let’s dive into the world of Embedded C programming for microcontrollers.


Embedded C Fundamentals

What is the difference between C and Embedded C?
C is a general-purpose programming language, while Embedded C is tailored for programming microcontrollers. Embedded C includes features like direct hardware access, I/O register manipulation, and real-time constraints.

What are the essential features of Embedded C?
Embedded C supports fixed-point arithmetic, bit manipulation, real-time performance, and hardware-level access via memory-mapped I/O.

What are volatile variables and why are they used?
A volatile variable tells the compiler not to optimize reads/writes to it, as its value may change unexpectedly (e.g., via ISR or hardware registers).

What is the size of an int in Embedded C?
The size of an int is platform-dependent. On most 8-bit microcontrollers, an int is 16 bits (2 bytes).

How is a typedef used in Embedded C?
It helps define new data types or simplify complex declarations. For example:

What are bitwise operators and why are they important?
They allow manipulation of individual bits—critical in embedded systems for setting/clearing control bits. Example:

PORTA |= (1 << PA0); // Set bit PA0

What is the use of const with pointers in Embedded C?
It specifies immutability of data or address. Examples:

const int *p; // pointer to constant int

int *const p; // constant pointer to int

What are the different memory areas in Embedded C?
Embedded C uses memory areas like Code (Flash/ROM), Data (RAM – initialized), BSS (RAM – uninitialized), Stack, and Heap (if dynamic memory is used).

Why is the main() function needed in Embedded C?
It serves as the starting point for program execution, though in embedded systems, it often ends with an infinite loop.

What is an infinite loop and why is it used in embedded programs?
An infinite loop, like this:

while(1) { /* Task */ }

is used to continuously monitor/control the hardware.


Pointers & Memory Handling

What is a pointer in C?
A pointer is a variable that holds the address of another variable. Example:

int a = 10;

int *p = &a;

What is a NULL pointer?
A pointer that does not point to any valid memory location. It’s used to indicate the pointer is not initialized or intentionally empty. Example:

int *p = NULL;

What is a wild pointer?
A pointer that has not been initialized. It points to an unknown memory location and can lead to unpredictable behavior.

How do you pass a pointer to a function?
You can pass a pointer to a function like this:

void updateValue(int *p) { *p = 10; }

What is the difference between ptr++ and (ptr)++?

*ptr++ increments the pointer after dereferencing, while (*ptr)++ increments the value at the pointer.

Can a pointer point to a constant?
Yes, using const in the declaration:

const int *ptr; // pointer to constant integer

What is pointer arithmetic?
It allows movement across memory locations using arithmetic operations on pointers (e.g., ptr++, ptr–).

What is a function pointer and how is it used?
A pointer that points to a function instead of data. Example:

void (*func_ptr)(void) = myFunction;

How do arrays and pointers relate in C?
An array name acts like a pointer to its first element. Example:

int arr[3] = {1,2,3};

int *p = arr;

What is the use of sizeof operator with pointers?
It returns the size of the pointer, not the data it points to.

How is dynamic memory allocated in Embedded C?
Using malloc, calloc, and free. However, its use is discouraged in resource-constrained embedded systems.

Why is dynamic memory allocation risky in embedded systems?
It can cause memory fragmentation and unpredictable heap usage, which are problematic in real-time environments.

How do you free dynamically allocated memory?
Using free(ptr).

What happens if free() is called twice on the same pointer?
It causes undefined behavior and may crash the program (double free).

How do you avoid memory leaks in embedded C?
Always deallocate memory when no longer needed and avoid unnecessary dynamic allocations.

What is a dangling pointer?
A pointer that points to a memory location that has been freed.

How to check if memory allocation failed?
Check if malloc() returns NULL. Example:

if(ptr == NULL) { /* Handle error */ }

What is memory alignment and why is it important?
It refers to storing data in memory at addresses that are multiples of word size. Misalignment can cause performance degradation or faults.

What is a memory map in embedded systems?
A layout showing how memory is divided—code, data, stack, peripherals, etc.

Can you use recursion in Embedded C?
Technically yes, but it’s generally discouraged due to limited stack size.


Interrupts, Timers, and ISRs

What is an interrupt?
An interrupt is a signal to the processor indicating that an event needs immediate attention, temporarily halting the current execution flow.

What is an ISR?
ISR (Interrupt Service Routine) is a special function executed in response to an interrupt. It should be fast and efficient.

Can ISRs be recursive?
No. Recursion in ISRs is highly discouraged and usually unsupported because stack usage must be minimal.

What should you avoid inside an ISR?
Avoid blocking calls, delays, long processing, printing (e.g., printf), and re-enabling global interrupts (unless nested interrupts are needed).

How do you write an ISR in Embedded C?
It’s platform/compiler-specific. Example:

void __interrupt() ISR_Handler(void) { /* code */ }

How are interrupts enabled/disabled globally?
For GCC (ARM): __disable_irq(); and __enable_irq();. For AVR: cli(); and sei();.

What is interrupt latency?
The time from when an interrupt is triggered to when the ISR starts executing. Lower latency is better for real-time systems.

What is interrupt nesting?
Allowing higher-priority interrupts to interrupt the current ISR. Requires careful handling to prevent corruption.

What is a timer in embedded systems?
A peripheral that counts clock pulses and can be configured to generate periodic interrupts for timekeeping or task scheduling.

How can you implement a software delay using timers?
Configure a timer to overflow after a specific period and count the number of overflows.

What’s the difference between a polling method and an interrupt method?
Polling actively checks a condition in a loop, while an interrupt passively waits until the condition occurs. Interrupts are more efficient.

How do you debounce a button using a timer ISR?
Start a timer when the button is pressed and confirm the button state after a short delay in the timer ISR.

Can you use delay functions inside ISRs?
No. ISRs should be as fast as possible and must avoid delays.

What are vectored and non-vectored interrupts?
Vectored interrupts have a fixed memory location, while non-vectored require the ISR address to be determined during execution.

What is a watchdog timer?
A hardware timer that resets the system if the software hangs. It must be periodically reset to avoid a system reset.

How do you reset a watchdog timer?
Use a special instruction or register write (e.g., WDT_RESET(); or write to a key register).

Can you nest interrupts in ARM Cortex-M?
Yes, Cortex-M supports nested interrupts via the NVIC and configurable priorities.

What happens if an interrupt occurs during ISR execution?
If global interrupts are disabled, it waits. If enabled and nested interrupts are supported, a higher-priority ISR can preempt.

What is ISR reentrancy?
An ISR is reentrant if it can be safely called again before its previous execution completes. Typically avoided in embedded systems.

What is a spurious interrupt?
An interrupt that occurs without a legitimate source, often due to electrical noise or incorrect configuration.


Communication Protocols (UART, I2C, SPI, CAN)

What is UART and how does it work?
UART (Universal Asynchronous Receiver/Transmitter) is a serial communication protocol using two lines: TX and RX. It transmits data bit by bit asynchronously.

What is baud rate in UART?
Baud rate is the speed of data transmission, measured in bits per second (bps). Both sender and receiver must use the same baud rate.

How do you detect a framing error in UART?
Most microcontrollers provide a status register flag indicating if the stop bit is missing or incorrect.

What is the purpose of start and stop bits in UART?
Start and stop bits frame each data byte, indicating the beginning and end of transmission.

What is I2C and its main features?
I2C (Inter-Integrated Circuit) is a two-wire, multi-master, serial communication protocol using SDA (data) and SCL (clock) lines. It supports multiple slaves and masters.

What are the possible modes in I2C?
Master Transmit, Master Receive, Slave Transmit, and Slave Receive.

How is addressing handled in I2C?
Each slave has a unique 7-bit or 10-bit address. The master initiates communication using this address.

What is clock stretching in I2C?
It allows a slave device to hold the SCL line low to delay the master, giving the slave more time to process data.

What is SPI and how is it different from I2C?
SPI (Serial Peripheral Interface) uses four lines: MOSI, MISO, SCLK, and SS. It supports full-duplex communication and is faster but requires more wires.

What are the main SPI modes?
Defined by CPOL (clock polarity) and CPHA (clock phase), there are four SPI modes: Mode 0 to Mode 3.

How is SPI data transmitted?
Data is shifted in/out simultaneously between master and slave with each clock pulse.

What is full-duplex and half-duplex communication?
Full-duplex allows simultaneous transmit and receive (e.g., SPI), while half-duplex allows transmit or receive, not both (e.g., UART).

What is a slave select (SS) pin in SPI?
It enables the targeted slave device. When pulled low, it selects that slave for communication.

How does SPI handle multiple slaves?
The master uses separate SS lines for each slave or a daisy-chaining technique.

What is CAN bus?
CAN (Controller Area Network) is a robust, multi-master protocol for automotive and industrial systems, supporting message arbitration and error checking.

What is the speed of CAN communication?
Standard CAN supports up to 1 Mbps. CAN FD supports faster data rates for payload transmission.

What is message arbitration in CAN?
When two nodes transmit simultaneously, the message with the highest priority (lowest ID) wins without data collision.

What are the main frame types in CAN?
Data Frame, Remote Frame, Error Frame, and Overload Frame.

What is the difference between standard and extended CAN frame?
Standard CAN uses an 11-bit identifier, while extended CAN uses a 29-bit identifier.

What is ACK in CAN communication?
Acknowledgment (ACK) is sent by receivers to confirm successful reception of a message.


Embedded System Programming Concepts (RTOS, Multitasking, Critical Sections)

What is an RTOS?
An RTOS (Real-Time Operating System) manages task scheduling and timing guarantees in real-time embedded systems.

What is the difference between a process and a thread?
A process is an independent execution unit with its own memory, while a thread is a lightweight unit within a process that shares memory.

What is a task in an RTOS?
A task is an independent thread of execution managed by the RTOS scheduler.

What is context switching?
It’s the process of storing a task’s state and loading another’s, allowing multitasking.

What is task priority in RTOS?
It determines the order of execution. Higher-priority tasks preempt lower ones.

What is a critical section in Embedded C?
A code segment that must not be interrupted. Interrupts are usually disabled during execution.

How do you protect a critical section?
Example:

__disable_irq();

// critical code

__enable_irq();

What is a semaphore?
A synchronization tool used to manage resource sharing and prevent race conditions.

What’s the difference between binary and counting semaphore?
A binary semaphore is either 0 or 1, acting like a lock. A counting semaphore manages multiple instances of a resource.

What is a mutex?
A mutual exclusion object to prevent simultaneous access to a shared resource, with ownership.

What is a deadlock?
A situation where tasks are waiting indefinitely for resources held by each other.

What is task starvation?
When a low-priority task never gets CPU time due to constant preemption by higher-priority tasks.

What is a watchdog task in an RTOS?
A task that monitors other tasks to ensure they are executing properly.

What is round-robin scheduling?
A scheduling technique where tasks are assigned equal CPU time slices in a cyclic order.

What is cooperative multitasking?
Tasks must voluntarily yield control back to the scheduler.

What is preemptive multitasking?
The scheduler interrupts and switches tasks based on priority or timing.

What is inter-task communication?
It refers to data exchange mechanisms like queues, semaphores, and message passing between tasks.

What is a real-time constraint?
A system requirement that operations must complete within a guaranteed timeframe.

What is priority inversion?
A lower-priority task holds a resource needed by a higher-priority task, blocking it.

How is priority inversion handled?
Using priority inheritance, where the lower-priority task temporarily inherits the higher priority.


Advanced Embedded C Concepts (Optimization, Bit Manipulation, Debugging)

What is bit manipulation in Embedded C?
Directly working with bits using bitwise operators (&, |, ^, ~, <<, >>) to control hardware registers or flags efficiently.

How do you set a specific bit in a register?
Example:

reg |= (1 << bit_position);

How do you clear a specific bit?
Example:

reg &= ~(1 << bit_position);

How do you toggle a bit?
Example:

reg ^= (1 << bit_position);

How do you check if a bit is set?
Example:

if (reg & (1 << bit_position)) { /* bit is set */ }

What are volatile variables in Embedded C?
The volatile keyword prevents the compiler from optimizing the variable, ensuring it reads from memory every time. Used in ISRs and hardware registers.

What is the use of the const keyword in embedded?
It ensures a variable’s value cannot be modified after initialization. Useful for ROM constants.

What is an inline function and its benefit?
An inline function replaces the call with the actual code to avoid function call overhead.

What is the difference between a macro and an inline function?
A macro is preprocessor-based with no type checking, while an inline function is compiler-handled and type-safe.

What are memory sections in embedded systems?
Divisions like .text (code), .data (initialized variables), .bss (zero-initialized), .stack, and .heap.

What is a linker script?
It controls the memory layout in embedded applications by placing code and data in specific memory regions.

What is startup code in embedded systems?
Assembly/C code that initializes hardware, stack, memory, and jumps to main().

What are map files used for?
They show the memory layout and symbols after linking, useful for debugging and optimization.

What is the use of assert() in embedded C?
To validate assumptions at runtime. Typically disabled in production builds.

What is cross-compilation?
Compiling code on one platform (host) for another (target). Essential for embedded development.

What is memory-mapped I/O?
A technique where I/O devices are accessed like memory using specific addresses.

How do you debug embedded C applications?
Using tools like JTAG/SWD debuggers, breakpoints, watchpoints, UART logs, or an oscilloscope for signals.

What is a breakpoint?
A pause inserted in code to inspect the program state during debugging.

What is stack overflow in embedded?
When a program uses more stack memory than allocated, potentially corrupting memory.

What are common causes of embedded system crashes?
Stack overflow, null pointer dereference, ISR misconfiguration, infinite loops, and misuse of volatile.


Conclusion

This guide has covered Embedded C interview questions, focusing on microcontroller systems—from fundamentals to advanced debugging techniques. Whether you’re working with interrupts, communication protocols like UART or SPI, or optimizing code for an RTOS, these concepts are crucial for success in embedded systems programming. Keep practicing, and you’ll be well-prepared for your next interview or project!

Leave a Reply

Your email address will not be published. Required fields are marked *