SPI Interface, Endianness and bitrev(..)

Technical questions regarding the XTC tools and programming with XMOS.
User avatar
jonathan
Respected Member
Posts: 377
Joined: Thu Dec 10, 2009 6:07 pm

SPI Interface, Endianness and bitrev(..)

Post by jonathan »

Code: Select all

void spi_out_byte(unsigned char data)
{
	// MSb-first bit order - SPI standard
	unsigned x = bitrev(data) >> 24;
	spi_mosi <: x;
	spi_sclk <: 0xAA;
	spi_sclk <: 0xAA;
	sync(spi_sclk);
	spi_miso :> void;
}
This is a fragment from the XMOS-originated SPI interface.

bitrev() appears to be an assembler instruction that does what it says: reverses the bits in a word. I'm assuming therefore that chars are stored in the fourth byte of a register? The code fragment also appears to imply that they are stored little-endian bit order, so that applying bitrev and then right-shifting by 24 will leave the fourth byte of the register holding the char in big-endian bit order. Is this correct?

The rest of the SPI interface assumes a big-endian byte order.

Finally, the output to the 1-bit 8-place buffered port spi_mosi using an unsigned (32-bit) integer will presumably do some conversion too - I assume it knows to read the least-significant byte assuming a big-endian format as the 8 bits?

Appreciate help with this. I think the way the code is written is far from obvious, and I'll comment it up with any help I receive before putting it somewhere helpful for others to use.


Image
richard
Respected Member
Posts: 318
Joined: Tue Dec 15, 2009 12:46 am

Post by richard »

I assume that spi_mosi is a buffered output port of width 8 (this isn't shown in the snippet of code). Serialising ports output the least significant port width bits of data first. Usually data transferred over SPI is transmitted most significant bit first. Because of this the bits in the byte you want to send must be reversed.

bitrev(data) reverses bits in the word. The least significant byte of data ends up reversed in the most significant byte of the result. The shift >> 24 is used to extract the most significant byte. The end result is the least significant byte of data is reversed.
Last edited by richard on Tue Mar 09, 2010 7:12 pm, edited 1 time in total.
User avatar
Andy
Respected Member
Posts: 279
Joined: Fri Dec 11, 2009 1:34 pm

Post by Andy »

I think I'm using

Code: Select all

byterev(bitrev(data))
in my SPI code to do the reversal, but haven't got it at hand.
User avatar
mike
Member++
Posts: 19
Joined: Fri Dec 11, 2009 11:21 am

Post by mike »

The port behaviour is documented in chapter 2 of the XC programming manual: http://www.xmos.com/system/files/xcuser_en.pdf

Mike