Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 30 de julho: cloud retrieve para brain setpoint
- * ruido tecla zero ohm = 10 em campo
- * 25 de julho: inclusão de 50 vetores de calibração
- * fu- modo manual de wifi config(mudança vouluntaria de AP)
- Range de temperatura (32-40°C)--OK
- Nova Temp. máx 40°C --OK
- Corrigir ruido no botão de "reduzir a temperatura" que está mudando de automático para manual
- Ler Estado do Cube pela serial
- Levar dados do fluxômetro para o Copacabana e Gerar Relatório (Thingspeak com exportação xlsx)
- Programa para comandar ThermoCube via resposta do ptc - cateter
- 3 update 29/6/2016: incluir wifi e thingspeak
- wifi tenta conexão anterior. Se falhar entra em modo configuração
- - abre AP chamado TheCube, sem senha
- - serve pagina http em 192.168.4.1
- - na pagina entre com scan ou escolha a rede
- - depois o programa inicia normalmente
- 2 update 28 jun 2016: 3 setpoints por botaõ
- temp esfriar = 0,1 C
- temp default = 10 C
- temp aquecer = 20 C
- calibração coarse para prova de conceito
- pode depender de outras temperaturas, tabelar, criar regressões e correções
- testar mesma correção com diversor chips para repetibilidade
- agora mostra temperatura em Celsuis no lcd
- comandos apenas enviam, mas serial está montada para receber status
- sem campainha
- */
- #include <ESP8266WiFi.h> // lib do ESP8266 para wifi, só necessário quando usa wifi
- #include <SPI.h>
- #include <SmartConnect.h>
- #include <stdlib.h>
- #include <string.h>
- #include "WiFiUdp.h"
- WiFiUDP udp;
- //needed for library WiFiManager
- #include <DNSServer.h>
- #include <ESP8266WebServer.h>
- #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
- #include <SimpleTimer.h> // via interrupção, melhor opção para publicação a cada 16s
- SimpleTimer timer; // inicia instancia com nome "timer" ( podem ser várias instancias)
- #include "ThingSpeak.h" // lib do thingspeak.com
- int status = WL_IDLE_STATUS;
- WiFiClient client;
- unsigned long myChannelNumber = 139811; // canal thingspeak do Cube2
- const char * myWriteAPIKey = "LV2ICZ6QLKBYBEJU"; // api key do Cube2
- const char * myReadAPIKey = "DB7J18KFYYB5VHG9"; // api key do Cube2
- #include <LiquidCrystal_I2C.h>
- LiquidCrystal_I2C lcd(0x27,20,4); // ajusta LCD para endereço 0x27 com 20 caracteres x 4 linhas
- #define ledVermelho 14
- #define ledVerde 12
- #define ledAmarelo 5
- int contador = 0;
- int leitura = 1023;
- int lastLeitura = 0;
- int ptcSetPoint = 300; // temperatura default: mudou durante a programação. FU passar para Celsius
- int candidato = 0;
- int lastValido = 0;
- float cloudSetpoint = 0.0;
- float newC = 0;
- float newDeciF = 0;
- float temperatura = 0.0;
- float SET = 34.0;
- // nome dos tres botoes setpoints:
- const int superior = 321; // 34,5 C ; usar temperatura C aqui dara erro de arredondamento tipico dos floats
- const int medio = 300; // 34,0 C
- const int inferior = 332; // 33,5 C
- boolean pub = true;
- boolean automatico = true;
- int entradaCalibrar = 0;
- float saidaCalibrar = 0.0;
- int resultCode = 0;
- float x = 0.0; // entrada na tabela
- float y = 0.0; // saida da tabela
- boolean bancada = true; // modo bancada, nao precisa sensores, display etc, e aciona serial monitor
- IPAddress ipBroadCast(192, 168, 2, 255);
- unsigned int udpRemotePort=8080;
- unsigned int udplocalPort=8080;
- const int UDP_PACKET_SIZE = 50;
- char udpBuffer[ UDP_PACKET_SIZE];
- //____________________________________________________________________________________________________ smart vars
- //char server[] = "www.smartapps.com.br"; //Endereco Smartapps.
- char server[] = "192.168.0.14"; //Endereco Smartapps.
- // é igual pq o email é igual
- char login[] = "4d2011a4c907452432fea42d7f001e96"; //Login do usuario: Encontra-se na plataforma.
- //char password[] = "WzVUbVNsDzYIYwluVjE="; //Senha do usuário: Encontra-se na plataforma.
- char password[] = "WjYHMlVj";
- char app[] = "controls"; //Nome do aplicativo utilizado.
- 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.
- String postDataVar1 = "variavel=1&valor=";
- String responseData;
- long randNumber;
- //================================================================
- // Function to send udp message
- //================================================================
- void fncUdpSend()
- {
- float t = 1.0; float h = 2.0;
- char buffer[12];
- strcpy(buffer,".......temp");
- //dtostrf(FLOAT, WIDTH,PRECSISION, BUFFER )
- dtostrf(temperatura, 2, 2, buffer );
- udp.beginPacket(ipBroadCast, udpRemotePort);
- udp.write(buffer, sizeof(buffer));
- udp.endPacket();
- delay(1000);
- char buffer2[12];
- strcpy(buffer2,"........SET");
- //dtostrf( FLOAT ,WIDTH, PRECSISION, BUFFER)
- dtostrf( SET, 2, 2, buffer2);
- udp.beginPacket(ipBroadCast, udpRemotePort);
- udp.write(buffer2, sizeof(buffer2));
- udp.endPacket();
- delay(1000);
- }
- //================================================================
- void cloudRetrieve(){
- cloudSetpoint = ThingSpeak.readFloatField(myChannelNumber, 2, myReadAPIKey); // field2 = brain setpoint
- resultCode = ThingSpeak.getLastReadStatus();
- lcd.setCursor(0,3);
- lcd.print(" ");
- lcd.setCursor(0,3);
- lcd.print(resultCode);
- if (bancada){Serial.print("result-code=");Serial.println(resultCode);}
- if(resultCode == 200){
- SET = cloudSetpoint; // ajusta setpoint pela nuvem
- }
- }
- void publish(){
- if (pub == false){return;} // nao publica em certas condições (setup por exemplo)
- // ativado por SimpleTimer em setup, a cada 16s...
- // ThingSpeak will only accept updates every 15 seconds.
- yield(); // solta background tasks
- lcd.setCursor(0,3);
- lcd.print("enviando dados");
- ThingSpeak.setField(1,temperatura); // brain temp
- ThingSpeak.setField(2,SET); // brain setpoint
- ThingSpeak.setField(3,newC); // cube setpoint
- ThingSpeak.setField(4,automatico); // cube auto/manual status
- ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); // Write the fields that you've set all at once.
- yield(); // solta background tasks
- lcd.setCursor(0,3);
- lcd.print(" ");
- cloudRetrieve(); // coleta ultimo dado salvo na nuvem
- }
- void configModeCallback (WiFiManager *myWiFiManager) { // coisas a fazer durante o wifi setup mode
- lcd.setCursor(0,1);
- lcd.print("WiFi Config Mode");
- if (bancada){Serial.println("Wifi Config Mode");}
- //Serial.println("Entered config mode");
- yield(); // solta background tasks
- //Serial.println(WiFi.softAPIP());
- yield(); // solta background tasks
- //Serial.println(myWiFiManager->getConfigPortalSSID());
- }
- //=========================================================================================================================================================
- void setup() { //............................................................................................S E T U P ..................................
- SMART.begin(9600, false);
- // Initiate the i2c connection on esp pins 13 (DAT/SDA) and 0 (CLK/SCL)
- Wire.begin(13,0); // gpio 0 reusado - funcionou no copacabana
- lcd.begin(20, 4);
- lcd.setBacklight(HIGH);
- lcd.print("TheCube2");
- pinMode(4, OUTPUT);
- pinMode(ledAmarelo, OUTPUT);
- pinMode(ledVerde, OUTPUT);
- pinMode(ledVermelho, OUTPUT);
- Serial.begin(9600); // inicializa comunicação com serial monitor a 9600 8n1 cr/lf
- // -------------------------------------configuração WIFI
- //WiFiManager
- //Local intialization. Once its business is done, there is no need to keep it around
- WiFiManager wifiManager;
- wifiManager.setDebugOutput(false); // impede degug pela serial, uso apenas em diagnostico
- if (analogRead(A0)<20){ // boot + qquer tecla = WiFi reset Settings
- wifiManager.resetSettings();
- lcd.clear();
- lcd.setCursor(0,0);
- lcd.print("Reconfigure WiFi ");
- if (bancada){Serial.println("Reconfigura Wifi ");}
- lcd.setCursor(0,1);
- lcd.print("Rede TheCube-2 ");
- lcd.setCursor(0,2);
- lcd.print("pagina 192.168.4.1 ");
- }
- //set custom ip for portal
- //wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
- //fetches ssid and pass from eeprom and tries to connect
- //if it does not connect it starts an access point with the specified name
- //here "AutoConnectAP"
- //and goes into a blocking loop awaiting configuration
- //wifiManager.setConfigPortalTimeout(60); // 1 minuto para conectar o tel no esp, escolher rede e resumir
- // wifiManager.setAPCallback(configModeCallback);
- wifiManager.autoConnect("TheCube-2");
- //or use this for auto generated name ESP + ChipID
- //wifiManager.autoConnect();
- //if you get here you have connected to the WiFi
- //Serial.println("connected...yeey :)");
- lcd.clear();
- lcd.print("TheCube2 conectado!");
- if (bancada){Serial.println("conectado wifi");}
- // Setup a function to be called every second
- timer.setInterval(30000L, publish); // vai postar no thingspeak a cada 16s
- // timer.setInterval(5000L, cloudRetrieve);
- yield(); // solta background tasks
- ThingSpeak.begin(client);
- cloudRetrieve(); // em boot: coleta ultimo Setpoint salvo na nuvem
- //_________________________________________________________________________smart Setup:
- SMART.begin(9600, false);
- // connect on smartapps platform
- if (bancada){Serial.println("Conectando na plataforma Smart");}
- if (SMART.connect(server, login, password, 80)) { if(bancada){Serial.println("Dispositivo autenticado.");} }
- else {if (bancada){Serial.println("Nao autenticado.");} }
- } // ..............................fim de setup........................................................
- // subrotinas..........................................................................................
- void tabela(){ // são 50 equações de reta a interpolar
- float Y[51] = {
- 7.0,
- 19.1,
- 29.2,
- 29.6,
- 29.6,
- 30.0,
- 30.0,
- 30.3,
- 30.3,
- 30.7,
- 30.7,
- 31.0,
- 31.0,
- 31.4,
- 31.4,
- 31.8,
- 31.8,
- 32.1,
- 32.1,
- 32.5,
- 32.5,
- 32.9,
- 32.9,
- 33.3,
- 33.3,
- 33.6,
- 34.0,
- 34.0,
- 34.5,
- 34.9,
- 35.3,
- 35.3,
- 35.8,
- 35.8,
- 36.7,
- 37.1,
- 37.6,
- 38.0,
- 38.0,
- 38.5,
- 38.5,
- 39.1,
- 39.1,
- 39.6,
- 39.6,
- 40.1,
- 40.6,
- 41.5,
- 42.0,
- 42.3,
- //43.7
- };
- float X[51]={
- -10.0,
- 14.7,
- 29.9,
- 30.0,
- 30.3,
- 30.3,
- 30.9,
- 31.0,
- 31.4,
- 31.5,
- 31.7,
- 31.8,
- 32.1,
- 32.2,
- 32.4,
- 32.6,
- 32.8,
- 33.0,
- 33.3,
- 33.4,
- 33.5,
- 33.7,
- 33.9,
- 34.1,
- 34.4,
- 34.6,
- 34.8,
- 34.9,
- 35.6,
- 35.7,
- 36.2,
- 36.5,
- 36.8,
- 36.9,
- 37.7,
- 38.1,
- 38.4,
- 38.6,
- 39.1,
- 39.1,
- 39.4,
- 39.5,
- 39.7,
- 39.9,
- 40.0,
- 40.4,
- 41.0,
- 41.2,
- 41.7,
- 42.2,
- // 42.9
- };
- for (int index = 0; index < 50-1; index++){
- yield();
- if ((x>42)||(x<-9)){y=0;break;} // proteção dos limites
- if((x>X[index])&&(x<X[index+1])){
- // inicio da interpolação no segmento correto
- float x1=X[index];float x2=X[index+1];
- float y1=Y[index];float y2=Y[index+1];
- float dy=y2-y1;float dx=x2-x1;
- float inclinacao=dy/dx;
- float subx=x-x1;
- float suby=dy*subx/dx;
- y=suby+y1+0.5; // devolvi 0,5C por conta dos arredontamentos falhos de floats
- // fim da interpolação
- // Serial.print("leitura atual = "); // impressão para diagnostico
- // Serial.println(x);
- // Serial.print(X[index]);
- // Serial.print(" encontrado..... ");
- // Serial.println(Y[index]);
- // Serial.print(" convertido..... ");
- // Serial.println(y);
- // delay(500);
- break;
- }
- // Serial.print(X[index]);
- // Serial.print(" ");
- // Serial.println(Y[index]);
- // Serial.print("leitura atual = ");
- // Serial.println(x);
- }
- }
- void calibrar(){ // aqui é corrigida a leitura e convertida a graus Celsius
- yield(); // solta background tasks
- // primeira correção
- float temp = ((-8.74126*entradaCalibrar)/100 + 62.5402); // calibração dixtal na planilha google com regressão linear
- // erro até 0,5 C fora do intervado dos 3 setpoints!!!
- // segunda correção, após compilação
- saidaCalibrar =((0.986842*temp) - 1.789473);
- // mais correções até amadurecer o projeto
- // terceira correção, via tabela com 50 vetores usando resultados acima
- x = saidaCalibrar;
- tabela(); // computa na sub tabela
- saidaCalibrar = y; // corrigido pela tabela
- }
- void piscaVerde(){
- digitalWrite(ledVerde, HIGH); // turn the LED on (HIGH is the voltage level)
- delay(10);
- return;
- }
- void piscaVermelho(){
- digitalWrite(ledVermelho, HIGH); // turn the LED on (HIGH is the voltage level)
- delay(10);
- return;
- }
- void piscaAmarelo(){
- digitalWrite(ledAmarelo, HIGH); // turn the LED on (HIGH is the voltage level)
- delay(10);
- digitalWrite(ledAmarelo, LOW); // turn the LED on (HIGH is the voltage level)
- return;
- }
- void pedeParaAquecer(){
- if (automatico == false){return;}
- yield(); // solta background tasks
- // envia protocolo tosco new SetPoint = 36 -- qquer numero seguro acima para fazer subir temperatura
- ////Serial.println("pede para Aquecer++++++++++++++++++++++++++++++++++++");
- lcd.setCursor(0,2);
- lcd.print("comando AQUECER");
- // codigo a seguir imaturo: ideia: mandar aquecer pedindo um grau acima... qquer grau seguro
- // nao pedir demais. se perder comunicação o Cube deve achar um limite seguro
- byte commandByte = 225; // = send new setpoint to cube
- newC = 40.0; // fu. analog read do pot ou ptc
- newDeciF = (newC * 1.8 + 32);
- int newF = (10 * newDeciF);
- byte highF = highByte(newF);
- byte lowF = lowByte(newF);
- // fim do codigo imaturo
- // lcd.setCursor(0,3);
- // lcd.print(" ");
- // lcd.setCursor(0,3);
- // lcd.print(commandByte, HEX); // Print the raw binary value
- // lcd.print(" ");
- // lcd.print(lowF, HEX); // Print the raw binary value
- // lcd.print(" ");
- // lcd.print(highF, HEX); // Print the raw binary value
- // payload para ThermoCube:
- Serial.write(commandByte); // Print the raw binary value
- Serial.write(lowF); // Print the raw binary value
- Serial.write(highF); // Print the raw binary value
- delay(100);
- return;
- }
- void pedeParaEsfriar(){
- if (automatico == false){return;}
- yield(); // solta background tasks
- // envia protocolo tosco new SetPoint = 33 -- qquer numero seguro abaixo para fazer baixar temperatura
- ////Serial.println("pede para Esfriar -----------------------------------");
- lcd.setCursor(0,2);
- lcd.print("comando ESFRIAR");
- // codigo a seguir imaturo: ideia: mandar esfriar pedindo um grau abaixo... qquer grau seguro
- // nao pedir demais. se perder comunicação o Cube deve achar um limite seguro
- byte commandByte = 225; // = send new setpoint to cube
- newC = 0.1; // Bernardo pediu zero, coloquei 0.1C para evitar erros de calculo
- newDeciF = (newC * 1.8 + 32);
- int newF = (10 * newDeciF);
- byte highF = highByte(newF);
- byte lowF = lowByte(newF);
- // fim do codigo imaturo
- // lcd.setCursor(0,3);
- // lcd.print(" ");
- // lcd.setCursor(0,3);
- // lcd.print(commandByte, HEX); // Print the raw binary value
- // lcd.print(" ");
- // lcd.print(lowF, HEX); // Print the raw binary value
- // lcd.print(" ");
- // lcd.print(highF, HEX); // Print the raw binary value
- // payload para ThermoCube:
- Serial.write(commandByte); // Print the raw binary value
- Serial.write(lowF); // Print the raw binary value
- Serial.write(highF); // Print the raw binary value
- delay(100);
- return;
- }
- void pedeDefault(){ // se estiver na temperatura ou houver ruido, pede 35,5 C ao Cube
- if (automatico == false){return;}
- // envia protocolo tosco new SetPoint = 33 -- qquer numero seguro abaixo para fazer baixar temperatura
- yield(); // solta background tasks
- lcd.setCursor(0,2);
- lcd.print("comando DEFAULT");
- // codigo a seguir imaturo: ideia: mandar centrar em 10 graus
- // significa esfriar menos, reduzindo a diferença de temperaturas
- // nos estudos o esfriamento usou quase zero grau... aqui sobe um pouco... 10 inicialmente
- byte commandByte = 225; // = send new setpoint to cube
- newC = 10.0; // fu. analog read do pot ou ptc
- newDeciF = (newC * 1.8 + 32);
- int newF = (10 * newDeciF);
- byte highF = highByte(newF);
- byte lowF = lowByte(newF);
- // fim do codigo imaturo
- // lcd.setCursor(0,3);
- // lcd.print(" ");
- // lcd.setCursor(0,3);
- // lcd.print(commandByte, HEX); // Print the raw binary value
- // lcd.print(" ");
- // lcd.print(lowF, HEX); // Print the raw binary value
- // lcd.print(" ");
- // lcd.print(highF, HEX); // Print the raw binary value
- // payload para ThermoCube:
- Serial.write(commandByte); // Print the raw binary value
- Serial.write(lowF); // Print the raw binary value
- Serial.write(highF); // Print the raw binary value
- delay(100);
- return;
- }
- //..............................................................L O O P ..............................
- void loop() {
- // retirar a seguir: só para teste de compilação
- // esse loop de envio deve respeitar os outros e ser ativado pelo timer!!!!!!!!!!!!!!!1
- if (SMART.connected()) {
- Serial.println("Enviando dados dados...");
- String stringPostData = "";
- stringPostData.concat(postDataVar1);
- randNumber = random(30);
- stringPostData.concat(randNumber);
- char arrayPostData[20];
- stringPostData.toCharArray(arrayPostData, 20);
- responseData = SMART.exec("POST","csv", app, schema, "variaveis_valores/insert", arrayPostData);
- Serial.println(responseData);
- } else {
- Serial.println("Dispositivo desconectado!");
- }
- delay(1000);
- yield(); // solta background tasks
- timer.run(); // Initiates SimpleTimer
- lastLeitura = leitura; // atualiza leitura validada n vezes
- leitura = (analogRead(A0));
- if (bancada){leitura = 512;} // Fixa meia escala para bancada...............................................
- if(leitura < 100) { goto pulo1;} // salta para setpoint... melhorar para subrotina!!!!
- entradaCalibrar = leitura; // entra a leitura...
- calibrar(); // tabela e converte para celsius
- temperatura = saidaCalibrar; // ... e volta a temperatura calibrada
- fncUdpSend(); // publica UDP
- // impressão serial de diagnóstico --- comentar apos aprovação
- // Serial.print("leit=");
- // Serial.println(leitura);
- // yield(); // solta background tasks
- //Serial.print(" temp = ");
- //Serial.print(temperatura);
- //yield(); // solta background tasks
- //Serial.print(" SET = ");
- //Serial.print(SET);
- //yield(); // solta background tasks
- //Serial.print(" cont =");//Serial.println(contador);
- //Serial.println(temperatura, 1);
- if (automatico == true){ lcd.setCursor(0 ,0); lcd.print("Auto "); if (bancada){Serial.println("modo automatico");} }
- if (automatico == false){ lcd.setCursor(0 ,0); lcd.print("Manual ");
- if (bancada){Serial.println("modo manual");}
- lcd.setBacklight(LOW); delay(50); lcd.setBacklight(HIGH);}
- lcd.setCursor(11,1);
- lcd.print("inst ");
- yield(); // solta background tasks
- lcd.setCursor(16,1);
- lcd.print(" ");
- lcd.setCursor(16,1);
- lcd.print(temperatura,1);
- yield(); // solta background tasks
- piscaAmarelo();
- delay(300);
- if (bancada){Serial.print("instantaneo = "); Serial.println(temperatura,1);}
- // confirmador de leitura, para evitar ruidos... n leituras iguais valida
- if (leitura == lastLeitura){contador = contador + 1; piscaAmarelo();} // acumula leituras validas até n
- if(contador == 2) { // (baixei para n=2 confirmações) só executa os proximos comandos se validou um dado sem ruido
- yield(); // solta background tasks
- contador = 0;
- ////Serial.println("n leituras ");
- lcd.setCursor(9,0);
- lcd.print("valido ");
- lcd.setCursor(16,0);
- lcd.print(" ");
- lcd.setCursor(16,0);
- lcd.print(temperatura,1);
- pub = true; // habilita publicação no thingspeak
- if (bancada){Serial.print("valido = "); Serial.println(temperatura,1);}
- // falta de sonda.............nem publica pq fica em loop, mas pede default ao cube
- while (leitura > 1000){
- yield(); // solta background tasks
- lcd.setBacklight(LOW);
- delay(300);
- lcd.setBacklight(HIGH);
- lcd.setCursor(12,3);
- lcd.print("sonda ?");
- delay(1000);
- lcd.clear();
- lcd.print("TheCube2");
- pedeDefault();
- leitura = (analogRead(A0)); // leitura para ver se saiu do erro
- }
- // controle automatico do cube;
- if (temperatura < SET){ // se esfriou, avisa e pede para esquentar
- // led verde avisa que esta mais frio que o setpoint
- digitalWrite(ledVermelho, HIGH);
- digitalWrite(ledVerde, LOW);
- pedeParaAquecer();
- }
- if (temperatura > SET){ // se esquentou, avisa e pede para esfriar
- digitalWrite(ledVermelho, LOW);
- digitalWrite(ledVerde, HIGH);
- pedeParaEsfriar();
- }
- if (temperatura == SET){ // se está no ponto, peça default C ... com floats esse ponto nem existe!
- digitalWrite(ledVermelho, LOW);
- digitalWrite(ledVerde, LOW);
- pedeDefault();
- }
- // ,,,,,,,,,,,,,,,,,,,,,, ajuste dos Setpoints .....................................................
- /* upgrade para resistores de 100ohm ( down = 0 ohm, mid = 100ohm, up = 200ohm)
- * leituras............................... 0 17-18 34-38
- * tresholds........................................14......... .30..........62
- *
- */
- pulo1:
- yield(); // solta background tasks
- if(leitura < 62) { // qquer botão pressionado é lido como <20...
- pub = false;
- if ((leitura < 62) && (leitura > 30) && (SET < 40)) { // regiao do botao superior, que da leitura 34 a 38, set impede subir mais
- // ptcSetPoint = superior; // 0 a 1024 nao convertido F.U usar graus
- ptcSetPoint = ptcSetPoint - 1; // ainda estamos antes da conversão
- entradaCalibrar = ptcSetPoint;
- calibrar(); // converter para Celsius para mostrar no campo SET
- SET = saidaCalibrar; // nova temperatura ja convertida, para mostrar no LCD
- }
- yield(); // solta background tasks
- if ((leitura < 29) && (leitura > 14)){ // região do botao medio, que da leitura 17 a 18
- if (automatico == true){
- automatico = false;
- lcd.clear();
- lcd.setCursor(0,3);
- lcd.print("Modo Manual ");
- //Serial.println("mudando para manual");
- lcd.setCursor(0,0);
- lcd.print("raw= ");
- lcd.print(leitura);
- delay(3000);
- }
- else {
- automatico = true;
- lcd.setCursor(0,3);
- lcd.print("Modo Automatico ");
- lcd.setCursor(0,0);
- lcd.print("raw= ");
- lcd.print(leitura);
- //Serial.println("mudando para automatico");
- delay(3000);
- }
- }
- yield(); // solta background tasks
- if ((leitura < 14)&&(SET > 32)) { // região do botao inferior, que da leitura 0, set impede descer mais
- ptcSetPoint = ptcSetPoint + 1; // ainda estamos antes da conversão
- entradaCalibrar = ptcSetPoint; // emprestimo da variavel leitura para reuso da sub calibrar()
- calibrar(); // converter para Celsius para mostrar no campo SET
- SET = saidaCalibrar; // de novo, emprestimo da variavel temperatura para reuso de calibrar()
- }
- digitalWrite(ledVermelho, HIGH);
- digitalWrite(ledVerde, HIGH);
- lcd.setCursor(0,3);
- lcd.print("New SetPoint = ");
- lcd.setCursor(16,3);
- lcd.print(" ");
- lcd.setCursor(16,3);
- lcd.print(SET,1);
- lcd.setCursor(0,0);
- lcd.print("raw= ");
- lcd.print(leitura);
- delay(100); // aumenta ou diminui velocidade de mudança do setpoint
- lcd.clear();
- } // fim de setPoints
- lcd.setCursor(0,1);
- lcd.print("SET ");
- lcd.setCursor(4,1);
- lcd.print(SET,1);
- } // fim de if contador = 2 ( leitura valida)
- } // fim de loop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement