How to create and use Singletons in an Arduino Project

Oscar de la Hera Gomez
A flower that represents Arduino with the text "Singleton" beneath it.

A guide for creating and using Singletons.

The code for the following tutorial is found on Github through our Open Source Arduino starter project. This can be cloned using the command below:

git clone git@github.com:delasign/arduino-starter-project.git

Step One: Create the Class

A screenshot of the Arduino IDE highlighting the Serial Monitor whose logs demonstrate that the class works as expected.

Follow the tutorial linked below to learn how to create a class within an Arduino project.

Step Two: Update the Header and CPP files

A screenshot of the Arduino IDE showing the updated header file. The code for the header and cpp file can be found below.

Update the class to include the functionality required for it to behave like a singleton.

A | Header File

Add the following items to your header file:

  • A static shared variable that acts as the singleton.
  • Functionality for a private copy constructor and assignment operator to prevent cloning.

Please note that the items above have been highlighted using "=== Required for Singletons ===" in the code below.

B | CPP File

In your CPP file, Define the single instance as a static member.

Please note that the item above has been highlighted using "=== Required for Singletons ===" in the code below.

Step Three: Implement the Singleton

A screenshot of the Arduino IDE highlighting how we included the Singleton header file and how we called its functionality within the script.

To implement the singleton, include its header file in a script and call its functionality using code similar to the one below:

SampleManager::shared().setup();

Step Four: Test

A screenshot of the Arduino IDE demonstrating how the Serial Monitor confirms that the singleton works as expected.

Upload the code onto your board and confirm that the code works as expected.

Looking to learn more about things you can do with Arduino ?

Search our blog to find educational content on Arduino.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details