Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
9 years, 3 months ago. This question has been closed. Reason: Too broad - no single answer
Thread or RtosTimer as member variable
Hey guys. Sorry if this has come up before, but I'm looking for the best way for a class to use one or more Threads or RtosTimers internally. The problem is that RTX only accepts regular C function pointers, not C++ method pointers. Any ideas?
UPDATE
I may have figured out a solution, but I need somebody smarter than me to tell me if it makes sense. I added a static helper method to my class that matches the expected Thread function signature. Then, from inside the class, I create a Thread object using this helper method as the thread function, passing in the this pointer as the thread argument. The helper method casts the const void* argument back to an instance pointer, and calls the thread method. The thread method then executes a while loop, same as normal, except now it has access to the internal member variables. Make sense? I've attached some code:
TestClass.h
#ifndef TEST_CLASS_H #define TEST_CLASS_H #include "mbed.h" #include "rtos.h" /** TestClass class. * Used for demonstrating stuff. */ class TestClass { public: /** Create a TestClass object with the specified specifics * * @param led The LED pin. * @param flashRate The rate to flash the LED at in Hz. */ TestClass(PinName led, float flashRate); /** Start flashing the LED using a Thread */ void start(); private: //Member variables DigitalOut m_Led; float m_FlashRate; Thread* m_Thread; //Internal methods static void threadHelper(const void* arg); void threadMethod(); }; #endif
TestClass.cpp
#include "TestClass.h" TestClass::TestClass(PinName led, float flashRate) : m_Led(led, 0), m_FlashRate(flashRate) { //NOTE: The RTOS hasn't started yet, so we can't create the internal thread here } void TestClass::start() { //Create the internal thread using the helper function m_Thread = new Thread(TestClass::threadHelper, this); } void TestClass::threadHelper(const void* arg) { //Cast the argument to a TestClass instance pointer TestClass* instancePtr = static_cast<TestClass*>(const_cast<void*>(arg)); //Call the thread method for the TestClass instance instancePtr->threadMethod(); } void TestClass::threadMethod() { while (1) { //Toggle the LED m_Led = !m_Led; //Wait for a period of time Thread::wait((1.0 / m_FlashRate) * 1000); } }