1
Mach4 General Discussion / Re: Doing math to DRO values
« on: December 02, 2022, 04:54:44 AM »
Hi
Craig is right, but I am not sure it depends on the Mach4 version. In my case, the Screen Load script already came with a reading and writing registers according to the Lua script manual as below. please check the manual. This means reading and writing registers is straight forward, but please remember they are write and read as strings, not numbers.
That meant that the registers are strings, even though they are numbers. You have to convert them into a number
Then you can use the variables to do math.
Something that I did not have time to check is that I could not perform an if the operation (Equal) because the decimals were not the same.
I guess I need to use the following, but I have not had time to do it.
Silly things happened to me and crashed mach4, but now I learned (literally this week)
Check your register's name: an empty space at the end of the register. I copy/pasted from notepad and didn't check the empty space, which crashed the PLC script because a "new" variable with nil value was being used.
Pablo
Craig is right, but I am not sure it depends on the Mach4 version. In my case, the Screen Load script already came with a reading and writing registers according to the Lua script manual as below. please check the manual. This means reading and writing registers is straight forward, but please remember they are write and read as strings, not numbers.
Code: [Select]
function GetRegister(regname)
local inst = mc.mcGetInstance()
local hreg = mc.mcRegGetHandle(inst, string.format("iRegs0/%s", regname))
return mc.mcRegGetValueString(hreg)
end
Code: [Select]
function WriteRegister(regname, regvalue)
local inst = mc.mcGetInstance()
local hreg = mc.mcRegGetHandle(inst, string.format("iRegs0/%s", regname))
mc.mcRegSetValueString(hreg, tostring(regvalue))
end
That meant that the registers are strings, even though they are numbers. You have to convert them into a number
Code: [Select]
val = tonumber(val)
Then you can use the variables to do math.
Something that I did not have time to check is that I could not perform an if the operation (Equal) because the decimals were not the same.
I guess I need to use the following, but I have not had time to do it.
Code: [Select]
tonumber(string.format("%." .. (numDecimalPlaces or 0) .. "f", num))
Silly things happened to me and crashed mach4, but now I learned (literally this week)
Check your register's name: an empty space at the end of the register. I copy/pasted from notepad and didn't check the empty space, which crashed the PLC script because a "new" variable with nil value was being used.
Pablo