Little Bird Curriculum / code littlebird.com.au
vce_u1_06_hysteresis.ino Arduino (C/C++) 33 lines · 3 views ✦ Open in English IDE Raw Download Embed view

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);
}

Embed this snippet

As an iframe:

Or drop it inline with a script tag (injects the highlighted block where included):

Shared from Little Bird Electronics curriculum.

Copied to clipboard