c
/**
* Boot-time Diagnostic Routine for Embedded Medical Device
*
* This routine performs comprehensive self-tests at startup to ensure hardware integrity
* before loading the main application. Critical for medical devices to prevent faults.
*
* Assumptions:
* - ARM Cortex-M microcontroller (e.g., STM32-like).
* - Bare-metal, no OS/RTOS.
* - Basic peripherals: GPIO (LEDs for status), UART (loopback test), I2C/SPI (ID reads),
* ADC (voltage check), Watchdog, SysTick.
* - RAM: 64KB starting at 0x20000000.
* - Flash: Firmware checksum verification.
* - Customize hardware defines (e.g., registers) for your MCU.
*
* Usage: Call run_boot_diagnostics() early in main(). On pass, jump to app_entry().
* On fail: Blinks LED with error code pattern and enters safe state (WDT reset).
*
* Safety Notes:
* - Tests are non-destructive where possible.
* - Memory tests use safe patterns to detect stuck bits.
* - Failures halt progression to prevent unsafe operation.
* - Add CRC32 or HMAC for firmware integrity in production.
*/
#include <stdint.h>
#include <stdbool.h>
#include <string.h> // For memset
// =============================================================================
// Hardware Abstractions (CUSTOMIZE FOR YOUR MCU)
// =============================================================================
// GPIO for status LED (e.g., Port A Pin 5)
#define LED_PORT_BASE ((volatile uint32_t*)0x40020000) // GPIOA base
#define LED_PIN 5
#define LED_SET() (LED_PORT_BASE[0x18/4] |= (1 << LED_PIN)) // BSRR
#define LED_CLEAR() (LED_PORT_BASE[0x18/4] &= ~(1 << LED_PIN)) // BSRR
#define LED_TOGGLE() (LED_PORT_BASE[0x14/4] ^= (1 << LED_PIN)) // ODR
// UART (e.g., USART1, loopback by shorting TX/RX)
#define UART_BASE ((volatile uint32_t*)0x40013800) // USART1
#define UART_DR (UART_BASE[0x00/4]) // Data Register
#define UART_SR (UART_BASE[0x00/4]) // Status Register
#define UART_SR_TXE (1 << 7)
#define UART_SR_RXNE (1 << 5)
// I2C (e.g., read device ID from sensor at addr 0x68)
#define I2C_BASE ((volatile uint32_t*)0x40005400) // I2C1
#define I2C_CR1 (I2C_BASE[0x00/4])
#define I2C_DR (I2C_BASE[0x10/4])
// ADC for voltage monitor (e.g., VDD/3.3V check)
#define ADC_BASE ((volatile uint32_t*)0x40012400) // ADC1
#define ADC_DR (ADC_BASE[0x4C/4])
// Watchdog (kick macro)
#define WDT_KICK() (*(volatile uint32_t*)0xE0001008 = 0x5555; *(volatile uint32_t*)0xE000100C = 0xAAAA;)
// SysTick for delays (assume 1ms tick)
#define SYSTICK_BASE ((volatile uint32_t*)0xE000E010)
#define DELAY_MS(n) { SYSTICK_BASE[0] = (SystemCoreClock / 1000) * (n); while (SYSTICK_BASE[0]); }
// RAM range
#define RAM_START 0x20000000
#define RAM_SIZE (64 * 1024) // 64KB
// Flash size (for checksum)
#define FLASH_SIZE (256 * 1024)
// App entry point
extern void app_entry(void);
// =============================================================================
// Diagnostic Status & Errors
// =============================================================================
typedef enum {
DIAG_PASS = 0,
DIAG_FAIL_CPU = 1,
DIAG_FAIL_RAM = 2,
DIAG_FAIL_FLASH = 3,
DIAG_FAIL_UART = 4,
DIAG_FAIL_I2C = 5,
DIAG_FAIL_ADC = 6,
DIAG_FAIL_WDT = 7
} diag_status_t;
// Global result
static diag_status_t g_diag_result = DIAG_PASS;
// Blink error code: N short blinks + 1 long blink (pause between codes)
static void indicate_error(diag_status_t code) {
for (int i = 0; i < 10; i++) { // Repeat 10 times
for (int j = 0; j < (int)code; j++) {
LED_SET();
DELAY_MS(100);
LED_CLEAR();
DELAY_MS(100);
}
DELAY_MS(1000); // Long pause
}
}
// Safe state: Infinite loop with WDT (auto-reset)
static void enter_safe_state(void) {
while (1) {
WDT_KICK();
DELAY_MS(500);
}
}
// =============================================================================
// Individual Tests
// =============================================================================
// 1. CPU Test: ALU ops, registers, interrupts (basic)
static bool test_cpu(void) {
volatile uint32_t a = 0xDEADBEEF, b = 0xCAFEBABE, result;
WDT_KICK();
// ALU: add/sub/mul/neg
result = a + b; if (result != 0x6D6A6D5D) return false;
result = a - b; if (result != 0x0463F541) return false;
result = ~a; if (result != 0x21524110) return false;
// Branch/jump simulation
if ((a & 0xFF) != 0xEF) return false;
// SysTick interrupt enable/disable
SYSTICK_BASE[1] = 0; // Disable
SYSTICK_BASE[1] = 7; // Enable, IRQ
SYSTICK_BASE[1] = 0;
return true;
}
// 2. RAM Test: March C- algorithm (detects stuck-at, transition faults)
static bool test_ram(uint32_t start, uint32_t size) {
uint8_t *ram = (uint8_t*)start;
uint32_t i;
// Step 1: Write 0s
memset(ram, 0x00, size);
WDT_KICK();
for (i = 0; i < size; i++) {
if (ram[i] != 0x00) return false;
}
// Step 2: Write 1s, read 1s ↑ (up)
memset(ram, 0xFF, size);
WDT_KICK();
for (i = 0; i < size; i++) {
if (ram[i] != 0xFF) return false;
ram[i] = 0x00;
}
// Step 3: Read 0s ↓ (down)
for (i = size - 1; i != 0xFFFFFFFF; i--) {
if (ram[i] != 0x00) return false;
ram[i] = 0xFF;
}
// Step 4: Write 1s, read 1s ↑
memset(ram, 0xFF, size);
WDT_KICK();
for (i = 0; i < size; i++) {
if (ram[i] != 0xFF) return false;
ram[i] = 0x00;
}
// Step 5: Read 0s ↑, write pattern
for (i = 0; i < size; i++) {
if (ram[i] != 0x00) return false;
ram[i] = (uint8_t)(i & 0xFF);
}
return true;
}
// 3. Flash Checksum: Simple sum (use CRC32 in production)
static bool test_flash(void) {
uint32_t sum = 0;
uint8_t *flash = (uint8_t*)0x08000000; // Flash start
for (uint32_t i = 0; i < FLASH_SIZE; i += 4) {
sum += *(uint32_t*)(flash + i);
WDT_KICK();
}
// Expected checksum stored at last 4 bytes or computed offline
return (sum & 0xFFFF) == 0x1234; // Placeholder: replace with real expected value
}
// 4. UART Loopback Test
static bool test_uart(void) {
const char *test_str = "DIAG";
char rx_buf[5];
// Send
for (int i = 0; test_str[i]; i++) {
while (!(UART_SR & UART_SR_TXE));
UART_DR = test_str[i];
}
// Receive & verify (assume loopback wired)
WDT_KICK();
for (int i = 0; i < 4; i++) {
while (!(UART_SR & UART_SR_RXNE));
rx_buf[i] = (char)UART_DR;
}
rx_buf[4] = 0;
return (strcmp(test_str, rx_buf) == 0);
}
// 5. I2C Device ID Read (e.g., MPU6050-like sensor at 0x68)
static bool test_i2c(void) {
// Start, addr 0x68<<1=0xD0, reg 0x75 (WHO_AM_I)
I2C_CR1 |= 1; // Start placeholder (simplified; use full HAL in prod)
// ... Full I2C sequence omitted for brevity; assume returns 0x68
WDT_KICK();
return (*(volatile uint8_t*)0x68 == 0x68); // Placeholder read
}
// 6. ADC Voltage Check (VDD > 3.0V)
static bool test_adc(void) {
// Trigger conversion (placeholder)
*(volatile uint32_t*)0x40012400 = 1; // CR2 start
DELAY_MS(1);
uint32_t adc_val = ADC_DR & 0xFFF;
float voltage = (adc_val * 3.3f) / 4096.0f * 3.0f; // Vref/3 scaling
return (voltage > 3.0f);
}
// 7. Watchdog Test: Let it timeout once? (Skip for safety; just kick)
static bool test_wdt(void) {
WDT_KICK();
DELAY_MS(100);
return true; // Assume enabled upstream
}
// =============================================================================
// Main Diagnostic Runner
// =============================================================================
bool run_boot_diagnostics(void) {
// Init minimal HW (clocks, GPIO, peripherals)
// ... Assume called after clock init
LED_SET(); // Show boot start
// Run tests in order
if (!test_cpu()) { g_diag_result = DIAG_FAIL_CPU; goto fail; }
if (!test_ram(RAM_START, RAM_SIZE)) { g_diag_result = DIAG_FAIL_RAM; goto fail; }
if (!test_flash()) { g_diag_result = DIAG_FAIL_FLASH; goto fail; }
if (!test_uart()) { g_diag_result = DIAG_FAIL_UART; goto fail; }
if (!test_i2c()) { g_diag_result = DIAG_FAIL_I2C; goto fail; }
if (!test_adc()) { g_diag_result = DIAG_FAIL_ADC; goto fail; }
if (!test_wdt()) { g_diag_result = DIAG_FAIL_WDT; goto fail; }
LED_CLEAR(); // Green/Pass
DELAY_MS(500);
return true; // Proceed to app
fail:
LED_SET();
indicate_error(g_diag_result);
enter_safe_state();
return false; // Unreachable
}
// Example main()
int main(void) {
// Minimal init: clocks, WDT enable, GPIO config
// ...
if (run_boot_diagnostics()) {
app_entry();
}
// Never reached
return 0;
}