I'm trying to find out how to implement a singleton class. Here's the background...... I've been playing around with reading and writing to files on an SD card. I've written a very basic 'logger' class to write error messages and other stuff to a log file. So far so good, I can include the class in another class or a sketch and I can log messages to the file without problems.

I now want to include the 'logger' object in all of the classes in my arduino application, but I want all of my classes to write to the same log file on the SD card. My research so far tells me I need to implement this as a 'singleton class' so there will only ever be one copy of my 'logger' object.

As an Arduino (normally) has only one thread, does your class really need to be a singleton? It is no multitasking environment where different objects run in different threads. so ...

wrt the class,- add the filename to the constructor That enables you to have different loggings (different sketches) on the same SDcard.- add a flag to writeline indicating type of log; use an enum LEVEL { DEBUG, INFO, WARNING, ERROR, MAYDAY } - add a timestamp before every string (prefered from a RTC if available)

Does this mean an Arduino can be multithreaded? if so how? I thought arduino was single threaded only?

With respect to the original question, firstly, when a class is intrinsically linked to a single physical device it makes sense to have only a single instance of that class. Secondly, I have created multiple instances of my logger object, and although it does compile and run without error, only the first instance created actually manages to write to the file. This code snippet illustrates the problem?.

Does this mean an Arduino can be multithreaded? if so how? I thought arduino was single threaded only?

No, an Arduino can not be multi-threaded. That requires an operating system to manage which thread is running. The Arduino does not have an operating system.

Quote

Basically I have 2 questions....1) is it possible to implement a singleton class?2) if the answer is 'yes' how do I do it?

Typically, a singleton class has a private constructor and a public method to get the existing (static) instance. Your class has a public constructor, no static instance, and no method that returns that static instance.