problema con pachube (www.cosm.com)

Ciao Lesto,
ti allego una foto del debug di cosm... è quello che mi dicevi di controllare?
Grazie

Ciao lesto,
scusa se ne approfitto, tu mi sai dire come dovrei impostare il MAC adderss di una seconda scheda ethernet nella stessa rete di quella che è già installata?
Grazie

per impostare un MAC address diverso da quello dell'altro arduino (e diverso anche da ogni altro oggetto collegato in rete), basta che nell'array dove specifichi il MAC address cambi uno o più dei 6 valori, ad ognuno puoi associare un valore compreso tra 0 e 255 esprimendoli in esadecimale (quindi da 0x00 a 0xFF) oppure, puoi scrivere quelli che trovi sull'etichetta attaccata sotto lo shield.

Per risolvere molto alla spicciolata dovrebbe essere sufficiente invertire due elementi dell'aray:

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

Domanda: stai ancora usando il codice originale, non quello di cyberhs vero? In quello modificato da cyberhs la variabile String viene dichiarata globalmente, ma poi dentro il loop non viene mai resettata da qualche parte, questo significa che ad ogni loop aggiungi in coda le nuove letture, quindi Cosm.com potrebbe avere dei problemi ad interpretarle, ma fatto ancor più grave, quella stringa continua a crescere fino ad occupare tutta la RAM dell'Arduino con la conseguenza di imprevedibili da parte dell'Arduino.

Quello che intendeva dire lesto è di aggiungere anche una stampa sulla seriale di quello che stai mandado a Cosm.com, quindi in parole povere, sotto

client.println(thisData);

aggiungi:

Serial.println(thisData);

da ll'immagine sembra che il problema sia solo a lato arduino, tranne per uno spazio prima di "sensor1"

Grazie lesto e grazie Federico,
a dir il vero sto usando ancora il codice riscritto da Cyberhs, ma in effetti, e non ne capivo i motivi, l'altra sera si sonbo "inkiodate" entrambe le schede che sto usando, sia quella dei test che ho in studio che quella che ho montata vicino al bollitore del termosolare.
Le ho lasciate spente qualche ora ed ho ricaricato il codice, adesso funzionano, ma mi sembra di capire che si ribloccherano a breve...
Quindi, ricarico lo sketch che ho pubblicato all'inizio di questo topic e ci aggiungo i due comandi che mi hai detto?
Grazie

Per Federico Vanzati:

guarda che la variabile String dataString viene resettata nel loop con la riga: dataString = "sensor1,";

Ettore Massimo Albani

PS: ho risolto il problema di Alba e Tramonto riscrivendo una routine che funziona. Il problema della tua libreria non risiede (a quanto pare) nel cambio di IDE, ma nella sua logica. Ho confrontato con dei calcolatori on line e la tua libreria non fornisce risultati corretti. Fammi sapere. Ciao!

Ciao Ettore,
qundi, mantengo la tua libreria ed aggiungo:

client.println(thisData);aggiungi:

Serial.println(thisData);

in modo tale da vedere che dati escono da arduino?
Grazie

Caro elvis,

mandami il codice così lo esamino meglio.

Ettore Massimo Albani

Ho aggiunto

Serial.println(thisData);

ma non vedo cose diverse da prima sulla stampa della seriale...

ecco il codice che sto usando ora su cosm username: gelholder "test Termosolare":

/* IDE 1.01
 Ethernet shield attached to pins 10, 11, 12, 13
 Arduino uno
 This code is in the public domain.
 */

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

#define APIKEY         "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" // replace your Cosm api key here
#define FEEDID         XXXXX // replace your feed ID
#define USERAGENT      "TEST 2" // user agent is the project name

// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xBD};

// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(192,168,11,12);

// initialize the library instance:
EthernetClient client;

// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
// IPAddress server(216,52,233,121);      // numeric IP for api.cosm.com
char server[] = "api.cosm.com";   // name address for Cosm API

unsigned long lastConnectionTime = 0;          // last time you connected to the server, in milliseconds
boolean lastConnected = false;                 // state of the connection last time through the main loop
const unsigned long postingInterval = 10 * 1000;  //delay between updates to Cosm.com

int caldaiaON = 0;               //INGRESSO ANALOGICO PER CONTROLLO WEB STATO CALDAIA 
int Ventola = 0;  //INGRESSO ANALOGICO PER CONTROLLO WEB STATO CALDAIA 
float tempAria = 0.0;  //sensore di temperatura LM35DZ ARIA
float tempAcqua = 0.0;    // sensore di temperatura LM35DZ ACQUA
int sensorReading = 0;
String dataString = "";
int otherSensorReading = 0;  
int otherSensorReadingAria = 0;  
int otherSensorReadingCaldaia = 0;

void setup() {
  
  pinMode(5, OUTPUT);  //USCITA IN PARALLELO AL RELE CALDAIA PER VISUALIZZAZIONE WEB STATO CALDAIA   
  pinMode(6, OUTPUT);  //USCITA IN PARALLELO AL RELE CALDAIA PER VISUALIZZAZIONE WEB STATO CALDAIA   
  pinMode(8, OUTPUT);  //relay controllo ACQUA
  pinMode(9, OUTPUT);  //relay controllo ARIA

  // start serial port:
  Serial.begin(9600);
  // give the ethernet module time to boot up:
  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // DHCP failed, so use a fixed IP address:
    Ethernet.begin(mac, ip);
  }
}

void loop() {

  caldaiaON = analogRead(A0);  //INGRESSO ANALOGICO PER CONTROLLO WEB STATO CALDAIA 
  Ventola = analogRead(A2);  //INGRESSO ANALOGICO PER CONTROLLO WEB STATO CALDAIA 
  // read the analog sensor:
  tempAria = analogRead(A1) * 0.5;    //sensore di temperatura LM35DZ ARIA
  sensorReading = tempAria;
  Serial.print ("Temp. Aria:  ");
  Serial.println (tempAria);

  dataString = "sensor1,";
  dataString += sensorReading;

  if ((tempAria > 0) and (tempAria < 35)){
    Serial.println("Aria fredda"); 
    digitalWrite(9, LOW);      //VENTILAZIONE DISATTIVATA
    digitalWrite(5, LOW);      //VENTILAZIONE DISATTIVATA
    Serial.print ("Ventola Spenta  ");
    Serial.println (Ventola, DEC);
  }
  else if ((tempAria > 35) and (tempAria < 100)){
    Serial.println ("Aria calda");
    digitalWrite(9, HIGH);    //VENTILAZIONE ATTIVATA
    digitalWrite(5, HIGH);    //VENTILAZIONE ATTIVATA
    Serial.print ("Ventola Accesa  ");
    Serial.println (Ventola,DEC);
  }

  otherSensorReadingAria = Ventola;  
  dataString += "\nsensor2,";
  dataString += otherSensorReadingAria;
  // you can append multiple readings to this String if your
  // Cosm feed is set up to handle multiple values:
  tempAcqua = (analogRead(A3) * 0.5) + 4;    // sensore di temperatura LM35DZ ACQUA
  otherSensorReading = tempAcqua;
  Serial.print("Temp. Acqua: ");
  Serial.println(tempAcqua);

  dataString += "\nsensor3,";
  dataString += otherSensorReading;

  if ((tempAcqua > 0) and (tempAcqua < 42)) {
    Serial.println("Acqua fredda"); 
    digitalWrite(8, HIGH);    // ACCENSIONA CALDAIA
    digitalWrite(6, HIGH);    //USCITA IN PARALLELO AL SEGNALE CALDAIA PER TELECONTROLLO
    Serial.print("Caldaia Accesa ");
    Serial.println(caldaiaON, DEC);
  }
  else if ((tempAcqua > 42) and (tempAcqua < 100)){
    delay(2000);
    Serial.println ("Acqua Calda");
    digitalWrite(8, LOW);    //SPEGNIMENTO CALDAIA
    digitalWrite(6, LOW);    //USCITA IN PARALLELO AL SEGNALE CALDAIA PER TELECONTROLLO
    Serial.print("Caldaia Spenta ");
    Serial.println(caldaiaON, DEC);
  }

  otherSensorReadingCaldaia = caldaiaON;
  dataString += "\nsensor4,";
  dataString += otherSensorReadingCaldaia; 
  // 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 (millis() < lastConnectionTime) lastConnectionTime = millis();    // evita il blocco dopo 50gg poiché millis() si azzera

  if (!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
    sendData(dataString);
  }
  // store the state of the connection for next time through
  // the loop:
  lastConnected = client.connected();
}

// this method makes a HTTP connection to the server:

void sendData(String 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: ");
    client.println(thisData.length());

    // 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.println(thisData);
    Serial.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();
}

Grazie

In questo momento ho una scheda Arduino + ethernet in studio ed un'altra Arduino + ethernet accanto al bollitore termosolare ed entrambe connesse alla stessa rete.
Se andate su cosm e cercate gelholder noterete che la scheda Termosolare fa il refresh ogni 20min. circa, mentre quella in studio ogni 70sec. circa.
Considerato che lo sketch è lo stesso (con le uniche differenze di mac address, IP e impostazioni cosm...) è la temperatura ambiente che influenza la velocità di aggiornamento dei dati?
In studio ci sono 24°C, accanto al bollitore termosolare 32°C...

Caro elvis,

il codice aveva un errore piuttosto grave che forse inficiava la ricezione da parte del sito.

L'assegnazione:
dataString += otherSensorReading;
funziona con stringhe e non con interi o peggio float!

Poiché non era scritto molto chiaro, mi sono permesso di modificarlo.

Prova adesso.

Ettore Massimo Albani

/* IDE 1.01
 Ethernet shield attached to pins 10, 11, 12, 13
 Arduino uno
 This code is in the public domain.
 */

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

#define APIKEY         "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"   // replace your Cosm api key here
#define FEEDID         XXXXX                                // replace your feed ID
#define USERAGENT      "TEST 2"                             // user agent is the project name

byte mac[] = {                                              // MAC address of Ethernet controller
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xBD};

IPAddress ip(192, 168, 11, 12);                             // IP address on your network here

EthernetClient client;                                      // initialize the library instance:

// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:

// IPAddress server(216, 52, 233, 121);                        // numeric IP for api.cosm.com
char server[] = "api.cosm.com";                             // name address for Cosm API

unsigned long lastConnectionTime = 0;                       // last time you connected to the server, in milliseconds
boolean lastConnected = false;                              // state of the connection last time through the main loop
const unsigned long postingInterval = 10000;                // delay between updates to Cosm.com

String DataString = "";                                     // stringa per invio dati
char Buffer[10];                                            // buffer per dftostr()

int CaldaiaStato = 0;                                       // INGRESSO ANALOGICO PER CONTROLLO WEB STATO CALDAIA 
int VentolaStato = 0;                                       // INGRESSO ANALOGICO PER CONTROLLO WEB STATO CALDAIA 
float TempAria = 0.0;                                       // sensore di temperatura LM35DZ aria
float TempAcqua = 0.0;                                      // sensore di temperatura LM35DZ acqua

int SensorReading = 0;                                      // lettura sensori

void setup() {
  
  pinMode(A0, INPUT_PULLUP);                                // stato caldaia
  pinMode(A1, INPUT_PULLUP);                                // sensore di temperatura aria (LM35DZ)
  pinMode(A2, INPUT_PULLUP);                                // stato ventola 
  pinMode(A3, INPUT_PULLUP);                                // sensore di temperatura acqua (LM35DZ)

  pinMode(8, OUTPUT);                                       // relay caldaia ON/OFF
  pinMode(6, OUTPUT);                                       // relay caldaia ON/OFF (replica)
  
  pinMode(9, OUTPUT);                                       // relay ventola ON/OFF
  pinMode(5, OUTPUT);                                       // relay ventola ON/OFF (replica)

  Serial.begin(9600);

  if (Ethernet.begin(mac) == 0) {                           // start the Ethernet connection
    Ethernet.begin(mac, ip);                                // DHCP failed, so use a fixed IP address
    Serial.println("Failed to configure Ethernet using DHCP");
  }
}

void loop() {

  TempAria = analogRead(A1) * 0.5;                          // temperatura aria

  Serial.print("Temp. Aria: ");
  Serial.println(TempAria, 1);

  if ((TempAria > 0) and (TempAria < 35)) {
    digitalWrite(9, LOW);                                   // relay ventola OFF
    digitalWrite(5, LOW);                                   // relay ventola OFF (replica)
    Serial.println("Aria fredda - Ventola OFF"); 
  }
  else if ((TempAria > 35) and (TempAria < 100)) {
    digitalWrite(9, HIGH);                                  // relay ventola ON
    digitalWrite(5, HIGH);                                  // relay ventola ON (replica)
    Serial.println("Aria calda - Ventola ON");
  }

  TempAcqua = analogRead(A3) * 0.5 + 4;                     // temperatura acqua

  Serial.print("Temp. Acqua: ");
  Serial.println(TempAcqua, 1);

  if ((TempAcqua > 0) and (TempAcqua < 42)) {
    digitalWrite(8, HIGH);                                  // relay caldaia ON
    digitalWrite(6, HIGH);                                  // relay caldaia ON (replica)
    Serial.println("Acqua fredda - Caldaia ON"); 
  }
  else if ((TempAcqua > 42) and (TempAcqua < 100)) {
    digitalWrite(8, LOW);                                  // relay caldaia OFF
    digitalWrite(6, LOW);                                  // relay caldaia OFF (replica)
    Serial.println("Acqua Calda - Caldaia OFF");
  }

  CaldaiaStato = analogRead(A0);                           // stato caldaia 
  VentolaStato = analogRead(A2);                           // stato ventola

  DataString = "Sensor1,";
  DataString += FloatFormat(TempAria, 10, 1, false, true);
  DataString += "\nSensor2,";
  DataString += FloatFormat(TempAcqua, 10, 1, false, true);
  DataString += "\nsensor3,";
  DataString += String(CaldaiaStato, DEC);
  DataString += "\nsensor4,";
  DataString += String(VentolaStato, DEC);

  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 (millis() < lastConnectionTime) lastConnectionTime = millis();    // evita il blocco dopo 50gg poiché millis() si azzera

  if (!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
    sendData(DataString);
  }
  // store the state of the connection for next time through
  // the loop:
  lastConnected = client.connected();
}

// this method makes a HTTP connection to the server:

void sendData(String 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: ");
    client.println(thisData.length());

    // 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.println(thisData);
    Serial.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();
}

String FloatFormat(float X, char Size, unsigned char Decimal, boolean Plus, boolean AutoReduce) {

  char Buffer[Size + 1];

  String Z = dtostrf(X, Size, Decimal, Buffer);
  if (Plus && X > 0) Z[Z.lastIndexOf(' ')] = '+';
  if (AutoReduce) Z.trim();

  return Z;
}

Provo subito.
Grazie

Ciao Ettore,
ho caricato lo sketch sull'arduino che ho in studio, ma se vai vedere la mia pagina in cosm, vedrai che adesso abbiamo dei valori di temperatura molto sballati.
In compenso il refresh avviene ogni 50sec. circa...

@Ettore: sulla stringa hai ragionissimo, m'era sfuggito. Riguardo la libreria per il calcolo di alba e tramonto mi hai fatto ricordare una mail che mi hai mandato un po' di tempo fa. Però sarà opportuno ripescare il vecchio topi oppure aprirne uno nuovo o continuare per email.

Con Arduino puoi sommare un intero ad una stringa perchè le dovute conversioni vengono fatte dalla apposita libreria per le stringhe (fino a 4 cifre). Con i float non è stato implementato. Elvis alla fine si salvava perchè tramite l'assegnamento di un float ad int otteneva solo la parte intera del float...un piccolo spreco di variabili ma funzionale.

Bene, sono arrivato alla conclusione che i dati dalle due schede arduino che ho installato hanno unntenpo di refresh molto diverso perché lavorano a temperature diverse.
Come posso fare per avere un refresh ogni 30sec. circa? C'è un modo per inviare i dati a cosm ogni X cicli di lettura dei sensori?
Grazie

è vero che ci possono essere delle differenze per via della temperatura, ma parliamo di minuto al giorno a dir tanto, prendendo come base i dati del swrtc.
comunque in caso la soluzione è appunto un RTC, ovvero un piccolo orologio indipendente. Prendili che copensano la temperatura

Caspita, allora cosa può essere? ho invertito entrambi le schede ma ottengo lo stesso risultato, l'unica differenza è che uno dei sensori LM35 montati sull'impianto termosolare ha un cavo lungo 80cm circa. Per il resto è tutto identico.
Vedo che il led giallo (L) della scheda ethernet lampeggia veramente a frequenze diverse. E' molto più veloce sulla scheda che ho in laboratorio a 24°C, ma in effetti, oggi in centrale termica ci sono solo 28°C...
Non capisco dove sia il problema...

Ti sei accorto, vero, che nel mio sketch ho inviato nell'ordine Temp. Aria, Temp Acqua, Ventola e Caldaia?

In COSM ho notato che l'ordine è Temp. Aria, Ventola, Temp Acqua e Caldaia.

Quindi basta che rimetti a posto l'ordine nello sketch, scambiando la posizione di Temp Acqua e Ventola.

Comunque, credo proprio sia impossibile scendere al di sotto dei 50 s di refresh.

Ettore Massimo Albani

Ciao Ettore,
sull'Arduino che ho in studio ho ricaricato il file che mi hai passato, se vai a vedere il device "Ettore" su cosm (gelholder) noterai che le letture dei sensori LM35 danno dei valori molto strani.
Di positivo però è che il refresh avviene ogni 50sec. circa. (tempo ottimo).

Ho modificato il codice per calcolare meglio le temperature secondo le cartteristiche del tuo sensore (alim. 5V e range tra +2°C e 100°C).

Inoltre ho portato i due segnali "finti" analogici (Caldaia e Ventola) allo stato di digitali (0 e 1).

CI sarebbe un'altra cosa da fare, il "resampling" delle misure di temperatura per evitare il rumore, ma per ora prova così.

Ettore Massimo Albani

/* IDE 1.01
 Ethernet shield attached to pins 10, 11, 12, 13
 Arduino uno
 This code is in the public domain.
 */

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

#define APIKEY         "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"   // replace your Cosm api key here
#define FEEDID         XXXXX                                // replace your feed ID
#define USERAGENT      "TEST 2"                             // user agent is the project name

byte mac[] = {                                              // MAC address of Ethernet controller
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xBD};

IPAddress ip(192, 168, 11, 12);                             // IP address on your network here

EthernetClient client;                                      // initialize the library instance:

// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:

// IPAddress server(216, 52, 233, 121);                        // numeric IP for api.cosm.com
char server[] = "api.cosm.com";                             // name address for Cosm API

unsigned long lastConnectionTime = 0;                       // last time you connected to the server, in milliseconds
boolean lastConnected = false;                              // state of the connection last time through the main loop
const unsigned long postingInterval = 10000;                // delay between updates to Cosm.com

String DataString = "";                                     // stringa per invio dati
char Buffer[10];                                            // buffer per dftostr()

int CaldaiaStato = 0;                                       // INGRESSO ANALOGICO PER CONTROLLO WEB STATO CALDAIA 
int VentolaStato = 0;                                       // INGRESSO ANALOGICO PER CONTROLLO WEB STATO CALDAIA 
float TempAria = 0.0;                                       // sensore di temperatura LM35DZ aria
float TempAcqua = 0.0;                                      // sensore di temperatura LM35DZ acqua

int SensorReading = 0;                                      // lettura sensori

void setup() {

  analogReference(DEFAULT);                                 // DEFAULT (5V), INTERNAL (1,1V), EXTERNAL (0÷5V)

  pinMode(A0, INPUT_PULLUP);                                // stato caldaia
  pinMode(A1, INPUT_PULLUP);                                // sensore di temperatura aria (LM35DZ) alim. 5V
  pinMode(A2, INPUT_PULLUP);                                // stato ventola 
  pinMode(A3, INPUT_PULLUP);                                // sensore di temperatura acqua (LM35DZ) alim. 5V

  pinMode(8, OUTPUT);                                       // relay caldaia ON/OFF
  pinMode(6, OUTPUT);                                       // relay caldaia ON/OFF (replica)

  pinMode(9, OUTPUT);                                       // relay ventola ON/OFF
  pinMode(5, OUTPUT);                                       // relay ventola ON/OFF (replica)

  Serial.begin(9600);

  if (Ethernet.begin(mac) == 0) {                           // start the Ethernet connection
    Ethernet.begin(mac, ip);                                // DHCP failed, so use a fixed IP address
    Serial.println("Failed to configure Ethernet using DHCP");
  }
}

void loop() {

  CaldaiaStato = analogRead(A0);                            // stato caldaia 
  delayMicroseconds(120);                                   // 120 µs (min time reading = 100 µs x channel) 

  TempAria = analogRead(A1) * (100 - 2) / 1024 + 2;         // temperatura aria in °C (10 mV/°C, range +2°C - +100°C)
  delayMicroseconds(120);                                   // 120 µs (min time reading = 100 µs x channel) 

  VentolaStato = analogRead(A2);                            // stato ventola
  delayMicroseconds(120);                                   // 120 µs (min time reading = 100 µs x channel) 

  TempAcqua = analogRead(A3) * (100 - 2) / 1024 + 2;        // temperatura acqua in °C (10 mV/°C, range +2°C - +100°C)
  delayMicroseconds(120);                                   // 120 µs (min time reading = 100 µs x channel) 

  CaldaiaStato = map(CaldaiaStato, 0, 1023, 0, 1);          
  VentolaStato = map(VentolaStato, 0, 1023, 0, 1);

  Serial.print("Temp. Aria: ");
  Serial.println(TempAria, 1);

  if ((TempAria > 0) and (TempAria < 35)) {
    digitalWrite(9, LOW);                                   // relay ventola OFF
    digitalWrite(5, LOW);                                   // relay ventola OFF (replica)
    Serial.println("Aria fredda - Ventola OFF"); 
  }
  else if ((TempAria > 35) and (TempAria < 100)) {
    digitalWrite(9, HIGH);                                  // relay ventola ON
    digitalWrite(5, HIGH);                                  // relay ventola ON (replica)
    Serial.println("Aria calda - Ventola ON");
  }

  Serial.print("Temp. Acqua: ");
  Serial.println(TempAcqua, 1);

  if ((TempAcqua > 0) and (TempAcqua < 42)) {
    digitalWrite(8, HIGH);                                  // relay caldaia ON
    digitalWrite(6, HIGH);                                  // relay caldaia ON (replica)
    Serial.println("Acqua fredda - Caldaia ON"); 
  }
  else if ((TempAcqua > 42) and (TempAcqua < 100)) {
    digitalWrite(8, LOW);                                  // relay caldaia OFF
    digitalWrite(6, LOW);                                  // relay caldaia OFF (replica)
    Serial.println("Acqua Calda - Caldaia OFF");
  }

  DataString = "TempAria,";
  DataString += FloatFormat(TempAria, 10, 1, false, true);
  DataString += "\nVentola,";
  DataString += String(VentolaStato, DEC);
  DataString += "\nTempAcqua,";
  DataString += FloatFormat(TempAcqua, 10, 1, false, true);
  DataString += "\nCaldaia,";
  DataString += String(CaldaiaStato, DEC);

  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 (millis() < lastConnectionTime) lastConnectionTime = millis();    // evita il blocco dopo 50gg poiché millis() si azzera

  if (!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
    sendData(DataString);
  }
  // store the state of the connection for next time through
  // the loop:
  lastConnected = client.connected();
}

// this method makes a HTTP connection to the server:

void sendData(String 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: ");
    client.println(thisData.length());

    // 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.println(thisData);
    Serial.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();
}

String FloatFormat(float X, char Size, unsigned char Decimal, boolean Plus, boolean AutoReduce) {

  char Buffer[Size + 1];

  String Z = dtostrf(X, Size, Decimal, Buffer);
  if (Plus && X > 0) Z[Z.lastIndexOf(' ')] = '+';
  if (AutoReduce) Z.trim();

  return Z;
}