JAVA:使用RXTX从串口写入和读取缓冲区

时间:2013-05-28 14:00:12

标签: java serial-port rxtx

当我尝试使用RXTX从串口com读取字符串缓冲区时,我得到了奇怪的结果。 在向COM写入字符串后,我将字符串存储为回复。这是一个循环。在控制台中打印的字符串有时不会与最后一个写入命令相对应,但属于前一个命令。

     while (running) {
          char campioni = (char) start;
          hexStart = Integer.toHexString(campioni).toUpperCase();
          String stringa = ">eL#" + hexStart + "??!\r\n" + "\n";
          output.write((">eL" + "L#" + hexStart + "??!\r\n").getBytes());
          output.flush();

           byte[] buffer = new byte[10000];

           n=0;
       try {
          n = input.read(buffer);
        } catch (IOException e1) {
        e1.printStackTrace();
        }

             if(n>0){
                    String data = new String (buffer,0,n);
                    System.out.println(new String(buffer));
                    start=start+5;
                    Thread.sleep(2000); 
               }
          }

2 个答案:

答案 0 :(得分:0)

我找到了两件你可以检查的东西

  • 是睡眠引起的吗?
  • 可以缓冲System.out;你正在使用 print (与 println 相反),所以如果你的缓冲区不包含CR / LF,它可能不会立即显示。

答案 1 :(得分:0)

以下示例是用户读取rfid阅读器扫描的Rfid值

