从JFrame类调用串行端口类

时间:2015-11-30 08:00:46

标签: java constructor serial-port

我正在通过串口尝试使用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                   
}

2 个答案:

答案 0 :(得分:1)

在进入可用端口列表后,您有错误检查以查看端口是否为空。确保它确实获得了可用的端口,并确保为其分配了值。

schema

要确认尝试打印出portName以查看它实际上正在获得的端口if (portId == null) { System.out.println("Could not find COM port."); return; } ,并检查以确保它不为空。如果是,那就是你的问题。

答案 1 :(得分:0)

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

这是SerialTest.注意它不应该是静态的。如果发现端口,则在调用initialize()时初始化,并且由于initialize()不会抛出异常或返回任何状态,因此无法知道它是否成功。解决了这个问题。

private static OutputStream SerialOut;

那是NewJFrame。它与前一个数据项不同。它永远不会被初始化,所以它是null,所以你得到一个NullPointerException。将其删除,然后使用SerialTest.

中的一个