Ecrire à intervalle régulier les données d'un capteur de température/humidité

De Wiki L.A.B
Aller à : navigation, rechercher
Matériel
  • Arduino Uno
  • Shield datalogger
  • Carte SD formatée en FAT 16/32
  • Plaque d'essai (breadbord)
  • Capteur DHT11 ou DHT22
  • Résistance 4,7kΩ 1/4W (si besoin)
  • Straps ou fils de liaison
Montage

Montage DHT11 Montage DHT11

Programme


Voici le programme qu'il faut éditer dans l'IDE Arduino, puis compiler et charger dans la carte Arduino. Il utilise une librairie.

Pour télécharger la librairie : DHT11 La librairie SD pour écrire sur la carte est nativement fournie par l'IDE.

#include <dht11.h>
#include <SD.h>
#include <SPI.h>

dht11 DHT11;
File myFile;
long iteration;

#define DHT11PIN 2

void setup()
{
  Serial.begin(9600);
  Serial.print("Initializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin 
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output 
  // or the SD library functions will not work. 
   pinMode(10, OUTPUT);
   
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
  myFile = SD.open("sensors.csv", FILE_WRITE);
  if (myFile) {
    Serial.print("Writing to sensors.csv...");
    myFile.println("loop;humidity,temperature");
    myFile.close();
    Serial.println("done.");
  } else {
    Serial.println("error opening sensors.csv");
  }
  
  Serial.println("DHT11 Humidity and Temperature Digital Sensor sketch");
  delay(1000);          // wait for sensor initialization

  // loop
  iteration = 1;
}

void loop()
{
  uint8_t chk = DHT11.read(DHT11PIN);

  Serial.print("Sensor status: ");
  switch (chk)
  {
    case 0:  Serial.println("OK"); break;
    case -1: Serial.println("Checksum error"); break;
    case -2: Serial.println("Time out error"); break;
    case -3: Serial.println("The sensor is busy"); break;
    default: Serial.println("Unknown error"); break;
  }

  Serial.print("Humidity (%): ");
  Serial.println(DHT11.humidity, DEC);

  Serial.print("Temperature (C): ");
  Serial.println(DHT11.temperature, DEC);

  myFile = SD.open("sensors.csv", FILE_WRITE);
  if (myFile) {
    Serial.print("Writing data from sensors to sensors.csv...");    
    String sIteration = String(iteration);
    String sHumidity = String(DHT11.humidity); 
    String sTemperature = String(DHT11.temperature); 
    myFile.println(sIteration + ";" + sHumidity + ";" + sTemperature);  
    myFile.close();
    Serial.println("done.");
  } else {
    Serial.println("error opening sensors.csv");
  }
  
  iteration++;
  delay(2000);
}