Electronic – How to give several classes access to the single RTC on the MCU

cembeddedrtcstm32

I'm writing my first large-ish C++ embedded program on a STM32F413. I've become a reasonably firm believer in object oriented coding but am not particularly knowledgeable. The STM32F413 has one RTC but almost all my classes need to time stamp events. I have a class for each of my sensors like GPS, pressure, pH, humidity and so on. Every time a new piece of data comes in from any sensor, it needs to get time stamped. I'd like to write a RTC class and give many other classes access to the RTC date and time through a single public "getDateTime" method. The only way I know how to do this is with a singleton. Is there a better way?

Thanks in advance

Best Answer

If you decide to use a class paradigm, then your choice is really between having a member (or instance) function of a singleton, vs. having a static (or class) method.

If you feel it makes sense to simply read the RTC hardware each time, and you don't need to track any useful RTC related state in software, then you can simply go with simplicity of a static or class method. Call it from anywhere, it grabs some kind of hardware lock (probably buried in a C-language HAL library), reads the hardware, releases the lock, and returns the value.

But maybe you conclude you do need to track state in an object instance. Or maybe you'd like that mutex to be owned by an instance - in this case, you can legitimately say "hey, there's a single instance of the RTC hardware, there should be a single instance of the class as well" and go with a singleton pattern.

Of course there's a third choice, too... you don't have to use an OOP paradigm for the RTC. Either in C++, or by calling an extern "C" method defined in a C source file it's perfectly legitimate to just have code which interacts with the hardware - if you use a vendor HAL, you're likely to end up with that under the covers, even if you put an OOP wrapper on top.

I believe you'll find that on larger systems, system time is usually either something that breaks the OOP model, or else in a language that is fundamentally object oriented, it tends to be a static or class method. I can't off the top of my head recall a singleton case; though there are examples of IPC based system services (in Android for example) where you access certain resources by first getting a unique instance of a class to do the local end of the IPC.