/communication-buses:communication-busesfrom communication-buses
Reference for I2C, SPI, UART, CAN, and USB driver development: addressing, pull-up sizing, bus recovery, SPI modes, DMA cache rules, ring buffers, CAN bit timing, USB descriptors, and STM32 HAL code. Use when writing or reviewing a bus driver or diagnosing a misbehaving bus.
Ships in communication-buses. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Reference patterns for I2C, SPI, UART, CAN, and USB driver development. Use as a lookup when designing or reviewing drivers.
| Address space | Bits | Range |
|---|---|---|
| 7-bit | bits 7..1 | 0x08–0x77 (0x00-0x07 and 0x78-0x7F reserved) |
| 10-bit | bits 9..0 | 0x000–0x3FF |
Format on the wire (7-bit):
S | 7-bit addr | R/W | A | ... | P
The R/W bit is bit 0. Many HALs accept the address pre-shifted (address << 1); some accept it raw. Confirm against the HAL docs — common bug source.
For VCC = 3.3V:
| Speed | Recommended pull-up |
|---|---|
| Standard (100 kHz) | 4.7 kΩ |
| Fast (400 kHz) | 4.7 kΩ or 2.2 kΩ |
| Fast Plus (1 MHz) | 2.2 kΩ or 1 kΩ |
| High Speed (3.4 MHz) | 1 kΩ + external buffer |
Bus capacitance matters. Wire capacitance ~ 1 pF/cm. Total bus capacitance (wire + slaves + master) should be < 400 pF for standard, < 200 pF for fast modes.
Slave holds SCL low to gain processing time. Master must wait. STM32 hardware I2C handles this. Some software bit-bang implementations don't. If using bit-bang, sample SCL before assuming the master controls it.
When SDA is stuck low (slave hung mid-transfer):
1. Configure SDA + SCL as GPIO (out of AF)
2. Pulse SCL low → high, 9-16 times
3. Check if SDA released (high)
4. If yes: generate STOP (SCL high, SDA low → high)
5. Restore SDA + SCL to AF
6. Re-init the I2C peripheral
| Mode | CPOL | CPHA | Idle clock | Data captured on |
|---|---|---|---|---|
| 0 | 0 | 0 | Low | Rising edge |
| 1 | 0 | 1 | Low | Falling edge |
| 2 | 1 | 0 | High | Falling edge |
| 3 | 1 | 1 | High | Rising edge |
Most sensors: mode 0 or 3. Always verify against datasheet — wrong mode silently corrupts every byte.
Hardware NSS (single slave):
GPIO CS (multi-slave):
| MCU family | Requirement |
|---|---|
| Cortex-M0/M3/M4 (no cache) | No alignment requirement beyond AHB bus |
| Cortex-M7 with cache | Buffer in non-cacheable region OR explicit cache maintenance |
| ESP32 | DMA-capable memory region only (check linker) |
For Cortex-M7 cache maintenance:
// Before DMA write (CPU → peripheral):
SCB_CleanDCache_by_Addr((uint32_t*)tx_buf, len);
// Before DMA read (peripheral → CPU):
SCB_InvalidateDCache_by_Addr((uint32_t*)rx_buf, len);
For multiple SPI slaves on one CS:
Master MOSI → Slave 1 MOSI
Slave 1 MISO → Slave 2 MOSI
Slave 2 MISO → Master MISO
Common CS to all slaves
Common SCK to all slaves
Transfer N×M bytes for N slaves with M-byte registers. Each slave shifts out its previous-cycle data while shifting in new data. Useful for sensor arrays.
Start bit | Data bits (5-9) | Parity (optional) | Stop bits (1 / 1.5 / 2)
Common configurations:
Common rates: 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600, 1500000, 2000000, 3000000
Above 921600, accuracy of the MCU's UART clock matters. STM32 USART_BRR can hit any baud rate; calculate the actual rate and verify it's within ±2% of nominal.
| Throughput | Pattern |
|---|---|
| < 1 kbps | Polled (rare, debug only) |
| 1 kbps – 100 kbps | Interrupt RX + ring buffer |
| 100 kbps – 1 Mbps | DMA RX + IDLE line detection |
| > 1 Mbps | DMA RX circular + IDLE line + flow control |
typedef struct {
uint8_t buf[256];
volatile uint16_t head;
uint16_t tail;
} ringbuf_t;
// ISR
void USART2_IRQHandler(void) {
if (USART2->SR & USART_SR_RXNE) {
uint8_t byte = USART2->DR;
uint16_t next = (rb.head + 1) & 0xFF;
if (next != rb.tail) { // Not full
rb.buf[rb.head] = byte;
rb.head = next;
}
// else: overflow — log it
}
}
// Task
ssize_t ringbuf_read(uint8_t *out, size_t maxlen) {
size_t count = 0;
while (rb.tail != rb.head && count < maxlen) {
out[count++] = rb.buf[rb.tail];
rb.tail = (rb.tail + 1) & 0xFF;
}
return count;
}
When the host can stall:
For STM32 USART:
USART_CR3_CTSE enables CTSUSART_CR3_RTSE enables RTSBit time = sync + propagation + phase1 + phase2
Sample point = (sync + propagation + phase1) / bit time
Recommended sample point: 75–87.5% of bit time. Higher sample point gives more margin for bus propagation delay but less margin for resync.
For 500 kbps on 42 MHz APB clock:
For STM32 bxCAN:
Configure for the IDs you actually consume. Other IDs dropped at the controller (no CPU work).
Active → Passive (TX error count > 127): sends recessive error frames only
Active → Bus-off (TX error count > 255): controller stops
Bus-off → Active (after 128 × 11 recessive bits): automatic recovery
Driver must detect bus-off and either wait for auto-recovery OR explicitly re-init. Auto-recovery is safer for production.
Device descriptor
├─ Configuration descriptor (1+)
│ ├─ Interface descriptor (1+)
│ │ └─ Endpoint descriptor (0+)
│ └─ String descriptors (indexed)
└─ Vendor extensions (rare)
Total length in configuration descriptor must equal sum of all subordinate descriptor lengths. Off-by-one here causes enumeration to fail at the configuration-read step.
| Symptom | Likely cause |
|---|---|
| Host doesn't see device at all | D+ pullup not raised; VBUS detection wrong |
| Host sees device but fails enumeration | Descriptor length mismatch; EP0 size wrong |
| Host enumerates but wrong driver loads | VID/PID conflict with existing driver |
| Enumerates fine but immediate disconnect | Power request > bus can provide |
| Sometimes works, sometimes not | VBUS noise; pullup raised before VBUS stable |
A slave is holding SDA low. Use bus recovery (pulse SCL 9-16 times, then STOP). Common causes:
Slave isn't driving MISO. Check:
RX overrun. Either:
Filter bank misconfigured. Check the filter bank's ID + mask vs. the actual message ID being broadcast.
Descriptor issue. Some hosts are stricter than others. Run USB-IF compliance tool on the descriptors.
Production communication bus patterns for embedded C. STM32 HAL and LL examples.
Generic register-addressed I2C sensor driver (BME280, MPU-6050, etc.):
#define I2C_TIMEOUT_MS 5U
HAL_StatusTypeDef sensor_write_reg(I2C_HandleTypeDef *hi2c,
uint8_t dev_addr, uint8_t reg, uint8_t val)
{
uint8_t buf[2] = { reg, val };
return HAL_I2C_Master_Transmit(hi2c, dev_addr << 1, buf, 2, I2C_TIMEOUT_MS);
}
HAL_StatusTypeDef sensor_read_reg(I2C_HandleTypeDef *hi2c,
uint8_t dev_addr, uint8_t reg,
uint8_t *out, uint16_t len)
{
HAL_StatusTypeDef s;
s = HAL_I2C_Master_Transmit(hi2c, dev_addr << 1, ®, 1, I2C_TIMEOUT_MS);
if (s != HAL_OK) { return s; }
return HAL_I2C_Master_Receive(hi2c, (dev_addr << 1) | 1,
out, len, I2C_TIMEOUT_MS);
}
/* I2C bus recovery: toggle SCL 9 times to release stuck SDA */
void i2c_bus_recover(GPIO_TypeDef *scl_port, uint16_t scl_pin,
GPIO_TypeDef *sda_port, uint16_t sda_pin)
{
for (int i = 0; i < 9; i++) {
HAL_GPIO_WritePin(scl_port, scl_pin, GPIO_PIN_SET);
HAL_Delay(1);
HAL_GPIO_WritePin(scl_port, scl_pin, GPIO_PIN_RESET);
HAL_Delay(1);
}
/* Generate STOP: SDA low→high while SCL high */
HAL_GPIO_WritePin(sda_port, sda_pin, GPIO_PIN_RESET);
HAL_GPIO_WritePin(scl_port, scl_pin, GPIO_PIN_SET);
HAL_Delay(1);
HAL_GPIO_WritePin(sda_port, sda_pin, GPIO_PIN_SET);
}
Non-blocking SPI using DMA and FreeRTOS binary semaphore for completion notification:
static SemaphoreHandle_t s_spi_done;
void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi)
{
if (hspi == &hspi1) {
BaseType_t woken = pdFALSE;
xSemaphoreGiveFromISR(s_spi_done, &woken);
portYIELD_FROM_ISR(woken);
}
}
void spi_dma_init(void)
{
s_spi_done = xSemaphoreCreateBinary();
}
bool spi_transfer(const uint8_t *tx, uint8_t *rx, uint16_t len)
{
spi_cs_assert();
HAL_SPI_TransmitReceive_DMA(&hspi1, (uint8_t *)tx, rx, len);
/* Block task until DMA complete (max 10ms) */
bool ok = xSemaphoreTake(s_spi_done, pdMS_TO_TICKS(10)) == pdTRUE;
spi_cs_deassert();
return ok;
}
Most reliable pattern for variable-length UART frames at high baud:
#define DMA_RX_BUF 256U
static uint8_t s_dma_rx[DMA_RX_BUF];
static uint32_t s_rx_wr = 0U; /* Written by IDLE ISR */
static uint32_t s_rx_rd = 0U; /* Read by application */
void uart_dma_init(UART_HandleTypeDef *hu)
{
/* Start DMA receive in circular mode — never needs restart */
HAL_UARTEx_ReceiveToIdle_DMA(hu, s_dma_rx, DMA_RX_BUF);
__HAL_DMA_DISABLE_IT(hu->hdmarx, DMA_IT_HT); /* Disable half-transfer */
}
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *hu, uint16_t size)
{
/* size = write position in s_dma_rx (bytes from buffer start), not a */
/* count since the last callback. size == DMA_RX_BUF means it wrapped. */
s_rx_wr = size % DMA_RX_BUF;
}
uint16_t uart_available(void) {
return (s_rx_wr - s_rx_rd + DMA_RX_BUF) % DMA_RX_BUF;
}
uint8_t uart_read_byte(void) {
uint8_t c = s_dma_rx[s_rx_rd];
s_rx_rd = (s_rx_rd + 1U) % DMA_RX_BUF;
return c;
}
/* Transmit CAN frame */
CAN_TxHeaderTypeDef tx_hdr = {
.StdId = 0x123U,
.IDE = CAN_ID_STD,
.RTR = CAN_RTR_DATA,
.DLC = 8U,
.TransmitGlobalTime = DISABLE,
};
void can_send(uint8_t *data)
{
uint32_t mailbox;
if (HAL_CAN_GetTxMailboxesFreeLevel(&hcan1) == 0) { return; }
HAL_CAN_AddTxMessage(&hcan1, &tx_hdr, data, &mailbox);
}
/* Receive: called from CAN RX FIFO0 interrupt */
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan)
{
CAN_RxHeaderTypeDef hdr;
uint8_t buf[8];
if (HAL_CAN_GetRxMessage(hcan, CAN_RX_FIFO0, &hdr, buf) == HAL_OK) {
can_dispatch(hdr.StdId, buf, hdr.DLC);
}
}
/* STM32 HAL SPI mode to CPOL/CPHA mapping */
/* Mode 0: CPOL=0, CPHA=0 — idle low, sample rising */
hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
/* Mode 3: CPOL=1, CPHA=1 — idle high, sample rising */
hspi1.Init.CLKPolarity = SPI_POLARITY_HIGH;
hspi1.Init.CLKPhase = SPI_PHASE_2EDGE;
/* Always verify against the sensor's timing diagram.
ICM-42688 (IMU): Mode 0 or Mode 3
W25Q128 (Flash): Mode 0 or Mode 3
MCP3204 (ADC): Mode 0 or Mode 3 */
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub ormus-solutions/libreembed-claude-code --plugin communication-busesOther plugins' skills for the same job