Serial port management in a class, constructor undefined error

Hello,

I am having trouble moving some code into a class. The code works fine outside the class, in the setup() function for instance. Within the class the following line raises an error on build :

myPort = new Serial(this, Serial.list()[serialport], baudrate);

Error:

The constructor Serial(class_test.mytest, String, int) is undefined

I’m pretty sure I’m calling it ok, as I said, the same line compiles and works fine outside the class.

What am I missing?

Thanks,

Alexander

1 Like

I guess the problem is that

  • outside the class when you use this, it refers to the sketch
  • inside the class it refers to the class.

Work-around would be to pass this to the class constructor and use there.

Chrisir

2 Likes

Hi @Chrisir,

Perfect, this makes sense. I now take a PApplet type value in the constructor of my class, which I pass to the Serial method. From the main sketch I just pass this.

Thanks!

Alexander

2 Likes

Summary of working solution. We pass the parent (this, type PApplet) to the MyClass constructor, so we can then pass it to the Serial constructor.

myclass_test.pde:

// Test of MyClass
MyClass themyclass;
int serialport=1;

void setup () {

  themyclass = new MyClass(this,serialport);

}

myclass.pde:

// Include Serial libraries
import processing.serial.*;

class MyClass {

  // Serial connection
  Serial myPort;
  int serialport;
  int baudrate=57600;
  char parity='N';
  int dataBits=8;
  float stopBits=1.0;

  // Constructor
  MyClass(PApplet Parent,int c_serialport) {

    // Open Serial line
    serialport=c_serialport;
    myPort=new Serial(Parent,Serial.list()[serialport],baudrate,parity,dataBits,stopBits);

  }

}

Cheers,

Alexander

3 Likes