Wednesday, September 3, 2014

Java serial communication with Arduino Uno with jSSC, on Raspberry Pi

jSSC (Java Simple Serial Connector) - library for working with serial ports from Java. jSSC support Win32(Win98-Win8), Win64, Linux(x86, x86-64, ARM), Solaris(x86, x86-64), Mac OS X 10.5 and higher(x86, x86-64, PPC, PPC64).

This post show a Java program run on Raspberry Pi, using jSSC library, to send message to USB connected Arduino Uno board.


The development platform is a PC running Ubuntu with Netbeans 8, and deploy the program to Raspberry Pi remotely.

- To add jSSC library to our Netbeans Java project, read the post "Install and test java-simple-serial-connector with Arduino".

- The program code is almost same as the code on the page. With 3 seconds delay after serialPort.openPort(), to wait Automatic (Software) Reset on Arduino Uno board.
package java_jssc_uno;

import java.util.logging.Level;
import java.util.logging.Logger;
import jssc.SerialPort;
import jssc.SerialPortException;

public class Java_jSSC_Uno {

    public static void main(String[] args) {
        SerialPort serialPort = new SerialPort("/dev/ttyACM0");
        try {
            System.out.println("Port opened: " + serialPort.openPort());

            try {
                Thread.sleep(3000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("Java_jSSC_Uno".getBytes()));
            System.out.println("Port closed: " + serialPort.closePort());
        }
        catch (SerialPortException ex){
            System.out.println(ex);
        }
    }
    
}

- To deploy to Raspberry Pi remotely with Netbeans 8, refer to the post "Set up Java SE 8 Remote Platform on Netbeans 8 for Raspberry Pi".


For the sketch (and extra info) on Arduino Uno, read the post in my Arduino blog.


No comments: