Two thresholds with a gap between them, so the output switches cleanly instead of chattering.
From the unit VCE Systems Engineering Unit 1 — Electrotechnological systems design
· activity PRP 6: Hysteresis, and open versus closed loop
// PRP 6 — hysteresis.
//
// One threshold chatters because the sensor's own noise crosses it
// repeatedly. Two thresholds with a gap wider than that noise fixes it.
//
// Make the gap wider than the noise you measured in PRP 4, and no wider.
const int SENSOR_PIN = A0;
const int OUTPUT_PIN = 13;
const int TURN_ON_BELOW = 480; // <-- your numbers
const int TURN_OFF_ABOVE = 520;
bool outputOn = false;
void setup() {
pinMode(OUTPUT_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
int reading = analogRead(SENSOR_PIN);
if (!outputOn && reading < TURN_ON_BELOW) {
outputOn = true;
} else if (outputOn && reading > TURN_OFF_ABOVE) {
outputOn = false;
}
// Between the two thresholds nothing changes. That is the whole trick.
digitalWrite(OUTPUT_PIN, outputOn ? HIGH : LOW);
Serial.println(reading);
delay(100);
}
Shared from Little Bird Electronics curriculum.