在Java中,可以使用JavaComm或RXTX库来读取串口数据。以下是使用RXTX库的示例代码:
首先,确保已经安装了RXTX库。然后,在Java代码中导入相关的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;
然后,定义一个类实现SerialPortEventListener接口,以便监听串口事件:
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;
????????????//?其他事件处理
????????}
????} }
接下来,在主方法中进行串口的初始化和监听:
public?static?void?main(String[]?args)?{????try?{
????????CommPortIdentifier?portIdentifier?=?CommPortIdentifier.getPortIdentifier(“/dev/ttyUSB0”);?
????????//?根据实际串口路径来指定
????????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"是串口路径,根据实际情况进行修改。
这样,当有数据到达串口时,SerialReader的serialEvent方法会被调用,并读取数据。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>