Aplikasi Serial Terminal Berbasis Java Menggunakan NetBeans IDE (Menggunakan SimpleSerialNative.dll)

_________________________________________

Buatlah New Project.

Pilih Java Aplication lalu Next. Setelah itu isilah Project Name dengan nama java serial dan uncheck Create Main Class lalu Finish.

Setelah itu, buatlah form baru pada Source Packages dengan cara klik kanan pada <default package> lalu pilih New, lalu JFrame Form…

Lalu isilah Class Name dengan serialport lalu Finish.

Lalu copy file SimpleSerial.java dan SimpleSerialNative.java ke folder src pada folder project yang dikerjakan dan copy juga file SimpleSerialNative.dll ke directory folder project sehingga tampak pada window Projects seperti gambar di bawah ini.

Setelah itu buatlah form seperti di bawah ini.

Control Property Value
JFrame Title Java Serial Port
Status_label Text Status:
Receive_textarea lineWrap True
Receive_textarea wrapStyleWord True

Lalu ketiklah kode di bawah ini. kode di bawah adalah kode untuk form GUI

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * java_terminal.java
 *
 * Created on Aug 21, 2011, 11:12:42 PM
 */
/**
 *
 * @author Administrator
 */
import javax.swing.*;

public class java_terminal extends javax.swing.JFrame {

