# Estou com problema com um codigo

**URL:** https://forum.fazedores.com/t/estou-com-problema-com-um-codigo/9783
**Category:** Arduino
**Created:** [Novembro 10, 2024, 10:38pm UTC](https://forum.fazedores.com/t/estou-com-problema-com-um-codigo/9783 "2024-11-10T22:38:24Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![Warley](https://avatars.discourse-cdn.com/v4/letter/w/4da419/32.png) [@Warley](https://forum.fazedores.com/u/Warley)
#### Post date: [Novembro 10, 2024, 10:38pm UTC](https://forum.fazedores.com/t/estou-com-problema-com-um-codigo/9783/1 "2024-11-10T22:38:24Z")

</div>

"Boa noite. Estou desenvolvendo um código para criar uma estação de evapotranspiração. Embora não haja erros no código, ele não está funcionando conforme esperado.  
"A data não está iniciando corretamente, o que impede a execução do `if` de calculos do código. Além disso, embora o SD card indique que está funcionando perfeitamente, os dados não conseguem ser gravados.  
meu código

#include \<OneWire.h\> // Temperatura  
#include \<DallasTemperature.h\>  
#include \<LiquidCrystal\_I2C.h\> // LCD  
#include \<SD.h\> // SD  
#include \<SoftwareSerial.h\>  
#include \<Wire.h\> // Data  
#include \<RTClib.h\>  
#include \<avr/wdt.h\> // Reset  
#include \<EEPROM.h\> // Salva latitude

// Configurações de Temperatura  
#define ONE\_WIRE\_BUS 2  
OneWire oneWire(ONE\_WIRE\_BUS);  
DallasTemperature sensors(&oneWire);

float tempMax = -127.0;  
float tempMin = 127.0;  
unsigned long lastReadingTime = 0;  
//const unsigned long readingInterval = 1000;  
const unsigned long readingInterval = 24000; //Intervalo de 24 segundos (para 150 leituras por hora)  
const int totalReadingsPerHour = 150;  
float tempTotal = 0.0;  
int readingsCount = 0;  
float tempMed = 0.0;

// LCD  
LiquidCrystal\_I2C lcd(0x27, 16, 2);

// Cartão SD  
const int chipSelect = 10;  
File arquivo;

// Bluetooth  
SoftwareSerial bluetooth(3, 5);

// Latitude  
int latitude = 0;  
bool latitudeConfirmed = false;  
const int LATITUDE\_ADDRESS = 0;

// Data  
RTC\_DS3231 rtc;  
char daysOfTheWeek[7][12] = {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”};

// Tabela de Ra (radiação solar) para latitudes de 0 a 70  
const float Ra[36][12] PROGMEM = { /\* valores da tabela Ra \*/  
{14.5, 15.0, 15.2, 14.7, 13.9, 13.4, 13.5, 14.2, 14.9, 14.9, 14.6, 14.3}, //Latitude 0  
{14.8, 15.2, 15.2, 14.5, 13.6, 13.0, 13.2, 14.0, 14.8, 15.0, 14.8, 14.6}, //Latitude 2  
{15.0, 15.3, 15.1, 14.3, 13.3, 12.7, 12.8, 13.7, 14.7, 15.1, 15.0, 14.9}, //Latitude 4  
{15.3, 15.4, 15.1, 14.1, 13.0, 12.6, 12.5, 13.5, 14.6, 15.1, 15.2, 15.1}, //Latitude 6  
{15.6, 15.6, 15.0, 14.0, 12.7, 12.0, 12.2, 13.2, 14.5, 15.2, 15.4, 15.4}, //Latitude 8  
{15.9, 15.7, 15.0, 13.8, 12.4, 11.6, 11.9, 13.0, 14.4, 15.3, 15.7, 15.7}, //Latitude 10  
{16.1, 15.8, 14.9, 13.5, 12.0, 11.2, 11.5, 12.7, 14.2, 15.3, 15.8, 16.0}, //Latitude 12  
{16.3, 15.8, 14.9, 13.2, 11.6, 10.8, 11.1, 12.4, 14.0, 15.3, 15.9, 16.2}, //Latitude 14  
{16.5, 15.9, 14.8, 13.0, 11.3, 10.4, 10.8, 12.1, 13.8, 15.3, 16.1, 16.4}, //Latitude 16  
{16.7, 15.9, 14.7, 12.7, 10.9, 10.0, 10.4, 11.8, 13.7, 15.3, 16.2, 16.6}, //Latitude 18  
{16.7, 16.0, 14.5, 12.4, 10.6, 9.6, 10.0, 11.5, 13.5, 15.3, 16.4, 16.8}, //Latitude 20  
{16.9, 16.0, 14.3, 12.0, 10.2, 9.1, 9.6, 11.1, 13.1, 15.2, 16.5, 17.0}, //Latitude 22  
{16.9, 15.9, 14.1, 11.7, 9.8, 8.6, 9.1, 10.7, 13.1, 15.1, 16.5, 17.1}, //Latitude 24  
{17.0, 15.9, 13.9, 11.4, 9.4, 8.1, 8.7, 10.4, 12.8, 15.0, 16.6, 17.3}, //Latitude 26  
{17.1, 15.8, 13.7, 11.1, 9.0, 7.8, 8.3, 10.0, 12.6, 14.9, 16.6, 17.5}, //Latitude 28  
{17.2, 15.7, 13.5, 10.8, 8.5, 7.4, 7.8, 9.6, 12.2, 14.7, 16.7, 17.6}, //Latitude 30  
{17.2, 15.6, 13.3, 10.5, 8.1, 7.0, 7.4, 9.2, 11.9, 14.6, 16.7, 17.6}, //Latitude 32  
{17.2, 15.5, 13.0, 10.1, 7.6, 6.6, 7.0, 8.8, 11.6, 14.4, 16.7, 17.6}, //Latitude 34  
{17.3, 15.4, 12.7, 9.7, 7.2, 6.1, 6.5, 8.3, 11.3, 14.3, 16.6, 17.7}, //Latitude 36  
{17.3, 15.2, 12.4, 9.3, 6.7, 5.6, 6.0, 7.9, 11.0, 14.1, 16.6, 17.7}, //Latitude 38  
{17.3, 15.1, 12.1, 8.9, 6.3, 5.1, 5.5, 7.5, 10.6, 13.9, 16.5, 17.8}, //Latitude 40  
{17.2, 14.9, 11.7, 8.4, 5.9, 4.6, 5.1, 7.1, 10.2, 13.7, 16.4, 17.8}, //Latitude 42  
{17.2, 14.7, 11.4, 8.0, 5.5, 4.2, 4.7, 6.7, 9.8, 13.4, 16.3, 17.8}, //Latitude 44  
{17.1, 14.5, 11.0, 7.5, 5.0, 3.8, 4.2, 6.2, 9.4, 13.1, 16.2, 17.8}, //Latitude 46  
{17.0, 14.3, 10.6, 7.0, 4.5, 3.3, 3.7, 5.7, 9.0, 12.8, 16.1, 17.8}, //Latitude 48  
{16.9, 14.1, 10.3, 6.6, 4.0, 2.8, 3.2, 5.3, 8.7, 12.5, 15.9, 17.8}, //Latitude 50  
{16.8, 13.8, 9.9, 6.1, 3.5, 2.4, 2.8, 4.9, 8.2, 12.2, 15.7, 17.7}, //Latitude 52  
{16.7, 13.5, 9.5, 5.7, 3.0, 2.0, 2.4, 4.5, 7.8, 11.8, 15.5, 17.7}, //Latitude 54  
{16.6, 13.2, 9.0, 5.2, 2.5, 1.6, 2.0, 4.0, 7.3, 11.4, 15.4, 17.6}, //Latitude 56  
{16.5, 12.9, 8.6, 4.7, 2.1, 1.2, 1.6, 3.5, 6.9, 11.1, 15.2, 17.6}, //Latitude 58  
{16.4, 12.7, 8.2, 4.2, 1.7, 0.8, 1.1, 3.0, 6.4, 10.8, 15.1, 17.5}, //Latitude 60  
{16.4, 12.4, 7.7, 3.7, 1.4, 0.6, 0.9, 2.5, 5.9, 10.4, 15.0, 17.6}, //Latitude 62  
{16.4, 12.1, 7.2, 3.2, 1.0, 0.4, 0.7, 2.1, 5.4, 10.0, 14.9, 17.7}, //Latitude 64  
{16.4, 11.8, 6.7, 2.8, 0.6, 0.3, 0.5, 1.6, 4.9, 9.8, 14.8, 17.8}, //Latitude 66  
{16.4, 11.5, 6.2, 2.4, 0.3, 0.1, 0.3, 1.2, 4.4, 9.4, 14.6, 17.9}, //Latitude 68  
{16.4, 11.2, 5.9, 2.0, 0.1, 0.0, 0.0, 0.8, 4.0, 9.0, 14.5, 18.1} //Latitude 70  
};

float getRa(int month, int latitude) {  
int latIndex = latitude / 2;  
return pgm\_read\_float(&(Ra[latIndex][month - 1]));  
}

void setup() {  
Wire.begin();  
Serial.begin(9600);  
bluetooth.begin(9600);  
sensors.begin();

// Inicialização do LCD  
lcd.init();  
lcd.backlight();  
lcd.setCursor(3, 0);  
lcd.print(“BEM VINDO!”);  
lcd.setCursor(1, 1);  
lcd.print(“Estacao de ETo”);  
delay(5000);  
lcd.clear();

// Carrega latitude salva  
latitude = EEPROM.read(LATITUDE\_ADDRESS);  
if (latitude == 255) {  
latitude = 0;  
latitudeConfirmed = false;  
} else {  
latitudeConfirmed = true;  
lcd.clear();  
lcd.setCursor(2, 0);  
lcd.print(“Latitude ok!”);  
delay(2500);  
lcd.clear();  
}

// Inicialização do Cartão SD  
if (!SD.begin(chipSelect)) {  
Serial.println(“Erro ao iniciar cartao SD!”);  
lcd.print(“ERRO CARTAO SD”);  
delay(5000);  
lcd.clear();  
return;  
}  
Serial.println(“Cartao SD funcionando perfeitamente!”);  
lcd.print(“CARTAO SD OK!!”);  
delay(5000);  
lcd.clear();

// Inicialização do RTC  
if (!rtc.begin()) {  
lcd.print(“Erro no RTC”);  
Serial.println(“Nao foi possível iniciar data”);  
while (1); // trava o código caso o RTC não seja encontrado  
}

// Sincroniza o RTC com o horário atual (apenas uma vez)  
[//rtc.adjust](https://rtc.adjust)(DateTime(F( **DATE** ), F( **TIME** ))); // Use essa linha se precisar ajustar a hora

displayLatitude();  
}

void loop() {  
unsigned long currentMillis = millis();

if (!latitudeConfirmed) {  
if (bluetooth.available()) {  
char command = bluetooth.read();  
if (command == ‘U’) {  
latitude = min(latitude + 2, 70);  
displayLatitude();  
} else if (command == ‘D’) {  
latitude = max(latitude - 2, 0);  
displayLatitude();  
} else if (command == ‘C’) {  
latitudeConfirmed = true;  
EEPROM.write(LATITUDE\_ADDRESS, latitude);  
lcd.clear();  
lcd.setCursor(2, 0);  
lcd.print(“Latitude ok!”);  
delay(2500);  
lcd.clear();  
}  
}  
} else {  
if (currentMillis - lastReadingTime \>= readingInterval) {  
lastReadingTime = currentMillis;

```
  sensors.requestTemperatures();
  float tempAtual = sensors.getTempCByIndex(0);

  if (tempAtual != DEVICE_DISCONNECTED_C && tempAtual != -127.0 && tempAtual >= -50 && tempAtual <= 50) {
    tempMax = max(tempMax, tempAtual);
    tempMin = min(tempMin, tempAtual);
    tempTotal += tempAtual;
    readingsCount++;

    if (readingsCount >= totalReadingsPerHour) {
      tempMed = tempTotal / readingsCount;
      tempTotal = 0.0;
      readingsCount = 0;
    }
  }

  DateTime now = rtc.now();
  
  //if (now.minute() == 1 && now.second() == 00) { 
  if (now.hour() == 23 && now.minute() == 59 && now.second() == 59){
    float Ra_value = pgm_read_float(&(Ra[latitude / 2][now.month() -1]));                               
    float etoSensor = 0.0023 * Ra_value * (tempMed + 17.8) * sqrt(tempMax - tempMin);
    float etoCal = 0.0023 * Ra_value * (((tempMax+tempMin)/2) + 17.8) * sqrt(tempMax - tempMin);
    saveTemperatureToSD(getData(now), getHora(now), tempMax, tempMin, tempMed, etoSensor, etoCal);

    Serial.println();
    Serial.print("Data/Hora: ");
    Serial.print(getData(now));
    Serial.print(" / ");
    Serial.print(getHora(now));
    Serial.print(", Tmax: ");
    Serial.print(tempMax);
    Serial.print(" C, Tmin: ");
    Serial.print(tempMin);
    Serial.print(" C, Tmed: ");
    Serial.print(tempMed);
    Serial.print(" C, ETo sensor:");
    Serial.print(etoSensor);
    Serial.print(" mm, ETo calculado:");
    Serial.print(etoCal);
    Serial.print(" mm.");

    tempMax = -127.0;
    tempMin = 127.0;
    tempTotal = 0.0;
    readingsCount = 0;
  }

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(getData(now));
  lcd.setCursor(2, 1);
  lcd.print("Temp:");
  lcd.print(tempAtual);
  lcd.print("'C");
  lcd.setCursor(10, 0);
  lcd.print("LAT:");
  lcd.print(latitude);      
}  
ligaDesliga();

```

}  
}

void displayLatitude() {  
lcd.clear();  
lcd.setCursor(3, 0);  
lcd.print(“QUAL A SUA”);  
lcd.setCursor(0, 1);  
lcd.print(“LATITUDE?”);  
lcd.setCursor(10, 1);  
lcd.print(latitude);  
}

void ligaDesliga() {  
if (bluetooth.available()) {  
char command = bluetooth.read();  
if (command == ‘Q’) {  
lcd.backlight();  
bluetooth.println(“Backlight ON”);  
} else if (command == ‘T’) {  
lcd.noBacklight();  
bluetooth.println(“Backlight OFF”);  
} else if (command == ‘R’) {  
bluetooth.println(“Reiniciando o equipamento…”);  
delay(500);  
resetSystem();  
}  
}  
}

void resetSystem() {  
EEPROM.write(LATITUDE\_ADDRESS, 255);  
wdt\_enable(WDTO\_15MS);  
while (true) {}  
}

// Função para formatar a data como String  
String getData(DateTime now) {  
String data = “”;  
if (now.day() \< 10) data += “0”; // Adiciona zero à esquerda, se necessário  
data += String(now.day()) + “/”;  
if (now.month() \< 10) data += “0”;  
data += String(now.month()) + “/”;  
data += String(now.year());  
return data;  
}

// Função para formatar a hora como String  
String getHora(DateTime now) {  
String hora = “”;  
if (now.hour() \< 10) hora += “0”; // Adiciona zero à esquerda, se necessário  
hora += String(now.hour()) + “:”;  
if (now.minute() \< 10) hora += “0”;  
hora += String(now.minute()) + “:”;  
if (now.second() \< 10) hora += “0”;  
hora += String(now.second());  
return hora;  
}

void saveTemperatureToSD(String data, String hora, float tempMax, float tempMin, float tempMed, float etoSensor, float etoCal) {  
if (arquivo){  
(SD.begin(chipSelect));  
arquivo = SD.open(“dados.txt”, FILE\_WRITE);  
if (arquivo) {  
arquivo.println();  
arquivo.print(“Data/Hora: “);  
arquivo.print(data);  
arquivo.print(” / “);  
arquivo.print(hora);  
arquivo.print(”,”);  
arquivo.print(tempMax);  
arquivo.print(“,”);  
arquivo.print(tempMin);  
arquivo.print(“,”);  
arquivo.print(tempMed);  
arquivo.print(“,”);  
arquivo.print(etoSensor);  
arquivo.print(“,”);  
arquivo.print(etoCal);  
arquivo.println();  
arquivo.close();  
Serial.print(" Dados gravados corretamente.“);  
} else {  
Serial.println(” Erro ao abrir o arquivo no SD.“);  
}  
} else {  
Serial.println(” SD Card não inicializado.");  
}  
}
