展开全部

可以,使用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";//发送e68a843231313335323631343130323136353331333262346433命令

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

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

}

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 串口通信问题_jsp,java串口通信的问题相关推荐

  1. codesys中打开linux端的串口_干货分享——安卓串口通信

    1 引言 串行接口是一种可以将接受来自CPU的并行数据字符转换为连续的串行数据流发送出去,同时可将接受的串行数据流转换为并行的数据字符供给CPU的器件.串口通信(Serial Communicatio ...

  2. 蓝牙串口通信java_Java程序与串口通信的实现及通信原码-全网最详细,一步一步教会...

    RS-232(ANSI/EIA-232标准)是IBM-PC及其兼容机上的串行连接标准.RS-422(EIA RS-422-AStandard)是Apple的Macintosh计算机的串口连接标准.RS ...

  3. 【Java编程系列】使用Java进行串口SerialPort通讯

    热门系列: [Java编程系列]WebService的使用 [Java编程系列]在Spring MVC中使用工具类调用Service层时,Service类为null如何解决 [Java编程系列]Spr ...

  4. java多线程三之线程协作与通信实例

    多线程的难点主要就是多线程通信协作这一块了,前面笔记二中提到了常见的同步方法,这里主要是进行实例学习了,今天总结了一下3个实例: 1.银行存款与提款多线程实现,使用Lock锁和条件Condition. ...

  5. JAVA SE学习day_07:异常处理、TCP通信

    一.异常中常见的方法 public static void main(String[] args) {System.out.println("程序开始了");try {String ...

  6. stm32串口通信(初学者对于串口通信的理解)

    stm32串口通信(初学者对于串口通信的理解) 标签: stm32串口通信单片机 2015-01-24 10:12 987人阅读 评论(0) 收藏 举报  分类: stm32 版权声明:本文为博主原创 ...

  7. java连接stk外部接口_SLWSTK无线开发工具上的外扩串口如何使用(虚拟串口/VCOM)...

    标题:   SLWSTK无线开发工具上的外扩串口如何使用(虚拟串口/VCOM) 关键词:ZigBee, 串口,VCOM,虚拟串口,外扩串口,EFR32, PCB4001,  EFR32MG13P732 ...

  8. qt linux 串口eventdriven,详解 Qt 串口通信程序全程图文 (1)

    Qt 串口通信程序全程图文 是本文介绍的内容,在Qt中并没有特定的串口控制类,现在大部分人使用的是第三方写的qextserialport类,我们这里也是使用的该类.我们可以去 http://sourc ...

  9. android 串口调试工具_树莓派通用串口通信实验

    一.介绍 对于树莓派 3B+来说,他的UART功能有三种:1.内部蓝牙使用:2.控制终端使用:3.与其他设备进行串口通信. 在树莓派USB TO TTL模块实验中学习了通过串口对树莓派进行控制台控制, ...

  10. 【无线串口模块快速选型指南】通信频点、芯片、通信距离、功率灵敏度、电流 空中速率

    目录 简介 串口模块的选型要点 01 通信频点 02 芯片方案 03 通信距离 04 发射功率.接收灵敏度 发射功率 接收灵敏度 05 发射电流.接收电流.休眠电流 06  空中速率 07 天线接口形 ...

最新文章

  1. 使用mysql-proxy 快速实现mysql 集群 读写分离
  2. VS2019配置opencv环境时找不到Microsoft.Cpp.x64.user.props
  3. 裁剪(Clipping)-Window GDI
  4. windows7出现MTP usb设备驱动安装问题解决方法
  5. 【洛谷 2661】信息传递
  6. Visual C# 诠释常用排序算法
  7. java GoF 的 23 种设计模式的分类和功能
  8. 如何查看Android项目的gradle版本和路径
  9. linux通过数字权限设置密码,linux--权限管理和用户管理
  10. Matlab —— 电路仿真
  11. 2020秋招华为笔试题-买钉子
  12. hscan命令redis中游标的含义
  13. 公共基础知识:四大名楼简介
  14. 数字万用表常用功能使用
  15. 解决pr调用麦克风的问题
  16. Spatial-Spectral Transformer for Hyperspectral Image Classification_外文翻译
  17. 给一个字符类型的数组chas和一个整数size,请把大小为size的左半区整体右移到右半区,右半区整体移动到左边。
  18. 2020中国最佳创新公司50榜单正式发布,哔哩哔哩、理想汽车等上榜
  19. 通用型RS485通讯电池监测模块的功能及应用方案
  20. 【React+TS】从零开始搭建react+typescript+router+redux+less+px2rem自适应+sass+axios反向代理+别名@+Antd-mobile

热门文章

  1. lvchange的available參数
  2. HDOJ 5184 Brackets 卡特兰数扩展
  3. 【互联在线1001个设想】之“自需产品在自家店买”
  4. top、kill实现进程结束
  5. phantom物料 issue
  6. Matlab仿真产生复高斯白噪声,验证包络服从瑞利分布,包络平方服从指数分布
  7. 8086汇编语言实现数组冒泡排序(全注释)
  8. python开始_python开始的一天
  9. java dom_Java DOM 解析 XML详解
  10. mysql sql dateadd_在SQL语句中DATEADD和DATEDIFF函数