co2_sensor.cpp 11.2 KB
Newer Older
1
2
3
4
#include "co2_sensor.h"

namespace config {
  // Values should be defined in config.h
Eric Duminil's avatar
Eric Duminil committed
5
6
7
  uint16_t measurement_timestep = MEASUREMENT_TIMESTEP; // [s] Value between 2 and 1800 (range for SCD30 sensor)
  const uint16_t altitude_above_sea_level = ALTITUDE_ABOVE_SEA_LEVEL; // [m]
  uint16_t co2_calibration_level = ATMOSPHERIC_CO2_CONCENTRATION; // [ppm]
Eric Duminil's avatar
Eric Duminil committed
8
9
  int8_t max_deviation_during_calibration = 30; // [ppm]
  int8_t enough_stable_measurements = 60;
10
11
12
#ifdef TEMPERATURE_OFFSET
  // Residual heat from CO2 sensor seems to be high enough to change the temperature reading. How much should it be offset?
  // NOTE: Sign isn't relevant. The returned temperature will always be shifted down.
Eric Duminil's avatar
Eric Duminil committed
13
  const float temperature_offset = TEMPERATURE_OFFSET; // [K]
14
15
16
#else
  const float temperature_offset = -3.0;  // [K] Temperature measured by sensor is usually at least 3K too high.
#endif
17
  bool auto_calibrate_sensor = AUTO_CALIBRATE_SENSOR; // [true / false]
18
  const bool debug_sensor_states = false; // If true, log state transitions over serial console
19
20
21
22
}

namespace sensor {
  SCD30 scd30;
23
  uint16_t co2 = 0;
24
25
  float temperature = 0;
  float humidity = 0;
26
  char timestamp[23];
27
  int16_t stable_measurements = 0;
Käppler's avatar
Käppler committed
28
29
30
31
32
33
34
35
36
37
38

  /**
   * Define sensor states
   * INITIAL -> initial state
   * BOOTUP -> state after initializing the sensor, i.e. after scd.begin()
   * READY -> sensor does output valid information (> 0 ppm) and no other condition takes place
   * (NOTE: This state is currently unused)
   * NEEDSCALIBRATION -> sensor measurements are too low (< 250 ppm)
   * PREPARECALIBRATION -> forced calibration was initiated, waiting for stable measurements
   * CALIBRATION -> the sensor does calibrate itself
   */
39
40
41
42
  enum state {
    INITIAL,
    BOOTUP,
    READY,
43
    NEEDS_CALIBRATION,
44
    PREPARE_CALIBRATION_UNSTABLE,
45
    PREPARE_CALIBRATION_STABLE,
46
    CALIBRATION
Käppler's avatar
Käppler committed
47
  };
48
49
50
51
  const char *state_names[] = {
      "INITIAL",
      "BOOTUP",
      "READY",
52
      "NEEDS_CALIBRATION",
53
      "PREPARE_CALIBRATION_UNSTABLE",
54
      "PREPARE_CALIBRATION_STABLE",
55
      "CALIBRATION" };
Käppler's avatar
Käppler committed
56
57
58
  state current_state = INITIAL;
  void switchState(state);

59
60
  void initialize() {
#if defined(ESP8266)
61
    Wire.begin(12, 14); // ESP8266 - D6, D5;
62
63
#endif
#if defined(ESP32)
Eric Duminil's avatar
Eric Duminil committed
64
    Wire.begin(21, 22); // ESP32
65
66
67
68
69
70
71
72
73
74
75
    /**
     *  SCD30   ESP32
     *  VCC --- 3V3
     *  GND --- GND
     *  SCL --- SCL (GPIO22) //NOTE: GPIO3 Would be more convenient (right next to GND)
     *  SDA --- SDA (GPIO21) //NOTE: GPIO1 would be more convenient (right next to GPO3)
     */
#endif

    // CO2
    if (scd30.begin(config::auto_calibrate_sensor) == false) {
Eric Duminil's avatar
Eric Duminil committed
76
77
78
      Serial.println(F("ERROR - CO2 sensor not detected. Please check wiring!"));
      led_effects::showKITTWheel(color::red, 30);
      ESP.restart();
79
80
    }

Käppler's avatar
Käppler committed
81
82
    switchState(BOOTUP);

83
    // SCD30 has its own timer.
Eric Duminil's avatar
Eric Duminil committed
84
    //NOTE: The timer seems to be inaccurate, though, possibly depending on voltage. Should it be offset?
85
86
87
88
    Serial.println();
    Serial.print(F("Setting SCD30 timestep to "));
    Serial.print(config::measurement_timestep);
    Serial.println(" s.");
Eric Duminil's avatar
Eric Duminil committed
89
    scd30.setMeasurementInterval(config::measurement_timestep); // [s]
90

91
    Serial.print(F("Setting temperature offset to -"));
92
93
94
    Serial.print(abs(config::temperature_offset));
    Serial.println(" K.");
    scd30.setTemperatureOffset(abs(config::temperature_offset)); // setTemperatureOffset only accepts positive numbers, but shifts the temperature down.
95
    delay(100);
96

97
    Serial.print(F("Temperature offset is : -"));
98
99
100
    Serial.print(scd30.getTemperatureOffset());
    Serial.println(" K");

101
    Serial.print(F("Auto-calibration is "));
102
    Serial.println(config::auto_calibrate_sensor ? "ON." : "OFF.");
103

104
105
106
    sensor_console::defineIntCommand("co2", setCO2forDebugging, F(" 1500 (Sets co2 level, for debugging purposes)"));
    sensor_console::defineIntCommand("timer", setTimer, F(" 30 (Sets measurement interval, in s)"));
    sensor_console::defineCommand("calibrate", startCalibrationProcess, F(" (Starts calibration process)"));
Eric Duminil's avatar
Eric Duminil committed
107
    sensor_console::defineIntCommand("calibrate", calibrateSensorToSpecificPPM,
108
        F(" 600 (Starts calibration process, to given ppm)"));
Eric Duminil's avatar
Eric Duminil committed
109
    sensor_console::defineIntCommand("calibrate!", calibrateSensorRightNow,
110
111
112
        F(" 600 (Calibrates right now, to given ppm)"));
    sensor_console::defineIntCommand("auto_calibrate", setAutoCalibration,
        F(" 0/1 (Disables/enables autocalibration)"));
113
114
  }

Eric Duminil's avatar
Eric Duminil committed
115
  //NOTE: should timer deviation be used to adjust measurement_timestep?
Eric Duminil's avatar
Eric Duminil committed
116
  void checkTimerDeviation() {
117
    static int32_t previous_measurement_at = 0;
Eric Duminil's avatar
Eric Duminil committed
118
    int32_t now = millis();
119
    Serial.print(F("Measurement time offset : "));
Eric Duminil's avatar
Eric Duminil committed
120
121
122
123
124
    Serial.print(now - previous_measurement_at - config::measurement_timestep * 1000);
    Serial.println(" ms.");
    previous_measurement_at = now;
  }

125
126
  bool countStableMeasurements() {
    // Returns true, if a sufficient number of stable measurements has been observed.
Eric Duminil's avatar
Eric Duminil committed
127
    static int16_t previous_co2 = 0;
Eric Duminil's avatar
Eric Duminil committed
128
129
    if (co2 > (previous_co2 - config::max_deviation_during_calibration)
        && co2 < (previous_co2 + config::max_deviation_during_calibration)) {
130
      stable_measurements++;
Eric Duminil's avatar
Eric Duminil committed
131
      Serial.print(F("Number of stable measurements : "));
Eric Duminil's avatar
Eric Duminil committed
132
      Serial.println(stable_measurements);
133
      switchState(PREPARE_CALIBRATION_STABLE);
134
135
    } else {
      stable_measurements = 0;
136
      switchState(PREPARE_CALIBRATION_UNSTABLE);
137
    }
Eric Duminil's avatar
Eric Duminil committed
138
    previous_co2 = co2;
139
    return (stable_measurements == config::enough_stable_measurements);
140
141
142
  }

