java 串口通信

背景

由于最近在做一个交通雷达项目,必须要接触到串口通信,将雷达的数据不断接收并处理,摸爬滚打了几天,浅显的谈谈串口通信是什么已经怎么去使用java串口通信。

环境

刚接触到串口通信时拿到的资料以及jar包是98年的javacomm20-win32.zip
由于发布时所适应的platform和JDK环境都已经难以匹配,故改用RXTX下载点击,
使用RXTX,和javacomm20基本是兼容的,除了引用的包有所不同,所以,在commapi(javacomm20-win32.zip)sample中给出的demo关于怎样去连接串口,读写数据都还可以使用,只需要import改为RXTX相应的包,即IO包,也可以使用快捷键快速修改,在eclipse是shift+Ctrl+O,功能就是自动整理所import的包。
对于RXTX包的引入,还是有几点需要说明的。当然这些点在官方doc中都是有说明的:

Windows
----------------------------------------------------
Choose your binary build - x64 or x86 (based on which version of
the JVM you are installing to)

NOTE: You MUST match your architecture.  You can't install the i386
version on a 64-bit version of the JDK and vice-versa.

For a JDK installation:

Copy RXTXcomm.jar ---> \jre\lib\ext
Copy rxtxSerial.dll ---> \jre\bin
Copy rxtxParallel.dll ---> \jre\bin

说明

串口通信是指在计算机连接了一些物理设备,设备可以通过连接电脑的串口(一般是RS-232,或转为USB-232)来传输数据,传输数据是双向的,既可以读也可以写。

java 串口通信_第1张图片
雷达和PC的连接关系

所以,对于Starter来说,一般会通过代码去了解怎样读取所用PC的串口号以及怎样连接此串口并读取物理设备通过串口发送来的数据。话不多说,看代码:

/**
 * 雷达参数设置
 */

package com.jky.radar;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.TooManyListenersException;

/**
 * 
 * @author edit WENTAO_Wanna
 * @author  original kotkis
 */
/* 串口监听 */
public class INT1 extends javax.swing.JFrame implements SerialPortEventListener {

    static CommPortIdentifier portId;
    static Enumeration portList;

    InputStream inputStream;
    static SerialPort serialPort;
    Thread readThread;

    static OutputStream outputStream;
    int radix = 16;
    String txt;

    ObjectInputStream inputFromClient;
    ObjectOutputStream outputToClient;

    String output = "";
    // 数据帧数
    int groupNums = 0;
    //用于存储接收的数据
    ArrayList outputData = new ArrayList();

