我想從連接到我的電腦的稱重橋讀取數據(這是重量),端口號爲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