InputHysteresis Arduino Sketch

This sketch is used by Exercise: Input Hysteresis.

Full Source Code

The full code is all in one file InputHysteresis.ino.

 1// InputHysteresis.ino : Arduino program to demonstrate a simple single-state hysteretic response.
 2
 3// Copyright (c) 2014-2015, Garth Zeglin.  All rights reserved. Licensed under the terms
 4// of the BSD 3-clause license as included in LICENSE.
 5
 6// The baud rate is the number of bits per second transmitted over the serial port.
 7const long BAUD_RATE = 115200;
 8
 9// This assumes a photoresistor is pulling A0 up and a resistor is pulling A0
10// down.  When the input is bright, the voltage increases, when dark, the
11// voltage decreases.
12const int INPUT_PIN = A0;
13
14/****************************************************************/
15// Global variables.
16
17// The state of the system can be captured with only two values, e.g., it is
18// represented as a single bit.  The following statement defines two symbolic
19// values, one for each possible state.
20enum state_t { IS_DARK, IS_LIGHT };
21
22// Declare the state variable as a symbolic value.
23enum state_t state = IS_DARK;
24
25// The hysteretic response is defined by using two thresholds.  
26const int light_threshold = 700;
27const int dark_threshold  = 300;
28
29/****************************************************************/
30/**** Standard entry points for Arduino system ******************/
31/****************************************************************/
32
33// Standard Arduino initialization function to configure the system.
34
35void setup()
36{
37  // initialize the Serial port
38  Serial.begin( BAUD_RATE );
39
40  // configure our trivial I/O
41  pinMode( LED_BUILTIN, OUTPUT );
42
43  // the LED start out ON to match the initial state
44  digitalWrite(LED_BUILTIN, HIGH);
45}
46
47/****************************************************************/
48// Standard Arduino polling function.
49
50void loop()
51{
52  // Read the ambient light level.
53  int input = analogRead(INPUT_PIN);
54
55  if (state == IS_LIGHT) {
56    if (input < dark_threshold) {
57      Serial.print("Dark observed at input level ");
58      Serial.println(input);
59      Serial.println("Transitioning to the IS_DARK state.");
60      
61      state = IS_DARK;
62      digitalWrite(LED_BUILTIN, HIGH);
63    }
64
65  } else { // state must be IS_DARK
66    if (input > light_threshold) {
67      Serial.print("Light observed at input level ");
68      Serial.println(input);
69      Serial.println("Transitioning to the IS_LIGHT state.");
70      
71      state = IS_LIGHT;
72      digitalWrite(LED_BUILTIN, LOW);
73    }
74  }
75}
76
77/****************************************************************/