0

First project, its only out of interest so i can learn.

I am trying to make an app that will send a string down a comm port. Below is my GUI (first attempt!)

I have created buttons and they do things but now i need to add the com port functionality.

Please can someone give me a pointer? In the most simple language possible please. I am self taught.

import java.awt.GridLayout;
import java.io.*;
import javax.swing.*;

import java.util.*;



public class AlarmGenerator extends javax.swing.JFrame {

public AlarmGenerator() {
    initComponents();
}


private void initComponents() {

    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();


    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jTextField1.setText("Enter Custom String Here");
    jTextField2.setText("Result");
    jButton1.setText("Alarm1");
    jButton2.setText("Alarm2");
    jButton3.setText("Alarm3");
    jButton4.setText("Custom Alarm");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()               

                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)    
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4)
                    .addComponent(jTextField1)
                    .addComponent(jTextField2)

    )));
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()

            .addComponent(jButton1)
            .addComponent(jButton2)
            .addComponent(jButton3)
            .addComponent(jButton4)
            .addComponent(jTextField1)
            .addComponent(jTextField2)

            .addContainerGap(0, Short.MAX_VALUE))
    );

    pack();

    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }

        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextField2.setText("Alarm 1 Activated, String: "+alarm1);
        }
    });

    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }

        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextField2.setText("Alarm 2 Activated, String: "+alarm2);
        }
    });

    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }

        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextField2.setText("Alarm 3 Activated, String: "+alarm3);
        }
    });

    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }

        private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextField2.setText("Custom alarm, string sent: "+jTextField1.getText ());
        }
    });
}                       

public static void main(String args[]) {        

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new AlarmGenerator().setVisible(true);


        }
    });


}

// Variables declaration                    
private static javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
String alarm1 = "Hello";
String alarm2 = "Bye";
String alarm3 = "Custom";
// End of variables declaration                   
}

Class 2

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

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class TwoWaySerialComm {
public TwoWaySerialComm() {
    super();
}

void connect(String portName) throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier
            .getPortIdentifier(portName);
    if (portIdentifier.isCurrentlyOwned()) {
        System.out.println("Error: Port is currently in use");
    } else {
        CommPort commPort = portIdentifier.open(this.getClass().getName(),
                2000);

        if (commPort instanceof SerialPort) {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

            InputStream in = serialPort.getInputStream();
            OutputStream out = serialPort.getOutputStream();

            (new Thread(new SerialReader(in))).start();
            (new Thread(new SerialWriter(out))).start();

        } else {
            System.out
                    .println("Error: Only serial ports are handled by this example.");
        }
    }
}

/** */
public static class SerialReader implements Runnable {
    InputStream in;

    public SerialReader(InputStream in) {
        this.in = in;
    }

    public void run() {
        byte[] buffer = new byte[1024];
        int len = -1;
        try {
            while ((len = this.in.read(buffer)) > -1) {
                System.out.print(new String(buffer, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/** */
public static class SerialWriter implements Runnable {
    OutputStream out;

    public SerialWriter(OutputStream out) {
        this.out = out;
    }

    public void run() {
        try {
            int c = 0;
            while ((c = System.in.read()) > -1) {
                this.out.write(c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static void main(String[] args) {
    try {
        (new TwoWaySerialComm()).connect("COM3");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}
Display Name
  • 405
  • 6
  • 26

2 Answers2

2

Take a look at this link.

It will give more insight in how to send data via COM port

How to send data to COM PORT using JAVA?

this page links to some of the possible answers

Java Serial Communication on Windows

Is there Java library or framework for accessing Serial ports?

Reading serial port in Java

and two other answers which are basically equal as the reading serial ports answer.

private TwoWaySerialComm twoWaySerCom;

public AlarmGenerator() {

    initComponents();   

    twoWaySerCom = new TwoWaySerialComm();

    try {

        twoWaySerCom.connect("COM1");
    } 
    catch (Exception e) {

        e.printStackTrace();
    }
}

I noticed you have multiple

 public static void Main(string[] args)

in your project those are project entries and one should be sufficient.

Community
  • 1
  • 1
Blaatz0r
  • 1,205
  • 1
  • 12
  • 24
  • Hi, Thanks of the pointers. I have read through those but they are a little advanced for me. I have added the RXTX Api and i created a new class using an example i found on the internet. See below. How to i pass the string from the first class to the second class? – Display Name Jan 16 '15 at 07:23
  • Patrick I have edited my answer you should be able to use it this way – Blaatz0r Jan 16 '15 at 11:18
  • Hi Blaatz0r, Thanks for your assistance i did that and i can now open the Com port. I have a jbutton and i want to send the string that is String 1 on the button press. can you give another pointer on that? – Display Name Feb 06 '15 at 01:52
  • Hi Patrick what you want to do is to convert your string to an array of bytes. that can be transfered by a send. I won't be able to go into this directly (@ the office :)) but will try to get to this tonight when I get back. – Blaatz0r Feb 06 '15 at 08:00
  • In such a case it is common practice to use the COMPort object as a field (e.g define it in the class and not in a function) so you can reference the object. below is some pseudo code class x public x () { port = new comport(); } private COMPort port; public onbuttonclick() { comport.Write( ("string value").tobytearray() ); } – Blaatz0r Feb 08 '15 at 11:47
0

If you're using Linux, I've created a Java package, j232, and native library, libj232, that's open source and hosted on GitHub. It should be considered a 'work-in-progress' and currently only handles synchronous serial data.

The main Java package is here and its associated native library here. Also take a look at the wiki for j232 and finally the example page.

D-Dᴙum
  • 7,689
  • 8
  • 58
  • 97