-
Notifications
You must be signed in to change notification settings - Fork 0
/
esp32-co2-traffic-light.ino
100 lines (87 loc) · 2.13 KB
/
esp32-co2-traffic-light.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/****************************************************************************************
*
* @file ESP32_CO2_TrafficLight_With_LED.ino
* @author captain-maramo
* @brief Traffic light with ESP32, RGB LED and CCS811 Sensor with I2C comunication
*
*
* @copyright [MIT License](http://opensource.org/licenses/MIT)
****************************************************************************************/
#include "CCS811-SOLDERED.h"
#include "Wire.h"
#define PIN_RED 16
#define PIN_GREEN 17
#define PIN_BLUE 18
CCS_811 ccs811Sensor;
bool isFirstRun = true;
void setup()
{
setPinModes();
Wire.begin();
Serial.begin(115200);
ccs811Sensor.begin();
}
void loop()
{
if(isFirstRun){
initializeFirstRun();
isFirstRun = false;
}
if (ccs811Sensor.dataAvailable())
{
int co2 = getCo2Value(ccs811Sensor);
printCo2ToSerial(co2);
setLedByCo2(co2);
delay(5000); // Don't spam the I2C bus
}
}
int getCo2Value(CCS_811 ccs811Sensor){
ccs811Sensor.readAlgorithmResults();
return ccs811Sensor.getCO2();
}
void printCo2ToSerial(int co2){
Serial.print("CO2["+String(co2)+"]");
}
void setLedByCo2(int co2){
if(co2<=999){
// Green
setLedColor(0, 255, 0);
printColorToSerial(0, 255, 0);
}
else if(co2>=1600){
// Red
setLedColor(255, 0, 0);
printColorToSerial(255, 0, 0);
}
else{
// Yellow
setLedColor(255, 155, 0);
printColorToSerial(255, 155, 0);
}
}
//20 min warum up phase for the sensor to give correct data
void initializeFirstRun(){
for(int i = 1; i <= 120; i++){
setLedColor(0,0,255);
delay(5000);
setLedColor(0,125,255);
delay(5000);
Serial.println("Warmup round: " + String(i) + "/1200");
}
}
void setLedColor(int R, int G, int B) {
analogWrite(PIN_RED, R);
analogWrite(PIN_GREEN, G);
analogWrite(PIN_BLUE, B);
}
void printColorToSerial(int R, int G, int B){
String red = String(R);
String green = String(G);
String blue = String(B);
Serial.println("Red: " + red +" Green: " + green + " Blue: " + blue);
}
void setPinModes(){
pinMode(PIN_RED, OUTPUT);
pinMode(PIN_GREEN, OUTPUT);
pinMode(PIN_BLUE, OUTPUT);
}