/* cd4021Vv3 11/03/2024 This version will work with as many CD4021's as needed. All data is stored in the myButtons[] array Many thanks to runaway_pancake for writing some code that got me pointed in the right direction // Demo4021 // // A --1 16-- + // x --2 15-- B dataPin/SO --3 14-- C // E --4 13-- D // F --5 12-- x // G --6 11-- + // H --7 10-- clk // gnd --8 9-- latch */ #define NUMCD4021CHIPS 2 byte myButtons[NUMCD4021CHIPS];//sets the array to the number of chips int latchPin = 8; int clockPin = 7; int dataPin = 9; unsigned long currentMillis; unsigned long delayMillis; int delayTimer = 2000;//2 seconds void setup (){ Serial.begin(9600); Serial.println("cd4021Vv3"); pinMode (latchPin, OUTPUT); pinMode (clockPin, OUTPUT); pinMode (dataPin, INPUT); } void loop (){ int q; int w; currentMillis = millis(); if(currentMillis - delayMillis >= delayTimer){ delayMillis = currentMillis; //This sets the system up to read the data latch4021(latchPin);//This function MUST be called before the get4021Byte() is called for(q=0;q < NUMCD4021CHIPS;q++){ myButtons[q] = get4021Byte(dataPin,clockPin); //Put the bytes into the myButtons[] array } //At this point all the data is in the myButtons[] array and can be used as required //This just shows the results for(w=0;w < NUMCD4021CHIPS;w++){ Serial.print("myButtons[w] : "); Serial.print(w); Serial.print(" = "); Serial.println(myButtons[w],BIN); for(q=0;q<8;q++){//work though the bytes if(bitRead(myButtons[w],q) == 1){//if a bit is set Serial.print("Button Pressed : ");//tells us the button pressed 0-7 Serial.println(q); } } Serial.println(" "); } } } void latch4021(int funcPin){ digitalWrite (funcPin, HIGH); delayMicroseconds(5); //works... I want the smallest stable value possible digitalWrite (funcPin, LOW); } byte get4021Byte(int funcDataPin, int funcClockPin){ byte registerContent; int bitContent; for (int idx = 0; idx < 8; idx++) { bitContent = digitalRead (funcDataPin); if (bitContent == 1) { bitWrite (registerContent,idx,1); } else { bitWrite (registerContent,idx,0); } digitalWrite (funcClockPin, LOW); delayMicroseconds(5); //works... I want the smallest stable value possible digitalWrite (funcClockPin, HIGH); } return registerContent; }