I have arduino with SHT21, DHT21 and DS1307 and ethernet.
I'm trying to push sensor reading to cosm.com and sync DS1307 to NTP every hour.
while serial still active after ~6-8 hours it stops sending any data to cosm.
it looks like it happens right after NTP sync. I'm using arduino IDE 1.0.1 Arduino Mega 2560 and W5100 ethernet.
// libraries for ethershield
#include <SPI.h>
#include <Ethernet.h>
#if ARDUINO >= 100
#include <EthernetUdp.h> // New from IDE 1.0
#else
#include <Udp.h>
#endif
// libraries for realtime clock
#include <Wire.h>
#include <RTClib.h>
#include <stdlib.h>
#include "DHT.h"
#include <Ports.h>
#include <PortsSHT21.h>
#include <SHT2x.h>
#define DHTTYPE DHT21
#define DHTPIN 3
#define APIKEY "key removed" // your cosm api key
#define FEEDID feedID // your feed ID
#define USERAGENT "Cosm Arduino feed ()" // user agent is the project name
DHT dht(DHTPIN, DHTTYPE);
SHT21 hsensor (2); // pins A1 and D5 - Sensor 2
RTC_DS1307 RTC;
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
static uint8_t mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = {
192, 168, 1, 6 }; // if no DHCP so we set our own IP address
byte subnet[] = {
255, 255, 255, 0 }; // subnet mask
byte gateway[] = {
192, 168, 1, 1 }; // internet access via router
unsigned int localPort = 8888; // local port to listen for UDP packets
// find your local ntp server http://www.pool.ntp.org/zone/europe or
// http://support.ntp.org/bin/view/Servers/StratumTwoTimeServers
IPAddress timeServer(192, 43, 244, 18); // time.nist.gov NTP server
// byte timeServer[] = {193, 79, 237, 14}; // ntp1.nl.net NTP server
const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the message
byte pb[NTP_PACKET_SIZE]; // buffer to hold incoming and outgoing packets
int h1, h2;
DateTime cur_t;
#if ARDUINO >= 100
// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp; // New from IDE 1.0
#endif
EthernetClient client;
EthernetServer server(80);
IPAddress cosm_server(216,52,233,121); // numeric IP for api.cosm.com
//char server[] = "api.cosm.com"; // name address for cosm API
int lastConnectionTime; // last time you connected to the server, in milliseconds
void sendData(String thisData) {
// if there's a successful connection:
if (client.connect(cosm_server, 80)) {
client.flush();
Serial.println(F("Pushing Data to COSM"));
// send the HTTP PUT request:
client.print(F("PUT /v2/feeds/"));
client.print(FEEDID);
client.println(F(".csv HTTP/1.1"));
client.println(F("Host: api.cosm.com"));
client.print(F("X-ApiKey: "));
client.println(APIKEY);
client.print(F("User-Agent: "));
client.println(USERAGENT);
client.print(F("Content-Length: ") );
// calculate the length of the sensor reading in bytes:
client.println(thisData.length());
// last pieces of the HTTP PUT request:
client.println(F("Content-Type: text/csv"));
client.println(F("Connection: close"));
client.println();
// here's the actual content of the PUT request:
client.println(thisData);
client.flush();
client.stop();
lastConnectionTime = cur_t.minute();
}
else {
// if you couldn't make a connection:
Serial.println(F("connection failed"));
Serial.println(F(""));
Serial.println(F("disconnecting."));
client.flush();
client.stop();
}
// note the time that the connection was made or attempted:
// lastConnectionTime = millis();
}
////////////////////////////////////////////////////////////////////////////
// Updating time from NTP source ///////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
void NTPTimeSet()
{
Serial.print(F("RTC before: "));
PrintDateTime(RTC.now());
Serial.println();
// send an NTP packet to a time server
sendNTPpacket(timeServer);
// wait to see if a reply is available
delay(1000);
if ( Udp.parsePacket() ) {
// read the packet into the buffer
#if ARDUINO >= 100
Udp.read(pb, NTP_PACKET_SIZE); // New from IDE 1.0,
#else
Udp.readPacket(pb, NTP_PACKET_SIZE);
#endif
// NTP contains four timestamps with an integer part and a fraction part
// we only use the integer part here
unsigned long t4;
t4 = 0;
/// = t2 = t3 = t4 = 0;
for (int i=0; i< 4; i++)
{
t4 = t4 << 8 | pb[40+i];
}
float f4;
f4 = ((long)pb[44] * 256 + pb[45]) / 65536.0;
const unsigned long seventyYears = 2208988800UL;
t4 -= seventyYears;
PrintDateTime(DateTime(t4));
Serial.println(f4,4);
Serial.println();
// Adjust timezone and DST... in my case substract 4 hours for Chile Time
// or work in UTC?
t4 -= (4 * 3600L); // Notice the L for long calculations!!
t4 += 1; // adjust the delay(1000) at begin of loop!
if (f4 > 0.4) t4++; // adjust fractional part, see above
RTC.adjust(DateTime(t4));
Serial.print(F("RTC after : "));
PrintDateTime(RTC.now());
Serial.println();
Serial.println(F("done ..."));
Udp.flush();
}
else
{
Serial.println(F("No UDP available ..."));
}
}
void PrintDateTime(DateTime t)
{
char datestr[24];
sprintf(datestr, "%04d-%02d-%02d %02d:%02d:%02d ", t.year(), t.month(), t.day(), t.hour(), t.minute(), t.second());
Serial.print(datestr);
}
// 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(pb, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
pb[0] = 0b11100011; // LI, Version, Mode
pb[1] = 0; // Stratum, or type of clock
pb[2] = 6; // Polling Interval
pb[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
pb[12] = 49;
pb[13] = 0x4E;
pb[14] = 49;
pb[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
#if ARDUINO >= 100
// IDE 1.0 compatible:
Udp.beginPacket(address, 123); //NTP requests are to port 123
Udp.write(pb,NTP_PACKET_SIZE);
Udp.endPacket();
#else
Udp.sendPacket( pb,NTP_PACKET_SIZE, address, 123); //NTP requests are to port 123
#endif
}
void setup()
{
Serial.begin(9600);
Serial.println("Staring up...");
// start Ethernet and UDP
Ethernet.begin(mac); // For when you are directly connected to the Internet.
Serial.println(Ethernet.localIP());
Udp.begin(localPort);
Serial.println(F("network ..."));
// init RTC
Wire.begin();
RTC.begin();
Serial.println(F("rtc ..."));
Serial.print(F("Starting webserver....."));
Serial.println(F("done"));
dht.begin();
}
void loop()
{
// getting RTC time
cur_t = RTC.now();
h2 = cur_t.hour();
//COSM feed
if ( lastConnectionTime != cur_t.minute() ) {
// float h = dht.readHumidity();
// float t = dht.readTemperature();
float h1, t1;
hsensor.measure(SHT21::HUMI);
hsensor.measure(SHT21::TEMP);
hsensor.calculate(h1, t1);
float hum2 = (h1);
float temp2 = (t1);
char buffer[20];
String dataString = "sensor1,";
dataString += dtostrf(t1,6,2,buffer);
dataString += "\nsensor2,";
dataString += dtostrf(h1,6,2,buffer);
PrintDateTime(cur_t);
sendData(dataString);
}
// storing current hour in h2
// if h1 = h2 we can skip
if ( h1 != h2 ) {
NTPTimeSet();
h1 = cur_t.hour();
Serial.println( "Time updated..." );
}
}
Please advice.