title: Java/Arduino - Read data from the Serial Port
body: <p>I've got a program in Java where I have to read the information that an Arduino is sending.
  I took the Java code from <a href="http://playground.arduino.cc/Interfacing/Java" rel="noreferrer">here</a>. Now, I didn't really understand how it works, but I tried to modify it and I got this:</p>
  
  <pre><code>import java.io.BufferedReader;
  import java.io.InputStreamReader;
  import java.io.OutputStream;
  import gnu.io.CommPortIdentifier;
  import gnu.io.SerialPort;
  import gnu.io.SerialPortEvent;
  import gnu.io.SerialPortEventListener;
  import java.util.Enumeration;
  
  public class Serial implements SerialPortEventListener {
      SerialPort serialPort;
  
      private static final String PORT_NAMES[] = {
              "/dev/tty.usbserial-A9007UX1", // Mac OS X
              "/dev/ttyUSB0", // Linux
              "COM3", // Windows
      };
  
      private BufferedReader input;
      private static OutputStream output;
      private static final int TIME_OUT = 2000;
      private static final int DATA_RATE = 115200;
  
      public void initialize() {
          CommPortIdentifier portId = null;
          Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
  
          while (portEnum.hasMoreElements()) {
              CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
              for (String portName : PORT_NAMES) {
                  if (currPortId.getName().equals(portName)) {
                      portId = currPortId;
                      break;
                  }
              }
          }
          if (portId == null) {
              System.out.println("Could not find COM port.");
              return;
          }
  
          try {
              serialPort = (SerialPort) portId.open(this.getClass().getName(),TIME_OUT);
  
              serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,    SerialPort.PARITY_NONE);
  
              input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
              output = serialPort.getOutputStream();
  
              serialPort.addEventListener(this);
              serialPort.notifyOnDataAvailable(true);
          }
          catch (Exception e) {
              System.err.println(e.toString());
          }
      }
  
      public synchronized void serialEvent(SerialPortEvent oEvent) {
          if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
              try {
                  String inputLine=input.readLine();
                  System.out.println(inputLine);
              } catch (Exception e) {
                  System.err.println(e.toString());
              }
          }
      }
  
      public synchronized void close() {
          if (serialPort != null) {
              serialPort.removeEventListener();
              serialPort.close();
          }
      }
  
      public Serial(String ncom){
          if(Integer.parseInt(ncom)&gt;=3 &amp;&amp; Integer.parseInt(ncom)&lt;=9)
              PORT_NAMES[2] = "COM" + ncom;
          initialize();
          Thread t=new Thread() {
              public void run() {
                  try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
              }
          };
          t.start();
          System.out.println("Serial Comms Started");
      }
  
      public synchronized void send(int b){
          try{
              output.write(b);
          }
          catch (Exception e) {
              System.err.println(e.toString());
          }
      }
  
      public synchronized int read(){
          int b = 0;
  
          try{
              b = (int)input.read();
          }
          catch (Exception e) {
              System.err.println(e.toString());
          }
          return b;
      }
  }
  </code></pre>
  
  <p>I create the object Serial with the <a href="http://en.wikipedia.org/wiki/Serial_port#Hardware_abstraction" rel="noreferrer">COM port</a> I need in the main program, then I use <code>Serial.read</code> and <code>Serial.write</code> when I need it.</p>
  
  <p><code>Serial.write</code> works great, Arduino gets the data and show it in a LCD Display. The problem is <code>Serial.read</code>. When the program is running, it keep read from serial port (around every 40&nbsp;ms), but that doesn't mean Arduino sent something. Arduino sends a byte only when a button is pushed. So, when the Java code is running, it throws "n" Exception before read something, and this couses so much lag.</p>
  
  <p>I know I need something like <code>Serial.available()</code>, I tried <code>input.available()</code>, but it doesn't work. I don't know how to solve this problem.</p>
  
  <p>If you have a code that working, I'd be so much grateful if you could give it to me. I just need two methods, read and write, I don't care how the code works :D</p>
  
  <p>EDIT:</p>
  
  <p>I changed the Serial class, now it has again this method as apremalal said</p>
  
  <pre><code>public synchronized void serialEvent(SerialPortEvent oEvent) {
  
          if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
              try {
  
                  String inputLine=null;
                  if (input.ready()) {
                      inputLine = input.readLine();
                      panel.read(inputLine);
                  }
  
              } catch (Exception e) {
                  System.err.println(e.toString());
              }
          }       
      }
  </code></pre>
  
  <p>and in the other class (Panel in this case) I've got this:</p>
  
  <pre><code>public void read(String data){
      System.out.println(data);
      System.out.println(data == "255");
      if(data == "255")
          //code here 
  }
  </code></pre>
  
  <p>It print the values correctly but <code>data == "255"</code> is always false, even if I really get a 255
  ....I tried to do <code>Integer.parseInt</code> but nothing changed. Why the hell?</p>
  
  <p>EDIT 2: Ok solved :\</p>
  
  <pre><code>public void read(String data){
  
      serialRead = Integer.parseInt(data);
  
      if(serialRead == 255)
          //code here 
  }
  </code></pre>
  
  <p>Now it's work..don't know why I had to do this... meh whatever :)</p>