your_main_code.ino #include "my_library.h" Now, let’s use this function in our sketch again.
Here you just import your header file, and you implement the code for the function. The implementation will be done in the Cpp file. On your main program it’s automatically added for you if you forget it, but not on other files or libraries.įinally, you have the prototype of your function. Then, don’t forget to include the Arduino library. For example, if you have a temperature_sensor.h file, you can use “TEMPERATURE_SENSOR_H”.
You start with the header guards and add your code between the #define MY_LIBRARY_H and #endif.įor the header guard’s name, usually it’s a good practice to use the name of your file in uppercase and add “_H”. Write the following code into those 3 files. Then restart your Arduino IDE, or close/open your current sketch. If you named your project MyProgram, then the file is called MyProgram.ino, and is located inside the MyProgram/ folder.Ĭreate 2 new files: my_library.h and my_library.cpp. In this folder, you should already have a. Also, you can find where is your current sketch file directly from the Arduino IDE: click on “Sketch” > “Show Sketch Folder”. Usually it’s inside the “My Documents/Arduino” folder, unless you changed the default location. To do that, find where your Arduino sketch is located. Let’s create 2 files: a Cpp and a header file. Separating the library code from the rest
Here we’ll make the addTwoInts() function a part of a library named my_library.įor now, all the code is in the same file, which isn’t really practical for separating the library from the main code.
You are learning how to use Arduino to build your own projects?Ĭheck out Arduino For Beginners and learn step by step. The function will take 2 integers as parameters and return the sum. Let’s start with a very simple program, and from that create a library step by step.įirst, write this small Arduino sketch, which only has one function. Step 1: Write your Arduino library code Starting code