SPI Interface, Endianness and bitrev(..)

Technical questions regarding the xTIMEcomposer, xSOFTip Explorer and Programming with XMOS.
User avatar
Respected Member
Posts: 377
Joined: Thu Dec 10, 2009 6:07 pm

SPI Interface, Endianness and bitrev(..)

Postby jonathan » Tue Mar 09, 2010 11:33 am

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;
	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.
Respected Member
Posts: 318
Joined: Tue Dec 15, 2009 12:46 am

Postby richard » Tue Mar 09, 2010 12:23 pm

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
Respected Member
Posts: 279
Joined: Fri Dec 11, 2009 1:34 pm

Postby Andy » Tue Mar 09, 2010 12:43 pm

I think I'm using

Code: Select all

in my SPI code to do the reversal, but haven't got it at hand.
User avatar
Posts: 19
Joined: Fri Dec 11, 2009 11:21 am

Postby mike » Tue Mar 09, 2010 12:57 pm

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


Who is online

Users browsing this forum: No registered users and 7 guests