lua脚本CRC16校验
function add_crc16(start, n, data)
local carry_flag, a = 0
local result = 0xffff
local i = start
while(true)
do
result = result ~ data[i]
for j = 0, 7
do
a = result
carry_flag = a & 0x0001
result = result >> 1
if carry_flag == 1
then
result = result ~ 0xa001
end
end
i = i + 1
if i == start + n
then
break
end
end
return result
end
lua脚本串口发送与CRC16校验使用方法
function UartSendBuf()
local BUF= {}
local send_crc16 = 0
local cmd_head = 0x5A
local cmd_end = 0xA5
BUF[0] = cmd_head
BUF[1] = 0x01
BUF[2] = 0x02
BUF[3] = 0x03
BUF[4] = 0x03
send_crc16 = add_crc16(1, 4, BUF)
BUF[5] = (send_crc16 >> 8) & 0xFF
BUF[6] = (send_crc16 >> 0) & 0xFF
BUF[7] = cmd_end
uart_send_data(BUF)
end
lua脚本串口接收与CRC16校验使用方法
local buff = {}
local cmd_length = 0
local cmd_head_tag = 0
local cmd_end_tag = 0
function on_uart_recv_data(packet)
local cmd_head = 0xA5
local cmd_end = 0x5A
local recv_packet_size = (#(packet))
local check16 = 0
for i = 0, recv_packet_size
do
if packet[0] == cmd_head and cmd_head_tag == 0
then
cmd_head_tag = 1
end
if cmd_head_tag == 1
then
buff[cmd_length] = packet[i]
cmd_length = cmd_length + 1
cmd_end_tag = (cmd_end_tag << 8) | (packet[i])
if (cmd_end_tag & cmd_end)== buff[7]
then
check16 = ((buff[cmd_length - 3] << 8) | buff[cmd_length - 2]) & 0xFFFF
print('CODE= '..string.format('%04X', check16))
print('check16_is = '..string.format('%04X', add_crc16(0, cmd_length - 3, buff)))
if check16 == add_crc16(0, cmd_length - 3, buff)
then
buff = {}
cmd_length = 0
cmd_end_tag = 0
cmd_head_tag = 0
else
buff = {}
cmd_length = 0
cmd_end_tag = 0
cmd_head_tag = 0
end
end
end
end
end