1.What is an embedded system, and how does it differ from a general-purpose computer?
-answer: NA
Can you explain the difference between microcontrollers and microprocessors?
-answer: NA
2.Programming Skills:
a. Which programming languages are commonly used in embedded systems development, and what are their advantages and disadvantages?
-answer: C programming language, and assembly language
b. How would you optimize code for memory-constrained environments in embedded systems?
answer:
. Enable compiler optimization flags,for size optimization.
. To minimize the use of constants, for example:
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // Initializes first 10 elements,
///use the below code instead to save flash.
int a[10];
for (i = 0 ; i < 20; i++)
{
a[i] = i;
}
. Conditional Compilation (#ifdef, #ifndef)
. Minimize or avoid dynamic memory allocation (malloc, free) to prevent fragmentation
. Use static or stack-based memory allocation where possible.
. Store read-only data in flash memory rather than RAM when applicable.
. Consider using bit-fields for boolean flags to save space.
. Use data types that consume less memory when possible (e.g., uint8_t instead of int).
3.RTOS (Real-Time Operating System):
What is an RTOS, and when would you choose to use one in an embedded system?
-answer: NA
Can you name some popular RTOSs, and what factors would you consider when selecting one for a project?
-answer:
. FreeRTOS
real-time operating system
. μC/OS
Real-time operating systems
. embOS
A real-time operating system developed by SEGGER Microcontroller. It is known for its small footprint and fast context switching.
. MQX
a real-time operating system (RTOS) developed by NXP.
4.Interrupt Handling:
Explain the concept of interrupts in embedded systems.
How would you prioritize and handle multiple interrupts in a system?
What is interrupt latency? How can you reduce it?
Interrupt latency is the time it takes to return from the interrupt service function after handling a given interrupt.
5.Communication Protocols:
Briefly describe common communication protocols used in embedded systems (e.g., SPI, I2C, UART,CAN,ZigBee, BLE, Wi-Fi)?
-answer:
SPI:
. Involves four signals: MISO (Master In Slave Out), MOSI (Master Out Slave In), SCLK (Serial Clock), and SS/CS (Slave Select/Chip Select).
. Typically used for short-distance communication within a circuit board.
. Supports high data transfer rates (typically 10 Mbps.).
. Used for communication with sensors, displays, memory devices, and other peripherals.s.
I2C :
.speed: 400khz,(fast mode)
. waveform diagram- refer to the picture below,
. hw- Actual values for pull-up resistance used: 2.2Kohms ,Typical values :2.2k to 10k ohms
. the max number of devices :128(7-bi adress bit.)) ,
. the data could be transmission only SCL is low, because the DATA transmission
. when SCL is high, indicates it is a START or STOP condition.
. Uses two wires: SDA (Serial Data) and SCL (Serial Clock).
. Supports multiple devices on the same bus with unique addresses.
. Suited for moderate-speed communication.
. Commonly used for connecting sensors, EEPROMs, and other low to moderate-speed peripheral
UART:
.Involves two signals: TX (Transmit) and RX (Receive).
.No clock signal; timing is agreed upon by both communicating devices.
.Well-suited for longer-distance communication.
.Used for communication between microcontrollers, modules, and devices such as .GPS receivers and Bluetooth modules.
CAN:
. Differential signaling for noise immunity.
. Supports multiple nodes on the same bus.
. Built for reliability in noisy environments.
. Commonly used in automotive systems, industrial automation, and other . applications requiring real-time communication.
CAN Bus Explained — A Simple Intro [2023] — CSS Electronics
ZigBee:
. Utilizes low power, making it suitable for battery-operated devices.
. Supports mesh networking, allowing devices to relay messages through the network.
. Typically used in applications like home automation, industrial control systems, and wireless sensor networks.
BLE:
. Optimized for intermittent data transmission, making it energy-efficient.
. Commonly used in applications like wearables, health devices, and IoT (Internet of Things) devices for short-range communication.
Wi-Fi:
. High data rates suitable for applications requiring fast and reliable data transfer.
. Longer communication range compared to Zigbee and BLE.
. Used for internet connectivity in embedded systems, smart devices, and applications where high bandwidth is essential.
. When would you choose one communication protocol over another, and what are the trade-offs?
Answer:
. Data Transfer Rate
-High Data: Rate-Wi-Fi,
-Low to Moderate Data Rate:Zigbee and BLE)
. Power Consumption
-low-power operation:Zigbee and BLE
-Higher Power: Wi-Fi
. Communication Range:
-short-range communication: Zigbee and BLE
-Longer Range:Wi-Fi
. Application Specifics:
-internet connectivity: Wi-Fi
. Cost
6.Memory Management:
How do you manage memory in embedded systems with limited resources?
Can you explain the difference between stack and heap memory?
Answer:
1.Heap:
.brief description:
-used for dynamic memory allocation during runtime, is suitable for managing dynamic data structures like arrays, linked lists, and objects,use the function OS_HEAP_malloc, OS_HEAP_free.
void HPTask(void) {
OS_U32* p;
while (1) {
p = (OS_U32*)OS_HEAP_malloc(4);
*p = 42;
OS_HEAP_free(p);
}
}
. advantage:
-Flexibility for managing variable-sized data structures.
-Efficient use of memory.
Considerations(risk):
- memory leak -embedded device fails to release dynamically allocated memory properly.
- memory fragmentation
2. stack:
. used for managing function calls and local variables.
-risk: stack overflow
. solution:
-Size Determination;
-Stack Overflow Protection and monitoring,
-long-duration test and stress test.
. Considerations:
-Limited flexibility
static OS_STACKPTR int Stack[128]; // Task stack
static OS_TASK TCB; // Task control block
static OS_SEMAPHORE Sema; // Semaphore
static OS_TIMER Timer; // Timer to emulate interrupt
static void Task(void) {
while(1) {
OS_SEMAPHORE_TakeBlocked(&Sema); // Wait for signaling of received data
printf("Task is processing data\n"); // Act on received data
}
...
OS_TASK_CREATE(&TCB, "Task", 100, Task, Stack);
...
7.Debugging and Testing:
. What debugging tools and techniques do you use for embedded systems development?
-answer:
. Integrated Development Environments (IDEs)
. Oscilloscopes
. Serial Debugging (printf debugging)
. In-Circuit Emulators (ICE)
How would you approach testing and debugging in a real-time embedded system?
-answer: NA
8.Power Management:
What are some power management techniques used in battery-powered embedded systems? or How would you optimize power consumption in an embedded device?
-Answer:
. Low-Power Modes.
. Dynamic Voltage and Frequency Scaling (DVFS)
. Disable or selectively activate peripheral devices when they are not in use.
. Disable clock signals to specific modules or components when they are not needed.
. Adjust the supply voltage based on the specific requirements of the running application.
. Activate the system periodically and spend the majority of time in a low-power sleep state.
. Monitor and manage the operating temperature to optimize power consumption
. Advanced Algorithms.
9.Security:
Discuss the importance of security in embedded systems. What are some common security threats, and how can they be mitigated?
10.Can you explain the difference between a mutex and a semaphore, and the characteristics of a mutex and a semaphore?
Semaphores or mutexes cannot be used to interrupt context. Spinlocks, however, can be used to lock in an interrupt context.
Differences:
Mutual Exclusion:
. A mutex ensures exclusive access to a resource (only one thread at a time).
. A semaphore allows controlled access to a resource (multiple threads within the specified limit).
Operations:
. A mutex has lock and unlock operations.
#include "RTOS.h"
#include <stdio.h>
static OS_MUTEX _Mutex;
...
OS_MUTEX_Create(&_Mutex); // Creates a mutex.
...
OS_MUTEX_LockBlocked(&_Mutex); // Claims a mutex and blocks it for other tasks.
...
OS_MUTEX_Unlock(&_Mutex); // Releases a mutex currently in use by a task.
...
OS_MUTEX_Delete(&_Mutex); // Deletes a specified mutex. The memory of that mutex may be reused for other purposes
or may be used for creating another mutex using the same memory.
...
. A semaphore has wait § and signal (V) operations.
#include "RTOS.h"
#include <stdio.h>
static OS_SEMA _Sema;
...
OS_SEMAPHORE_Create(&_Sema, 8); // Creates a semaphore with a specified initial count value.
...
OS_SEMAPHORE_TakeBlocked(&_Sema); // waitand Decrements the counter of a semaphore.
...
OS_SEMAPHORE_GiveMax(&_Sema, 8); // Increments the counter of a semaphore up to a specified maximum value.
...
OS_SEMAPHORE_Delete(&_Sema); // Deletes a semaphore.
...
11.What is a reentrant function?
What is a reentrant function?
When the execution of a function is suspended in the middle and resumed without risk, we say that the function is reentrant. Both external events and signals, as well as internal signals, such as a call or a leap, can serve as interruptions. Execution of the reentrant function picks up just where it left off and continues until it’s done.
12.What is the use of volatile keywords?
The volatile keyword is primarily used to stop compilers from optimizing variables that might unpredictably change their behavior after the optimization.
13.loop
Which loop is better: one that counts up from zero or one that counts down to zero?
Count-down to zero loops is preferable over count-up loops. The compiler can better optimize the comparison to zero when the loop finishes running. The improvement frees CPU resources by eliminating the requirement to simultaneously load the loop variable and compare the maximum value. Therefore, it is usually preferable to use a countdown loop that ends in 0.
#include <stdint.h>
int main() {
for (int64_t i=0; i<100000000ll; ++i) {
asm("nop");
}
}
#include <stdint.h>
int main() {
for (int64_t i=100000000ll; i!=0; --i) {
asm("nop");
}
}
/*
Let’s run it and benchmark:
$ perf stat -r 100 -d ./count_up
...
0.440219748 seconds time elapsed ( +- 0.73% )
$ perf stat -r 100 -d ./count_down
*/
...
0.440001691 seconds time elapsed ( ± 0.68% )
14.pointer
In Embedded C, what do you mean by a null pointer?
A null pointer is an invalid reference to a memory address. It guarantees that the invalid pointer cannot be used to make any changes. The pointer is considered “NULL” if it does not have an associated address.
15.storage classes
What do you know about the storage classes in C?
. automatic
void exampleFunction() {
auto int x = 10; // 'auto' is optional
}
. register
register int counter;
. static
static int globalCounter; // static global variable
void exampleFunction() {
static int localCounter; // static local variable
}
. extern
extern int globalVariable; // Declaration (definition is in another file)
. typedef:
typedef int integer; // 'integer' is now an alias for 'int'
integer x; // Equivalent to 'int x;'
16.characteristics of embedded system
What are the characteristics of embedded systems?
17.MCU architectures
Explain the difference between RISC and CISC architectures.
How would you troubleshoot a firmware issue in a device that’s already deployed?
18.types of memory
Discuss the types of memory in an embedded system?
EEPROMs are reprogrammable one bit at a time, while flash storage is a reprogrammable one block at a time.
19.How do you handle multiple interrupts in a embedded system?
How do you handle multiple interrupts in a embedded system?
. Priority Assignment
. Interrupt Nesting (If a higher-priority interrupt occurs while a lower-priority ISR is already executing, the processor can temporarily suspend the lower-priority ISR, save its context, and start executing the higher-priority ISR)
. Interrupt Service Routine (ISR) Design(Keep Interrupt Service Routines (ISRs) short and efficient)
. Interrupt Vector Table
. Use Flags ,Semaphores or mail
. Avoid Blocking Operations(Avoid using blocking operations, such as waiting for a resource or I/O operation)
1111
20.MCU architectures
brief describe the kinds of MCU architectures?
Answer:
Harvard Architecture(PIC, 51MCU, ARM9, ARM10, ARM11,STM32, ):
the program memory (instruction memory) and data memory (RAM) are physically separate and have dedicated buses,Improved performance due to simultaneous access to program and data memory
Von Neumann Architecture(ARM7, X86, MIPS):
features a unified memory space for both program and data storage. The CPU fetches instructions and data from the same memory using a single bus,Slower access to data
21.coding:
binary search :
Binary search is a classic algorithm used to efficiently locate a target value within a sorted array
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if target is present at the middle
if (arr[mid] == target)
return mid;
// If target is greater, ignore the left half
if (arr[mid] < target)
left = mid + 1;
// If target is smaller, ignore the right half
else
right = mid - 1;
}
// Target is not present in the array
return -1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 7;
int result = binarySearch(arr, 0, n - 1, target);
(result == -1) ? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
// output :Element 7 is present at index 6
2 pointer search
Here’s a simple example of the two-pointer technique for searching in a sorted array in C:
#include <stdio.h>
int twoPointerSearch(int arr[], int n, int target) {
int left = 0;
int right = n - 1;
while (left < right) {
int currentSum = arr[left] + arr[right];
if (currentSum == target) {
// Found the pair
printf("Pair found: %d, %d\n", arr[left], arr[right]);
return 1; // or return index or do something else
} else if (currentSum < target) {
// Move the left pointer to increase the sum
left++;
} else {
// Move the right pointer to decrease the sum
right--;
}
}
// Pair not found
return 0;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 13;
int result = twoPointerSearch(arr, n, target);
if (!result) {
printf("Pair not found for the target sum %d\n", target);
}
return 0;
}
// output: Pair found: 3, 10
sliding window problem
we’ll find the maximum sum of a subarray of a fixed size k in an array.
#include <stdio.h>
int max_sum_subarray(int arr[], int n, int k) {
int window_sum = 0;
// Calculate the sum of the first window
for (int i = 0; i < k; ++i) {
window_sum += arr[i];
}
int max_sum = window_sum;
// Slide the window over the array
for (int i = k; i < n; ++i) {
// Update the window sum by removing the leftmost element and adding the rightmost element
window_sum = window_sum - arr[i - k] + arr[i];
// Update the maximum sum
if (window_sum > max_sum) {
max_sum = window_sum;
}
}
return max_sum;
}
int main() {
int arr[] = {1, 4, 2, 10, 2, 3, 1, 0, 20};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
int result = max_sum_subarray(arr, n, k);
printf("Maximum sum of a subarray of size %d is: %d\n", k, result);
return 0;
}
//output: Maximum sum of a subarray of size 3 is: 21
kadane algorithm
e.g., :The given array [7,1,5,3,6,4] represents the prices of a stock on each day, where the ith element is the price on the ith day. If you are allowed to make at most one transaction (buy one and sell one stock), design an algorithm to calculate the maximum profit you can achieve.
#include <stdio.h>
int maxProfit(int prices[], int n) {
if (n <= 1) {
return 0; // 无法完成交易
}
int min_price = prices[0];
int max_profit = 0;
for (int i = 1; i < n; ++i) {
// 更新最小股价
if (prices[i] < min_price) {
min_price = prices[i];
}
// 计算当前利润并更新最大利润
else {
int current_profit = prices[i] - min_price;
if (current_profit > max_profit) {
max_profit = current_profit;
}
}
}
return max_profit;
}
int main() {
int prices[] = {7, 1, 5, 3, 6, 4};
int n = sizeof(prices) / sizeof(prices[0]);
int result = maxProfit(prices, n);
printf("最大利润:%d\n", result);
return 0;
}
//max profit is 5
Strings:
Reverse string
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int length = strlen(str);
int start = 0;
int end = length - 1;
while (start < end) {
// Swap characters at start and end indices
char temp = str[start];
str[start] = str[end];
str[end] = temp;
// Move indices towards the center
start++;
end--;
}
}
int main() {
char inputString[100];
printf("Enter a string: ");
scanf("%s", inputString);
reverseString(inputString);
printf("Reversed string: %s\n", inputString);
return 0;
}
/*
Enter a string: IamFirmwareEngineer
Reversed string: reenignEerawmriFmaI
*/
Linked List:
Reverse Singly Linked List
Reverse Doubly Linked List
Merger two linked lists
Add, Delete, Search element of Linked List
Find Middle of List
Find last nth element of list
Find if there is loop in list
Stacks and Queue:
Implement Stack (FIFO) using Arrays
Implement Stack using Linked List
Implement Queue using Linked List
Implement Queue using Arrays
Implement Circular buffer
Bit Manipulation:
atoi, itoa, itob, float to bin (link), atof
Add/Sub in binary (w/o using + operator) link
#include <stdio.h>
int add(int a, int b)
{
// for loop will start from 1 and move till the value of
// second number , first number(a) is incremented in for
// loop
for (int i = 1; i <= b; i++)
a++;
return a;
}
int main()
{
// first number is 10 and second number is 32 , for loop
// will start from 1 and move till 32 and the value of a
// is incremented 32 times which will give us the total
// sum of two numbers
int a = add(10, 32);
printf("%d", a);
return 0;
}
//42
// This code is contributed by Aditya Kumar (adityakumar129)
2s complement (-ve numbers)
Decimal 3 in binary: 0011
Two’s complement of 3:
Invert the bits: 1100
Add 1: 1101
So, -3 in a 4-bit two’s complement representation is 1101.