我想从连接到我的电脑的称重桥读取数据(这是重量),端口号为com1
。我搜索网页,我可以连接到端口并读取数据,但问题是数据不完整。在java中从串口读取数据
我越来越有点像下面
有145的权重是在称重桥架,但我获得这些符号。 这是我正在阅读数据的代码。
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package readingports;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
/**
*
* @author IamUsman
*/
public class ReadingPorts implements SerialPortEventListener, Runnable {
static CommPortIdentifier portId;
static Enumeration portList;
static SerialPort port;
static InputStream inputStream;
static Thread readThread;
static byte buffer[];
static BufferedReader br;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM1")) {
if (!portId.isCurrentlyOwned()) {
ReadingPorts rp = new ReadingPorts();
} else {
System.out.println("This port is already used by some other program");
}
}
}
}
}
public ReadingPorts() {
try {
port = (SerialPort) portId.open("Custom", 500);
inputStream = port.getInputStream();
br = new BufferedReader(new InputStreamReader(inputStream));
System.out.println("** Connected To COM6 **");
port.addEventListener(this);
port.notifyOnDataAvailable(true);
port.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
port.enableReceiveTimeout(500);
System.out.println("................................");
readThread = new Thread(this);
readThread.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
buffer = new byte[8];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(buffer);
System.out.println(new String(buffer,0,numBytes));
}
} catch (Exception ex) {
ex.printStackTrace();
}
break;
}
}
@Override
public void run() {
try {
System.out.println("In Run");
Thread.sleep(2000);
} catch (Exception ex) {
ex.printStackTrace();;
}
}
}
超级终端读取正确的数据。
请确保您有使用正确的串行连接设置,并且称重站使用明文协议。 – Robert
设置是否正确。超级终端使用相同设置读取正确的数据。什么是明文原型? –
明文表示人类可读(通常是ASCII文本)。串行连接可以发送/接收二进制数据。但是,如果你已经成功地使用超级终端,它看起来像一个明文协议。 – Robert