Using SPI with shift registers

From HalfgeekKB
Revision as of 08:18, 23 February 2018 by Psmay (talk | contribs)
Jump to navigation Jump to search

74HC165 and similar

// 74HC165 connection via SPI

#include <SPI.h>

//  UNO   SPI   '165
//  9*    n/a   storage clock (ST_CP, /PL, DIP #1)
//  10*   NSS   shift clock inhibit (CLK INH, /CE, DIP #15)
//  11    MOSI  n/c
//  12    MISO  serial data output (Q7, DIP #9)
//  13    SCK   shift clock (SH_CP, CP, DIP #2)

// Note that the storage clock and the NSS can be anywhere. The UNO pin 10
// must be OUTPUT for the SPI master to work (the "NSS" functionality of the
// pin is applicable for SPI *in slave mode* when it is an input), but it
// need not be the actual select pin.

const uint8_t IM_STO = 9;
const uint8_t IM_NSS = 10;

const unsigned long IM_MAX_SPEED = 4000000; // A guess; could probably do way faster
const uint8_t IM_BIT_ORDER = MSBFIRST;
const uint8_t IM_SPI_MODE = SPI_MODE0;

void setup() {
  pinMode(IM_STO, OUTPUT);
  digitalWrite(IM_STO, true);
  pinMode(IM_NSS, OUTPUT);
  digitalWrite(IM_NSS, true);

  Serial.begin(115200);
  Serial.println("start");

  SPI.begin();
}

void sendStorePulse() {
  digitalWrite(IM_STO, false);
  delayMicroseconds(5);
  digitalWrite(IM_STO, true);
  delayMicroseconds(5);
}

uint8_t loadBySpi() {
  // Select device and begin transaction
  digitalWrite(IM_NSS, false);
  SPI.beginTransaction(SPISettings(IM_MAX_SPEED, IM_BIT_ORDER, IM_SPI_MODE));

  // Perform transfer
  uint8_t receivedData = SPI.transfer(0x00);

  // End transaction and deselect device
  SPI.endTransaction();
  digitalWrite(IM_NSS, true);

  return receivedData;
}

void loop() {
  sendStorePulse();
  uint8_t reading = loadBySpi();

  Serial.print("SPI: ");
  Serial.print(reading, BIN);
  Serial.println();

  delay(1000);
}


74HC595 and similar

Note: The following was tested on a shift register module with soldering defects on some outputs, so this code is only probably right. Recheck on known working hardware.

#include <SPI.h>

//  UNO   SPI   '595
//  9*    n/a   output disable (/OE, DIP #13)
//  10*   NSS   storage clock (ST_CP, DIP #12)
//  11    MOSI  serial data in (DS, DIP #14)
//  12    MISO  n/c
//  13    SCK   shift clock (SH_CP, CP, DIP #11)

const uint8_t OM_BLK = 9;
const uint8_t OM_STO = 10;

const unsigned long OM_MAX_SPEED = 4000000; // A guess
const uint8_t OM_BIT_ORDER = LSBFIRST;
const uint8_t OM_SPI_MODE = SPI_MODE0;

void setup() {
    pinMode(OM_BLK, OUTPUT);
    digitalWrite(OM_BLK, true);
    pinMode(OM_STO, OUTPUT);
    digitalWrite(OM_STO, true);

    SPI.begin();
}

void sendBySpi(uint8_t value) {
  digitalWrite(OM_STO, false);
  SPI.beginTransaction(SPISettings(OM_MAX_SPEED, OM_BIT_ORDER, OM_SPI_MODE));
  SPI.transfer(value);
  SPI.endTransaction();
  digitalWrite(OM_STO, true);
  digitalWrite(OM_BLK, false);
}

uint8_t c = 0;

void loop() {
  c = (uint8_t)((c + 1) & 0xFF);
  sendBySpi(c);
  delay(100);
}