Sunday, July 6, 2014

Creating the Super Simple Library

Functions allow you to remove repetitive routines from your main code, and call them when needed. There are times when you would like to move commonly used functions out of your Arduino sketch entirely, and into a library you can call from your sketch. This helps clean up your sketch visually, and allows you to reuse code without having to recreate it each time. Below is a simple sketch that takes a value in Celsius, and converts it to Fahrenheit. I'll show you how to convert that into a called function, then I'll repost it by calling an external library that does the same thing. This is kept simple, in order to show the process. There is much more you can do with libraries, but this is the bare minimum to get it to work.

Original sketch without a function:

float celsius = 20;
float tempF = 0;

void setup()
{
  Serial.begin(9600);
  tempF = (1.8 * celsius) + 32;
  Serial.print(tempF);
}

void loop()
{
  
}



Original sketch with a function:

float celsius = 20;
float tempF = 0;

void setup()
{
  Serial.begin(9600);
  tempF = tempConvert(celsius);
  Serial.print(tempF);
}

void loop()
{
  
}


float tempConvert(float celsius)
{
  float fahrenheit = 0;
  fahrenheit = (1.8 * celsius) + 32;
  return fahrenheit; 

}

Now let's remove the function tempConvert, and put it in a seperately called library, ( a pair of .h & .cpp files).

Sketch calling libary:

float celsius = 20;
float tempF = 0;

#include <tempConvert.h>

void setup()
{
  Serial.begin(9600);
  tempF = tempConvert(celsius);
  Serial.print(tempF);
}

void loop()
{
  
}

put the following two files in a folder called tempConvert, inside the libraries folder.

tempConvert.cpp

// tempConvert.cpp

#include "Arduino.h"   
// use: Wprogram.h for Arduino versions prior to 1.0

#include "tempConvert.h"

float tempConvert(float celsius)
{
  float fahrenheit = 0;
  fahrenheit = (1.8 * celsius) + 32;
  return fahrenheit; 
}

tempConvert.h

/*
 * tempConvert.h
 * Library header file for tempConvert library
 */
#include "Arduino.h"

float tempConvert(float celsius);  // function prototype

For more on creating libraries, see http://arduino.cc/en/Hacking/LibraryTutorial