读写连续32bit M变量转DINT

对连续32位 M变量,可以读取连续32bit M变量并转成对用DINT,或者将DINT数据存储到连续32bit M变量

使用如下JBI和lua代码


-- author:chenliao@elibot.cn
-- 20220708

NOP
SET I000 528
//设置开始M变量地址
SET D002 -1987
//设置需要赋值的数据 DINT
SET B000 2
//B000 =2,将D002 设置到从mstartbit开始的32bit
TIMER T=1 S
WAIT B000 = 0


SET I000 528
//设置开始M变量地址
SET B000 1
//B000 =1,从mstartbit开始的32bit数据转为DINT,存储到D001中
TIMER T=1 S
WAIT B000 = 0
END



function M32bitToDint(startbit)
    local mout = 0
    local mbit = 0
    for i = 32, 1, -1 do
        mbit = get_robot_io_status("M" .. (startbit + i - 1))
        mout = mout | mbit
        mout = mout<<1
    end
    mout = mout>>1
    mout = string.pack("I", mout)
    return string.unpack("i", mout)
end

function DintToM32(data, startbit)
    local mout = 0
    mout = string.pack("i", data)
    mout = string.unpack("I", mout)

    for i = 1, 32, 1 do
        if (mout & 1) > 0 then
            set_robot_io_status("M" .. (startbit+i-1), 1)
        else
            set_robot_io_status("M" .. (startbit+i-1), 0)
        end
        mout = mout >> 1
    end
end

sleep(0.3)
local startbit
--I000存储开始bit
local D001
-- 读取从M_startbit开始的32bit并转为DINT数据,存储到D001
local D002
-- 将D002数据(32bit DINT) 存储到M_startbit开始的32bit
local B000
-- B000 =1 ,get data from m_startbit -- m_startbit_32 and transfer to dint, set data to D001
-- B000 =2 ,get data from D002 , and store data in m_startbit -- m_startbit_32
while true do
    B000 = get_global_variable("B000")
    if (B000 == 1) then
        --Read M_startbit to M_startbit+32 and transfer to DINT
        --set result in D001
        startbit = get_global_variable("I000")
        D001 = M32bitToDint(startbit)
        set_global_variable("D001", D001)
        set_global_variable("B000", 0)
    end
    if (B000 == 2) then
        --Set D002(32bit DINT) to M_startbit to M_startbit+32(ttl 32bit)
        startbit = get_global_variable("I000")
        D002 = get_global_variable("D002")
        DintToM32(D002, startbit)
        set_global_variable("B000", 0)
    end
    sleep(0.5)
end
点击显示全文
赞同0
发表评论
分享

手机扫码分享
0
1.059K
收藏
举报
收起
登录
  • 密码登录
  • 验证码登录
还没有账号,立即注册
还没有账号,立即注册
注册
已有账号,立即登录
选择发帖板块
上传文件
举报
请选择举报理由
举报
举报说明