Configure STM32 SPI1 master mode with SPI_CR1 bits
Configure STM32F4 SPI1 as a mode 0 master by setting MSTR, SSM and SSI in SPI_CR1 with a divide-by-16 baud rate, then enable it with SPE.
An STM32F4 SPI master needs one register write for its settings and one more bit to start. The detail that trips people up is the chip-select handling: with software slave management (SSM) on, the internal SSI bit must be set, or the peripheral sees itself as deselected and drops out of master mode with a mode fault.
#include "stm32f4xx.h"
void spi1_master_init(void)
{
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
RCC->APB2ENR |= RCC_APB2ENR_SPI1EN;
(void)RCC->APB2ENR;
/* PA5 = SCK, PA6 = MISO, PA7 = MOSI, alternate function 5 */
GPIOA->MODER = (GPIOA->MODER & ~(GPIO_MODER_MODER5_Msk | GPIO_MODER_MODER6_Msk | GPIO_MODER_MODER7_Msk))
| GPIO_MODER_MODER5_1 | GPIO_MODER_MODER6_1 | GPIO_MODER_MODER7_1;
GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(0xFFFu << 20))
| (5u << 20) | (5u << 24) | (5u << 28);
SPI1->CR1 = SPI_CR1_MSTR | SPI_CR1_SSM | SPI_CR1_SSI
| SPI_CR1_BR_1 | SPI_CR1_BR_0; /* fPCLK / 16 */
SPI1->CR1 |= SPI_CR1_SPE;
}CPOL and CPHA are left at zero, which is SPI mode 0, and the frame is 8 bits, MSB first. BR of 011 divides the APB2 clock by 16, so a 96 MHz bus gives a 6 MHz clock, a safe start for most devices. Chip select is not part of this: drive it from a GPIO yourself.
The SPE bit is set in a second write so the configuration is complete when the peripheral starts. Settings such as CPOL and BR must not be changed while SPE is set. Register names are from STM32CubeF4 V1.28.