Hysteresis for Day/Night LDR sensor

I've been trying to make an led turn on when it is dark and off when it is bright. The threshold at where it turns on or off is changed by using a potentiometer connected to an analog pin. But I've been having a problem with the led flashing on and off when the value of the ldr is close to the threshold value.

int sensorPin = A2; // select the input pin for ldr
int sensorValue = 0; // variable to store the value coming from the sensor

int calibratePin = A3;
int calibrateVal = 0;

int relayPin = 0;

void setup() {
void loop() {
sensorValue = analogRead(sensorPin); // read the value from the sensor
calibrateVal = analogRead(calibratePin);

if(sensorValue >= calibrateVal){



At the moment I decided that I could add a 10sec delay to the code so that the led won't flash, but if possible I'd rather use a different method without delaying the code. I've read that a hysteresis could be used, but I don't know how to implement it into my code.

Just have two thresholds, one that has to be exceeded to turn the LED on and the other that has to be smaller to turn the LED off. Have a variable that keeps track of the state of your LED so you know what threshold to use.

You might find that, if using hysteresis, you must set quite a large difference between the two thresholds to account for the variation in light levels on partially cloudy days or if there are trees/buildings that block the sun around sunrise & sunset.

I would stick to using a single threshold and using timing to prevent unwanted switching. Use the millis() function to check that at least 6hours have passed since the last switch.

I don't want to add two thresholds because I want to be able to change the threshold anytime with a potentiometer. If I had two thresholds then I'd need two potentiometers.

I'll go with using the millis() function instead. Thank you for the help guys!

If I had two thresholds then I’d need two potentiometers.

Wrong, read the first threshold from the pot and the second from the pot value plus an offset.