const byte latchPin = 5; // to latch the inputs into the registers
const byte clockPin = 18; // I choose the SCK pin
const byte dataPin = 19; // I choose the MISO pin
const int numberOfRegisters = 32;
uint8_t switchStates[numberOfRegisters];
boolean switchStatesEach[numberOfRegisters][8];
const int pulseWidth = 10; // pulse width in microseconds
// The ReadOne165() function reads only 8 bits,
// because of the similar functions shiftIn() and SPI.transfer()
// which both use 8 bits.
//
// The shiftIn() can not be used here, because the clock is set idle low
// and the shiftIn() makes the clock high to read a bit.
// The 74HC165 require to read the bit first and then give a clock pulse.
//
byte ReadOne165()
{
byte ret = 0x00;
// The first one that is read is the highest bit (input D7 of the 74HC165).
for( int i=7; i>=0; i--)
{
if( digitalRead( dataPin) == HIGH)
bitSet( ret, i);
digitalWrite( clockPin, HIGH);
delayMicroseconds( pulseWidth);
digitalWrite( clockPin, LOW);
}
return( ret);
}
void setup ()
{
Serial.begin( 115200);
Serial.println( "Turn on and off the switches");
Serial.println( "Top row is switch 0 (right) to switch 7 (left)");
Serial.println( "Second row is 8 to 15, and so on");
pinMode( clockPin, OUTPUT); // clock signal, idle LOW
pinMode( latchPin, OUTPUT); // latch (copy input into registers), idle HIGH
digitalWrite( latchPin, HIGH);
}
void loop ()
{
// Give a pulse to the parallel load latch of all 74HC165
digitalWrite( latchPin, LOW);
delayMicroseconds( pulseWidth);
digitalWrite( latchPin, HIGH);
// Reading one 74HC165 at a time and combining them into a 32 bit variable
// The last 74HC165 is at the bottom, but the switches start numbering
// at the top. So the first byte has to be shifted into the highest place.
for( int i=numberOfRegisters-1; i>=0; i--)
{
uint8_t temp = (uint8_t) ReadOne165();
if(switchStates[i] != temp)
{
Serial.print( "Switches ");
Serial.print(i*8);
Serial.print(" tot ");
Serial.print((i+1)*8);
Serial.print(" : ");
Serial.println(temp);
switchStates[i] = temp;
for( int j=7; j>=0; j--)
{
boolean switchState = (bitRead(temp,j) == 0 ? false:true);
Serial.print(switchState);
switchStatesEach[i][j] = switchState;
// if(switchStatesEach[i][j] != switchState)
// {
// Serial.println(switchState);
// }
}
Serial.println();
}
}
delay( 25); // slow down the sketch to avoid switch bounce
}