int dataPin = 2;
int clockPin = 4;
int latchPin = 6;
int ledExp[] = {7,6,5,4,3,2,1,0};
byte leds;
int chaserRightToLeftTurnOnPattern[] = {1, 3, 7, 15, 31, 63, 127, 255};
int chaserLeftToRightTurnOffPattern[] = {255, 127, 63, 31, 15, 7, 3, 1, 0};
uint32_t oldOptionSwitch = 0;
const int pulseWidth = 10;
void setup() {
Serial.begin(115200);
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(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.
uint32_t 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);
}
void updateShift(byte leds, int ms){
digitalWrite(latchPin, HIGH);
shiftOut(dataPin, clockPin, LSBFIRST, leds);
digitalWrite(latchPin, LOW);
delay(ms);
}
void chaserRightToLeftTurnOn(){
for(int i=0; i<8; i++){
int val = chaserRightToLeftTurnOnPattern[i];
updateShift(val, 500);
Serial.println(val);
};
}
void chaserLeftToRightTurnOff(){
for(int i=0; i<9; i++){
int val = chaserLeftToRightTurnOffPattern[i];
updateShift(val, 500);
Serial.println(val);
};
};
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);
}