SDFat with multiple SPI devices (Shared SPI Bus)

Status
Not open for further replies.
Hello all,

This is more of a "tip" to anyone using SDFat (https://github.com/greiman/SdFat) with their Teensy 3.x devices. Specifically, this tip applies to anyone using SDFat and other devices on the same SPI bus.

In the project I'm working on, I use SDFat for data-logging to an SD card and the same SPI bus to communicate with some MCP2515 CAN controllers. The baud rates are different, but the Mode (referencing the "4-modes" of SPI) are the same, both Mode 0. My problem was that I could get SD logging to work or the MCP2515 chips working, but not both at the same time. Ultimately, if SD logging was occurring, the MCP2515 SPI data would appear to be corrupted and I couldn't read data from the chips properly. Looking at the data on a scope revealed that the data was being sent to the chips fine and the chips were responding with the expected data, but my SPI routines wouldn't receive the same data.

As it turns out, I needed to clear the RX FIFO buffer in the Teensy before sending SPI data to/from the MCP2515's. I didn't find a specific function to do this in the SPI.h files, so I made a simple function to do this.

Here is an example:

Code:
void SpiFlushRxFifo(void)
{
	uint32_t u32_SPI0_MCR_copy;
	/* Flush the RX FIFO */
	u32_SPI0_MCR_copy = SPI0_MCR;	// Grab a copy of the current register value
	SPI0_MCR |= SPI_MCR_CLR_RXF;
}

...Using the flushing function:

Code:
	can2.beginTransaction(SPISettings(MCP2515_MAXSPEED,MSBFIRST,SPI_MODE0));
	SpiFlushRxFifo();
	digitalWrite(CAN2_CS,LOW);		// pull down CS
	can2.transfer(MCP2515_READ);	// READ command
	can2.transfer(CANSTAT);		// Start address
	retVal = (can2.transfer(DUMMY) >> 1u) & 0x07u;
	digitalWrite(CAN2_CS,HIGH);		// Release the CS
	can2.endTransaction();

I hope this helps someone else that's also dealing with similar strangeness while sharing the SPI bus with SDFat.
 
@afterhoursengineering - I just wanted to reply and thank you for posting this! Your function worked great for me and got me up and running. In my prior work around I wound up exchanging data with my other SPI device using digitalWrite/digitalRead. Thanks again!
 
Thank you

I just registered on this forum so that I could THANK YOU for taking the time to post that. You have saved me countless hours of frustration.
 
Hello,
Thank you very much for sharing. I am having the same problem. I am using Teensy 3.2+SDFAT+MCP2515(Seeed Library). I can get them working alone but not togother.
I would like to use your function but i don not know which file i need to change. It would be great if someone can help me.
Thanks!
Basel
 
Status
Not open for further replies.
Back
Top