Вы находитесь на странице: 1из 41

Exercise Workbook

for ZMxxx programmable indicators

Document No: 160xxx-SUE01 Version : 0.1 Date: May 1, 2015


ZM Exercise Workbook

TABLE OF CONTENT

Exercise #1 – ZTools install...............................................................................4


Exercise #2 – IDE environment..........................................................................5
Exercise #3 - Set and use Breakpoints................................................................6
Exercise #4 - Use Watch Window.......................................................................7
Exercise #5 - Use Setpoint editor and Setpoint Window........................................7
Exercise #6 - Setpoints, watch window and output window...................................8
Exercise #7a – LUA function..............................................................................9
Exercise #7b – LUA function with 1 parameter...................................................10
Exercise #7c – LUA function with 2 parameters..................................................11
Exercise #7d – LUA function with a return value.................................................12
Exercise #7e – LUA function with multiple return values......................................13
Exercise #8 – LUA Table..................................................................................14
Exercise #9 – Control Structures......................................................................15
Exercise #10 – More Control Structures............................................................16
Exercise #11 – Event Handler..........................................................................17
Exercise #12 – Using Print Formats..................................................................18
Exercise #13 – Control Structures....................................................................20
Exercise #14 – Using Setpoints........................................................................23
Exercise #15 – Using Serial Ports.....................................................................24
Exercise #16 – Using Serial Ports.....................................................................25
Exercise #17 – Using Graphic Controls..............................................................26
Exercise #18 – Using serialization....................................................................28
Exercise #19 – FTP –USB notification................................................................29

160xxx-SUE01 Version 0.1


2
ZM Exercise Workbook

Values Returned by getCurrent.........................................................................30


Values returned by getConfig...........................................................................32
ZM Print Tokens.............................................................................................33
ASCII Table...................................................................................................36
Escape Sequences..........................................................................................37
Format Specifier – used in string formatting......................................................38
LUA Operators................................................................................................39
LUA Control Structures – Syntax......................................................................40
if .. then .. else ….......................................................................................40
while loops................................................................................................40
repeat .. until.............................................................................................40
for loops...................................................................................................40
break and return........................................................................................40
Resources......................................................................................................41
Links.........................................................................................................41
Books.......................................................................................................41
Videos.......................................................................................................41
Revision History.............................................................................................41

160xxx-SUE01 Version 0.1


3
ZM Exercise Workbook

Exercise #1 – ZTools install

Actions:
■ Install Ztools Beta from USB drive
■ Start Ztools - Beta
■ Select File-New
■ Select ZM400 Family
■ Select ZM405 Model
■ Select Lua Programming Language
■ Select US for Region
■ Click the Zedit Icon
■ Manipulate your screens so Ztools and Zedit are visible simultaneously

160xxx-SUE01 Version 0.1


4
ZM Exercise Workbook

Exercise #2 – IDE environment

Actions:
■ Manipulate your screen#2 so Ztools, and place Zedit on top of it
■ Select the Play button from the Zedit toolbar
■ Zsim will appear on Screen#1
■ Move it to the upper left hand corner of the display
■ Open up a serial window
■ Devices-Serial Port-Serial Port 1
■ Open up setpoint monitor
■ Make Zsim, setpoint monitor, and Serial Port window fit on one screen simultaneously
■ Move the slide bar up/down
■ Observe that the left slider is Coarse, middle is Moderate, and the right slider is Fine
adjustment.
■ Apply a weight on the scale, then click on the TARE key, observe the functionality
■ Apply some weight, press the PRINT key

160xxx-SUE01 Version 0.1


5
ZM Exercise Workbook

Exercise #3 - Set and use Breakpoints


File : Exercise3.ztools
--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Exercise3

Description: Sample code to accompany the training of the ZM programmable products.


]]--

print("Hello world!") --Prints to the ZEdit output window

x = 0 -- initialize a global variable


y = 0 -- init a global variable

--Start key event for when the key is pressed down


function awtx.keypad.KEY_START_DOWN()
x = x + 1 --increment a variable by 1
y = y + 2 --increment a different variable by 2
print(x,y) --print the values to the output console
end

--****************Startup code should be inserted after this line*************************


--Call to my startup function here

Actions:
■ Open Exercise3.ztools
■ Click on Zedit - maximize
■ Hover cursor between line number and expand/collapse tool by the word print (line 11)
■ Single click – a red dot appears
■ Click Play
■ Observe how the software stops

160xxx-SUE01 Version 0.1


6
ZM Exercise Workbook

Exercise #4 - Use Watch Window


