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 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liuyuinsdu

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

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

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

打赏作者

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

抵扣说明:

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

余额充值