In
this tutorial we are going to see how to create a library in Arduino in a
simple and easier method.
Prerequisite:
Basics
of C and C++ language
In
this example we are going to develop a LED ON and OFF using library.
CODE WITHOUT LIBRARY
In
above code, 3 LED are connected in 2, 3 and 4 pin of Arduino UNO.
Here
we turn ON and OFF LED individually for 500 MS.
Here
the task is ON and OFF for all the LED.
This
CODE can be further simplified using Library.
CODE
WITH LIBRARY
To
create a library we need to create Header file, cpp files and the main code file.
The
header file is saved as .h and cpp file is saved as .cpp
STEP 1: click New Tab
STEP 2: name file as led.h
STEP 3: name file as led. cpp
HEADER
FILE CODE
In
header file The #ifndef is a macro which is used for code
protect.
The
compiler checks the header file for 1st time it will
check ,if the name is defined or NOT .
If
not defined the condition is true and it process to second line
We
define the name using #define macro.
If
the file is accessed 2nd time the compiler checks whether the
file is defined or not, already the file is defined in 1st time
itself and the file is skipped.
The
#include Arduino is added for access functionality of Arduino boards
Class
is created with name LED
Class
name – LED
In
Public
void toggle(int
_delay);
void ledpin(int led_pin);
int PIN;
is
used globally in all files.
CPP
FILE CODE
In
cpp file, first we need to add header file, #include “led.h”
The
functions are defined with class name
Return
type class name: function name (arguments)
MAIN
CODE
In
main code,first we need to include header file.
#include”led.h”
CLASS
NAME Object name
LED
led1, led2, led3
Here
LED is class name and led1, led2 and led 3 are objects
In
void setup
Object
name. function name(argument);
led1
.ledpin(2);
here
led1 is object name.
ledpin(2)
is class function
2
is Arduino pin no passed as argument.
In
void loop()
led1.
toggle(500);
Here
led1 is object name
toggle
(500) is function name with delay mills are argument.
CREATING AS LIBRARY
Save
file in Documents->Arduino->Libraries ->LED (create new folder and
rename as LED)
Inside
LED folder
led.cpp
led.h
Examples
(create new folder and rename as examples)
Examples
folder -> LED (create new folder and rename as file name LED).
LED
folder->LED.ino main coding file.
Now
open Arduino IDE and Files->Examples->LED->LED
Opens
LED. ino as example file.
Comments
Post a Comment