java 串口通信
更新時(shí)間: 2007-05-10 13:45:44來(lái)源: 粵嵌教育瀏覽量:1658
本文主要給出一個(gè)實(shí)用的java 串口通信程序,供大家討論學(xué)習(xí).
/******************************************
* 程序文件名稱:SendComm.java
* 功能:從串行口COM1中發(fā)送數(shù)據(jù)
******************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.comm.*;
class S_Frame extends Frame implements Runnable,ActionListener
{
/*檢測(cè)系統(tǒng)中可用的通訊端口類 */
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("打開(kāi)COM1,波特率9600,數(shù)據(jù)位8,停止位1.");
TextArea out_message=new TextArea();
Button btnOpen=new Button("打開(kāi)串口, 發(fā)送數(shù)據(jù)");
Button btnClose=new Button("關(guān)閉串口, 停止發(fā)送數(shù)據(jù)");
byte data[]=new byte[10240];
/*設(shè)置判斷要是否關(guān)閉串口的標(biāo)志*/
boolean mark;
/*安排窗體*/
S_Frame()
{ super("串口發(fā)送數(shù)據(jù)");
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
/*點(diǎn)擊按扭打開(kāi)串口.*/
public void actionPerformed(ActionEvent event) {
if (event.getSource()==btnClose){
serialPort.close(); //關(guān)閉串口
mark=true; //用于中止線程的run()方法
in_message.setText("串口COM1已經(jīng)關(guān)閉,停止發(fā)送數(shù)據(jù).");
}
else { mark=false;
/*從文本區(qū)按字節(jié)讀取數(shù)據(jù)*/
data=out_message.getText().getBytes();
/*打開(kāi)串口*/
start();
in_message.setText("串口COM1已經(jīng)打開(kāi),正在每2秒鐘發(fā)送一次數(shù)據(jù).....");
}
} //actionPerformed() end
/*打開(kāi)串口,并調(diào)用線程發(fā)送數(shù)據(jù)*/
public void start(){
/*獲取系統(tǒng)中所有的通訊端口 */
portList=CommPortIdentifier.getPortIdentifiers();
/* 用循環(huán)結(jié)構(gòu)找出串口 */
while (portList.hasMoreElements()){
/*強(qiáng)制轉(zhuǎn)換為通訊端口類型*/
portId=(CommPortIdentifier)portList.nextElement();
if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
if (portId.getName().equals("COM1")) {
/*打開(kāi)串口 */
try {
serialPort = (SerialPort) portId.open("ReadComm", 2000);
}
catch (PortInUseException e) { }
/*設(shè)置串口輸出流*/
try {
outputStream = serialPort.getOutputStream();
}
catch (IOException e) {}
} //if end
} //if end
} //while end
/*調(diào)用線程發(fā)送數(shù)據(jù)*/
try{
readThread = new Thread(this);
//線程負(fù)責(zé)每發(fā)送一次數(shù)據(jù),休眠2秒鐘
readThread.start();
}
catch (Exception e) { }
} //start() end
/*發(fā)送數(shù)據(jù),休眠2秒鐘后重發(fā)*/
public void run() {
/*設(shè)置串口通訊參數(shù)*/
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}
catch (UnsupportedCommOperationException e) { }
/*發(fā)送數(shù)據(jù)流(將數(shù)組data[]中的數(shù)據(jù)發(fā)送出去)*/
try {
outputStream.write(data);
}
catch (IOException e) { }
/*發(fā)送數(shù)據(jù)后休眠2秒鐘,然后再重發(fā)*/
try { Thread.sleep(2000);
if (mark)
{return; //結(jié)束run方法,導(dǎo)致線程死亡
}
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中接收數(shù)據(jù)
******************************************/
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
{
/* 檢測(cè)系統(tǒng)中可用的通訊端口類 */
static CommPortIdentifier portId;
/* Enumeration 為枚舉型類,在java.util中 */
static Enumeration portList;
InputStream inputStream;
/* 聲明RS-232串行端口的成員變量 */
SerialPort serialPort;
Thread readThread;
String str="";
TextField out_message=new TextField("上面文本框顯示接收到的數(shù)據(jù)");
TextArea in_message=new TextArea();
Button btnOpen=new Button("打開(kāi)串口");
/*建立窗體*/
R_Frame()
{
super("串口接收數(shù)據(jù)");
setSize(200,200);
setVisible(true);
btnOpen.addActionListener(this);
add(out_message,"South");
add(in_message,"Center");
add(btnOpen,"North");
} //R_Frame() end
/*點(diǎn)擊按扭所觸發(fā)的事件:打開(kāi)串口,并監(jiān)聽(tīng)串口. */
public void actionPerformed(ActionEvent event)
{
/*獲取系統(tǒng)中所有的通訊端口 */
portList=CommPortIdentifier.getPortIdentifiers();
/* 用循環(huán)結(jié)構(gòu)找出串口 */
while (portList.hasMoreElements()){
/*強(qiáng)制轉(zhuǎn)換為通訊端口類型*/
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("已打開(kāi)端口COM1 ,正在接收數(shù)據(jù)..... ");
}
catch (PortInUseException e) { }
/*設(shè)置串口監(jiān)聽(tīng)器*/
try {
serialPort.addEventListener(this);
}
catch (TooManyListenersException e) { }
/* 偵聽(tīng)到串口有數(shù)據(jù),觸發(fā)串口事件*/
serialPort.notifyOnDataAvailable(true);
} //if end
} //if end
} //while end
readThread = new Thread(this);
readThread.start(); //線程負(fù)責(zé)每接收一次數(shù)據(jù)休眠20秒鐘
} //actionPerformed() end
/*接收數(shù)據(jù)后休眠20秒鐘*/
public void run() {
try {
Thread.sleep(20000);
}
catch (InterruptedException e) { }
} //run() end
/*串口監(jiān)聽(tīng)器觸發(fā)的事件,設(shè)置串口通訊參數(shù),讀取數(shù)據(jù)并寫(xiě)到文本區(qū)中*/
public void serialEvent(SerialPortEvent event) {
/*設(shè)置串口通訊參數(shù):波特率、數(shù)據(jù)位、停止位、奇偶校驗(yàn)*/
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 {
/* 從線路上讀取數(shù)據(jù)流 */
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
} //while end
str=new String(readBuffer);
/*接收到的數(shù)據(jù)存放到文本區(qū)中*/
in_message.append(str+"\n");
}
catch (IOException e) { }
} //serialEvent() end
} //類R_Frame end
public class ReadComm
{
public static void main(String args[])
{
/* 實(shí)例化接收串口數(shù)據(jù)的窗體類 */
R_Frame R_win=new R_Frame();
/* 定義窗體適配器的關(guān)閉按鈕功能 */
R_win.addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(0); }
});
R_win.pack();
}
}
粵嵌動(dòng)態(tài)
推薦閱讀
- ·Linux字符設(shè)備驅(qū)動(dòng)框架解析:file_operations的核心作用與實(shí)現(xiàn)
- ·廣東朝歌數(shù)碼科技股份有限公司專場(chǎng)招聘會(huì)
- ·深化產(chǎn)教融合,共筑技能人才培養(yǎng)新生態(tài) —— 廣州華立學(xué)院到訪粵嵌從化校區(qū)為深化產(chǎn)教
- ·校企合作新突破 | 粵嵌科技與三亞學(xué)院共探產(chǎn)教融合新路徑
- ·粵嵌科技入選國(guó)家級(jí)職業(yè)數(shù)字展館聯(lián)合建設(shè)單位,賦能計(jì)算機(jī)程序設(shè)計(jì)員高技能人才培養(yǎng)
- ·嵌入式實(shí)時(shí)操作系統(tǒng)的性能優(yōu)化與實(shí)現(xiàn)路徑
- ·校企攜手賦能教育!粵嵌科技助力海南科技職業(yè)大學(xué)探索 AGI 時(shí)代教學(xué)新范式
- ·嵌入式系統(tǒng)中的低功耗設(shè)計(jì)策略與實(shí)現(xiàn)路徑
- ·深圳市軒宇軟件開(kāi)發(fā)有限公司專場(chǎng)招聘會(huì)
- ·嵌入式系統(tǒng)中的代碼空間優(yōu)化:策略與實(shí)踐