    public MSComm() {

        // Creat Server,作为服务器端发送数据
        try {
            // Creat a Server Socket
            ServerSocket serverSocket = new ServerSocket(8000);
            System.out.println("Server Started!");

            // Creat data input and output streams      
            // inputFromClient = new ObjectInputStream(socket.getInputStream());

            // Listen for a connection request
            Socket socket = serverSocket.accept();
            outputToClient = new ObjectOutputStream(socket.getOutputStream());
        
            /*while (true) {
                // Receive param from the Client
                // TODO
                
            }*/
        }
        catch (IOException e) {
            System.err.println(e);
        }
        
        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.
     */
    // //GEN-BEGIN:initComponents
    private void initComponents() {
        defPane = new javax.swing.JFrame();
        defPane.setSize(new java.awt.Dimension(600, 480));
        // defPane.setSize(new Dimension(600, 480));

        setFrame = new javax.swing.JInternalFrame();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        ComBox = new javax.swing.JComboBox();
        BaudBox = new javax.swing.JComboBox();
        DataBox = new javax.swing.JComboBox();
        StopBox = new javax.swing.JComboBox();
        ParityBox = new javax.swing.JComboBox();
        FlowBox = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        setButton = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        closeset = new javax.swing.JButton();
        aboutFrame = new javax.swing.JInternalFrame();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanel2 = new javax.swing.JPanel();
        sfield = new javax.swing.JTextField();
        sendbutton = new javax.swing.JButton();
        testf = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        openp = new javax.swing.JButton();
        closep = new javax.swing.JButton();
        recBufft = new javax.swing.JTabbedPane();
        jScrollPane5 = new javax.swing.JScrollPane();
        asciiBuff = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        recBuff = new javax.swing.JTextArea();
        jScrollPane4 = new javax.swing.JScrollPane();
        decBuff = new javax.swing.JTextArea();
        jScrollPane6 = new javax.swing.JScrollPane();
        binBuff = new javax.swing.JTextArea();
        jMenuBar3 = new javax.swing.JMenuBar();
        filemenu = new javax.swing.JMenu();
        newPrj = new javax.swing.JMenuItem();
        Save = new javax.swing.JMenuItem();
        loadPrj = new javax.swing.JMenuItem();
        exitMenu = new javax.swing.JMenuItem();
        Buffer = new javax.swing.JMenu();
        Clearbuff = new javax.swing.JMenuItem();
        setmenu = new javax.swing.JMenu();
        comset = new javax.swing.JMenuItem();
        optMenu = new javax.swing.JMenuItem();
        helpmenu = new javax.swing.JMenu();
        aboutmenu = new javax.swing.JMenuItem();

        defPane.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        defPane.setTitle("串口设置");
        defPane.setLocation(750, 100);

        // full Screen
        // defPane.setMaximizedBounds(defPane.getMaximizedBounds());
        // defPane.setExtendedState(MAXIMIZED_BOTH);

        setFrame.getContentPane().setLayout(
                new java.awt.GridLayout(3, 6, 7, 10));

        setFrame.setClosable(true);
        setFrame.setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        setFrame.setPreferredSize(new java.awt.Dimension(300, 130));

        jLabel1.setText("串口端口");// com port
        setFrame.getContentPane().add(jLabel1);

        jLabel2.setText("波特率");// Baud Rate
        setFrame.getContentPane().add(jLabel2);

        jLabel3.setText("数据位");// Bits
        setFrame.getContentPane().add(jLabel3);

        jLabel4.setText("停止位");// Stop Bits
        setFrame.getContentPane().add(jLabel4);

        jLabel5.setText("奇偶校验");// Parity
        setFrame.getContentPane().add(jLabel5);

        jLabel6.setText("流控制");// Flow Control
        setFrame.getContentPane().add(jLabel6);

        ComBox.setModel(new javax.swing.DefaultComboBoxModel(
                new String[] { "COM1" }));
        setFrame.getContentPane().add(ComBox);

        BaudBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "38400", "300", "600", "1200", "2400", "4800", "9600", "19200",
                "57600", "115200" }));
        setFrame.getContentPane().add(BaudBox);

        DataBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "8", "7", "6" }));
        setFrame.getContentPane().add(DataBox);

        StopBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "1", "2" }));// STOPBITS_2,STOPBITS_1
        setFrame.getContentPane().add(StopBox);

        ParityBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "无", "奇", "偶" }));// PARITY_NONE,PARITY_ODD,PARITY_EVEN
        setFrame.getContentPane().add(ParityBox);

        FlowBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "无", "RTSCTS_IN模式", "RTSCTS_OUT模式", "XONXOFF_IN模式",
                "XONXOFF_OUT模式" }));
        // FlowBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
        // "FLOWCONTROL_NONE", "FLOWCONTROL_RTSCTS_IN",
        // "FLOWCONTROL_RTSCTS_OUT", "FLOWCONTROL_XONXOFF_IN",
        // "FLOWCONTROL_XONXOFF_OUT" }));
        setFrame.getContentPane().add(FlowBox);

        setFrame.getContentPane().add(jLabel7);

        setButton.setText("确定");// OK
        setButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setButtonActionPerformed(evt);
            }
        });

        setFrame.getContentPane().add(setButton);

        setFrame.getContentPane().add(jLabel9);

        setFrame.getContentPane().add(jLabel8);

        closeset.setText("取消");// 取消
        closeset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closesetActionPerformed(evt);
            }
        });

        setFrame.getContentPane().add(closeset);

        defPane.getContentPane().add(setFrame, java.awt.BorderLayout.NORTH);

        aboutFrame.setClosable(true);
        aboutFrame
                .setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        aboutFrame.setMinimumSize(new java.awt.Dimension(95, 39));
        aboutFrame.setPreferredSize(new java.awt.Dimension(600, 300));
        try {
            aboutFrame.setSelected(true);
        } catch (java.beans.PropertyVetoException e1) {
            e1.printStackTrace();
        }
        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jTextArea1
                .setText("-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\t\t\t                RS232TM 0.2 Alpha by Kotkis\n\n \t\t\t       This program can be freely distributed under GPL \n\n\t\t\t       For help ,support , bug report and everything else \n\n\t\t\t              http://www.sourceforge.net/rsmon\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n JRE 1.5 or later is needed to run this program - http://sun.java.com\n Also javacomm20-win32  is needed - \n\nhttp://javashoplm.sun.com/ECom/docs/Welcome.jsp?StoreId=22&PartDetailId=7235-javacomm-2.0-spec-oth-JSpec&SiteId=JSC&TransactionId=noreg\n\nhttp://www.freepoc.org/download/javacomm20-win32.zip");
        jScrollPane1.setViewportView(jTextArea1);

        aboutFrame.getContentPane().add(jScrollPane1,
                java.awt.BorderLayout.CENTER);

        defPane.getContentPane().add(aboutFrame, java.awt.BorderLayout.CENTER);
        aboutFrame.getAccessibleContext().setAccessibleName("关于框架");// aboutFrame

        jScrollPane2.setAutoscrolls(true);
        jScrollPane2.setMinimumSize(new java.awt.Dimension(200, 23));
        jScrollPane2.setPreferredSize(new java.awt.Dimension(200, 100));
        jPanel2.setLayout(new java.awt.GridLayout(200, 2, 1, 1));

        jPanel2.setMinimumSize(new java.awt.Dimension(150, 479));
        jPanel2.setOpaque(false);
        jPanel2.setPreferredSize(new java.awt.Dimension(180, 5000));
        sfield.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sfield1ActionPerformed(evt);
            }
        });
        sfield.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                sfieldKeyReleased(evt);
            }
        });

        jPanel2.add(sfield);

        sendbutton.setText("发送");
        sendbutton.setToolTipText("此时只有1个字节可以被发送\n");// At this time only 1 byte
                                                        // can be send
        sendbutton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendbuttonActionPerformed(evt);
            }
        });

        jPanel2.add(sendbutton);

        testf.setEditable(false);
        jPanel2.add(testf);

        jScrollPane2.setViewportView(jPanel2);

        defPane.getContentPane().add(jScrollPane2, java.awt.BorderLayout.WEST);

        openp.setText("打开端口");// Open Port
        openp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openpActionPerformed(evt);
            }
        });

        jPanel1.add(openp);

        closep.setText("关闭端口");// Close port
        closep.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closepActionPerformed(evt);
            }
        });

        jPanel1.add(closep);

        defPane.getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);

        recBufft.setAutoscrolls(true);
        jScrollPane5
                .setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane5.setAutoscrolls(true);
        jScrollPane5
                .addComponentListener(new java.awt.event.ComponentAdapter() {
                    public void componentShown(java.awt.event.ComponentEvent evt) {
                        jScrollPane5ComponentShown(evt);
                    }
                });

        asciiBuff.setColumns(20);
        asciiBuff.setEditable(false);
        asciiBuff.setRows(5);
        jScrollPane5.setViewportView(asciiBuff);

        recBufft.addTab("ASCII", jScrollPane5);

        jScrollPane3
                .setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane3.setAutoscrolls(true);
        jScrollPane3
                .addComponentListener(new java.awt.event.ComponentAdapter() {
                    public void componentShown(java.awt.event.ComponentEvent evt) {
                        jScrollPane3ComponentShown(evt);
                    }
                });

        recBuff.setColumns(20);
        recBuff.setEditable(false);
        recBuff.setRows(5);
        recBuff.setAutoscrolls(false);
        recBuff.setFocusCycleRoot(true);
        jScrollPane3.setViewportView(recBuff);

        recBufft.addTab("十六进制", jScrollPane3);// HEX

        jScrollPane4
                .setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane4.setAutoscrolls(true);
        jScrollPane4
                .addComponentListener(new java.awt.event.ComponentAdapter() {
                    public void componentShown(java.awt.event.ComponentEvent evt) {
                        jScrollPane4ComponentShown(evt);
                    }
                });

        decBuff.setColumns(20);
        decBuff.setEditable(false);
        decBuff.setRows(5);
        decBuff.setAutoscrolls(false);
        decBuff.setFocusCycleRoot(true);
        jScrollPane4.setViewportView(decBuff);

        recBufft.addTab("十进制", jScrollPane4);// DEC

        jScrollPane6
                .setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane6.setAutoscrolls(true);
        jScrollPane6
                .addComponentListener(new java.awt.event.ComponentAdapter() {
                    public void componentShown(java.awt.event.ComponentEvent evt) {
                        jScrollPane6ComponentShown(evt);
                    }
                });

        binBuff.setColumns(20);
        binBuff.setEditable(false);
        binBuff.setRows(5);
        binBuff.setAutoscrolls(false);
        binBuff.setFocusCycleRoot(true);
        jScrollPane6.setViewportView(binBuff);

        recBufft.addTab("二进制", jScrollPane6);// BIN

        recBufft.setSelectedIndex(1);

        defPane.getContentPane().add(recBufft, java.awt.BorderLayout.CENTER);

        filemenu.setText("工程");
        newPrj.setText("新建");
        newPrj.setEnabled(false);
        filemenu.add(newPrj);

        Save.setText("保存");
        Save.setEnabled(false);
        filemenu.add(Save);

        loadPrj.setText("装载");
        loadPrj.setEnabled(false);
        filemenu.add(loadPrj);

        exitMenu.setText("退出");
        exitMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuActionPerformed(evt);
            }
        });

        filemenu.add(exitMenu);

        jMenuBar3.add(filemenu);

        Buffer.setText("缓存");
        Clearbuff.setText("清除缓存 ");
        Clearbuff.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ClearbuffActionPerformed(evt);
            }
        });

        Buffer.add(Clearbuff);

        jMenuBar3.add(Buffer);

        setmenu.setText("设置");
        comset.setText("串口设置");
        comset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comsetActionPerformed(evt);
            }
        });

        setmenu.add(comset);

        optMenu.setText("选项");
        optMenu.setEnabled(false);
        setmenu.add(optMenu);

        jMenuBar3.add(setmenu);

        helpmenu.setText("帮助");
        aboutmenu.setText("关于");
        aboutmenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutmenuActionPerformed(evt);
            }
        });

        helpmenu.add(aboutmenu);

        jMenuBar3.add(helpmenu);

        defPane.setJMenuBar(jMenuBar3);

        getContentPane().setLayout(null);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setEnabled(false);
        setMaximizedBounds(new java.awt.Rectangle(0, 0, 0, 0));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit()
                .getScreenSize();
        setBounds((screenSize.width - 365) / 2, (screenSize.height - 240) / 2,
                365, 240);
    }// //GEN-END:initComponents

    private void exitMenuActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_exitMenuActionPerformed
        System.exit(0); // Menu Exit Code - save Project ?

    }// GEN-LAST:event_exitMenuActionPerformed

    private void sfieldKeyReleased(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_sfieldKeyReleased
        // TODO add your handling code here:
        String s = sfield.getText();
        if (s.length() > 0) {
            if (radix != 0) {
                try {
                    int v = Integer.parseInt(sfield.getText(), radix);
                } // Routine for removing invalid simbols
                catch (Exception e) {
                    int a = s.length(); // in ascii mode everithing is valid
                    sfield.setText(s.substring(0, a - 1)); // remove invalid
                                                            // char
                }
            }
        }
    }// GEN-LAST:event_sfieldKeyReleased

    private void jScrollPane6ComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_jScrollPane6ComponentShown
        // TODO add your handling code here:
        testf.setText("二进制模式"); // converting between modes
        int oldRadix = radix;
        radix = 2;
        try {
            updateSfield(sfield.getText(), oldRadix);
        } catch (Exception e) {
        }
    }// GEN-LAST:event_jScrollPane6ComponentShown

    private void jScrollPane4ComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_jScrollPane4ComponentShown
        // TODO add your handling code here:
        testf.setText("十进制模式");
        int oldRadix = radix;
        radix = 10;
        try {
            updateSfield(sfield.getText(), oldRadix);
        } catch (Exception e) {
        }
    }// GEN-LAST:event_jScrollPane4ComponentShown

    private void jScrollPane3ComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_jScrollPane3ComponentShown
        // TODO add your handling code here:
        testf.setText("十六进制模式");
        int oldRadix = radix;
        radix = 16;
        String s = null;
        try {
            updateSfield(sfield.getText(), oldRadix);
        } catch (Exception e) {
        }
    }// GEN-LAST:event_jScrollPane3ComponentShown

    private void jScrollPane5ComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_jScrollPane5ComponentShown
        // TODO add your handling code here:
        testf.setText("ASCII码模式");
        int oldRadix = radix;
        radix = 0;
        try {
            updateSfield(sfield.getText(), oldRadix);
        } catch (Exception e) {
        }
    }// GEN-LAST:event_jScrollPane5ComponentShown

    private void formWindowActivated(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_formWindowActivated
        setVisible(false);
        defPane.setVisible(true);

    }// GEN-LAST:event_formWindowActivated

    private void setButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_setButtonActionPerformed
        // TODO add your handling code here:
        setFrame.setVisible(false);
        try {
            serialPort.close();
            txt = ("串口 " + serialPort.getName() + " 关闭\n");
            buffWrite(txt);
        } catch (Exception e) {
            txt = ("串口未能关闭\n");
            buffWrite(txt);
        }
        try {
            portList = CommPortIdentifier.getPortIdentifiers();

            while (portList.hasMoreElements()) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    if (portId.getName().equals(
                            (String) ComBox.getSelectedItem())) { // For Windows
                                                                    // settings
                        // if (portId.getName().equals("/dev/term/a")) { //For
                        // Linux settings
                        SimpleRead();
                    }
                }
            }
        } catch (Exception e) {
            txt = ("串口关闭\n");
            buffWrite(txt);
            ;
        }

    }// GEN-LAST:event_setButtonActionPerformed

    private void closesetActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_closesetActionPerformed
        // TODO add your handling code here:
        setFrame.setVisible(false);
    }// GEN-LAST:event_closesetActionPerformed

    private void openpActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_openp1ActionPerformed
        // TODO add your handling code here:

        try {
            portList = CommPortIdentifier.getPortIdentifiers();

            while (portList.hasMoreElements()) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    if (portId.getName().equals(
                            (String) ComBox.getSelectedItem())) { // For Windows
                                                                    // settings
                        // if (portId.getName().equals("/dev/term/a")) { //For
                        // Linux settings
                        SimpleRead();
                    }
                }
            }
        } catch (Exception e) {
            txt = ("串口关闭\n");
            buffWrite(txt);
            ;
        }
    }// GEN-LAST:event_openp1ActionPerformed

    private void comsetActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_comsetActionPerformed
        // TODO add your handling code here:
        setFrame.setVisible(true);
        ComBox.removeAllItems();
        // ComBox.addItem("COM1");
        try {
            portList = CommPortIdentifier.getPortIdentifiers();

            while (portList.hasMoreElements()) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    ComBox.addItem(portId.getName()); // For Windows
                    System.out.println("当前检测到的串口: " + portId.getName());
                    // settings
                    // if (portId.getName().equals("/dev/term/a")) { //For Linux
                    // settings

                }
            }
        } catch (Exception e) {
            txt = ("无法获得端口\n");
            buffWrite(txt);
        }

    }// GEN-LAST:event_comsetActionPerformed

    private void ClearbuffActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_ClearbuffActionPerformed
        // TODO add your handling code here:
        recBuff.setText("");
        asciiBuff.setText("");
        decBuff.setText("");
        binBuff.setText("");

    }// GEN-LAST:event_ClearbuffActionPerformed

    private void sendbuttonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_sendbuttonActionPerformed
        // TODO add your handling code here:
        senddata();

    }// GEN-LAST:event_sendbuttonActionPerformed

    private void aboutmenuActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_aboutmenuActionPerformed
        // TODO add your handling code here:
        aboutFrame.setVisible(true);
        try {
            aboutFrame.setMaximum(true);
        } catch (Exception e) {
        }
    }// GEN-LAST:event_aboutmenuActionPerformed

    private void sfield1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_sfieldActionPerformed
        // TODO add your handling code here:
        senddata();

    }// GEN-LAST:event_sfieldActionPerformed

    private void senddata() {
        String s = null;
        s = sfield.getText();
        SerialWrite(s);

        // recBuff.append(">>"+s+"\n"); //TODO add ascii view
        // txt=(">>"+s+"\n");
        // buffWrite(txt);
    }

    private void closepActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_closepActionPerformed
        // TODO add your handling code here:
        try {
            serialPort.close();
            txt = ("串口 " + serialPort.getName() + " 关闭 \n");
            buffWrite(txt);
        } catch (Exception e) {
            txt = ("串口关闭\n");
            buffWrite(txt);
        }
    }// GEN-LAST:event_closepActionPerformed

    /*
     * public static void main(String args[]) {
     * java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new
     * INT1().setVisible(true); } }); }
     */

    public void serialEvent(SerialPortEvent event) {// 串口数据处理函数
        switch (event.getEventType()) {
        case SerialPortEvent.BI:
        case SerialPortEvent.OE:
        case SerialPortEvent.FE:
        case SerialPortEvent.PE:
        case SerialPortEvent.CD:
        case SerialPortEvent.CTS:
        case SerialPortEvent.DSR:
        case SerialPortEvent.RI:
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;
        case SerialPortEvent.DATA_AVAILABLE:
            int w;
            try {
                txt = ("<<");
                buffWrite(txt);
                // function 内部计数变量,每一帧数据个数为100
                int count = 0;

                while (inputStream.available() > 0) {

                    w = inputStream.read();
                    recBuff.append(Integer.toString(w, 16) + " "); // TODO radix
                                                                    // replacement
                    decBuff.append(Integer.toString(w, 10) + " ");
                    binBuff.append(Integer.toString(w, 2) + " ");
                    String aChar = new Character((char) w).toString();
                    asciiBuff.append("" + aChar); // ASCII output
                    
                    // 将每一帧的数据保存到output
                    output += Integer.toString(w, 16) + " ";
                    count++;
                    if (count % 100 == 0 && count > 0) {
                        outputData.add(output);
                        //System.out.print(outputData.get(groupNums));
                        
                        //wirte data to client
                        outputToClient.writeObject(outputData.get(groupNums));
                        groupNums++;
                        //clear output
                        output = "";
                        
                        //System.out.println("counts: " + count);
                        //count = 0;
                    }
                }
                txt = ("\n");
                buffWrite(txt);
            } catch (IOException e) {
            }
            break;
        }
    }

    public void SimpleRead() {// 简单读取程序
        Boolean open = true;
        try {
            if (portId.isCurrentlyOwned() == false) {
                serialPort = (SerialPort) portId.open("RS232TM", 2000);

                txt = ("串口 " + serialPort.getName() + "打开\n");
                buffWrite(txt);
            } else {
                txt = ("串口 " + serialPort.getName() + " 已经被 "
                        + portId.getCurrentOwner() + "打开 \n");
                buffWrite(txt);
                open = false;
            }
        } catch (PortInUseException e) {
            txt = ("串口打开\n");
            open = false;
            buffWrite(txt);
        }
        if (open == true) {
            try {
                inputStream = serialPort.getInputStream();
            } catch (IOException e) {
            }
            try {
                serialPort.addEventListener(this);
            } catch (TooManyListenersException e) {
            }
            serialPort.notifyOnDataAvailable(true);

            try {

                int f = Integer.parseInt((String) BaudBox.getSelectedItem());
                serialPort.setSerialPortParams(f,
                        8 - DataBox.getSelectedIndex(),
                        StopBox.getSelectedIndex() + 1,
                        ParityBox.getSelectedIndex());
                f = FlowBox.getSelectedIndex();
                if (f == 4)
                    f = 8;
                if (f == 3)
                    f = 4;
                serialPort.setFlowControlMode(f);
                String txt = ("参数: " + serialPort.getBaudRate() + "比特/秒 , "
                        + serialPort.getDataBits() + "位 , "
                        + serialPort.getStopBits() + "停止位 , 奇偶校验 模式: "
                        + serialPort.getParity() + " , 流控制模式:"
                        + serialPort.getFlowControlMode() + " \n");
                buffWrite(txt);
            } catch (UnsupportedCommOperationException e) {
                txt = ("不支持的通信 参数\n");
                buffWrite(txt);
            }

        }
    }

    public void SerialWrite(String s) {// 简单写入程序
        try {
            try {
                outputStream = serialPort.getOutputStream();
            } catch (IOException e) {
                txt = ("串口错误11\n");
                buffWrite(txt);
            }
            int val = 0;
            char c;

            if (radix == 0) {
                c = s.charAt(0);
                val = c;
                outputStream.write(val);
            }

            else {
                val = Integer.parseInt(s, radix);
                outputStream.write(val);
                c = new Character((char) val);// .toString();
            }

            asciiBuff.append(">>" + c + "\n");
            recBuff.append(">>" + Integer.toString(val, 16) + "\n "); // TODO
                                                                        // radix
                                                                        // replacement
            decBuff.append(">>" + Integer.toString(val, 10) + "\n ");
            binBuff.append(">>" + Integer.toString(val, 2) + "\n ");

        } catch (IOException e) {
            txt = ("串口错误 12\n");
            buffWrite(txt);
        }
    }

    public void buffWrite(String s) {
        recBuff.append(s);
        asciiBuff.append(s);
        decBuff.append(s);
        binBuff.append(s);
        recBuff.setCaretPosition(recBuff.getDocument().getLength());
        asciiBuff.setCaretPosition(asciiBuff.getDocument().getLength());
        decBuff.setCaretPosition(decBuff.getDocument().getLength());
        binBuff.setCaretPosition(binBuff.getDocument().getLength());
    }

    public void updateSfield(String s1, int oldRadix) {
        int v;
        if (oldRadix != 0) {
            v = Integer.parseInt(s1, oldRadix);
            if (radix == 0) {
                String aChar = new Character((char) v).toString();
                sfield.setText(aChar);
            }

            else {
                sfield.setText(Integer.toString(v, radix));
            }
        } else {
            char c = s1.charAt(0);
            v = c;
            sfield.setText(Integer.toString(v, radix));
            // sfield.setText(""+Integer.parseInt( s1, radix ));
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox BaudBox;
    private javax.swing.JMenu Buffer;
    private javax.swing.JMenuItem Clearbuff;
    private javax.swing.JComboBox ComBox;
    private javax.swing.JComboBox DataBox;
    private javax.swing.JComboBox FlowBox;
    private javax.swing.JComboBox ParityBox;
    private javax.swing.JMenuItem Save;
    private javax.swing.JComboBox StopBox;
    private javax.swing.JInternalFrame aboutFrame;
    private javax.swing.JMenuItem aboutmenu;
    private javax.swing.JTextArea asciiBuff;
    private javax.swing.JTextArea binBuff;
    private javax.swing.JButton closep;
    private javax.swing.JButton closeset;
    private javax.swing.JMenuItem comset;
    private javax.swing.JTextArea decBuff;
    private javax.swing.JFrame defPane;
    private javax.swing.JMenuItem exitMenu;
    private javax.swing.JMenu filemenu;
    private javax.swing.JMenu helpmenu;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenuBar jMenuBar3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JMenuItem loadPrj;
    private javax.swing.JMenuItem newPrj;
    private javax.swing.JButton openp;
    private javax.swing.JMenuItem optMenu;
    private javax.swing.JTextArea recBuff;
    private javax.swing.JTabbedPane recBufft;
    private javax.swing.JButton sendbutton;
    private javax.swing.JButton setButton;
    private javax.swing.JInternalFrame setFrame;
    private javax.swing.JMenu setmenu;
    private javax.swing.JTextField sfield;
    private javax.swing.JTextField testf;

    // End of variables declaration//GEN-END:variables

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new INT1().setVisible(true);
            }
        });
    }

}

代码的注释应该是比较清楚的,我自己加入了数据存储并把这个作为服务端发送数据,仅供参考哦~

你可能感兴趣的:(java 串口通信)