Photocell in pin A0, causing chartering output

Newbeeeeee, of course. Using a photocell to tell wheter its light or dark with 5vdc external supply to photocell leg 1 , leg 2 to A0, 1kohm resistor from leg 2 to ground. the code if ((distance) < 200 && (analogRead(0)) < 100){digitalWrite(3,HIGH);}
else{digitalWrite(3,LOW);} pin 3 in an input to to 5vdc relay driving a light. The light chatters on and off. i can put in a delay to slow it down, but cant figure out why its chattering when i make the photocell value drop below 100. What am i doing wrong?


Please read and follow the directions in the “How to use this forum” post.

Post the code properly and also post a hand drawn (not “Fritzing for the brain dead”) circuit diagram, showing the power supply and relay connections.

Post a link to the exact relay module you have.

The hysteresis tutorial may be of interest.

When the illumination is low, turn on the light to increase the illumination? Then it’s brighter and it’s time to turn the light off.

You need to shield the sensor from the light. It should not see any of its own light. Plus add some hysteresis.