java串口通信
① java高人指點串口通信
搜了下,都說是配置問題
一種解決方案
win32com.dll 放在 jdk\jre\bin 目錄
comm.jar in 放在 jdk\jre\lib\ext目錄
javax.comm.properties 放在 jdk\jre\lib目錄
另外javax.comm在win下不再維護,可以考慮配合使用rxtx
Sun no longer offer's the Windows platform binaries of javax.comm, however javax.comm 2.0.3 can be used for the Windows platform, by using it in conjunction with the Win32 implementation layer provided by the RxTx project. To use that, download javax.comm for the 'generic' platform (which provides the front-end javax.comm API only, without platform specific back-end implementations bundled). Then acquire the Windows binary implementation rxtx-2.0.7pre1 from http://www.rxtx.org(搬到http://users.frii.com/jarvi/rxtx/index.html了).
② java串口,讀取和發送數據
publicstaticvoidprocess(){
try{
EnumerationportList=CommPortIdentifier.getPortIdentifiers();
while(portList.hasMoreElements())
{
CommPortIdentifierportId=(CommPortIdentifier)portList.nextElement();
if(portId.getPortType()==CommPortIdentifier.PORT_SERIAL)//如果埠類型是串口則判斷名稱
{
if(portId.getName().equals("COM1")){//如果是COM1埠則退出循環
break;
}else{
portId=null;
}
}
}
SerialPortserialPort=(SerialPort)portId.open("Serial_Communication",1000);//打開串口的超時時間為1000ms
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);//設置串口速率為9600,數據位8位,停止位1們,奇偶校驗無
InputStreamin=serialPort.getInputStream();//得到輸入流
OutputStreamout=serialPort.getOutputStream();//得到輸出流
//進行輸入輸出操作
//操作結束後
in.close();
out.close();
serialPort.close();//關閉串口
}catch(PortInUseExceptione){
e.printStackTrace();
}catch(){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
③ java串口通信中怎樣以十六進制數發送
做串口通訊的時候基本都是通過io流讀取、輸出。那麼在java開發中發送數據的時候使用OutputStream,而其write()的參數是位元組數組、int整形。如果使用位元組數組發送的時候,通常可以直接寫成out.write("1234".getBytes())。這樣一來單片機讀到的數據則是31 32 33 34。但是在串口發送的時候先把16進制字元串轉化為byte數組在發送出來,則是發送什麼讀取到的就是什麼。使用:out.write(HexString2Bytes("1234"));那麼讀取到的還是1234。16進制字元串轉化為byte數組的方法為:
public static byte[] HexString2Bytes(String src) {
if (null == src || 0 == src.length()) {
return null;
}
byte[] ret = new byte[src.length() / 2];
byte[] tmp = src.getBytes();
for (int i = 0; i < (tmp.length / 2); i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
在用java做串口開發的時候建議使用開源的Rxtx做。效率、使用方法都要優。使用sun開源的comm個人覺得不是很便利。rxtx網上有開源實例。可以根據自己個需求進行加以修飾利用。
④ java串口通信數據丟失,怎麼解決
解決辦法:
1、將兩台PC間波特率設置為一樣的大小。
2、採取進距離傳輸,隨著距離的增加,信息衰減率也便增加。
3、盡量採用低波特率傳輸,這樣誤碼率會大大減少。
4、加入數據校驗功能,在接收數據一方實現「奇偶校驗法」等方法驗證數據傳輸的完整性。
⑤ java 串口通信
這里的Byte並不是Java中八種基本類型中的byte,作為數據類型,byte是要表示負數的,但作為串口值,並不需要負數,所以這里的Byte最大值可以表示255
⑥ java實現串口通信代碼
public static void process() {
try {
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements())
{
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)//如果埠類型是串口則判斷名稱
{
if(portId.getName().equals("COM1")){//如果是COM1埠則退出循環
break;
}else{
portId=null;
}
}
}
SerialPort serialPort = (SerialPort)portId.open("Serial_Communication", 1000);//打開串口的超時時間為1000ms
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);//設置串口速率為9600,數據位8位,停止位1們,奇偶校驗無
InputStream in = serialPort.getInputStream();//得到輸入流
OutputStream out = serialPort.getOutputStream();//得到輸出流
//進行輸入輸出操作
//操作結束後
in.close();
out.close();
serialPort.close();//關閉串口
} catch (PortInUseException e) {
e.printStackTrace();
} catch ( e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
⑦ 在java的web程序中怎麼使用串口通訊
最近在做java串口通訊,主要是用個人電腦通過串口從RS485讀取數據,並通過crc循環冗餘校驗,把接收正確的數據解析,插入資料庫mysql,並用SSH技術把資料庫數據以表格以及圖表形式顯示
思路:
1.為了從RS485讀取數據,由於暫時沒有硬體設備,系統是win7,故採用Virtual Serial Port Drive(VSPD)這塊虛擬串口軟體代替。並下載sscom32.exe模擬串口通信軟體。
2. 要想實現串口通信,用Java實現串口通信(windows系統下),需要用到sun提供的串javacomm20-win32.zip。其中要用到三個文件,配置如下:
comm.jar放置到 JAVA_HOME/jre/lib/ext;
win32com.dll放置到 JAVA_HOME/bin;
javax.comm.properties 兩個地方都要放
jre/lib(也就是在JAVA文件夾下的jre),JAVA_HOME/jre/lib下
這個配置在我電腦上測試成功,也許不需要這樣麻煩。注意的是,如果你使用myeclipse,因為它自帶jre,你需要在它所在的jre相應位置放dll以及properties文件。
是不是感覺這個很麻煩,還有windows的限制。後來我們下載rxtx這款開源包代替了剛才的comm。不僅windows下可以,linux下也可以。使用方法很簡單,配置如下:
RXTXcomm.jar放到JAVA_HOME/jre/lib/ext
rxtxSerial.dll放到JAVA_HOME/bin
如果你使用myeclipse工具,你需要把rxtxSerial.dll放到它自帶的jre里。
3.新建eclipse工程,添加comm.jar或者RXTXcomm.jar包。因為javacomm20-win32.zip包里有樣例SimpleRead.java,可以通過這個例子測試串口是否正確
4.接收數據正確後,根據傳送接收雙方的協議,採用CRC循環校驗,根據傳輸的一方的校驗函數判定是否是正確傳輸
5.把正確結束的數據解析,查看自己指定的通訊規則,然後解析
6.插入資料庫,jdbc插入
7.數據統計,定時統計每小時,每天,每月,每年的平均值,採用quartz服務來實現。
8.建立web工程,採用hibernate3,spring3,dwr技術把資料庫數據動態顯示,圖表採用jfreechart,以及AJAX的運用
⑧ 如何用java進行多串口通信
串口的話只能用JAVA調用,然後通過關閉、打開來判斷。
另外Java是寫不了串口的,需要C才可以
⑨ 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();
}
}
⑩ java串口通信數據緩存要怎麼清空
java串口通信數據緩存要清空步驟:
找到Java的安裝目錄(默認為C:Program FilesJava)選擇當前使用的jre版本,如果用的版本為jre5則進入jre5文件夾,如果用的版本為jre6則進入jre6文件夾。在該文件夾下進入bin文件夾。雙擊打開文件javacpl.exe
在常規選項中的臨時Internet文件點擊「設置」按鈕再點擊「刪除文件」按鈕,刪除所有的臨時文件。
刪除完緩存之後,需要關閉所有瀏覽器。再次打開瀏覽器進入虛擬實驗系統即可。