JAVA 串口编程(二)

三、实例

(1)打开、关闭串口

首先使用CommPortIdentifier中的方法,获取可用的端口,并且选择一个端口打开作为通信端口。

A:枚举可用端口

 

void listPortChoices() 
{
     CommPortIdentifier portId;
     Enumeration en = CommPortIdentifier.getPortIdentifiers();
      while (en.hasMoreElements()) 
       {
         portId = (CommPortIdentifier) en.nextElement();
         if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) 
         System.out.println(portId.getName());
10         }
11         portChoice.select(parameters.getPortName());
12   }
13   
14   
 
B:打开指定的端口
CommPortIdentifier portId;
try 
{
  //生成CommPortIdentifier类的实例
  portId = CommPortIdentifier.getPortIdentifier("COM4");
} 
catch (NoSuchPortException e)
{
   e.printStackTrace();
10  }
11  try 
12  {
13      //打开串口COM4,设置超时时限为3000毫秒
14      serialPort = (SerialPort) portId.open("testApp", 3000);
15  } 
16  catch (PortInUseException e)
17  {
18      e.printStackTrace();
19  }
20   
21   
 
C:关闭端口

使用完的端口,必须记得将其关闭,否则其它的程序将无法使用该端口,CommPortIdentifier类只提供了开启端口的方法,而要关闭端口,则要调用CommPort类的close()方法。

serialPort.close()

(2)设置串口参数

try {
    try {
        serialPort.setSerialPortParams(9600, //  波特率
                                       SerialPort.DATABITS_8,//  数据位数
                                       SerialPort.STOPBITS_1, //  停止位
                                       SerialPort.PARITY_NONE);//  奇偶位
    } 
    catch (UnsupportedCommOperationException e)
     {
10          e.printStackTrace();
11      }
12   

(3)串口的读、写

A:向串口写数据
    OutputStream outputStream;
    try
    {
        outputStream = serialPort.getOutputStream();
    } 
    catch (IOException e)
     {
        e.printStackTrace();
    }
10      bt = new byte[] { (byte) 0x55, (byte) 0xAA, (byte) 0xF1 };
11      try
12      {
13          outputStream.write(bt);
14          outputStream.flush();
15          outputStream.close();
16      }
17      catch (IOException e)
18       {
19          e.printStackTrace();
20      }
21   
B:读取串口中的数据

读操作,需继承SerialPortEventListener接口。为SerialPort添加监听Listener。实现该接口的serialEvent (SerialPortEvent event)方法。

        public class SerialRead implements SerialPortEventListener{
       
            InputStream inputStream;
            byte[] rBuffer = new byte[38];
             SerialRead(SerialPort serialPort)
             {
                try {
                    serialPort.addEventListener((SerialPortEventListener) this);
                    this.serialPort.notifyOnDataAvailable(true);
10         
11                  } catch (TooManyListenersException e) {
12                  }
13             
14                  try {
15                      if (serialPort != null)
16                          inputStream = serialPort.getInputStream();
17                  } catch (IOException e) {
18                  }
19                  }
20               
21              public void serialEvent(SerialPortEvent event) 
22              {
23                  if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE)
24                  { 
25                      int count = 0;
26                      try 
27                      {
28                          while ((ch = inputStream.read()) != -1) 
29                          {       
30                              bt[count++]=(byte)ch;
31                          }
32                      }
33                      catch (IOException e) 
34                      {
35                          e.printStackTrace();
36                      }
37                  }   
38              }
39   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然,我可以为您提供一个简单的Java串口编程实例。请注意,为了运行此示例,您需要在计算机上安装Java串口通信库。 首先,您需要导入所需的库。您可以使用`RXTX`库来实现Java串口通信。您可以在以下网址下载并安装该库:http://rxtx.qbang.org/wiki/index.php/Main_Page 接下来,让我们看一个简单的Java串口通信示例: ```java import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; public class SerialCommunicationExample { public static void main(String[] args) { try { // 获取串口通信端口标识符 CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM1"); // 打开串口 SerialPort serialPort = (SerialPort) portIdentifier.open("SerialCommunicationExample", 2000); // 设置串口参数 serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // 获取输入流和输出流 BufferedReader input = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); OutputStream output = serialPort.getOutputStream(); // 向串口发送数据 output.write("Hello, World!".getBytes()); // 读取串口返回的数据 String line; while ((line = input.readLine()) != null) { System.out.println("Received: " + line); } // 关闭串口 serialPort.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这个示例演示了如何通过串口与外部设备进行通信。它在COM1端口上打开串口,并设置波特率为9600,数据位为8,停止位为1,无校验位。然后,它向串口发送"Hello, World!"的数据,并打印串口返回的数据。 请注意,这只是一个简单的示例,您可能需要根据您的具体需求进行调整和扩展。希望对您有所帮助!如果您有任何问题,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值