當前位置:首頁 » 編程語言 » java讀取串口

java讀取串口

發布時間: 2024-11-02 23:01:17

java如何通過串口IC讀卡器讀取IC卡號

讀取IC讀卡器分很多種,有種最簡單的是直接連電腦,使用串口助手軟體,選定特定的波特率,就可以接收IC卡號(有些是像RFIC的就需要對其解碼)

上面問題解決後,重點的是java如何做一個串口助手,眾所周知,java是運行在虛擬機上,也就是要運行在window的一個進程上,如果要java讀寫串口的話,肯定需要對它進行驅動編寫,而不僅僅是載入個jar包就能解決的。

幸運的是SUN公司已經幫我們解決了這個問題,你可以到sun公司網站上下載javacomm20-win32.zip的壓縮包,裡面就包含了串口的驅動(.dll文件)以及對應的jar包,下載後把.dll文件放到你<JDK路徑>/bin,通過jar包提供的api你就可以操作串口相關的介面了。這里一遍關於java串口使用的文章,希望能提供給您:http://blog.csdn.net/kabini/article/details/1601324

㈡ 在java的web程序中怎麼使用串口通訊

方法如下:

  1. 新建eclipse工程,添加comm.jar或者RXTXcomm.jar包。因為javacomm20-win32.zip包里有樣例SimpleRead.java,可以通過這個例子測試串口是否正確。

  2. 接收數據正確後,根據傳送接收雙方的協議,採用CRC循環校驗,根據傳輸的一方的校驗函數判定是否是正確傳輸。

  3. 把正確結束的數據解析,查看自己指定的通訊規則,然後解析。

  4. 插入資料庫,jdbc插入。

  5. 數據統計,定時統計每小時,每天,每月,每年的平均值,採用quartz服務來實現。

  6. 建立web工程,採用hibernate3,spring3,dwr技術把資料庫數據動態顯示,圖表採用jfreechart,以及AJAX的運用

㈢ jsp,java串口通信的問題

可以,使用comm,jar

class SerialExample {

public static void main(String[] args) {
//TO DO: Add your JAVA codes here
long curTime = System.currentTimeMillis();
long serialtime = 8000;
boolean state = true;
SerialBean SB = new SerialBean(2);//設置埠號2
String Msg = "AD 01 0D";//發送命令
SB.Initialize(9600);//設置波率
SB.WritePort(Msg);//發送命令
/* for (int i = 5; i < 10; i++) {
System.out.println( SB.ReadPort(3));//設置讀取個數
}
*/
String readdata = SB.ReadPort("0D",4000);//讀取以OD結束的數據,4000ms沒有數據就返回空
if (readdata.length() > 0) { //System.out.println(readdata.length());//如果有讀到數據
System.out.println(readdata);//如果有讀到數據
}
while (readdata.length() < 1 && state) {//如果沒有讀到數據
readdata = SB.ReadPort("0D",4000);
System.out.println(readdata);
if (System.currentTimeMillis() - curTime > serialtime) {
state = false;//設置讀取錯誤超時
}
System.out.println("readdaa:" + state);
System.out.println(System.currentTimeMillis() - curTime);
}
if (!state) {
System.out.println("數據讀取超時");
}
SB.ClosePort();//關閉連接
}
}

