SerialSender.java

Java for Small Spaces
Java on a chip
by Chris Carpenter
Listing 4. SerialSender.java.


/**
    SerialSender sends text to the connected display
**/
package bookshelf.utils;

import javax.comm.*;
import java.util.*;

public class SerialSender {
    protected static final int CLEAR_SCREEN = 12;
    protected static SerialSender serialSender;
    protected Enumeration portList;
    protected CommPortIdentifier portId;
    protected SerialPort serialPort;
public SerialSender() {
    super();
}
public static SerialSender getCurrent(){
    if(serialSender == null)
        serialSender = new SerialSender();

    return serialSender;
}
public void sendData(String dataToSend) {

    try {
        setupAndCaptureSerialPort();

serialPort.getOutputStream().write(new byte[] {CLEAR_SCREEN});
serialPort.getOutputStream().write(dataToSend.getBytes());
    } catch (Exception e) {
        System.out.println("Exception caught setting up serial port in sendData. " + e);
    } catch (Error err) {
        System.out.println(err);
    } finally {
        serialPort.close();
    }
}
public void setupAndCaptureSerialPort() {
    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
        portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        if (portId.getName().equalsIgnoreCase("COM1"))
                break;
        if (portId.getName().equalsIgnoreCase("serial0"))
                break;
        }
    }

    try {
        serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
    } catch (PortInUseException e) {
    System.out.println("PortInUseException in DataSendTester.
setupAndCaptureSerialPort()");
    }
    try {
        serialPort.setSerialPortParams(
            9600,
            SerialPort.DATABITS_8,
            SerialPort.STOPBITS_1,
            SerialPort.PARITY_NONE);
    } catch (UnsupportedCommOperationException e) {
    }
}
}

About the Author

Chris Carpenter is a software engineer and architect at RoleModel Software, Inc. in Holly Springs, NC. He can be contacted at [email protected].