Go Down

Topic: C++ Problem with Wire.OnReceive() (Read 1 time) previous topic - next topic

tgiachi

Hi all,
I'm using Eclipse with Arduino plugin and I've problem with Wire.OnReceive function:

This is my code:
Code: [Select]

void AuroraLibrary::_init_wire_link()
{
Wire.begin(WIRE_LINK);
Wire.onReceive(_on_wire_message_recevied);
}

my function _on_wire_message_recevied is definited in header and in file .cpp
Code: [Select]

void AuroraLibrary::_on_wire_message_recevied(int howMany)

But when i compile i've got this error:


ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say '&AuroraLibrary::_on_wire_message_recevied'   AuroraLibrary.cpp   /AuroraFirmware/lib/AuroraLibrary   line 106   C/C++ Problem


I also try to put this but i've same problem...

Code: [Select]

void AuroraLibrary::_init_wire_link()
{
Wire.begin(WIRE_LINK);
Wire.onReceive(&_on_wire_message_recevied);
}



Thanks Tommaso

WizenedEE

Every method needs an object to work with. If you just give the name of the method, the onReceive method doesn't know what object to apply the method to.

You could do some messy things with pointer to member stuff, or you could make a static member of AuroraLibrary that figures out which instance of the class to use (the constructor could assign a static pointer to "this") and does stuff to it.

Code: [Select]

#include <Wire.h>
class myclass {
  static myclass* classToUse;

  int randomdatayay;
public:
  myclass() {
    classToUse = this;
  }

  void init() {
    Wire.begin();
    Wire.onReceive(onMessageReceive);
  }
  void randommethodyay() {

  }
  static void onMessageReceive(int howmany) {
    classToUse->randomdatayay = howmany;
    classToUse->randommethodyay();
  }
};
myclass* myclass::classToUse = NULL;

hugocura

Hi WizenedEE,

I'm having this same problem right now.

I'm using ICSC library (registerCommand method) inside another library I've made.

When I'm using function Callback (second argument on registerCommand method), I receive the same error that tgiachi received.

So I tried your solution but I can't figure out how to adapt your example properly.

May you explain it better?

Thank you.

kowalski

Hi!

The compiler is telling you exactly what the problem is. The error message is perfect ;-) If you check the specification of onReceive() you will see that it takes a callback function as parameter. Not an object and not a member function.

Code: [Select]

    void onReceive( void (*)(int) );


Define _on_wire_message_recevied() as static and it will compile BUT remember that there is no context ("this" is not valid in a static member function). A static member function cannot reference member variables.

There is an example sketch in arduino/libraries/Wire/examples. See slave_receiver.ino.

Cheers!

Go Up