簡體   English   中英

從JFrame類調用串行端口類

[英]Calling Serial Port Class from a JFrame Class

我正在通過串行端口在Arduino上使用Java的JFrame進行實驗,但遇到了一個問題,我不確定如何繼續執行我的代碼。

我試圖使用構造函數從另一個類的JFrame代碼中調用一個類的串行端口部分。 基本上,我正在嘗試將Java程序與Arduino Uno連接。

我的問題是,當我嘗試從GUI類運行代碼時,請訪問SerialOut.write(“ test” .getBytes());。 ,錯誤提示“線程“ main”中的異常java.lang.NullPointerException”。

有人可以看一下構造函數,然后告訴我是否犯了任何錯誤嗎? 謝謝!

設置串行端口的類該代碼本身可以工作[我使用Uno和LED對其進行測試以查看其是否點亮。 (確實)]

package javaapplication1;

import javaapplication1.RCDA_JFrame;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier; 
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent; 
import gnu.io.SerialPortEventListener; 
import java.util.Enumeration;
import java.io.IOException;

public class SerialTest implements SerialPortEventListener {
        //constructor
        public SerialTest(){
            this.initialize();
            this.close();
            this.serialEvent(null);
        }        
    SerialPort serialPort;
        /** The port we're normally going to use. */
    private static final String PORT_NAMES[] = { 
            "COM8",}; // Windows 
    private BufferedReader input;
    private static OutputStream SerialOut;/** The output stream to the port */
    private static final int TIME_OUT = 2000;/** Milliseconds to block while waiting for port open */
    private static final int DATA_RATE = 9600;/** Default bits per second for COM port. */

    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        //First, Find an instance of serial port as set in PORT_NAMES.
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
            System.out.println("Could not find COM port.");
            return;
        }

        try {
            // open serial port, and use class name for the appName.
            serialPort = (SerialPort) portId.open(this.getClass().getName(),
                    TIME_OUT);

            // set port parameters
            serialPort.setSerialPortParams(DATA_RATE,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
            // open the streams
            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
            SerialOut = serialPort.getOutputStream();

            // add event listeners
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
    /**
     * This should be called when you stop using the port.
     * This will prevent port locking on platforms like Linux.
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }
    //Handle an event on the serial port. Read the data and print it.
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                String inputLine=input.readLine();
                System.out.println(inputLine);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
    }
    public static void main(String[] args) throws Exception {

        SerialTest main = new SerialTest();
        main.initialize();
        Thread t=new Thread() {
            public void run() {
                //the following line will keep this app alive for 1000 seconds,
                //waiting for events to occur and responding to them (printing incoming messages to console).
                try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
            }
        };
        t.start();
        System.out.println("Started");
        //testing
                try {
                System.out.println("This is a test");
                System.out.println("test".getBytes());
                SerialOut.write("test".getBytes()); //SEND STRING THROUGH SERIAL PORT
        } catch (IOException e1) {
                        e1.printStackTrace();
        } //end of testing
    }
}

JFrame類-我試圖在上面調用的類:

package javaapplication1;

import javaapplication1.SerialTest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier; 
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent; 
import gnu.io.SerialPortEventListener; 
import java.util.Enumeration;
import java.io.IOException;

public class NewJFrame extends javax.swing.JFrame implements SerialPortEventListener {

    @Override
    public void serialEvent(SerialPortEvent ev) {
    SerialTest ST1 = new SerialTest();
    }
    private static OutputStream SerialOut;
    SerialPort serialPort;
        /** The port we're normally going to use. */
//    private static final String PORT_NAMES[] = { 
//          "COM8"}; // Windows 
//    private BufferedReader input;
//    private static final int TIME_OUT = 2000;/** Milliseconds to block while waiting for port open */
//    private static final int DATA_RATE = 9600;/** Default bits per second for COM port. */
//    
    public NewJFrame() {
        initComponents();
    }

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

public static void main(String args[]) {
        //constructor from SerialTest
        SerialTest ST1 = new SerialTest();

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

        try {
            System.out.println("This is a test");
            System.out.println("test".getBytes());
              SerialOut.write("test".getBytes()); //SEND STRING THROUGH SERIAL PORT
            } catch (IOException e1) {
        e1.printStackTrace();
        }
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}

您需要進行錯誤檢查,以查看端口在通過可用端口列表之后是​​否為空。 確保它確實在獲取可用端口,並且確實為它分配了一個值。

if (portId == null) {
     System.out.println("Could not find COM port.");
     return;
}

要進行確認,請嘗試打印出portName,以查看端口實際獲得的端口,如portId.getName()並檢查以確保其不為null。 如果是這樣,那就是您的問題。

private static OutputStream SerialOut;/** The output stream to the port */

這是在SerialTest. 注意,它不應該是靜態的。 如果已找到端口,則在調用initialize()時將對其進行initialize() ,並且initialize()不會引發異常或返回任何狀態,因此無法知道它是否成功。 解決這個。

private static OutputStream SerialOut;

NewJFrame 它與上一個數據項不同。 它永遠不會被初始化,因此它為null,因此您將獲得NullPointerException 刪除它,然后在SerialTest.使用它SerialTest.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM