//74hc165
const byte inputLatchPin = 7; // Пин защелки входной микросхемы 74HC165
const byte inputClockPin = 6; // Пин управляющего clock микросхемы
const byte inputDataPin = 5; // Пин для передачи данных от кнопок
//74hc595
const int outputLatchPin = 4; // Пин защелки выходной микросхемы 74HC595
const int outputClockPin = 3; // Пин управляющего clock микросхемы
const int outputDataPin = 2;// Пин для передачи данных на микросхему 74HC595
uint32_t oldOptionSwitch = 0; // previous state of all the inputs
const int pulseWidth = 10; // pulse width in microseconds
void setup() {
// put your setup code here, to run once:
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( inputClockPin, OUTPUT); // clock signal, idle LOW
pinMode( inputLatchPin, OUTPUT); // latch (copy input into registers), idle HIGH
digitalWrite( inputLatchPin, HIGH);
}
void loop() {
// Give a pulse to the parallel load latch of all 74HC165
digitalWrite( inputLatchPin, LOW);
delayMicroseconds( pulseWidth);
digitalWrite( inputLatchPin, 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.
uint32_t optionSwitch = 0;
for( int i=16; i>=0; i-=8)
{
optionSwitch |= ((uint32_t) ReadOne165()) << i;
}
for( int i = 0; i<24; i++)
{
if( bitRead( optionSwitch, i) != bitRead( oldOptionSwitch,i))
{
Serial.print( "Switch ");
if( i < 10)
Serial.print( " ");
Serial.print( i);
Serial.print( " is now ");
Serial.println( bitRead( optionSwitch, i) == 0 ? "down ↓" : "up ↑");
}
}
oldOptionSwitch = optionSwitch;
delay( 25); // slow down the sketch to avoid switch bounce
}
// 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( inputDataPin) == HIGH)
bitSet( ret, i);
digitalWrite( inputClockPin, HIGH);
delayMicroseconds( pulseWidth);
digitalWrite( inputClockPin, LOW);
}
return( ret);
}