Thanks so much for sharing this information! This sort of thing has been discussed several times here on the Forum over the years, but this is the first time I can remember seeing a fully documented solution presented.
I have a couple of suggestions:
BRIOT_Patrick:
#define SKETCH_VERSION "1.0.2"
// | | |_______ Build version : Automatic control
// | |_________ Minor Version : Human control
// |___________ Major Version : Human control
I recommend following the semver specification in your versioning:
Build metadata MAY be denoted by appending a plus sign and a series of dot separated identifiers immediately following the patch or pre-release version. Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Build metadata SHOULD be ignored when determining version precedence. Thus two versions that differ only in the build metadata, have the same precedence. Examples: 1.0.0-alpha+001, 1.0.0+20130313144700, 1.0.0-beta+exp.sha.5114f85.
So it would look like this:
#define SKETCH_VERSION "1.0.2+1"
// | | | |______Build version : Automatic control
// | | |_______ Patch version : Human control
// | |_________ Minor Version : Human control
// |___________ Major Version : Human control
BRIOT_Patrick:
5. Now, each time you will compile your sketch, the current SKETCH_VERSION will appear in your application.
The compilation will increment the build number in your INO file for the next modification.
In order for this to work, the sketch must be saved before each compilation. There is a preference option (File > Preferences > Save when verifying or uploading), that is on by default, but I normally find that behavior annoying and so always have it off. For this reason, it would be a good idea to mention that the sketch must be saved (either automatically or manually) before compiling/uploading.
BRIOT_Patrick:
After the compilation, Arduino IDE couldn't automatically reload the sketch modified in background by this script, so you must first click in menu Tools the command Fix Encoding & Reload and now you could see the next SKETCH_VERSION updated for the next modification of your sketch.
There is a feature that will make this step no longer necessary in the works:
That feature is already available in the Arduino IDE Beta Build: