Logic Machine Forum
attempt to index global 'mb' (a nil value) - Printable Version

+- Logic Machine Forum (https://forum.logicmachine.net)
+-- Forum: LogicMachine eco-system (https://forum.logicmachine.net/forumdisplay.php?fid=1)
+--- Forum: Scripting (https://forum.logicmachine.net/forumdisplay.php?fid=8)
+--- Thread: attempt to index global 'mb' (a nil value) (/showthread.php?tid=5738)



attempt to index global 'mb' (a nil value) - Simuzer - 12.11.2024

hi all,

I have a project that uses LM and Wago PLC. I am communicating with Modbus.

i think so that if mb is global variable, the problem will be solved


LM send a value to PLC by using event-based script this like : event for (32/1/2)

Code:
value = event.getvalue()
mb:writeregisters(0, value)


LM get values from PLC by using resident-script :

Code:
require('luamodbus')
mb = luamodbus.tcp()
mb:open('192.168.1.102', 502)
mb:connect()

  value = mb:readregisters(0)
  grp.update('32/1/2', value)

mb:close()


I have 2 questions.

First;
I don't want to write connect and ip in every event script. Because when the PLC IP address changes, it will be troublesome to change all of them. And this type of usage is not a correct usage. 

Second;
If the value of LM or PLC changes, that value will be equal in both.



   


RE: attempt to index global 'mb' (a nil value) - admin - 12.11.2024

You can't share the connection this way. You must open a new connection in each script separately.
The best approach is to create a profile instead of multiple scripts.


RE: attempt to index global 'mb' (a nil value) - Simuzer - 12.11.2024

it works like this.

Resident
Code:
require('luamodbus')
mb = luamodbus.tcp()
PLC_IpNo1 = '192.168.1.102'
PLC_IpNo2 = '192.168.1.103'
mb:open(PLC_IpNo1, 502)
mb:connect()
storage.set('strPLC_IpNo1', PLC_IpNo1)
storage.set('strPLC_IpNo2', PLC_IpNo2)
  -- -- --
    curr = mb:readregisters(0)
    prev = storage.get('prev_value')
    if curr ~= prev then
      storage.set('prev_value', curr)
      grp.update('32/1/2', curr)
    end
mb:close()


event-based.
Code:
PLC_IpNo = storage.get('strPLC_IpNo1')
require('luamodbus')
mb = luamodbus.tcp()
mb:open(PLC_IpNo, 502)
mb:connect()
value = event.getvalue()
mb:writeregisters(0, value)
mb:close()