1
Mach4 General Discussion / PLC script to write to a text file
« on: March 09, 2024, 08:37:05 PM »
Hi
I have been trying to debug a code without success for the PLC script (See below). I want to record X,Y,Z vs time in an external text file activated by an output that will start data acquisition of another hardware.
I can successfully monitor the values I want in registers. However, I get an error as soon as I want to use
--attempt to index a nil value (global 'file')
--strack traceback
-- in function 'Mach_PLC_script'
I can open, write, save, and close files in Macros, but that is inconvenient.
Does any one have any idea how to approach this problem or what I am doing wrong?
Code that is added to the PLC:
I have been trying to debug a code without success for the PLC script (See below). I want to record X,Y,Z vs time in an external text file activated by an output that will start data acquisition of another hardware.
I can successfully monitor the values I want in registers. However, I get an error as soon as I want to use
Code: [Select]
file = io.open(MyFile, "a") --open the file in append mode
, --attempt to index a nil value (global 'file')
--strack traceback
-- in function 'Mach_PLC_script'
I can open, write, save, and close files in Macros, but that is inconvenient.
Does any one have any idea how to approach this problem or what I am doing wrong?
Code that is added to the PLC:
Code: [Select]
-------------------------------------------------------
-- position Data
-------------------------------------------------------
local val_x = mc.mcAxisGetPos(inst, mc.X_AXIS) -- get X position
local val_y= mc.mcAxisGetPos(inst, mc.Y_AXIS) -- get Y position
WriteRegister("X_pos",val_x) -- to monitor in register diagnostics ok
WriteRegister("Y_pos",val_y) -- to monitor in register diagnostics ok
local LoadCellSignal = mc.mcSignalGetHandle(inst, mc.OSIG_OUTPUT9 ) -- monitor output 9 activated by macro
local LoadCellSignalState = mc.mcSignalGetState(LoadCellSignal)
if (LoadCellSignalState == 1) then -- if output 9 is activated
local hregTime_LC = mc.mcRegGetHandle(inst, "iRegs0/Time_LC") -- get register Time_LC = 0
local LoadCellTime= mc.mcRegGetValue(hregTime_LC)
if (LoadCellTime==0) then
local Path = GetRegister(Layer_path) -- get File path from register
local MyFile = wx.wxGetCwd() .. Path -- define the file path in Mach4
file = io.open(MyFile, "a") -- open file in append mode
end
LoadCellTime = LoadCellTime+0.05 - follow PLC cycle time as sample rate
WriteRegister("Time_LC",LoadCellTime) -- monitor in register ok
local text = string.format ("%.4f, %.4f, %.4f \n", val_x, val_y, LoadCellTime );
file:write (text ) --Write the Gcode file
file:flush (MyFile) --Save written data
file:close (MyFile) --Close file
end