co2_sensor.cpp 13 KB
Newer Older
1
2
#include "co2_sensor.h"

3
4
5
6
7
8
#include "config.h"
#include "led_effects.h"
#include "util.h" // Just time.h
#include "sensor_console.h"
#include <Wire.h>

9
namespace config {
10
  // UPPERCASE values should be defined in config.h
Eric Duminil's avatar
Eric Duminil committed
11
  uint16_t measurement_timestep = MEASUREMENT_TIMESTEP; // [s] Value between 2 and 1800 (range for SCD30 sensor).
Eric Duminil's avatar
Eric Duminil committed
12
13
  const uint16_t altitude_above_sea_level = ALTITUDE_ABOVE_SEA_LEVEL; // [m]
  uint16_t co2_calibration_level = ATMOSPHERIC_CO2_CONCENTRATION; // [ppm]
14
  const uint16_t measurement_timestep_bootup = 5; // [s] Measurement timestep during acclimatization.
15
  const uint8_t max_deviation_during_bootup = 20; // [%]
16
17
18
  const int8_t max_deviation_during_calibration = 30; // [ppm]
  const int16_t timestep_during_calibration = 10; // [s] WARNING: Measurements can be unreliable for timesteps shorter than 10s.
  const int8_t stable_measurements_before_calibration = 120 / timestep_during_calibration; // [-] Stable measurements during at least 2 minutes.
19
  const uint16_t co2_alert_threshold = 2000; // [ppm] Display a flashing led ring, if concentration exceeds this value
20

21
22
23
#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
24
  const float temperature_offset = TEMPERATURE_OFFSET; // [K]
25
26
27
#else
  const float temperature_offset = -3.0;  // [K] Temperature measured by sensor is usually at least 3K too high.
#endif
28
  bool auto_calibrate_sensor = AUTO_CALIBRATE_SENSOR; // [true / false]
29
  const bool debug_sensor_states = false; // If true, log state transitions over serial console
30
31
32
33
}

namespace sensor {
  SCD30 scd30;
34
  uint16_t co2 = 0;
35
36
  float temperature = 0;
  float humidity = 0;
37
  char timestamp[23];
38
  int16_t stable_measurements = 0;
Käppler's avatar
Käppler committed
39
40
41

  /**
   * Define sensor states
42
   * BOOTUP -> initial state, until first >0 ppm values are returned
Käppler's avatar
Käppler committed
43
   * READY -> sensor does output valid information (> 0 ppm) and no other condition takes place
Eric Duminil's avatar
Eric Duminil committed
44
   * NEEDS_CALIBRATION -> sensor measurements are too low (< 250 ppm)
45
46
   * PREPARE_CALIBRATION_UNSTABLE -> forced calibration was initiated, last measurements were too far apart
   * PREPARE_CALIBRATION_STABLE -> forced calibration was initiated, last measurements were close to each others
Käppler's avatar
Käppler committed
47
   */
48
49
50
  enum state {
    BOOTUP,
    READY,
51
    NEEDS_CALIBRATION,
52
    PREPARE_CALIBRATION_UNSTABLE,
53
    PREPARE_CALIBRATION_STABLE
Käppler's avatar
Käppler committed
54
  };
55
56
57
  const char *state_names[] = {
      "BOOTUP",
      "READY",
58
      "NEEDS_CALIBRATION",
59
      "PREPARE_CALIBRATION_UNSTABLE",
60
      "PREPARE_CALIBRATION_STABLE" };
61
62

