Mikedowney.co.uk
What's New
Site Map

Diary
Astronomy
Bits N Bobs
Computing
Food And Drink
Links
Photography
Welcome


Recipe Collections
Recipe A Week 2013
Recipe A Week 2010
A-Z of Regional Cakes
Alphabet of Nations

Using the Raspberry Pi serial port from Java

Story location: Home / computing / raspberry_pi /
25/Feb/2017

A couple of days ago I wrote about connecting the Raspberry Pi to the NodeMCU microprocessor board. I originally used Python since I find that the easiest for testing ideas or simple prototyping. Since I use Java for most of my application programming, I thought I should work out how to do the same thing in Java too.

Luckily there is a Java serial comms library called RxTx which is available precompiled for Debian Linux and can be installed on the Raspberry Pi simply by typing

sudo apt-get install librxtx-java

The jar file is placed in /usr/share/java/RXTXcomm.jar (and doesn't seem to be added automatically to the classpath) so to compile any code, you'll need to use something like

javac -cp /usr/share/java/RXTXcomm.jar:. SerialTest.java

and to run the code you need to reference both the jar and the JNI library, using

java -cp /usr/share/java/RXTXcomm.jar:. -Djava.library.path=/usr/lib/jni SerialTest

The Code

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.*
import java.util.Scanner;

public class SerialTest{

    public static void main(String[] args) throws Exception{
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("/dev/ttyS0");
        CommPort commPort = portIdentifier.open("Java Serial Test",1000);
        System.out.println("Opened Port");

        SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

        String[] leds = new String[]{"r","g","b","off"};

                try(BufferedInputStream in = new BufferedInputStream(serialPort.getInputStream());
                BufferedOutputStream out = new BufferedOutputStream(serialPort.getOutputStream());
        Scanner s = new Scanner(in)){

            for(String c : leds){
                out.write(c.getBytes());
                out.flush();
                System.out.println(s.next());
                Thread.sleep(1000);
            }
        }
    }
}

I saved the code as SerialTest.java and compiled it and ran it using the commands above. It expects the serial.lua file to already be running on the NodeMCU board, either by running the python script from last time or by executing

python nodemcu-uploader.py --port /dev/serial0 file do serial.lua

As you can see, the code is much more verbose than the Python version but it gets the job done.