Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arduino Serial.print() optimization

unsigned long current_millis_value = 0;
unsigned long previous_millis_value = 0;
unsigned long m = 0;
unsigned int seconds = 0;
unsigned int minutes = 0;
unsigned int hours = 0;

unsigned long clockTimeStart = 1800000; //30 Minutes
unsigned long currentClockTime;

void loop() {
    current_millis_value = millis();
    currentClockTime -= current_millis_value - previous_millis_value;
    previous_millis_value = current_millis_value;

    minutes = (currentClockTime / 1000 / 60);
    seconds = (currentClockTime / 1000) % 60;
    m = (currentClockTime % 100);

    Serial.print(minutes);
    Serial.print(":");
    Serial.print(seconds);
    Serial.print(":");
    Serial.println(m);
}

I'm getting a gap in times between serial writes of anywhere from 9-11 ms per serial line written. Is there a way to optimize the Serial.print() method to allow writing of multiple values across types of long and String values?

Example (this is not valid but along the lines of what I'm thinking):

Serial.print(minutes + ":" + seconds + ":" + m);

I know this isn't JavaScript I'm working in - just looking for optimization possibilities for the writing process. I know that MOD can be expensive but just doing the simple subtraction and writing out the value of currentClockTime leaves me with a gap time of 6-7 ms.

like image 933
Jeff Avatar asked Feb 24 '26 14:02

Jeff


2 Answers

The arduino has a semi-java like string concatenation. I have no idea if this will get you any speed up, but it will concatenate everything into one string before sending it.

String package = "" + minutes;
package += ":"+seconds;
package += ":"+m;
Serial.print(package);

If you're able to reconstruct the string on the other side, perhaps a better course of action is to use Serial.Write and send the raw data, then reconstruct the String on the receiving side. This would reduce the amount of data you send each loop from 5-10 bytes to 3-4 bytes.

like image 125
helloworld922 Avatar answered Feb 26 '26 04:02

helloworld922


Any way to pre-convert everything to a string value so you can write out the entire string at once? For instance, use something like a snprintf() function to write into a pre-allocated char[] that you then print out in one call to Serial.print()?

So for instance:

char buffer[32];
snprintf(buffer, 32, "%u : %u : %lu", minutes, seconds, m);
Serial.print(buffer);

--Jason

like image 37
Jason Avatar answered Feb 26 '26 04:02

Jason