사물인터넷(ThingSpeak)

thingspeak_esp32_ai_scindapsus_01

coding art 2021. 3. 9. 21:01
728x90

#include <ThingSpeak.h>

#include <WiFi.h>

#include <DHT11.h>

 

char ssid[] = "droidan1234"; // your network SSID (name)

char pass[] = "dddddddddd"; // your network password

 

WiFiClient client;

 

unsigned long myChannelNumber = 1256213;

const char * myWriteAPIKey = "BT5NV74GODM6PRFI";

 

int sensor = 32;//moisture sensor

int pin = 19; //dht11 온습도센서

int hg = 3150;//3359

int lw = 1392;

unsigned long sampling_time =10000;

int Motorpin = 16;//->GPIO 로 변환 요

int Threshold = 86;//적정값으로 설정

int watering_time = 20000;//급수시간 20

float soil0, soil1, soil2;

 

DHT11 dht11(pin);

 

void setup() {

Serial.begin(115200); //Initialize serial

 

WiFi.mode(WIFI_STA);

ThingSpeak.begin(client); // Initialize ThingSpeak

pinMode(pin, INPUT);

pinMode(Motorpin, GPIO);//->GPIO 로 변환 요

 

soil0 = 30;// 첫번 변수

soil1 = 30;// 둘째 변수

}

 

void loop() {

int err,xsoil;

float temp, humi,soil;

 

// Connect or reconnect to WiFi

if(WiFi.status() != WL_CONNECTED){

Serial.print("Attempting to connect to SSID: ");

while(WiFi.status() != WL_CONNECTED){

WiFi.begin(ssid,pass); // Connect to WPA/WPA2 network. Change this line if using open or WEP network

Serial.print(".");

delay(5000);

}

Serial.println("\nConnected.");

}

 

if((err=dht11.read(humi, temp))==0) {

xsoil = analogRead(sensor);

if( xsoil < 1600 ) xsoil = 1600;

if( xsoil > 3350 ) xsoil = 3350;

soil = 100.0*(xsoil-lw)/(hg - lw);//

Serial.print(soil, 0);

Serial.print(temp, 0);

Serial.print(humi, 0);

Serial.println();

}

else {

Serial.println();

Serial.print("Error No :");

Serial.print(err);

Serial.println();

}

 

// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different

// pieces of information in a channel. Here, we write to field 1.

// set the fields with the values

ThingSpeak.setField(1, soil);

ThingSpeak.setField(2, temp);

ThingSpeak.setField(3, humi);

int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);

 

soil2 = soil;

}

// 3점 데이타 이동평균 계산

float a = (soil0 + soil1 + soil2)/3.0;

// 3점 데이타표준편차 계산

float sd = sqrt( ( (soil0-a)*(soil0-a) + (soil1-a)*(soil1-a) + (soil2-a)*(soil2-a) )/3);

// 하나씩 밀기

soil0 = soil1;

soil1 = soil2;

soil2 = 0; // 다시 읽어야 할 값 리세트

 

client.stop(); //꼭 필요한지 체크 필요

if ( a > Threshold ) { // 나증에 soil 대신 3 이동평균 값 사용 동시에 표준편차가 0.47(0.8) 버다 적으면 급수

digitalWrite(Motorpin,HIGH);

delay(watering_time);

digitalWrite(Motorpin,LOW);

delay(1000);// 급수후 그냥 1초 휴식

}

//delay(100);

delay(sampling_time); // 1시간마다 샘플링

 

}