AVR SPI gotcha

I've had all sorts of problems getting a SPI radio device to work for the last few days - I wasn't using the default /SS pin to select the slave as I was reusing some code from another program that already used the default /SS pin for a different device. For the life of me I couldn't figure out why I couldn't get it work reliably unless I used the standard /SS pin - if I used a different pin it sometimes worked, but most of the time didn't, or it just worked very slowly, or only if I waggled wires - most baffling. It's perfectly possible to drive multiple SPI devices using a different /SS pin for each, so I was completely stumped as to what was causing the problem. Eventually I noticed this in the documentation:

If /SS is configured as an output, the pin is a general output pin which does not affect the SPI system. Typically, the pin will be driving the /SS pin of the SPI Slave. If /SS is configured as an input, it must be held high to ensure Master SPI operation. If the /SS pin is driven low by peripheral circuitry when the SPI is configured as a Master with the /SS pin defined as an input, the SPI system interprets this as another master selecting the SPI as a slave and starting to send data to it.

And then the penny finally dropped - because I wasn't using the default /SS pin it wasn't being explicitly configured, which meant it was in the default post-reset state. The default post-reset state for pins is to be configured for input. That meant that any noise on the pin would trigger the logic that switched the AVR from SPI master to SPI slave mode, and things would apparently lock up, or generally start behaving oddly. It was easy enough to confirm this, I simply configured the default /SS pin to be an output pin, even thought I wasn't using it, and the problem went away.

Moral of the story: When using multiple SPI devices, always use the default /SS pin to control one of them.

Meta-moral of the story: Always re-read the documentation thoroughly when you have unexplained problems :-)

Categories : Tech, AVR