實用的java 串口通訊程式,從串列口COM1中發送/接收資料

來源:互聯網
上載者:User
本文主要給出一個實用的java 串口通訊程式,供大家討論學習.

/******************************************
* 程式檔案名稱:SendComm.java
* 功能:從串列口COM1中發送資料
******************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.comm.*;

class S_Frame extends Frame implements Runnable,ActionListener
{
/*檢測系統中可用的通訊連接埠類 */
static CommPortIdentifier portId;
/*Enumeration 為枚舉型類,在util中 */
static Enumeration portList;
OutputStream outputStream;
/*RS-232的串列口 */
SerialPort serialPort;
Thread readThread;
Panel p=new Panel();
TextField in_message=new TextField("開啟COM1,傳輸速率9600,資料位元8,停止位1.");
TextArea out_message=new TextArea();
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);
} //R_Frame() end

/*點擊按扭開啟串口.*/
public void actionPerformed(ActionEvent event) {
if (event.getSource()==btnClose){
serialPort.close(); //關閉串口
mark=true; //用於中止線程的run()方法
in_message.setText("串口COM1已經關閉,停止發送資料.");
}
else { mark=false;
/*從文本區按位元組讀取資料*/
data=out_message.getText().getBytes();
/*開啟串口*/
start();
in_message.setText("串口COM1已經開啟,正在每2秒鐘發送一次資料.....");
}
} //actionPerformed() end

/*開啟串口,並調用線程發送資料*/
public void start(){
/*擷取系統中所有的通訊連接埠 */
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("ReadComm", 2000);
}
catch (PortInUseException e) { }
/*設定串口輸出資料流*/
try {
outputStream = serialPort.getOutputStream();
}
catch (IOException e) {}
} //if end
} //if end
} //while end
/*調用線程發送資料*/
try{
readThread = new Thread(this);
//線程負責每發送一次資料,休眠2秒鐘
readThread.start();
}
catch (Exception e) { }
} //start() end

/*發送資料,休眠2秒鐘後重發*/
public void run() {
/*設定串口通訊參數*/
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}
catch (UnsupportedCommOperationException e) { }
/*發送資料流(將數組data[]中的資料發送出去)*/
try {
outputStream.write(data);
}
catch (IOException e) { }
/*發送資料後休眠2秒鐘,然後再重發*/
try { Thread.sleep(2000);
if (mark)
{return; //結束run方法,導致線程死亡
}
start();
}
catch (InterruptedException e) { }
} //run() end
} //類S_Frame end

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();
}
}

/******************************************
* 程式檔案名稱:ReadComm.java
* 功能:從串列口COM1中接收資料
******************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.comm.*;

class R_Frame extends Frame implements Runnable,ActionListener,SerialPortEventListener
{
/* 檢測系統中可用的通訊連接埠類 */
static CommPortIdentifier portId;
/* Enumeration 為枚舉型類,在java.util中 */
static Enumeration portList;
InputStream inputStream;
/* 聲明RS-232序列埠的成員變數 */
SerialPort serialPort;
Thread readThread;
String str="";
TextField out_message=new TextField("上面文字框顯示接收到的資料");
TextArea in_message=new TextArea();
Button btnOpen=new Button("開啟串口");

/*建立表單*/
R_Frame()
{
super("串口接收資料");
setSize(200,200);
setVisible(true);
btnOpen.addActionListener(this);
add(out_message,"South");
add(in_message,"Center");
add(btnOpen,"North");
} //R_Frame() end

/*點擊按扭所觸發的事件:開啟串口,並監聽串口. */
public void actionPerformed(ActionEvent event)
{
/*擷取系統中所有的通訊連接埠 */
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("ReadComm", 2000);
out_message.setText("已開啟連接埠COM1 ,正在接收資料..... ");
}
catch (PortInUseException e) { }

/*設定串口監聽器*/
try {
serialPort.addEventListener(this);
}
catch (TooManyListenersException e) { }
/* 偵聽到串口有資料,觸發串口事件*/
serialPort.notifyOnDataAvailable(true);
} //if end
} //if end
} //while end
readThread = new Thread(this);
readThread.start(); //線程負責每接收一次資料休眠20秒鐘
} //actionPerformed() end

/*接收資料後休眠20秒鐘*/
public void run() {
try {
Thread.sleep(20000);
}
catch (InterruptedException e) { }
} //run() end

/*串口監聽器觸發的事件,設定串口通訊參數,讀取資料並寫到文本區中*/
public void serialEvent(SerialPortEvent event) {
/*設定串口通訊參數:傳輸速率、資料位元、停止位、同位*/
try {
serialPort.setSerialPortParams(9600,
  SerialPort.DATABITS_8,
  SerialPort.STOPBITS_1,
  SerialPort.PARITY_NONE);
}
catch (UnsupportedCommOperationException e) {   }
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+"/n");
}
catch (IOException e) { }
} //serialEvent() end
} //類R_Frame end

public class ReadComm
{
public static void main(String args[])
{
/* 執行個體化接收串口資料的表單類 */
R_Frame R_win=new R_Frame();
/* 定義表單適配器的關閉按鈕功能 */
R_win.addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(0); }
});
R_win.pack();
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.