简体   繁体   中英

STM32 SPI communication

I am trying SPI communication using STM32F411VE . I am getting some issues with SPI communication. I am following the transmit and receive from this particular code

http://www.handsonembedded.com/stm32f103-spl-tutorial-5/

I am using SPI4. an my Initialization of SPI is like this:

/* SPI4 init function */
void MX_SPI4_Init(void)
{

  hspi4.Instance = SPI4;
  hspi4.Init.Mode = SPI_MODE_MASTER;
  hspi4.Init.Direction = SPI_DIRECTION_2LINES;
  hspi4.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi4.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi4.Init.CLKPhase = SPI_PHASE_2EDGE;
  hspi4.Init.NSS = SPI_NSS_SOFT;
  hspi4.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
  hspi4.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi4.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi4.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  hspi4.Init.CRCPolynomial = 10;
  if (HAL_SPI_Init(&hspi4) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

}

Here is the code:

uint8_t SPISend(uint8_t data)
{
    SPI4->DR = data;
    while (!(SPI4->SR & SPI_SR_TXE));
    while (!(SPI4->SR & SPI_SR_RXNE));
    while (!(SPI4->SR & SPI_SR_BSY));
    return(SPI4->DR);
}

I this particular SPISend() method the control never reaches to the end. It's stuck in the loop while (!(SPI4->SR & SPI_SR_TXE)); .

My fuction call is like this:

void write8(char reg, unsigned char data)
{
    uint8_t retVal;
    enableChip;
    reg|=0x80;
    retVal = SPISend(reg);
    retVal = SPISend(data);
    disableChip;
}

Any suggestions.

Off the top of my head, SPI_CR1_SPE and/or SPI_CR1_SSI should be enabled in SPI4->CR1 . HAL_SPI_Init() doesn't set one or the other, but the HAL SPI transmit function does, you should do it yourself if you are using your own transmit code.

UPDATE

If you are enabling the SPE and SSI bits in enableChip , it'll be never called, because it's not a function call without the parentheses.

These two lines

SPI4->DR = data;
while (!(SPI4->SR & SPI_SR_TXE));

are in the wrong order. You wait first for TXE != 0 , which means that the transmitter queue is ready for more data, and then write the data.

The second line here

while (!(SPI4->SR & SPI_SR_RXNE));
while (!(SPI4->SR & SPI_SR_BSY));

will likely be an endless loop, because by the time SPI_SR_RXNE becomes 1 , or shortly thereafter, SPI_SR_BSY will change from 1 to 0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM