Callback_08.cpp 876 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include "mbed.h"
  2. #include "rtos.h"
  3. /*
  4. * https://os.mbed.com/questions/77791/Correct-construction-for-callback-on-a-m/
  5. */
  6. class OtherClass
  7. {
  8. public:
  9. OtherClass(DigitalOut* out) :
  10. _out(out) {};
  11. ~OtherClass(void) {}
  12. DigitalOut* digitalOut() {
  13. return _out;
  14. }
  15. private:
  16. DigitalOut* _out;
  17. };
  18. class MyClass
  19. {
  20. public:
  21. MyClass(OtherClass* other) :
  22. _other(other) {}
  23. ~MyClass(void) {}
  24. void myCallback(void) {
  25. while (1) {
  26. *_other->digitalOut() = !*_other->digitalOut();
  27. wait(1);
  28. }
  29. }
  30. private:
  31. OtherClass* _other;
  32. };
  33. int main(void) {
  34. OtherClass otherClass(&led2);
  35. MyClass myClass(&otherClass);
  36. thread.start(callback(&myClass, &MyClass::myCallback)); // callback using member function
  37. while (true) {
  38. led1 = !led1;
  39. wait_ms(500);
  40. }
  41. }