使用 STM32 MCU 和低级 LL API 通过 SPI 发送数据

Ale*_*lek 4 spi stm32 low-level

我的板是 nucleo STM32L432KCU 板。我正在尝试使用低级 API 通过 SPI 发送字符。SPI 配置为“仅发送主机”并且硬件 NSS 信号被禁用。

不幸的是,我的代码不起作用(见下文)。当我连接逻辑分析仪时,我看不到任何东西。

这是我的代码:

SPI初始化(由CubeMX生成)

void MX_SPI1_Init(void)
{
  LL_SPI_InitTypeDef SPI_InitStruct;

  LL_GPIO_InitTypeDef GPIO_InitStruct;
  /* Peripheral clock enable */
  LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_SPI1);

  /**SPI1 GPIO Configuration  
  PA1   ------> SPI1_SCK
  PA7   ------> SPI1_MOSI 
  */
  GPIO_InitStruct.Pin = SCLK1_to_SpW_Pin|MOSI1_to_SpW_Pin;
  GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE;
  GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_VERY_HIGH;
  GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL;
  GPIO_InitStruct.Pull = LL_GPIO_PULL_NO;
  GPIO_InitStruct.Alternate = LL_GPIO_AF_5;
  LL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  SPI_InitStruct.TransferDirection = LL_SPI_FULL_DUPLEX;
  SPI_InitStruct.Mode = LL_SPI_MODE_MASTER;
  SPI_InitStruct.DataWidth = LL_SPI_DATAWIDTH_8BIT;
  SPI_InitStruct.ClockPolarity = LL_SPI_POLARITY_LOW;
  SPI_InitStruct.ClockPhase = LL_SPI_PHASE_1EDGE;
  SPI_InitStruct.NSS = LL_SPI_NSS_SOFT;
  SPI_InitStruct.BaudRate = LL_SPI_BAUDRATEPRESCALER_DIV8;
  SPI_InitStruct.BitOrder = LL_SPI_LSB_FIRST;
  SPI_InitStruct.CRCCalculation = LL_SPI_CRCCALCULATION_DISABLE;
  SPI_InitStruct.CRCPoly = 7;
  LL_SPI_Init(SPI1, &SPI_InitStruct);

  LL_SPI_SetStandard(SPI1, LL_SPI_PROTOCOL_MOTOROLA);

  LL_SPI_EnableNSSPulseMgt(SPI1);

}
Run Code Online (Sandbox Code Playgroud)

发送一个字符的代码

以下代码位于调用MX_SPI1_Init()函数后的主函数中。

while (!(SPI1->SR & SPI_SR_TXE));
// Send bytes over the SPI
LL_SPI_TransmitData8(SPI1,0b01010111);
// Wait until the transmission is complete
while (SPI1->SR & SPI_SR_BSY);
Run Code Online (Sandbox Code Playgroud)

谢谢。

Ale*_*lek 5

我认为我已经找到了解决方案,或者至少找到了可行的方法。我的问题是我忘记启用 SPI(写入 CR1 寄存器的第 6 位)。以下是工作代码(当前解决方案):

  // Check if the SPI is enabled
  if((SPI1->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE)
  {
      // If disabled, I enable it
      SET_BIT(SPI1->CR1, SPI_CR1_SPE);
  }

  while (!(SPI1->SR & SPI_SR_TXE));
  // Send bytes over the SPI
  LL_SPI_TransmitData16(SPI1,0xA0A0);
  // Wait until the transmission is complete
  while (SPI1->SR & SPI_SR_BSY);

  // Disable SPI
  CLEAR_BIT(SPI1->CR1, SPI_CR1_SPE);
Run Code Online (Sandbox Code Playgroud)