0

I used the below code sample to communicate with my Arduino-uno board. The board uses COM40. But when i ran this code from Eclipse, i get the message "Could not find COM port". The board connects via COM40 from the Arduino IDE. My machine is a 64bit Windows7.

package control;
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/ttyACM0", // Raspberry Pi
        "/dev/ttyUSB0", // Linux
        "COM40", // Windows
};
/**
* A BufferedReader which will be fed by a InputStreamReader 
* converting the bytes into characters 
* making the displayed results codepage independent
*/
private BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;

public void initialize() {
            // the next line is for Raspberry Pi and 
            // gets us into the while loop and was suggested here was suggested http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186
            System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");

    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 {
        // open serial port, and use class name for the appName.
        serialPort = (SerialPort) portId.open(this.getClass().getName(),
                TIME_OUT);

        // set port parameters
        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();

        // add event listeners
        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);
    } catch (Exception e) {
        System.err.println(e.toString());
    }
}

/**
 * This should be called when you stop using the port.
 * This will prevent port locking on platforms like Linux.
 */
public synchronized void close() {
    if (serialPort != null) {
        serialPort.removeEventListener();
        serialPort.close();
    }
}

/**
 * Handle an event on the serial port. Read the data and print it.
 */
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());
        }
    }
    // 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");
}

}

Ted Mad
  • 75
  • 2
  • 14
  • If you're COM40 is what device manager lists for your Uno can you also try `"\\\\.\\COM40"` ? – George Profenza Sep 17 '14 at 23:15
  • I tried that, but still i get the same output! – Ted Mad Sep 17 '14 at 23:31
  • Are you sure no one else is using that port? – frarugi87 Sep 18 '14 at 12:09
  • It is the port that is used by the arduino IDE. Communication between the arduino board and the IDE is just fine as i can upload sketches and view the output via the serial monitor. – Ted Mad Sep 18 '14 at 12:17
  • Very strange. Unfortunately I don't have enough time at the moment to debug but I have a hacky suggestion: try [Processing](https://processing.org/download/?processing). If you go to **Examples > Libraries > serial** you should be able to modify one of the samples to use your port and see if the port can be opened to begin with. If it does, go one step further and try reading/writing to the port. If this is all fine, you can use the Processing's serial library in your java project, or see it's implementation (e.g. `C:\Program Files (x86)\processing-2.0.1\modes\java\libraries\serial`). HTH – George Profenza Sep 18 '14 at 12:38
  • @GeorgeProfenza i used this sketch [sketch](http://arduinobasics.blogspot.co.uk/2012/07/arduino-basics-simple-arduino-serial.html) , and i was able to read and write to the arduino board via serial communication. I will check out the Processing's serial library, and if you find a solution to this please get back her and post it. – Ted Mad Sep 18 '14 at 16:36
  • so there is a problem with your implementation above, have a look at `C:\Program Files (x86)\processing-2.0.1\modes\java\libraries\serial\src\processing\serial\Serial.java`. Note that their implementation depends on Processing's PApplet class, but it's fairly easy to understand what's going on, so you can reuse code for your own thing – George Profenza Sep 18 '14 at 19:01
  • Did you find a solution for this ? – Ced May 28 '15 at 21:26

2 Answers2

1

This code is working with both, Arduino and Raspberry Pi.

But in order to run that properly with Arduino, you need to comment (or delete) this line of code "System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");". It is the first line of public void initialize()

0

On Windows, just deleted the following line:

System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");
Matheus Santz
  • 538
  • 6
  • 7