java 串口(java 串口jSerialComm?发送返回-1)

大家好,今天小编来为大家解答以下的问题,关于java 串口,java 串口jSerialComm?发送返回-1这个很多人还不知道,现在让我们一起来看看吧!

在众多编程语言中,Java以其跨平台、高性能、易学易用等特点,受到了广大开发者的喜爱。而在嵌入式系统、物联网等领域,串口通信更是不可或缺的一部分。本文将带你从入门到精通,深入了解Java串口编程。

一、什么是串口通信

串口通信,即串行通信,是指数据在一条线路上按位进行传输的通信方式。相比于并行通信,串口通信具有成本低、距离远、抗干扰能力强等优点。在Java中,串口通信主要通过`SerialPort`类实现。

二、Java串口编程环境搭建

1. JDK安装:确保你的电脑上已安装Java开发工具包(JDK)。可以从Oracle官网下载最新版本的JDK。

2. IDE选择:推荐使用IntelliJ IDEA、Eclipse等集成开发环境(IDE),它们都支持Java串口编程。

3. 串口工具:可以使用串口调试助手等工具进行串口通信的测试。

三、Java串口编程基础

1. 获取串口列表:在Java中,可以使用`SerialPort.getCommPorts()`方法获取当前电脑上可用的串口列表。

2. 创建串口对象:通过串口列表,可以创建一个`SerialPort`对象,用于后续的串口操作。

3. 配置串口参数:包括波特率、数据位、停止位、校验位等。这些参数需要根据实际硬件进行配置。

4. 打开串口:使用`SerialPort.open()`方法打开串口。

5. 读写数据:使用`SerialPort.getInputStream()`和`SerialPort.getOutputStream()`方法分别获取输入流和输出流,用于读写数据。

6. 关闭串口:完成串口操作后,使用`SerialPort.close()`方法关闭串口。

四、Java串口编程实例

以下是一个简单的Java串口编程实例,用于实现串口数据的发送和接收。

“`java

import com.fazecast.jSerialComm.SerialPort;

public class SerialPortTest {

public static void main(String[] args) {

try {

// 获取串口列表

SerialPort[] ports = SerialPort.getCommPorts();

if (ports.length == 0) {

System.out.println(“

在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通过串口接收数据时,避免使用inputStream.available()方法,因为available返回的是尚未被阻塞的字节数,即已经被缓冲的内容。建议尝试使用read(byte b[])方法,并通过返回值是否为-1来判断数据接收是否结束。具体实现如下:

int bytesRead= inputStream.read(readBuffer);

while(bytesRead!=-1){

readStr+= new String(readBuffer).trim();

bytesRead= inputStream.read(readBuffer);

}

这样可以确保每次读取操作都从上一次读取结束的地方开始,直到读取到-1为止,表明没有更多的数据可读。这种方法能够更好地处理数据流,避免遗漏或重复读取数据。

需要注意的是,read(byte b[])方法每次读取的数据量是不确定的,取决于串口的实际数据传输情况。因此,循环中每次读取的数据应被累加到readStr变量中,直到读取到-1为止。同时,使用trim()方法去除字符串中的多余空格,确保数据的整洁性。

另外,在实际应用中,还应考虑异常处理,确保程序在遇到错误时能够正常退出并给出提示。例如,可以使用try-catch语句捕获可能出现的IOException等异常,及时处理。

总之,通过这种方式读取串口数据,可以更可靠地处理数据流,避免因为available方法的局限性导致的问题。

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(UnsupportedCommOperationException 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;

}

publicString 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 串口jSerialComm?发送返回-1、java 串口的信息别忘了在本站进行查找哦。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享