Need help with SPI byte order and registers

honey_the_codewitch

Well-known member
I'm porting some code to make it friendlier to graphics libraries like mine and LVGL.
I'm confused about byte order.
See the if() in the code below. I know how to change the byte order of the else block, but not the if true block using the registers.
I was hoping for some help there - the same thing applies to DMA transfers. I need to turn off byte swapping.

Could anyone show me the secret sauce? I tried changing the ArduinoSPI settings but it was already MSBFIRST which I'm pretty sure is what i need based on my work on other platforms.

C++:
void SSD1351_t3::writedata16(uint16_t d)
{
    if (hwSPI) {
        maybeUpdateTCR(LPSPI_TCR_PCS(1) | LPSPI_TCR_FRAMESZ(15) | LPSPI_TCR_CONT);
        _pimxrt_spi->TDR = d;
        _pending_rx_count++;    //
        waitFifoNotFull();
    } else {
        DIRECT_WRITE_HIGH(_dcport, _dcpinmask);
        spiwrite(d >> 8);
        spiwrite(d);
    }
}
 
One option would be:

C++:
_pimxrt_spi->TDR = __builtin_bswap16(d);

Another:

C++:
_pimxrt_spi->TDR = (d >> 8) | (d << 8);

Not sure which is the most efficient method (or if it compiles to be the same byte code), but could aid your testing and you could measure. From an efficiency point of view, it's better to generate in the correct order vs swap every byte, every time - LVGL has the option to swap the bytes at generation, for instance. Also, can hwSPI be changed on the fly in the code? You don't really want to do an if check for every single pixel......unless it's const and optimized away by the compiler.
 
Last edited:
I do generate it in the correct order - big endian like the display. It's the SPI hardware that's doing the byte swapping. I want it not to.

Adding. I don't care about the efficiency of the routine above. 95% of my data is transmitted via DMA.
 
Back
Top