#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 20, 4);
#define dataPin 2 /* Q7 */
#define clockPin 3 /* CP */
#define latchPin 4 /* PL */
const int numBits = 24; /* Set to 8 * number of shift registers */
byte pulseWidth = 2;
long oldOptionSwitch;
long keyValue;
long optionSwitch = 0;
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);
}
int getKey(void){
long optionSwitch = 0;
for( int i=24; i>=0; i-=8)
{
optionSwitch |= ((uint32_t) ReadOne165()) << i;
}
for( int i = 0; i<32; 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
}
void setup() {
Serial.begin(115200);
pinMode(dataPin, INPUT);
pinMode(clockPin, OUTPUT);
pinMode(latchPin, OUTPUT);
LCD.init();
LCD.backlight();
LCD.setCursor(0, 0);
LCD.print("Button Test ");
}
void loop() {
long keyValue = getKey();
Serial.print(keyValue,DEC);
LCD.setCursor(0, 1);
LCD.print(keyValue,DEC);
}