Project/Arduino

ESP32로 CO2 센서(MH-Z14A) 측정하기

Juzero 2020. 6. 18. 13:25

MH-Z14A 센서로 CO2를 측정하니 전압값이 너무 안맞아서 한참 고생했다.

 

ESP32와 MH-Z14A 예제도 별로 없음 ㅠㅠ

 

아래 코드는 5V에 연결된 전압을 변환해서 적정 값으로 바꾸어주는 코드이다.

 

#include <WiFi.h>
#include <HTTPClient.h>
#include <HttpClient.h>

//#include <Wire.h>

 
const char* ssid = "A";
const char* password =  "A";
const char* serverName = "http://00.000.00.000:0000/";
int value;
int sensor_number = 1;
int analog = 34;

IPAddress hostIp(00, 000, 00, 000);
int SERVER_PORT = 5000;
WiFiClient client;

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

  WiFi.begin(ssid, password); 
 
  while (WiFi.status() != WL_CONNECTED) { //Check for the connection
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
 
  Serial.println("Connected to the WiFi network");
 
}
 
void loop() {
 // 여기서 부터 
 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

     for(int i=0; i<8; i++){
      value+=analogRead(analog);
      delay(200);
     } // 값이 너무 튀어서 8번 측정값의 평균으로 안정값을 도출했다. 
     value/=8;
     int adcVal = value;
     float voltage = adcVal*(3.3/4095.0);
    if(voltage == 0)
    {
    Serial.println("A problem has occurred with the sensor.");
    }
    else if(voltage < 0.4)
    {
    Serial.println("Pre-heating the sensor...");
    }
    else
    {
 
    float voltageDiference=voltage-0.4;
    float concentration=(voltageDiference*5000.0)/1.6;
    Serial.println(voltageDiference);
    Serial.println("voltageDiference");
    Serial.println(concentration);
    Serial.println("concentration");
    
    }
    
    //여기까지가 이산화탄소 측정 부분이다. 
     HTTPClient http;
   
     http.begin("http://00.000.00.000:0000/");  //Specify destination for HTTP request
     http.addHeader("Content-Type",  "application/x-www-form-urlencoded");             //Specify content-type header
  
     String httpRequestData = "sensor_number="+String(sensor_number)+"&value="+String(value);
     int httpResponseCode = http.POST(httpRequestData);   //Send the actual POST request
   
     if(httpResponseCode>0){
  
      String response = http.getString();                       //Get the response to the request
   
      //Serial.println(httpResponseCode);   //Print return code
      //Serial.println(response);           //Print request answer
   
     }else{
   
      Serial.print("Error on sending POST: ");
      Serial.println(httpResponseCode);
   
     }
   
     http.end();  //Free resources
   
 }else{

    Serial.println("Error in WiFi connection");   
 }
 
  delay(500);  //Send a request every 10 seconds
 
}

 

HTTP 부분은 이 전 게시글을 보면 될 듯하고, 저 위에 // 로 주석 달은 부분이 센서값 측정하는 부분이다. 

 

와이파이 부분에서 HTTP로 잘 전송되었으면 저 httpRespondCode가 200으로 시리얼모니터에 뜰 것이다.