鎬庝箞浣跨敤Java瀹炵幇涓插彛閫氫俊
瑕佷娇鐢↗ava瀹炵幇涓插彛閫氫俊锛屽彲浠ヤ娇鐢↗ava鐨凴XTX搴撱€備互涓嬫槸涓€涓畝鍗曠殑绀轰緥浠g爜锛?/p>
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.InputStream;
import java.io.OutputStream;
public class SerialCommunication {
public static void main(String[] args) {
try {
// 鑾峰彇涓插彛鏍囪瘑绗?/span>
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM1");
// 鎵撳紑涓插彛骞惰缃€氫俊鍙傛暟
CommPort commPort = portIdentifier.open("SerialCommunication", 2000);
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// 鑾峰彇杈撳叆娴佸拰杈撳嚭娴?/span>
InputStream inputStream = serialPort.getInputStream();
OutputStream outputStream = serialPort.getOutputStream();
// 鍚戜覆鍙e彂閫佹暟鎹?/span>
outputStream.write("Hello World".getBytes());
// 浠庝覆鍙h鍙栨暟鎹?/span>
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
String receivedData = new String(buffer, 0, len);
System.out.println("Received data: " + receivedData);
// 鍏抽棴涓插彛
serialPort.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
鍦ㄤ笂杩颁唬鐮佷腑锛岄鍏堣幏鍙栦覆鍙f爣璇嗙锛岀劧鍚庢墦寮€涓插彛骞惰缃€氫俊鍙傛暟銆傛帴涓嬫潵锛岄€氳繃鑾峰彇杈撳叆娴佸拰杈撳嚭娴佹潵杩涜鏁版嵁鐨勮鍐欐搷浣溿€傛渶鍚庯紝鍏抽棴涓插彛銆傝娉ㄦ剰锛岄渶瑕佸鍏XTX搴擄紝骞舵牴鎹疄闄呮儏鍐典慨鏀逛覆鍙e悕绉板拰閫氫俊鍙傛暟銆?/p>