Logic Machine Forum
Modbus - Write bits in word - Printable Version

+- Logic Machine Forum (https://forum.logicmachine.net)
+-- Forum: LogicMachine eco-system (https://forum.logicmachine.net/forumdisplay.php?fid=1)
+--- Forum: Gateway (https://forum.logicmachine.net/forumdisplay.php?fid=10)
+--- Thread: Modbus - Write bits in word (/showthread.php?tid=1777)



Modbus - Write bits in word - JohnTH - 07.12.2018

Hi,
I have to write bits in a 16-bit register (bitmask) see attachment. This is a control-word for a eaton DC1 freq.converter.
On start I have to set 
Bit2=Fault reset, and Bit8=Control 
Speed reference is set to another register.

I found this thread about reading bit in a bitmask, but can`t figure out how to use the function to write.
https://forum.logicmachine.net/showthread.php?tid=522&pid=2850#pid2850

-John


RE: Modbus - Write bits in word - admin - 07.12.2018

This script will set bit 0 if 1/1/1 is on, bit 1 if 1/1/2 is on etc. Adjust as needed and add writing to ModBus register at the end of the script.

Code:
function setbit(value, bitnr)
  local mask = bit.lshift(1, bitnr)
  return bit.bor(value, mask)
end

value = 0

if grp.getvalue('1/1/1') then
  value = setbit(value, 0)
end

if grp.getvalue('1/1/2') then
  value = setbit(value, 1)
end

if grp.getvalue('1/1/3') then
  value = setbit(value, 2)
end

log(value)



RE: Modbus - Write bits in word - JohnTH - 07.12.2018

Thank you!


RE: Modbus - Write bits in word - iJAF - 12.03.2019

Hello,

I have also made the inverse resetbit() function that could be useful :


Code:
function resetbit(value, bitnr)
 local mask
 mask = bit.lshift(1, bitnr)
 mask = bit.bnot(mask)
 return bit.band(value, mask)
end