基本信息
源码名称:RTXT 通信示例源码
源码大小:0.09M
文件格式:.rar
开发语言:Java
更新时间:2017-07-18
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
现在身边没有硬件设备,所以只能给简单的实例给你看了
现在身边没有硬件设备,所以只能给简单的实例给你看了
package com.rxtx;
import gnu.io.SerialPort;
import java.util.Observer;
import java.util.*;
public class Test implements Observer{
SerialReader sr=new SerialReader();
public Test()
{
openSerialPort(""); //打开串口。
}
public void update(Observable o, Object arg){
String mt=new String((byte[])arg);
System.out.println("---" mt); //串口数据
}
/**
* 往串口发送数据,实现双向通讯.
* @param string message
*/
public void send(String message)
{
Test test = new Test();
test.openSerialPort(message);
}
/**
* 打开串口
* @param String message
*/
public void openSerialPort(String message)
{
HashMap<String, Comparable> params = new HashMap<String, Comparable>();
String port="COM1";
String rate = "9600";
String dataBit = "" SerialPort.DATABITS_8;
String stopBit = "" SerialPort.STOPBITS_1;
String parity = "" SerialPort.PARITY_NONE;
int parityInt = SerialPort.PARITY_NONE;
params.put( SerialReader.PARAMS_PORT, port ); // 端口名称
params.put( SerialReader.PARAMS_RATE, rate ); // 波特率
params.put( SerialReader.PARAMS_DATABITS,dataBit ); // 数据位
params.put( SerialReader.PARAMS_STOPBITS, stopBit ); // 停止位
params.put( SerialReader.PARAMS_PARITY, parityInt ); // 无奇偶校验
params.put( SerialReader.PARAMS_TIMEOUT,100 ); // 设备超时时间 1秒
params.put( SerialReader.PARAMS_DELAY, 100 ); // 端口数据准备时间 1秒
try {
sr.open(params);
sr.addObserver(this);
if(message!=null&&message.length()!=0)
{
sr.start();
sr.run(message);
}
} catch (Exception e) {
}
}
public String Bytes2HexString(byte[] b) {
String ret = "";
for (int i = 0; i < b.length; i ) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' hex;
}
ret = hex.toUpperCase();
}
return ret;
}
public String hexString2binaryString(String hexString) {
if (hexString == null || hexString.length() % 2 != 0)
return null;
String bString = "", tmp;
for (int i = 0; i < hexString.length(); i ) {
tmp = "0000" Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i 1), 16));
bString = tmp.substring(tmp.length() - 4);
}
return bString;
}
}