2021-11-17 04:06 AM
Hi,
I am trying to interface eeprom module with STM32F0308-Disco board using CUBE IDE - HAL library. SPI communication is not working properly, I am getting random values while trying to read the Eeprom ID.
While debugging the code I found that the SPE bit in CR1 register is not set to 1 even after initialization. What could be the issue?
Attaching the code below.
static void MX_SPI1_Init(void)
{
/* USER CODE BEGIN SPI1_Init 0 */
/* USER CODE END SPI1_Init 0 */
/* USER CODE BEGIN SPI1_Init 1 */
/* USER CODE END SPI1_Init 1 */
/* SPI1 parameter configuration*/
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_128;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 7;
hspi1.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
hspi1.Init.NSSPMode = SPI_NSS_PULSE_ENABLE;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI1_Init 2 */
/* USER CODE END SPI1_Init 2 */
}
Solved! Go to Solution.
2021-11-17 04:57 AM
> While debugging the code I found that the SPE bit in CR1 register is not set to 1 even after initialization.
Cube is open source, so you can check what HAL_SPI_Init() does. Indeed, it does not enable SPI; the idea is, that it's enabled only when some of the "communication" (HAL_SPI_TransmitXXX()) functions are called.
To reveal what's the problem, observe MISO/MOSI/SCK lines using oscilloscope/logic analyzer.
JW
2021-11-17 04:57 AM
> While debugging the code I found that the SPE bit in CR1 register is not set to 1 even after initialization.
Cube is open source, so you can check what HAL_SPI_Init() does. Indeed, it does not enable SPI; the idea is, that it's enabled only when some of the "communication" (HAL_SPI_TransmitXXX()) functions are called.
To reveal what's the problem, observe MISO/MOSI/SCK lines using oscilloscope/logic analyzer.
JW
2021-11-17 06:17 AM
That's just how the library works.
You can send a zero-length message which has the effect of enabling the peripheral which sets the clock polarity correctly.
HAL_SPI_Transmit(&hspi1, 0, 0, 0);
> I am getting random values
What values are you getting and what values are you expecting instead? Most likely they're not random, but off by a bit or otherwise related.
2021-11-22 10:07 PM
The issue was resolved, I was reading two bytes using the HAL_SPI_Receive which should be 1 byte in my case. As @Community member said the SPI is enabled only during the Transmit or receive function is called.
Thank you @Community member and @TDK