java串口编程3

终于完成了串口的编写,功能很简单,如下:

    做出一个简单界面,向串口发送特定的命令(串口上接有供测试用的串口设备),接收设备返回的数据在界面上显示:

  1. import gnu.io.CommPortIdentifier; 
  2. import gnu.io.PortInUseException; 
  3. import gnu.io.SerialPort; 
  4. import gnu.io.SerialPortEvent; 
  5. import gnu.io.SerialPortEventListener; 
  6. import gnu.io.UnsupportedCommOperationException; 
  7.  
  8. import java.awt.Button; 
  9. import java.awt.Frame; 
  10. import java.awt.Panel; 
  11. import java.awt.TextArea; 
  12. import java.awt.TextField; 
  13. import java.awt.event.ActionEvent; 
  14. import java.awt.event.ActionListener; 
  15. import java.awt.event.WindowAdapter; 
  16. import java.awt.event.WindowEvent; 
  17. import java.io.IOException; 
  18. import java.io.InputStream; 
  19. import java.io.OutputStream; 
  20. import java.util.Enumeration; 
  21. import java.util.TooManyListenersException; 
  22.  
  23. class S_Frame extends Frameimplements ActionListener,SerialPortEventListener { 
  24.      
  25.     //检测系统中可用的通讯端口类 
  26.     static CommPortIdentifier portId; 
  27.     //Enumeration 为枚举型类,在util中 
  28.     static Enumeration portList; 
  29.      
  30.     //输入输出流 
  31.     InputStream inputStream; 
  32.     OutputStream outputStream; 
  33.      
  34.     //RS-232的串行口 
  35.     SerialPort serialPort; 
  36.      
  37.     Thread readThread; 
  38.     String str = ""
  39.      
  40.     //界面 
  41.     Panel p = new Panel(); 
  42.     TextArea in_message = new TextArea("打开COM1,波特率9600,数据位8,停止位1."); 
  43.     TextArea out_message = new TextArea("X010600Y"); 
  44.     Button btnOpen = new Button("打开串口, 发送数据"); 
  45.     Button btnClose = new Button("关闭串口, 停止发送数据"); 
  46.     byte data[] = newbyte[10240]; 
  47.      
  48.     //设置判断要是否关闭串口的标志 
  49.     boolean mark; 
  50.  
  51.     //构造方法:安排窗体 
  52.     S_Frame() { 
  53.         super("串口发送数据"); 
  54.         setSize(200, 200); 
  55.         setVisible(true); 
  56.         add(out_message, "Center"); 
  57.         add(p, "North"); 
  58.         p.add(btnOpen); 
  59.         p.add(btnClose); 
  60.         add(in_message, "South"); 
  61.         btnOpen.addActionListener(this); 
  62.         btnClose.addActionListener(this); 
  63.     } 
  64.      
  65.     //实现ActionListener接口的方法,发生操作时调用 
  66.     //点击按扭打开串口 
  67.     public void actionPerformed(ActionEvent event) { 
  68.          
  69.         //getSource是ActionEvent的父类java.util.EventObject的方法 
  70.         //如果点击关闭按钮 
  71.         if (event.getSource() == btnClose) { 
  72.             serialPort.close(); // 关闭串口 
  73.             mark = true;// 用于中止线程的run()方法 
  74.             in_message.setText("串口COM1已经关闭,停止发送数据."); 
  75.         }  
  76.         //点击打开串口按钮 
  77.           else
  78.             mark = false
  79.             //从文本区按字节读取数据到字节数组 
  80.             data = out_message.getText().getBytes(); 
  81.              
  82.             //获取系统中所有的通讯端口 
  83.             portList = CommPortIdentifier.getPortIdentifiers(); 
  84.             //用循环结构找出串口 
  85.             while (portList.hasMoreElements()) { 
  86.                 //强制转换为通讯端口类型 
  87.                 portId = (CommPortIdentifier) portList.nextElement(); 
  88.                 //判断是否为串口 
  89.                 if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { 
  90.                     if (portId.getName().equals("COM1")) { 
  91.                         //打开串口 
  92.                         try
  93.                             serialPort = (SerialPort) portId.open("testSerialPort",2000); 
  94.                         } catch (PortInUseException e) {} 
  95.                          
  96.                         try
  97.                             //打开输出流 
  98.                             outputStream = serialPort.getOutputStream(); 
  99.                             //向设备发送数据 
  100.                             outputStream.write(data); 
  101.                             //获得输入流 
  102.                             inputStream = serialPort.getInputStream(); 
  103.                         } catch (IOException e) {} 
  104.                          
  105.                         //设置串口监听 
  106.                         try
  107.                             serialPort.addEventListener((SerialPortEventListener)this); 
  108.                         } catch (TooManyListenersException e) {} 
  109.                          
  110.                         serialPort.notifyOnDataAvailable(true); 
  111.                          
  112.                         /* 设置串口通讯参数 */ 
  113.                         try
  114.                             serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, 
  115.                                     SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); 
  116.                         } catch (UnsupportedCommOperationException e) {} 
  117.                     } 
  118.                 } 
  119.             in_message.setText("串口COM1已经打开,正在每2秒钟发送一次数据....."); 
  120.             } 
  121.         } 
  122.     } 
  123.  
  124.     public void serialEvent(SerialPortEvent event) {  
  125.         byte[] readBuffer =new byte[20];  
  126.         try {  
  127.             inputStream = serialPort.getInputStream();  
  128.         } catch (IOException e) {}  
  129.         try {  
  130.             /**//* 从线路上读取数据流 */  
  131.             while (inputStream.available() >0) {  
  132.                 int numBytes = inputStream.read(readBuffer);  
  133.      
  134.             } // while end  
  135.             str = new String(readBuffer);  
  136.      
  137.             //接收到的数据存放到文本区中  
  138.             in_message.append(str + " ");  
  139.         } catch (IOException e) {}  
  140.     } 
  141.  
  142. /**
  143. * SendComm主方法
  144. * @author warm
  145. *
  146. */ 
  147. public class SendComm { 
  148.     public staticvoid main(String args[]) { 
  149.         S_Frame S_win = new S_Frame(); 
  150.         S_win.addWindowListener(new WindowAdapter() { 
  151.             public void windowClosing(WindowEvent e) { 
  152.                 System.exit(0); 
  153.             } 
  154.         }); 
  155.         S_win.pack(); 
  156.     } 
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

import java.awt.Button;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;

class S_Frame extends Frame implements ActionListener,SerialPortEventListener {
    
    //检测系统中可用的通讯端口类
    static CommPortIdentifier portId;
    //Enumeration 为枚举型类,在util中
    static Enumeration portList;
    
    //输入输出流
    InputStream inputStream;
    OutputStream outputStream;
    
    //RS-232的串行口
    SerialPort serialPort;
    
    Thread readThread;
    String str = "";
    
    //界面
    Panel p = new Panel();
    TextArea in_message = new TextArea("打开COM1,波特率9600,数据位8,停止位1.");
    TextArea out_message = new TextArea("X010600Y");
    Button btnOpen = new Button("打开串口, 发送数据");
    Button btnClose = new Button("关闭串口, 停止发送数据");
    byte data[] = new byte[10240];
    
    //设置判断要是否关闭串口的标志
    boolean mark;

    //构造方法:安排窗体
    S_Frame() {
        super("串口发送数据");
        setSize(200, 200);
        setVisible(true);
        add(out_message, "Center");
        add(p, "North");
        p.add(btnOpen);
        p.add(btnClose);
        add(in_message, "South");
        btnOpen.addActionListener(this);
        btnClose.addActionListener(this);
    }
    
    //实现ActionListener接口的方法,发生操作时调用
    //点击按扭打开串口
    public void actionPerformed(ActionEvent event) {
        
        //getSource是ActionEvent的父类java.util.EventObject的方法
        //如果点击关闭按钮
        if (event.getSource() == btnClose) {
            serialPort.close(); // 关闭串口
            mark = true; // 用于中止线程的run()方法
            in_message.setText("串口COM1已经关闭,停止发送数据.");
        } 
        //点击打开串口按钮
          else {
            mark = false;
            //从文本区按字节读取数据到字节数组
            data = out_message.getText().getBytes();
            
            //获取系统中所有的通讯端口
            portList = CommPortIdentifier.getPortIdentifiers();
            //用循环结构找出串口
            while (portList.hasMoreElements()) {
                //强制转换为通讯端口类型
                portId = (CommPortIdentifier) portList.nextElement();
                //判断是否为串口
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    if (portId.getName().equals("COM1")) {
                        //打开串口
                        try {
                            serialPort = (SerialPort) portId.open("testSerialPort", 2000);
                        } catch (PortInUseException e) {}
                        
                        try {
                            //打开输出流
                            outputStream = serialPort.getOutputStream();
                            //向设备发送数据
                            outputStream.write(data);
                            //获得输入流
                            inputStream = serialPort.getInputStream();
                        } catch (IOException e) {}
                        
                        //设置串口监听
                        try {
                            serialPort.addEventListener((SerialPortEventListener) this);
                        } catch (TooManyListenersException e) {}
                        
                        serialPort.notifyOnDataAvailable(true);
                        
                        /* 设置串口通讯参数 */
                        try {
                            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
                                    SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                        } catch (UnsupportedCommOperationException e) {}
                    }
                }
            in_message.setText("串口COM1已经打开,正在每2秒钟发送一次数据.....");
            }
        }
    }

    public void serialEvent(SerialPortEvent event) { 
        byte[] readBuffer = new byte[20]; 
        try { 
            inputStream = serialPort.getInputStream(); 
        } catch (IOException e) {} 
        try { 
            /**//* 从线路上读取数据流 */ 
            while (inputStream.available() > 0) { 
                int numBytes = inputStream.read(readBuffer); 
    
            } // while end 
            str = new String(readBuffer); 
    
            //接收到的数据存放到文本区中 
            in_message.append(str + " "); 
        } catch (IOException e) {} 
    }
}

/**
 * SendComm主方法
 * @author warm
 *
 */
public class SendComm {
    public static void main(String args[]) {
        S_Frame S_win = new S_Frame();
        S_win.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        S_win.pack();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值