我试图通过COM端口通过SerialPort类发送数据并通过COM端口接收数据,但是遇到了这个问题...................... .................................................. .................................
谢谢。
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.*;
public class writeValues {
public static void main(String[] args) {
SerialPort serialPort = new SerialPort("COM1");
try {
//Open port
String T;
serialPort.openPort();
serialPort.setParams(2400,7,2,1, false, true);
String bytes = serialPort.readString(); //Reads 10 bytes from serial port
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
serialPort.writeString("connected.");
//serialPort.closePort();
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
public static class PortReader implements SerialPortEventListener {
@Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
String receivedData = SerialPort.readString(event.getEventValue());
System.out.println("Received response: " + receivedData);
}
catch (SerialPortException ex) {
System.out.println("Error in receiving string from COM-port: " + ex);
}
}
}
}
}
答案 0 :(得分:0)
由于SerialPort类不是静态的 - (你称为serialPort = new SerialPort()对吗?)你需要在该实例'serialPort'而不是SerialPort类上调用readstring。你可以做的是改为
public class writeValues {
public static SerialPort serialPort;
public static void main(String[] args) {
serialPort = new SerialPort("COM1");
try {
//Open port
String T;
serialPort.openPort();
serialPort.setParams(2400,7,2,1, false, true);
String bytes = serialPort.readString(); //Reads 10 bytes from serial port
serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
serialPort.writeString("connected.");
//serialPort.closePort();
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
public static class PortReader implements SerialPortEventListener {
@Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
String receivedData = serialPort.readString(event.getEventValue());
System.out.println("Received response: " + receivedData);
}
catch (SerialPortException ex) {
System.out.println("Error in receiving string from COM-port: " + ex);
}
}
}
}
所以现在我们引用serialPort的实例而不是静态类SerialPort。希望有所帮助