Fin du code ![]()
void loop(){ // debut de la fonction loop()
//---- crée fichier en écriture ---
file = SD.open("data.txt", FILE_WRITE); // ouvre le fichier en écriture
// NB : le fichier est créé si il n'existe pas !
//---- test si fichier dispo en écriture
if (!file) { // si fichier pas dispo
Serial.println ("Erreur ouverture fichier !");
} // fin if
else { // si le fichier existe et est ouvert
Serial.println ("Fichier pret pour ecriture !");
//----- Ecriture dans le fichier au format CSV -----
Serial.println ("Enregistrement en cours :");
// valeur deuxieme champ
file.print(comptageImpulsion), file.print(';');
// valeur quatrieme champ
file.print(millis()), file.print(';');
// le dernier champ doit se terminer par un saut de ligne +++
if( now() != prevDisplay) //update the display only if the time has changed
{
prevDisplay = now();
digitalClockDisplay();
}
file.close(); // ferme le fichier
Serial.println("Fin enregistrement !");
Serial.println("Fermeture fichier !");
// cosm
// read the analog sensor:
int sensorReading = comptageImpulsion ;
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
sendData(sensorReading);
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
//
delay(120000);
} // fin else
} // fin de la fonction loop() - le programme recommence au début de la fonction loop sans fin
// ********************************************************************************
// this method makes a HTTP connection to the server:
void sendData(int thisData) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.cosm.com");
client.print("X-ApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
// calculate the length of the sensor reading in bytes:
// 8 bytes for "sensor1," + number of digits of the data:
int thisLength = 8 + getLength(thisData);
client.println(thisLength);
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT request:
client.print("sensor2,");
client.println(thisData);
}
else {
//if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made or attempted:
lastConnectionTime = millis();
}
// This method calculates the number of digits in the
// sensor reading. Since each digit of the ASCII decimal
// representation is a byte, the number of digits equals
// the number of bytes:
int getLength(int someValue) {
// there's at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you're at 0:
int dividend = someValue /10;
while (dividend > 0) {
dividend = dividend /10;
digits++;
}
// return the number of digits:
return digits;
}
// ////////////////////////// FONCTIONS DE GESTION DES INTERRUPTIONS ////////////////////
// ------------------- fonction de gestion l'interruption externe n°0 (broche 2) ----------------
// cette fonction est appelée à chaque fois que l'interruption a lieu selon le mode configuré (LOW, CHANGE, RISING, FALLING)
void gestionINT0() {// la fonction appelée par l'interruption externe n°0
comptageImpulsion=comptageImpulsion+1; // Incrémente la variable de comptage
//---- affiche le nombre d'impulsions sur le port série
Serial.print("Nombre impulsions = ");
Serial.println(comptageImpulsion);
// tout se passe dans la fonction de gestion de l'interruption externe
}
// ////////////////////////// AUTRES FONCTIONS DU PROGRAMME ////////////////////
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();
file.print(hour()), file.print(';');
printDigitsSD(minute()), file.print(';');
printDigitsSD(second()), file.print(';');
file.print(day()), file.print(';');
file.print(month()), file.print(';');
file.print(year()), file.print(';');
file.println();
}
void printDigits(int digits){
// utility function for digital clock display: prints preceding colon and leading 0
Serial.print(":");
if(digits < 10)
Serial.print('0');
Serial.print(digits);
}
void printDigitsSD(int digits){
// utility function for digital clock display: prints preceding colon and leading 0
if(digits < 10)
file.print('0');
file.print(digits);
}
/*-------- NTP code ----------*/
unsigned long getNtpTime()
{
sendNTPpacket(timeServer); // send an NTP packet to a time server
delay(1000);
if ( Udp.parsePacket() ) {
// We've received a packet, read the data from it
Udp.read(packetBuffer,NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years and add the time zone:
unsigned long epoch = secsSince1900 - seventyYears + (timeZoneOffset * 3600L);
return epoch;
}
return 0;
}
// send an NTP request to the time server at the given address
unsigned long 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();
}