cancel
Showing results for 
Search instead for 
Did you mean: 

HAL SPI cannot handle LSB data?

KYou.1
Associate II

I setup SPI using CubeMX and set First Bit as LSB First as described in the datasheet.

0693W000005BOJEQA4.pngI thought setting this will handle LSB data by itself however it is not working as expected.

Below code only work with _SPI_HARDWARE_LSB defined which means I have to manually realign all the data in the buffer when transmitting through HAL_SPI function.

Is this is known issue or is how LSB suppose to be handled?

void spi_rw(uint8_t* data, uint8_t count) {
    HAL_GPIO_WritePin(RFID_SS_GPIO_Port, RFID_SS_Pin, GPIO_PIN_RESET);
    HAL_Delay(1);
#ifndef _SPI_HARDWARE_LSB
    for (uint8_t i = 0; i < count; i++) {
        data[i] = reverse_bit(data[i]);
    }
    HAL_SPI_TransmitReceive(&hspi1, data, data, count, _SPI_TIMEOUT);
    for (uint8_t i = 0; i < count; i++) {
        data[i] = reverse_bit(data[i]);
    }
#else
    HAL_SPI_TransmitReceive(&hspi1, data, data, count, _SPI_TIMEOUT);
#endif
    HAL_Delay(1);
    HAL_GPIO_WritePin(RFID_SS_GPIO_Port, RFID_SS_Pin, GPIO_PIN_SET);
}
 
uint8_t reverse_bit(uint8_t num) {
    uint8_t result = 0;
    for (uint8_t i = 0; i < 8; i++) {
        result <<= 1;
        result += (num & 1);
        num >>= 1;
    }
    return result;
}

1 REPLY 1
TDK
Guru

The hardware probably works. Put together a simpler example that strips possibly faulty logic from your program. Verify that SPIx_CR1_LSBFIRST is as expected.

If you feel a post has answered your question, please click "Accept as Solution".