Ecriture sur carte SD avec utilisation de l'Ethernet pour la date

Bonjour,
j’essaie de compiler 2 exemples de programmes sans succès

Ecriture sur carte SD
Lecture de la date via une synchronisation NTP

Dans mon programme ci joint, je n’ai aucune information écrite sur la carte SD…

Je ne vois pas d’ou pourrait venir le souci…

Votre avis ?

MERCI !

#include <SPI.h>

#include <Ethernet.h>
#include <EthernetUdp.h>
#include <Time.h> 

#include <LiquidCrystal.h>
#include <SD.h>

LiquidCrystal lcd(2, 3, 5, 6, 7, 8);

const int brocheSDCardSelect=4; // broche utilisée pour sélectionner la SD card

int capteur1 = 0;    float U_temperature;    float temperature;
int capteur2 = 1;    float U_lumiere;        float lumiere;
int capteur3 = 2;    float hygrometrie;      float U_hygrometrie;

int test; // Variable utilisée pour tester valeur renvoyée par fonctions SD Card
File file; // objet file
File root; // objet root pour le répertoire racine

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 
IPAddress ip( 192, 168, xxx, xxx );    
IPAddress gateway( 192, 168, xxx, xxx );
IPAddress subnet( 255, 255, 255, 0 );

IPAddress timeServer(132, 163, 4, 101);
const int timeZone = 1; 

EthernetUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets




void setup() {
     Serial.begin(9600);
     
     pinMode(10, OUTPUT); // met la broche 10 (SS) en sortie (nécessaire avec module ethernet)
     digitalWrite(10, HIGH); // mais désactive le  circuit intégré W5100 du module ethernet!
     

     Serial.println("Initialisation de la SD card...");
     test=SD.begin(brocheSDCardSelect);
          if (test!=true) {
          Serial.println("Echec initialisation!"); 
                          }
          else {
          Serial.println("Initialisation reussie !"); 
          root = SD.open("/");
          Serial.println("Repertoire racine ouvert !");
              } 
              
     test=SD.remove("data.txt");  
          if (test) Serial.println("Fichier efface");
          file = SD.open("data.txt", FILE_WRITE); 
          if (!file) { 
          Serial.println ("Erreur ouverture fichier !");
                     }
          else {
          Serial.println ("Fichier pret pour ecriture !");
               }
     file.println("temps;temperature;lumiere;hygrometrie");
     file.close();

   
     delay(1000);   
    
    
    
  while (!Serial) ; // Needed for Leonardo only
      Serial.println ("2 !");
    delay(250);
  Serial.println("TimeNTP Example");
  if (Ethernet.begin(mac) == 0) {
    // no point in carrying on, so do nothing forevermore:
    while (1) {
      Serial.println("Failed to configure Ethernet using DHCP");
      delay(10000);
    }
  }
  
  Serial.print("IP number assigned by DHCP is ");
  Serial.println(Ethernet.localIP());
  Udp.begin(localPort);
  
  Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);
  
  }





time_t prevDisplay = 0; // when the digital clock was displayed




void loop(){  
  
     U_temperature = analogRead(capteur1);
     temperature=1/((1/298.15)+(log ((((5* U_temperature)/1024)/((5-((5* U_temperature)/1024))/10000))/10000)/3977))-273.15;
  
     U_lumiere = analogRead(capteur2);  
     lumiere=5*U_lumiere/1024;
  
     U_hygrometrie = analogRead(capteur3);
     hygrometrie=31.687*((5* U_hygrometrie)/1024) - 24.323 ;
 
     prevDisplay = now();
     digitalClockDisplay();  
    
       file = SD.open("data.txt", FILE_WRITE); // ouvre le fichier en écriture puis écriture des données
       file.print(temperature), file.print(';');  
       file.print(lumiere), file.print(';');
       file.print(hygrometrie);
       file.println();
       file.close(); // ferme le fichier
 
 
     // lcd.setCursor(0, 1); lcd.print("Temp    : "); lcd.print(temperature); lcd.print(" oC");
     // lcd.setCursor(0, 2); lcd.print("Lumiere : "); lcd.print(lumiere); lcd.print(" V");
     // lcd.setCursor(0, 3); lcd.print("Hygro   : "); lcd.print(hygrometrie); lcd.print(" HR%");
     // delay(2000);
     // lcd.clear();
  
  
 delay(1000); // 1 secondes entre chaque mesure  
  
}



void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year()); 
  Serial.println(); 
}

void printDigits(int digits){
  // utility for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}






/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;
  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:                 
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}

As tu essayé juste d'écrire sur la carte SD avec les exemples? Ensuite tu testes la connection NTP avec d'abord un affichage sur le Serial

Et enfin tu assembles les 2

;)

Oui, j'ai en effet testé les 2 programmes indépendamment avec succès.

C'est le rassemblement qui pose problème...

Et avec quelques Serial.print bien placé tu ne trouves pas d'où ça vient?

Je pense que comme tu partages l'Ethernet et le SD il doit y avoir le pin select à gérer, tantot dans un état pour l'ethernet, tantot dans un autre état pour la SD

j'en ai placé en effet plusieurs... et je pense que c'est dans le setup, des la création du fichier, celui ci ne veut pas s'ouvrir, alors qu'il bien été créé...

Dans un premier temps tu dois mettre la carte Ethernet éteinte par:

digitalWrite(10, HIGH); // mais désactive le  circuit intégré W5100 du module ethernet!

Mais du coup tu dois activer aussi la SD par:

digitalWrite(SS_SD_CARD, LOW);  // SD Card ACTIVE

Or dans ton code je ne vois pas l'activation de la SD?

Prévois déjà un code du type:

#define SS_SD_CARD   4
#define SS_ETHERNET 10

void setup() {
    // ...
    pinMode(SS_SD_CARD, OUTPUT);
    pinMode(SS_ETHERNET, OUTPUT);
    digitalWrite(SS_SD_CARD, HIGH);  // SD Card not active
    digitalWrite(SS_ETHERNET, HIGH); // Ethernet not active
    // ...
}

void sdCardCode() {
    // ...
    digitalWrite(SS_SD_CARD, LOW);  // SD Card ACTIVE
    // code that sends to the sd card slave device over SPI
    // using SPI.transfer() etc.
    digitalWrite(SS_SD_CARD, HIGH); // SD Card not active
    // ...
}

void ethernetCode() {
    // ...
    digitalWrite(SS_ETHERNET, LOW);  // Ethernet ACTIVE
    // code that sends to the ethernet slave device over SPI
    // using SPI.transfer() etc.
    digitalWrite(SS_ETHERNET, HIGH); // Ethernet not active
    // ...
}

est ce que : SD.begin(brocheSDCardSelect) ne vient pas jouer ce role d'activation ?

L'intitialisation de la SD se fait correctement

donc je dois bien communiquer avec la SD ?

L'ajout de ta fonction ne modifie pas le comportement de mon prog...

Je ne comprends pas bien le comportement de ma carte mais en insistant betement avec les fonctions active/desactive, j'ai un résultat interressant.... je vais poursuivre mon programme ! MErci john_lenfr !!!

Ok, dit nous si tu as résolu le problème

... non... faux espoir...

j'ai trouvé cet exemple sur le net qui utilise la SD et la connection pour la date via NTP : http://skyduino.wordpress.com/2013/01/02/arduino-systeme-de-traitement-online-offline/

il déclare juste la pin 10 en sortie, meme pas de niveau !

je ne comprends pas comment cela fonctionne... et du coup, d'ou vient mon pb ???

Il faut que tu fasses des tests méthodiques avec des Serial.print réguliers dans ton code pour "voir" ce qu'il se passe.

Prends l'un des deux codes, ensuite ajoute la librairie de l'autre et ensuite tu ajoutes le code progressivement et tu vois ce qu'il se passe.

Quel est le dernier code que tu utilises pour l'instant? Il faut repartir de là pour debugger ;)

Je reprends tout de 0

1- Pour l’écriture SD, je prends l’exemple de :

Ce programme fonctionne bien avec mon matériel, j’ai bien le fichier de créé sur la SD et rempli correctement!

2- Pour la data via NTP, je prends l’exemple dans
Fichier/exemples/time/time NTP dans le logiciel
soit :

/*
 * Time_NTP.pde
 * Example showing time sync to NTP time source
 *
 * This sketch uses the Ethernet library
 */
 
#include <Time.h> 
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 
// NTP Servers:
IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov
// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov
// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov


const int timeZone = 1;     // Central European Time
//const int timeZone = -5;  // Eastern Standard Time (USA)
//const int timeZone = -4;  // Eastern Daylight Time (USA)
//const int timeZone = -8;  // Pacific Standard Time (USA)
//const int timeZone = -7;  // Pacific Daylight Time (USA)


EthernetUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets

void setup() 
{
  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  delay(250);
  Serial.println("TimeNTP Example");
  if (Ethernet.begin(mac) == 0) {
    // no point in carrying on, so do nothing forevermore:
    while (1) {
      Serial.println("Failed to configure Ethernet using DHCP");
      delay(10000);
    }
  }
  Serial.print("IP number assigned by DHCP is ");
  Serial.println(Ethernet.localIP());
  Udp.begin(localPort);
  Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);

  pinMode(10, OUTPUT);

if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");


}

time_t prevDisplay = 0; // when the digital clock was displayed

void loop()
{  
  if (timeStatus() != timeNotSet) {
    if (now() != prevDisplay) { //update the display only if time has changed
      prevDisplay = now();
      digitalClockDisplay();  
    }
  }
  
    String dataString = "";
    
      for (int analogPin = 0; analogPin < 3; analogPin++) {
    int sensor = analogRead(analogPin);
    dataString += String(sensor);
    if (analogPin < 2) {
      dataString += ",";
    }
  }

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.println(dataString);
  }  
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }

  
  
  
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year()); 
  Serial.println(); 
}

void printDigits(int digits){
  // utility for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;
  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:                 
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}

Ce programme fonctionne bien avec mon matériel, j’ai bien la connection et la date d’affichier sur l’espion.

3- j’intégre à mesure le programme de la SD dans le soft du NTP et la …
l’espion m’indique ‘error opening datalog.txt’ > l’écriture ne se réalise pas…

Je me demande bien ce qui ce passe dans les fonctions… > et la je n’ai pas d’acces pour mettre le mouchard…

voici mon code complilé :

/*
 * Time_NTP.pde
 * Example showing time sync to NTP time source
 *
 * This sketch uses the Ethernet library
 */
 
#include <Time.h> 
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 
// NTP Servers:
IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov
// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov
// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov


const int timeZone = 1;     // Central European Time
//const int timeZone = -5;  // Eastern Standard Time (USA)
//const int timeZone = -4;  // Eastern Daylight Time (USA)
//const int timeZone = -8;  // Pacific Standard Time (USA)
//const int timeZone = -7;  // Pacific Daylight Time (USA)


EthernetUDP Udp;
unsigned int localPort = 8888;  // local port to listen for UDP packets

void setup() 
{
  Serial.begin(9600);
  while (!Serial) ; // Needed for Leonardo only
  delay(250);
  Serial.println("TimeNTP Example");
  if (Ethernet.begin(mac) == 0) {
    // no point in carrying on, so do nothing forevermore:
    while (1) {
      Serial.println("Failed to configure Ethernet using DHCP");
      delay(10000);
    }
  }
  Serial.print("IP number assigned by DHCP is ");
  Serial.println(Ethernet.localIP());
  Udp.begin(localPort);
  Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);

  pinMode(10, OUTPUT);

if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");


}

time_t prevDisplay = 0; // when the digital clock was displayed

void loop()
{  
  if (timeStatus() != timeNotSet) {
    if (now() != prevDisplay) { //update the display only if time has changed
      prevDisplay = now();
      digitalClockDisplay();  
    }
  }
  
    String dataString = "";
    
      for (int analogPin = 0; analogPin < 3; analogPin++) {
    int sensor = analogRead(analogPin);
    dataString += String(sensor);
    if (analogPin < 2) {
      dataString += ",";
    }
  }

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.println(dataString);
  }  
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }

  
  
  
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year()); 
  Serial.println(); 
}

void printDigits(int digits){
  // utility for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

/*-------- NTP code ----------*/

const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets

time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress &address)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;
  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:                 
  Udp.beginPacket(address, 123); //NTP requests are to port 123
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}

Je ne vois pas dans ton code la gestion du SS de la SD à low sur le Pin 4 et la même chose sur le Pin 10 pour l'Ethernet?

Tu dois gérer tanto l'accès à l'ethernet, tantot l'accès à la SD et là ça n'est pas pris en compte. Car ces 2 fonctions partagent le même bus SPI sur les Pins MOSI - pin 11 / ** MISO - pin 12 et ** CLK - pin 13

Essaie d'insérer ton code dans la trame que j'avais donné:

#define SS_SD_CARD   4
#define SS_ETHERNET 10

void setup() {
    // ...
    pinMode(SS_SD_CARD, OUTPUT);
    pinMode(SS_ETHERNET, OUTPUT);
    digitalWrite(SS_SD_CARD, HIGH);  // SD Card not active
    digitalWrite(SS_ETHERNET, HIGH); // Ethernet not active
    // ...
}

void sdCardCode() {
    // ...
    digitalWrite(SS_SD_CARD, LOW);  // SD Card ACTIVE
    // code that sends to the sd card slave device over SPI
    // using SPI.transfer() etc.
    digitalWrite(SS_SD_CARD, HIGH); // SD Card not active
    // ...
}

void ethernetCode() {
    // ...
    digitalWrite(SS_ETHERNET, LOW);  // Ethernet ACTIVE
    // code that sends to the ethernet slave device over SPI
    // using SPI.transfer() etc.
    digitalWrite(SS_ETHERNET, HIGH); // Ethernet not active
    // ...
}

Et qui te permet de passer de l'un à l'autre ;)

Bonjour,
je suis bien d’accord avec toi,
mais les exemples cités, et les qq infos que j’ai ne parle que d’une chose
> Sur un shield ethernet, pour communiquer avec la SD, il faut mettre la pin 10 en sortie, et ne pas utiliser la pin4
> C’est juste cela que je souhaiterai faire confirmer!

sinon, sans comprendre pourquoi, voilà le code compilé, qui fonctionne et stable… sans que je n’explique pkoi…

#include <Time.h> 
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <SPI.h>
#include <SD.h>

String temps;

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 

IPAddress timeServer(132, 163, 4, 101);
const int timeZone = 1;

EthernetUDP Udp;
unsigned int localPort = 8888;

int test; // Variable utilisée pour tester valeur renvoyée par fonctions SD Card
File file; // objet file
File root; // objet root pour le répertoire racine




void setup() 
{
  Serial.begin(9600);
  
  pinMode(10, OUTPUT);
 
 
   if (Ethernet.begin(mac) == 0) {
   while (1) {
      Serial.println("Failed to configure Ethernet using DHCP");
      delay(10000);
    }
  }
    Serial.print("IP number assigned by DHCP is ");
  Serial.println(Ethernet.localIP());
  Udp.begin(localPort);
  Serial.println("waiting for sync");
  setSyncProvider(getNtpTime);


if (!SD.begin(4)) {
    Serial.println("Card failed, or not present");
    return;
  }
  Serial.println("card initialized.");

 test=SD.remove("datalog.txt"); // efface fichier et mémorise résultat opération  
 
 File dataFile = SD.open("datalog.txt", FILE_WRITE);
 dataFile.println("temps;mesurebrute0;tension0;mesurebrute1;tension1;mesurebrute2;tension2");
 dataFile.close(); // ferme le fichier

}



time_t prevDisplay = 0;




void loop()
{  
  temps= String (day()) + "/" + String (month()) + "/" + String ( year ()) + " " + String ( hour ()) + ":" + String ( minute ()) + ":"+String ( second ());
  
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println(temps);
    dataFile.close();
    Serial.println(temps);
  } 
  else {
    Serial.println("error opening datalog.txt");
  }
  
    delay(1000);
  
}


const int NTP_PACKET_SIZE = 48;
byte packetBuffer[NTP_PACKET_SIZE];

time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ;
  Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);
      unsigned long secsSince1900;
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0;
}


void sendNTPpacket(IPAddress &address)
{

  memset(packetBuffer, 0, NTP_PACKET_SIZE);

  packetBuffer[0] = 0b11100011; 
  packetBuffer[1] = 0;  
  packetBuffer[2] = 6; 
  packetBuffer[3] = 0xEC;
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;
              
  Udp.beginPacket(address, 123); 
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}

Au cas ou je te mets un petit code de test fonctionnel si ton problème n’est pas résolu:

/*
  Web Server

 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe

 /////PIN MAPPING////
 D0: RX Serial
 D1: TX Serial
 D2: 
 D3: 
 D4: SS_SD_CARD (or CS PIN)
 D5: 
 D6: 
 D7: 
 D8: 
 D9: 
 D10: SS_ETHERNET
 D11: MOSI
 D12: MISO
 D13: CLK
 
 A0: 
 A1: 
 A2: 
 A3: 
 A4: 
 A5: 

 */

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

#define DEBUG_SD
#define DEBUG_ETHERNET

#define SS_SD_CARD   4
#define SS_ETHERNET 10

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};// give an unique adress on your network

IPAddress ip(192, 168, 1, 252);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

void setup() {
  
  pinMode(SS_SD_CARD, OUTPUT);
  pinMode(SS_ETHERNET, OUTPUT);
  digitalWrite(SS_SD_CARD, HIGH);  // SD Card not active
  digitalWrite(SS_ETHERNET, HIGH); // Ethernet not active
 
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
    
  SDCardCode_init();
  ethernetCode_init();
  
}


void loop() {
  
  ethernetCode();
  
  SDCardCode();
  
}

