Created
April 19, 2020 04:51
-
-
Save grafi-tt/970369d643ac5ce05c47a9372d91f77d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void setup() { | |
Serial.begin(9600); | |
analogReference(DEFAULT); | |
} | |
unsigned int co2mon(unsigned long delta) { | |
static const unsigned int SensorIn = A0; | |
static const unsigned int BaseVoltage = 480; | |
static const unsigned int PollInterval = 10; | |
static unsigned int pollTime = 0; | |
static unsigned int concentrationSamples0[8] = {0}; | |
static unsigned int concentrationSamples1[8] = {0}; | |
static unsigned int pos0 = 0; | |
static unsigned int pos1 = 0; | |
static unsigned int concentrationCache = 0; | |
if ((pollTime += (unsigned int)delta) < PollInterval) return concentrationCache; | |
pollTime = 0; | |
unsigned int sensorVal = analogRead(SensorIn); | |
unsigned int voltage = sensorVal * (long)5000 / 1024; | |
unsigned int concentrationNow = 0; | |
if (voltage > BaseVoltage) { // initialized | |
voltage -= BaseVoltage; | |
concentrationNow = (unsigned long)voltage * 50 / 16; | |
} | |
// Max 5000 ppm | |
if (concentrationNow > 5000) concentrationNow = 5000; | |
// Set sample0 | |
concentrationSamples0[++pos0] = concentrationNow; | |
if (pos0 != 8) return concentrationCache; | |
// Set sample1 by average of samples0 | |
unsigned int concentrationSum0 = 0; | |
do { | |
concentrationSum0 += concentrationSamples0[--pos0]; | |
} while (pos0); | |
concentrationSamples1[pos1++ % 8] = concentrationSum0 / 8; | |
// Moving window average of samples1 | |
unsigned int pos1New = pos1 - 8; | |
unsigned int concentrationSum1 = 0; | |
do { | |
concentrationSum1 += concentrationSamples1[--pos1 % 8]; | |
} while (pos1 != pos1New); | |
concentrationCache = concentrationSum1 / 8; | |
return concentrationCache; | |
} | |
void loop() { | |
static unsigned long timeOld = 0; | |
unsigned long timeNow = millis(); | |
unsigned long delta = timeNow - timeOld; | |
timeOld = timeNow; | |
unsigned int concentration = co2mon(delta); | |
if (Serial.available()) { | |
char c = Serial.read(); | |
if (c == 'c') { | |
Serial.println(concentration); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment