传递过来的data_bin不是原始数值,是字符,要转换,也就是代码里面调用的bin = tonumber(string.byte(data_bin, i,i)),就是这个功能。
完整代码如下:
[Lua] 纯文本查看 复制代码 ------------------------------------------------------------------
-- 安富莱开发板V6的CAN例子解码器
------------------------------------------------------------------
--分窗标志定义
WIN_0 = 0x0001
WIN_1 = 0x0002
WIN_2 = 0x0004
WIN_3 = 0x0008
WIN_4 = 0x0010
WIN_5 = 0x0020
WIN_6 = 0x0040
WIN_7 = 0x0080
WIN_8 = 0x0100
WIN_9 = 0x0200
WIN_10 = 0x0400
WIN_11 = 0x0800
WIN_12 = 0x1000
WIN_13 = 0x2000
WIN_14 = 0x4000
WIN_15 = 0x8000
bin = {} --全局变量
g_id = 0
g_std_ext = 0
g_data_remote = 0
--CAN 解码函数,返回的字符串将展示到数据窗口
--id 帧ID
--std_ext 0表示标准帧, 1表示扩展帧
--data_remote 0表示数据帧, 1表示远程帧
--datalen 数据长度,字节
--data_bin 二进制数据
--函数返回: ret1解码字符串 , ret2分窗控制字, 波形数据字符串
function can_decoder(id, std_ext, data_remote, datalen, data_bin)
local ret1 = "" --返回值1 解码显示结果
local ret2 = 0 --返回值2 分窗标志
local bin = {}
local i
local str_wave = ""
local pos --位置
local speed --速度
g_id = id
g_std_ext = std_ext
g_data_remote = data_remote
--#将字符串转换到整数数组存放
for i = 1,#data_bin,1 do
bin[i] = tonumber(string.byte(data_bin, i, i))
end
--计算解码结果,将显示在数据包后面
if (id == 0x321) then
pos = bin[1] << 24 + bin[2] << 16 + bin[3] << 8 + bin[4]
speed = bin[5] << 24 + bin[6] << 16 + bin[7] << 8 + bin[8]
str_wave = string.format("%d,%d\r\n", pos, speed)
--判断数据域
if (bin[1] == 0x00) then
ret1 = "控制LED1点亮"
elseif (bin[1] == 0x01) then
ret1 = "控制LED2点亮"
elseif (bin[1] == 0x02) then
ret1 = "控制LED3点亮"
elseif (bin[1] == 0x03) then
ret1 = "控制LED4点亮"
end
end
--计算分窗标志, 决定数据包同步显示到哪些子窗口
if (bin[1] == 0x00) then
ret2 = ret2 | WIN_0
elseif (bin[1] == 0x01) then
ret2 = ret2 | WIN_1
elseif (bin[1] == 0x02) then
ret2 = ret2 | WIN_2
elseif (bin[1] == 0x03) then
ret2 = ret2 | WIN_3
end
return ret1, ret2, str_wave
end
效果:
|