Gbertaz / NonBlockingDallas

Arduino library for the DS18B20 temperature sensor. Avoid blocking the sketch while reading the sensor.
MIT License
11 stars 4 forks source link

how to define the call back function in a class scenario #8

Closed meltoner closed 1 year ago

meltoner commented 1 year ago

Hello i am trying to use your library via a class but can't figure out how to write callback function in my class i separate the .h with the .cpp in the h file i specify these

class Context{ public: Context(); void setup() OneWire oneWire = OneWire(4); DallasTemperature dallasTemp = DallasTemperature(&oneWire); NonBlockingDallas sensorDs18b20 = NonBlockingDallas(&dallasTemp); void handleIntervalElapsed(float temperature, bool valid, int deviceIndex); ...

in the cpp file I specify

void Context::handleIntervalElapsed(float temperature, bool valid, int deviceIndex){ if(valid) temperatures[deviceIndex] = temperature; } void Context::setup(){ sensorDs18b20.begin(NonBlockingDallas::resolution_12, NonBlockingDallas::unit_C, 1500); sensorDs18b20.onIntervalElapsed(handleIntervalElapsed); } on line sensorDs18b20.onIntervalElapsed(handleIntervalElapsed);

it says error: invalid use of non-static member function 'void Context::handleIntervalElapsed(float, bool, int)

I understand that this is probably a c++ know how but would appreciate letting me know how to properly pass the function in a class scenario. Thanks in advance

Gbertaz commented 1 year ago

Hello @meltoner

You need to define the callback in your Context class in a different way. I will provide you an example later today.

In the meantime if you want to check it yourself, you can find a similar thing in my Globosat repository, here:

https://github.com/Gbertaz/GloBoSaT/blob/master/src/TemperatureDs18b20.h

meltoner commented 1 year ago

thank you Gbertaz!

Gbertaz commented 1 year ago

Hello @meltoner

I checked more carefully and your use case looks a bit different than the example I provided. I think the easiest solution in your case is to use a lambda function as the callback. In your cpp:

void Context::setup() {
    sensorDs18b20.begin(NonBlockingDallas::resolution_12, NonBlockingDallas::unit_C, 1500);
    sensorDs18b20.onIntervalElapsed([this](float temperature, bool valid, int deviceIndex) {
        if (valid) {
            this->temperatures[deviceIndex] = temperature;
        }
    });
}