Skip to content

Commit 0dcdcc8

Browse files
committed
Rework string handling to check buffer lengths
1 parent 2baabcd commit 0dcdcc8

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

mobile-sense/mobile-sense.ino

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99

1010
#define UPDATE_PERIOD_IN_MILLISECONDS 2000
1111

12+
#define TIMESTAMP_LENGTH 20
13+
#define LOCATION_LENGTH 18
14+
#define TEMPERATURE_LENGTH 21
15+
1216
// For hardware serial 1 (recommended):
1317
// GPS TX to Arduino Due Serial1 RX pin 19
1418
// GPS RX to Arduino Due Serial1 TX pin 18
@@ -75,7 +79,7 @@ void setupThermocouples(void) {
7579
SPI.begin(CS1);
7680
SPI.begin(CS2);
7781

78-
Serial.println('Thermocouples initialized.');
82+
Serial.println("Thermocouples initialized.");
7983
}
8084

8185
void setupXBee(void) {
@@ -160,20 +164,29 @@ void loop()
160164
if (millis() - timer > UPDATE_PERIOD_IN_MILLISECONDS) {
161165
timer = millis(); // reset the timer
162166

163-
int chars_formatted = 0;
164-
char timestamp[25];
165-
char location[25];
166-
char temperatures[25];
167+
int timestamp_len = 0;
168+
int location_len = 0;
169+
int temperature_len = 0;
170+
int output_len = 0;
171+
172+
char timestamp[TIMESTAMP_LENGTH + 1];
173+
char location[LOCATION_LENGTH + 1];
174+
char temperatures[TEMPERATURE_LENGTH + 1];
167175
char output[100];
168176

169-
chars_formatted = sprintf(timestamp, "20%02d-%02d-%02dT%02d:%02d:%02dZ", GPS.year, GPS.month, GPS.day, GPS.hour, GPS.minute, GPS.seconds);
177+
timestamp_len = sprintf(timestamp, "20%02d-%02d-%02dT%02d:%02d:%02dZ", GPS.year, GPS.month, GPS.day, GPS.hour, GPS.minute, GPS.seconds);
170178
if(GPS.fix) {
171-
chars_formatted = sprintf(location, "%4f%c, %4f%c", GPS.latitude, GPS.lat, GPS.longitude, GPS.lon);
179+
location_len = sprintf(location, "%4f%c | %4f%c", GPS.latitude, GPS.lat, GPS.longitude, GPS.lon);
180+
} else {
181+
location_len = sprintf(location, "Location | unknown");
182+
}
183+
temperature_len = sprintf(temperatures, "%03.2f | %03.2f | %03.2f", readThermocouple(CS0), readThermocouple(CS1), readThermocouple(CS2));
184+
185+
if(timestamp_len == TIMESTAMP_LENGTH && location_len == LOCATION_LENGTH && temperature_len == TEMPERATURE_LENGTH) {
186+
output_len = sprintf(output, "%s | %s | %s\r\n", timestamp, location, temperatures);
172187
} else {
173-
chars_formatted = sprintf(location, "Location unknown");
188+
output_len = sprintf(output, "Something wrong with buffer lengths: %d, %d, %d\n", timestamp_len, location_len, temperature_len);
174189
}
175-
chars_formatted = sprintf(temperatures, "%03.2f, %03.2f, %03.2f", readThermocouple(CS0), readThermocouple(CS1), readThermocouple(CS2));
176-
chars_formatted = sprintf(output, "%s | %s | %s\n", timestamp, location, temperatures);
177190
Serial.print(output);
178191
Serial2.print(output); // send to XBee
179192
}

0 commit comments

Comments
 (0)