mercredi 31 octobre 2018

How to use non static member functions as callback in C++

I am writing a small program for ESP8266 in C++ and run into trouble. I've created a Led class form handling leds. The idea is that the class should handle a blink function. For this I use a library called Ticker.

A function in Ticker, attach_ms requires a callback and I cant get that to work with a non static member functions.

This is my header file:

#ifndef led_h
#define led_h

#include <Arduino.h> 
#include <Ticker.h>
#include "debugutils.h"

#define tickLength 100


enum class LedState {
        OFF,
        ON,
        SLOW_BLINK,
        FAST_BLINK
};


class Led {
public:

    Led(Ticker *tick, uint8_t ledPin, int slowBlinkTime, int fastBlinkTime);

    void on();
    void off();
    void slowBlink( );
    void fastBlink( );

private:
    uint8_t pin;
    int counter;
    int slowNoBlinkTicks;
    int fastNoBlinkTicks;
    LedState state;
    void ledOn();
    void ledOff();
    void ledInvert();
    void clean();
    void blink(int par);
    void tickerCallbackLed();
};
#endif

This is my code file:

#include "led.h"


void Led::ledOn() {
    digitalWrite(pin, HIGH);
}

void Led::ledOff() {
     digitalWrite(pin, LOW);
}

void Led::ledInvert() {
    digitalWrite(pin, !digitalRead(pin));
}

void Led::clean() {
    counter = 0;
}

void Led::blink(int par) {
    if (counter > par) {
        ledInvert();
        counter = 0;
    }
    else {
        counter++;
    }
}

void Led::tickerCallbackLed() {

    switch (state) {
        case LedState::OFF : break;
        case LedState::ON : break;
        case LedState::SLOW_BLINK : blink(slowNoBlinkTicks); break;
        case LedState::FAST_BLINK : blink (fastNoBlinkTicks);  break;
        default : break;
    };


};

void Led::on() {
    ledOn();
    state = LedState::ON;
};


void Led::off(){
    ledOff();
    state = LedState::OFF;
};

void Led::slowBlink(){
    clean();
    ledInvert();
    state = LedState::SLOW_BLINK;
};

void Led::fastBlink(){
    clean();
    ledInvert();
    state = LedState::FAST_BLINK;
};


Led::Led(Ticker *tick, uint8_t ledPin, int slowBlinkTime, int fastBlinkTime) {

    tick->attach_ms(tickLength, std::bind(&Led::tickerCallbackLed,this));

    slowNoBlinkTicks = slowBlinkTime/tickLength;
    fastNoBlinkTicks = fastBlinkTime/tickLength;

    pinMode(ledPin,OUTPUT);

    digitalWrite(ledPin,LOW);

    pin = ledPin;
    state = LedState::OFF;
    counter = 0;

}

This line gives a compile error and I dont know how to fix it. Have tried to follow all "advice" I have found on internet.

 tick->attach_ms(tickLength, std::bind(&Led::tickerCallbackLed,this));

Greatful for help.

Aucun commentaire:

Enregistrer un commentaire