Actions:
■ Place another breakpoint inside the Start key function (Line 18)
■ Right click on the variable “X”, either highlight it, or put the cursor to the right of the
variable. Select “Add Watch Expression” from the list
■ Position the watch window, it can dock onto the primary IDE or remain a separate
window
■ Use the “Step Over” tool to walk through the next lines Click Play to resume code
execution
■ “Pop up” windows appear by hovering over your code with your cursor
■ “Pop up” help appears by hovering over functions

Exercise #5 - Use Setpoint editor and Setpoint Window


Actions:
■ Close Zsim, if you have not already
■ Make Ztools full screen and click Setpoint Editor
■ Septoint#2
 Activate Above, Constant:750lb, Gross Weight, Motion:off
 Deactivate Below, Constant:750lb, Gross, Motion:off
■ Setpoint#3
 Activate Above, Constant:1000lb, Gross Weight, Motion:off
 Deactivate Below, Constant:1000lb, Gross, Motion:off
■ File-Save
■ Click the Play button
■ Run weight up/down and observe the setpoint monitor (Note: your previous screen
settings were remembered)

160xxx-SUE01 Version 0.1


7
ZM Exercise Workbook

Exercise #6 - Setpoints, watch window and output window


File : Exercise6.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Exercise6

Description: Sample code to accompany the training of the ZM programmable products.


]]--

print("Hello world!") --Prints to the ZEdit output window


myVar_0 = 555 -- initialize a global variable on power up
x = 0 -- initialize a global variable on power up
y = 0 -- initialize a global variable on power up

--Start key event for when the key is pressed down


function awtx.keypad.KEY_START_DOWN()
local myVar_0 = 123
x = x + 1 -- increment a variable by 1
y = y + 2 -- increment a variable by 2
print(x,y) -- print variables to the output console
end

--****************Startup code should be inserted after this line*************************


--Call to my startup function here
--This assumes it has already been declared

Actions:
■ Open Ztools, Select File-Open
■ Create a project called Exercise6.ztools
■ Click on the Zedit from the ribbon
■ You will see code that demonstrates the following:
■ Print “Hello World” to the output console
■ Create a global variable to the file, name it myVar_0, make this on line 12
■ Assign it to a default value of 555
■ Add a local variable to the Start key function called myVar_0. Make this on line 18
■ Assign it to a default value of 123
■ Place a breakpoint on lines 12 and 18
■ Start the simulator, observe the variable myVar_0 in a watch window, then press play
again.
■ Press the Start key and use the step over tool.

160xxx-SUE01 Version 0.1


8
ZM Exercise Workbook

Exercise #7a – LUA function


File : Exercise7a.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Exercise7a

Description: Sample code to accompany the training of the ZM programmable products.


]]--

--Define the function

function addValues()
local a
local b
local c
a=4
b=6
c=a+b
print ("c="..c)
end

--call the function


addValues()

Actions:
■ create a function (addValues) to add the value of 2 local variables and store the sum in
another local variable
■ call the function

160xxx-SUE01 Version 0.1


9
ZM Exercise Workbook

Exercise #7b – LUA function with 1 parameter


File : Exercise7b.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Exercise7b

Description: Sample code to accompany the training of the ZM programmable products.


]]--

--Define the function with a parameter

function addValues(a)
local b
local c
b=6
c=a+b
print ("c="..c)
end

--call the function passing the value 4 as argument


addValues(4)

Actions:
■ modify the function to pass one of the variable to add as a parameter to the function
■ call the function passing a value as argument

160xxx-SUE01 Version 0.1


10
ZM Exercise Workbook

Exercise #7c – LUA function with 2 parameters


File : Exercise7c.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Exercise7c

Description: Sample code to accompany the training of the ZM programmable products.


]]--

--Define the function with 2 parameters


--function returns sum

function addValues(a,b)
local c
c=a+b
print ("c="..c)
end

--call the function passing the values 4 and 6 as argument


addValues(4,6)

Actions:
■ modify the function to pass both variables to add as a parameters to the function
■ call the function passing values to add as argument

160xxx-SUE01 Version 0.1


11
ZM Exercise Workbook

Exercise #7d – LUA function with a return value


File : Exercise7d.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Exercise7d

Description: Sample code to accompany the training of the ZM programmable products.


]]--

--Define the function with 2 parameters


--function returns sum

function addValues(a,b)
local c
c=a+b
print ("c="..c)
return c
end

--call the function passing the value 4 and 6 as arguments


sum = addValues(4,6)
print ("sum="..sum)

Actions:
■ modify the function to return the sum of both parameters
■ call the function passing values to add as argument
■ print the returned value

160xxx-SUE01 Version 0.1


12
ZM Exercise Workbook

Exercise #7e – LUA function with multiple return values


File : Exercise7e.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Exercise7e

Description: Sample code to accompany the training of the ZM programmable products.


]]--

--Define the function with two parameters


-- return the sum and mult
function addValues(a,b)
local c
local d
c=a+b
d=a*b
print ("c="..c)
print ("d="..d)
return c,d
end

--call the function passing the values 4 and 6 as arguments


sum,product = addValues(4,6)
print ("sum="..sum)
print ("product="..product)

Actions:
■ modify the function to return the sum and product of both parameters to the function
■ call the function passing values to add as argument
■ print returned values

160xxx-SUE01 Version 0.1


13
ZM Exercise Workbook

Exercise #8 – LUA Table


File : Exercise8.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Exercise8

Description: Sample code to accompany the training of the ZM programmable products.


]]--

--Generic function to assign values to a table


myTable = {} --Create a table

function setupTable()
myTable = {15, 20, 30, 40} --assign some values to the table
print(myTable[1]) --print the first element of the table
print(myTable[2]) --print the second element of the table
print(myTable[3]) --print the third element of the table
print(myTable[4]) --print the forth element of the table
end

--****************Startup code should be inserted after this line*************************


--Call to my startup function here
--This assumes it has already been declared
setupTable() --call the setupTable function on power up

Actions:
■ Create a project called Exercise8.ztools
■ Click on the Zedit from the ribbon
■ Create a comment stating that a function called setupTable is being created to allocate
memory
■ Create a global table called myTable
■ Create a new function called setupTable
■ Assign my table to 4 values, 15, 20, 25, and 30
■ Print to the output console each of these values individually.
■ Call the setupTable function, which will occur on power up.

160xxx-SUE01 Version 0.1


14
ZM Exercise Workbook

Exercise #9 – Control Structures


File : Exercise9.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Exercise9

Description: Sample code to accompany the training of the ZM programmable products.


]]--

--Generic function to assign values to a table


myTable = {} --Create a table

function setupTable()
local i = 1
myTable = {15, 20, 30, 40}
print("For loop")
for i=1,4,1 do -- loop upto 4 times, stepping/incrementing by 1
print(myTable[i]) --print myTable
end

print("While loop")
i=1 --reinitialize index variable
while i <= 4 do
print(myTable[i])
i = i + 1 --increment index variable, since a while loop doesn't do this automatically
end

print("While loop with if statement")


i=1 --reinitialize index variable
while i <= 4 do
if (i==1 or i==3) then
print(myTable[i])
else
print("wrong number ".. i) -- prints a word and a variable by concatenating a variable
to it before printing
end
i = i + 1 --increment index variable, since a while loop doesn't do this automatically
end
end
--****************Startup code should be inserted after this line*************************
--Call to my startup function here
--This assumes it has already been declared
setupTable() --call the setupTable function on power up

Actions:
■ Open Ztools, Select File-New
■ Create a project called Exercise9.ztools
■ Click on the Zedit from the ribbon
■ Modify the code to use a for loop instead of individual print statements
■ Then add code to use a while loop to do the same thing as the for loop
■ Then add code to only print the first and third numbers in the table using a while loop to
index through the whole table. You must use an if statement to accomplish this.

160xxx-SUE01 Version 0.1


15
ZM Exercise Workbook

Exercise #10 – More Control Structures


File : Exercise10.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Example10

Description: Sample code to accompany the training of the ZM programmable products.


]]--

--Generic function to assign values to a table


myTable = {}
function setupTable()
local i = 1
myTable = {15, 20, 30, 40}
end

--function that finds a number in a global table and returns it


function findNumber(num)
local i = 1
while i <=4 do
if myTable[i] == num then -- did we find our number?
return i, myTable[i] -- yes, return it
else
i = i + 1 -- no, continue on
end
end
end

--F1 key event for when the key is pressed down


function awtx.keypad.KEY_F1_DOWN()
local myValue1, myValue2 = findNumber(30) --call function,it will return index and number
print(myValue1 .." ".. myValue2) --print to output console
end

--****************Startup code should be inserted after this line*************************


--Call to my startup function here
--This assumes it has already been declared
setupTable() --call the setupTable function on power up

Actions:
■ Open Ztools, Select File-New
■ Create a project called Exercise10.ztools
■ Click on the Zedit from the ribbon
■ Create the Start key event
 function awtx.keypad.KEY_START_DOWN()
■ Create a local variable which is assigned by a function called findNumber
■ You will pass this function the number you wish to find inside of myTable from the
previous examples.
■ You will return 2 values from this function once the number is found.
■ Print these variables to the Output console

160xxx-SUE01 Version 0.1


16
ZM Exercise Workbook

Exercise #11 – Event Handler


File : Exercise11.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Example11

Description: Sample code to accompany the training of the ZM programmable products.


]]--

-- These are constant values defined by the AWTX API


local DISPLAY_MODE_SCALE = 0 --local constant for setting the display to the weighing mode
local DISPLAY_MODE_USER = 1 --local constant for setting the display to the user mode
local DISPLAY_TIME = 1000 -- local constant to this file

-- This is the function 'displayWord'.


--
-- It takes a single parameter 'name' and writes the value
-- to the display for a set amount of time.

local function displayWord(word)


local mode = awtx.display.setMode(DISPLAY_MODE_USER)
awtx.display.writeLine(word)
awtx.os.sleep(DISPLAY_TIME)
awtx.display.setMode(mode)
end

-- This is the event handler for the 'START' key.


--
-- It gets called by the firmware when the START key is
-- pushed down on the front panel.
--
function awtx.keypad.KEY_START_DOWN()
displayWord("START")
end

Actions:
■ Open Ztools, Select File-New
■ Create a project called Exercise11.ztools
■ Click on the Zedit from the ribbon
■ Create a function to write on the screen the text passed as parameter
 switch the display to user mode
 write text
 sleep
 switch display back to previous mode
■ Create the Start key event handler
■ function awtx.keypad.KEY_START_DOWN()
■ In event handler, call the function to display “START”

160xxx-SUE01 Version 0.1


17
ZM Exercise Workbook

Exercise #12 – Using Print Formats


File: Exercise12.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Example12

Description: Sample code to accompany the training of the ZM programmable products.


]]--

-- This is the ID value that we will prompt the user to change.


-- The print format we use will also reference this value when it
-- performs a print operation.
enteredID = 0

function onStart()
-- Initializes a print variable to print slot 1
-- 'enteredID' is the name of the global lua variable defined above that it references
-- 'Truck ID' is the variable name, which can be referenced as part of the print format
awtx.fmtPrint.varSet(1, 'enteredID', 'Truck ID', 13)
-- Registers a handler for the print complete event which tells us
-- if a print request was approved or not approved
awtx.weight.registerPrintCompleteEvent(onPrintComplete)
end

-- Handler function for the F1/ID key down event


-- Called when the F1/ID key is pressed down
function awtx.keypad.KEY_F1_DOWN()

local isEnterKey = false

enteredID, isEnterKey = awtx.keypad.enterInteger(enteredID, 0, 1000)

if (isEnterKey) then
print('The user entered ID = ' .. enteredID)
else
print('The user canceled the ID entry')
end
end
-- Handler function for the PRINT key down event
-- Called when the PRINT key is pressed down
--
function awtx.keypad.KEY_PRINT_DOWN()
-- Requests a print operation from firmware.
-- The request response will be handled in the onPrintComplete event handler below
awtx.weight.requestPrint()
end

160xxx-SUE01 Version 0.1


18
ZM Exercise Workbook

-- Handler function for a print request respsonse from firmware


-- This function will get called when a print request is made on the scale
-- and the request is either approved or denied
function onPrintComplete(result, errMsg)
if result == 0 then
awtx.printer.PrintFmt(5)
print('The print request was successful')
else
print('The print requeset failed with error: ' .. errMsg)
end
end

onStart()

Actions:

■ In ZTools
 Setup PrintFormat#5 to print the Name and the Value of ApplicationVariable#1.
 Setup a Print protocol to send PrintFormat#5 to Port 1.
■ In ZEdit
 Define a variable enteredID to hold the Truck ID entered by the user.
 Create an OnStart function to create an application variable named ‘Truck ID’
using the value of the variable enteredID and register a function called
onPrintComplete as handler for the PrintComplete event.
 In the KEY_F1_DOWN handler, prompt the user for an integer between 0 and
1000. Store the entered value in the variable enteredID
 In the PRINT_KEY_DOWN handler, create a print request
 Create the onPrintComplete function to print PrintFormat#5, if the print request
succeeds.
■ Start the Simulator
 Open the Port 1 window
 Press the F1 key
 Enter an ID
 Press the Print key.
 Data should show up in the Port1 window

160xxx-SUE01 Version 0.1


19
ZM Exercise Workbook

Exercise #13 – Control Structures


File : Exercise13.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Example13

Description: Sample code to accompany the training of the ZM programmable products.


]]--

require('ReqConstants')
require('ReqScaleKeys')
require('ReqVariables')
require('ReqDisplayMessages')

local MAX_RECORDS = 10

-- Default record entry


local blankRecord = { }
blankRecord.id = 0
blankRecord.ingName = ''
blankRecord.tare = 0
blankRecord.target = 0

local records = { }

--
-- Function: onStart
--
-- This function sets up our application when it first runs
--
local function onStart()

-- Create the persistent records


for i= 0, MAX_RECORDS do
records[i] = awtx.SavedVariable('Record_' .. i, blankRecord, true)
records[i].id = i
end

end

--

160xxx-SUE01 Version 0.1


20
ZM Exercise Workbook

160xxx-SUE01 Version 0.1


21
ZM Exercise Workbook

Actions:
■ Include Require files for writing to the display
■ Create a table with permanent storage for up to 10 records with 4 associated fields. ID,
Tare, Target, ingName
■ Create a function to enter/edit items in the list
■ Assign the function to the KEY_SETUP_DOWN event
■ Create a function to list items on the list in the output window when the key F1 is pressed

160xxx-SUE01 Version 0.1


22
ZM Exercise Workbook

Exercise #14 – Using Setpoints


File : Exercise14.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Example14

Description: Sample code to accompany the training of the ZM programmable products.


]]--

require('ReqConstants')
require('ReqScaleKeys')
require('ReqVariables')
require('ReqDisplayMessages')

sp1Target = 0

function onSp1Change(number, state)


if (state == false) then
awtx.display.displayDone()
end
end

function onStart()
-- Create an event listener for SP1
awtx.setPoint.registerOutputEvent(1, onSp1Change)
end

function awtx.keypad.KEY_START_DOWN()
local wt = awtx.weight.getCurrent(1)
local tempGross = wt.gross
sp1Target = tempGross + 100
awtx.setPoint.outputSet(1)
end

onStart()

Actions:
■ In ZTools, set Setpoint#1 activation mode to User Control and deactivation mode to a
variable sp1Target.
■ Create and register an event handler for the setpoint change event. The function should
display Done when the setpoint turns off.
■ When the start key is pressed, set the target weight for the setpoint target to the current
gross weight + 100 and turn Setpoint#1 on.
■ Start the Simulator
 Open the Setpoint Monitor window
 Press START key. This will set the new target weight and Setpoint#1 is activated
 Increase weight on the scale. When the target weight is reached, Setpoint#1 is
deactivated and a message is displayed on the display

160xxx-SUE01 Version 0.1


23
ZM Exercise Workbook

Exercise #15 – Using Serial Ports


File : Exercise15.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Example15

Description: Sample code to accompany the training of the ZM programmable products.


]]--

function onStart()
openPort(1)
end

function comMessage(portNum) -- handler called when the EOM character is received


local rxData, count = awtx.serial.getRx(portNum)
-- rxData contains received data(including the EOM character
-- count contains the byte count up to the EOM character
print(string.format("Received %d bytes on serial port %d.", count, portNum))
awtx.serial.send(portNum,string.format("You sent me :%s",rxData) )
end

function openPort(portNum)
local EOMchar = 13 -- Carriage return
local result = awtx.serial.open(portNum, 115200, 8, "none", 1, "none")
if result ~= 0 then
print(string.format("Error opening port %d Result = %d", portNum, result ))
return
end
awtx.serial.setEomChar(portNum, EOMchar)
result = awtx.serial.registerEomEvent(portNum, comMessage)
if (result == 0) then
print('Successfully registered EOM event handler on port ' .. portNum)
else
print('Failed to register EOM event handler on port '.. portNum .. ' error ' .. result)
end
end
function closePort(portNum)
local result
result = awtx.serial.unregisterEomEvent(portNum)
result = awtx.serial.close(portNum)
end

onStart()

Actions:
■ Create an event handler for serial port #1. Read received data and re-send on the same
serial port.
■ Create a function to open the serial port and set the OEM character to carriage return
and register the event handler.
■ In ZSim , enter characters in the Serial port 1 window.

160xxx-SUE01 Version 0.1


24
ZM Exercise Workbook

Exercise #16 – Using Serial Ports


File : Exercise16.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Example16

Description: Sample code to accompany the training of the ZM programmable products.


]]--

function writeGrossWeight()
local SCALE_1 = 1
--Get weight table for scale 1
local currWtTable = awtx.weight.getCurrent(SCALE_1)
local file = io.open("a:\\Gross.txt", "a") -- file opened in append mode
io.output(file)
file:write (string.format("Gross weight =%d %s\r\n", currWtTable.gross,
currWtTable.unitsStr))
file:close()
end

function awtx.keypad.KEY_START_DOWN()
awtx.display.setDisplayBusy()
writeGrossWeight()
awtx.os.sleep(2500)
awtx.display.clrDisplayBusy ()
end

Actions:
■ Display busy on the display
■ Write a function to write the gross weight to a text file
■ Assign the function to the KEY_START_DOWN event
■ Sleep 2500 ms
■ Return the display to weighing mode

160xxx-SUE01 Version 0.1


25
ZM Exercise Workbook

Exercise #17 – Using Graphic Controls


File : Exercise17.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Example17

Description: Sample code to accompany the training of the ZM programmable products.


]]--

local DISPLAY_MODE_SCALE = 0 --local constant for setting the display to the weighing mode
local DISPLAY_MODE_USER = 1 --local constant for setting the display to the user mode

function displayWord(word)
local curMode = awtx.display.setMode(DISPLAY_MODE_USER)
awtx.display.writeLine(word)
awtx.os.sleep(750)
awtx.display.setMode(DISPLAY_MODE_SCALE)
end

local scr1 = awtx.graphics.screens.new('scr1')


local lbl1 = awtx.graphics.label.new('lbl1')
lbl1:setLocation(0, 10)
lbl1:reSize(40, 5)
lbl1:setFont(3)
lbl1:setText('Dots..')
lbl1:setVisible(true)

-- The segment text label


local segLabel = awtx.display.getLabelControl()

-- Add labels to the screeen


scr1:addControl(lbl1)
scr1:addControl(segLabel)

-- Show
function awtx.keypad.KEY_START_DOWN()
awtx.display.setMode(DISPLAY_MODE_USER)
awtx.graphics.clearScreen()
scr1:show()
segLabel:setText('Hello')
end

function awtx.keypad.KEY_STOP_DOWN()
displayWord('DONE', 750)
awtx.display.setMode(DISPLAY_MODE_SCALE)
awtx.graphics.clearScreen()
end

160xxx-SUE01 Version 0.1


26
ZM Exercise Workbook

Actions:
■ Using the graphics library, create a new screen called ‘scr1’
■ Create a label control call ‘lbl1’
■ Set the Location, Size, Font, Visibility and Text for ‘lbl1’
■ Get a reference to the segment control
■ Add ‘lbl1’ and the segment control to ‘scr1’
■ When the START key is pressed
 Switch the display to ‘user’ mode
 Display ‘scr1’
 Set the Text for the segment label to ‘Hello’
■ When the key STOP is pressed
 Write “Done” to the display
 Return the display to the scale mode
 Clear the screen

160xxx-SUE01 Version 0.1


27
ZM Exercise Workbook

Exercise #18 – Using serialization


File : Exercise18.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Example18

Description: Sample code to accompany the training of the ZM programmable products.


]]--

local truck = { }
truck.ID = 456
truck.name = "Dan's Truck"
truck.tare = 200

--Encodes the table into a JSON string {"ID":456,"tare":200,"name":"Dan's Truck"}


local truckJson = json.encode(truck)

function onSerialData(portNum)
local rxData, count = awtx.serial.getRx(portNum)

--Decodes the JSON string into a table


local rxTable = json.decode(rxData)
print("Iterate using pairs function")
for k,v in pairs(rxTable) do
print (k,v)
end
print("Print table items")
print ("ID : ".. rxTable.ID)
print ("Name : " ..rxTable.name)
print ("tare : " .. rxTable.tare )

end

awtx.serial.open(1, 115200, 8, "none", 1, "none")


awtx.serial.setEomChar(1, 13)
awtx.serial.registerEomEvent(1, onSerialData)

--Send the encoded table


awtx.serial.send(1, truckJson)
awtx.serial.send(1, '\r')

Actions:
■ Create a table with id, tare and name
■ Encode the table using json
■ Setup serial port and define a handler to process incoming data
■ Encode the table using the json library
■ Transmitting the string on the serial port
■ In the event handler for the serial port, decode the incoming string and print the content
of the table using the pairs function and using the record structure.
■ From the Simulator Serial Port 1 window, copy data transmitted on the Output Data
window.
■ Paste it in the Text box, add the terminating character and press Send

160xxx-SUE01 Version 0.1


28
ZM Exercise Workbook

Exercise #19 – FTP –USB notification


File : Exercise19.zTools

--[[
Copyright (c) 2015 Avery Weigh-Tronix

Module: Example19

Description: Sample code to accompany the training of the ZM programmable products.


]]--

DISPLAY_MODE_SCALE_OBJECT = 0
DISPLAY_MODE_USER_SCRIPT = 1
DISPLAY_MODE_USER_MENU = 2

function onStart()
displayWORD("DEMO")
awtx.os.registerFtpFileAddedEvent (onFtpFileAdded)
awtx.os.registerUsbDriveMountEvent (onUSBMounted)
end

function onFtpFileAdded(filePath)
awtx.display.doBeep()
awtx.display.doBeep()
displayWORD ("NEW")
awtx.display.doBeep()
displayWORD("FILE")
end

function onUSBMounted(newDrive)
awtx.display.doBeep()
awtx.display.doBeep()
displayWORD ("NEW")
awtx.display.doBeep()
displayWORD("USB")
end
function displayWORD(word)
local mode = awtx.display.setMode(DISPLAY_MODE_USER_SCRIPT)
awtx.display.writeLine(word)
awtx.os.sleep(1750)
awtx.display.setMode(mode)
end

onStart()

Actions:
■ Create a function displaying a message on the ZM display to show a new file has been
added.
■ Register this function as the event handler for the FtpFileAddedEvent
■ Create a function displaying a message on the ZM display to show a new file has been
added.
■ Register this function as the event handler for the UsbDriveMountEvent
■ Download the ZTools file to the ZM405
■ Insert a US stick – ZM405 should show message
■ Using an FTP CLIENT, connect to the ZM FTP SERVER.
■ (the ZM405 IP address is 192.168.1.50 )
■ Send a file to the ZM405

160xxx-SUE01 Version 0.1


29
ZM Exercise Workbook

Values Returned by getCurrent


Value Description
Gross Gross Weight - Double value of the total amount weight of an object.
Net Net Weight - Double value of the weight of the object that is being weighed minus the
container it is located in.
Tare Tare Weight - Double value of the weight container when empty.
Units Units of Measure - Integer value of the units of measure that the object is being
measured in.
unitsStr Units of Measure String - String value that is name of the units of measure itself.
Count Count - Double value
Motion Motion - Boolean value
centerZero Center Zero - Boolean value
underRange Under Range/Under Flag - Boolean value
overRange Over Range/Over Flag - Boolean value
Min Minimum - Double value
Max Maximum - Double value
Roc Rate of Change - Double value
Gtot Gross Total - Double value of the total amount of gross weight.
Ntot Net Total - Double value of the total amount of net weight.
Gtotcal Gross Total Calculation - Double value of the calculated total of gross weight.
Ntotcal Net Total Calculation - Double value of the calculated total of net weight.
Ctot Count Total - Double value
Tran Transaction Count - Double value of the amount of objects passed onto the scale.
Pcwt Current Piece Weight - Double value of the weight of the object currently on the scale.
Adc Analog to Digital Converter Counts - Double value
inGrossBand In Gross Band. - Boolean value
Percent Percent - Double value
timestamp Time Stamp - Integer value
curUnitsFactor Current Units Conversion - Double value of the converted units of measure.
curCapacity Current Capacity - Double value
curDivision Current Division - Double value
curDigitsRight Current Digits Right - Integer value
curDigitsLeft Current Digits Left - Integer value
curDigitsTotal Current Digits Total - Integer value
consecNumber Transaction Count - Integer value
Inmotion Current In-motion Weight - Double value
Target Target - Double value of the desired weight of the objects.
holdEnabled Hold Enabled - Double value
holdCounts Hold Counts - Double value
gtotpluscur Gross Total plus Current - Double value
gtotminuscur Gross Total minus Current - Double value
ntotpluscur Net Total plus Current - Double value
ntotminuscur Net Total minus Current - Double value
ctotpluscur Count Total plus Current - Double value
ctotminuscur Count Total minus Current - Double value
Grossavg Average Gross Weight - Double value
Netavg Average Net Weight - Double value
countavg Average Weight Count - Double value
freefall1 Free Fall 1 - Double value
freefall2 Free Fall 2 - Double value
futuregross1 Future Gross 1 - Double value
futuregross2 Future Gross 2 - Double value
futurenet1 Future Net 1 - Double value
futurenet2 Future Net 2 - Double value
pcwtx1k Current Piece Weight * 1000.0 - Double value
Netmin Minimum Net Weight - Double value
Netmax Maximum Net Weight - Double value

160xxx-SUE01 Version 0.1


30
ZM Exercise Workbook

lastsample Last Sample Size - Double value

160xxx-SUE01 Version 0.1


31
ZM Exercise Workbook

Values returned by getConfig


Value Description
Site Contains scale site information (e.g. USA, GB, CAN, EU, CHINA, INDIA).
Capacity Double value containing configured capacity
division Double value indicating current scale divisions setting
updateFreq Integer value of the scale update frequency.
autoTareClear Boolean value indicating if tare clears automatically when the scale returns to the
gross-zero band.
presetTareFlag Boolean value indicating whether or not preset tare is enabled.
pbTareFlag Boolean value indicating whether or not pushbutton tare is enabled.
keyTareFlag Boolean value indicating whether or not keypad tare is enabled.
calwtunit Integer value inticating the configured calibration unit (1 = lb, 2 = kg).
calwtunitStr String identifier for current calibration unit ("lb" or "kg").
siteID String of configured site ID.
displaySeparator Integer value indicating the current decimal separator character (0 = '.', 1 = ',')
grossZeroBand Integer value indicating the number of divisions on either side of center zero to be
considered inside the gross-zero band.
Autoprintpercent Double value indicating at what percentage of capacity an auto-print should occur.
printRTZ Boolean value indicating if the weight must return to zero before another auto-print
can occur.
dateFormat Integer value indicating the current date format (0 = "MMDD2Y", 1 = "MMDD4Y", 2 =
"DDMM2Y", 3 = "DDMM4Y").
timeFormat Integer value indicating the current time format (0 = "12HR", 1 = "12HR-AP", 2 =
"24HR").

