1
\$\begingroup\$

I am working on a piece of software for an STM32F4xx device which started from a STM32CubeMX generated project.

I am using the SPI peripheral which has been initialized using the HAL library. This is an example of an SPI write function that works:

void spi_write(uint8_t data) {
    HAL_SPI_Transmit(&hspi2,&data,1,HAL_MAX_DELAY);
}

If I want to send data using the SPI without using the HAL library, but doing it barebones on the registers (because it is faster) it does not work. This is my implementation:

void spi_write(uint8_t data) {
    (&hspi2)->Instance->DR = data;
    while (!((&hspi2)->Instance->SR & ((uint16_t)0x0002))); //Check TXE flag (SPI_I2S_FLAG_TXE)
    while ((&hspi2)->Instance->SR & ((uint16_t)0x0080)); // Check busy flag (SPI_I2S_FLAG_BSY)
}

Any idea why the second implementation does not work? Thank you!

\$\endgroup\$

bumped to the homepage by Community 2 hours ago

This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

  • \$\begingroup\$ In what way does it not work? \$\endgroup\$ – brhans Apr 22 '18 at 14:23
  • \$\begingroup\$ It does not send any data. \$\endgroup\$ – Cezar Chirila Apr 22 '18 at 14:30
  • 2
    \$\begingroup\$ The STM HAL Library's HAL_SPI_Transmit() does a __HAL_SPI_ENABLE(hspi) before writing to the DR. Are you sure the SPI peripheral you're writing to is actually enabled and not just configured? \$\endgroup\$ – brhans Apr 22 '18 at 15:10
0
\$\begingroup\$

depending on the implementation of the SPI probably you need to cast properly

*(volatile uint8_t *)&SPIx -> DR = data;

Then waiting for both flags after the send is pointless. Using the magic numbers is just ridiculous.

void spi_write(uint8_t data) 
{
    while (!(hspi2.Instance->SR & SPI_SR_TXE)));  // check  the CMSIS definition for you uC
    *(volatile uint8_t *)&hspi2.Instance->DR = data;
}

The last check is needed only if you are going to disable the SPI or you manually change the state of the CS pin and you have to wait until the last was transmitted.

Another errors - SR register is 32 bit not 16. What is the point of using HAL for initialization if you want to use it the "bare regiser" way?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.