MODBUS RTU 如何计算CRC校验

用LUA脚本写的demo,大家可以参考

---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by liuyu.
--- DateTime: 2022/1/27 16:17
---

function And(num1,num2)
    local tmp1 = num1
    local tmp2 = num2
    local ret = 0
    local count = 0
    repeat
        local s1 = tmp1 % 2
        local s2 = tmp2 % 2
        if s1 == s2 and s1 == 1 then
            ret = ret + 2^count
        end
        tmp1 = math.modf(tmp1/2)
        tmp2 = math.modf(tmp2/2)
        count = count + 1
    until(tmp1 == 0 and tmp2 == 0)
    return ret
end

function Xor(num1,num2)
    local tmp1 = num1
    local tmp2 = num2
    local ret = 0
    local count = 0
    repeat
        local s1 = tmp1 % 2
        local s2 = tmp2 % 2
        if s1 ~= s2 then
            ret = ret + 2^count
        end
        tmp1 = math.modf(tmp1/2)
        tmp2 = math.modf(tmp2/2)
        count = count + 1
    until(tmp1 == 0 and tmp2 == 0)
    return ret
end

function bit_rshift(value,n)
    value = math.modf(value / (2^n))
    return value
end

function CRC16(arr,len)
    local tmp = 0xffff
    for i=1,len do
        tmp = Xor(arr[i],tmp)
        for j=1,8 do
            local tmp1 = And(tmp,0x01)
            if tmp1 == 1 then
                tmp = bit_rshift(tmp,1)
                tmp = Xor(tmp,0xa001)
            else
                tmp = bit_rshift(tmp,1)
            end
        end
    end
    local ret1 = (tmp % 256)
    local ret2 = math.modf( tmp / 256)
    return ret1,ret2
end

requestADU = {}

requestADU[1] = 0x01
requestADU[2] = 0x03
requestADU[3] = 0x00
requestADU[4] = 0x00
requestADU[5] = 0x00
requestADU[6] = 0x01
crcH,crcL = CRC16(requestADU,6)
requestADU[7] = crcH
requestADU[8] = crcL

for i=1,8 do
    print(string.format("%x",requestADU[i]))
end

所以整个是 01 03 00 00 00 01 84 0a

CRC是84 0a 

参与评论 您还未登录,请先 登录 后发表或查看评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

liuyuinsdu

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值