0

My program is a bit large and I'm worried about stability.

I need to print data to both a file and to my LCD. It's like this:

if (hour<10) {
 dataFile.print("0");
}
dataFile.print(hour, DEC);
dataFile.print(":");
if (minute<10) {
 dataFile.print("0");
}
dataFile.print(minute, DEC);
dataFile.print(":");
if (second<10) {
 dataFile.print("0");
}

Then

if (hour<10) {
 lcd.print("0");
}
lcd.print(hour, DEC);
lcd.print(":");
if (minute<10) {
 lcd.print("0");
}
lcd.print(minute, DEC);
lcd.print(":");
if (second<10) {
 lcd.print("0");
}

What is a smart way to make this shorter? Should I write a function to add the leading zero then another that does something like:

void printboth (thing) {
 dataFile.print(thing);
 lcd.print(thing);
}

good idea?

Jake C
1,0997 silver badges18 bronze badges
asked Aug 1, 2015 at 4:06
3
  • possible duplicate of What will use less memory, an array or if ... else? Commented Aug 2, 2015 at 7:52
  • You asked an almost identical question here: arduino.stackexchange.com/questions/13876/… where you start: I'm trying to make my sketch smaller. Please stick to one question for one topic to avoid splitting answers. Commented Aug 2, 2015 at 7:54
  • Give __attribute__((always_inline)) void printboth (thing) a try and see if it results in a smaller size. PS make sure you are using the latest version of the Arduino IDE. Commented Aug 2, 2015 at 15:46

1 Answer 1

1

You could format the data with snprintf:

char timestamp[9];
snprintf(timestamp, 9, "%02d:%02d:%02d", hour, minute, second);
dataFile.print(timestamp);
lcd.print(timestamp);

%02d in the snprintf format means "print at least 2 digits of this value and pad with leading zeros".

answered Aug 1, 2015 at 21:41
3
  • 1
    While true, note that *printf() will increase code size a lot. Commented Aug 1, 2015 at 21:47
  • Define "a lot". I make it an increase of 1046 bytes and the program is far more readable. Commented Aug 1, 2015 at 21:53
  • I'm making changes with the main goal of making the sketch smaller Commented Aug 2, 2015 at 1:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.