Go Down

Topic: Time and TimeAlarms Libraries – Ask here for help or suggestions (Read 219503 times) previous topic - next topic

karacayali

I have to wonder why you think that "." id OK in building the String, but "0" is not.
Fixed.


The SD class needs a 512 byte buffer to hold data to write to the card. On a Uno, that is 25% of the available memory. Other classes need memory, too.
How much memory TimeAlarms library needs to run? I got my Mega. Timestamp worked with millis. But functions from TimeAlarms library don't work. I haven't included control codes yet. They work seperately. I will include them if I manage to run a Web server with Time alarms.

Sketch uses 23,314 bytes (9%) of program storage space. Maximum is 253,952 bytes.
Global variables use 1,627 bytes (19%) of dynamic memory, leaving 6,565 bytes for local variables. Maximum is 8,192 bytes.

Code: [Select]

#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <Time.h>
#include <TimeLib.h>
#include <TimeAlarms.h>

#define REQ_BUF_SZ   60    // size of buffer used to capture HTTP requests
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 200);
EthernetServer server(80);         // create a server at port 80
File webFile;                      // the web page file on the SD card
char HTTP_req[REQ_BUF_SZ] = {0};   // buffered HTTP request stored as null terminated string
char req_index = 0;                // index into HTTP_req buffer

int x;

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 2000;
String currentTime = "";

void setup()
{

  setTime(8,25,53,8,1,2016); // hr,min,sec,day,month,yr);

  Alarm.alarmRepeat(8,26,0, MorningAlarm);  // 8:30am every day
  Alarm.timerRepeat(2, Repeats); 
 
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);    // disable Ethernet chip
 
  // for debugging
  Serial.begin(9600);     
  Serial.println("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;    // init failed
  }
  Serial.println("SUCCESS - SD card initialized.");
  if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find index.htm file!");
    return;  // can't find index file
  }
  Serial.println("SUCCESS - Found index.htm file.");
   
  Ethernet.begin(mac, ip);  // initialize Ethernet device
  server.begin();           // start to listen for clients
}

void loop()
{

//  currentMillis = millis();
//  if(currentMillis - previousMillis > interval) {
//    previousMillis = currentMillis;
//    timee();
//  }
 
  EthernetClient client = server.available();  // try to get client
   
  if (client) {  // got client?
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {   // client data available to read
        char c = client.read(); // read 1 byte (character) from client
         if (req_index < (REQ_BUF_SZ - 1)) {        // -- limit the size of the stored received HTTP request -- buffer first part of HTTP request in HTTP_req array (string) - leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
          HTTP_req[req_index] = c;          // save HTTP request character
          req_index++;
        }
        if (c == '\n' && currentLineIsBlank) {     // last line of client request is blank and ends with \n -- respond to client only after last line received
          client.println("HTTP/1.1 200 OK");    // send a standard http response header
          if (StrContains(HTTP_req, "ajax_inputs")) {   // remainder of header follows below, depending on if web page or XML page is requested Ajax request - send XML file
            client.println(F("Content-Type: text/xml"));   // send rest of HTTP header
            client.println(F("Connection: keep-alive"));
            client.println();
            WebRoleCalistir();
            XMLGonder(client);       // send XML file containing input states
          }
          else {  // web page request
            client.println(F("Content-Type: text/html"));       // send rest of HTTP header
            client.println(F("Connection: keep-alive"));
            client.println();
            webFile = SD.open("index.htm");        // open web page file
            if (webFile) {
              while (webFile.available()) {
                client.write(webFile.read()); // send web page to client
              }
              webFile.close();
            }
          }
         
          Serial.print(HTTP_req);   // display received HTTP request on serial port
          req_index = 0;    // reset buffer index and all buffer elements to 0
          StrClear(HTTP_req, REQ_BUF_SZ);
          break;
        }
       
        if (c == '\n') {          // every line of text received from the client ends with \r\n
          currentLineIsBlank = true;    // last character on line of received text  // starting new line with next character read
        }
        else if (c != '\r') {
          currentLineIsBlank = false;     // a text character was received from client
        }
       
      } // end if (client.available())
    } // end while (client.connected())
    delay(1);      // give the web browser time to receive the data
    client.stop(); // close the connection
  } // end if (client)

  //AmpulKontrol(); 
}

void MorningAlarm() {
  Serial.println("Alarm: - MorningAlarm");
  timee();
}

void Repeats() {
  Serial.println("Repeats");
  timee();
}


void timee() {

    currentTime = "";
    if (day()<10){ currentTime += "0" + String(day()); }
      else { currentTime += String(day()); }
    if (month()<10){ currentTime += ".0" + String(month()); }
      else { currentTime += "." + String(month()); }
    currentTime += "." + String(year()) + " ";
    if (hour()<10){ currentTime += "0" + String(hour()); }
    else { currentTime += String(hour()); }
    if (minute()<10){ currentTime += ":0" + String(minute()); }
    else { currentTime += ":" + String(minute()); }
    if (second()<10){ currentTime += ":0" + String(second()); }
    else { currentTime += ":" + String(second()); }
   
    Serial.print("2 seconds passed. Time is: ");
    Serial.println(currentTime);
 
}



void StrClear(char *str, char length)     // sets every element of str to 0 (clears array)
{
  for (int i = 0; i < length; i++) {
    str[i] = 0;
  }
}


char StrContains(char *str, char *sfind)    // searches for the string sfind in the string str - returns 1 if string found - returns 0 if string not found
{
  char found = 0;
  char index = 0;
  char len;

  len = strlen(str);

  if (strlen(sfind) > len) {
    return 0;
  }
  while (index < len) {
    if (str[index] == sfind[found]) {
      found++;
      if (strlen(sfind) == found) {
        return 1;
      }
    }
    else {
      found = 0;
    }
    index++;
  }

  return 0;
}


void WebRoleCalistir(void) 
{

x = 4;

}


void XMLGonder(EthernetClient cl)     
{

  cl.print("<?xml version = \"1.0\" ?>");
  cl.print("<inputs>");

  cl.print("<states>");
    cl.print("x");
  cl.println("</states>");

  cl.print("</inputs>");
}




Keep them out, with the F() macro.
client.println(F("Connection: keep-alive"));
Fixed.

while (webFile.available()) {
   client.write(webFile.read()); // send web page to client }
Sending a packet containing one character is incredibly inefficient. Use an array, and read and send at least 32 characters per packet.
I couldn't understand that..


Connect your ethernet shield to a wifi router and check out HMI droid (also available for iphone). You can control your entire home from your phone.
I tried Blynk. But I have to pay to create my whole Project. I didn't like the interface of HMI droid. Bu I'll give a chance after your suggestion. I may try to make my own app or get a Raspberry Pi fow Web server. I am confused.

PaulS

Quote
I couldn't understand that..
Suppose you want to write a letter to your mother. You could write one word per page, fold the page up, put it in an envelope, address it, stamp it, and mail it.

Or, you could write several words per page.

Which would be more efficient? Which would be cheaper?

Code: [Select]
String currentTime = "";
Get rid of the stupid Strings. There is NO reason to piss away resources.

Code: [Select]
  Alarm.alarmRepeat(8,26,0, MorningAlarm);  // 8:30am every day
Bullshit.

Code: [Select]

//  currentMillis = millis();
//  if(currentMillis - previousMillis > interval) {
//    previousMillis = currentMillis;
//    timee();
//  }

When you are writing to your mother, one word per page, would you send her all the crossed out words?

Code: [Select]
          StrClear(HTTP_req, REQ_BUF_SZ);
You do not understand what NULL-terminated means, do you? If people blow through the stop sign at the end of the street, would putting up 12 stop signs make any difference?

Code: [Select]
void timee() {

    currentTime = "";
    if (day()<10){ currentTime += "0" + String(day()); }
      else { currentTime += String(day()); }
    if (month()<10){ currentTime += ".0" + String(month()); }
      else { currentTime += "." + String(month()); }
    currentTime += "." + String(year()) + " ";
    if (hour()<10){ currentTime += "0" + String(hour()); }
    else { currentTime += String(hour()); }
    if (minute()<10){ currentTime += ":0" + String(minute()); }
    else { currentTime += ":" + String(minute()); }
    if (second()<10){ currentTime += ":0" + String(second()); }
    else { currentTime += ":" + String(second()); }
   
    Serial.print("2 seconds passed. Time is: ");
    Serial.println(currentTime);
 
}

Why is this appropriate at 8:30?

Count how many useless calls to the String constructor and destructor you are causing here. Compare that to ONE call to sprintf().
The art of getting good answers lies in asking good questions.

karacayali

Why is this appropriate at 8:30?
timee function was just copy paste. I need alarms because I have to change the mod variable at specific times for heating control. For example every midnight the mod should change to sleep mode if mod type is automatic.
Code: [Select]

Alarm.alarmRepeat(23,45,0, alarm1);

void alarm1() {  //evernight 23:45:00
    if (modType==0){  //if automatic mode
        currentMod = 2; //1-Home 2-Sleep 3-Outside
      }
}



StrClear(HTTP_req, REQ_BUF_SZ);
You do not understand what NULL-terminated means, do you?
True I have no idea. I am not a programmer. Trying to learn. I couldn't learn much about this HTTP thing. Coppied from another project.

I removed all strings and comments. Still not working. The problem is not the strings in timestamp.

Code: [Select]


#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include <Time.h>
#include <TimeLib.h>
#include <TimeAlarms.h>

#define REQ_BUF_SZ   60
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 200);
EthernetServer server(80);
File webFile;
char HTTP_req[REQ_BUF_SZ] = {0};
char req_index = 0;

int x;

void setup()
{

  setTime(8,25,53,8,1,2016);

  Alarm.alarmRepeat(8,26,0, MorningAlarm);
  Alarm.timerRepeat(2, Repeats);
  
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  
  Serial.begin(9600);
  Serial.println("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;
  }
  Serial.println("SUCCESS - SD card initialized.");
  if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find index.htm file!");
    return;
  }
  Serial.println("SUCCESS - Found index.htm file.");
  
  Ethernet.begin(mac, ip);
  server.begin();
}

void loop()
{
  
  EthernetClient client = server.available();
    
  if (client) {
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
         if (req_index < (REQ_BUF_SZ - 1)) {
          HTTP_req[req_index] = c;      
          req_index++;
        }
        if (c == '\n' && currentLineIsBlank) {
          client.println("HTTP/1.1 200 OK");  
          if (StrContains(HTTP_req, "ajax_inputs")) {
            client.println(F("Content-Type: text/xml"));
            client.println(F("Connection: keep-alive"));
            client.println();
            WebRoleCalistir();
            XMLGonder(client);
          }
          else {
            client.println(F("Content-Type: text/html"));
            client.println(F("Connection: keep-alive"));
            client.println();
            webFile = SD.open("index.htm");  
            if (webFile) {
              while (webFile.available()) {
                client.write(webFile.read());
              }
              webFile.close();
            }
          }
          
          Serial.print(HTTP_req);  
          req_index = 0;  
          StrClear(HTTP_req, REQ_BUF_SZ);
          break;
        }
        
        if (c == '\n') {        
          currentLineIsBlank = true;  
        }
        else if (c != '\r') {
          currentLineIsBlank = false;    
        }
        
      }
    }
    delay(1);    
    client.stop();
  }


}

void MorningAlarm() {
  Serial.println("Alarm: - MorningAlarm");
}

void Repeats() {
  Serial.println("Alarm: - Repeats");
}




void StrClear(char *str, char length)  
{
  for (int i = 0; i < length; i++) {
    str[i] = 0;
  }
}


char StrContains(char *str, char *sfind)
{
  char found = 0;
  char index = 0;
  char len;

  len = strlen(str);

  if (strlen(sfind) > len) {
    return 0;
  }
  while (index < len) {
    if (str[index] == sfind[found]) {
      found++;
      if (strlen(sfind) == found) {
        return 1;
      }
    }
    else {
      found = 0;
    }
    index++;
  }

  return 0;
}


void WebRoleCalistir(void)  
{

x = 4;

}


void XMLGonder(EthernetClient cl)    
{

  cl.print("<?xml version = \"1.0\" ?>");
  cl.print("<inputs>");

  cl.print("<states>");
    cl.print("x");
  cl.println("</states>");

  cl.print("</inputs>");
}




Result;

Initializing SD card...
SUCCESS - SD card initialized.
SUCCESS - Found index.htm file.

PaulS

Quote
The problem is not the strings in timestamp.
Well that narrows it down.

How is the Alarm class supposed to know that time has passed? You need to go back an re-read the documentation/examples for the Alarm class.
The art of getting good answers lies in asking good questions.

odometer

True I have no idea. I am not a programmer. Trying to learn. I couldn't learn much about this HTTP thing. Coppied from another project.
If you copy things that you don't understand, and try to put them together without understanding how to put them together, that can lead to trouble. Now you are experiencing this kind of trouble.

Quote
I removed all strings and comments. Still not working. The problem is not the strings in timestamp.
It is good that you have done this. This is one way that programmers try to solve problems. They try to find out exactly what is causing the problem.


It seems that you have a big project in mind. Because it is such a big project, you should learn how to program, and not just copy and paste. Looking at examples is good, but you need to understand how they work, and how to modify them to suit your own needs. Also, know that some examples are poorly written, and not good to use.

Welsyntoffie

If you setup your own Blynk server at your home then you dont need to pay anything.

dgidney

Hi there,

I am super new to Arduino.

I am trying to use the time library to create a 60 second loop of on and off signals for an LED. Printing the second works perfect, getting 0-60 and then an overflow back to zero, but once I try to use second() in an if statement, the LED is always on. Am I using second() wrong?



#include <Time.h>
#include <TimeLib.h>



void setup() {
  // put your setup code here, to run once:
Serial.begin (9600);
  // set the digital pin as output:
  pinMode(LED_BUILTIN, OUTPUT);
   digitalWrite(LED_BUILTIN, LOW);


}

void loop() {
  // put your main code here, to run repeatedly:

if (second() == 5); {
 digitalWrite(LED_BUILTIN, HIGH);
}




Serial.println (second());
}

UKHeliBob

Quote
once I try to use second() in an if statement, the LED is always on
Where do you turn the LED off in your code apart from in the setup() function ?

Check the syntax of the if command too.  Should the semicolon at the end be there I wonder ...
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

PaulS

Code: [Select]
if (second() == 5); {
Can you find a single other example where an if statement ends in a semi-colon?
The art of getting good answers lies in asking good questions.

UKHeliBob

Can you find a single other example where an if statement ends in a semi-colon?
Yes, I have seen plenty on here.  All of them wrong.
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

PaulS

The art of getting good answers lies in asking good questions.

Pearo

Hi folks, just find a very minor issue with Time when syncing with a GPS.

to recreate:
make a call to hour();
make a call to setTime();
make a call to adjustTime(timezoneCorrection);
make a call to hour();

occasionally hour() will return the time not adjusted for the timezone correction if the call is made within a second of calling adjustTime().

fix:
change refreshCache to force refresh
Code: [Select]


void refreshCache(time_t t, bool bForce = false) {
  if (t != cacheTime) {
    breakTime(t, tm);
    cacheTime = t;
  }
}


add new call to refreshCache to both setTime() and adjustTime()

Code: [Select]

void setTime(int hr,int min,int sec,int dy, int mnth, int yr){
 // year can be given as full four digit year or two digts (2010 or 10 for 2010); 
 //it is converted to years since 1970
  if( yr > 99)
      yr = yr - 1970;
  else
      yr += 30; 
  tm.Year = yr;
  tm.Month = mnth;
  tm.Day = dy;
  tm.Hour = hr;
  tm.Minute = min;
  tm.Second = sec;
  setTime(makeTime(tm));
 
  refreshCache(sysTime,true);
}

void adjustTime(long adjustment) {
  sysTime += adjustment;
 
  refreshCache(sysTime,true);
}

h35am

Is there an easy way to time stamp.
I'm trying to put a time stamp next to my sensor reading but I don't know how to get this done.
Any help is greatly appreciated.

 
Code: [Select]
dateTijd = String(year() + "/" + month() +"/"+ day() +"-" + hour() +":" + minute() + ":" + second())
 message = String( paalID + ":" + temperatuurID + ":" + temperature*16 + ":" + temperature + ":" + dateTijd);
 Serial.println( message );

UKHeliBob

What does the snippet of code that you posted do ?  What do you want the output to look like ?  Where will it be output to ?
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

PaulS

Quote
Is there an easy way to time stamp.
Yes. It does NOT involve pissing away resources using the String class.

sprintf() is more than you need, but it IS easy to use.
The art of getting good answers lies in asking good questions.

Go Up