Electronic – arduino – Using a counter to reduce pin counts for SPI slave selection

arduinocounterspi

I've got five SPI SRAM chips, which I want to control off a single Arduino. I've seen setups like this, which share SCLK, MOSI and MISO, with separate SS pins:

Multiple slave SPI
(image courtesty of Wikipedia)

However, I'd like to avoid using five pins for separate SS enables. I'm considering using a counter to select the different slaves, so I can cut the count down to 2 pins.

The idea is to use two pins for the counter's direction and clock. The code would look something like this:

int currentSlave = 1; // on setup I'll set the counter to 1

void SelectSlave(int id)
{
  // error checking
  if (id < 1 || id > 5) Serial.writeln("Invalid slave ID passed to SelectSlave.");

  // calculate the ID difference
  int diff = abs(id - currentSlave);
  if (diff == 0) return; // no need to do anything

  if (id > currentSlave) set(CTR_DIRECTION); // increment
  if (id < currentSlave) clear(CTR_DIRECTION); // decrement

  // calculate the number of clock pulses to send to the counter
  int pulses = 0;
  if (id > currentSlave) pulses = (1 << (id - 1)) - (1 << (currentSlave - 1));
  if (id < currentSlave) pulses = (1 << (currentSlave - 1)) - (1 << (id - 1));

  // send the clock pulses
  for(int i = 0; i < pulses; i++)
  {
    set(CTR_CLOCK);
    delay(1);
    clear(CTR_CLOCK);
    delay(1);
  }
}

I have a few questions:

  • Are there any issues related to turning multiple SS pins on and off during the interim counting period?
  • Can I rely on (most) counters being set to zero when it is first powered on?
  • Are there other/better ways to cut pin counts in this kind of setup?

Best Answer

You might consider a serial-in-parallel-out shifter like 74HC164. You need 2 pins. You can generate as many enables as you wish with 2 pins. A 74HC138 decoder would need more pins as the number of outputs increased. A counter would need many many clock pulses to enable only one output at a time in some cases. The 74HC164 shifter needs at most n clock pulses to produce n enables.

Related Topic