How to create and use Singletons in an Arduino Project
![Oscar de la Hera Gomez](https://www.delasign.com/CDN/headshots/profile.webp)
![A flower that represents Arduino with the text "Singleton" beneath it.](https://www.delasign.com/CDN/images/How-to-create-and-use-Singletons-in-Arduino.webp)
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.](https://www.delasign.com/CDN/images/TEST_2023-09-28-162444_tslf.webp)
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.](https://www.delasign.com/CDN/images/Header-File_2023-09-28-165643_sjyt.webp)
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.](https://www.delasign.com/CDN/images/Implement_2023-09-28-170217_aqkp.webp)
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.](https://www.delasign.com/CDN/images/Test_2023-09-28-170335_vncs.webp)
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.