在 class 中使用 RtosTimer

Using an RtosTimer inside a class

我正在尝试在 class 中使用 RtosTimer,但 mbed 锁定了。我认为这是因为我在每个滴答声中调用 threadHelper 并创建一个新指针,而我实际上想在每个滴答声中调用 threadMethod 或在每个滴答声中调用 threadHeper 但使用相同的指针。

谁能告诉我应该怎么做?

下面的代码适用于 RtosThread,因为 threadHelper 只被调用一次,但我需要使用 Rtos 定时器。

.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;
    RtosTimer *m_rtosTimer;

    //Internal methods
    static void threadHelper(const void* arg);
    void threadMethod();
};

#endif

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()
{
    m_rtosTimer = new RtosTimer(&TestClass::threadHelper, osTimerPeriodic, (void *)0);
    int updateTime = (1.0 / m_FlashRate) * 1000;
    m_rtosTimer->start(updateTime);
}

void TestClass::threadHelper(const void* arg)
{
    //Cast the argument to a TestClass instance pointer
    TestClass* instance = (TestClass*)arg;

    //Call the thread method for the TestClass instance
    instance ->threadMethod();
}

void TestClass::threadMethod()
{
    //Do some stuff
}

谢谢

传递给 threadHelper()arg 指针是您传递给 RtosTimer 构造函数的参数 - 在本例中为空指针。 threadHelper() 取消引用此空指针导致运行时错误。

改为:

m_rtosTimer = new RtosTimer(&TestClass::threadHelper, osTimerPeriodic, (void*)this);