Advertisement
m33600

wilker - smart

Sep 29th, 2016
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 31.34 KB | None | 0 0
  1. /*
  2.  * 30 de julho: cloud retrieve para brain setpoint
  3.  * ruido tecla zero ohm = 10 em campo
  4.  * 25 de julho: inclusão de 50 vetores de calibração
  5.  * fu- modo manual de wifi config(mudança vouluntaria de AP)
  6.         Range de temperatura (32-40°C)--OK
  7.         Nova Temp. máx 40°C           --OK
  8.         Corrigir ruido no botão de "reduzir a temperatura" que está mudando de automático para manual
  9.         Ler Estado do Cube pela serial
  10.         Levar dados do fluxômetro para o Copacabana e Gerar Relatório (Thingspeak com exportação xlsx)
  11.  
  12. Programa para comandar ThermoCube via resposta do ptc - cateter
  13. 3 update 29/6/2016: incluir wifi e thingspeak
  14. wifi tenta conexão anterior. Se falhar entra em modo configuração
  15. - abre AP chamado TheCube, sem senha
  16. - serve pagina http em 192.168.4.1
  17. - na pagina entre com scan ou escolha a rede
  18. - depois o programa inicia normalmente
  19.  
  20.  
  21. 2 update 28 jun 2016: 3 setpoints por botaõ
  22. temp esfriar = 0,1 C
  23. temp default = 10 C
  24. temp aquecer = 20 C
  25. calibração coarse para prova de conceito
  26. pode depender de outras temperaturas, tabelar, criar regressões e correções
  27. testar mesma correção com diversor chips para repetibilidade
  28.  
  29. agora mostra temperatura em Celsuis no lcd
  30.  
  31. comandos apenas enviam, mas serial está montada para receber status
  32. sem campainha
  33.  
  34.  */
  35. #include <ESP8266WiFi.h>   // lib do ESP8266 para wifi, só necessário quando usa wifi
  36. #include <SPI.h>
  37. #include <SmartConnect.h>
  38. #include <stdlib.h>
  39. #include <string.h>
  40.  
  41.  
  42. #include "WiFiUdp.h"
  43. WiFiUDP udp;
  44.  
  45.  
  46. //needed for library WiFiManager
  47. #include <DNSServer.h>
  48. #include <ESP8266WebServer.h>
  49. #include <WiFiManager.h>                                       //https://github.com/tzapu/WiFiManager
  50.  
  51.  
  52.  
  53.   #include <SimpleTimer.h>                                     // via interrupção, melhor opção para publicação a cada 16s
  54.   SimpleTimer timer;                                           // inicia instancia com nome "timer" ( podem ser várias instancias)
  55.  
  56.   #include "ThingSpeak.h"                                      // lib do thingspeak.com
  57.  
  58.   int status = WL_IDLE_STATUS;
  59.   WiFiClient  client;
  60.  
  61.   unsigned long myChannelNumber = 139811;                     // canal thingspeak do Cube2
  62.   const char * myWriteAPIKey = "LV2ICZ6QLKBYBEJU";            // api key do Cube2
  63.   const char * myReadAPIKey = "DB7J18KFYYB5VHG9";             // api key do Cube2
  64.  
  65.  
  66. #include <LiquidCrystal_I2C.h>
  67. LiquidCrystal_I2C lcd(0x27,20,4);                                    // ajusta LCD para endereço 0x27 com 20 caracteres x 4 linhas
  68.  
  69. #define ledVermelho 14
  70. #define ledVerde 12
  71. #define ledAmarelo 5
  72.  
  73. int contador = 0;
  74. int leitura = 1023;
  75. int lastLeitura = 0;
  76. int ptcSetPoint = 300;                                              // temperatura default: mudou durante a programação. FU passar para Celsius
  77. int candidato = 0;
  78. int lastValido = 0;
  79. float cloudSetpoint = 0.0;
  80.  
  81. float newC = 0;
  82. float newDeciF = 0;
  83. float temperatura = 0.0;
  84. float SET = 34.0;
  85.  
  86. // nome dos tres botoes setpoints:
  87. const int superior = 321;                                           // 34,5 C ; usar temperatura C aqui dara erro de arredondamento tipico dos floats
  88. const int medio = 300;                                              // 34,0 C
  89. const int inferior = 332;                                           // 33,5 C
  90. boolean pub = true;
  91. boolean automatico = true;
  92. int entradaCalibrar = 0;
  93. float saidaCalibrar = 0.0;
  94. int resultCode = 0;
  95. float x = 0.0;                                                      // entrada na tabela
  96. float y = 0.0;                                                      // saida da tabela
  97. boolean bancada = true;                                            // modo bancada, nao precisa sensores, display etc, e aciona serial monitor
  98.  
  99.  
  100.  
  101.    IPAddress ipBroadCast(192, 168, 2, 255);
  102.    unsigned int udpRemotePort=8080;
  103.    unsigned int udplocalPort=8080;
  104.    const int UDP_PACKET_SIZE = 50;
  105.    char udpBuffer[ UDP_PACKET_SIZE];
  106.  
  107.    
  108. //____________________________________________________________________________________________________ smart vars
  109. //char server[] = "www.smartapps.com.br";              //Endereco Smartapps.
  110. char server[] = "192.168.0.14";              //Endereco Smartapps.
  111. // é igual pq o email é igual
  112. char login[] = "4d2011a4c907452432fea42d7f001e96";   //Login do usuario: Encontra-se na plataforma.
  113. //char password[] = "WzVUbVNsDzYIYwluVjE=";            //Senha do usuário: Encontra-se na plataforma.
  114. char password[] = "WjYHMlVj";
  115. char app[] = "controls";                             //Nome do aplicativo utilizado.
  116. char schema[] = "4d2011a4c907452432fea42d7f001e96";  //Login do aplicativo: Normalmente o mesmo do usuário, só muda se for utilizado um aplicativo que foi compartilhado por outro usuário, neste caso é o login do outro usuário.
  117. String postDataVar1 = "variavel=1&valor=";
  118. String responseData;
  119. long randNumber;
  120.  
  121.  
  122. //================================================================
  123. // Function to send udp message
  124. //================================================================
  125. void fncUdpSend()
  126. {
  127.  
  128.   float t = 1.0; float h = 2.0;
  129.                                
  130.   char buffer[12];
  131.   strcpy(buffer,".......temp");
  132.    //dtostrf(FLOAT,     WIDTH,PRECSISION,  BUFFER  )
  133.    dtostrf(temperatura,   2,      2,       buffer );
  134.                                                              
  135.   udp.beginPacket(ipBroadCast, udpRemotePort);
  136.   udp.write(buffer, sizeof(buffer));
  137.   udp.endPacket();
  138.                                                                                      
  139.   delay(1000);
  140.                                                                                            
  141.                                                              
  142.   char buffer2[12];
  143.   strcpy(buffer2,"........SET");
  144.   //dtostrf( FLOAT  ,WIDTH, PRECSISION,  BUFFER)
  145.   dtostrf(    SET,     2,     2,         buffer2);
  146.                                                                                    
  147.   udp.beginPacket(ipBroadCast, udpRemotePort);
  148.   udp.write(buffer2, sizeof(buffer2));
  149.                                                                                            
  150.                                                                    
  151.   udp.endPacket();
  152.                                                                                            
  153.   delay(1000);
  154. }
  155. //================================================================
  156.  
  157.  
  158.  
  159.  
  160.  
  161.  
  162.  
  163.  
  164.  
  165.  
  166.  
  167.  
  168.  
  169.  
  170.  
  171. void cloudRetrieve(){
  172.     cloudSetpoint = ThingSpeak.readFloatField(myChannelNumber, 2, myReadAPIKey);  // field2 = brain setpoint
  173.     resultCode = ThingSpeak.getLastReadStatus();
  174.  
  175.     lcd.setCursor(0,3);
  176.     lcd.print("                ");
  177.     lcd.setCursor(0,3);
  178.     lcd.print(resultCode);
  179.     if (bancada){Serial.print("result-code=");Serial.println(resultCode);}
  180.  
  181.     if(resultCode == 200){
  182.       SET = cloudSetpoint;                                         // ajusta setpoint pela nuvem
  183.      
  184.     }
  185. }
  186.  
  187. void publish(){
  188.  if (pub == false){return;}                                         // nao publica em certas condições (setup por exemplo)
  189.     // ativado por SimpleTimer em setup, a cada 16s...  
  190.     // ThingSpeak will only accept updates every 15 seconds.
  191.     yield();                                                        // solta background tasks
  192.     lcd.setCursor(0,3);
  193.     lcd.print("enviando dados");
  194.  
  195.  
  196.     ThingSpeak.setField(1,temperatura);                             // brain temp
  197.     ThingSpeak.setField(2,SET);                                     // brain setpoint
  198.     ThingSpeak.setField(3,newC);                                    // cube setpoint
  199.     ThingSpeak.setField(4,automatico);                              // cube auto/manual status
  200.  
  201.     ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);         // Write the fields that you've set all at once.
  202.  
  203.     yield();                                                        // solta background tasks
  204.     lcd.setCursor(0,3);
  205.     lcd.print("                ");
  206.  
  207.     cloudRetrieve();                                               // coleta ultimo dado salvo na nuvem
  208.  
  209.  
  210. }
  211.  
  212.  
  213. void configModeCallback (WiFiManager *myWiFiManager) {              // coisas a fazer durante o wifi setup mode
  214.     lcd.setCursor(0,1);
  215.     lcd.print("WiFi Config Mode");
  216.     if (bancada){Serial.println("Wifi Config Mode");}
  217.  
  218.     //Serial.println("Entered config mode");
  219.     yield(); // solta background tasks
  220.     //Serial.println(WiFi.softAPIP());
  221.     yield(); // solta background tasks
  222.     //Serial.println(myWiFiManager->getConfigPortalSSID());
  223. }
  224. //=========================================================================================================================================================
  225. void setup() {  //............................................................................................S E T U P ..................................
  226.    SMART.begin(9600, false);
  227.  
  228.      // Initiate the i2c connection on esp pins 13 (DAT/SDA) and 0 (CLK/SCL)
  229.      Wire.begin(13,0); // gpio 0 reusado - funcionou no copacabana
  230.      lcd.begin(20, 4);
  231.      lcd.setBacklight(HIGH);
  232.      lcd.print("TheCube2");
  233.  
  234.       pinMode(4, OUTPUT);
  235.       pinMode(ledAmarelo, OUTPUT);
  236.       pinMode(ledVerde, OUTPUT);
  237.       pinMode(ledVermelho, OUTPUT);
  238.  
  239.         Serial.begin(9600);                                                 // inicializa comunicação com serial monitor a 9600 8n1 cr/lf
  240. // -------------------------------------configuração WIFI
  241.     //WiFiManager
  242.     //Local intialization. Once its business is done, there is no need to keep it around
  243.     WiFiManager wifiManager;
  244.     wifiManager.setDebugOutput(false);                                    // impede degug pela serial, uso apenas em diagnostico
  245.  
  246.     if (analogRead(A0)<20){                                             // boot + qquer tecla = WiFi reset Settings
  247.         wifiManager.resetSettings();              
  248.         lcd.clear();
  249.         lcd.setCursor(0,0);
  250.         lcd.print("Reconfigure WiFi    ");
  251.         if (bancada){Serial.println("Reconfigura Wifi ");}
  252.         lcd.setCursor(0,1);
  253.         lcd.print("Rede TheCube-2      ");
  254.         lcd.setCursor(0,2);
  255.         lcd.print("pagina 192.168.4.1  ");
  256.         }
  257.  
  258.    
  259.     //set custom ip for portal
  260.     //wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
  261.  
  262.     //fetches ssid and pass from eeprom and tries to connect
  263.     //if it does not connect it starts an access point with the specified name
  264.     //here  "AutoConnectAP"
  265.     //and goes into a blocking loop awaiting configuration
  266.  
  267.  
  268.     //wifiManager.setConfigPortalTimeout(60);                             // 1 minuto para conectar o tel no esp, escolher rede e resumir
  269.     // wifiManager.setAPCallback(configModeCallback);
  270.     wifiManager.autoConnect("TheCube-2");
  271.     //or use this for auto generated name ESP + ChipID
  272.     //wifiManager.autoConnect();
  273.  
  274.    
  275.     //if you get here you have connected to the WiFi
  276.     //Serial.println("connected...yeey :)");
  277.     lcd.clear();
  278.     lcd.print("TheCube2  conectado!");
  279.     if (bancada){Serial.println("conectado wifi");}
  280.  
  281.  
  282.    
  283.   // Setup a function to be called every second
  284.   timer.setInterval(30000L, publish);                                       // vai postar no thingspeak a cada 16s
  285.  // timer.setInterval(5000L, cloudRetrieve);
  286.  
  287.   yield();                                                                  // solta background tasks
  288.   ThingSpeak.begin(client);
  289.  
  290.  
  291.   cloudRetrieve();                                                          // em boot: coleta ultimo Setpoint salvo na nuvem
  292.  
  293.   //_________________________________________________________________________smart Setup:
  294.    SMART.begin(9600, false);
  295.  
  296.   // connect on smartapps platform
  297.   if (bancada){Serial.println("Conectando na plataforma Smart");}
  298.   if (SMART.connect(server, login, password, 80)) { if(bancada){Serial.println("Dispositivo autenticado.");}  }
  299.   else {if (bancada){Serial.println("Nao autenticado.");} }
  300.  
  301. } // ..............................fim de setup........................................................
  302.  
  303.  
  304.  
  305. // subrotinas..........................................................................................
  306.  
  307.  
  308. void tabela(){                                                             // são 50 equações de reta a interpolar
  309.  
  310.  
  311.   float Y[51] = {
  312.   7.0,
  313.   19.1,
  314.   29.2,
  315.   29.6,
  316.   29.6,
  317.   30.0,
  318.   30.0,
  319.   30.3,
  320.   30.3,
  321.   30.7,
  322.   30.7,
  323.   31.0,
  324.   31.0,
  325.   31.4,
  326.   31.4,
  327.   31.8,
  328.   31.8,
  329.   32.1,
  330.   32.1,
  331.   32.5,
  332.   32.5,
  333.   32.9,
  334.   32.9,
  335.   33.3,
  336.   33.3,
  337.   33.6,
  338.   34.0,
  339.   34.0,
  340.   34.5,
  341.   34.9,
  342.   35.3,
  343.   35.3,
  344.   35.8,
  345.   35.8,
  346.   36.7,
  347.   37.1,
  348.   37.6,
  349.   38.0,
  350.   38.0,
  351.   38.5,
  352.   38.5,
  353.   39.1,
  354.   39.1,
  355.   39.6,
  356.   39.6,
  357.   40.1,
  358.   40.6,
  359.   41.5,
  360.   42.0,
  361.   42.3,
  362.   //43.7
  363.     };
  364.  
  365.   float X[51]={
  366.   -10.0,
  367.   14.7,
  368.   29.9,
  369.   30.0,
  370.   30.3,
  371.   30.3,
  372.   30.9,
  373.   31.0,
  374.   31.4,
  375.   31.5,
  376.   31.7,
  377.   31.8,
  378.   32.1,
  379.   32.2,
  380.   32.4,
  381.   32.6,
  382.   32.8,
  383.   33.0,
  384.   33.3,
  385.   33.4,
  386.   33.5,
  387.   33.7,
  388.   33.9,
  389.   34.1,
  390.   34.4,
  391.   34.6,
  392.   34.8,
  393.   34.9,
  394.   35.6,
  395.   35.7,
  396.   36.2,
  397.   36.5,
  398.   36.8,
  399.   36.9,
  400.   37.7,
  401.   38.1,
  402.   38.4,
  403.   38.6,
  404.   39.1,
  405.   39.1,
  406.   39.4,
  407.   39.5,
  408.   39.7,
  409.   39.9,
  410.   40.0,
  411.   40.4,
  412.   41.0,
  413.   41.2,
  414.   41.7,
  415.   42.2,
  416.  // 42.9
  417.   };
  418.  
  419.   for (int index = 0; index < 50-1; index++){
  420.     yield();
  421.     if ((x>42)||(x<-9)){y=0;break;}                                   // proteção dos limites
  422.     if((x>X[index])&&(x<X[index+1])){
  423.      
  424.         // inicio da interpolação no segmento correto
  425.         float x1=X[index];float x2=X[index+1];
  426.         float y1=Y[index];float y2=Y[index+1];
  427.         float dy=y2-y1;float dx=x2-x1;
  428.         float inclinacao=dy/dx;
  429.         float subx=x-x1;
  430.         float suby=dy*subx/dx;
  431.         y=suby+y1+0.5;                                                // devolvi 0,5C por conta dos arredontamentos falhos de floats
  432.         // fim da interpolação
  433.        
  434. //        Serial.print("leitura atual =        ");                    // impressão para diagnostico
  435. //        Serial.println(x);
  436. //        Serial.print(X[index]);
  437. //        Serial.print(" encontrado..... ");
  438. //        Serial.println(Y[index]);
  439. //        Serial.print(" convertido..... ");
  440. //        Serial.println(y);
  441.        // delay(500);
  442.         break;
  443.         }
  444.    
  445. //    Serial.print(X[index]);
  446. //    Serial.print("  ");
  447. //    Serial.println(Y[index]);
  448. //    Serial.print("leitura atual =        ");
  449. //    Serial.println(x);
  450.     }
  451.  
  452.  
  453.  
  454. }
  455.  
  456.  
  457.  
  458.  
  459. void calibrar(){                                                                   // aqui é corrigida a leitura e convertida a graus Celsius
  460.       yield();                                                                     // solta background tasks
  461.        // primeira correção
  462.      float  temp = ((-8.74126*entradaCalibrar)/100 + 62.5402);                     // calibração dixtal na planilha google com regressão linear
  463.                                                                                    // erro até 0,5 C  fora do intervado dos 3 setpoints!!!
  464.     // segunda correção, após compilação
  465.     saidaCalibrar =((0.986842*temp) - 1.789473);
  466.     // mais correções até amadurecer o projeto  
  467.  
  468.     // terceira correção, via tabela com 50 vetores usando resultados acima
  469.     x = saidaCalibrar;
  470.     tabela();                                                                      // computa na sub tabela
  471.     saidaCalibrar = y;                                                             // corrigido pela tabela
  472.  
  473.    
  474. }
  475.  
  476.  
  477. void piscaVerde(){
  478.   digitalWrite(ledVerde, HIGH);                                     // turn the LED on (HIGH is the voltage level)
  479.   delay(10);
  480.   return;    
  481.   }
  482.   void piscaVermelho(){
  483.   digitalWrite(ledVermelho, HIGH);                                  // turn the LED on (HIGH is the voltage level)
  484.   delay(10);
  485.   return;    
  486.   }
  487.   void piscaAmarelo(){
  488.   digitalWrite(ledAmarelo, HIGH);                                   // turn the LED on (HIGH is the voltage level)
  489.   delay(10);
  490.   digitalWrite(ledAmarelo, LOW);                                    // turn the LED on (HIGH is the voltage level)
  491.  
  492.   return;    
  493.   }
  494. void pedeParaAquecer(){
  495.   if (automatico == false){return;}
  496.   yield(); // solta background tasks
  497.   // envia protocolo tosco new SetPoint = 36 -- qquer numero seguro acima para fazer subir temperatura
  498.   ////Serial.println("pede para Aquecer++++++++++++++++++++++++++++++++++++");
  499.         lcd.setCursor(0,2);
  500.         lcd.print("comando AQUECER");
  501.        
  502.         // codigo a seguir imaturo: ideia: mandar aquecer pedindo um grau acima... qquer grau seguro
  503.         // nao pedir demais. se perder comunicação o Cube deve achar um limite seguro  
  504.         byte commandByte = 225;                                    // = send new setpoint to cube
  505.         newC = 40.0;                                               // fu. analog read do pot ou ptc
  506.         newDeciF = (newC * 1.8 + 32);
  507.         int newF = (10 * newDeciF);
  508.         byte highF = highByte(newF);
  509.         byte lowF = lowByte(newF);
  510.         // fim do codigo imaturo
  511.  
  512. //           lcd.setCursor(0,3);
  513. //           lcd.print("         ");
  514. //           lcd.setCursor(0,3);
  515. //           lcd.print(commandByte, HEX);                           // Print the raw binary value
  516. //           lcd.print(" ");
  517. //           lcd.print(lowF, HEX);                                  // Print the raw binary value
  518. //           lcd.print(" ");
  519. //           lcd.print(highF, HEX);                                 // Print the raw binary value
  520.              
  521.               // payload para ThermoCube:
  522.               Serial.write(commandByte);                            // Print the raw binary value
  523.               Serial.write(lowF);                                   // Print the raw binary value
  524.               Serial.write(highF);                                  // Print the raw binary value
  525.  
  526.  
  527.  
  528.        
  529.  
  530.         delay(100);          
  531.   return;
  532. }
  533.  
  534.  
  535. void pedeParaEsfriar(){
  536.     if (automatico == false){return;}
  537.  
  538.   yield(); // solta background tasks
  539.   // envia protocolo tosco new SetPoint = 33 -- qquer numero seguro abaixo para fazer baixar temperatura
  540.   ////Serial.println("pede para Esfriar -----------------------------------");
  541.         lcd.setCursor(0,2);
  542.         lcd.print("comando ESFRIAR");
  543.  
  544.         // codigo a seguir imaturo: ideia: mandar esfriar pedindo um grau abaixo... qquer grau seguro
  545.         // nao pedir demais. se perder comunicação o Cube deve achar um limite seguro  
  546.         byte commandByte = 225;                                     // = send new setpoint to cube
  547.         newC = 0.1;                                                 // Bernardo pediu zero, coloquei 0.1C para evitar erros de calculo
  548.         newDeciF = (newC * 1.8 + 32);
  549.         int newF = (10 * newDeciF);
  550.         byte highF = highByte(newF);
  551.         byte lowF = lowByte(newF);
  552.         // fim do codigo imaturo
  553.  
  554. //           lcd.setCursor(0,3);
  555. //           lcd.print("         ");
  556. //           lcd.setCursor(0,3);
  557. //           lcd.print(commandByte, HEX);                           // Print the raw binary value
  558. //           lcd.print(" ");
  559. //           lcd.print(lowF, HEX);                                  // Print the raw binary value
  560. //           lcd.print(" ");
  561. //           lcd.print(highF, HEX);                                 // Print the raw binary value
  562.              
  563.               // payload para ThermoCube:
  564.               Serial.write(commandByte);                            // Print the raw binary value
  565.               Serial.write(lowF);                                   // Print the raw binary value
  566.               Serial.write(highF);                                  // Print the raw binary value        
  567.  
  568.        
  569.         delay(100);  
  570.   return;
  571. }
  572. void pedeDefault(){                                                // se estiver na temperatura ou houver ruido, pede 35,5 C ao Cube
  573.     if (automatico == false){return;}
  574.  
  575.   // envia protocolo tosco new SetPoint = 33 -- qquer numero seguro abaixo para fazer baixar temperatura
  576.         yield(); // solta background tasks
  577.         lcd.setCursor(0,2);
  578.         lcd.print("comando DEFAULT");
  579.  
  580.         // codigo a seguir imaturo: ideia: mandar centrar em 10 graus
  581.         // significa esfriar menos, reduzindo a diferença de temperaturas
  582.         // nos estudos o esfriamento usou quase zero grau... aqui sobe um pouco... 10 inicialmente
  583.         byte commandByte = 225;  // = send new setpoint to cube
  584.         newC = 10.0; // fu. analog read do pot ou ptc
  585.         newDeciF = (newC * 1.8 + 32);
  586.         int newF = (10 * newDeciF);
  587.         byte highF = highByte(newF);
  588.         byte lowF = lowByte(newF);
  589.         // fim do codigo imaturo
  590.  
  591. //           lcd.setCursor(0,3);
  592. //           lcd.print("         ");
  593. //           lcd.setCursor(0,3);
  594. //           lcd.print(commandByte, HEX);                              // Print the raw binary value
  595. //           lcd.print(" ");
  596. //           lcd.print(lowF, HEX);                                     // Print the raw binary value
  597. //           lcd.print(" ");
  598. //           lcd.print(highF, HEX);                                    // Print the raw binary value
  599.              
  600.               // payload para ThermoCube:
  601.               Serial.write(commandByte);                              // Print the raw binary value
  602.               Serial.write(lowF);                                     // Print the raw binary value
  603.               Serial.write(highF);                                    // Print the raw binary value        
  604.  
  605.  
  606.  
  607.        
  608.         delay(100);  
  609.   return;
  610. }
  611.  
  612.  
  613.  
  614.  
  615. //..............................................................L O O P ..............................  
  616.  
  617. void loop() {
  618.  
  619.   // retirar a seguir: só para teste de compilação
  620.   // esse loop de envio deve respeitar os outros e ser ativado pelo timer!!!!!!!!!!!!!!!1
  621.                                   if (SMART.connected()) {
  622.                              
  623.                                   Serial.println("Enviando dados dados...");
  624.                              
  625.                                   String stringPostData = "";
  626.                                   stringPostData.concat(postDataVar1);
  627.                                   randNumber = random(30);
  628.                                   stringPostData.concat(randNumber);
  629.                              
  630.                                   char arrayPostData[20];
  631.                                   stringPostData.toCharArray(arrayPostData, 20);
  632.                              
  633.                                   responseData = SMART.exec("POST","csv", app, schema, "variaveis_valores/insert", arrayPostData);
  634.                                   Serial.println(responseData);
  635.                              
  636.                                 } else {
  637.                              
  638.                                   Serial.println("Dispositivo desconectado!");
  639.                              
  640.                                 }
  641.                              
  642.                                 delay(1000);
  643.  
  644.   yield();                                                               // solta background tasks
  645.   timer.run();                                                           // Initiates SimpleTimer
  646.  
  647.       lastLeitura = leitura;                                             // atualiza leitura validada n vezes
  648.  
  649.       leitura = (analogRead(A0));
  650.       if (bancada){leitura = 512;}                                       // Fixa meia escala para bancada...............................................
  651.        if(leitura < 100)  { goto pulo1;}                                  // salta para setpoint... melhorar para subrotina!!!!
  652.       entradaCalibrar = leitura;                                         // entra a leitura...
  653.       calibrar();                                                        // tabela e converte para celsius
  654.       temperatura = saidaCalibrar;                                       // ... e volta a temperatura calibrada
  655.  
  656.  
  657.   fncUdpSend();  // publica UDP
  658.  
  659. // impressão serial de diagnóstico --- comentar apos aprovação
  660.      // Serial.print("leit=");
  661.      // Serial.println(leitura);
  662.      // yield();                                                           // solta background tasks
  663.       //Serial.print(" temp = ");
  664.       //Serial.print(temperatura);
  665.       //yield();                                                           // solta background tasks
  666.       //Serial.print(" SET = ");
  667.       //Serial.print(SET);
  668.       //yield();                                                           // solta background tasks
  669.       //Serial.print(" cont =");//Serial.println(contador);
  670.       //Serial.println(temperatura, 1);
  671.  
  672.      
  673.       if (automatico == true){ lcd.setCursor(0 ,0); lcd.print("Auto    "); if (bancada){Serial.println("modo automatico");}  }
  674.  
  675.  
  676.       if (automatico == false){ lcd.setCursor(0 ,0); lcd.print("Manual  ");
  677.       if (bancada){Serial.println("modo manual");}
  678.      
  679.       lcd.setBacklight(LOW); delay(50); lcd.setBacklight(HIGH);}    
  680.       lcd.setCursor(11,1);
  681.       lcd.print("inst ");
  682.       yield();                                                           // solta background tasks
  683.       lcd.setCursor(16,1);
  684.       lcd.print("    ");
  685.       lcd.setCursor(16,1);
  686.       lcd.print(temperatura,1);
  687.       yield();                                                           // solta background tasks  
  688.       piscaAmarelo();
  689.       delay(300);
  690.       if (bancada){Serial.print("instantaneo = "); Serial.println(temperatura,1);}
  691.  
  692.  
  693.      
  694.                                                      
  695.  
  696.   // confirmador de leitura, para evitar ruidos... n leituras iguais valida    
  697.   if (leitura == lastLeitura){contador = contador + 1; piscaAmarelo();}  // acumula leituras validas até n
  698.  
  699.   if(contador == 2) {                                    // (baixei para n=2 confirmações) só executa os proximos comandos se validou um dado sem ruido
  700.         yield(); // solta background tasks
  701.         contador = 0;
  702.  
  703.         ////Serial.println("n leituras ");
  704.         lcd.setCursor(9,0);
  705.         lcd.print("valido ");
  706.         lcd.setCursor(16,0);
  707.         lcd.print("    ");
  708.         lcd.setCursor(16,0);
  709.         lcd.print(temperatura,1);
  710.         pub = true; // habilita publicação no thingspeak
  711.         if (bancada){Serial.print("valido = "); Serial.println(temperatura,1);}
  712.        
  713.  
  714.        
  715.         // falta de sonda.............nem publica pq fica em loop, mas pede default ao cube
  716.         while (leitura > 1000){
  717.           yield();                                                 // solta background tasks
  718.           lcd.setBacklight(LOW);
  719.           delay(300);
  720.           lcd.setBacklight(HIGH);          
  721.           lcd.setCursor(12,3);
  722.           lcd.print("sonda ?");
  723.           delay(1000);
  724.           lcd.clear();
  725.           lcd.print("TheCube2");
  726.           pedeDefault();
  727.           leitura = (analogRead(A0));                              // leitura para ver se saiu do erro
  728.           }
  729.  
  730.         // controle automatico do cube;            
  731.         if (temperatura < SET){                                    // se esfriou, avisa e pede para esquentar
  732.         // led verde avisa que esta mais frio que o setpoint
  733.         digitalWrite(ledVermelho, HIGH);
  734.         digitalWrite(ledVerde, LOW);
  735.         pedeParaAquecer();
  736.         }
  737.         if (temperatura > SET){                                    // se esquentou, avisa e pede para esfriar
  738.         digitalWrite(ledVermelho, LOW);
  739.         digitalWrite(ledVerde, HIGH);
  740.         pedeParaEsfriar();
  741.         }
  742.         if (temperatura == SET){                                  // se está no ponto, peça default  C ... com floats esse ponto nem existe!
  743.         digitalWrite(ledVermelho, LOW);
  744.         digitalWrite(ledVerde, LOW);
  745.         pedeDefault();
  746.         }
  747.  
  748.  
  749.  
  750. // ,,,,,,,,,,,,,,,,,,,,,,  ajuste dos Setpoints .....................................................
  751. /* upgrade para resistores de 100ohm ( down = 0 ohm, mid = 100ohm, up = 200ohm)
  752.  * leituras...............................    0           17-18      34-38
  753.  * tresholds........................................14.........  .30..........62
  754.  *
  755.  */
  756. pulo1:
  757.           yield(); // solta background tasks
  758.        
  759.    if(leitura < 62)  {                                            // qquer botão pressionado é lido como <20...
  760.           pub = false;
  761.  
  762.         if ((leitura < 62) && (leitura > 30) && (SET < 40)) {      // regiao do botao superior, que da leitura 34 a 38, set impede subir mais
  763.            // ptcSetPoint = superior;                             // 0 a 1024 nao convertido F.U usar graus
  764.            ptcSetPoint = ptcSetPoint - 1;                         // ainda estamos antes da conversão
  765.            entradaCalibrar = ptcSetPoint;
  766.            calibrar();                                            // converter para Celsius para mostrar no campo SET
  767.            SET = saidaCalibrar;                                   // nova temperatura ja convertida, para mostrar no LCD
  768.            }
  769.        
  770.         yield();                                                   // solta background tasks  
  771.      
  772.         if ((leitura < 29) && (leitura > 14)){                       // região do botao medio, que da leitura 17 a 18
  773.  
  774.              if (automatico == true){
  775.                  automatico = false;
  776.                  lcd.clear();
  777.                  lcd.setCursor(0,3);
  778.                  lcd.print("Modo Manual     ");
  779.                  //Serial.println("mudando para manual");
  780.                  lcd.setCursor(0,0);        
  781.                  lcd.print("raw= ");
  782.                  lcd.print(leitura);
  783.                  delay(3000);
  784.                  }
  785.                 else {
  786.                   automatico = true;
  787.                   lcd.setCursor(0,3);
  788.                   lcd.print("Modo Automatico    ");
  789.                   lcd.setCursor(0,0);        
  790.                   lcd.print("raw= ");
  791.                   lcd.print(leitura);
  792.                   //Serial.println("mudando para automatico");
  793.                   delay(3000);
  794.                   }
  795.          }
  796.        
  797.           yield(); // solta background tasks
  798.  
  799.         if ((leitura < 14)&&(SET > 32)) {                            // região do botao inferior, que da leitura 0, set impede descer mais
  800.            ptcSetPoint = ptcSetPoint + 1;                           // ainda estamos antes da conversão
  801.            entradaCalibrar = ptcSetPoint;                           // emprestimo da variavel leitura para reuso da sub calibrar()
  802.            calibrar();                                              // converter para Celsius para mostrar no campo SET
  803.            SET = saidaCalibrar;                                     // de novo, emprestimo da variavel temperatura para reuso de calibrar()
  804.            }
  805.  
  806.  
  807.  
  808.  
  809.  
  810.              
  811.         digitalWrite(ledVermelho, HIGH);
  812.         digitalWrite(ledVerde, HIGH);
  813.         lcd.setCursor(0,3);
  814.         lcd.print("New SetPoint = ");
  815.         lcd.setCursor(16,3);
  816.         lcd.print("   ");
  817.         lcd.setCursor(16,3);
  818.         lcd.print(SET,1);
  819.         lcd.setCursor(0,0);        
  820.         lcd.print("raw= ");
  821.         lcd.print(leitura);
  822.         delay(100);                                                  // aumenta ou diminui velocidade de mudança do setpoint
  823.         lcd.clear();
  824.        
  825.                
  826.  
  827.  
  828.        
  829.   } // fim de setPoints
  830.  
  831.  
  832.         lcd.setCursor(0,1);
  833.         lcd.print("SET ");
  834.         lcd.setCursor(4,1);
  835.         lcd.print(SET,1);
  836.  
  837.  
  838. } // fim de if contador = 2 ( leitura valida)
  839.  
  840.  
  841. } // fim de loop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement