Shift Register Issue

Hello.

I have a model railway and just built a circuit board that uses coils to sense current draw and connects a pin from a 4021B register to GND via a 555 timer to remove any small current fluctuations.

I then wrote a simple program for my clone mega to read in the status of all the inputs and print them to serial.

//define where your pins are
int latchPin = 8;
int dataPin = 9;
int clockPin = 7;
byte switchVar1;

void setup() {
  //start serial
  Serial.begin(9600);

//define pins used to connect to the CD4021 Shift Register
  pinMode(dataPin, INPUT);
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT); 

}

void loop() {

  //Set latch pin to 1 to get recent data into the CD4021
  digitalWrite(latchPin,1);
  
  delayMicroseconds(50);
  
  //Set latch pin to 0 to get data from the CD4021
  digitalWrite(latchPin,0);

  //Get CD4021 register data in byte variable
  switchVar1 = shiftIn(dataPin, clockPin, MSBFIRST);
  Serial.println(switchVar1, BIN);
  delay(500);
}

When I activate the unit with no draw I get 11111111 displayed. When I add a current draw to one of the coils it displays 11111101. The problem is that it doesn’t stay like that. Keeps changing back to 11111111, 11111011 and 11111110. I have connected a small led to the same output of the 555 timer and that stays constantly lit whist there is a current draw.

Would seem to be a problem at the logic level of the circuit.

As this is the first time I have used a shift register for input am i doing anything wrong in my code?

Thanks.

There's not much to go wrong with your code. We really need to see a schematic of how you have wired this all up. Sounds like it could be floating inputs, on the shift register perhaps.