이산화탄소 센서 사용해보기

상상·2023년 1월 22일
0

알리 익스프레스를 기웃거리다 CO2 센서가 있길래 2개 사봤다

SCD4x

Wemos d1 mini

결과

조립

점퍼선 연결

  • PIN #G - 센서 GND
  • PIN #3v3 – 센서 VDC
  • PIN #D2 – 센서 SDA
  • PIN #D1 - 센서 SCL

작동 방법

  • 5분마다 센서가 온도, 습도, 이산화탄소를 측정해서 Json 포맷으로 서버에 전달한다.
  • 서버는 데이터를 받으면 보기 편하게 파일로 저장한다.

클라이언트 (아두이노)

#include <SensirionI2CScd4x.h>
#include <Wire.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

SensirionI2CScd4x scd4x;

const char* ssid = "HelloWorld";
const char* password = "sangyeon";

const char* serverName = "YOUR SERVER ADDRESS";

  

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 300000; // 5 min

  
void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  Serial.println("Connecting");

  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");

  Serial.println(WiFi.localIP());
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  //Send an HTTP POST request every 5 minutes

  if ((millis() - lastTime) > timerDelay) {

    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){

      Wire.begin();
      scd4x.begin(Wire);
      scd4x.stopPeriodicMeasurement();
      scd4x.startPeriodicMeasurement();

      uint16_t error;
      char errorMessage[256];

      delay(5000);

      // Read Measurement
      uint16_t co2;
      float temperature;
      float humidity;

      error = scd4x.readMeasurement(co2, temperature, humidity);

      if (error) {
          Serial.print("Error trying to execute readMeasurement(): ");
          errorToString(error, errorMessage, 256);
          Serial.println(errorMessage);

      } else if (co2 == 0) {
          Serial.println("Invalid sample detected, skipping.");

      } else {
      WiFiClient client;
      HTTPClient http;

      // Your Domain name with URL path or IP address with path
      http.begin(client, serverName);
      http.addHeader("Content-Type", "application/json");
      int httpResponseCode = http.POST("{\"Temp\": "+String(temperature)+", \"Humi\": "+String(humidity)+",\"CO2\":"+co2+"}");

      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);

      http.end();
      }
    }
    else {
      Serial.println("WiFi Disconnected");
    }

    lastTime = millis();
  }
}

서버 php 코드

<?php
$data = json_decode(file_get_contents('php://input'),true);
$date = date("d");

$filedate = date("Y-m");
$file = json_decode(file_get_contents('YOUR LOCATION'.$filedate),true);


if (empty($file)){
  $file[$date] = [[date("H:i") => $data]];
} else {
  array_push($file[$date], [date("H:i") => $data]);
}


file_put_contents('YOUR LOCATION'.$filedate, json_encode($file, JSON_PRETTY_PRINT));
?>

C 랑 C++ 는 잘 몰라서 아두이노 라이브러리 이것저것 조합해서 일단 작동만 되도록 만들었다.

{
    "22": [
        {
            "Temp": 6.29,
            "Humi": 41.32,
            "CO2": 438,
            "time": "21:02"
        },
        {
            "Temp": 5.96,
            "Humi": 41.29,
            "CO2": 411,
            "time": "21:07"
        },
        {
            "Temp": 5.88,
            "Humi": 40.72,
            "CO2": 411,
            "time": "21:12"
        },
   
      ...
 

요런 형태로 저장되고,

그래프로 바꿔보면


😎 굳!


재밌는건

24일 내방 📈온도 그래프 이다.

1번과 2번이 각각 새벽 3시, 5시 인데 CO2와 습도가 내려가는걸 볼 수 있다.
왜 그런가 찾아보니 집에 💨환기팬이 3시와 5시에 돌아갔었다.

3번은 1시쯤인데, 저때 일어나서 나갔더니 확연한 차이를 보여줬다. 🦥

profile
열심히 이것저것 해보는중!

0개의 댓글