How to create and use Singletons in an Arduino Project
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
Follow the tutorial linked below to learn how to create a class within an Arduino project.
Step Two: Update the Header and CPP files
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
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
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.