Serial Communication Example using Pi4J.

The following example demonstrates how to transmit and receive data using the Raspberry Pi serial port.
(A complete article on building and installing a serial port on the Raspberry Pi is available here:  http://www.savagehomeautomation.com/projects/raspberry-pi-installing-a-rs232-serial-port.html)

Prerequisites

By default, the serial port on the Raspberry Pi is configured as a console port for communicating with the Linux OS shell. If you want to use the serial port in a software program, you must disable the OS from using this port. Please see this blog article by Clayton Smith for step-by-step instructions on how to disable the OS console for this port: http://www.irrational.net/2012/04/19/using-the-raspberry-pis-serial-port/

Source Code

The source code for this example is included in the github repository:
https://github.com/Pi4J/pi4j/tree/master/pi4j-example/src/main/java/SerialExample.java


/*
 * #%L
 * **********************************************************************
 * ORGANIZATION  :  Pi4J
 * PROJECT       :  Pi4J :: Java Examples
 * FILENAME      :  SerialExample.java  
 * 
 * This file is part of the Pi4J project. More information about 
 * this project can be found here:  http://www.pi4j.com/
 * **********************************************************************
 * %%
 * Copyright (C) 2012 - 2013 Pi4J
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */


import java.util.Date;

import com.pi4j.io.serial.Serial;
import com.pi4j.io.serial.SerialDataEvent;
import com.pi4j.io.serial.SerialDataListener;
import com.pi4j.io.serial.SerialFactory;
import com.pi4j.io.serial.SerialPortException;

/**
 * This example code demonstrates how to perform serial communications using the Raspberry Pi.
 * 
 * @author Robert Savage
 */
public class SerialExample {
    
    public static void main(String args[]) throws InterruptedException {
        
        // !! ATTENTION !!
        // By default, the serial port is configured as a console port 
        // for interacting with the Linux OS shell.  If you want to use 
        // the serial port in a software program, you must disable the 
        // OS from using this port.  Please see this blog article by  
        // Clayton Smith for step-by-step instructions on how to disable 
        // the OS console for this port:
        // http://www.irrational.net/2012/04/19/using-the-raspberry-pis-serial-port/
                
        System.out.println("<--Pi4J--> Serial Communication Example ... started.");
        System.out.println(" ... connect using settings: 38400, N, 8, 1.");
        System.out.println(" ... data received on serial port should be displayed below.");
        
        // create an instance of the serial communications class
        final Serial serial = SerialFactory.createInstance();

        // create and register the serial data listener
        serial.addListener(new SerialDataListener() {
            @Override
            public void dataReceived(SerialDataEvent event) {
                // print out the data received to the console
                System.out.print(event.getData());
            }            
        });
                
        try {
            // open the default serial port provided on the GPIO header
            serial.open(Serial.DEFAULT_COM_PORT, 38400);
            
            // continuous loop to keep the program running until the user terminates the program
            for (;;) {
                try {
                    // write a formatted string to the serial transmit buffer
                    serial.write("CURRENT TIME: %s", new Date().toString());
    
                    // write a individual bytes to the serial transmit buffer
                    serial.write((byte) 13);
                    serial.write((byte) 10);
    
                    // write a simple string to the serial transmit buffer
                    serial.write("Second Line");
    
                    // write a individual characters to the serial transmit buffer
                    serial.write('\r');
                    serial.write('\n');
    
                    // write a string terminating with CR+LF to the serial transmit buffer
                    serial.writeln("Third Line");
                }
                catch(IllegalStateException ex){
                    ex.printStackTrace();                    
                }
                
                // wait 1 second before continuing
                Thread.sleep(1000);
            }
            
        }
        catch(SerialPortException ex) {
            System.out.println(" ==>> SERIAL SETUP FAILED : " + ex.getMessage());
            return;
        }
    }
}

JavaDoc

The following JavaDoc links are the primary interfaces used to communicate via the Pi's serial ports:

Wiring Diagram

The circuit below illustrates a RS232 serial port connected to the Raspberry Pi's GPIO header.
The following circuit can be used in conjunction with this sample code.

(A complete article on building and installing a serial port on the Raspberry Pi is available here:  http://www.savagehomeautomation.com/projects/raspberry-pi-installing-a-rs232-serial-port.html)

(click here for hi-resolution image)

Navigate

If you have not already downloaded and installed the Pi4J library on the RaspberryPi, then view this page for instructions on where to download and how to install Pi4J:
Download & Install Pi4J

First, locate the SerialExample.java source file in the samples folder of the Pi4J installation on the RaspberryPi.
You can use the following command on the Pi's console or SSH terminal to navigate to this path:
cd /opt/pi4j/examples

Compile

Next, use the following command to compile this example program:

javac -classpath .:classes:/opt/pi4j/lib/'*' -d . SerialExample.java

Execute

The following command will run this example program:

sudo java -classpath .:classes:/opt/pi4j/lib/'*' SerialExample

Output

To test this program you will need to connect your computer via serial cable and use a serial communications tool such as Hyperterminal or Indigo Terminal Emulator. Establish a connection using baud rate 34800 with parity set to NONE, data bits to 8 and stop bits to 1. (38400,N,8,1) Once connected you should see the following data displayed in the terminal software:

CURRENT TIME: <Date/Time>
Second Line
Third Line

This data should be repeated every second.

 <br />You can also submit data from the terminal software and that data should be displayed on the Raspberry Pi's console.