AnsweredAssumed Answered

Strange reading over SPI

Question asked by JulienD on May 15, 2015
Latest reply on Sep 21, 2016 by Imen D

I'm porting an implementation of SD over spi to stm2 using Cube library.
It seems that the communication micro to sd card is ok, it seems that the sd card
answers like it should but it looks like the microcontroler does not interpret correctly
the data on the spi bus.

To get this conclusion, I asked the micro to echo each byte received on SPI to an uart.
On the logic analyzer screen capture joined, you can see :
- on channel 5 (green), data micro -> SD
- on channel 7 (pink), data SD -> micro
- on channel 3 (orange), the uart echo.

Each byte on channel 3 should be the same of the preceeding byte on channel 7 which is
not always the case.

Here's the initialization code of the spi channel :

    GPIO_InitStructure.Pin   = GPIO_Pin_SPI_SD_SCK | GPIO_Pin_SPI_SD_MOSI;
    GPIO_InitStructure.Mode  = GPIO_MODE_AF_PP;
    GPIO_InitStructure.Pull = GPIO_NOPULL;
    GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
    GPIO_InitStructure.Alternate = GPIO_AF5_SPI2;
    HAL_GPIO_Init(GPIO_SPI_SD, &GPIO_InitStructure);

    GPIO_InitStructure.Pin   = GPIO_Pin_SPI_SD_MISO;
    GPIO_InitStructure.Mode  = GPIO_MODE_INPUT;
    GPIO_InitStructure.Pull = GPIO_PULLUP;   // obligatoire
    HAL_GPIO_Init(GPIO_SPI_SD, &GPIO_InitStructure);

    /* SPI configuration */
    hndSPI.Instance = SPI_SD;
    hndSPI.Init.Mode = SPI_MODE_MASTER;
    hndSPI.Init.Direction = SPI_DIRECTION_2LINES;
    hndSPI.Init.DataSize = SPI_DATASIZE_8BIT;
    hndSPI.Init.CLKPolarity = SPI_POLARITY_LOW;
    hndSPI.Init.CLKPhase = SPI_PHASE_1EDGE;
    hndSPI.Init.NSS = SPI_NSS_SOFT;
    hndSPI.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; // 72000kHz/256=281kHz < 400kHz
    hndSPI.Init.FirstBit = SPI_FIRSTBIT_MSB;
    hndSPI.Init.TIMode = SPI_TIMODE_DISABLED; // todo valeur au hasard = motorola, sinon TI
    hndSPI.Init.CRCPolynomial = 7;


Here's how I read over it :

BYTE rcvr_spi() {
    uint8_t rx;
    uint8_t tx = 0xff;
    HAL_SPI_TransmitReceive(&hndSPI, &tx, &rx, 1, 50);
    HAL_UART_Transmit(&huart4, &rx, 1, 50);
    return rx;

Does anybody have an idea of what could be wrong ?