Initial SCD4x release

This commit is contained in:
Laura Hausmann 2023-05-30 02:29:44 +02:00
commit c209d81b34
Signed by: zotan
GPG key ID: D044E84C5BE01605
12 changed files with 4036 additions and 0 deletions

9
.gitignore vendored Normal file
View file

@ -0,0 +1,9 @@
.DS_Store
.pio
.idea
.vscode
CMakeLists.txt
CMakeListsPrivate.txt
cmake-build-az-delivery-devkit-v4
cmake-build-debug

3593
.uncrustify.cfg Normal file

File diff suppressed because it is too large Load diff

11
README.md Normal file
View file

@ -0,0 +1,11 @@
# esp32-co2-scd4x
This project displays the current co2 levels, along with temperature and humidity information, on a HD44780 16x2 display. All of this is powered by an ESP32 devkit and a SCD40/41 photoacoustic NDIR CO2 sensor.
## Wiring
![Wiring diagram](img/wiring.jpeg)
The main components here are wired up like this:
- The green, yellow and red LEDs are connected to ground and pins 25, 33 and 32 respectively
- The HD44780 16x2 display is connected to an I2C daughterboard, which itself is connected to +5V, ground, as well as the I2C bus pins of the ESP32, 22 for clock and 21 for data
- The SCD40/41 photoacoustic NDIR CO2 sensor is connected to +5V and ground for power and to pins 22 and 21 (ESP32 I2C_bus1; MH-Z19B side pins SCL and SDA respectively)
- A button to toggle the backlight is connected between pin 23 and ground

BIN
img/wiring.jpeg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

BIN
img/wiring.jpeg_original Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

39
include/README Normal file
View file

@ -0,0 +1,39 @@
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

10
include/wifiFix.h Normal file
View file

@ -0,0 +1,10 @@
#pragma once
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
class WiFiClientFixed : public WiFiClient {
public:
void flush() override;
};
#pragma clang diagnostic pop

46
lib/README Normal file
View file

@ -0,0 +1,46 @@
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html

26
platformio.ini Normal file
View file

@ -0,0 +1,26 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:az-delivery-devkit-v4]
platform = espressif32@^6.0.0
board = az-delivery-devkit-v4
framework = arduino
upload_protocol = esptool
upload_speed = 921600
monitor_speed = 115200
monitor_filters = esp32_exception_decoder
lib_deps =
wifwaf/MH-Z19@^1.5.3
adafruit/Adafruit AHTX0@^2.0.1
fmalpartida/LiquidCrystal@^1.5.0
sparkfun/SparkFun SCD4x Arduino Library@^1.0.4
juerd/ESP-WiFiSettings@^3.8.0
bblanchon/ArduinoJson@^6.20.0

263
src/main.cpp Normal file
View file