void SDCardCode_init() {
    // ...
    digitalWrite(SS_SD_CARD, LOW);  // SD Card ACTIVE
    
    #ifdef DEBUG_SD
        Serial.print(F("Initializing SD card..."));
      
        // we'll use the initialization code from the utility libraries
        // since we're just testing if the card is working!
        if (!card.init(SPI_HALF_SPEED, SS_SD_CARD)) {
          Serial.println(F("initialization failed. Things to check:"));
          Serial.println(F("* is a card is inserted?"));
          Serial.println(F("* Is your wiring correct?"));
          Serial.println(F("* did you change the chipSelect pin to match your shield or module?"));
          return;
        } else {
          Serial.println(F("Wiring is correct and a card is present."));
        }
        
        // print the type of card
        Serial.print("Card type: ");
        switch (card.type()) {
          case SD_CARD_TYPE_SD1:
            Serial.println(F("SD1"));
            break;
          case SD_CARD_TYPE_SD2:
            Serial.println(F("SD2"));
            break;
          case SD_CARD_TYPE_SDHC:
            Serial.println(F("SDHC"));
            break;
          default:
            Serial.println(F("Unknown"));
        }
      
        // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
        if (!volume.init(card)) {
          Serial.println(F("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card"));
          return;
        }
    
    
        // print the type and size of the first FAT-type volume
        uint32_t volumesize;
        Serial.print(F("Volume type is FAT"));
        Serial.println(volume.fatType(), DEC);
        Serial.println();
      
        volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
        volumesize *= volume.clusterCount();       // we'll have a lot of clusters
        volumesize *= 512;                         // SD card blocks are always 512 bytes
        Serial.print(F("Volume size (bytes): "));
        Serial.println(volumesize);
        Serial.print(F("Volume size (Kbytes): "));
        volumesize /= 1024;
        Serial.println(volumesize);
        Serial.print(F("Volume size (Mbytes): "));
        volumesize /= 1024;
        Serial.println(volumesize);
      
      
        Serial.println(F("\nFiles found on the card (name, date and size in bytes): "));
        root.openRoot(volume);
      
        // list all files in the card with date and size
        root.ls(LS_R | LS_DATE | LS_SIZE);
    
    #endif
    
    if (!SD.begin(SS_SD_CARD)) {
      Serial.println(F("Card failed, or not present"));
      // don't do anything more:
      return;
    }
    Serial.println(F("card initialized."));
    
    
    digitalWrite(SS_SD_CARD, HIGH); // SD Card not active
    // ...
}

void SDCardCode() {
    // ...
    digitalWrite(SS_SD_CARD, LOW);  // SD Card ACTIVE
    
      // make a string for assembling the data to log:
    String dataString = "";
  
    // read three sensors and append to the string:
    for (int analogPin = 0; analogPin < 3; analogPin++) {
      int sensor = analogRead(analogPin);
      dataString += String(sensor);
      if (analogPin < 2) {
        dataString += ",";
      }
    }
  
    // open the file. note that only one file can be open at a time,
    // so you have to close this one before opening another.
    File dataFile = SD.open("data.txt", FILE_WRITE);
    delay(10);
    // if the file is available, write to it:
    if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
      // print to the serial port too:
      Serial.println(dataString);
    }
    // if the file isn't open, pop up an error:
    else {
      Serial.println(F("error opening datalog.txt"));
    }
    
    digitalWrite(SS_SD_CARD, HIGH); // SD Card not active
    // ...
}




void ethernetCode_init() {
    // ...
    digitalWrite(SS_ETHERNET, LOW);  // Ethernet ACTIVE

    // start the Ethernet connection and the server:
    Ethernet.begin(mac, ip);
    server.begin();
    #ifdef DEBUG_ETHERNET
    Serial.print(F("server is at "));
    Serial.println(Ethernet.localIP());
    #endif
    
    digitalWrite(SS_ETHERNET, HIGH); // Ethernet not active
    // ...
}

void ethernetCode() {
    // ...
    digitalWrite(SS_ETHERNET, LOW);  // Ethernet ACTIVE
    
    // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println(F("new client"));
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println(F("HTTP/1.1 200 OK"));
          client.println(F("Content-Type: text/html"));
          client.println(F("Connection: close"));  // the connection will be closed after completion of the response
          //client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println(F("<!DOCTYPE HTML>"));
          client.println(F("<html>"));
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print(F("analog input "));
            client.print(analogChannel);
            client.print(F(" is "));
            client.print(sensorReading);
            client.println(F("
"));
          }
          client.println(F("</html>"));
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println(F("client disconnected"));
  }
    
    
    
    digitalWrite(SS_ETHERNET, HIGH); // Ethernet not active
    // ...
}