[英]Reading from Com Port java
I am a beginner java developer.我是一名初学者 java 开发人员。 I have a problem with reading from com port.
从 com 端口读取时出现问题。 Code:
代码:
public class Main {
private static SerialPort serialPort;
public static void main(String[] args) {
serialPort = new SerialPort("COM3");
try {
serialPort.openPort();
Thread.sleep(2000);
serialPort.setParams(SerialPort.BAUDRATE_57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.writeBytes("Test".getBytes());
serialPort.setEventsMask(SerialPort.MASK_RXCHAR);
serialPort.addEventListener(new EventListener());
}
catch (SerialPortException | InterruptedException ex) {
System.out.println(ex);
}
}
private static class EventListener implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() == 8){
try {
byte[] buffer = serialPort.readBytes(8);
for(int i = 0; i < buffer.length; i++){
System.out.println("Output" + buffer[i]);
}
serialPort.closePort();
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
}
Nothing is displayed but I know that the data are written.没有显示任何内容,但我知道数据已写入。 Help, please.
请帮忙。
What is the lib you are using for comm/serial stuff?您用于通信/串行内容的库是什么? You may try add
serialPort.addEventListener(new EventListener());
您可以尝试添加
serialPort.addEventListener(new EventListener());
line before you send anything, this is possible that a receive event is sent before listener mapping.在发送任何内容之前的行,这可能是在侦听器映射之前发送接收事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.