Arduino Code – Logging

Needing to write output to the Arduino IDE’s ‘Serial Monitor’ is something you might find yourself doing a lot. It’s one of the easiest ways of giving feedback on variables, and is invaluable when it comes to debugging.

To output content you can use code like this:

Serial.println("Hello world");

All good so far. How about if you want to output a variable? That’s slightly more work…


Adding more variables is simple, but before long I find myself filling up my screen with these ‘print’ lines – Is there a better way?

Well I decided there was – I have created some handy macros which will help do this for you:

#define LOG(a) Serial.println(a)
#define LOG1(a) Serial.println(a)
#define LOG2(a, b) { Serial.print(a); Serial.print(","); Serial.println(b); }
#define LOG3(a, b, c) { Serial.print(a); Serial.print(","); Serial.print(b); Serial.print(","); Serial.println(c); }
#define LOG4(a, b, c, d) { Serial.print(a); Serial.print(","); Serial.print(b); Serial.print(","); Serial.print(c); Serial.print(","); Serial.println(d); }

(See my earlier article on how to put this code into its own header file, to make it even easier to use in your projects.)

Now you can output much more concisely:

LOG("Hello world");
LOG2("Angle:", my_angle);
LOG4("Position", x, y, z);

Leave a Reply

Your email address will not be published.