  state current_state = BOOTUP;
Käppler's avatar
Käppler committed
63
64
  void switchState(state);

65
66
  void initialize() {
#if defined(ESP8266)
67
    Wire.begin(12, 14); // ESP8266 - D6, D5;
68
69
#endif
#if defined(ESP32)
Eric Duminil's avatar
Eric Duminil committed
70
    Wire.begin(21, 22); // ESP32
71
72
73
74
75
76
77
78
    /**
     *  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
79
80
    Serial.println();
    scd30.enableDebugging(); // Prints firmware version in the console.
81

82
    if (!scd30.begin(config::auto_calibrate_sensor)) {
Eric Duminil's avatar
Eric Duminil committed
83
84
85
      Serial.println(F("ERROR - CO2 sensor not detected. Please check wiring!"));
      led_effects::showKITTWheel(color::red, 30);
      ESP.restart();
86
87
    }

88
89
90
91
92
    // Changes of the SCD30's measurement timestep do not come into effect
    // before the next measurement takes place. That means that after a hard reset
    // of the ESP the SCD30 sometimes needs a long time until switching back to 2 s
    // for acclimatization. Resetting it after startup seems to fix this behaviour.
    scd30.reset();
Käppler's avatar
Käppler committed
93

94
    Serial.print(F("Setting temperature offset to -"));
95
    Serial.print(abs(config::temperature_offset));
Eric Duminil's avatar
Eric Duminil committed
96
    Serial.println(F(" K."));
97
    scd30.setTemperatureOffset(abs(config::temperature_offset)); // setTemperatureOffset only accepts positive numbers, but shifts the temperature down.
98
    delay(100);
99

100
    Serial.print(F("Temperature offset is : -"));
101
    Serial.print(scd30.getTemperatureOffset());
Eric Duminil's avatar
Eric Duminil committed
102
    Serial.println(F(" K"));
103

104
    Serial.print(F("Auto-calibration is "));
105
    Serial.println(config::auto_calibrate_sensor ? "ON." : "OFF.");
106

107
108
109
110
    // SCD30 has its own timer.
    //NOTE: The timer seems to be inaccurate, though, possibly depending on voltage. Should it be offset?
    Serial.println();
    Serial.print(F("Setting SCD30 timestep to "));
111
    Serial.print(config::measurement_timestep_bootup);
Eric Duminil's avatar
Eric Duminil committed
112
    Serial.println(F(" s during acclimatization."));
113
    scd30.setMeasurementInterval(config::measurement_timestep_bootup); // [s]
114

115
116
117
    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
118
    sensor_console::defineIntCommand("calibrate", calibrateSensorToSpecificPPM,
119
        F("600 (Starts calibration process, to given ppm)"));
Eric Duminil's avatar
Eric Duminil committed
120
    sensor_console::defineIntCommand("calibrate!", calibrateSensorRightNow,
121
122
        F("600 (Calibrates right now, to given ppm)"));
    sensor_console::defineIntCommand("auto_calibrate", setAutoCalibration, F("0/1 (Disables/enables autocalibration)"));
123
    sensor_console::defineCommand("reset_scd", resetSCD, F("(Resets SCD30)"));
124
125
  }

126
127
128
129
130
131
132
  bool hasSensorSettled() {
    static uint16_t last_co2 = 0;
    uint16_t delta;
    delta = abs(co2 - last_co2);
    last_co2 = co2;
    // We assume the sensor has acclimated to the environment if measurements
    // change less than a specified percentage of the current value.
Eric Duminil's avatar
Eric Duminil committed
133
    return (co2 > 0 && delta < ((uint32_t) co2 * config::max_deviation_during_bootup / 100));
134
135
  }

Eric Duminil's avatar
Eric Duminil committed
136
  bool enoughStableMeasurements() {
Eric Duminil's avatar
Eric Duminil committed
137
    static int16_t previous_co2 = 0;
Eric Duminil's avatar
Eric Duminil committed
138
139
    if (co2 > (previous_co2 - config::max_deviation_during_calibration)
        && co2 < (previous_co2 + config::max_deviation_during_calibration)) {
140
      stable_measurements++;
Eric Duminil's avatar
Eric Duminil committed
141
      Serial.print(F("Number of stable measurements : "));
142
143
144
      Serial.print(stable_measurements);
      Serial.print(F(" / "));
      Serial.println(config::stable_measurements_before_calibration);
145
      switchState(PREPARE_CALIBRATION_STABLE);
146
147
    } else {
      stable_measurements = 0;
148
      switchState(PREPARE_CALIBRATION_UNSTABLE);
149
    }
Eric Duminil's avatar
Eric Duminil committed
150
    previous_co2 = co2;
151
    return (stable_measurements == config::stable_measurements_before_calibration);
152
153
154
  }

  void startCalibrationProcess() {
155
    /** From the sensor documentation:
Eric Duminil's avatar
Eric Duminil committed
156
     * Before applying FRC, SCD30 needs to be operated for 2 minutes with the desired measurement period in continuous mode.
157
     */
158
159
160
161
    Serial.print(F("Setting SCD30 timestep to "));
    Serial.print(config::timestep_during_calibration);
    Serial.println(F("s, prior to calibration."));
    scd30.setMeasurementInterval(config::timestep_during_calibration); // [s] The change will only take effect after next measurement.
162
163
    Serial.println(F("Waiting until the measurements are stable for at least 2 minutes."));
    Serial.println(F("It could take a very long time."));
164
    switchState(PREPARE_CALIBRATION_UNSTABLE);
165
166
  }

167
  void calibrate() {
168
    Serial.print(F("Calibrating SCD30 now..."));
169
170
    scd30.setAltitudeCompensation(config::altitude_above_sea_level);
    scd30.setForcedRecalibrationFactor(config::co2_calibration_level);
171
172
    Serial.println(F(" Done!"));
    Serial.println(F("Sensor calibrated."));
173
    switchState(BOOTUP); // In order to stop the calibration and select the desired timestep.
174
175
    //WARNING: Do not reset the ampel or the SCD30!
    //At least one measurement needs to happen in order for the calibration to be correctly applied.
176
  }
177

178
  void logToSerial() {
Eric Duminil's avatar
Eric Duminil committed
179
180
    Serial.print(timestamp);
    Serial.print(F(" - co2(ppm): "));
181
182
    Serial.print(co2);
    Serial.print(F(" temp(C): "));
183
    Serial.print(temperature, 1);
184
    Serial.print(F(" humidity(%): "));
185
    Serial.println(humidity, 1);
186
187
  }

Käppler's avatar
Käppler committed
188
  void switchState(state new_state) {
189
190
191
    if (new_state == current_state) {
      return;
    }
192
193
194
    if (config::debug_sensor_states) {
      Serial.print(F("Changing sensor state: "));
      Serial.print(state_names[current_state]);
Eric Duminil's avatar
Eric Duminil committed
195
      Serial.print(F(" -> "));
196
197
      Serial.println(state_names[new_state]);
    }
Käppler's avatar
Käppler committed
198
199
200
    current_state = new_state;
  }

201
  void switchStateForCurrentPPM() {
202
    if (current_state == BOOTUP) {
Eric Duminil's avatar
Eric Duminil committed
203
204
205
      if (!hasSensorSettled()) {
        return;
      }
206
207
208
209
      switchState(READY);
      Serial.println(F("Sensor acclimatization finished."));
      Serial.print(F("Setting SCD30 timestep to "));
      Serial.print(config::measurement_timestep);
Eric Duminil's avatar
Eric Duminil committed
210
      Serial.println(F(" s."));
Eric Duminil's avatar
Eric Duminil committed
211
      if (config::measurement_timestep < 10) {
212
213
        Serial.println(F("WARNING: Timesteps shorter than 10s can lead to unreliable measurements!"));
      }
214
215
      scd30.setMeasurementInterval(config::measurement_timestep); // [s]
    }
Eric Duminil's avatar
Eric Duminil committed
216
217
218

    // Check for pre-calibration states first, because we do not want to
    // leave them before calibration is done.
Käppler's avatar
Käppler committed
219
    if ((current_state == PREPARE_CALIBRATION_UNSTABLE) || (current_state == PREPARE_CALIBRATION_STABLE)) {
Eric Duminil's avatar
Eric Duminil committed
220
      if (enoughStableMeasurements()) {
221
        calibrate();
222
223
224
225
226
227
228
229
230
      }
    } else if (co2 < 250) {
      // Sensor should be calibrated.
      switchState(NEEDS_CALIBRATION);
    } else {
      switchState(READY);
    }
  }

231
232
233
  void displayCO2OnLedRing() {
    /**
     * Display data, even if it's "old" (with breathing).
Eric Duminil's avatar
Eric Duminil committed
234
     * A short delay is required in order to let background tasks run on the ESP8266.
235
     * see https://github.com/esp8266/Arduino/issues/3241#issuecomment-301290392
236
     */
237
    if (co2 < config::co2_alert_threshold) {
238
      led_effects::displayCO2color(co2);
239
      delay(100);
240
    } else {
241
      // Display a flashing led ring, if concentration exceeds a specific value
242
      led_effects::redAlert();
243
244
245
    }
  }

246
  void showState() {
247
248
249
250
251
    switch (current_state) {
    case BOOTUP:
      led_effects::showWaitingLED(color::blue);
      break;
    case READY:
252
      displayCO2OnLedRing();
253
      break;
254
    case NEEDS_CALIBRATION:
255
256
      led_effects::showWaitingLED(color::magenta);
      break;
257
    case PREPARE_CALIBRATION_UNSTABLE:
258
259
      led_effects::showWaitingLED(color::red);
      break;
260
    case PREPARE_CALIBRATION_STABLE:
261
262
263
      led_effects::showWaitingLED(color::green);
      break;
    default:
Eric Duminil's avatar
Eric Duminil committed
264
      Serial.println(F("Encountered unknown sensor state")); // This should not happen.
265
266
267
    }
  }

Eric Duminil's avatar
Eric Duminil committed
268
  /** Gets fresh data if available, checks calibration status, displays CO2 levels.
269
   * Returns true if fresh data is available, for further processing (e.g. MQTT, CSV or LoRa)
Eric Duminil's avatar
Eric Duminil committed
270
271
272
273
274
   */
  bool processData() {
    bool freshData = scd30.dataAvailable();

    if (freshData) {
275
      ntp::getLocalTime(timestamp);
Eric Duminil's avatar
Eric Duminil committed
276
277
278
      co2 = scd30.getCO2();
      temperature = scd30.getTemperature();
      humidity = scd30.getHumidity();
279

280
      switchStateForCurrentPPM();
281

282
283
      // Log every time fresh data is available.
      logToSerial();
284
285
    }

286
    showState();
287

288
289
290
    // Report data for further processing only if the data is reliable
    // (state 'READY') or manual calibration is necessary (state 'NEEDS_CALIBRATION').
    return freshData && (current_state == READY || current_state == NEEDS_CALIBRATION);
291
  }
292
293
294
295
296
297
298
299

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

303
304
305
306
307
308
309
  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."));
  }

