Keep SPI/TWI master active

avrcommunicationi2cmicrocontrollerspi

I'm designing a data recorder application which uses an 8-bit AVR microcontroller. It uses the TWI and SPI interfaces with the microcontroller being the master. There is one SPI device, a microSD card, and one TWI device, the MMA8452 accelerometer. The accelerometer is going to be sampled at 400~800 Hz, and I plan on storing relatively large amounts of data so there will be semi-frequent writes to the microSD card as the uC's memory gets filled.

My question is what is the recommended workflow for enabling/disabling the interfaces. Can I keep the SS for the SPI interface asserted low throughout my application, or should I only keep it active when I'm interfacing with the microSD card?

Also, can I keep the TWI/SPI master interfaces enabled, or should I enable them only when the interface is required?

ex. code (for TWI, similar for SPI):

// enable/disable during each operation
twi_master_enable(&TWIC);
// ... TWI-related operations
twi_master_disable(&TWIC);

Or, is this better:

// initialization/wake-up code
twi_master_enable(&TWIC);

// .. somewhere else in the code, perform TWI operations

// power-down/sleep code
twi_master_disable(&TWIC);

Best Answer

You should keep them enabled.

SD cards require the /SS line to be toggled at certain times, to e.g. reset the SPI transfer to a known state, cut an otherwise longer transaction shorter, etc. So you cannot leave it always asserted, it needs to be controlled correctly.

You will run into problems with SD performance. It is hard to find exact specifications for all manufacterers, but most SD cards can go "out to lunch" for up to 250 ms while doing internal write cycles (which may include large erases, or sector remapping to balance load). You'll find that while writes to the card will initially return in a few tens or hundreds of microseconds, once in a while (maybe every 30 seconds or so, depends highly on the card) the card will take a few tens to hundreds of milliseconds to complete the write. This means you'll need the capability to buffer hundreds of accelerometer samples, so you'll have to be careful to ensure you have enough free SRAM in your AVR for that. Or, add external buffer storage. I've had great success with FRAM chips, due to the speed at which it can read and write single bytes.