Introduction
Embedded systems often have small memory and strict timing. Bugs can cause crashes or wrong behavior. Knowing common bugs helps fix problems faster.
/* Example: Fixing a common bug - uninitialized variable */ int sensor_value; void read_sensor() { sensor_value = 0; // Initialize before use // code to read sensor }
/* Bug: Using uninitialized variable */ int count; void loop() { count = count + 1; // count was never set first }
/* Fix: Initialize variable */ int count = 0; void loop() { count = count + 1; // now count starts at 0 }
/* Bug: Forgetting to clear interrupt flag */
void ISR() {
// handle interrupt
// missing code to clear flag
}
/* Fix: Clear interrupt flag */
void ISR() {
// handle interrupt
CLEAR_INTERRUPT_FLAG();
}
/* Example: Fixing a common embedded bug - uninitialized variable and interrupt flag */ #include <stdio.h> volatile int count = 0; volatile int interrupt_flag = 0; void ISR() { interrupt_flag = 0; // Clear interrupt flag count++; } int main() { // Simulate interrupt interrupt_flag = 1; if (interrupt_flag) { ISR(); } printf("Count after interrupt: %d\n", count); return 0; }
volatile int flag = 0;
void ISR() {
flag = 1;
}
int main() {
while(flag == 0) {
// wait
}
return 0;
}int counter;
void setup() {
// No initialization of counter
}
void loop() {
counter++;
if(counter > 10) {
counter = 0;
}
}volatile int sensor_value;
int safe_value;
void ISR() {
sensor_value = read_sensor();
}
int main() {
// What should be done here?
}Pass the test and this pattern moves unknown