@ -0,0 +1,263 @@
#include <Arduino.h>
#include "LiquidCrystal_I2C.h"
#include "WiFiSettings.h"
#include "ArduinoJson.h"
#include <SparkFun_SCD4x_Arduino_Library.h>
#include <HTTPClient.h>
#include <SPIFFS.h>
#include "wifiFix.h"
String weather_lat = "";
String weather_long = "";
String weather_apikey = "";
String weather_final_url = "";
SCD4x scd4x;
LiquidCrystal_I2C LCD(0x27,2,1,0,4,5,6,7,3,POSITIVE);
WiFiClient* wifi = new WiFiClientFixed();
HTTPClient* http = new HTTPClient();
#define PIN_LED_GREEN 25
#define PIN_LED_YELLOW 33
#define PIN_LED_RED 32
int backlightState = HIGH;
volatile bool interruptFired = false;
unsigned long lastInterrupt = 0;
unsigned long lastUpdated = 0;
unsigned long lastWeatherUpdate = 0;
bool weatherUpdateSuccess = false;
int lastWeatherPressure = 0;
int avgAtmosphericPressure = 1013;
unsigned const int updateTimer = 5000;
unsigned const int interruptTimer = 500;
void led(int red, int green, int yellow)
{
analogWrite(PIN_LED_RED, red);
analogWrite(PIN_LED_GREEN, green);
analogWrite(PIN_LED_YELLOW, yellow);
}
void IRAM_ATTR BacklightToggle() {
if (!interruptFired)
interruptFired = true;
}
void UpdateWeatherData() {
if (lastWeatherUpdate != 0 && millis() - lastWeatherUpdate < 60000) {
return;
}
lastWeatherUpdate = millis();
Serial.print("Attempting to get weather data from ");
Serial.println(weather_final_url);
http->begin(*wifi, weather_final_url);
int httpResponseCode = http->GET();
if (httpResponseCode == 200) {
String payload = http->getString();
http->end();
Serial.println(payload);
StaticJsonDocument<1024> doc;
DeserializationError error = deserializeJson(doc, payload.c_str());
if (error) {
weatherUpdateSuccess = false;
lastWeatherPressure = avgAtmosphericPressure;
}
float coord_lon = doc["coord"]["lon"]; // 3.45
float coord_lat = doc["coord"]["lat"]; // 1.23
JsonObject weather_0 = doc["weather"][0];
int weather_0_id = weather_0["id"]; // 804
const char* weather_0_main = weather_0["main"]; // "Clouds"
const char* weather_0_description = weather_0["description"]; // "overcast clouds"
const char* weather_0_icon = weather_0["icon"]; // "04d"
const char* base = doc["base"]; // "stations"
JsonObject main = doc["main"];
float main_temp = main["temp"]; // 301.92
float main_feels_like = main["feels_like"]; // 306.28
float main_temp_min = main["temp_min"]; // 301.92
float main_temp_max = main["temp_max"]; // 301.92
int main_pressure = main["pressure"]; // 1012
int main_humidity = main["humidity"]; // 75
int main_sea_level = main["sea_level"]; // 1012
int main_grnd_level = main["grnd_level"]; // 1012
int visibility = doc["visibility"]; // 10000
JsonObject wind = doc["wind"];
float wind_speed = wind["speed"]; // 4.71
int wind_deg = wind["deg"]; // 219
float wind_gust = wind["gust"]; // 4.52
int clouds_all = doc["clouds"]["all"]; // 100
long dt = doc["dt"]; // 1684079803
long sys_sunrise = doc["sys"]["sunrise"]; // 1684042647
long sys_sunset = doc["sys"]["sunset"]; // 1684086466
int timezone = doc["timezone"]; // 0
int id = doc["id"]; // 0
const char* name = doc["name"]; // nullptr
int cod = doc["cod"]; // 200
lastWeatherPressure = main_pressure;
weatherUpdateSuccess = true;
Serial.println(String("Got pressure: ") + lastWeatherPressure);
}
else {
http->end();
lastWeatherPressure = avgAtmosphericPressure;
weatherUpdateSuccess = false;
Serial.println(String("Failed getting pressure (Error code: ") + httpResponseCode + String("), using avg atmospheric pressure: ") + lastWeatherPressure);
}
}
void UpdateSensorCompensation(){
if (weatherUpdateSuccess) {
scd4x.setAmbientPressure(lastWeatherPressure * 100); // It wants the data in Pascal!
}
}
void setup()
{
Serial.begin(115200);
LCD.begin(16, 2);
LCD.clear();
LCD.setBacklight(backlightState);
LCD.print("WiFi init...");
SPIFFS.begin(true);
WiFiSettings.hostname = "co2-scd4x-";
weather_apikey = WiFiSettings.string("OpenWeatherMap API key", "hskjdfghjkdfhgyuw");
weather_lat = WiFiSettings.string("Location: latitude", "1.23");
weather_long = WiFiSettings.string("Location: longitude", "3.45");
weather_final_url = "http://api.openweathermap.org/data/2.5/weather?lat=" + weather_lat + "&lon=" + weather_long + "&appid=" + weather_apikey;
WiFiSettings.connect();
scd4x.enableDebugging();
if (!scd4x.begin(Wire)) {
Serial.println("Could not find SCD4x? Check wiring");
LCD.clear();
LCD.print("SCD4x not found");
LCD.setCursor(0, 1);
LCD.print("Check wiring");
while (true);
}
scd4x.stopPeriodicMeasurement();
LCD.setCursor(0, 0);
LCD.print("SCD4x SELF TEST ");
if (!scd4x.performSelfTest()) {
Serial.println("SCD4x self test failed");
LCD.setCursor(0, 1);
LCD.print("FAIL");
while (true);
}
scd4x.setAutomaticSelfCalibrationEnabled(true);
LCD.setCursor(0, 1);
LCD.print("PASS");
delay(1000);
Serial.println("SCD4x init:");
char mySerial[16];
scd4x.getSerialNumber(mySerial);
Serial.print("Serial no: ");
Serial.println(mySerial);
LCD.setCursor(6, 0);
LCD.print("SERIAL # ");
LCD.setCursor(0, 1);
LCD.print(mySerial);
delay(1000);
Serial.print("Altitude: ");
Serial.println(scd4x.getSensorAltitude());
Serial.print("Self-cal enabled: ");
Serial.println(scd4x.getAutomaticSelfCalibrationEnabled() ? "Yes" : "No");
Serial.print("Temperature Offset: ");
Serial.println(scd4x.getTemperatureOffset());
UpdateWeatherData();
UpdateSensorCompensation();
scd4x.startPeriodicMeasurement();
pinMode(23, INPUT_PULLUP);
attachInterrupt(23, BacklightToggle, FALLING);
LCD.clear();
}
void loop() {
if (interruptFired) {
if (millis() - lastInterrupt > interruptTimer || lastInterrupt == 0) {
backlightState = !backlightState;
Serial.printf("Setting backlight to %i \n", backlightState);
LCD.setBacklight(backlightState);
lastInterrupt = millis();
}
interruptFired = false;
}
if (millis() - lastUpdated > updateTimer || lastUpdated == 0) {
lastUpdated = millis();
} else {
return;
}
UpdateWeatherData();
UpdateSensorCompensation();
int co2 = scd4x.getCO2();
float temp = scd4x.getTemperature();
float rh = scd4x.getHumidity();
LCD.setCursor(0, 0);
LCD.print(temp, 1);
LCD.print(" C ");
LCD.setCursor(9, 0);
LCD.print(rh, 1);
LCD.print("%rH");
LCD.setCursor(0, 1);
LCD.print(co2);
LCD.print("ppm ");
LCD.setCursor(9, 1);
LCD.print(lastWeatherPressure);
LCD.print("hPa");
Serial.print(co2);
Serial.print(" ppm, ");
Serial.print(temp);
Serial.print(" ºC, ");
Serial.print(rh);
Serial.println(" %rH");
if (co2 < 1000)
led(0, 1, 0);
else if (co2 < 1500)
led(0, 0, 5);
else
led(5, 0, 0);
}

28
src/wifiFix.cpp Normal file
View file

@ -0,0 +1,28 @@
#include <WiFi.h>
#include <lwip/sockets.h>
#include "wifiFix.h"
#define WIFI_CLIENT_FLUSH_BUFFER_SIZE (1024)
void WiFiClientFixed::flush() {
int res;
size_t a = available();
if (!a) {
return;//nothing to flush
}
auto* buf = (uint8_t *) malloc(WIFI_CLIENT_FLUSH_BUFFER_SIZE);
if (!buf) {
return;//memory error
}
while (a) {
// override broken WiFiClient flush method, ref https://github.com/espressif/arduino-esp32/issues/6129#issuecomment-1237417915
res = read(buf, min(a, (size_t)WIFI_CLIENT_FLUSH_BUFFER_SIZE));
if (res < 0) {
log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
stop();
break;
}
a -= res;
}
free(buf);
}

11
test/README Normal file
View file

@ -0,0 +1,11 @@
This directory is intended for PlatformIO Unit Testing and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PlatformIO Unit Testing:
- https://docs.platformio.org/page/plus/unit-testing.html