- 创建好串口工具类:
https://blog.csdn.net/qq_30297763/article/details/85997689
- 创建LED滚动字幕工具类
public class LEDUtils {
public static String getCommond(String data) throws UnsupportedEncodingException {
String hexData = getHexData(data);
int dataLength = hexData.length() / 2;
String dataLengthHex = Integer.toHexString(dataLength);
if (dataLengthHex.length() % 2 != 0) {
dataLengthHex = "0" + dataLengthHex;
}
if (dataLengthHex.length() == 2) {
dataLengthHex = "00" + dataLengthHex;
}
String part1 = "5AA5";
String part2 = "5201010000000001000000000000";
int toalLengthHex = part1.length() / 2 + 2 + part2.length() / 2 + dataLengthHex.length() / 2 + dataLength + 2;
String totalLengthHex = Integer.toHexString(toalLengthHex);
if (totalLengthHex.length() % 2 != 0) {
totalLengthHex = "0" + totalLengthHex;
}
if (totalLengthHex.length() == 2) {
totalLengthHex = "00" + totalLengthHex;
}
String str = part1 + totalLengthHex + part2 + dataLengthHex + hexData;
String crc = getCRC(str);
String result = str + crc;
return result;
}
public static String getHexData(String str) throws UnsupportedEncodingException {
//汉语标点符号的正则 [\u3002\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b]
//汉字的正则 [\u4E00-\u9FA5]
String chinese = "[\\u3002\\uff1b\\uff0c\\uff1a\\u201c\\u201d\\uff08\\uff09\\u3001\\uff1f\\u300a\\u300b\\u4E00-\\u9FA5]";
StringBuffer sb = new StringBuffer();
Pattern pattern = Pattern.compile(chinese);
for (int i = 0; i < str.length(); i++) {
String c = str.substring(i, i + 1);
Matcher m = pattern.matcher(c);
if (m.find()) {
String gb2312 = URLEncoder.encode(c, "GB2312");
String replace = gb2312.replace("%", "");
sb.append(replace);
} else {
String s = strTo16(c);
sb.append(s);
}
}
return sb.toString();
}
public static String getCRC(String str) {
int crc = 0x0;
for (int i = 0; i < str.length() / 2; i++) {
String s = str.substring(i * 2, i * 2 + 2);
int data = Integer.parseInt(s, 16);
for (int j = 0; j < 8; j++) {
int result = (data ^ (char) crc) & 1;
boolean r = result == 1;
crc = r ? ((crc >> 1) ^ 0xA001) : (crc >> 1);
data >>= 1;
}
}
int low = crc & 0xFF;
int heigh = crc >> 8;
String lowStr = Integer.toHexString(low)
.toUpperCase();
String heighStr = Integer.toHexString(heigh)
.toUpperCase();
String result = lowStr + heighStr;
return result;
}
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
if (str.length() % 2 != 0) {
str = "0" + str;
}
return str;
}
}
3.发送指令:
serialPortUtils.sendSerialPort(LEDUtils.getCommond("这是发送的led滚动字幕"));