
i used a coding for getting data from serial port. JOptionbox with "port not found" message is shown when i execute thru jar file. but when i execute thru netbeans, data is received from comm port. why it is happening? i attached the coding i used.
public class SimpleRead implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; static Enumeration portList; InputStream inputStream; SerialPort serialPort; Thread readThread;
public static void main(String[] args) { boolean portFound = false; String defaultPort = "COM2";
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
JOptionPane.showMessageDialog("Found port: "+defaultPort);
portFound = true;
SimpleRead reader = new SimpleRead();
}
}
}
if (!portFound) {
JOptionPane.showMessageDialog("port " + defaultPort + " not found.");
}
}
private int numBytes; private String s;
public SimpleRead() { try { serialPort = (SerialPort) portId.open("SimpleReadApp", 2000); } catch (PortInUseException e) { System.out.println("port in use"); }
try { System.out.println("Getting input Stream"); inputStream = serialPort.getInputStream(); } catch (IOException e) { System.out.println(e); }
try { serialPort.addEventListener(this); } catch (TooManyListenersException e) { System.out.println(e); } serialPort.notifyOnDataAvailable(true); try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this); readThread.start(); }
public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) {} }
public void serialEvent(SerialPortEvent event) { switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUTBUFFEREMPTY: break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[8];
byte[] readBuffer2=null;
try {
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
readBuffer2= new byte[numBytes];
for(int i=0;i }
}
}}
s = new String(readBuffer2);
System.out.println("readbuffer......"+ s);
} catch (IOException e) {}
break;
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.