Working with two codes at the same time

I found two codes that give me the information I need to assemble a mini datalogger but I'm having trouble getting the two to work together. One of the codes works with an RTC DS3231 and provides the day and date of data collection and the other code collects the temperature and humidity through a DHT 22 and saves the information on an SD card. Can anyone make the DHT data be saved with the day and time of collection?
Below are the two codes I used.

//biblioteca responsável pela comunicação com o Cartão SD
#include <SD.h>
//biblioteca responsável pela comunicação com o sensor DHT22
#include <DHT.h>

#define DHTPIN D2     // pino de dados do DHT será ligado no D6 do esp
#define DHTTYPE DHT22   // tipo do sensor

// construtor do objeto para comunicar com o sensor
DHT dht(DHTPIN, DHTTYPE);
 
//pino ligado ao CS do módulo SD Card
#define CS_PIN  D8
 
void setup()
{
  Serial.begin(9600);
  Serial.print("Inicializando o cartão SD...");

  //inicializa o objeto para comunicarmos com o sensor DHT
  dht.begin();
  
  // verifica se o cartão SD está presente e se pode ser inicializado
  if (!SD.begin(CS_PIN)) {
    Serial.println("Falha, verifique se o cartão está presente.");
    //programa encerrrado
    return;
  }
  
  //se chegou aqui é porque o cartão foi inicializado corretamente  
  Serial.println("Cartão inicializado.");
 
}
 
void loop()
{
  //faz a leitura da umidade
  float umidade = dht.readHumidity();
  Serial.print("Umidade: ");
  Serial.println(umidade);
  //faz a leitura da temperatura
  float temperatura = dht.readTemperature();
  Serial.print("Temperatura: ");
  Serial.println(temperatura);

  File dataFile = SD.open("LOG.txt", FILE_WRITE);
  // se o arquivo foi aberto corretamente, escreve os dados nele
  if (dataFile) {
    Serial.println("O arquivo foi aberto com sucesso.");
      //formatação no arquivo: linha a linha >> UMIDADE | TEMPERATURA
      dataFile.print(umidade);
      dataFile.print(" | ");
      dataFile.println(temperatura);

      //fecha o arquivo após usá-lo
      dataFile.close();
  }
  // se o arquivo não pôde ser aberto os dados não serão gravados.
  else {
    Serial.println("Falha ao abrir o arquivo LOG.txt");
  }

  //intervalo de espera para uma nova leitura dos dados.
  delay(2000);

}

#include <Wire.h> 
#include <RtcDS3231.h>

RtcDS3231<TwoWire> Rtc(Wire);

void setup() 
{
  Serial.begin(115200); 
  Rtc.Begin();      
  
  RtcDateTime tempoatual = RtcDateTime(__DATE__,__TIME__); 
  Rtc.SetDateTime(tempoatual);                      
}

void loop() 
{
   RtcDateTime instante = Rtc.GetDateTime();    
   char valores[20];   
 
   sprintf(valores, "%d/%d/%d %d:%d:%d",     
          instante.Year(),   
          instante.Month(),  
          instante.Day(),    
          instante.Hour(),   
          instante.Minute(),
          instante.Second()  
         );
         
   Serial.println(valores);
   delay(20000); 
}

The two setup() functions appear to have no conflicts, they can be combined as one after you settle on a baud rate (and use just once Serial.begin()).

The two loop() functions also appear to be independent, at a glance through the small window anyway.

One loop uses delay() to do something every 2 seconds, the other every 20 seconds.

You could use the "blink without delay" paradigm you can google up, and have the guts of the two loops independently firing at the desired rate.

Or you could hack it and still using delay just do the slow thing every Nth time you've done the fast thing.

Probably.

a7

A tutorial on merging codes.

Watch out for pin conflicts.

What Arduino board are you using?

Give it a try and if you have trouble post the code, a description of what the code actually does and how that differs from what you want.

When I join the two code and observe through the serial monitor the information appears like this.

image