1) Reader Form Build in netbeans

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package rfid_thumb;

    import com.data.access.AbstractDao;
    import gnu.io.SerialPort;

    /**
     *
     * @author ANGEL
     */
    public class ReaderForm extends javax.swing.JFrame {

        /**
         * Creates new form ReaderForm
         */
        public AbstractDao abstractDao=new AbstractDao();
        SerialPort serialPort, serialPort1;
         //Communicator object
        Communicator communicator = null;
        //KeybindingController object


        @Override
        public void list() {
            super.list(); //To change body of generated methods, choose Tools | Templates.
        }


        public ReaderForm() {
            initComponents();
            createObjects();
            communicator.searchForPorts();
        }

        private void createObjects()
        {
            communicator = new Communicator(this);
        }

        /**
         * 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")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {

            jPanel1 = new javax.swing.JPanel();
            thumbCobBox = new javax.swing.JComboBox();
            jLabel6 = new javax.swing.JLabel();
            jLabel7 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            txtLog = new javax.swing.JTextArea();
            jButton1 = new javax.swing.JButton();
            Scan = new javax.swing.JButton();
            jButton3 = new javax.swing.JButton();

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "RFID and Thumb Scanning", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 1, 14))); // NOI18N

            jLabel6.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
            jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
            jLabel6.setText("Thumb Scanning Port");
            jLabel6.setOpaque(true);

            jLabel7.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
            jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
            jLabel7.setText("Logs");
            jLabel7.setOpaque(true);

            txtLog.setColumns(20);
            txtLog.setRows(5);
            jScrollPane1.setViewportView(txtLog);

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

            Scan.setText("Scan");
            Scan.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ScanActionPerformed(evt);
                }
            });

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

            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap(24, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(thumbCobBox, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(29, 29, 29)
                                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(Scan, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGap(34, 34, 34))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap(37, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(thumbCobBox, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(13, 13, 13))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(Scan, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                    .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            );

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(31, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            );

            pack();
        }// </editor-fold>                        

        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
            communicator.connect();
            if (communicator.getConnected() == true)
            {
                if (communicator.initIOStream() == true)
                {
                    communicator.initListener();
                }
            }
        }                                        

        private void ScanActionPerformed(java.awt.event.ActionEvent evt) {                                     
            // TODO add your handling code here:
        }                                    

        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
        }                                        

        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(ReaderForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(ReaderForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(ReaderForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(ReaderForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>

            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ReaderForm().setVisible(true);
                }
            });
        }

        // Variables declaration - do not modify                     
        private javax.swing.JButton Scan;
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton3;
        private javax.swing.JLabel jLabel6;
        private javax.swing.JLabel jLabel7;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        public javax.swing.JComboBox thumbCobBox;
        public javax.swing.JTextArea txtLog;
        // End of variables declaration                   
    }

2)用于读取序列值的Communicator类

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

package rfid_thumb;

import com.data.model.ThumbTemp;
import gnu.io.*;
import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.TooManyListenersException;
import java.util.Vector;

public class Communicator implements SerialPortEventListener
{
    //passed from main GUI
    ReaderForm window = null;
    public Vector<String> inDataVector;
    //for containing the ports that will be found
    private Enumeration ports = null;
    //map the port names to CommPortIdentifiers
    private final HashMap portMap = new HashMap();
     public int inData = 0, outData = 0, outData1 = 0;
    //this is the object that contains the opened port

    private final CommPortIdentifier selectedPortIdentifierT = null;
    private SerialPort serialPort = null;
    private SerialPort serialPortT = null;

    String rfid="";
    String thumb="";



    private InputStream inputT = null;
    private OutputStream outputT = null;

    //just a boolean flag that i use for enabling
    //and disabling buttons depending on whether the program
    //is connected to a serial port or not
    private boolean bConnected = false;

    //the timeout value for connecting with the port
    final static int TIMEOUT = 2000;

    //some ascii values for for certain things
    final static int SPACE_ASCII = 32;
    final static int DASH_ASCII = 45;
    final static int NEW_LINE_ASCII = 10;

    public boolean dataReady=false, dataReady1=false, receivedPin=false;

    //a string for recording what goes on in the program
    //this string is written to the GUI
    String logText = "";

    public Communicator(ReaderForm window)
    {
        this.window = window;
        inDataVector = new Vector<String>();
        dataReady = false;
        dataReady1 = false;
    }

    //search for all the serial ports
    //pre: none
    //post: adds all the found ports to a combo box on the GUI
    public void searchForPorts()
    {
        ports = CommPortIdentifier.getPortIdentifiers();

        while (ports.hasMoreElements())
        {
            CommPortIdentifier curPort = (CommPortIdentifier)ports.nextElement();

            //get only serial ports
            if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL)
            {
                //window.rfidComBox.addItem(curPort.getName());
                window.thumbCobBox.addItem(curPort.getName());
                portMap.put(curPort.getName(), curPort);
            }
        }
    }

    //connect to the selected port in the combo box
    //pre: ports are already found by using the searchForPorts method
    //post: the connected comm port is stored in commPort, otherwise,
    //an exception is generated
    public void connect()
    {

          //String selectedPort = (String)window.rfidComBox.getSelectedItem();
            String selectedPortT = (String)window.thumbCobBox.getSelectedItem();

            //selectedPortIdentifier = (CommPortIdentifier)portMap.get(selectedPort);
            //selectedPortIdentifierT = (CommPortIdentifier)portMap.get(selectedPortT);
            CommPort commPort = null;
            CommPort commPortT = null;
            try
            {
                //the method below returns an object of type CommPort
               // commPort = selectedPortIdentifier.open("TigerControlPanel", TIMEOUT);
                commPortT = selectedPortIdentifierT.open("TigerControlPanel1", TIMEOUT);
                //the CommPort object can be casted to a SerialPort object
                serialPort = (SerialPort)commPort;
                serialPortT = (SerialPort)commPortT;

                //for controlling GUI elements
                setConnected(true);

                //logging
                logText = selectedPortT + " opened successfully.";
                window.txtLog.setForeground(Color.black);
                window.txtLog.append(logText + "\n");

                //CODE ON SETTING BAUD RATE ETC OMITTED
                //XBEE PAIR ASSUMED TO HAVE SAME SETTINGS ALREADY

                //enables the controls on the GUI if a successful connection is made
                //window.keybindingController.toggleControls();
            }
            catch (PortInUseException e)
            {
                logText = selectedPortT + " is in use. (" + e.toString() + ")";
                window.txtLog.setForeground(Color.RED);
                window.txtLog.append(logText + "\n");
            }
            catch (Exception e)
            {
                logText = "Failed to open " + selectedPortT + "(" + e.toString() + ")";
                window.txtLog.append(logText + "\n");
                window.txtLog.setForeground(Color.RED);
            }
    }

    //open the input and output streams
    //pre: an open port
    //post: initialized intput and output streams for use to communicate data
    public boolean initIOStream()
    {
        //return value for whather opening the streams is successful or not
        boolean successful = false;

        try {
            //
            //input = serialPort.getInputStream();
            //output = serialPort.getOutputStream();

            inputT = serialPortT.getInputStream();
            outputT = serialPortT.getOutputStream();

            //writeData(0, 0);

            successful = true;
            return successful;
        }
        catch (IOException e) {
            logText = "I/O Streams failed to open. (" + e.toString() + ")";
            window.txtLog.setForeground(Color.red);
            window.txtLog.append(logText + "\n");
            return successful;
        }
    }

    //starts the event listener that knows whenever data is available to be read
    //pre: an open serial port
    //post: an event listener for the serial port that knows when data is recieved
    public void initListener()
    {
        try
        {
            //serialPort.addEventListener(this);
            //serialPort.notifyOnDataAvailable(true);

            serialPortT.addEventListener(this);
            serialPortT.notifyOnDataAvailable(true);

        }
        catch (TooManyListenersException e)
        {
            logText = "Too many listeners. (" + e.toString() + ")";
            window.txtLog.setForeground(Color.red);
            window.txtLog.append(logText + "\n");
        }
    }

    //disconnect the serial port
    //pre: an open serial port
    //post: clsoed serial port
    public void disconnect()
    {
        //close the serial port
        try
        {


            serialPort.removeEventListener();
            serialPort.close();

            serialPortT.removeEventListener();
            serialPortT.close();

            //input.close();
            //output.close();

            inputT.close();
            outputT.close();
            setConnected(false);
            //window.keybindingController.toggleControls();

            logText = "Disconnected.";
            window.txtLog.setForeground(Color.red);
            window.txtLog.append(logText + "\n");
        }
        catch (Exception e)
        {
            logText = "Failed to close " + serialPort.getName() + "(" + e.toString() + ")";
            window.txtLog.setForeground(Color.red);
            window.txtLog.append(logText + "\n");
        }
    }

    final public boolean getConnected()
    {
        return bConnected;
    }

    public void setConnected(boolean bConnected)
    {
        this.bConnected = bConnected;
    }

    //what happens when data is received
    //pre: serial event is triggered
    //post: processing on the data it reads
    public void serialEvent(SerialPortEvent evt) {

        if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
        {
            try
            {

                    while (inputT.available() > 0) {
                        inData = inputT.read();
                        //inDataVector.add(new String("" + (char) inData));
                        System.out.print(new String("" + (char) inData));
                        thumb+=new String("" + (char) inData);
                        ThumbTemp thumbTemp=(ThumbTemp)window.abstractDao.getById("id", 1, ThumbTemp.class);

                        if(thumb.length()==100){
                            thumbTemp.setValue(thumb.split("#")[1].substring(0,2));
                            window.abstractDao.update(thumbTemp);
                            window.txtLog.append("Thumb Id : "+thumb+"\n");
                            thumb="";
                        }
                        else
                        {
                            thumbTemp.setValue("none");
                            //window.abstractDao.update("");
                        }
                        window.abstractDao.update(thumbTemp);
                    }
                    //rfid="";
            }
            catch (Exception e)
            {
                logText = "Failed to read data. (" + e.toString() + ")";
                window.txtLog.setForeground(Color.red);
                window.txtLog.append(logText + "\n");
            }
        }
    }

    //method that can be called to send data
    //pre: open serial port
    //post: data sent to the other device
    public void writeData(int id)
    {
        try
        {
            outputT.write(id);
        }
        catch (Exception e)
        {
            logText = "Failed to write data. (" + e.toString() + ")";
            window.txtLog.setForeground(Color.red);
            window.txtLog.append(logText + "\n");
        }
    }
}