Arduino, CD4021 and SPI

The “ShiftIn” tutorial on the Arduino site (Parallel to Serial Shifting-In with a CD4021BE) is very clear on why and how to setup and test your Arduino in combination with a CD4021 IC. I needed extra digital inputs and decided to communicate via SPI with the CD4021 chip. Figured it out, it was actually pretty simple thanks to the easy SPI implementation in the Arduino software since version 0020 or so (?)

Setup as described in the Arduino tutorial. Reconnect the clock, the MOSI and the slaveselect as the #defines in the following code. And you’re all set.

#include

#define PIN_SCK          13             // SPI clock
#define PIN_MISO         12             // SPI data input
#define PIN_MOSI         11             // SPI data output
#define PIN_SS1          10             // SPI hardware default SS pin

void setup() {
  Serial.begin(9600);
  SPI.begin();
}

void loop() {
  digitalWrite(PIN_SS1,HIGH);

  // while gathering info from parallel inputs
  // do some other processing
  // for now I'll use
  delayMicroseconds(200);

  // select PIN_SS1 CD4021 IC
  digitalWrite(PIN_SS1,LOW);
  // read byte from CD4021 IC
  Serial.println(SPI.transfer(0x00),BIN);
}

tip: buy some resistor arrays instead of all individual resistors