Challenge trying to pass a pointer to a port as an argument to class method using the SC16IS7xxRH library

I have two devices that run on separate ports and am using the SC16IS7xxRK library to communicate with them. When I use the library directly (see below), everything works great.


void setup() 
{
  ...
  extSerial.withI2C(&Wire, 0x4D);
  Wire.setSpeed(CLOCK_SPEED_400KHZ);
  extSerial.softwareReset();
  extSerial.powerOnCheck();
  
  extSerial.a().begin(19200);
  extSerial.b().begin(9600);
  ...
}

void loop()
{
  if (extSerial.a().available()) {
    // do stuff here
  }

  if (extSerial.b().available()) {
    // do stuff here
  }
}

However, I would ideally like to pass a reference/pointer to a separate library and tell it to use extSerial.a() as the serial to read from, but have encountered troubles I have been unable to resolve, mostly due to intermediate (at best) C++ skills. As an example, it could look something like:

Say I have a Sensor class like the following:

class Sensor {
  public:
    Sensor();
    virtual ~Sensor();

    Sensor &withPort(SC16IS7xxPort *port) { m_port = port; return *this; };

    // These wouldn't normally be written inline like this
    void setup() {
      m_port->begin(19200);
    };

    void loop() {
      if (m_port->available()) { 
        // do something 
      }
    };
  
  private:
    SC16IS7xxPort *m_port;
}

And then code that looks something like this:

void setup() 
{
  ...
  extSerial.withI2C(&Wire, 0x4D);
  Wire.setSpeed(CLOCK_SPEED_400KHZ);
  extSerial.softwareReset();
  extSerial.powerOnCheck();
  
  // assume  I want to use a sensor that allows me to set it's serial port
  sensor.withPort(&extSerial.a())
      .setup();

  ...
}

void loop() 
{
  sensor.loop();
}

Everything appears to initialize just fine and the call to begin from within the Sensor class returns true, but m_port->available() always returns nothing. Am I lost? Is there something I can do to use the SC16IS7xxRK ports and pass them to another library in this way?

That looks like it should work. I'll take a closer look later.

I still don't see what's wrong with your code, but I added two new examples to SC16IS7xxRK. I tested them with a SC16IS752 connected by I2C and they appear to work properly.

Example 11 is basically like yours.

Example 12 factors at Stream instead of SC16IS7xxPort. The downside of this is that you need to set the baud rate outside of your class. The upside is that you can pass Serial1 so your sensor class would work with any SC16IS7xx or a hardware UART.

1 Like

Thanks! I'll give that a try and see if I can get it operating.

The examples you posted seem to work well. I did notice that using Stream rather than SC16IS7xxPort seems to be what fixed my issue. For some reason, when using the latter, most of the data appears corrupt.

1 Like