Obiective:
Sensors measure (temperature, redox, PH, water level/presence etc..)
Drive (relays, light, dimmer, pump, elettrovalve etc..)
Event Management (WebBased, Mail, SMS, Light Segnal, Buzzer, LCD, etc..)
Logging (Record data history, webserver presentation, graph / twitter notification etc..)
Action (Manage complex action with multiple variables)

Code

The code has been compiled with ARDUINO IDE 0023
Not yet ported to ARDUINO IDE 1.0 ... waiting for some new library..
or take a look.

----------------------------------------------------------------------------------------------------------
------------------------------     VER 2.1  --------------------------------------------------------------
----------------------------------------------------------------------------------------------------------

//Loaded Libraries
#include <Ethernet.h>             //for ethernetshield
#include <EthernetDNS.h>
#include <SPI.h>                  //for ethernetshield also
#include <CONVERT.h>                 //fot float to ascii function
#include <EEPROM.h>
#include <DHT.h>
#include <math.h>
#include <Twitter.h>
//-----------Variables----------------------------------------------------------
#define SHARE_FEED_ID              17552      // the Pachube feed ID that shares your sensor data 
#define CONTROL_FEED_ID            17552      // feed ID of the Pachube controller feed 
#define UPDATE_INTERVAL            (unsigned long) 60000     // if the connection is good wait 60 seconds before updating again - should not be less than 5
#define RESET_INTERVAL             (unsigned long) 10000     // if the connection is bad wait 30 seconds before retry updating again - should not be less than 5
#define PACHUBE_API_KEY            "gtr3thsght3rhshIs-it-Not-Truetr3shs5trhrht" // fill in your API key 
//----------Metereology-----------------------------------------------------------
float calc_dewpoint(float h,float t)
//-------------------------------------------------------------------- 
{ float logEx,dew_point;
logEx=0.66077+7.5*t/(237.3+t)+(log10(h)-2);
dew_point = (logEx - 0.66077)*237.3/(0.66077+7.5-logEx);
return dew_point;
}
#define e(t,u)               (float)6.11 * (float) exp(5417.7530 * (float)((float) (1/273.16) - (float) (1/dew_point(t,u)))) // h = (0.5555)*(e - 10.0);
#define calc_humidex(t,u)    (float) (0.5555)*(float)(e(t,u) -10)  
//--------------------------------------------------------------------
// Humidex = (air temperature in Celcius) + h 
// for pachube datastream
float DataS0 = 0;  //Air Temperature Ouside
char    DataS0_char[10];  //Air Temperature Ouside Temp for Float to ascii conversion (display decimal and negative number)
int DataS1 = 0;  //
int DataS2 = 0;  //Soil Moisture 5cm
int DataS3 = 0;  //Soil Moisture 10cm
float DataS4 = 0;  //Air Temperature Inside
char    DataS4_char[10];  //Air Temperature Inside Temp for Float to ascii conversion (display decimal and negative number)
float DataS5 = 0;  //Air Humidity Outside
char    DataS5_char[10];  //Air Humidity Outside Temp for Float to ascii conversion (display decimal and negative number)
int DataS6 = 0;       //Irrigation Pump Status
float   DataS7 = 0;  //Air Humidity Inside
char    DataS7_char[10];  //Air Humidity Insite for Float to ascii conversion (display decimal number)
float   DataS8 = 0;  //Upload success vs failed
char    DataS8_char[10];  //Upload success vs failed for Float to ascii conversion (display decimal number)
float   DataS9 = 0;       //humdex index
char    DataS9_char[10];  //Upload success vs failed for Float to ascii conversion (display decimal number)
float   DataS10 = 0;      //dewpoint
char    DataS10_char[10];  //Upload success vs failed for Float to ascii conversion (display decimal number)
int     startupcount; 

// ethernet params  ---------------------------------------------------
  byte mac[] = { 0xCC, 0xAC, 0xBE, 0xEF, 0xFE, 0x91 };
  byte ip[] = { 172, 23, 96, 100   };
  byte gateway[] = { 172, 23, 96, 252   };
  byte subnet[] = { 255, 255, 255, 0   };
  byte remoteServer[] = { 173,203,98,29 };
  Client localClient(remoteServer, 80);
// ethernet statistics  -----------------------------------------------
  int failures = 0;
  int successfull = 1;
//Analog Input   ------------------------------------------------------
  int maxA0= 0;
  int minA0= 1023;
  int maxA1= 0;
  int minA1= 1023;
  int A0norm =0;
  int A1norm =0;
// others  ------------------------------------------------------------
int content_length; 
char buff[64];
int pointer = 0;
char *found; /////?????
char pachube_data[70];
boolean found_content = false;
boolean request_pause = false;
unsigned long last_connect;
unsigned long interval;
boolean reading_pachube = false;
Twitter twitter("296807387-TrJ5XBrYxFYH7mSnGMiUoU2IKhsz8Sq4VqGsCv4F");  //Twitter
char msg[140];
//onewire
#define DHTPIN_out 7     // what pin we're connected to
#define DHTPIN_in 6     // what pin we're connected to
#define DHTTYPE_in DHT22   // DHT 22  (AM2302)
#define DHTTYPE_out DHT22   // DHT 22  (AM2302)
DHT dht_in (DHTPIN_in, DHTTYPE_in);
DHT dht_out (DHTPIN_out, DHTTYPE_out);
//---------------------------------------------------END-Variables------------------------------
//----------------------------------------------------------------------------------------------
void setup()
{
  Serial.begin(115200); 
  pinMode(A0, INPUT);  
  pinMode(A1, INPUT);
//Startup Count
  startupcount = EEPROM.read(0);
  EEPROM.write(0, startupcount+1);  
  Serial.print("Ver Nio_Prj 2.1 StartUP count: ");
  Serial.println(startupcount);
// Start up the ONEWIRE DHT22 library
  dht_in.begin();
  dht_out.begin();
  setupEthernet(); 
//twitter startup message
sprintf(msg,"%s,%d","Arduino ver 2.1 is Online...Now! http://goo.gl/3YopU Reboot count:",startupcount);          //  twitter message
sendtwitter();  // send to twitter function
}

void loop()

//Serial.println("Void Loop - pre Pachube");
  ifwaiting();
//Serial.println("Void Loop - post Pachube");

}

void Humidity() {
  Serial.println("-------HUMIDITY -----------");
// read the analog in value and Convert range fron 1023-0 to 0-100 for umidity
  A0norm = 100-(analogRead(A0)/10.23); 
  A1norm = 100-(analogRead(A1)/10.23);
//A0norm = (A0norm+34); // Sensor Tuning
//A1norm = (A1norm+34); // Sensor Tuning
if (A0norm > maxA0){maxA0 = A0norm;}   // record max value of A0
if (A0norm < minA0){minA0 = A0norm;}   // record min value of A0
if (A1norm > maxA1){maxA1 = A1norm;}
if (A1norm < minA1){minA1 = A1norm;}
// Print over serial the recorded Value------------
  Serial.print("Umidity  5cm = " );                       
  Serial.print(A0norm);       
  Serial.print(" MIN-MAX = " );                       
  Serial.print(minA0);     
  Serial.print("-" );
  Serial.println(maxA0);
  Serial.print("Umidity 10cm = " );                       
  Serial.print(A1norm); 
  Serial.print(" MIN-MAX = " );                       
  Serial.print(minA1);
  Serial.print("-" );  
  Serial.println(maxA1);       
}
//-------------- One-wire temp ----------------------
void onewire () {
  
 Serial.println("-------  DHT 22 -----------");
  delay(1000);
//  Serial.print("Requesting data...");
    DataS4 = dht_in.readTemperature();   //Air Temperature Inside
    DataS7 = dht_in.readHumidity();      //Air Humdity Inside
  delay(1000);
//  Serial.println("-------ONEWIRE DHT22 OUT-----" );
    DataS0 = dht_out.readTemperature();  //Air Temperature Ouside
    DataS5 = dht_out.readHumidity();     //Air Humidity Ouside
 Serial.print("IN temp " );
  Serial.print(DataS4);
  Serial.print(" IN hum " );
  Serial.println(DataS7);
  Serial.print("OUT temp " );
  Serial.print(DataS0);
  Serial.print(" OUT hum " );
  Serial.println(DataS5);
  }

// --------------------------------------SETUP ETHERNET---------------
void setupEthernet()
{
  Serial.println("Setup ethernet...");
  Serial.print("Waiting till ");
  Serial.print(interval);
  Serial.print(" millis Intervall...");
  Ethernet.begin(mac, ip, gateway, subnet);
  Client remoteClient(255);
  delay(500);
  
}
// --------------------------------------CLEAN BUFFERS---------------
void clean_buffer() {

  Serial.println("Void clean_buffer"); 
  localClient.stop();
  pointer = 0;
  memset(buff,0,sizeof(buff)); 
//  
}
// --------------------------------------Restart Ethernet------------
void resetEthernet()
{
  localClient.stop();
  localClient.flush();
  Serial.println("------------------------------" );
  Serial.println("Connection Statistics ...");
  Serial.print("Failures:");
  Serial.println(failures);
  Serial.print("Successfull:");
  Serial.println(successfull);
  Serial.println("------------------------------" );
  Serial.println("Restart Ethernet...");
  Serial.println("------------------------------" );
  Serial.println("------------------------------" );
  setupEthernet();
}
// --------------------------------------TIME WAITING---------------------
void ifwaiting()
  {
    if (millis() < last_connect) last_connect = millis(); // avoid problem when counter reach limits
    if ((millis() - last_connect) > interval)
      {
      Serial.println("GO !");
      reading_pachube = false;
      GetData();
      }
  }
void metereology() 
  {
      DataS10 = calc_dewpoint(DataS5,DataS0);
//      DataS9  = calc_humidex(DataS5,DataS0);
      Serial.print("Apparent temperature (Humidex): ");
      Serial.println(DataS9);
      Serial.print("Drewpoint: ");
      Serial.println(DataS10);
   }     
// ---------------------------------------READING SENSORS VALUE----------
void GetData()
  {
    Serial.println("-------SENSOR READING:-------");
    Humidity();
    onewire();
    metereology();
// ---------------------------------------FORMATTING DATA TO SEND---------
 //    DataS0 = random(0, 0);  //Air Temperature Outside
      DataS1 = 0;                 //temp
      DataS2 = 0;                 //temp
 //    DataS2 = A1norm;            //Soil Moisture 5cm
      DataS2 = 0;        //Soil Moisture 5cm
 //    DataS3 = A0norm;          //Soil Moisture 10cm
      DataS3 = 0;        //Soil Moisture 5cm
 //    DataS4 = random(0, 32);  //Air Temperature Outside
 //    DataS5 = random(0, 0);  //Air Humidity Outside
      DataS6 = random(0, 0);;     //Irrigation Pump Status
 //    DataS7 = random(0, 100);  //Air Humidity Inside
      DataS8 = (100/(((float)successfull)+(float)(failures)))*(float)successfull; 
 //     DataS9 = 0;                  //humidex index
 //    DataS10 = 0;                //dewpoint

      ftoa(DataS0_char, DataS0, 1);  //convert float to ascii for temperature (display decimal and negative number)
      ftoa(DataS4_char, DataS4, 1);  //convert float to ascii fot temperature (display decimal and negative number)
      ftoa(DataS5_char, DataS5, 1);  //convert float to ascii for temperature (display decimal and negative number)
      ftoa(DataS7_char, DataS7, 1);  //convert float to ascii for temperature (display decimal and negative number)
      ftoa(DataS8_char, DataS8, 2);  //convert float to ascii for temperature (display decimal and negative number)
      ftoa(DataS9_char, DataS9, 2);//convert float to ascii for temperature (display decimal and negative number)
      ftoa(DataS10_char, DataS10, 2);//convert float to ascii for temperature (display decimal and negative number)
      Serial.println("-------STRING TO SEND--------" );
      sprintf(pachube_data,"%s,%d,%d,%d,%s,%s,%d,%s,%s,%s,%s",DataS0_char,DataS1,DataS2,DataS3,DataS4_char,DataS5_char,DataS6,DataS7_char,DataS8_char,DataS9_char,DataS10_char);
      Serial.println(pachube_data); 
      Serial.println("-------SENDING DATAS----------" ); 
    Pachube();
  }

void Pachube()
  {
    if (localClient.connect()) 
      {
//      Serial.println("Arduino is Connected to Pachube");
      content_length = strlen(pachube_data);
//  Serial.println("GET request to retrieve");

      localClient.print("GET /api/");
      localClient.print(CONTROL_FEED_ID);
      localClient.print(".csv HTTP/1.1\nHost: pachube.com\nX-PachubeApiKey: ");
      localClient.print(PACHUBE_API_KEY);
      localClient.print("\nUser-Agent: Arduino (Niomix controller v1.9)");
      localClient.println("\n");

//  Serial.println("finished GET now PUT, to update");

      localClient.print("PUT /api/");
      localClient.print(SHARE_FEED_ID);
      localClient.print(".csv HTTP/1.1\nHost: pachube.com\nX-PachubeApiKey: ");
      localClient.print(PACHUBE_API_KEY);
      localClient.print("\nUser-Agent: Arduino (Pachube controller v1.1)");
      localClient.print("\nContent-Type: text/csv\nContent-Length: ");
      localClient.print(content_length);
      localClient.print("\nConnection: close\n\n");
      localClient.print(pachube_data);
      localClient.print("\n");
//      Serial.println("Update OK post Completed");
      last_connect = millis();
      interval = UPDATE_INTERVAL;
      reading_pachube = true;
      }
    else 
      {
      Serial.print("Ethernet Down...\n");
      failures = failures++;
      reading_pachube = false;
      last_connect = millis(); 
      interval = RESET_INTERVAL;
      resetEthernet();
      }
// --------------------------------------- Grab Response -----
    while (reading_pachube)
      {
        while (localClient.available())
          {
          checkForResponse();
          } 
        if (!localClient.connected()) 
          {
          Serial.println("Process Completed");
          reading_pachube = false;
          interval = UPDATE_INTERVAL;
          resetEthernet();
          }
      } 
  }
// --------------------------------------- Check Response -----
void checkForResponse()
  {  
  char c = localClient.read();
  buff[pointer] = c;
  Serial.print(c); //--- Debug the HTTP response from pachube
    if (pointer < 64) pointer++;
      if (c == '\n') 
        {
        found = strstr(buff, "200 OK");
           if (found != 0)
            {
            Serial.println("Status 200 OK");
            successfull = successfull++;
       
            }
            else
            {
            Serial.println("Response Failed");
            failures = failures++;
            }
        buff[pointer]=0;
        clean_buffer(); 
        reading_pachube = false;
       }
  }
void sendtwitter()
  {
twitter.post(msg);
   }


Nessun commento:

Posta un commento