Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท Libraries and Projects

Writing Your Own Arduino Library

Package reusable Arduino code as a library: header and source files, classes with constructors and begin(), non-blocking update(), folder layout and library.properties.

When you copy the same fifty lines into your third sketch, it is time to make a library. A library gives the code a name, hides the details behind a small set of functions, lets several sketches share it and makes it easy to fix a bug once. It does not need to be big or published: a five-function library for your own button or LED pattern already pays off.

The Arduino IDE and boards cannot run here. The library code below is real C++ shown read-only; the C programs are labelled stand-ins that model the same object structure with a struct and fake millis() time, which is the core idea.

Anatomy: header and implementation

A class-based library has two files in a src folder. The header (.h) declares what the library offers; the source (.cpp) holds the implementation.

Blinker.h:

C++
#ifndef BLINKER_H
#define BLINKER_H

#include <Arduino.h>

class Blinker {
  public:
    Blinker(byte pin, unsigned long onMs, unsigned long offMs);
    void begin();
    void update();                       // call every loop()
    void stop();
    bool isOn() const;

  private:
    byte _pin;
    unsigned long _onMs;
    unsigned long _offMs;
    unsigned long _lastChange;
    bool _state;
    bool _running;
};

#endif

Blinker.cpp:

C++
#include "Blinker.h"

Blinker::Blinker(byte pin, unsigned long onMs, unsigned long offMs)
  : _pin(pin), _onMs(onMs), _offMs(offMs),
    _lastChange(0), _state(false), _running(true) {
}

void Blinker::begin() {
  pinMode(_pin, OUTPUT);
  digitalWrite(_pin, LOW);
  _lastChange = millis();
}

void Blinker::update() {
  if (!_running) {
    return;
  }
  unsigned long interval = _state ? _onMs : _offMs;
  if (millis() - _lastChange >= interval) {
    _state = !_state;
    digitalWrite(_pin, _state ? HIGH : LOW);
    _lastChange = millis();
  }
}

void Blinker::stop() {
  _running = false;
  digitalWrite(_pin, LOW);
  _state = false;
}

bool Blinker::isOn() const {
  return _state;
}

Why each part is there:

  • #ifndef / #define / #endif (an include guard) stops the header from being included twice, which would cause "redefinition" errors. (#pragma once also works with the Arduino toolchain.)
  • #include <Arduino.h> gives access to pinMode, millis, byte and friends inside library files; in a sketch it is added for you.
  • The constructor only stores settings. It runs before setup(), when the hardware is not ready, so do not call pinMode or Serial there. That is the job of a separate begin() method, which is why almost every Arduino library has one.
  • Private members are named with a leading underscore by convention; the public interface is small.
  • update() is non-blocking: it checks millis() and returns, so several Blinker objects (and your other code) work together. A library that calls delay() inside forces everything else to wait.

Using it in a sketch:

C++
#include <Blinker.h>

Blinker slow(8, 1000, 1000);
Blinker quick(9, 100, 400);

void setup() {
  slow.begin();
  quick.begin();
}

void loop() {
  slow.update();
  quick.update();
  // two independent blink patterns, no delay() anywhere
}

The same structure in C

C has no classes, but a struct plus functions that take a pointer to it is the same idea (and is how many C libraries work). Time is simulated with a counter so the program is deterministic.

C Stand-in: a Blinker 'object' with begin and update (C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Folder layout and library.properties

For the IDE (1.5 format) to accept the folder:

Text
Blinker/
  library.properties
  keywords.txt
  README.md
  src/
    Blinker.h
    Blinker.cpp
  examples/
    TwoLeds/
      TwoLeds.ino

library.properties is a plain text file of key=value lines:

Text
name=Blinker
version=1.0.0
author=Your Name <[email protected]>
maintainer=Your Name <[email protected]>
sentence=Non-blocking LED blinking.
paragraph=Blink several pins at independent rates without delay().
category=Signal Input/Output
url=https://example.com/blinker
architectures=*

Put the folder in your sketchbook's libraries directory and restart the IDE: it appears under Sketch, Include Library and its examples under File, Examples. To share it, upload to a Git repository and (optionally) submit it to the Library Manager index; the format and version rules were covered in installing and managing libraries. Increase version whenever you change behavior.

keywords.txt colors your class names (KEYWORD1) and methods (KEYWORD2) in the editor; fields are separated by a tab character, not spaces.

Design advice

  • One job per library. Blinker blinks; it does not also read buttons.
  • Small public interface. Everything public becomes a promise to your users.
  • Never block. Offer update() or callbacks instead of delay().
  • Avoid hidden dynamic memory. new, malloc and String on a 2 KB board cause fragmentation; prefer fixed arrays.
  • Be explicit about pins. Pass pins to the constructor rather than hard-coding them.
  • Add an example sketch that doubles as documentation and a test.
  • Support different boards with care. Use #if defined(ARDUINO_ARCH_AVR) only where needed.
  • Name things distinctively to avoid clashes with other libraries (Blinker might exist: check the Library Manager first).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should hardware setup such as pinMode go in begin() instead of the constructor?

    Global objects are built before setup() and before the core finishes initialization. Hardware calls belong in begin(), which you call from setup().
  2. 2. What is the include guard (#ifndef / #define / #endif) for?

    Without a guard, including the header twice would redeclare the class and cause errors.
  3. 3. Where do the .h and .cpp files of a modern Arduino library go?

    The 1.5 library layout expects code in src, examples in examples, and metadata in library.properties.
  4. 4. Why does a good library provide update() rather than calling delay() internally?

    Non-blocking updates let many tasks share the loop.

Summary

  • A library is a header (declarations), a source file (implementation) and library.properties, in a folder with a src directory.
  • Constructors store settings; begin() touches hardware; update() runs without blocking.
  • Use include guards, a small public interface and example sketches.
  • The idea survives in C as a struct plus functions taking a pointer to it.

Next: Power Supplies and Batteries