Arduino debugging 1: Getting your Arduino program to tell you where it has got to
/Why not have a mini-sequence of posts about Arduino debugging. Why not indeed?
Let’s start with a consideration of why the Arduino is hard to debug. The main reason is that you have no idea what is going in inside your code. If you’re writing a program on a computer with a keyboard and screen you can use any number of tools to find out what broke. There are debugging tools in Visual Studio that let you watch your program statements run one at a time and view (and even change) the values held in program variables.
The Arduino device has nothing like this. If you want to find out where your program has reached you have to put your own debugging statements. You end up writing things like this:
Serial.println(“I got this far”);
This prints out a message to the serial port tell us how far the program got. If you use the Arduino serial monitor you can view this message and know that at least the program has got this far.
This works and can be very useful. Developers call it “code instrumentation”. However, these messages can get confusing if you lots of them. What I’d really like to know is which line in the code that the program has got to. Then I can look this up in the source file. Turns out that this is quite easy. The compiler maintains two symbols called __FILE__ and __LINE__ which hold the name of the source file and the line number at that point in the program source.
So you can print this information out in your code:
Serial.print("Program is in file ");
Serial.print( __FILE__);
Serial.print(" at line " );
Serial.println(__LINE__);
These statements will tell you exactly where you have got to:
Program is in file C:\Users\Rob\Documents\Arduino\blah\blah.ino at line 12
This works well, but we can make it easier to use by putting the behaviour into a function:
void show_location(char * file, int line)
{
Serial.print("Program is in file ");
Serial.print(file);
Serial.print(" at line " );
Serial.println(line);
}
Now we can find out where our program has got to by just calling this function and passing the file and line values:
show_location(__FILE__, __LINE__);
We can now drop calls of show_location in our program to tell us exactly where the program has got to.
Of course, we have a problem in that we have to go and remove all these statements when we have finished debugging, but tomorrow I’ll show you how to make this easy too.