Skip to content

Instantly share code, notes, and snippets.

@robotjoosen
Created May 11, 2013 12:52
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save robotjoosen/5559890 to your computer and use it in GitHub Desktop.
//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