对modbus寄存器读写带符号整数和浮点数,可以参考以下代码:
--Author:chenliao@elibot.cn --Aug.7,2023 function GetInt16FromModbus(startAdd) -- 读取modbus 1个16bit寄存器,并返回带符号的整数 ret,result = modbus_read_register(ctx,startAdd) if result>32767 then result = result-65536 end return result end function SetInt16ToModbus(startAdd,value) -- 将带符号16位整数value赋值到地址add的modbus寄存器 out= value & 65535 ret1=modbus_write_register(ctx,startAdd,out) end function SetFloatToModbus(startAdd, value) -- 将浮点数value赋值到地址add开始的连续2个modbus寄存器 out = string.pack('f',value) out = string.unpack('I4',out) low = out &65535 high = (out>>16) &65535 -- elite_print(low..','..high) ret1=modbus_write_registers(ctx,startAdd,2,{low,high}) -- elite_print(ret1) -- ret1=modbus_write_register(ctx,startAdd+1,high) end function GetFloatFromModbus(startAdd) -- 从地址add开始的连续2个modbus寄存器读取数据(add地址为低字节,add+1为高字节),并返回浮点数value ret,low = modbus_read_register(ctx,startAdd) ret,high = modbus_read_register(ctx,startAdd+1) local out = (high<<16) | low out = string.pack('I4',out) out = string.unpack('f',out) return out end function SetInt32ToModbus(startAdd, value) -- 将带符号32位整数value 赋值到地址add开始的连续2个modbus寄存器,add地址为低字节,add+1为高字节 low = value &65535 high = (value>>16) &65535 ret1=modbus_write_registers(ctx,startAdd,2,{low,high}) end function GetInt32FromModbus(startAdd) -- 从地址add开始的连续2个modbus寄存器读取数据(add地址为低字节,add+1为高字节),并返回带符号32位整数 ret,low = modbus_read_register(ctx,startAdd) ret,high = modbus_read_register(ctx,startAdd+1) -- elite_print(low..','..high) local out = (high<<16) | low out = string.pack('I4',out) out = string.unpack('i4',out) return out end sleep(0.3) ip="192.168.1.200" --机器人本机ip port=502 ctx=modbus_new_tcp(ip,port) modbus_set_slave(ctx,1) repeat ret=modbus_connect(ctx) until(ret~=-1) elite_print('modbus连接成功') while(true) do B001 = get_global_variable('B001') if(B001==1) then in16 = GetInt16FromModbus(300) elite_print('获取到寄存器300的值为'..in16) set_global_variable('B001',0) end if(B001==2) then in32 = GetInt32FromModbus(300) elite_print('获取到寄存器300-301的int32为'..in32) set_global_variable('B001',0) end if(B001==3) then f = GetFloatFromModbus(300) elite_print('获取到寄存器300-301浮点数为'..f) set_global_variable('B001',0) end if(B001==4) then SetInt16ToModbus(300,-16) --设置16位带符号整数 elite_print('寄存器300设置为'..-16) set_global_variable('B001',0) end if(B001==5) then SetInt32ToModbus(300,-70000) --地址300存储低字节, 301存储高字节,设置32位带符号整数 elite_print('寄存器300-301设置为-70000') set_global_variable('B001',0) end if(B001==6) then SetFloatToModbus(300,-1.987) --地址300存储低字节, 301存储高字节,设置32位浮点数 elite_print('寄存器300-301设置为-1.987') set_global_variable('B001',0) end end