  void startCalibrationProcess() {
143
144
145
146
    /** From the sensor documentation:
     * For best results, the sensor has to be run in a stable environment in continuous mode at
     * a measurement rate of 2s for at least two minutes before applying the FRC command and sending the reference value.
     */
147
148
149
150
    Serial.println(F("Setting SCD30 timestep to 2s, prior to calibration."));
    scd30.setMeasurementInterval(2); // [s] The change will only take effect after next measurement.
    Serial.println(F("Waiting until the measurements are stable for at least 2 minutes."));
    Serial.println(F("It could take a very long time."));
151
    switchState(PREPARE_CALIBRATION_UNSTABLE);
152
153
  }

154
  void calibrateAndRestart() {
Käppler's avatar
Käppler committed
155
    switchState(CALIBRATION);
156
    Serial.print(F("Calibrating SCD30 now..."));
157
158
    scd30.setAltitudeCompensation(config::altitude_above_sea_level);
    scd30.setForcedRecalibrationFactor(config::co2_calibration_level);
159
160
    Serial.println(F(" Done!"));
    Serial.println(F("Sensor calibrated."));
Eric Duminil's avatar
Eric Duminil committed
161
    ESP.restart(); // softer than ESP.reset
162
  }
163

164
  void logToSerial() {
Eric Duminil's avatar
Eric Duminil committed
165
166
    Serial.print(timestamp);
    Serial.print(F(" - co2(ppm): "));
167
168
    Serial.print(co2);
    Serial.print(F(" temp(C): "));
169
    Serial.print(temperature, 1);
170
    Serial.print(F(" humidity(%): "));
171
    Serial.println(humidity, 1);
172
173
  }

Käppler's avatar
Käppler committed
174
  void switchState(state new_state) {
175
176
177
    if (new_state == current_state) {
      return;
    }
178
179
180
181
182
183
    if (config::debug_sensor_states) {
      Serial.print(F("Changing sensor state: "));
      Serial.print(state_names[current_state]);
      Serial.print(" -> ");
      Serial.println(state_names[new_state]);
    }
Käppler's avatar
Käppler committed
184
185
186
    current_state = new_state;
  }

187
188
189
  void displayCO2OnLedRing() {
    /**
     * Display data, even if it's "old" (with breathing).
Eric Duminil's avatar
Eric Duminil committed
190
     * A short delay is required in order to let background tasks run on the ESP8266.
191
     * see https://github.com/esp8266/Arduino/issues/3241#issuecomment-301290392
192
193
     */
    if (co2 < 2000) {
194
      led_effects::displayCO2color(co2);
195
      delay(100);
196
197
    } else {
      // >= 2000: entire ring blinks red
198
      led_effects::redAlert();
199
200
201
    }
  }

202
  void showState() {
203
204
205
206
    switch (current_state) {
    case BOOTUP:
      led_effects::showWaitingLED(color::blue);
      break;
207
      // No special signaling, we want to show the CO2 value
208
209
    case READY:
      break;
210
    case NEEDS_CALIBRATION:
211
212
      led_effects::showWaitingLED(color::magenta);
      break;
213
    case PREPARE_CALIBRATION_UNSTABLE:
214
215
      led_effects::showWaitingLED(color::red);
      break;
216
    case PREPARE_CALIBRATION_STABLE:
217
218
      led_effects::showWaitingLED(color::green);
      break;
219
      // No special signaling here, too.
220
221
    case CALIBRATION:
      break;
222
      // This should not happen.
223
224
    default:
      Serial.println(F("Encountered unknown sensor state"));
225
226
227
    }
  }

Eric Duminil's avatar
Eric Duminil committed
228
  /** Gets fresh data if available, checks calibration status, displays CO2 levels.
229
   * Returns true if fresh data is available, for further processing (e.g. MQTT, CSV or LoRa)
Eric Duminil's avatar
Eric Duminil committed
230
231
232
233
234
235
   */
  bool processData() {
    bool freshData = scd30.dataAvailable();

    if (freshData) {
      // checkTimerDeviation();
236
      ntp::getLocalTime(timestamp);
Eric Duminil's avatar
Eric Duminil committed
237
238
239
      co2 = scd30.getCO2();
      temperature = scd30.getTemperature();
      humidity = scd30.getHumidity();
240

241
      if (co2 <= 0) {
242
243
        // NOTE: Data is available, but it's sometimes erroneous: the sensor outputs
        // zero ppm but non-zero temperature and non-zero humidity.
244
        Serial.println(F("Invalid sensor data - CO2 concentration <= 0 ppm"));
245
        switchState(BOOTUP);
246
      } else if ((current_state == PREPARE_CALIBRATION_UNSTABLE) || (current_state == PREPARE_CALIBRATION_STABLE)) {
247
248
249
250
251
252
        // Check for pre-calibration states first, because we do not want to
        // leave them before calibration is done.
        bool ready_for_calibration = countStableMeasurements();
        if (ready_for_calibration) {
          calibrateAndRestart();
        }
253
254
      } else if (co2 < 250) {
        // Sensor should be calibrated.
255
        switchState(NEEDS_CALIBRATION);
256
257
      } else {
        switchState(READY);
Eric Duminil's avatar
Eric Duminil committed
258
      }
259

260
261
      // Log every time fresh data is available.
      logToSerial();
262
263
    }

264
265
266
267
268
    // We need to show LED effects for "old" data, too, as long as we get new data.
    if (current_state == READY) {
      displayCO2OnLedRing();
    } else {
      showState();
269
270
    }

Eric Duminil's avatar
Eric Duminil committed
271
    return freshData;
272
  }
273
274
275
276
277
278
279
280
281
282