public class SerialBuffer {

Convents cv = new Convents();
private String Content = "";
private String CurrentMsg, TempContent;
private boolean available = false;
private int LengthNeeded = 1;
String str = "";
byte b;

/**
*
* This function returns a string with a certain length from the incoming
* messages.
*
* @param Length The length of the string to be returned.
*
*/
public synchronized String GetMsg(int Length) {
LengthNeeded = Length;
long timeout=2000;
long curtime=System.currentTimeMillis();
notifyAll();

if (LengthNeeded > Content.length()) {
available = false;
while (available == false) {
try {
if(System.currentTimeMillis()-curtime<timeout) wait();
} catch (InterruptedException e) {
}
}
}

CurrentMsg = Content.substring(0, LengthNeeded);
TempContent = Content.substring(LengthNeeded);
Content = TempContent;
LengthNeeded = 1;
notifyAll();
return CurrentMsg;
}

public synchronized String GetMsg(String endstring,long timeout) {
LengthNeeded =Content.indexOf(endstring);
notifyAll();
if (LengthNeeded < 0) {
available = false;
while (available == false) {
try {
wait(timeout);
available=true;
} catch (InterruptedException e) {
}
}
return "";
}
if (LengthNeeded > 0) {
CurrentMsg = Content.substring(0, LengthNeeded+endstring.length());
TempContent = Content.substring(LengthNeeded+endstring.length());
Content = TempContent;
}

LengthNeeded = -1;
notifyAll();
return CurrentMsg;

}

public synchronized void PutChar(int c) {
Content = Content.concat(cv.byteToHexString(c));
if (LengthNeeded < Content.length() && Content.length() > 0) {
available = true;
}
notifyAll();
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package common.serial;

/**
*
* @author Jason
*/
import java.io.*;
import java.util.*;
import javax.comm.*;
import common.code.Convents;

public class SerialBean {
Convents cv=new Convents();
String PortName = "";
CommPortIdentifier portId = null;
SerialPort serialPort = null;
OutputStream out;
InputStream in;
SerialBuffer SB;
ReadSerial RT;
int rate=9600;
String endstring ="";
long timeout=2000;

public SerialBean(int PortID) {
PortName = "COM" + PortID;
}

public int Initialize(int rate) {

int InitSuccess = 1;
int InitFail = -1;

try {
portId = CommPortIdentifier.getPortIdentifier(PortName);
try {
serialPort = (SerialPort) portId.open("Serial_Communication", 2000);
} catch (PortInUseException e) {

return InitFail;
}

//Use InputStream in to read from the serial port, and OutputStream
//out to write to the serial port.

try {

in = serialPort.getInputStream();
out = serialPort.getOutputStream();
} catch (IOException e) {

return InitFail;
}

//Initialize the communication parameters to 9600, 8, 1, none.

try {

serialPort.setSerialPortParams(rate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);

} catch ( e) {

return InitFail;
}

} catch (NoSuchPortException e) {

return InitFail;
}
SB = new SerialBuffer();
RT = new ReadSerial(SB, in);
RT.start();
return InitSuccess;
}
public String ReadPort(int Length) {
String Msg;
Msg = SB.GetMsg(Length);
return Msg;
}
public String ReadPort(String endstring,long timeout) {
String Msg;
Msg = SB.GetMsg(endstring,timeout);
return Msg;
}
public void WritePort(String Msg) {
try {
out.write(cv.hexStringToByte(Msg));
} catch (IOException e) {
}
}
public void ClosePort() {
serialPort.close();
}
}

package common.serial;

import java.io.*;

public class ReadSerial extends Thread {
private SerialBuffer ComBuffer;
private InputStream ComPort;
char[] ch;

public ReadSerial(SerialBuffer SB, InputStream Port) {
ComBuffer = SB;
ComPort = Port;
}

@Override
public void run() {
int c;
try {
while (true) {
c=ComPort.read();
ComBuffer.PutChar(c);
}
} catch (IOException e) {
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package common.serial;
/**
*
* @author Administrator
*/
public class PortOpreate {
private String sendtxt="";
private String recivetxt="";
private int comid = 1;
private int comrate = 9600;
private int timeout = 4000;
private long waittime = 13000;
private String endtxt = "0D";
private boolean pstate=false;
private String massage="";
public void PortOpreate(boolean hasreturn) {
long curTime = System.currentTimeMillis();
long serialtime = getWaittime();
boolean state = true;
int t=0;
SerialBean SB = new SerialBean(getComid());//設置埠號2
t=SB.Initialize(getComrate());//設置波率
if(t>0){
SB.WritePort(getSendtxt());//發送命令
if (hasreturn) {
String readdata = SB.ReadPort(getEndtxt(), getTimeout());//讀取以OD結束的數據,4000ms沒有數據就返回空
if (readdata.length() > 0) { //System.out.println(readdata.length());//如果有讀到數據
System.out.println(readdata);//如果有讀到數據
}
while (readdata.length() < 1 && state) {//如果沒有讀到數據
readdata = SB.ReadPort(getEndtxt(), getTimeout());
System.out.println(readdata);
if (System.currentTimeMillis() - curTime > serialtime) {
state = false;//設置讀取錯誤超時
}
System.out.println("readdaa:" + state);
System.out.println(System.currentTimeMillis() - curTime);
}
if (!state) {
System.out.println("數據讀取超時");
setMassage("數據讀取超時");
}
setRecivetxt(readdata);
setPstate(state);
}
SB.ClosePort();//關閉連接
}else{
System.out.println("埠號出現錯誤");
setMassage("埠號出現錯誤");
}
}

/**
* @return the sendtxt
*/
public String getSendtxt() {
return sendtxt;
}

/**
* @param sendtxt the sendtxt to set
*/
public void setSendtxt(String sendtxt) {
this.sendtxt = sendtxt;
}

/**
* @return the recivetxt
*/
public String getRecivetxt() {
return recivetxt;
}

/**
* @param recivetxt the recivetxt to set
*/
public void setRecivetxt(String recivetxt) {
this.recivetxt = recivetxt;
}

/**
* @return the comid
*/
public int getComid() {
return comid;
}

public void setComid(int comid) {
this.comid = comid;
}

public int getComrate() {
return comrate;
}

public void setComrate(int comrate) {
this.comrate = comrate;
}

public int getTimeout() {
return timeout;
}

public void setTimeout(int timeout) {
this.timeout = timeout;
}

public long getWaittime() {
return waittime;
}

public void setWaittime(long waittime) {
this.waittime = waittime;
}

public String getEndtxt() {
return endtxt;
}

public void setEndtxt(String endtxt) {
this.endtxt = endtxt;
}

public boolean isPstate() {
return pstate;
}

public void setPstate(boolean pstate) {
this.pstate = pstate;
}

public String getMassage() {
return massage;
}

public void setMassage(String massage) {
this.massage = massage;
}
}

package common.serial;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class PortOperatorServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
long curTime = System.currentTimeMillis();
long serialtime = 8000;
boolean state = true;
String Msg = "AD 01 0D";//發送命令
SerialBean SB = new SerialBean(10);//設置埠號2
SB.Initialize(9600);//設置波率
SB.WritePort(Msg);//發送命令
/* for (int i = 5; i < 10; i++) {
System.out.println( SB.ReadPort(3));//設置讀取個數
}
*/
String readdata = SB.ReadPort("0D",4000);//讀取以OD結束的數據
if (readdata.length() > 0) { //System.out.println(readdata.length());//如果有讀到數據
System.out.println(readdata);//如果有讀到數據
}
while (readdata.length() < 1 && state) {//如果沒有讀到數據
readdata = SB.ReadPort("0D",4000);
System.out.println(readdata);
out.println(readdata);
if (System.currentTimeMillis() - curTime > serialtime) {
state = false;//設置讀取錯誤超時
}
System.out.println("readdaa:" + state);
System.out.println(System.currentTimeMillis() - curTime);

}
if (!state) {
System.out.println("數據讀取超時");
out.println("數據讀取超時");
}
SB.ClosePort();//關閉連接
} finally {
out.close();
}
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

public String getServletInfo() {
return "Short description";
}

}

package common.code;

public final class Convents {

public final static char[] BToA = "0123456789abcdef".toCharArray();

/**
* 把16進制字元串轉換成位元組數組A1 01 0D
* @param hex
* @return
*/
public byte[] hexStringToByte(String hex) {
String str[] = hex.split(" ");
int len = str.length;
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
result[i] = (byte) (toByte(str[i].charAt(0)) * 16 + toByte(str[i].charAt(1)));
}
return result;
}

private static byte toByte(char c) {
byte b = (byte) ("0123456789ABCDEF".indexOf(c));
return b;
}

/**
* 把位元組數組轉換成16進制字元串
* @param bArray
* @return
*/
public String byteToHexString(int b){
String st="";
st=Integer.toHexString(b);
if (st.length() < 2) {
st="0"+Integer.toHexString(b).toUpperCase()+" ";
} else {
st=Integer.toHexString(b).toUpperCase()+" ";
}
return st;
}
public String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(bArray[i]).toUpperCase();

}
return sb.toString();
}
}

熱點內容
看巴士的解壓密碼 發布:2024-11-23 10:30:18 瀏覽:578
oracle的sql練習題 發布:2024-11-23 10:28:37 瀏覽:315
linux進程間同步 發布:2024-11-23 10:14:25 瀏覽:185
android朋友圈圖片 發布:2024-11-23 10:02:08 瀏覽:159
eclipsejar源碼亂碼 發布:2024-11-23 10:01:33 瀏覽:145
oracle導入資料庫數據 發布:2024-11-23 09:57:09 瀏覽:796
高訪問網址 發布:2024-11-23 09:53:02 瀏覽:520
android內置apk 發布:2024-11-23 09:46:18 瀏覽:320
郵箱伺服器搭建windows 發布:2024-11-23 09:44:46 瀏覽:560
安卓如何強制關閉 發布:2024-11-23 09:43:05 瀏覽:448