-->
Page 1 of 1

Can somebody explain the delegate-example

PostPosted: Sun Feb 19, 2017 5:27 pm
by Hotglue
Hello Board,

could somebody please explain this example?

- What does the "req" mean (reqPin, reqRun, reqinterval)?
- What is the general flow of the program?
- Why would I use it for this purpose?


- How does this structure work (what d8es the colon mean:
LedBlinker(int reqPin) : ledPin(reqPin) {
pinMode(ledPin, OUTPUT);
};

the1 source code:

#include <user_config.h>
#include <SmingCore.h>

class LedBlinker
{

public :
LedBlinker(int reqPin) : ledPin(reqPin) {
pinMode(ledPin, OUTPUT);
};
bool setTimer(int reqInterval) {
if (reqInterval <= 0) return false;
ledInterval = reqInterval;
return true;
}
void blink(bool reqRun) {
if (reqRun) {
ledTimer.initializeMs(ledInterval, TimerDelegate(&LedBlinker::ledBlink,this)).start();
}
else {
ledTimer.stop();
}
}
void ledBlink () { ledState = !ledState ; digitalWrite(ledPin, ledState);}

private :
int ledPin = 2;
Timer ledTimer;
int ledInterval = 1000;
bool ledState = true;
};

#define LEDPIN_1 2 // GPIO2
#define LEDPIN_2 4 // GPIO4

LedBlinker myLed1 = LedBlinker(LEDPIN_1);
LedBlinker myLed2 = LedBlinker(LEDPIN_2);

void init()
{
myLed1.setTimer(1000);
myLed1.blink(true);
myLed2.setTimer(500);
myLed2.blink(true);
}

Re: Can somebody explain the delegate-example

PostPosted: Mon Mar 27, 2017 6:23 am
by zgoda
This example shows how to use class members as callbacks. In C++ you can write exactly as you do in C or in object-oriented way. To use class member method as callback function, you have to wrap it as delegate. This code creates LedBlinker class that takes pin as constructor argument, then it creates 2 blinker instances for 2 leds/pins. Each instance initializes timer that blinks its assigned led.

The construct after colon in constructor initializes member variables during instance initialization.