  /*****************************************************************
   * Callbacks for sensor commands                                 *
   *****************************************************************/
  void setCO2forDebugging(int32_t fakeCo2) {
    Serial.print(F("DEBUG. Setting CO2 to "));
    co2 = fakeCo2;
    Serial.println(co2);
  }

283
284
285
286
287
288
289
  void setAutoCalibration(int32_t autoCalibration) {
    config::auto_calibrate_sensor = autoCalibration;
    scd30.setAutoSelfCalibration(autoCalibration);
    Serial.print(F("Setting auto-calibration to : "));
    Serial.println(autoCalibration ? F("On.") : F("Off."));
  }

290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
  void setTimer(int32_t timestep) {
    if (timestep >= 2 && timestep <= 1800) {
      Serial.print(F("Setting Measurement Interval to : "));
      Serial.print(timestep);
      Serial.println("s.");
      sensor::scd30.setMeasurementInterval(timestep);
      config::measurement_timestep = timestep;
      led_effects::showKITTWheel(color::green, 1);
    }
  }

  void calibrateSensorToSpecificPPM(int32_t calibrationLevel) {
    if (calibrationLevel >= 400 && calibrationLevel <= 2000) {
      Serial.print(F("Force calibration, at "));
      config::co2_calibration_level = calibrationLevel;
      Serial.print(config::co2_calibration_level);
      Serial.println(" ppm.");
      sensor::startCalibrationProcess();
    }
  }

  void calibrateSensorRightNow(int32_t calibrationLevel) {
    stable_measurements = config::enough_stable_measurements;
    calibrateSensorToSpecificPPM(calibrationLevel);
  }
315
}