共計(jì) 1956 個(gè)字符,預(yù)計(jì)需要花費(fèi) 5 分鐘才能閱讀完成。
在 Java 中,可以使用 JavaComm 或 RXTX 庫來讀取串口數(shù)據(jù)。以下是使用 RXTX 庫的示例代碼:
首先,確保已經(jīng)安裝了 RXTX 庫。然后,在 Java 代碼中導(dǎo)入相關(guān)的 RXTX 類:
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
然后,定義一個(gè)類實(shí)現(xiàn) SerialPortEventListener 接口,以便監(jiān)聽串口事件:
public class SerialReader implements SerialPortEventListener {????private?InputStream?in;
????public?SerialReader(InputStream?in)?{
????????this.in?=?in;
????}
????public?void?serialEvent(SerialPortEvent?event)?{
????????switch?(event.getEventType())?{
????????????case?SerialPortEvent.DATA_AVAILABLE:
????????????????try?{
????????????????????byte[]?buffer?=?new?byte[in.available()];
????????????????????in.read(buffer);
????????????????????String?data?=?new?String(buffer);
????????????????????System.out.println("Received?data:?"?+?data);
????????????????}?catch?(IOException?e)?{
????????????????????e.printStackTrace();
????????????????}
????????????????break;
????????????//?其他事件處理
????????}
????}
}
接下來,在主方法中進(jìn)行串口的初始化和監(jiān)聽:
public?static?void?main(String[]?args)?{
????try?{
????????CommPortIdentifier?portIdentifier?=?CommPortIdentifier.getPortIdentifier(“/dev/ttyUSB0”);?
????????//?根據(jù)實(shí)際串口路徑來指定
????????if?(portIdentifier.isCurrentlyOwned())?{
????????????System.out.println(“Error:?Port?is?currently?in?use”);
????????}?else?{
????????????CommPort?commPort?=?portIdentifier.open(“SerialTest”,?2000);
????????????if?(commPort?instanceof?SerialPort)?{
????????????????SerialPort?serialPort?=?(SerialPort)?commPort;
????????????????serialPort.addEventListener(new?SerialReader(serialPort.getInputStream()));
????????????????serialPort.notifyOnDataAvailable(true);
????????????}?else?{
????????????????System.out.println(“Error:?Only?serial?ports?are?supported”);
????????????}
????????}
????}?catch?(Exception?e)?{
????????e.printStackTrace();
????}
}
在上述代碼中,"/dev/ttyUSB0" 是串口路徑,根據(jù)實(shí)際情況進(jìn)行修改。
這樣,當(dāng)有數(shù)據(jù)到達(dá)串口時(shí),SerialReader 的 serialEvent 方法會(huì)被調(diào)用,并讀取數(shù)據(jù)。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!