c++microcontrollerstm32single-threaded

How do I run something inside a class concurrently (in single threaded platform)?


I have to write a class that implements the given interface below. When I call the start function it should starts counting every 1 millisecond and when I call the stop function it should stop counting. The read function should return the value of the counter.

How should I go about writing this implementation as I'm implementing this on for a microcontroller without any RTOS. As such this project is strictly single threaded and I don't see a way as how to implement this without threads.

class Counter{
public:
    virtual void stop() = 0;
    virtual void start() = 0;
    virtual int read() = 0;
};

example usage:

int main()
{
   Counter *cnt = new Counter_Implemented();
   cnt->start();

   //do some heavy task here

   cnt->stop();
   int duration = cnt->read();
}

Solution

  • If you use HAL libraries:

    class Counter{
    public:
        void stop()
        {
            end = HAL_GetTick();
        }
        void start() 
        { 
            start = HAL_GetTick();
        }
        uint32_t read()  
        {
            return end-start;
        }
    };
    

    If you want to be able stop counting just use any hardware timer this purpose instead of SysTick.