# Weather Station Data logger

**URL:** <https://forum.arduino.cc/t/weather-station-data-logger/1180421>\
**Category:** Programming\
**Created:** [October 20, 2023, 3:24pm UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421 "2023-10-20T15:24:01Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![all\_practically](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/all_practically/32/1008927_2.png) [@all\_practically](https://forum.arduino.cc/u/all_practically)\
**Post date:** [October 20, 2023, 3:24pm UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/1 "2023-10-20T15:24:01Z")

</div>

```arduino
#include <SFE_BMP180.h>
#include <MechaQMC5883.h>
#include "DHT.h"
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"
#include <SPI.h>

SFE_BMP180 pressure;
float temperature;

#define ALTITUDE 241.05 // Altitude at my location

#define DHTPIN 2 // what pin we're connected DHT11 to
#define DHTTYPE DHT11   
DHT dht(DHTPIN, DHTTYPE);

#define LOG_INTERVAL 1000 // mills between entries (reduce to take more/faster data)
      
#define SYNC_INTERVAL 10000 // mills between calls to flush() - to write data to the card
uint32_t syncTime = 0; // time of last sync()
#define ECHO_TO_SERIAL 1 // Echo data to serial monitor (Setting it to 0 will turn it off)
#define WAIT_TO_START 0 // Wait for serial input in setup() (Setting it to 1 you have to send a character to the Arduino´s Serial port to start the logging)
      
#define redLEDpin 4 // the digital pins that connect to the LEDs (green and red)
#define greenLEDpin 3
      
#define windSpeedPin A0 // The analog pin connected to the Anemometer voltage divider

#define rainPin A3
int rainset=145;

MechaQMC5883 qmc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
RTC_DS1307 RTC; // define the Real Time Clock object
     
const int chipSelect = 10; // for the data logging shield, we use digital pin 10 for the SD cs line
        
File logfile; // the logging file  

void setup(void)
{
 Serial.begin(57600);
 Serial.println();
pinMode(rainPin,INPUT);
      // use debugging LEDs
 pinMode(redLEDpin, OUTPUT);
 pinMode(greenLEDpin, OUTPUT);

#if WAIT_TO_START
 Serial.println("Type any character to start");
 while (!Serial.available());
#endif //WAIT_TO_START
      // initialize the SD card
 Serial.print("Initializing SD card...");
        // make sure that the default chip select pin is set to
        // output, even if you don't use it:
 pinMode(10, OUTPUT);

 // see if the card is present and can be initialized:
 if (!SD.begin(chipSelect)) 
 {
 error("Card failed, or not present");
 }
 Serial.println("card initialized.");

 // create a new file
 char filename[] = "LOGR000.CSV";
 for (uint8_t i = 0; i < 1000; i++) 
 {
 filename[4] = (i/100)%10 + '0';
 filename[5] = (i/10)%10 + '0';
 filename[6] = i%10 + '0';
 if (! SD.exists(filename)) 
 {
 // only open a new file if it doesn't exist
 logfile = SD.open(filename, FILE_WRITE);
 break; // leave the loop!
 }
 }

 if (! logfile)
 {
 error("couldnt create file");
 }

 Serial.print("Logging to: ");
 Serial.println(filename);
 
 Wire.begin();
 
 if (!RTC.begin()) // connect to RTC
 {
  logfile.println("RTC failed");
 #if ECHO_TO_SERIAL
  Serial.println("RTC failed");
 #endif //ECHO_TO_SERIAL
 }
 if (! RTC.isrunning())                 
  {
    error("RTC is NOT running, let's set the time!");
    RTC.adjust(DateTime(F( __DATE__ ), F( __TIME__ )));
  }  
  qmc.init(); // Initialize GY273 Compass sensor  
  dht.begin(); // Initialize DHT11 sensor
 
if (!pressure.begin())
  {
  error("Could not find a valid BMP085 sensor, check wiring!");
  while (1) {}
  }
 logfile.println("Date, Day, Time, WindSpeed, WindDir, Raining, TempBMP, PressureBMP, HumidityDHT");
#if ECHO_TO_SERIAL
 Serial.print("Date");
 Serial.print("\t");
 Serial.print("\t");
 Serial.print("Day");
 Serial.print("\t");
 Serial.print("Time");
 Serial.print("\t");
 Serial.print("WindSpeed");
 Serial.print("\t");
 Serial.print("WindDir");
 Serial.print("\t");
 Serial.print("RainStatus");
 Serial.print("\t");
 Serial.print("TempBMP");
 Serial.print("\t");
 Serial.print("PressBMP");
 Serial.print("\t");
 Serial.println("HumDHT");
#endif //ECHO_TO_SERIAL
 }
  
void loop(void)
{
 DateTime now;
 
 delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL)); // delay for the amount of time we want between readings
 digitalWrite(greenLEDpin, HIGH);
 
 uint32_t m = millis(); // log milliseconds since starting
 
 
 now = RTC.now(); // fetch the time
 // log time
 logfile.print(now.day(), DEC);
 logfile.print("-");
 logfile.print(now.month(), DEC);
 logfile.print("-");
 logfile.print(now.year(), DEC);
 logfile.print(",");
 logfile.print(daysOfTheWeek[now.dayOfTheWeek()]);
 logfile.print(",");
 logfile.print(now.hour(), DEC);
 logfile.print(":");
 logfile.print(now.minute(), DEC);
 logfile.print(":");
 logfile.print(now.second(), DEC);
 logfile.print(",");
 #if ECHO_TO_SERIAL
    Serial.print(now.day(),DEC);
    Serial.print("-");
    Serial.print(now.month(),DEC);
    Serial.print("-");
    Serial.print(now.year(),DEC);
    Serial.print(", ");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(", ");
    Serial.print(now.hour(), DEC);
    Serial.print(":");
    Serial.print(now.minute(), DEC);
    Serial.print(":");
    Serial.print(now.second(), DEC);
    Serial.print(", ");
#endif //ECHO_TO_SERIAL

 int windSpeed = (analogRead(windSpeedPin)/1024.0)*5.0; // Read an analog input A0 and converting the value of windSpeed to actual speed
 logfile.print(windSpeed);
 logfile.print(",");
 #if ECHO_TO_SERIAL
    Serial.print(windSpeed);
    Serial.print(", ");
 #endif //ECHO_TO_SERIAL
  // Read GY273 compass sensor data
  int x, y, z;
  int azimuth;
  qmc.read(&x, &y, &z,&azimuth);                  
  int windDirection = azimuth;
 logfile.print(windDirection);
 logfile.print("Deg N");
 logfile.print(",");
 #if ECHO_TO_SERIAL
    Serial.print(windDirection);
    Serial.print("Deg N");
    Serial.print(", ");
#endif //ECHO_TO_SERIAL
 //Read an analog input A3
  String rain="";    
  int rainValue = analogRead(rainPin); // Read Rain sensor data and calculate
  rainValue = map(rainValue,0,1023,225,0);
  if(rainValue>=rainset)
  {
  rain="Raining";
  }
  else
  {
  rain="Clear";
  }
 logfile.print(rain);
 logfile.print(",");
#if ECHO_TO_SERIAL
    Serial.print(rain);
    Serial.print(", ");
#endif //ECHO_TO_SERIAL
   
 float pressure = readPressureAndTemperature(); // Read BMP180 sensor data by calling function
 logfile.print(temperature);
 logfile.print(", ");
 logfile.print(pressure);
 logfile.println(",");
 #if ECHO_TO_SERIAL
    Serial.print(temperature);
    Serial.print(", ");
    Serial.print(pressure);
    Serial.println(", ");
 #endif //ECHO_TO_SERIAL
 
/* float humidity = dht.readHumidity()+10.0f; //whole code stopped working if this code is uncommented. Need solution. please help
 logfile.print(humidity);
 #if ECHO_TO_SERIAL
    Serial.println(humidity);
#endif //ECHO_TO_SERIAL*/

// At the end of data logging the green LED is turned off
digitalWrite(greenLEDpin, LOW);
 
 //Now we write data to disk! Don't sync too often - requires 2048 bytes of I/O to SD card which uses a bunch of power and takes time
 if ((millis() - syncTime) < SYNC_INTERVAL) return;   
 syncTime = millis();

 // blinking Red LED to show we are syncing data to the card & updating FAT!
 digitalWrite(redLEDpin, HIGH);
 logfile.flush();
 digitalWrite(redLEDpin, LOW);

} 
// Functions called in the loop

void error(char *str)
{
 Serial.print("error: ");
 Serial.println(str);

      // red LED indicates error
 digitalWrite(redLEDpin, HIGH);
 while(1);
}

float readPressureAndTemperature()
{
  char status;
  double T,P,p0,a;

  status = pressure.startTemperature();
  if (status != 0)
  {
    delay(status);
    status = pressure.getTemperature(T);
    if (status != 0)
    { 
      temperature = T;
      status = pressure.startPressure(3);
      if (status != 0)
      {
        delay(status);
        status = pressure.getPressure(P,T);
        if (status != 0)
        {
          p0 = pressure.sealevel(P,ALTITUDE);       
          return p0;
        }
      }
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![all\_practically](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/all_practically/32/1008927_2.png) [@all\_practically](https://forum.arduino.cc/u/all_practically)\
**Post date:** [October 20, 2023, 3:31pm UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/2 "2023-10-20T15:31:15Z")

</div>

i am new to arduino code. i have learned about many sensors. So i have planned to use them here in my code to create a data logger for weather report . There is a problem with this code. If i uncomment the code for DHT11 sensor for reading humidity. The whole loop stopped working further and also stopped from logging data to SD card. Please help me with code. Thanks and Regard in advance.

---

<div class="post-metadata">

**Author:** ![SupArdu](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/supardu/32/1089208_2.png) [@SupArdu](https://forum.arduino.cc/u/SupArdu)\
**Post date:** [October 20, 2023, 5:25pm UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/3 "2023-10-20T17:25:17Z")

</div>

> [@all\_practically](#):
>
> `float humidity = dht.readHumidity()`

The function readHumidity() is not included in this code. Obviously the program is hanging there. You should test this function in a separate sketch.

---

<div class="post-metadata">

**Author:** ![all\_practically](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/all_practically/32/1008927_2.png) [@all\_practically](https://forum.arduino.cc/u/all_practically)\
**Post date:** [October 21, 2023, 12:12am UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/4 "2023-10-21T00:12:30Z")

</div>

Thank you SupArdu for your response. ''dht.readHumidity()" is included in DHT library. But as per your advice i have run the code separately. All works fine.

```arduino
#include "DHT.h"
#include <SFE_BMP180.h>
#include <Wire.h>

SFE_BMP180 pressure;

float temperature;

#define ALTITUDE 241.05 // Altitude at my location
#define DHTPIN 2 // what pin we're connected to

#define DHTTYPE DHT11   

DHT dht(DHTPIN, DHTTYPE);

void setup(void) {
  Serial.begin(57600);
  dht.begin();
  pressure.begin();
}

void loop() 
{
  
 float humidity = dht.readHumidity()+10.0f;
 float pressure = readPressureAndTemperature();
 

 //Printing Temperature
 Serial.print("T:"); 
 Serial.print(temperature);
 Serial.print(" C");
 Serial.print("\t");

 //Printing Pressure

 Serial.print("P: ");
 Serial.print(pressure);
 Serial.print(" hPa");
 Serial.print("\t");
 
 //Printing Humidity
 Serial.print("H: ");
 Serial.print(humidity);
 Serial.println("%");
 
 delay(2000);
}

float readPressureAndTemperature()
{
  char status;
  double T,P,p0,a;

  status = pressure.startTemperature();
  if (status != 0)
  {
    delay(status);
    status = pressure.getTemperature(T);
    if (status != 0)
    { 
      temperature = T;
      status = pressure.startPressure(3);
      if (status != 0)
      {
        delay(status);
        status = pressure.getPressure(P,T);
        if (status != 0)
        {
          p0 = pressure.sealevel(P,ALTITUDE);       
          return p0;
        }
      }
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![xfpd](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/xfpd/32/1120236_2.png) [@xfpd](https://forum.arduino.cc/u/xfpd)\
**Post date:** [October 21, 2023, 1:48am UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/5 "2023-10-21T01:48:39Z")

</div>

> [@SupArdu](#):
>
> The function readHumidity() is not included in this code. **Obviously**

Really? It is... #include\<DHT.h\>

> `float DHT::readHumidity(bool force);`

---

<div class="post-metadata">

**Author:** ![xfpd](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/xfpd/32/1120236_2.png) [@xfpd](https://forum.arduino.cc/u/xfpd)\
**Post date:** [October 21, 2023, 2:03am UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/6 "2023-10-21T02:03:56Z")

</div>

> [@all\_practically](#):
>
> uncomment the code for DHT11

The un-commented section involves the SD card. Do you have enough power for the SD card read/write and the other devices?

---

<div class="post-metadata">

**Author:** ![all\_practically](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/all_practically/32/1008927_2.png) [@all\_practically](https://forum.arduino.cc/u/all_practically)\
**Post date:** [October 21, 2023, 5:23am UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/7 "2023-10-21T05:23:44Z")

</div>

Thank you for your concern. I have separate 5v suply for the whole setup beyond the arduino output power. But no luck at all. output stuck here just reading before 'float humidity = dht.readHumidity()'

 ![Screenshot 2023-10-21 104615](https://europe1.discourse-cdn.com/arduino/original/4X/4/a/c/4ac463343121ac0ebf53acee94d3eec97fa2edb5.png)  
But if i comment out the DHT sensor code only then the all works fine. Shows on Serial and also write on SD card with the same setup.  
Serial out put is as  
 ![Screenshot 2023-10-21 103823](https://europe1.discourse-cdn.com/arduino/original/4X/1/1/d/11d9a8e14f14abf5ea51835330750d494c825afc.png)  
and SD logged data as  
 ![Screenshot 2023-10-21 103722](https://europe1.discourse-cdn.com/arduino/original/4X/d/4/a/d4a61a6ca67883abb6ade2eeac03dc66cfc54ab9.png)

---

<div class="post-metadata">

**Author:** ![xfpd](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/xfpd/32/1120236_2.png) [@xfpd](https://forum.arduino.cc/u/xfpd)\
**Post date:** [October 21, 2023, 5:36am UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/8 "2023-10-21T05:36:33Z")

</div>

Maybe the `Serial.print()` is interfering... try only comment-out the `Serial.println(humidity);` line

> [@all\_practically](#):
>
> ```arduino
> /*
> #if ECHO_TO_SERIAL
> Serial.println(humidity);
> #endif //ECHO_TO_SERIAL
> */
> 
> ```

---

<div class="post-metadata">

**Author:** ![all\_practically](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/all_practically/32/1008927_2.png) [@all\_practically](https://forum.arduino.cc/u/all_practically)\
**Post date:** [October 21, 2023, 7:33am UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/9 "2023-10-21T07:33:17Z")

</div>

i have made this changes without reading DHT actually. Serial.println() is working fine. But if i uncomment this line the code stopped working

```arduino
//float humidity = dht.readHumidity()+10.0f;      
 logfile.println("humidity");
 #if ECHO_TO_SERIAL
    Serial.println("humidity");
#endif //ECHO_TO_SERIAL

```

---

<div class="post-metadata">

**Author:** ![qubits-us](https://avatars.discourse-cdn.com/v4/letter/q/5daacb/32.png) [@qubits-us](https://forum.arduino.cc/u/qubits-us)\
**Post date:** [October 21, 2023, 2:36pm UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/10 "2023-10-21T14:36:10Z")

</div>

> [@all\_practically](#):
>
> `float humidity = dht.readHumidity()+10.0f;`

thinking maybe it returns a nan..  
try taking out the math in the read..  
read humidity then check if(!isnan(humidity)) then add the 10.0f..

good luck.. ~q

---

<div class="post-metadata">

**Author:** ![xfpd](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/xfpd/32/1120236_2.png) [@xfpd](https://forum.arduino.cc/u/xfpd)\
**Post date:** [October 21, 2023, 2:48pm UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/11 "2023-10-21T14:48:56Z")

</div>

> [@all\_practically](#):
>
> dht.readHumidity()+10.0f;

Hello @qubits-us - ~~This looks strange to me, but it is shown in the examples of the library.~~  
I can not find my library reference... I must have seen it in a random project (that probably has the same issue)

---

<div class="post-metadata">

**Author:** ![qubits-us](https://avatars.discourse-cdn.com/v4/letter/q/5daacb/32.png) [@qubits-us](https://forum.arduino.cc/u/qubits-us)\
**Post date:** [October 21, 2023, 2:53pm UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/12 "2023-10-21T14:53:21Z")

</div>

doesn't mean it's correct..

```arduino
float DHT::readHumidity(bool force) {
  float f = NAN;

```

result starts out as a nan..  
[DHT.cpp](https://github.com/adafruit/DHT-sensor-library/blob/master/DHT.cpp)

just saying might want to add a check..

~q

---

<div class="post-metadata">

**Author:** ![all\_practically](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/all_practically/32/1008927_2.png) [@all\_practically](https://forum.arduino.cc/u/all_practically)\
**Post date:** [October 22, 2023, 3:02am UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/13 "2023-10-22T03:02:53Z")

</div>

Thank you all for responding. In my other code of audio play from SD card and run servo accordingly. "TMRpcm.h"(audio Library) and "servo.h" have some **timer** issue. So i replaced servo library with "ServoTimer2.h". So timer issue is resolved and code is working fine.  
i thought if there is some _timer_ issue in this code too....  
What do you think?

---

<div class="post-metadata">

**Author:** ![qubits-us](https://avatars.discourse-cdn.com/v4/letter/q/5daacb/32.png) [@qubits-us](https://forum.arduino.cc/u/qubits-us)\
**Post date:** [October 22, 2023, 1:10pm UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/14 "2023-10-22T13:10:11Z")

</div>

> [@all\_practically](#):
>
> i thought if there is some _timer_ issue in this code too....

while I did not check all the libs used, I don't think so..  
Now pcm and servos, i have seen that before..

did you try adding a check for nan (Not A Number)??  
dht11 needs about 2 seconds between reads..  
if code from post 4 works, try slowing down code in post 1..

but yes, the trouble could be something else completely..

good luck.. ~q

---

<div class="post-metadata">

**Author:** ![all\_practically](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/all_practically/32/1008927_2.png) [@all\_practically](https://forum.arduino.cc/u/all_practically)\
**Post date:** [October 22, 2023, 2:58pm UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/15 "2023-10-22T14:58:35Z")

</div>

No luck. i have tried slowing down the code in post 1.  
Then i have changed code for other DHT libraries. Like [https://github.com/adafruit/DHT-sensor-library](https://github.com/adafruit/DHT-sensor-library). But this totally block SD card from creating new file.  
🙄

---

<div class="post-metadata">

**Author:** ![TomGeorge](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/tomgeorge/32/215261_2.png) [@TomGeorge](https://forum.arduino.cc/u/TomGeorge)\
**Post date:** [October 23, 2023, 1:20am UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/16 "2023-10-23T01:20:52Z")

</div>

Hi, @all_practically

What model Arduino controller are you using?

Thanks.. Tom.. 😀 👍 ☕ 🇦🇺

---

<div class="post-metadata">

**Author:** ![all\_practically](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/all_practically/32/1008927_2.png) [@all\_practically](https://forum.arduino.cc/u/all_practically)\
**Post date:** [October 23, 2023, 10:27am UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/17 "2023-10-23T10:27:15Z")

</div>

Arduino Uno

---

<div class="post-metadata">

**Author:** ![SupArdu](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/supardu/32/1089208_2.png) [@SupArdu](https://forum.arduino.cc/u/SupArdu)\
**Post date:** [October 23, 2023, 1:38pm UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/18 "2023-10-23T13:38:51Z")

</div>

In a former sketch of mine I had a hang up because of interrupts continuously firing leaving no time for running the rest of the program. After commenting one line deleting the interrupt flag was omitted. Therefore the interrupt was firing continuously.  
Are interrupts involved reading DHT sensor?

Waiting for a flag which is not coming up also may get a program hanging.

Perhaps there is some incompatibility between your libraries used. One library may use some internal hardware (timer, I/O pins, SPI, etc.) configuring it in a way which another library cannot work with...

---

<div class="post-metadata">

**Author:** ![SupArdu](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/supardu/32/1089208_2.png) [@SupArdu](https://forum.arduino.cc/u/SupArdu)\
**Post date:** [October 23, 2023, 1:48pm UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/19 "2023-10-23T13:48:30Z")

</div>

Another idea:  
check the available RAM after compilation. The Uno has very limited RAM. Nested function calls e.g. require more and more RAM. If there is not sufficient RAM for the stack then crazy program behaviour may occur.

---

<div class="post-metadata">

**Author:** ![tochinet](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/tochinet/32/1126458_2.png) [@tochinet](https://forum.arduino.cc/u/tochinet)\
**Post date:** [October 23, 2023, 4:14pm UTC](https://forum.arduino.cc/t/weather-station-data-logger/1180421/20 "2023-10-23T16:14:19Z")

</div>

Could be an idea. In that case, #define ECHO\_TO\_SERIAL 0 may be enough to solve your problem...

[Next page](https://forum.arduino.cc/t/weather-station-data-logger/1180421.md?page=2)
