Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java/Arduino - Read data from the Serial Port

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 here. Now, I didn't really understand how it works, but I tried to modify it and I got this:

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)>=3 && Integer.parseInt(ncom)<=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;
    }
}

I create the object Serial with the COM port I need in the main program, then I use Serial.read and Serial.write when I need it.

Serial.write works great, Arduino gets the data and show it in a LCD Display. The problem is Serial.read. When the program is running, it keep read from serial port (around every 40 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.

I know I need something like Serial.available(), I tried input.available(), but it doesn't work. I don't know how to solve this problem.

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

EDIT:

I changed the Serial class, now it has again this method as apremalal said

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());
            }
        }       
    }

and in the other class (Panel in this case) I've got this:

public void read(String data){
    System.out.println(data);
    System.out.println(data == "255");
    if(data == "255")
        //code here 
}

It print the values correctly but data == "255" is always false, even if I really get a 255 ....I tried to do Integer.parseInt but nothing changed. Why the hell?

EDIT 2: Ok solved :\

public void read(String data){

    serialRead = Integer.parseInt(data);

    if(serialRead == 255)
        //code here 
}

Now it's work..don't know why I had to do this... meh whatever :)

like image 622
gbos Avatar asked Apr 14 '13 06:04

gbos


2 Answers

The BufferedReader class has a ready() method that returns True if "the buffer is not empty, or if the underlying character stream is ready." and False otherwise. So you could add a check in the read() method to make sure there is data to be read before trying to read.

public synchronized int read(){

    int b = 0;  

    try{
        if (input.ready()) {
            b = (int)input.read();
        }
    }catch (Exception e) {
        System.err.println(e.toString());
    }
    return b;
}

It looks like the code has a try-catch in place to handle if those things fail, which is possibly what causes your lag because try-catch are quite expensive. So the input.ready() check should result in fewer exceptions.

like image 174
TheMerovingian Avatar answered Oct 22 '22 01:10

TheMerovingian


You don't want to specifically write a read function it's already there in the sample code.As TheMerovingian pointed out you can check the input Buffer before reading.Here is the working code which I have used in one of my projects.

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 SerialTest implements SerialPortEventListener {
SerialPort serialPort;
    /** The port we're normally going to use. */
private static final String PORT_NAMES[] = {                  "/dev/tty.usbserial-A9007UX1", // Mac OS X
        "/dev/ttyUSB0", // Linux
        "COM35", // Windows
};
private BufferedReader input;
private OutputStream output;
private static final int TIME_OUT = 2000;
private static final int DATA_RATE = 9600;

public void initialize() {
    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

    //First, Find an instance of serial port as set in PORT_NAMES.
    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);

        // open the streams
        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 close() {
    if (serialPort != null) {
        serialPort.removeEventListener();
        serialPort.close();
    }
}

public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            String inputLine=null;
            if (input.ready()) {
                inputLine = input.readLine();
                            System.out.println(inputLine);
            }

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
    // Ignore all the other eventTypes, but you should consider the other ones.
}

public static void main(String[] args) throws Exception {
    SerialTest main = new SerialTest();
    main.initialize();
    Thread t=new Thread() {
        public void run() {
            //the following line will keep this app alive for 1000    seconds,
            //waiting for events to occur and responding to them    (printing incoming messages to console).
            try {Thread.sleep(1000000);} catch (InterruptedException    ie) {}
        }
    };
    t.start();
    System.out.println("Started");
}
}

EDIT : serialEvent function is responsible for reading the buffer.

public synchronized void serialEvent(SerialPortEvent oEvent) {
 if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
    try {
        String inputLine=null;
        if (input.ready()) {
            inputLine = input.readLine();
            System.out.println(inputLine);
        }

    } catch (Exception e) {
        System.err.println(e.toString());
    }
 }
// Ignore all the other eventTypes, but you should consider the other ones.
}
like image 31
Anuruddha Avatar answered Oct 21 '22 23:10

Anuruddha