Loopback SPI in STM32F411RE

Paulson Raja L

I am trying loopback in SPI in STM32F411RE, using the STM32 HAL Library. The output in the serial terminal is distorted (Just boxes) I have connected the MOSI, MISO pins of the micro-controller. Could someone help me point out the problem. Thanks:).

void SPI_call()
{
    int i = 0, size = 3;
    uint8_t tx_buffer[3] = {0x10, 0x20, 0x30};
    uint8_t rx_buffer[3] = {0x00, 0x00, 0x00};

    for (i = 0; i < size; i++) {
        HAL_SPI_Receive(&hspi1, &rx_buffer[i], 1, 100);
        HAL_SPI_Transmit(&hspi1, &tx_buffer[i], 1, 100);
        HAL_UART_Transmit(&huart2, &rx_buffer[i], 1, HAL_MAX_DELAY);
    }
    
}

EDIT: Tried using the API HAL_UART_TransmitReceive(), but I was not able to receive the data.

void SPI_call()
{
    uint8_t tx_buffer = 0x20;
    uint8_t rx_buffer;

    HAL_SPI_TransmitReceive(&hspi1, &tx_buffer, &rx_buffer, 1, 1000);
    HAL_UART_Transmit(&huart2, &rx_buffer, 1, HAL_MAX_DELAY);   
}
Codo

In general, SPI communication needs at least a master and a slave. However, as SPI uses full duplex communication (i.e. it transmits and receives at the same time), it's usually possible to wire MOSI to MISO and achieve loopback communication.

I've tested it on a Nucleo-F411RE and it works.

Using STM32CubeMX I configured a project with the default settings for the Nucleo-F411RE (8 MHz external clock, SWD, UART2 pins suitable for on-board ST-Link etc.). Additionally, I've enabled SPI2. SPI1 is in conflict with the Nucleo board wiring. I've also shorted MOSI and MISO (PC2 and PC3).

The only code I've added is the piece in the while loop:

  while (1)
  {
    /* USER CODE END WHILE */

    HAL_Delay(1000);

    uint8_t tx_buffer[] = { 'H', 'e', 'l', 'l', 'o', '\r', '\n' };
    uint8_t rx_buffer;
    for (int i = 0; i < sizeof(tx_buffer); i++) {
      HAL_SPI_TransmitReceive(&hspi2, tx_buffer + i, &rx_buffer, 1, 100);
      HAL_UART_Transmit(&huart2, &rx_buffer, 1, 100);
    }

    /* USER CODE BEGIN 3 */
  }

The SPI initialization for reference (generated by STM32CubeMX):

  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_2;
  hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  hspi2.Init.CRCPolynomial = 10;
  if (HAL_SPI_Init(&hspi2) != HAL_OK)
  {
    Error_Handler();
  }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive