Claude Code for Embedded Systems: RTOS, Hardware Interfaces, and Firmware Patterns — Claude Skills 360 Blog
Blog / Embedded / Claude Code for Embedded Systems: RTOS, Hardware Interfaces, and Firmware Patterns
Embedded

Claude Code for Embedded Systems: RTOS, Hardware Interfaces, and Firmware Patterns

Published: October 22, 2026
Read time: 9 min read
By: Claude Skills 360

Embedded development has constraints that software development doesn’t: fixed memory, timing requirements, hardware dependencies, and limited debugging capability. Claude Code writes firmware that respects these constraints — properly sized RTOS stacks, interrupt-safe data structures, HAL-abstracted hardware drivers, and the patterns that prevent silent failures in production hardware.

CLAUDE.md for Embedded Projects

## Embedded Stack
- MCU: STM32H743 (Cortex-M7, 2MB Flash, 1MB RAM) or equivalent
- RTOS: FreeRTOS 11.x
- Hardware Abstraction: STM32 HAL (generated by CubeMX)
- Build: CMake + ARM GCC toolchain
- Debugging: OpenOCD + GDB, ITM tracing for printf-style debug
- Memory: heap_4 allocator; no dynamic allocation after init
- Stacks: always add 20% margin to empirically measured stack depth
- No blocking operations in ISRs — use queues/notifications to defer to tasks
- Critical sections: minimum duration — only protect shared data access

FreeRTOS Task Design

// firmware/src/tasks/sensor_task.c
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"

// Statically allocated task and stack — no heap allocation at runtime
static StaticTask_t sensor_task_buffer;
static StackType_t sensor_task_stack[512];  // 512 * 4 = 2KB

// Queue handle — shared between ISR and task
static QueueHandle_t sensor_data_queue;
static StaticQueue_t sensor_queue_buffer;
static SensorReading_t sensor_queue_storage[8];

// Task function: processes sensor readings from the ISR-populated queue
void sensor_task(void *pvParameters) {
    SensorReading_t reading;
    
    // Initialize peripheral (safe to do in task context)
    sensor_init();
    
    for (;;) {
        // Block on queue — yields CPU to other tasks while waiting
        if (xQueueReceive(sensor_data_queue, &reading, pdMS_TO_TICKS(1000)) == pdTRUE) {
            // Process reading — this can take as long as needed
            process_sensor_reading(&reading);
            
            // Notify data task that fresh data is available
            xTaskNotify(data_task_handle, SENSOR_DATA_READY_BIT, eSetBits);
        } else {
            // Timeout: sensor not responding
            handle_sensor_timeout();
        }
    }
}

// Call once during init — creates the task statically
void sensor_task_init(void) {
    sensor_data_queue = xQueueCreateStatic(
        8,                          // Queue depth
        sizeof(SensorReading_t),    // Item size
        (uint8_t *)sensor_queue_storage,
        &sensor_queue_buffer
    );
    configASSERT(sensor_data_queue != NULL);
    
    xTaskCreateStatic(
        sensor_task,
        "SensorTask",
        512,         // Stack depth in words
        NULL,
        tskIDLE_PRIORITY + 2,  // Priority — higher = runs first
        sensor_task_stack,
        &sensor_task_buffer
    );
}

Interrupt Service Routine (ISR)

// firmware/src/drivers/uart_driver.c
// Principle: ISRs do minimal work — data goes into a queue, task does processing

#define UART_RX_BUFFER_SIZE 256

typedef struct {
    uint8_t data[UART_RX_BUFFER_SIZE];
    uint16_t length;
    TickType_t timestamp;
} UartFrame;

static QueueHandle_t uart_rx_queue;
static uint8_t rx_buffer[UART_RX_BUFFER_SIZE];
static uint16_t rx_index = 0;

// DMA complete or IDLE line interrupt — called from ISR context
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
    if (huart->Instance != USART1) return;
    
    BaseType_t higher_prio_task_woken = pdFALSE;
    
    UartFrame frame;
    memcpy(frame.data, rx_buffer, rx_index);
    frame.length = rx_index;
    frame.timestamp = xTaskGetTickCountFromISR();
    
    // Non-blocking send — if queue is full, drop the frame (don't block ISR)
    xQueueSendFromISR(uart_rx_queue, &frame, &higher_prio_task_woken);
    
    // Reset buffer for next frame
    rx_index = 0;
    HAL_UART_Receive_IT(huart, rx_buffer + rx_index, 1);
    
    // Yield to higher-priority task if it was woken (critical for RTOS latency)
    portYIELD_FROM_ISR(higher_prio_task_woken);
}

// ISR for IDLE line detection (end of UART frame)
void USART1_IRQHandler(void) {
    if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE)) {
        __HAL_UART_CLEAR_IDLEFLAG(&huart1);
        
        uint16_t bytes_received = UART_RX_BUFFER_SIZE - huart1.hdmarx->Instance->NDTR;
        if (bytes_received > 0) {
            rx_index = bytes_received;
            HAL_UART_RxCpltCallback(&huart1);
        }
    }
    HAL_UART_IRQHandler(&huart1);
}

SPI Driver with Hardware Abstraction

// firmware/src/drivers/display_driver.c — SPI display driver
#include "spi_hal.h"

#define DISPLAY_SPI_TIMEOUT_MS 10
#define DISPLAY_CS_PIN  GPIO_PIN_4
#define DISPLAY_CS_PORT GPIOA
#define DISPLAY_DC_PIN  GPIO_PIN_5
#define DISPLAY_DC_PORT GPIOA

