在Java中,可以使用RXTXcomm庫來實現串口通信。下面是一個簡單的示例:
首先,你需要下載和安裝RXTXcomm庫。你可以在 https://github.com/rxtx/rxtx 找到最新版本的庫。
導入RXTXcomm庫到你的Java項目中。
創建一個新的Java類并導入所需的類和包:
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SerialCommunication {
private InputStream inputStream;
private OutputStream outputStream;
public void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
(new Thread(new SerialReader(inputStream))).start();
(new Thread(new SerialWriter(outputStream))).start();
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
public static class SerialReader implements Runnable {
private InputStream inputStream;
public SerialReader(InputStream inputStream) {
this.inputStream = inputStream;
}
public void run() {
byte[] buffer = new byte[1024];
int len = -1;
try {
while ((len = this.inputStream.read(buffer)) > -1) {
System.out.print(new String(buffer, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static class SerialWriter implements Runnable {
private OutputStream outputStream;
public SerialWriter(OutputStream outputStream) {
this.outputStream = outputStream;
}
public void run() {
try {
int c = 0;
while ((c = System.in.read()) > -1) {
this.outputStream.write(c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
SerialCommunication serial = new SerialCommunication();
serial.connect("/dev/ttyUSB0"); // Replace with your serial port name
} catch (Exception e) {
e.printStackTrace();
}
}
}
請注意,此示例假設你的系統上已經安裝并配置了正確的串口驅動程序。