Using SPI with shift registers
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);
}