C++ Problem with Wire.OnReceive()

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

This is my code:

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

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...

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

Thanks Tommaso

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.

#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;

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.

Hi!

The compiler is telling you exactly what the problem is. The error message is perfect :wink: 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.

    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!