How to SPI: SD card + NFC reader?

How would one go about efficiently communicating with an SD card and NFC reader which are on the same SPI on the photon? My main question is about how to handle the protocol differences - for example SD card uses MSBFIRST but the NFC uses LSBFIRST, do I have to call ‘setBitOrder()’ along with pulling the SS down for the corresponding module every time I want to start data transfer with the other module or reverse the bytes before sending or are there any more alternatives?

If you want to only use one SPI interface, you’d need to change the bit order each time you swap active device.
But allow for the interface to “settle” with a short delay and try to reduce the need for swapping as good as possible.

But if you have the pins free, you could also use SPI for one device and SPI1 for the other.

@Melx, I’ve had this issue on other devices (SharpMem display). In that case, I chose an assembler software trick to reverse the order of the bits instead of changing the mode of the SPI hardware. I did this because a) The code is much faster than switching the SPI mode and b) I could not get the SPI mode switch to work, though I didn’t exactly break out my logic analyzer and spend a lot of time trying to figure it out. :smile:

I forgot to ask - Do both devices run in same SPI mode (0, 1, 2 or 3)? If not, then you have a bigger problem that could only address by using software SPI or using the SPI/SPI1 ports.

1 Like

They are running in the same mode. The following snippet works quite well in solving the problem.

c = (c & 0x55) << 1 | (c & 0xAA) >> 1;
c = (c & 0x33) << 2 | (c & 0xCC) >> 2;
c = c << 4 | c >> 4;

@Melx, here is the code I use:

/**************************************************************************/
/*
	@brief  Software reverse bits function, reverse the order of bits in
		byte
*/
/**************************************************************************/
uint8_t revBits(uint8_t val)
{
	return (uint8_t)(__RBIT(val) >> 24);
}

:smile:

2 Likes

Any library that uses SPI should set SPI speed, mode, and bit order before each SPI access. The library should insure chip select is high after each access.

The SdFat library for SD cards does share SPI this way. Old versions of SdFat ported from Arduino may not since the core SdFat used by Arduino SD.h is now over six years old.

Many other libraries ported from Arduino do not handle SPI transactions properly so look at the code in any ported library.