Skip to content

Commit b872431

Browse files
committed
Parse date and time strings using Arduino string class instead of sscanf
1 parent ed69e4f commit b872431

File tree

1 file changed

+56
-6
lines changed

1 file changed

+56
-6
lines changed

libraries/CurieRTC/examples/SetTime/SetTime.ino

Lines changed: 56 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@ int Hour, Min, Sec;
99
int Day, Month, Year;
1010

1111
void setup() {
12-
while(!Serial);
12+
while (!Serial);
1313
Serial.begin(9600);
14-
14+
1515
// get the date and time the compiler was run
1616
if (getDate(__DATE__) && getTime(__TIME__)) {
1717
Serial.print("Curie configured Time=");
@@ -53,24 +53,74 @@ void loop() {
5353

5454
bool getTime(const char *str)
5555
{
56-
if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
56+
// Get time from string of format HH:MM:SS
57+
String s = str;
58+
59+
int firstColonIndex = s.indexOf(":");
60+
int lastColonIndex = s.lastIndexOf(":");
61+
62+
if (firstColonIndex == -1) {
63+
// first colon not found
64+
return false;
65+
}
66+
67+
if (lastColonIndex == -1) {
68+
// last colon not found
69+
return false;
70+
}
71+
72+
if (firstColonIndex == lastColonIndex) {
73+
// only one colon, first and last index are the same
74+
return false;
75+
}
76+
77+
String hourString = s.substring(0, firstColonIndex);
78+
String minuteString = s.substring(firstColonIndex + 1, lastColonIndex);
79+
String secondString = s.substring(lastColonIndex + 1);
80+
81+
Hour = hourString.toInt();
82+
Min = minuteString.toInt();
83+
Sec = secondString.toInt();
84+
5785
return true;
5886
}
5987

6088
bool getDate(const char *str)
6189
{
62-
char monthString[12];
90+
// Get Date from string of format MMM DD YYYY
91+
String s = str;
92+
93+
int firstSpaceIndex = s.indexOf(" ");
94+
int lastSpaceIndex = s.lastIndexOf(" ");
95+
96+
if (firstSpaceIndex == -1) {
97+
// first space not found
98+
return false;
99+
}
63100

64-
if (sscanf(str, "%s %d %d", monthString, &Day, &Year) != 3) {
101+
if (lastSpaceIndex == -1) {
102+
// last space not found
65103
return false;
66104
}
67105

106+
if (firstSpaceIndex == lastSpaceIndex) {
107+
// only one space, first and last index are the same
108+
return false;
109+
}
110+
111+
String monthString = s.substring(0, firstSpaceIndex);
112+
String dayString = s.substring(firstSpaceIndex + 1, lastSpaceIndex);
113+
String yearString = s.substring(lastSpaceIndex + 1);
114+
68115
for (Month = 1; Month <= 12; Month++) {
69-
if (strcmp(monthString, monthName[Month - 1]) == 0) {
116+
if (monthString.equals(monthName[Month - 1])) {
70117
break;
71118
}
72119
}
73120

121+
Day = dayString.toInt();
122+
Year = yearString.toInt();
123+
74124
return (Month <= 12);
75125
}
76126

0 commit comments

Comments
 (0)