Skip to content

Instantly share code, notes, and snippets.

@nmaupu
Created January 15, 2019 15:45
Show Gist options
  • Save nmaupu/ed53d4b8e6243e49808ae9d4dadb8658 to your computer and use it in GitHub Desktop.
Save nmaupu/ed53d4b8e6243e49808ae9d4dadb8658 to your computer and use it in GitHub Desktop.
/**
* Base on the following tutorial
* https://playground.arduino.cc/Code/ShiftRegSN74HC165N
*/
/**
* I/O pins
*/
#define PLOAD_PIN 4 // 4 (8 on tutorial) - PD4
#define CLOCK_ENABLE_PIN 5 // 5 (9 on tutorial) - PD5
#define DATA_PIN 6 // 6 (11 on tutorial) - PD6
#define CLOCK_PIN 7 // 7 (12 on tutorial) - PD7
// Delay between shift register reads
#define POLL_DELAY_MSEC 1
// With of pulse to trigger shift register to read and latch
#define PULSE_WIDTH_USEC 5
// Nb of inputs available (more than 8 if daisy chaining shit registers)
#define NB_INPUTS_PER_REGISTER 8
#define NB_REGISTERS 2
#define NB_INPUTS (NB_INPUTS_PER_REGISTER * NB_REGISTERS)
// Custom type to store bytes
#define BYTES_VAL_T unsigned int
// Global vars
BYTES_VAL_T pinValues;
BYTES_VAL_T oldPinValues;
void setup() {
Serial.begin(9600);
pinMode(PLOAD_PIN, OUTPUT);
pinMode(CLOCK_ENABLE_PIN, OUTPUT);
pinMode(CLOCK_PIN, OUTPUT);
pinMode(DATA_PIN, INPUT);
digitalWrite(CLOCK_PIN, LOW);
digitalWrite(PLOAD_PIN, HIGH);
}
void loop() {
// Read the state of all zones
pinValues = read_shift_regs();
// In case of change, display the current status
if(pinValues != oldPinValues) {
display_pin_values();
oldPinValues = pinValues;
}
delay(POLL_DELAY_MSEC);
}
BYTES_VAL_T read_shift_regs() {
long bitVal;
BYTES_VAL_T bytesVal = 0;
// Trigger Parallel Load to latch the state of the data lines.
digitalWrite(CLOCK_ENABLE_PIN, HIGH);
digitalWrite(PLOAD_PIN, LOW);
delayMicroseconds(PULSE_WIDTH_USEC);
digitalWrite(PLOAD_PIN, HIGH);
digitalWrite(CLOCK_ENABLE_PIN, LOW);
// Loop to read each bit value from the serial out line of the register
for(int i=0; i<NB_INPUTS; i++) {
bitVal = digitalRead(DATA_PIN);
// Set the corresponding pin in bytesVal
bytesVal |= (bitVal << ((NB_INPUTS-1) - i));
// Pulse the clock (rising edge shifts the next bit)
digitalWrite(CLOCK_PIN, HIGH);
delayMicroseconds(PULSE_WIDTH_USEC);
digitalWrite(CLOCK_PIN, LOW);
}
return bytesVal;
}
void display_pin_values() {
Serial.print("Pin States:\n");
for(int i=0; i<NB_INPUTS; i++) {
Serial.print("P");
Serial.print(i);
Serial.print(":");
if((pinValues >> i) & 1)
Serial.print("H");
else
Serial.print("L");
Serial.print("\n");
}
Serial.print("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment