I had myself a fine working program. But I had to refactor some things. I added a class and inside that class I would like all to do all the serial data handling.
I only have no clue how java works with this. I keep getting null pointer exceptions everywhere and I need some help.
I have this class with a private Serial object. Must it be private, I don’t really know.
public class LocoNet
{
private Serial serial ;
Several of this class’ methods do something like serial.write()
, serial.read()
etc
one such a method
public void sendMessage()
{
byte len = getLen( messageOUT[0], messageOUT[1] ) ;
for( byte i = 0 ; i < len ; i ++ )
{
try
{
serial.write( messageOUT[i] ) ;
}
catch( NullPointerException e)
{
NO_COM = true ;
}
}
}
All serial related things are in catch blocks. In the event the USB cable is yanked out, the program will not crash completely.
In an attempt to… get it compilable at the very least. I tried making a serial object in the main file and initialize the port in void setup()
like one normally do.
And I try to pass on the serial object via the constructor.
public LocoNet ( Serial s)
{
serial = s ;
}
// main
void setup()
{
try
{
s = new Serial(this, "COM4", 19200) ;
println("COM PORT OPENED");
loconet = new LocoNet( s ) ;
}
catch (Exception e)
{
println("COM PORT FAILURE");
}
It all doesnt work and all. And I don’t know how to continue.
I would like to know what I am doing wrong, how I must correctly pass on an object (or a pointer to that objec) and I want to know all steps I need to take so I can safely use the serial object inside the class methods.
Kind regards
Bas