:: How to Use the Print Class ::
If you are writing a library and you want to use the print functions - the same ones used in the Serial library - good news -- it's pretty easy! All of them are defined in a class simply called "Print." This tutorial will show you how to use the functions, both at the "for dummies" level and at the "how it works" level.
Assumptions: You are writing a Class within two files: a *.h and *.cpp. The *.h file contains the class definition, where it says
It's pretty easy. First, go to the *.h file and go to the section where you defined the name of your class after the word "class". Then, change it to this:
Now, in the public section, add this:
Save and close the *.h file, and open the *.cpp file. Add a new function, by adding this:
That's it!
Optional:
If it is convienent, you can also add things to do when given an entire string at one time, rather than just one letter. Do this by adding this to your *.h file
and this to your *.cpp file!
If you do that, it's also probably a good idea to add a function which takes an array of chars and a size, so add this to your *.h:
and this to your *.cpp
You can learn all about how it works by going to the folder with all the arduino things, then /hardware/arduino/cores/arduino/ and opening the files Print.h, Print.cpp. You can also look at an example of this -- an "extension" of the Print class -- by going to /libraries/LiquidCrystal/ and opening LiquidCrystal.h and LiquidCrystal.cpp
Basically, all of the functions in Print.cpp call each other until they get down to write(uint8_t), displaying a single character at a time. This write function is not defined in the Print class, and must be defined by the user. However, it also lets you define the two functions which are one level higher, because it could be easier for the user to display an entire string at once.
You can use these functions because of what you did in the class declaration in the *.h file. By writing "class blahblah : Print {", you are making the class blahblah an extension of the class Print, which makes it so that when the final user of your class initializes it, they also initialize the Print class. However, it also means that you can change those functions, which is what you are doing when adding the different write functions.