Problem with callback

Hi

I am having problem getting a callback function to work. I hope someone can guide me in the correct direction. Code looks like this.

Arduino sketch.

.. stuff
volatile static Class1 class1;
volatile static Class2 class2;


void setup()
{
    .. stuff
    class1.setCallback(&callback);
}

void callback(int i) 
{
    //Serial.println("Test");
    class2.put(i);
}

ISR(INT0_vect) // 
{
    class1.do();
}

void loop() {
   ...stuff
}

Then we have class1:

---  header file ----
public:
    Class1();
    void setCallback(void (*callback)(int));
    void do();
private:
    void (*_callback)(int);

---- cpp file ----
void Class1::setCallback(void (*callback)(int)) {
   _callback = callback;
}

void Class1::Do() {
    ... Stuff
    _callback(5);
}

Finally Class2

--- header file---
public
    Class2();
    void put(int i);

--- cpp file ---
Class2::put( int i) {
    ... Stuff
}

The problem with my code is that running it in this configuration produces rubbish on the serial connection. Random characters.

If I change the code,, removes the " class2.put(i) " and enables the "Serial.println("Test");" everything seem to be working nicely. The characters "Test" is printed on the serial connection.

So,, what is the problem.

So,, what is the problem.

Serial I/O in interrupt context?

Normally there are no printout on the serial line during interrupt. Only "class2.put(i);". Still something shows up on the serial line.

--- cpp file ---
Class2::put in i) {
    ... Stuff
}

What is this nonsense?

Typos in the code. Corrected. Hope you will understand it better now?

lgLindstrom:
Hope you will understand it better now?

Not really - the code is still incomplete, so replicating whatever results you claim is impossible.

So,,, it is not possible to see any syntax errors in the code?

The compiler is good at spotting syntax errors.
I thought your problem was at runtime?

Yes,,, it is run time problems. Compiler accepts this but there is a run time problem. If you google on C++ callbacks there is a number of methods ( syntax ) to archive correct functions. Some of them depends on the environment of the callback.
As the Arduino IDE compiles the sketch and add changes to the code under the hood ,,, I asked this on this forum.

In a pure C++ environment it is no match to get this to work.

I'm sorry, I don't understand the question.
Can you post a single minimal sketch that demonstrates your problem?

Hope you will understand it better now?

No. The code you posted will not compile. If you want help, POST ALL OF YOUR CODE. If not, quit whining.

Can you give me a hint of the problem? Where is the compilation error?

We don't know, because we can't see your code

1 Like