Lua:使用Bit32库来更改I / O的状态。

我正在尝试了解Lua编程如何改变Modbus I/O模块的I/O状态。我已阅读Modbus协议并理解了寄存器、线圈以及读写字符串的方式。但是现在,我正在努力理解如何操作读/写位以及如何使用函数执行这些操作。我知道现在可能很笼统,但是希望以下函数以及其中的一些问题能够帮助我更好地传达我正在断开连接的地方。自我了解比特/字节操作以来已经过了很长时间了。

local funcCodes = {  - [[我理解这一部分]]
    readCoil = 1,
    readInput = 2,
    readHoldingReg = 3,
    readInputReg = 4,
    writeCoil = 5,
    presetSingleReg = 6,
    writeMultipleCoils = 15,
    presetMultipleReg = 16
}
local function toTwoByte(value)
    return string.char(value / 255, value % 255) - [[为什么这两个函数对相同的值执行相同的操作?]]
end
local function readInputs(s)
    local s = mperia.net.connect(host, port)
    s:set_timeout(0.1)
    local req = string.char(0,0,0,0,0,6,unitId,2,0,0,0,6)
    local req = toTwoByte(0) .. toTwoByte(0) .. toTwoByte(6) ..
    string.char(unitId, funcCodes.readInput)..toTwoByte(0) ..toTwoByte(8)
    s:write(req)
    local res = s:read(10)
    s:close()
    if res:byte(10) then
        local out = {}
        for i = 1,8 do
            local statusBit = bit32.rshift(res:byte(10), i - 1) - [[bit32.rshift实际上对字符串执行了什么操作?下一行中的相同情况也是如此,与bit32.band。
            out[#out + 1] = bit32.band(statusBit, 1)
        end
        for i = 1,5 do
            tDT.value["return_low"] = tostring(out[1])
            tDT.value["return_high"] = tostring(out[2])
            tDT.value["sensor1_on"] = tostring(out[3])
            tDT.value["sensor2_on"] = tostring(out[4])
            tDT.value["sensor3_on"] = tostring(out[5])
            tDT.value["sensor4_on"] = tostring(out[6])
            tDT.value["sensor5_on"] = tostring(out[7])
            tDT.value[""] = tostring(out[8])
            end
        end
        return tDT
    end

如果需要更具体的问题,我一定会尝试。但是现在我很难将实际发生的事情与这里的比特/字节操作联系起来。我已阅读了比特32库的两本书和在线资料,但仍不知道这些操作实际上都在做什么。我希望通过这些示例,我可以得到一些澄清。

干杯!

点赞