STM32 SPI Notes | Notes / STM32 | 氵工的博客

STM32 SPI Notes

发表于 2026-03-25 15:00 400 字 2 min read

729DHS avatar

729DHS

氵工的博客 - 分享单片机开发、Linux、机器人技术、RL强化学习与嵌入式项目的学习笔记与实践记录。涵盖STM32、FreeRTOS、Rust、R语言等技术的详细教程与调试经验。

Google 未收录此页面? 在 Search Console 中请求编入索引
STM32 SPI communication basics and practical notes.

STM32 SPI Notes

SPI Introduction

SPI (Serial Peripheral Interface) is a synchronous serial communication interface proposed by Motorola.

Features

  • Full duplex communication
  • Master/Slave mode
  • Synchronous clock (SCK)
  • High-speed transmission (up to dozens of Mbps)

Signal Lines

SignalFull NameDescription
SCKSerial ClockClock signal, generated by the master
MOSIMaster Out Slave InMaster output / Slave input
MISOMaster In Slave OutMaster input / Slave output
NSS/CSChip SelectChip select signal, active low

2. STM32 SPI Working Modes

SPI Working Modes

ModeCPOLCPHASampling Edge
000First rising edge
101First falling edge
210Second rising edge
311Second falling edge
  • CPOL: Clock polarity (idle level)
  • CPHA: Clock phase (sampling moment)

HAL Library Configuration Example

Initialization Code

// SPI handle definition
SPI_HandleTypeDef hspi1;

// SPI initialization configuration
void MX_SPI1_Init(void)
{
    hspi1.Instance = SPI1;
    hspi1.Init.Mode = SPI_MODE_MASTER;
    hspi1.Init.Direction = SPI_DIRECTION_2LINES;
    hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
    hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
    hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
    hspi1.Init.NSS = SPI_NSS_SOFT;
    hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
    hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
    hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
    hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
    hspi1.Init.CRCPolynomial = 10;

    if (HAL_SPI_Init(&hspi1) != HAL_OK)
    {
        // Initialization error handling
        Error_Handler();
    }
}

Data Transfer Functions

// Transmit single byte
HAL_SPI_Transmit(&hspi1, &txData, 1, HAL_MAX_DELAY);

// Receive single byte
HAL_SPI_Receive(&hspi1, &rxData, 1, HAL_MAX_DELAY);

// Full duplex transmit/receive
HAL_SPI_TransmitReceive(&hspi1, txBuffer, rxBuffer, size, HAL_MAX_DELAY);

// Transmit via interrupt
HAL_SPI_Transmit_IT(&hspi1, txBuffer, size);

// Transmit via DMA
HAL_SPI_Transmit_DMA(&hspi1, txBuffer, size);

Common Issues

IssuePossible CauseSolution
No data communicationChip select not pulled lowCheck NSS pin configuration
Data misalignmentClock mode mismatchConfirm master/slave CPOL/CPHA match
Rate too lowPrescaler value too largeAdjust BaudRatePrescaler
Fixed received dataClock not sent firstSPI requires sending data first to generate clock

TODO

  • Add oscilloscope waveform diagrams
  • Add actual project application scenarios
  • Record problems encountered during debugging and their solutions