This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Declare CD4021 Pins | |
int __cd4021b_latchPin = 8; | |
int __cd4021b_dataPin = 9; | |
int __cd4021b_clockPin = 7; | |
void setup() { | |
//Start Serial Communication | |
Serial.begin(9600); | |
//Set pinMode of CD4021BCN | |
pinMode(__cd4021b_latchPin, OUTPUT); | |
pinMode(__cd4021b_clockPin, OUTPUT); | |
pinMode(__cd4021b_dataPin, INPUT); | |
} | |
void loop() { | |
//Get Inputs states in 1 byte a.k.a. 8 bit | |
byte inputValues = getInput(); | |
/* | |
HOW TO USE | |
Selecting a single input (a bit) from its inputValues (the byte) and testing if its TRUE or FALSE | |
in this case we check the first bit (bit 0) and see if its true or false. | |
*/ | |
if(getBit(inputValues,0)){ | |
Serial.println("The first bit is true a.k.a the first button is pushed"); | |
} else { | |
Serial.println("The first bit is false a.k.a the first button is not pushed"); | |
} | |
/* | |
OR | |
Looping through all values (bits) and see what they do | |
*/ | |
for(int i=0;i<8;i++){ | |
if(getBit(inputValues,i)){ | |
Serial.print("true"); | |
} else { | |
Serial.print("false"); | |
} | |
Serial.print("\t |"); | |
} | |
Serial.println(); | |
// A Delay to Slow things down, 1sec for readability, remove in real code | |
delay(1000); | |
} | |
/* | |
* CD4021BCN Shift Register - Functions | |
* Read Only when you really want to | |
* | |
*/ | |
boolean getBit(byte b, int bitNumber) | |
{ | |
return (b & (1 << bitNumber)) != 0; | |
} | |
byte getInput() | |
{ | |
byte input = B11111111; | |
digitalWrite(__cd4021b_latchPin,1); | |
delayMicroseconds(20); | |
digitalWrite(__cd4021b_latchPin,0); | |
input = shiftIn(__cd4021b_dataPin, __cd4021b_clockPin); | |
return input; | |
} | |
byte shiftIn(int thisDataPin, int thisClockPin) | |
{ | |
int temp = 0; | |
int pinState; | |
byte thisDataIn = 0; | |
pinMode(thisClockPin, OUTPUT); | |
pinMode(thisDataPin, INPUT); | |
for(int i=7;i>=0;i--){ | |
digitalWrite(thisClockPin, 0); | |
delayMicroseconds(2); | |
temp = digitalRead(thisDataPin); | |
if(temp) { | |
pinState = 1; | |
thisDataIn = thisDataIn | (1 << i); | |
} else { | |
pinState = 0; | |
} | |
digitalWrite(thisClockPin, 1); | |
} | |
return thisDataIn; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment