const uint8_t shift_registers_count = 4;
uint8_t shift_registers_data [ shift_registers_count ];
uint8_t shift_registers_previous_data [ shift_registers_count ];
const byte latchPin = 9; // to latch the inputs into the registers
const byte clockPin = 13; // I choose the SCK pin
const byte dataPin = 12; // I choose the MISO pin
const int pulseWidth = 10; // pulse width in microseconds
void setup ()
{
Serial.begin( 115200);
pinMode( clockPin, OUTPUT); // clock signal, idle LOW
pinMode( latchPin, OUTPUT); // latch (copy input into registers), idle HIGH
digitalWrite( latchPin, HIGH);
}
void loop ()
{
ReadAll165();
CompareAll165();
delay( 25); // slow down the sketch to avoid switch bounce
}
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 ReadAll165()
{
// Give a pulse to the parallel load latch of all 74HC165
digitalWrite( latchPin, LOW);
delayMicroseconds( pulseWidth);
digitalWrite( latchPin, HIGH);
for( uint8_t i = 0; i < shift_registers_count; ++i )
{
shift_registers_previous_data[ i ] = shift_registers_data[ i ];
shift_registers_data[ i ] = ReadOne165();
}
}
void CompareAll165()
{
for( uint8_t i = 0; i < shift_registers_count; ++i)
{
const uint8_t previous_data = shift_registers_previous_data[ i ];
const uint8_t data = shift_registers_data[ i ];
// If at least one of the 8 states from this shift register has changed
if ( previous_data != data )
{
for( uint8_t j = 0; j < 8; ++j )
{
if ( bitRead( data, j ) != bitRead( previous_data, j ) )
{
uint16_t switch_id = ( i * 8 ) + j;
Serial.print( "Switch ");
if( switch_id < 10 )
Serial.print( " " );
Serial.print( switch_id );
Serial.print( " is now " );
Serial.println( bitRead( data, j ) == 0 ? "down ↓" : "up ↑" );
}
}
}
}
}