0
\$\begingroup\$

I have a CD4021BE set up very similarly to the Arduino ShiftIn Tutorial (the main difference being that I don't currently have 8 buttons so have just connected PI-5 to PI-7 to ground with a resistor, I get the same misbehaviour if these are left floating).

All of the values that I'm getting are being shifted up 1 bit, so with 5 buttons connected to PI-1 to 4 and PI-8), pressing the one connected to PI-1 gives me the value 00000010, pressing PI-2 gives me 00000100 and PI-8 just gives me 00000000.

I have my data pin connected to Q8, which as far as I can see in the Datasheet is the right place. Just to see what happened I connected it to Q6 and get 00001000 from PI-1 and so on.

I got 5 of these chips when I ordered them and have tested 3 so far and all perform in the same way, which really just suggests that I'm doing something stupid.

This is the code I'm currently using:

#define CLK 10
#define LATCH 9
#define DATA 8

int data;

void setup() {
  Serial.begin(9600);
  pinMode(DATA, INPUT);
  pinMode(CLK, OUTPUT);
  pinMode(LATCH, OUTPUT);
  Serial.println("Begin...");
}

void loop() {
  digitalWrite(LATCH, HIGH);

  digitalWrite(LATCH, LOW);

  data = shiftIn(DATA, CLK, MSBFIRST);

  Serial.println(data, BIN);

  delay(500);
}

CLK is connected to CLOCK on the chip, and LATCH is PARALLEL/SERIAL CONTROL.

Why is this happening?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

After much further googling, I found an 'answer' of sorts. An Issue on the Arduino implementation of shiftIn() with a workaround:

There is a workaround: If you turn the clock on before turning the control flag down, you avoid the extra positive clock transition. digitalWrite(shiftClock, HIGH); digitalWrite(shiftControl, LOW); I'm not sure if this is a bug or a missing feature. The problem is that the first bit is already on the Q8 output when first positive clock transition happens in shiftIn. I think this is what is described in the datasheet as "In the HCC/HCF4021B, the CLOCK input of theinternal stage is ”forced” whenasynchronous parallel entry is made".

I added a CLK high between the LATCH pulse and it now works:

void loop() {
  digitalWrite(LATCH, HIGH);
  digitalWrite(CLK, HIGH);   // Set clock high to catch first bit.
  digitalWrite(LATCH, LOW);

  data = shiftIn(DATA, CLK, MSBFIRST);
  ...
}

Just when I feel like I've actually started to get the hang of things I start hitting weird bugs in the libraries!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.