310
311
312
313
  void setTimer(int32_t timestep) {
    if (timestep >= 2 && timestep <= 1800) {
      Serial.print(F("Setting Measurement Interval to : "));
      Serial.print(timestep);
Eric Duminil's avatar
Eric Duminil committed
314
      Serial.println(F("s (change will only be applied after next measurement)."));
Eric Duminil's avatar
Eric Duminil committed
315
      scd30.setMeasurementInterval(timestep);
316
317
318
319
320
321
322
323
324
325
      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);
Eric Duminil's avatar
Eric Duminil committed
326
      Serial.println(F(" ppm."));
Eric Duminil's avatar
Eric Duminil committed
327
      startCalibrationProcess();
328
329
330
331
    }
  }

  void calibrateSensorRightNow(int32_t calibrationLevel) {
Eric Duminil's avatar
Eric Duminil committed
332
333
334
335
336
    if (calibrationLevel >= 400 && calibrationLevel <= 2000) {
      Serial.print(F("Force calibration, right now, at "));
      config::co2_calibration_level = calibrationLevel;
      Serial.print(config::co2_calibration_level);
      Serial.println(F(" ppm."));
337
      calibrate();
Eric Duminil's avatar
Eric Duminil committed
338
    }
339
  }
340
341
342
343
344
345

  void resetSCD() {
    Serial.print(F("Resetting SCD30..."));
    scd30.reset();
    Serial.println(F("done."));
  }
346
}