STM32L4 - SPI2时钟问题

时间:2016-06-06 11:05:01

标签: c embedded clock stm32 spi

我目前正在研究STM32L476RG Nucleo板,我正在尝试与SPI2总线通信。

似乎我正在使用MOSI引脚发送数据,但SCK引脚上没有任何内容。

以下是我的初始化代码和发送数据代码:

在main.c中:

/ 初始化SPI的函数 /

void MX_SPI2_Init(void)
{
  hspi2.Instance = SPI2;
  hspi2.Init.Mode = SPI_MODE_MASTER;
  hspi2.Init.Direction = SPI_DIRECTION_2LINES;
  hspi2.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi2.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi2.Init.CLKPhase = SPI_PHASE_1EDGE;
  hspi2.Init.NSS = SPI_NSS_SOFT;
  hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
  hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi2.Init.TIMode = SPI_TIMODE_DISABLED;
  hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLED;
  hspi2.Init.CRCPolynomial = 7;
  hspi2.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
  hspi2.Init.NSSPMode = SPI_NSS_PULSE_DISABLED;
  HAL_SPI_Init(&hspi2);
}

/ 通过SPI将数据发送到从站的功能 /

void ADAS1000_SetRegisterValue(unsigned char regAddress,
                               unsigned long regVal)
{

    unsigned char writeCmd[4] = {0, 0, 0, 0};

    writeCmd[0] = 0x80 + regAddress;    // Write bit and register address.
    writeCmd[1] = (unsigned char)((regVal & 0xFF0000) >> 16);
    writeCmd[2] = (unsigned char)((regVal & 0x00FF00) >> 8);
    writeCmd[3] = (unsigned char)((regVal & 0x0000FF) >> 0);

    HAL_SPI_Transmit(&hspi2, &(writeCmd[0]), (uint16_t) sizeof(writeCmd[0]), 50);
    HAL_Delay(500);
    HAL_SPI_Transmit(&hspi2, &(writeCmd[1]), (uint16_t) sizeof(writeCmd[1]), 50);
    HAL_Delay(500);
    HAL_SPI_Transmit(&hspi2, &(writeCmd[2]), (uint16_t) sizeof(writeCmd[2]), 50);
    HAL_Delay(500);
    HAL_SPI_Transmit(&hspi2, &(writeCmd[3]), (uint16_t) sizeof(writeCmd[3]), 50);
    HAL_Delay(500);
}

在hal_msp.c中:

void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi)
{

  GPIO_InitTypeDef GPIO_InitStruct;
  if(hspi->Instance==SPI2)
  {
    /* Peripheral clock enable */
    __SPI2_CLK_ENABLE();

    /**SPI2 GPIO Configuration
    PC2     ------> SPI2_MISO
    PC3     ------> SPI2_MOSI
    PB10     ------> SPI2_SCK
    PB12     ------> SPI2_NSS
    */
    GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_MEDIUM;
    GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_12;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_MEDIUM;
    GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
  }

如果您有任何想法或建议,谢谢您的帮助!

修改

void MX_GPIO_Init(void) 
{ 
   /* GPIO Ports Clock Enable */ 
   __GPIOC_CLK_ENABLE(); 
   __GPIOA_CLK_ENABLE(); 
   __GPIOB_CLK_ENABLE(); 
} 

1 个答案:

答案 0 :(得分:0)

这可能是问题所在

// [...]
hspi2.Init.NSS = SPI_NSS_SOFT;
// [...]

在不检查HAL宏定义的情况下,我相信这会将SPI配置为不驱动NSS,而是通过软件来完成。这意味着您有责任在将数据放入SPI外设之前先手动声明NSS引脚。

这反过来可能导致SPI从设备侧不响应,这似乎像SCK信号根本没有到达从设备。