typedef struct {
    SPI_HandleTypeDef *hspi;
    GPIO_TypeDef *cs_port;
    uint16_t cs_pin;
    GPIO_TypeDef *dc_port;
    uint16_t dc_pin;
} DisplayHandle;

static DisplayHandle display;

HAL_StatusTypeDef display_write_command(uint8_t cmd) {
    HAL_GPIO_WritePin(display.dc_port, display.dc_pin, GPIO_PIN_RESET);  // DC=0 -> command
    HAL_GPIO_WritePin(display.cs_port, display.cs_pin, GPIO_PIN_RESET);  // CS active low
    
    HAL_StatusTypeDef status = HAL_SPI_Transmit(
        display.hspi, &cmd, 1, DISPLAY_SPI_TIMEOUT_MS
    );
    
    HAL_GPIO_WritePin(display.cs_port, display.cs_pin, GPIO_PIN_SET);
    return status;
}

HAL_StatusTypeDef display_write_data(const uint8_t *data, uint16_t length) {
    HAL_GPIO_WritePin(display.dc_port, display.dc_pin, GPIO_PIN_SET);  // DC=1 -> data
    HAL_GPIO_WritePin(display.cs_port, display.cs_pin, GPIO_PIN_RESET);
    
    // DMA transfer for large data — doesn't block CPU
    HAL_StatusTypeDef status = HAL_SPI_Transmit_DMA(display.hspi, (uint8_t *)data, length);
    
    // Wait for DMA complete notification (not busy-wait)
    if (xSemaphoreTake(spi_dma_complete_semaphore, pdMS_TO_TICKS(100)) != pdTRUE) {
        HAL_GPIO_WritePin(display.cs_port, display.cs_pin, GPIO_PIN_SET);
        return HAL_TIMEOUT;
    }
    
    HAL_GPIO_WritePin(display.cs_port, display.cs_pin, GPIO_PIN_SET);
    return HAL_OK;
}

Ring Buffer (Lock-Free for Single Producer/Consumer)

// firmware/src/lib/ring_buffer.h — lock-free for ISR producer, task consumer
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <stdatomic.h>

#define RING_BUFFER_SIZE 256  // Must be power of 2

typedef struct {
    uint8_t buffer[RING_BUFFER_SIZE];
    atomic_uint_fast16_t read_index;
    atomic_uint_fast16_t write_index;
} RingBuffer;

// Called from ISR: producer
bool ring_buffer_write(RingBuffer *rb, uint8_t byte) {
    uint_fast16_t write = atomic_load_explicit(&rb->write_index, memory_order_relaxed);
    uint_fast16_t read = atomic_load_explicit(&rb->read_index, memory_order_acquire);
    
    uint_fast16_t next_write = (write + 1) & (RING_BUFFER_SIZE - 1);
    
    if (next_write == read) return false;  // Full
    
    rb->buffer[write] = byte;
    atomic_store_explicit(&rb->write_index, next_write, memory_order_release);
    return true;
}

// Called from task: consumer
bool ring_buffer_read(RingBuffer *rb, uint8_t *byte) {
    uint_fast16_t write = atomic_load_explicit(&rb->write_index, memory_order_acquire);
    uint_fast16_t read = atomic_load_explicit(&rb->read_index, memory_order_relaxed);
    
    if (read == write) return false;  // Empty
    
    *byte = rb->buffer[read];
    atomic_store_explicit(&rb->read_index, (read + 1) & (RING_BUFFER_SIZE - 1), memory_order_release);
    return true;
}

Stack Usage Analysis

// firmware/src/debug/stack_monitor.c — detect stack overflow before it happens
void check_task_stacks(void) {
    TaskStatus_t task_status_array[16];
    volatile UBaseType_t task_count;
    
    task_count = uxTaskGetNumberOfTasks();
    if (uxTaskGetSystemState(task_status_array, task_count, NULL) == task_count) {
        for (UBaseType_t i = 0; i < task_count; i++) {
            uint32_t stack_high_water_mark = task_status_array[i].usStackHighWaterMark;
            
            // Alert if less than 64 words (256 bytes) remaining
            if (stack_high_water_mark < 64) {
                ITM_SendString("[WARN] Task '");
                ITM_SendString(task_status_array[i].pcTaskName);
                ITM_SendChar('\'');
                ITM_SendString(" stack nearly full! HWM=");
                ITM_SendUint32(stack_high_water_mark);
                ITM_SendString(" words\n");
            }
        }
    }
}

// FreeRTOS hook: called on stack overflow (enable via configCHECK_FOR_STACK_OVERFLOW=2)
void vApplicationStackOverflowHook(TaskHandle_t xTask, char *pcTaskName) {
    // Can't use printf/UART here (undefined state) — trigger debugger or reset
    (void)xTask;
    (void)pcTaskName;
    
    __disable_irq();
    while (1) {
        // Halt for debugger — will show task name in xTask
        __BKPT(0);
    }
}

For the Rust embedded development as an alternative to C firmware, the Rust async guide covers the async runtime patterns that apply to Embassy (Rust embedded framework). For the supply chain security considerations for firmware dependencies, the supply chain security guide covers SBOM generation applicable to embedded projects. The Claude Skills 360 bundle includes embedded systems skill sets covering FreeRTOS patterns, HAL drivers, and interrupt-safe data structures. Start with the free tier to try firmware pattern generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free