160xxx-SUE01 Version 0.1


32
ZM Exercise Workbook

ZM Print Tokens

160xxx-SUE01 Version 0.1


33
ZM Exercise Workbook

160xxx-SUE01 Version 0.1


34
ZM Exercise Workbook

160xxx-SUE01 Version 0.1


35
ZM Exercise Workbook

ASCII Table

160xxx-SUE01 Version 0.1


36
ZM Exercise Workbook

Escape Sequences
used in formatting strings and ZSim Serial port windows

Escape sequence Character


\a Alarm (Beep, Bell)
\b Backspace
\f Formfeed
\n Newline (Line Feed)
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\nnn The character whose numerical value is given by nnn interpreted
as an octal number
\xhh The character whose numerical value is given by hh interpreted as
a hexadecimal number

160xxx-SUE01 Version 0.1


37
ZM Exercise Workbook

Format Specifier – used in string formatting


%[flags][width][.precision][length]specifier

specifier Output Example


d or i Signed decimal integer 392
U Unsigned decimal integer 7235
O Unsigned octal 610
X Unsigned hexadecimal integer 7fa
F Decimal floating point 392.65
E Scientific notation (mantissa/exponent) 3.9265e+2
C Character a
S String of characters sample
A % followed by another % character will write a single % to the
% %
stream.

flags Description
Left-justify within the given field width; Right justification is the default
-
(see width sub-specifier).
Forces to preceed the result with a plus or minus sign ( + or -) even for positive
+
numbers. By default, only negative numbers are preceded with a - sign.
Left-pads the number with zeroes (0) instead of spaces when padding is specified
0
(see width sub-specifier).

width Description
Minimum number of characters to be printed. If the value to be printed is shorter
(number) than this number, the result is padded with blank spaces. The value is not
truncated even if the result is larger.
The width is not specified in the format string, but as an additional integer value
*
argument preceding the argument that has to be formatted.

.precision Description
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of
digits to be written. If the value to be written is shorter than this number, the result
is padded with leading zeros. The value is not truncated even if the result is longer.
A precision of 0 means that no character is written for the value 0.
For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the
.number decimal point (by default, this is 6).
For g and G specifiers: This is the maximum number of significant digits to be
printed.
For s: this is the maximum number of characters to be printed. By default all
characters are printed until the ending null character is encountered.
If the period is specified without an explicit value for precision, 0 is assumed.
The precision is not specified in the format string, but as an additional integer value
.*
argument preceding the argument that has to be formatted.

160xxx-SUE01 Version 0.1


38
ZM Exercise Workbook

LUA Operators

Type Description
Arithmetic + addition
Operate on numbers - Subtraction
• Multiplication
/ division
Relational == equal to
Results in true or false ~= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
Logical and
or
not
Concatenation ..

Comments -- or –[[ ]]--

160xxx-SUE01 Version 0.1


39
ZM Exercise Workbook

LUA Control Structures – Syntax

if .. then .. else …

if condition then
statements
else
statements
end

while loops

while condition do
statements
end

repeat .. until
repeat
statements
until condition

for loops
-- numeric
for var=fromexpr,toexpr,stepexpr do
statements
end

-- Generic
for vars in iterator do
statements
end

break and return


-- break out of a loop
break

-- exits a function, optionally returning one or more values


return returnValue1, returnValue2

160xxx-SUE01 Version 0.1


40
ZM Exercise Workbook

Resources

Links
Avery Weigh-Tronix Wiki ?
Lua site http://www.lua.org/
Lua Reference Manual 5.1 (on-line) http://www.lua.org/manual/5.1/
Lua Reference Manual 5.0 (PDF) www.lua.org/ftp/refman-5.0.pdf
Lua User’s site http://lua-users.org/wiki/LuaDirectory
contains several links
Lua Tutorial http://www.tutorialspoint.com/lua/

Books
Lua 5.1 Reference Manual ISBN 8590379833
by R. Ierusalimschy, L. H. de Figueiredo,
W. Celes, Lua.org
Programming in Lua Second Edition
by Roberto Ierusalimschy ISBN 8590379825
Beginning Lua Programming ISBN 0470069171
By Kurt Jung, Aaron Brown

Videos
■ Avery Weigh-Tronix on-demand training videos
■ Several training videos and tutorials on youtube.com

Revision History

Version Date By Description


0.1 Apr 17th,2015 MT Initial Draft

160xxx-SUE01 Version 0.1


41

Вам также может понравиться