    /** Creates new form java_terminal */
    public java_terminal() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    //
    private void initComponents() {

        textField1 = new java.awt.TextField();
        connect_button = new javax.swing.JButton();
        disconnect_button = new javax.swing.JButton();
        com_label = new javax.swing.JLabel();
        com_combobox = new javax.swing.JComboBox();
        send_textarea = new javax.swing.JTextField();
        kirim_button = new javax.swing.JButton();
        baudrate_combobox = new javax.swing.JComboBox();
        baudrate_label = new javax.swing.JLabel();
        format_data = new javax.swing.JLabel();
        status_label = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        receive_textarea = new javax.swing.JTextArea();
        clear_button = new javax.swing.JButton();

        textField1.setText("textField1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("WangReady Java Serial Terminal");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        connect_button.setText("Connect");
        connect_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connect_buttonActionPerformed(evt);
            }
        });

        disconnect_button.setText("Disconnect");
        disconnect_button.setEnabled(false);
        disconnect_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                disconnect_buttonActionPerformed(evt);
            }
        });

        com_label.setText("COM yg tersedia");

        kirim_button.setText("Kirim");
        kirim_button.setEnabled(false);
        kirim_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                kirim_buttonActionPerformed(evt);
            }
        });

        baudrate_combobox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "110", "300", "600", "1200", "2400", "4800", "9600", "14400", "19200", "38400", "56000", "57600", "115200" }));

        baudrate_label.setText("Baudrate");

        format_data.setText("Format data 8N1");

        status_label.setText("Status:");
        status_label.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        receive_textarea.setColumns(20);
        receive_textarea.setEditable(false);
        receive_textarea.setLineWrap(true);
        receive_textarea.setRows(5);
        receive_textarea.setWrapStyleWord(true);
        receive_textarea.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setViewportView(receive_textarea);

        clear_button.setText("Bersihkan layar data terima");
        clear_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clear_buttonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(status_label, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(baudrate_combobox, javax.swing.GroupLayout.Alignment.TRAILING, 0, 87, Short.MAX_VALUE)
                            .addComponent(com_combobox, javax.swing.GroupLayout.Alignment.TRAILING, 0, 87, Short.MAX_VALUE)
                            .addComponent(com_label)
                            .addComponent(baudrate_label, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(format_data)
                            .addComponent(connect_button, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
                            .addComponent(disconnect_button, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(clear_button)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(send_textarea, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(kirim_button)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(com_label)
                        .addGap(3, 3, 3)
                        .addComponent(com_combobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(baudrate_label)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(baudrate_combobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(format_data)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(connect_button))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(disconnect_button)
                    .addComponent(clear_button))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(status_label, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(send_textarea, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                    .addComponent(kirim_button))
                .addContainerGap())
        );

        pack();
    }//
    private SimpleSerialNative ss;
    private void connect_buttonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        String com_string = com_combobox.getSelectedItem().toString();
        int com_port = Integer.parseInt(com_string.substring(3));
        int baudrate = Integer.parseInt(baudrate_combobox.getSelectedItem().toString());
        try{
            ss = new SimpleSerialNative(com_port,baudrate, 8, SimpleSerialNative.ONESTOPBIT, SimpleSerialNative.NOPARITY);
            if(!ss.isValid()){
                status_label.setText("Status: PORT"+com_port +" tidak bisa digunakan. Coba PORT yang lain");
            }else{
                status_label.setText("Status: Connected... COM"+Integer.toString(com_port)+" Baudrate:"+Integer.toString(baudrate)+"bpsCatatan: Disconect apabila ingin close");
                disconnect_button.setEnabled(true);
                kirim_button.setEnabled(true);
                connect_button.setEnabled(false);
                setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

                new Thread(new ReadThread()).start();
            }
        }
        catch(Exception e){
            status_label.setText("Status: PORT tidak bisa digunakan. Coba PORT yang lain");
        }
    }

 /**
 * Buffer to hold the reading
 */
private byte[] readBuffer = new byte[400];

private void readSerial() {
    try {
        int availableBytes = ss.available();
        if (availableBytes > 0) {
            // Print it out
           receive_textarea.append(ss.readString());
        }
    } catch (Exception e) {
    }
}

private  class ReadThread implements Runnable {
        @Override
    public void run() {
        while(true) {
            readSerial();
        }
        }
    }

    private void disconnect_buttonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
         ss.close();
         status_label.setText("Status: Disconnected");
         disconnect_button.setEnabled(false);
         kirim_button.setEnabled(false);
         connect_button.setEnabled(true);
         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    private void kirim_buttonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        ss.writeString(send_textarea.getText());
        send_textarea.setText(null);
    }

    private void clear_buttonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        receive_textarea.setText(null);
    }

    private Object makeObj(final String item)  {
     return new Object() {@Override
 public String toString() { return item; } };
   }

    private void formWindowOpened(java.awt.event.WindowEvent evt) {
        // TODO add your handling code here:
        for(int ii = 0;ii < 50;ii++){
            try{
                ss = new SimpleSerialNative(ii+1);
                if(ss.available()==0){
                    com_combobox.addItem(makeObj("COM" + Integer.toString(ii + 1)));
                }
                ss.close();
            }
            catch(Exception e){

            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new java_terminal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JComboBox baudrate_combobox;
    private javax.swing.JLabel baudrate_label;
    private javax.swing.JButton clear_button;
    private javax.swing.JComboBox com_combobox;
    private javax.swing.JLabel com_label;
    private javax.swing.JButton connect_button;
    private javax.swing.JButton disconnect_button;
    private javax.swing.JLabel format_data;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton kirim_button;
    private javax.swing.JTextArea receive_textarea;
    private javax.swing.JTextField send_textarea;
    private javax.swing.JLabel status_label;
    private java.awt.TextField textField1;
    // End of variables declaration
}

Setelah semuanya selesai, Run Project atau F6. Jika berhasil, lalu Build Project atau F11, maka akan muncul forlde dist pada folder project yang berisi file .jar yang siap dijalankan. Akan tetapi file .jar tadi memerlukan file SimpleSerialNative.dll, maka copy file tersebut ke folder dist.

Berikut file yang berisi SimpleSerial.zip yang digunakan sebagai library.

Berikut file project.

http://www.mediafire.com/file/vtmd6kv1tb8sa2m/wangready-java%20terminal.rar

update REVISI

http://www.mediafire.com/?fclogl61qpldqq8

_______________________________

Daftar Pustaka

alumni.media.mit.edu/~benres/simpleserial/

About these ads

18 Responses to Aplikasi Serial Terminal Berbasis Java Menggunakan NetBeans IDE (Menggunakan SimpleSerialNative.dll)

  1. mulyawan says:

    Maaf mas, apakah aplikasi atas bisa dipakai untuk J2ME?
    jadi membaca data serial di HP..
    kalau bisa, apa perbedaannya?
    mohon bantuannya..

    • wangready says:

      program yg di atas sya coba di Windows + file SimpleSerialNative.dll. Sya pernah coba di Linux gk jalan, gara2 gk baca file SimpleSerialNative.dll. Jd sya ragu klo program di atas bisa dipake di OS lain untuk J2ME…

  2. Sahabat says:

    Maaf krn Saya baru belajar , bisa diperjelas pada saat pembuatan form-nya, utk pengisian di properties yang perlu dirubah apa saja. Sebelumnya sy ucapkan terimakasih.

    • wangready says:

      yang perlu dirubah pada window property untuk setiap komponen, langsung klik kanan aja di koponennya (misal, button, text area, atau JFrame). Lengkapnya bisa dilihat di project yg bisa di download dari link di atas. control:nama komponennya; property: bagian fungsi dari window property;value: nilai dari yang mengatur fungsi dari komponen.

      Control Property Value
      JFrame Title Java Serial Port
      Status_label Text Status:
      Receive_textarea lineWrap True
      Receive_textarea wrapStyleWord True
  3. cleverguys says:

    how can get SimpleSerialNative.dll for 64 bit platforms

  4. Joko says:

    Terima kasih sebelumnya ama penjelasannya
    Waktu itu, saya pasang kabel serial dari PC ke FPGA, tapi knp GUI saya g mendeteksi y??
    Kalo saya pake virtual serial emulator bisa jalan, GUi nya ke detect..
    Tolong penjelasannya thx..

    • wangready says:

      sya jg gk tau mas, terakhir saya coba juga gtu, gk kedetek…

      • Joko says:

        Akhirnya saya sdh tau kesalahannya, pas di simpleserialnative.java

        SimpleSerialNative(int comPort, int baud, int dataBits, int stopBits, int parity) {
        _initPort( convertToCommString(comPort), baud, 8, ONESTOPBIT, parity);
        }

        Untuk yang baudrate, port ama parity bs diubah2 tapi kalo yang databits ama stopbits didefault aj jd 8 ama ONESTOPBIT abis itu ud bs ke detect dh.

      • Dede says:

        Terima kasih mas atas perbaikan kodingnya, port komunikasi serial terdeteksi.
        Mas saya punya masalah apabila textarea terisi penuh dengan data atau huruf maka scrool nya malah lari nya ke atas,
        Jadi apabila ada text baru yang masuk text tersebut tidak kelihatan pada textarea, kecuali scrool nya di digeser manual ke bawah untuk melihat data yang baru masuk karena posisinya berada paling bawah text area
        mohon pencerahaanya.

      • wangready says:

        gk tau gan, udah lama gk ngoprek java lg…
        coba aja gan dibatasi jumlah huruf yg dapat ditampung di textarea nya….

  5. Ayodya says:

    Mas tolong dong source code yg build xml yg lengkapnya gmna?
    soalnya saya bingung, pas saya copas semua ke build.xml sebelum
    gak bisa run other mas

  6. rizki says:

    salam kenal mas :)

    mau tanya, saya sudah coba program yg mas buat. tapi waktu di eksekusi kok GUI-nya gak bisa nge-detect COMPort ya…? saya menggunakan 2 COM Port, dngn setting 9600 8N1 utk ke 2 COM Port tsb.

    saya menggunakan RxTX
    Native lib Version = RXTX-2.1-7
    Java lib Version = RXTX-2.1-7

  7. fa says:

    ni kenpa PORT nya g kedetect, padahal pada hal cuma dihubung kn laptop ke laptop

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.