Using a function in a class as the callback function

I am trying to clean up my code to use a class rather that just global functions and variables.

The class is for a device that sends serial data once a second. My original code initialized the UART and passed in the function that handled the serial data as a callback. I moved the handling of the data into a function of the class, and passed in the uart as a parameter when I construct the class, but when the callback fuction is called it looks like it does not have access to the rest of the data in the class so shared variables give me an error when I try to use them.

If I make the call back function external to the class, and then have that external function call the function inside the class everything works.

So is there a way to use a set a callback in a class to used a member function of the class?

s is instance of sensor class.  So inside the class I call this external callback, which then calls the function inside the class to handle the received data.

function uart_data_callback()
{
    s.uart_data()
}

class sensor {
// some init code here
...
    constructor(imp_i2c_bus, address, uart)
    {
        // Parameters:
        // 1. The chosen imp I2C bus object
        // 2. The 7-bit I2C address as an integer

        if(imp_i2c_bus) {
            server.log("Configuring with I2C")
            _i2c = imp_i2c_bus
            _i2c_address = address
            _i2c.configure(CLOCK_SPEED_400_KHZ)
        }
        if (uart) {
            //_uart = uart
            server.log("Configuring with UART"+_uart)
            _uart.configure(9600, 8, PARITY_EVEN, 1, NO_CTSRTS, uart_data_callback);  //WORKS
            _uart.configure(9600, 8, PARITY_EVEN, 1, NO_CTSRTS, uart_data);  //DOES NOT WORK
        }
    }
    
    function uart_data()
    {
       //this function has access to member data if called from external callback, but not 
    }

Try using bindenv to bind the environment of the instance to the function. This should give uart_data() access to all internal stuff.

_uart.configure(9600, 8, PARITY_EVEN, 1, NO_CTSRTS, uart_data.bindenv(this));

Thanks for the solution. This worked perfectly

This topic was automatically closed after 60 days. New replies are no longer allowed.