Advertisement
untoha

autopoliv.ino

Aug 23rd, 2019
357
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 7.79 KB | None | 0 0
  1. /* первый путь - импульсный дождеватель на поле  
  2.  * второй путь - улиточная ферма
  3.  * третий клапан мамин огород
  4.  */
  5.  
  6. //#include <IRremote.h>      
  7. //#include <Wire.h>
  8. #include <LiquidCrystal_I2C.h>
  9. //#include <iarduino_RTC.h>   // https://lesson.iarduino.ru/page/podklyuchenie-rtc-chasy-realnogo-vremeni-ds1302-ds1307-ds3231-k-arduino/
  10. #include <DS1302.h>           // time
  11. #include "DHT.h"              // датчик влажности и температуры воздуха
  12.  
  13. #define DHTTYPE DHT11 // DHT 11     кстати, зачем этом делается, потом же нигде не используется, но в мануале было так
  14.  
  15. int lastlcdusage[2] = {0,0};                    // на каком цикле было последнее включение lcd, ну чтобы выключать его если не используется типа для экономии =)
  16. int liter = 0;                                  // количество сделанных циклов
  17. int iters[1] = {30};                            // для проверок раз в
  18. int curstate[2] = {0,0};                        // глобальное состояние клапанов 0-off;1-?;2-?;3-?
  19. bool inited = false;                            // происходит 1 раз на старте
  20. int wslimits[1] = {500}; //,500,500};           // лимиты значений датчиков влажности при достижении которых начинает работать автополив конкретного датчика
  21. int wspins[3] = {A0,A1,A2};                     // пины на которых стоят датчики влажности почвы
  22. int rpins[3] = {10,9,8}; //,8,7,6,5,4,3};       // пин реле 10 это реле электричества
  23. int dht_pin = 13;                               // пин датчика влажности
  24. int humi = 65;                                  // если влажность ниже этого значения, то поливаем
  25.  
  26. //IRrecv irrecv(ir_pin); // указываем пин, к которому подключен IR приемник
  27. //decode_results results;
  28.  
  29. LiquidCrystal_I2C lcd(0x3F,20,4);
  30. DS1302 rtc(12, 11, 2);
  31.  
  32. DHT dht(dht_pin, DHTTYPE);
  33.  
  34. void setup()
  35. {
  36.   for (int i=0; i<=(sizeof(rpins)/2)-1; i++){   //выключаем все реле
  37.      digitalWrite(rpins[i], HIGH);}
  38.   for (int i=0; i<=(sizeof(rpins)/2)-1; i++){    
  39.      pinMode(rpins[i], OUTPUT);}  
  40.  
  41.   lcd.init();                    
  42.   lcd.backlight();                              // Включаем подсветку дисплея
  43.  
  44.   /*rtc.writeProtect(false);                    // init time here
  45.   rtc.halt(false);
  46.   Time t(2017, 8, 27, 20, 42, 50, Time::kSunday);
  47.   rtc.time(t);*/
  48.  
  49.   dht.begin();
  50. }
  51.  
  52. void loop()     // MAIN ////////////////////////////////////////////////////////////////////////////////////
  53. {    
  54.   int hum = dht.readHumidity();                                                     // влажность воздуха (вроде показания разнятся с реальными данными). по замерам 70-72 дождь, среднее 50. наверное если больше 65, то ненадо поливать.
  55.   if (!inited)
  56.   {    
  57.     lcd.print("watering inited");
  58.     lcd.setCursor(0, 1);
  59.     lcd.print("use controller");
  60.     inited = true;        
  61.   }
  62.  
  63.   if (liter > lastlcdusage[0] + 100){      
  64.     lcd.noBacklight();  }
  65.   if (liter > lastlcdusage[1]+iters[0]){                                            // time event
  66.     lastlcdusage[1] = liter;
  67.     Time t = rtc.time();    // t.yr t.mon t.date t.hr t.min
  68.    
  69.     if ((hum < humi) && (t.hr == 9 or t.hr == 11 or t.hr == 13 or t.hr == 15) && t.min == 0){       // клапан импульсного дождевателя
  70.       curstate[0] = 3;
  71.       klapan(1,true);
  72.     } else if (curstate[0] == 3 && t.min > 5){
  73.       curstate[0] = 0;
  74.       klapan(1,false);
  75.     }      
  76.      
  77.     /*else if(curstate[1] == 0 and t.min == 0 and t.hr >= 10 and t.hr < 19)         // клапан улиток   (проект с улитками закрыт)
  78.     {
  79.       klapan(2,true);                                                               // включаем на 1 тик
  80.       curstate[1] = 1;
  81.     }  
  82.      else if(curstate[1] == 1)
  83.     {
  84.       klapan(2,false);
  85.       curstate[1] = 0;
  86.     }*/    
  87.   }
  88.  
  89.   //wetanalyzer();                                                                      // влажность почвы
  90.  
  91.   if (digitalRead(5) == HIGH)             // A
  92.   {
  93.     Serial.println("5");  
  94.     if(curstate[0] != 1)
  95.     {
  96.       lcdmsg("turn on",1);
  97.       klapan(1,true);
  98.       curstate[0] = 1;
  99.     }
  100.     else if(curstate[0] == 1)
  101.     {
  102.       lcdmsg("turn off",1);
  103.       klapan(1,false);
  104.       curstate[0] = 0;
  105.     }  
  106.   }                                                                                     // нажатия кнопок пульта
  107.   else if (digitalRead(7) == HIGH)       // B
  108.   {
  109.     Serial.println("7");  
  110.     if(curstate[0] != 2)
  111.     {
  112.       lcdmsg("turn on",1);
  113.       klapan(2,true);
  114.       curstate[0] = 2;
  115.     }  
  116.     else if (curstate[0] == 2)
  117.     {
  118.       lcdmsg("turn off",1);
  119.       klapan(2,false);
  120.       curstate[0] = 0;
  121.     }
  122.   }
  123.   else if (digitalRead(4) == HIGH)      // C
  124.   {
  125.     lcdmsg("Humidity:"+String(dht.readHumidity()),1);
  126.   }
  127.   else if (digitalRead(6) == HIGH)      // D
  128.   {
  129.     Time t = rtc.time();
  130.     lcdmsg("time "+String(t.hr)+":"+String(t.min),1);
  131.   }
  132.  
  133.   liter++;
  134.   if (liter>=2000000){
  135.     liter = 0;
  136.     lastlcdusage[1] = 0;
  137.   }
  138.   delay(250);
  139. }
  140.  
  141. void wetanalyzer()
  142. {
  143.   for (int i=0; i<=(sizeof(wslimits)/2)-1; i++)
  144.   {
  145.     msg(String(analogRead(wspins[i])));
  146.     //msg(String(sizeof(wslimits)));
  147.   }
  148. }
  149.  
  150. void turnelec(int way)                                              // управление двумя главными реле
  151. {
  152.   if (way == 0)                                                     // выключаем електричество. на обоих реле минус
  153.   {
  154.     digitalWrite(rpins[0], HIGH);     // -
  155.     //digitalWrite(rpins[1], HIGH);     // -
  156.   }
  157.   else if (way == 1)                                                // вкл
  158.   {
  159.     digitalWrite(rpins[0], LOW);      // +
  160.     //digitalWrite(rpins[1], LOW);     // -
  161.   }
  162.   else if (way == 2)                                                // обратный не используется, вначале делал для постоянного тока, но блок питания на выходе переменный
  163.   {
  164.     digitalWrite(rpins[0], HIGH);     // -
  165.     digitalWrite(rpins[1], LOW);      // +
  166.   }
  167. }
  168.  
  169. void klapan(int id,bool action)                                     // id номер клапана с 1; action - true open, false close
  170. {
  171.   int way = 0;
  172.   if (action){
  173.     way = 1;
  174.     action = LOW;
  175.   }
  176.   else if (!action){
  177.     way = 0;
  178.     action = HIGH;
  179.   }
  180.  
  181.   turnelec(way);
  182.   Serial.println("rpins[id]");
  183.   Serial.println(rpins[id]);
  184.   digitalWrite(rpins[id], action);  
  185. }
  186.  
  187. void showinfo()
  188. {
  189.   for (int i=0; i<=(sizeof(wslimits)/2)-1; i++)
  190.   {
  191.     lcdmsg("wet sensor "+String(i+1),0);    
  192.     lcdmsg(String(analogRead(wspins[i])),1);    
  193.     delay(3000);
  194.   }
  195. }
  196.  
  197. void lcdmsg(String str,int line)                                  // как тут делать параметры по умолчанию?!
  198. {
  199.   lcd.backlight();
  200.   lcd.setCursor(0, line);
  201.   lcd.print("                ");       // clear line
  202.   lcd.setCursor(0, line);
  203.   lcd.print(str);  
  204.   lastlcdusage[0] = liter;
  205. }
  206.  
  207. bool isinarr(int what, int arr)
  208. {
  209.  
  210. }
  211.  
  212. void msg(String str)
  213. {
  214.     Serial.println(str);
  215. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement