Extracting ints from a string on Arduino

arduino

I'm trying to extract ints from a String on an Arduino.

I'm using This DCF77 Library (.zip) and I get a date and time in this format:

DCF77DATA 2012012531819CET

This translates ito

DCF77DATA YYYYMMDDwhhmmTZ

with Y,M,D being the date, w the day of the week, and h and m being the time. This is always generated at the full minute, so seconds can be expected to be 0.

I've been trying various ways to get the hours and minutes (the date doesn't concern me at the moment) and put them into int variables. The latest method I tried looks like this:

  const char *v = dcf77.getDateTime();
  if (strcmp (v,"DCF77POLL") != 0) {
    Serial.println(v);
    String time = String(v);
    // DCF77DATA 2012012531819CET
    char h_str[3];
    time.substring(19,20).toCharArray(h_str, 2);
    Serial.print("H: ");
    Serial.println(h_str);
    char m_str[2];
    time.substring(21,23).toCharArray(m_str, 2);
    Serial.print("M: ");
    Serial.println(m_str);

    int hours = atoi(h_str);
    int minutes = atoi(m_str);
  }

This produces an interesting result … I get the first number of the time. When it's "23" minutes I get "2", hence the h_str[3]. I thought it was related to the string being 0-terminated, but it didn't help. Same for the hour.

Additionally, when I try to print out the int I don't get any output at all in the serial console, it seems as if the program just halts.

Best Answer

FYI, a question about parsing strings is more suitable for Stack Overflow. But I'll try anyways.

It is unclear to me where the time starts in that string, is it 1819CET? Where 18 is the hour in 24-hour clock format and 19 is minutes? Why is there a 3 after the date? I will assume 1819CET is the time here in HHMM{TIMEZONE} format since you've indicated that the starting index is 19 in your code, since 18 would've landed on the 3 in the string.

I am unfamiliar with the arduino library, so I will read their documentation first. Doing so reveals the following. An excerpt from here: http://arduino.cc/en/Reference/StringSubstring

Get a substring of a String. The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive (the corresponding character is not included in the substring). If the ending index is omitted, the substring continues to the end of the String.

This:

time.substring(19,20)

Will not include index 20. It will only return a string of 1 character.

To be safe, try these sizes for your char arrays: char h_str[3]; and char m_str[3];

And try calling like this:

char h_str[3];
char m_str[3];
time.substring(19,21).toCharArray(h_str, sizeof(h_str));
time.substring(21,24).toCharArray(m_str, sizeof(m_str));

I'm using sizeof() here because toCharArray() asks for the size of the buffer being passed in as specified here.