P1 freezes when counter reaches 1,000,000

I have an application that I’m trying to profile. I’ve added six calls to millis() throughout my loop to see how much time each of six activities (sensor reads, mostly) are taking. At the end of the loop I dump the data out via the UART. Everything works great until one of the timestamp values exceeds 1,000,000 by some small amount, then the system freezes.

Collecting the timestamps:

unsigned long ts1 = millis();
...
unsigned long ts6 = millis();

Printing the timestamps:

	char output[100];
	char *format = "{\"ts1\": %lu, \"ts2\": %lu, \"ts3\": %lu, \"ts4\": %lu, \"ts5\": %lu, \"ts6\": %lu}\n";
	int ret = sprintf(output, format, ts1, ts2, ts3, ts4, ts5, ts6);
	Serial1.printf(output);

It’s pretty obvious that this is some sort of overflow or format incompatibility, but I’m not really sure how to solve it. From what I can tell, “lu” is the proper format for a long unsigned integer. The variables should be able to hold values up to something north of 2,000,000,000.

Any ideas?

Just try to donate a few more bytes to your output string - with 1,000,000 you won’t have any problems, but as soon at least two of your ts# get into the 10,000,000 your buffer will be too short.

Also don’t try to Serial1.printf() but just Serial.print() - you already have formatted via sprintf().

In addition to that, I’d always recommend using snprintf(buf, sizeof(buf), "format", ...) to avoid writing past the end of your buffer.

6 Likes