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
| Signal | Full Name | Description |
|---|
| SCK | Serial Clock | Clock signal, generated by the master |
| MOSI | Master Out Slave In | Master output / Slave input |
| MISO | Master In Slave Out | Master input / Slave output |
| NSS/CS | Chip Select | Chip select signal, active low |
2. STM32 SPI Working Modes
SPI Working Modes
| Mode | CPOL | CPHA | Sampling Edge |
|---|
| 0 | 0 | 0 | First rising edge |
| 1 | 0 | 1 | First falling edge |
| 2 | 1 | 0 | Second rising edge |
| 3 | 1 | 1 | Second 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
| Issue | Possible Cause | Solution |
|---|
| No data communication | Chip select not pulled low | Check NSS pin configuration |
| Data misalignment | Clock mode mismatch | Confirm master/slave CPOL/CPHA match |
| Rate too low | Prescaler value too large | Adjust BaudRatePrescaler |
| Fixed received data | Clock not sent first | SPI requires sending data first to generate clock |
TODO