JAVA 串口编程 (三)

http://www.cnblogs.com/dyufei/archive/2010/09/19/2573911.html


四、实例分析

同API一起下载的还有一个examples文件,里面有个最简单的读、写程序,对其进行注释,以增进了理。

(1)读串口

 

import java.io.*;
import java.util.*;
import javax.comm.*;
 
public class SimpleRead implements Runnable, SerialPortEventListener {
 
    static CommPortIdentifier portId;
    static Enumeration portList;//枚举类
 
10     InputStream inputStream;
11     SerialPort serialPort;
12     Thread readThread;
13  
14     public static void main(String[] args) {
15  
16         portList = CommPortIdentifier.getPortIdentifiers();/*不带参数的getPortIdentifiers方法获得一个枚举对象,该对象又包含了系统中管理每个端口的CommPortIdentifier对象。注意这里的端口不仅仅是指串口,也包括并口。这个方法还可以带参数。getPortIdentifiers(CommPort)获得与已经被应用程序打开的端口相对应的CommPortIdentifier对象。 getPortIdentifier(String portName)获取指定端口名(比如“COM1”)的CommPortIdentifier对象。*/
17  
18         while (portList.hasMoreElements()) {
19             portId = (CommPortIdentifier) portList.nextElement();
20             if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)/*getPortType方法返回端口类型*/ {
21                 // if (portId.getName().equals("COM1"))/* 找Windows下的第一个串口*/ {
22                 if (portId.getName().equals("/dev/term/a"))/*找Unix-like系统下的第一个串口*/ {
23                     SimpleRead reader = new SimpleRead();
24                 }
25             }
26         }
27     }
28  
29     public SimpleRead() {
30         try {
31             serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);/* open方法打开通讯端口,获得一个CommPort对象。它使程序独占端口。如果端口正被其他应用程序占用,将使用 CommPortOwnershipListener事件机制,传递一个PORT_OWNERSHIP_REQUESTED事件。每个端口都关联一个 InputStream 何一个OutputStream。如果端口是用open方法打开的,那么任何的getInputStream都将返回相同的数据流对象,除非有close 被调用。有两个参数,第一个为应用程序名;第二个参数是在端口打开时阻塞等待的毫秒数。*/
32         } catch (PortInUseException e) {}
33         try {
34             inputStream = serialPort.getInputStream();/*获取端口的输入流对象*/
35         } catch (IOException e) {}
36     try {
37             serialPort.addEventListener(this);/*注册一个SerialPortEventListener事件来监听串口事件*/
38     } catch (TooManyListenersException e) {}
39  
40         serialPort.notifyOnDataAvailable(true);/*数据可用*/
41  
42         try {
43             serialPort.setSerialPortParams(9600,
44                 SerialPort.DATABITS_8,
45                 SerialPort.STOPBITS_1,
46                 SerialPort.PARITY_NONE);/*设置串口初始化参数,依次是波特率,数据位,停止位和校验*/
47         } catch (UnsupportedCommOperationException e) {}
48  
49         readThread = new Thread(this);
50         readThread.start();
51     }
52  
53     public void run() {
54         try {
55             Thread.sleep(20000);
56         } catch (InterruptedException e) {}
57     }
58  
59 //串口事件
60     public void serialEvent(SerialPortEvent event) {
61  
62         switch(event.getEventType()) {
63         case SerialPortEvent.BI:/*Break interrupt,通讯中断*/
64         case SerialPortEvent.OE:/*Overrun error,溢位错误*/
65         case SerialPortEvent.FE:/*Framing error,传帧错误*/
66         case SerialPortEvent.PE:/*Parity error,校验错误*/
67         case SerialPortEvent.CD:/*Carrier detect,载波检测*/
68         case SerialPortEvent.CTS:/*Clear to send,清除发送*/
69         case SerialPortEvent.DSR:/*Data set ready,数据设备就绪*/
70         case SerialPortEvent.RI:/*Ring indicator,响铃指示*/
71         case SerialPortEvent.OUTPUT_BUFFER_EMPTY:/*Output buffer is empty,输出缓冲区清空*/
72             break;
73  
74         case SerialPortEvent.DATA_AVAILABLE:/*Data available at the serial port,端口有可用数据。读到缓冲数组,输出到终端*/
75             byte[] readBuffer = new byte[20];
76  
77             try {
78                 while (inputStream.available() > 0) {
79                     int numBytes = inputStream.read(readBuffer);
80                 }
81                 System.out.print(new String(readBuffer));
82             } catch (IOException e) {}
83             break;
84         }
85     }
86 }
87  
 
(2)写串口
import java.io.*;
import java.util.*;
import javax.comm.*;
 
public class SimpleWrite {
    static Enumeration portList;
    static CommPortIdentifier portId;
    static String messageString = "Hello, world!/n";
    static SerialPort serialPort;
10     static OutputStream outputStream;
11  
12     public static void main(String[] args) {
13         portList = CommPortIdentifier.getPortIdentifiers();
14  
15         while (portList.hasMoreElements()) {
16             portId = (CommPortIdentifier) portList.nextElement();
17             if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
18                 // if (portId.getName().equals("COM1")) {
19                 if (portId.getName().equals("/dev/term/a")) {
20                     try {
21                         serialPort = (SerialPort)
22                             portId.open("SimpleWriteApp", 2000);
23                     } catch (PortInUseException e) {}
24                     try {
25                         outputStream = serialPort.getOutputStream();
26                     } catch (IOException e) {}
27                     try {
28                         serialPort.setSerialPortParams(9600,
29                             SerialPort.DATABITS_8,
30                             SerialPort.STOPBITS_1,
31                             SerialPort.PARITY_NONE);
32                     } catch (UnsupportedCommOperationException e) {}
33                     try {
34                         outputStream.write(messageString.getBytes());
35                     } catch (IOException e) {}
36                 }
37             }
38         }
39     }
40 }
41  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值