As for the delay, it has to be the same on both because I would like to get both results together.

I'm going to take a look at the tutorial you recommended, and I'm using a nodeMCU board.

So… is that output correct? Writing OK to the SD card? I can't tell if you are trying to say it is not working.

If you want to do the two things at the same rate just use one delay call with the appropriate number.

Please post you combo code.

a7

I managed to join the codes but it is not giving the expected result, The code looks like this.

//biblioteca responsável pela comunicação com o Cartão SD
#include <SD.h>
//biblioteca responsável pela comunicação com o sensor DHT22
#include <DHT.h>
#include <MyRealTimeClock.h>

#define DHTPIN D4     // pino de dados do DHT será ligado no D6 do esp
#define DHTTYPE DHT22   // tipo do sensor

// construtor do objeto para comunicar com o sensor
DHT dht(DHTPIN, DHTTYPE);
 
//pino ligado ao CS do módulo SD Card
#define CS_PIN  D8

MyRealTimeClock myRTC(5,4,0); // Assign Digital Pins
 
void setup()
{
  Serial.begin(9600);  
  Serial.print("Inicializando o cartão SD...");

  //inicializa o objeto para comunicarmos com o sensor DHT
  dht.begin();
  
  // verifica se o cartão SD está presente e se pode ser inicializado
  if (!SD.begin(CS_PIN)) {
    Serial.println("Falha, verifique se o cartão está presente.");
    //programa encerrrado
    return;
  }
  myRTC.setDS1302Time(00, 40, 18, 01, 14, 11, 2022);
  
  //se chegou aqui é porque o cartão foi inicializado corretamente  
  Serial.println("Cartão inicializado.");
 
}
 
void loop()
{
  //faz a leitura da umidade
  float umidade = dht.readHumidity();
  Serial.print("Umidade: ");
  Serial.println(umidade);
  //faz a leitura da temperatura
  float temperatura = dht.readTemperature();
  Serial.print("Temperatura: ");
  Serial.println(temperatura);

  File dataFile = SD.open("LOG.txt", FILE_WRITE);
  // se o arquivo foi aberto corretamente, escreve os dados nele
  if (dataFile) {
    Serial.println("O arquivo foi aberto com sucesso.");
      //formatação no arquivo: linha a linha >> UMIDADE | TEMPERATURA
      dataFile.print(umidade);
      dataFile.print(" ; ");
      dataFile.println(temperatura);
      dataFile.print(" ; ");
      myRTC.updateTime();
 
Serial.print("Current Date / Time: ");
Serial.print(myRTC.dayofmonth); // Element 1
Serial.print("/");
Serial.print(myRTC.month); // Element 2
Serial.print("/");
Serial.print(myRTC.year); // Element 3
Serial.print(" ");
Serial.print(myRTC.hours); // Element 4
Serial.print(":");
Serial.print(myRTC.minutes); // Element 5
Serial.print(":");
Serial.println(myRTC.seconds); // Element 6

      //fecha o arquivo após usá-lo
      dataFile.close();
  }
  // se o arquivo não pôde ser aberto os dados não serão gravados.
  else {
    Serial.println("Falha ao abrir o arquivo LOG.txt");
  }

  //intervalo de espera para uma nova leitura dos dados.
  delay(2000);

}

I wanted the data written on the card to look like this but with the day of data collection too.

But when I look at the serial monitor it appears like this.
image

The SD card only saves the temperature and humidity and I'm not able to solve the problem.

You get the time, but never write it to the SD card.

A NodeMCU can get time off the internet, with daylight savings correction , and keeps perfect time between NTP updates. It also has built-in 4Mb flash that is enough to store data with timestamps for months. And that can be retrieved wireless with another WiFi device (PC/phone).
I don't see the need for a RTC or SD card.
Google "A beginner's guide to the ESP8266" to see how that can be done.
Leo..

I don't know how to write on SD card

All of those dataFile.print lines are writing to the SD card. Time to Google for Arduino SD library tutorials.