采用标准UART通信接口,逻辑电平为3.3V或5V(取决于上拉电阻)TTL电平,UART工作在8N1模式,即8位数据位,无奇偶校验,一位停止位,常见波特率19200bps, 38400bps。
累加和校验
/** 累加和**/
public static char calCheckSum(byte[] data) {
if (data == null || data.length == 0) {
return 0xFF;
}
char res = 0x00;
for (byte datum : data) {
res += datum & 0xFF;
}
// res ^= 0xFF; 视情况是否要异或取反
res &= 0xFF;
return res;
}
public static char calCheckSum(char... data) {
if (data == null || data.length == 0) {
return 0xFF;
}
char res = 0x00;
for (char datum : data) {
res += datum;
}
// res ^= 0xFF; 视情况是否要异或取反
res &= 0xFF;
return res;
}
可能有些串口协议定义需要对校验和进行异或(取反),或者加一减一的操作,视情况而定。
CRC7校验
/** CRC7**/
public static byte calCheckSum2(byte... data){
if(data == null || data.length == 0){
return (byte) 0xFF;
}
char res = 0x00;
for (byte datum : data) {
for (int j = 0; j < 8; j++) {
res <<= 1;
res ^= (((((datum << j) ^ res) & 0x80) > 0) ? 0x09 : 0);
}
}
res&=0x7F;
return (byte) res;
}
byte数组和String的相互转换:
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (byte b : src) {
int v = b & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase(Locale.ENGLISH);
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
计算协议帧中某个字节的值或者指定某个字节中一位或多位的值,可用以下方法:
/** 计算某个字节指定某几位的值 **/
public static int captureBits(char src, int start, int length) {
if ((length + start) > 16) {
throw new IllegalArgumentException();
}
int filter = (1 << length) - 1;
return (src >> start) & filter;
}
/** 计算某个字节指定某一位的值 **/
public static int captureBit(char src, int position) {
return captureBits(src, position, 1);
}