How to - Arduino code syntax in c++ (.c. cpp .h)?

by Visual Micro 1. June 2012 15:59

We often want to structure the code in our Arduino projects to keep it simple and organised. The Arduino system allows us to create two main types of source files. The first type of source file are the "standard" Arduino source files. These standard files have a .pde or .ino extension and are, behind the scenes, automatically combined into a single file during program compilation. This provides some advantages in terms of simplicity but is not as flexible as using standard C/C++ soure files.

The second type of file are normal C++ files. In Visual Studio it is possible to add C++ files to Arduino projects using the built in menu commands or the additional Arduino "quick insert" commands shown on the "Add New Item" button on the toolbar. The quick insert creates either a .c or a .cpp files and a .h file.

When c++ files are used in an Arduino project the Arduino core is not automatically available to the source code, as it is with .pde/ino files. However, the Arduino core can be included in various ways one of which is described below:-

If you look in "[arduinoide folder]/hardware/arduino/cores/arduino" you will see the arduino core files for include ideas such as hardwareserial.h, string.h or avr/pgmspace.h. HardwareSerial.h provides access to the Arduino serial commands that are normally available in a .pde or ino files.

In Arduino IDE version 1.0 and above the main Arduino program include is "Arduino.h", in older versions it is "WProgram.h". If required we can use the automatically defined ARDUINO constant to check for and use the correct include based on the current Arduino IDE version.

The following code example is how to include the correct Arduino core header and also to provide access to Arduino Serial functions from mycode.cpp and mycode.h files:-

mycode.c or mycode.cpp:-

#if defined(ARDUINO) && (ARDUINO >= 100)
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "HardwareSerial.h"
#include "myc.h"

mycode.h:-

#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "HardwareSerial.h"
#include "myc.h"

Tip: All arduino versions 1.0 and above have a version greater than or equal to 100

Other Pages