Java -> Serial communication

Hi, i’m having some trouble setting up a connection and sending data to arduino, here is my code:

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Scanner;

public class Serial extends Thread implements SerialPortEventListener {

    SerialPort serialPort;
    String str = new String();
    private static final String PORT_NAMES[] = {"/dev/tty.usbserial-A9007UX1", "/dev/ttyUSB0", "COM3"};
    private InputStream input;
    private OutputStream output;
    private static final int TIME_OUT = 2000;
    private static final int DATA_RATE = 9600;
    private int[] buffer = new int[100];
    private int len = 0;

    public Seriale() {
        CommPortIdentifier portId = null;
        System.out.println("Port enumeration...");
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
        System.out.println("Completed. Searching for COM3 port...");
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        System.out.println("Completed. ");
        if (portId == null) {
            System.err.println("Port not found.");
            return;
        }
        System.out.println("Port found. Establishing connection... ");
        try {
            serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
            serialPort.setDTR(false);
            serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            input = serialPort.getInputStream();
            output = serialPort.getOutputStream();
            //serialPort.addEventListener(this);
            //serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            System.err.println("Error connecting.");
            e.printStackTrace();
        }
        System.out.println("Connection established.");
        start();
    }

    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    @Override
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                int data = input.read();
                if ((data != 10) && (data != 13)) {
                    buffer[len] = data;
                    len++;
                } else {
                    for (int i = 0; i < len; i++) {
                        str = str + (char) buffer[i];
                    }
                    System.out.println(str);
                    str = new String();
                    len = 0;
                    input.skip(1);
                }

            } catch (Exception e) {
            }
        }
    }

    public static void main(String[] args) {
        new Serial();
    }

    public void run() {
        int i=0;
        while (true) {
            String data = "A";
            System.out.println("Sending data...");
            try {
                i+=1;
                output.write(data.getBytes());
                System.out.println("Data sent.");
                if(i==4) break;
            } catch (IOException ex) {
            }
        }
    }
}

There are no errors shown while connecting and sending data, i also see the RX-TX LEDs on the arduino blinking for 4 times, so i suppose Arduino is receiving all the data i send.

The point is, i’ve a Stepper motor connected to arduino, and i set up arduino so it rotates 90 degrees clockwise when it receives “A” via serial communication.
All of this works if i use the Arduino Serial Monitor, the stepper rotates 90 degrees clockwise, with this class it seems arduino is receiving and recycling all the data i send. Can anyone help me?

All of this works if i use the Arduino Serial Monitor, the stepper rotates 90 degrees clockwise, with this class it seems arduino is receiving and recycling all the data i send.

Does this class ever actually receive any data from the serial port? Does the Arduino send any? If not, why not?

In fact, i was not listening for some input from arduino, now i added the inputstream listener, arduino should send back the same data it receives, but it is not sending, i don't know why. As i said, it seems arduino receives and recycles all data i'm not sending with its serial monitor D:

harlandraka94:
All of this works if i use the Arduino Serial Monitor, the stepper rotates 90 degrees clockwise, with this class it seems arduino is receiving and recycling all the data i send. Can anyone help me?

I understand that the Arduino does what you expect when you send characters manually using the serial monitor. I don't understand what happens when you use 'this class'. What do you mean by 'recycling' data? Does the class actually send the data? Does the Arduino receive it? Does it react correctly?

Recycling means it receive the data, cause i see the RX/TX led blinking, but the Serial.read() function does not read any character i sent with java…

I suppose that might be an indication that your Java program is not using the correct serial communication settings for the COM port. It will need to set the correct options for speed, parity and stop bits.

Two things in your code I don't understand... but I am no Java expert...

  1. you have String data = "A"; but you then code output.write(a); Where did the "a" get initialized?

  2. if(i==4) break; Why break on ONLY i==4

What is the code on the Arduino side?

RPCoyle:
Two things in your code I don’t understand… but I am no Java expert…

  1. you have String data = “A”; but you then code output.write(a); Where did the “a” get initialized?

  2. if(i==4) break; Why break on ONLY i==4

What is the code on the Arduino side?

Well, sorry, i modified, it was output.write(data.getBytes()), don’t know why it was output.write(a) in my first message.
Why break only on i==4? because i decided it has to send the same data 4 times

It seems i solved it, i’ve seen that my Arduino board ignores the first two bytes received consequently with serial communication, so i added two empty bytes at the beginning of the array, the Ascii code for “A” is 65, “A”.getBytes() returns {65}, so my array will become {0,0,65}, cause the first 2 bytes sent are ignored. It also wants a delay between transferring every byte, i don’t know why, but now my Arduino receives all the data i send correctly…