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
uint16_t optionSwitch = 0;
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 ()
{
read_state();
Serial.println(bitRead( optionSwitch, 15));
Serial.println();
delay(2000); // slow down the sketch to avoid switch bounce
}
void read_state(){
// Give a pulse to the parallel load latch of all 74HC165
optionSwitch = 0;
digitalWrite( latchPin, LOW);
delayMicroseconds( pulseWidth);
digitalWrite( latchPin, HIGH);
for( int i=8; i>=0; i-=8)
{
optionSwitch |= ((uint16_t) ReadOne165()) << i;
}
}
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);
}