gpt4 book ai didi

java - 从 JFrame 类调用串行端口类

转载 作者:行者123 更新时间:2023-11-30 07:45:35 25 4
gpt4 key购买 nike

我正在通过串行端口使用 Arduino 试验 Java 的 JFrame,但遇到了问题,我不知道如何继续我的代码。

我正在尝试使用构造函数从另一个类中的 JFrame 代码调用一个类的串行端口部分。基本上,我正在尝试将我的 Java 程序与 Arduino Uno 连接。

我的问题是,当我尝试从 GUI 类运行代码时,在 SerialOut.write("test".getBytes()); 处,出现错误“Exception在线程“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() 并检查以确保它不为空。如果是,那就是你的问题了。

关于java - 从 JFrame 类调用串行端口类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33993899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com