java – Serial Communication with Precision Scale

Question:

I'm developing an application to measure the solder flux that passes through the board on a production line, but I'm having a bit of difficulty connecting the precision scale with the PC via serial port. I'm using the JAVA language and the javax.comm api, if anyone can help me or if you know another way to make this communication, help me!!!

Answer:

Well, I work a lot with serial here and I'll give you some tips about the javax.comm API, it's very outdated, I recommend using java rxtx (it's not hard to find), for it to work, you have to use its respective DLL's according to the installed Java (OS x64 and Java x86, DLL x86), here are some code examples:

import gnu.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.ArrayList;

public class serial{
    public SerialPort serialPort;
    private OutputStream outStream;
    private InputStream inStream;

/**
 * Get the serial ports available
 * @return The existing ports
 */
public String[] getPortas (){
    ArrayList<String> portas = new ArrayList<String>();
    //System.out.println(java.library.path);
    CommPortIdentifier serialPortId;
    //static CommPortIdentifier sSerialPortId;
    Enumeration<?> enumComm;
    //SerialPort serialPort;
    enumComm = CommPortIdentifier.getPortIdentifiers();
    while (enumComm.hasMoreElements()) {
        serialPortId = (CommPortIdentifier) enumComm.nextElement();
        if(serialPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            portas.add(serialPortId.getName());
        }
    }
    return portas.toArray(new String[portas.size()]);
}

/**
 * Connect to the given port
 *
 * @param portName The name from the port to be connected
 * @throws NoSuchPortException
 * @throws PortInUseException
 * @throws IOException
 */
public void connect(String portName) throws NoSuchPortException, PortInUseException, IOException {
        // Obtain a CommPortIdentifier object for the port you want to open
        CommPortIdentifier portId =
                CommPortIdentifier.getPortIdentifier(portName);

        // Get the port's ownership
        serialPort =
                (SerialPort) portId.open("Demo application", 5000);

        // Set the parameters of the connection.
        setSerialPortParameters();

        // Open the input and output streams for the connection. If they won't
        // open, close the port before throwing an exception.
        outStream = serialPort.getOutputStream();
        inStream = serialPort.getInputStream();

        serialPort.notifyOnDataAvailable(true);
}

public InputStream getSerialInputStream() {
    return inStream;
}

public OutputStream getSerialOutputStream() {
    return outStream;
}

private void setSerialPortParameters() throws IOException {
    int baudRate = 9600; // 19200bps
    try {
        // Set serial port to 19200bps-8N1
        serialPort.setSerialPortParams(
                baudRate,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);

        serialPort.setFlowControlMode(
                SerialPort.FLOWCONTROL_NONE);
    } catch (UnsupportedCommOperationException ex) {
        throw new IOException("Unsupported serial port parameter");
    }
}


public void disconnect() {
    if (serialPort != null) {
        try {
            outStream.close();
            inStream.close();
            serialPort.notifyOnDataAvailable(false);
            serialPort.removeEventListener();
        } catch (IOException ex) {
            // don't care
        }
        // Close the port.
        serialPort.close();
    }
}

public void enviaString (String b) throws IOException{
    enviaBytes(b.getBytes());
}


public void enviaBytes (byte[] b){
    try {
        outStream.write(b);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

With this class it is possible to send and receive data from Serial, in the main class it is necessary to connect to some port (the available ports can be seen with the getPortas method in the class above), and create a listener to receive the data.

serial porta = new serial();
porta.connect(n);
porta.serialPort.addEventListener(new SerialPortEventListener() {

                                @Override
                                public void serialEvent(SerialPortEvent arg0) {
                                    switch (arg0.getEventType()) {
                                    case SerialPortEvent.DATA_AVAILABLE:
                                        leSerial();
                                        break;
                                    }
                                }
                            });

private void leSerial() {
    InputStream inStream = porta.getSerialInputStream();
    try {
        int availableBytes = inStream.available();
        byte dadosRecebidos[] = new byte[availableBytes];
        if (availableBytes > 0) {
            // Read the serial port
            inStream.read(dadosRecebidos, 0, availableBytes);
        }
    } catch (IOException e) {

    }
}

and to send data use the methods of the serial class sendString and sendBytes.

Scroll to Top