Quick code question about Serial ports

I have a GDropList that I populate with the serial ports on my machine so I can select one. Here’s the code to set up the list…

// Method to setup the port listing popup selctor thing.
public void setupPortList(GDropList portList) {
   
  int i;
  List<String> ourPortList;
   
  ourPortList = new ArrayList<String>();  // Create the array/list of strings.
  ourPortList.add("No port selected");    // Preload the first string as the "No Port selected" label.
  i = 0;                                  // Set i, our list index to 0;
  while(i<myPort.list().length) {          // While our listr index is less than the number of serial ports..
    ourPortList.add(myPort.list()[i++]);  // We pop in each serial port name and bump up i.
  }
  portList.setItems(ourPortList,0);        // When we show this, set it to show item 0. (The none selcted text)
}

And as far as I can tell, this works fine. When it fires up I see No Port selected and there is no port selected.

Then when I select a port…

public void portList_click(GDropList source, GEvent event) { //_CODE_:portList:775264:
  
  int index = source.getSelectedIndex();
  String portName = Serial.list()[index-1];
  myPort = new Serial(this, portName, 57600);
} //_CODE_:portList:775264:

It chooses the port name and sets up my port. This also seems to work fine.

What I get errors on is when I choose a new port. In the c++ world I’d delete the old port and create a new one. But in Java I assumed I just create the new port and I magically get a new port. But it doesn’t seem to work like that. Switch back and forth, I no longer get data. But I see its still going out the hardware.

How is one to change ports?

Thanks!

-jim lee

I don’t have the hardware to test serial ports but shouldn’t you at least stop() your previous Serial instance before instantiating a new 1?

Much probably the Serial library is a wrapper over some code written in C or C++.

That’s why we need to explicitly close/stop an instance of anything that relies on native code.

Oh! That makes perfect sense! Thanks!

-jim lee