CNC machine semaphore application, using expressions (Expr.txt) – Part 3

At this step of the process we pretty much defined everything needed for semaphore application and we can begin writing the program.

Diagram of program

First we will illustrate simple program diagram(flowchart). Diagram is very helpful, because it visually  illustrates the program flow(in this case state machine) which we can use as a reference when designing program structure.

Diagram for state machine of our semaphore application:

 

Each state is able to transition to other state, which was defined earlier in the process. All transitions are conditioned, meaning in order for transition to happen, condition needs to be fulfilled.

So we will now describe each states possible transitions as also transition conditions.

It can transition to:

Run state
State transition condition: Start program

Estop state
State transition condition: Estop activated

Corresponding IDLE state parameter:

We can evaluate Idle state by combining three parameters.  Idle state is basically inverted run state, in a sense that no program or any other task is being executed. For this  we can use run state parameter !_hw_run. In order that we are 100% sure that system is not executing any remaining commands from the buffer, we also check _hw_buffempty parameter. We also need to be sure that Estop mode is not active with !_hw_estop.

(_hw_buffempty && !_hw_run) && !_hw_estop

 

Flowcharts:

 

#OnInit:

Below is a flowchart for #OnInit. #OnInit is a built in expression function, which is executed when TNG software is launched/initialized. It only has one iteration.  It is perfect for initialisation code of our semaphore.

At the beginning we define state decimal values and conditions for Alarm, Estop and Idle states.  Only these three states because, when system is powered up, it can only take up states Estop(button pressed), Alarm(alarm before system shutdown was not reset) or Idle(all is OK). So, depending on the conditions met, OnInit will set the state which will be then recognized in the #Loop function.

Snippet of code for flowchart above is following:

#OnInit
state_estop = 0; 
state_idle  = 1; 
state_pause = 2; 
state_run   = 3;  
state_alarm = 4;
from_init = 0;


cleared_not = !_alarm_cleared;
if(cleared_not,exec(state=state_alarm,from_init=1,msg('INIT: Please Reset Error')));

estop = _hw_estop && _hw_idle; 
if(estop, state=state_estop);

idle  = (_hw_buffempty && !_hw_run) && !_hw_estop && _alarm_cleared; 
if(idle, state=state_idle);

 

#Loop:

#Loop function’s role is that is constantly checks and recognizes active state of the system.

If we, for the sake of this tutorial say, that this will be #Loop’s first execution and iteration, and since we just launched the TNG system, somebody pressed the Estop button before system shutdown (many CNC machines actually recommend to activate Estop button before system shutdown). So, #OnInit recognized and set as state Estop state.

#Loop then checks for active state and executes corresponding procedure. In our case, Estop state -> #StateEstop

Snippet of code for flowchart above is following:

#Loop 
;Every 83ms
if (state == state_estop, exec('#StateEStop'));
if (state == state_idle, exec('#StateIdle'));
if (state == state_run, exec('#StateRun'));
if (state == state_pause, exec('#StatePause'));
if (state == state_alarm, exec('#StateAlarm'));

 

#StateEstop flowchart is below:

At the beginning we have two safety instances. First one checks if state is indeed StateEstop, second one checks if last valid state was not StateEstop. This is important since we execute the #StateEstopInit procedure only at first and initial state change.

#StateEstopInit procedure is where we actually set the new last state and activate corresponding light on the semaphore.

With _state_last = state_estop command we set new last state. _extout1|5 = 1  will activate Red light on our ExtInOut board. All other lights are in this state at 0.

 

Further we check for any state transition conditions being met. This will be continuously evaluated until Estop button is not released. So if Estop button is released and error has been reset, Idle state conditions are met and we execute procedure #StateEstopEnd and set new state, state_idle. And then we return back to #Loop, where Idle state is recognized and #StateIdle is executed.

Which state transitions conditions need to be checked within each state, is defined in our state machine at the beginning of this tutorial. 

 

Snippet of code for flowchart above is following:

#StateEStop
if (state != state_estop, return(0));
if (_state_last != state_estop, exec('#StateEStopInit'));

;Here we check for state transition conditions

idle = (_hw_buffempty && !_hw_run) && !_hw_estop; 
if(idle, exec('#StateEStopEnd', state = state_idle, return()));

if((!_alarm_cleared && !_hw_estop), exec('#StateEStopEnd', state = state_alarm, return()));

#StateEStopInit
_state_last = state_estop;
print('EStop: ',estop);
_extout1|5 = 1;
_extout1|1 = 0;
_extout1|2 = 0;
_extout1|3 = 0;

#StateEStopEnd

 

#StateRun flowchart is below:

At the beginning we have two safety instances. First one checks if state is indeed StateRun, second one checks if last valid state was not StateRun. This is important since we execute the #StateRunInit procedure only at first and initial state change.

#StateRunInit procedure is where we actually set the new last state and activate corresponding light on the semaphore.

With _state_last = state_run command we set new last state. _extout1|5 = 2  will activate Green light on our ExtInOut board. All other lights are in this state at 0.

 

Further we check for any state transition conditions being met. These conditions will be continuously evaluated until either Estop, Pause, Stop buttons are pressed or CNC doors are open.

Let’s say CNC doors are suddenly opened during program run (this is checked using the ExtInOut board’s input 1, _extin1|1).  Alarm state condition is met and program will execute procedure #StateRunEnd and set new state, state_alarm. Program returns back to #Loop function, where Alarm state is recognized and #StateAlarm procedure is executed.

Which state transitions conditions need to be checked within each state, is defined in our state machine at the beginning of this tutorial. 

 

 

 

CNC machine semaphore application, using expressions (Expr.txt) – Part 2

What is a State Machine and how it is used?

If you google State machine, this would be the average result more or less:

“A state machine is a behaviour model. It consists of a finite number of states and is therefore also called finite-state machine (FSM). Based on the current state and a given input the machine performs state transitions and produces outputs.” 

Sounds exactly what we need for our application doesn’t it?  5 states, which can transition one from another based on the pre-defined conditions.

Each semaphore state has its outputs and inputs.  State outputs are semaphore light configurations where specific relay output will be activated. State inputs are conditions that will cause the state transitions.

Both will be described in detail in Part 3 of this tutorial.

 

What is an Expr.txt file and how it is used?

  • Expr.txt is a file which contains functions that are evaluated by PlanetCNC TNG expression evaluator.
  • it can be very practical for PLC type applications where periodical evaluation is necessary or for program events
  • Expr.txt file can contain and use vast array of expression functions, parameters and other commands supported by PlanetCNC TNG
  • Expr.txt file is located in the profile folder of TNG software
  • Profile folder can contain multiple Expr.txt files. Specific Expr file naming convention is available for better distinction. e.g.: Expr_Semaphore
  • If multiple expr files use same function, then function will be called first in first file and only then the with the next file
  • Local variables(e.g. name convention of local variables: red_light, global variables: _red_light ) have scope only within the parent Expr file.
  • Each Expr file contains functions that are marked with symbol #.
  • Each function begins with symbol # and ends with the next # symbol.
  • Each expr file can use built-in functions that are related with program events

 

Built-in Expr functions:

  • #OnInit -> When TNG software is started/initialized, code under this function will be executed.
  • #OnShutdown -> On PlanetCNC TNG software shutdown request, code under this function will be executed, then TNG will shutdown.
  • #OnStart -> On NC program Start event, code under this function will be executed. Če obstaja v katerokoli expr datoteki s tem imenom, bo opoklicana
  • #OnEnd -> On NC program End event, code under this function will be executed.
  • #OnStop -> On NC program Stop event, code under this function will be executed.
  • #OnEStop -> On Estop event, code under this function will be executed.
  • #OnJog -> On Jogging event, code under this function will be executed.
  • #OnWheel -> On handwheel event, code under this function will be executed.
  • #OnCmd -> On MDI command event, code under this function will be executed.
  • #Loop          -> this loop is executed every 83ms, or the value of refresh rate set in settings, under: File/Settings/User Interface/Refresh Rate
  • #Loop5       ->this loop is executed every 5s
  • #Loop15      ->this loop is executed every 15s
  • #Loop60     ->this loop is executed every 60s
  • #Loop300  ->this loop is executed every 300s

 

 

 

CNC machine semaphore application, using expressions (Expr.txt) – Part 1

For this multi-part tutorial we will create CNC machine semaphore(signal tower lamp).

We hope that this tutorial will serve as a good example on how to set application goals and requirements as also on how to define the tools and solutions  for achieving them, while using powerful tools and flexibility of PlanetCNC motion control system.

 

How to begin?

First we need to clarify and define application requirements.

Semaphore application requirements

We want:

  • to use a semaphore with 5 lights.
  • Each light with different colour will visually represent dedicated machine state.
  • Combination of two active lights is allowed. This applies when NC program is running and pause is initiated.
  • Additionally, alarm should be activated if, at the beginning or during the program execution, front door of machine enclosure is open(ed).
  • In case of alarm, system should prevent or stop program execution.
  • Play siren sound to notify CNC operator.
  • Alarm notification is displayed on the main screen
  • Alarm state needs to be reset. Hardware Reset button will be used.
  • If alarm is not reset and system is shut down, system will notify user to reset any pre-existing alarm at the system startup.

 

Machine states are:

  • Estop state
  • Idle state
  • Run state
  • Pause state
  • Alarm state

 

State description:

Estop

Estop state indicates that estop has been activated either using a PC keyboard key, controller estop pin (e-stop button) or Error pin indicating a motor driver fault.

This state will be indicated using active RED LIGHT on the semaphore.

 

Idle

Idle state indicates that machine is turned ON and connected with PC. Machine in Idle state does not perform any motion.

This state will be indicated using active YELLOW LIGHT on the semaphore.

 

Run

Run state indicates that CNC machine is executing the NC program.

This state will be indicated using active GREEN LIGHT on the semaphore.

 

Pause

Pause state indicates that machine is executing NC program, however program pause has been initiated, meaning program execution is on hold.

This state will be indicated using active ORANGE LIGHT in combination with active GREEN LIGHT(Run state) on the semaphore.

 

Alarm

Alarm state will indicate if CNC machine enclosure doors are open, at the start of program or during the program execution. So, if doors will be opened in any other state than Run, there is no need for an alarm.

This state will be indicated using a  BLUE LIGHT on the semaphore. In this state, we will also use siren sound alarm.

 

What hardware will we use?

So, we need to control 5 lights on the semaphore, and read one enclosure door switch. Meaning we need to occupy 5 digital outputs and 1 digital input of our MK3 controller.

But, digital input and output pins of controller are a precious commodity.  It would be better to use these pins for some other purpose.

More economic approach would be the use of ExtInOut board. This board expands the number of inputs and relay outputs used with controller by 8, respectively.

 

-ExtInOut board relays will control the semaphore lights, while one of the inputs will be used to evaluate CNC front door switch and Alarm reset button: ExtInOut board

-PlanetCNC Mk3 motion controller and EXT interface will be used for communication with external ExtInOut board: Mk3 controller

-Semaphore lights will be simulated with normal LED’s. If a real semaphore device would be used, integration would not be much different.

Programming the application

For a clearer and effective programming, we will use a concept called State Machine. Its functionality is suitable for the type of our application.

Drawing a flowchart will help us with visualization of such state machine and better overview of state definitions and state transition conditions.

Since we need constant and responsive background evaluation of various parameters and control of relay outputs, all our code will be included in the Expr.txt file.

 

 

In part 2 we will describe our state machine and Expr.txt file

Using PRINT command with PlanetCNC TNG software

PRINT command will display any text, variable or parameter value used in PlanetCNC TNG or gcode program.
It can be considered as a debug tool, trough which user can observe and diagnose execution of program.
As an output, PRINT command uses Output window/panel:

 

Example 1:

Click in the MDI window and type this text:
(PRINT,PRINT example nr.1)

 

This will display “PRINT example nr.1” in Output window/panel:

 

Example 2:

Now, lets say we want to print the value of parameter  _workoff_z .

Click in the MDI window and type this text:
(PRINT,#<_workoff_z>)

This will display  work offset Z value in Output window/panel:

 

Program debugging in PlanetCNC TNG software

Debugging tools in PlanetCNC TNG

For purposes of program observation or debugging, user can use PRINT and LOG commands, output window and state tabs for parameter value display. G-code ref manual will also come very handy.

Output window

To show/hide output panel in PlanetCNC TNG main window, click the middle square symbol in the upper right corner:

Output window will appear at the bottom middle section of the main window:

 

PRINT and LOG commands can be inserted within main gcode or script gcode at appropriate program lines. With output window, printed values can be then observed, while LOG command creates its own file that can save desired parameter values.

Example:

We want to observe values of the following parameters:

_current_tool
_tooloff
_tooloff_z
_workoff_z

These parameters can be displayed in Output window, Custom state tab or separate LOG file:

 

More on PRINT, LOG commands and how to create your own state tab can be found on links below:

PRINT: https://planet-cnc.com/using-print-command-with-planetcnc-tng-software/

LOG: https://planet-cnc.com/using-log-command-with-planetcnc-tng-software/

State tabs: https://planet-cnc.com/create-custom-tabs-planetcnc-tng-software/

 

 

Gcode in PlanetCNC TNG software

PlanetCNC TNG is a motion control software intended for control of CNC machines. As a standard, g-code is used as native programming language.

PlanetCNC TNG software processes gcode program and sends series of commands to motion controller. Controller interprets these commands and arranges coordinated machine motion.

 

Gcodes

G-code commands can be divided into multiple groups which differ from one another based on functionality and intended use.

Single G-code line, aka block, can include commands for modal state configuration, machine motion, program control and data manipulation, or peripheral control.
PlanetCNC TNG supports also gcode functions, expression functions, parameters, operators etc…

 

List of Gcode groups:
G-codes (G21,G17,G90, G00,G01…)
M-codes (M3,M5,M6…)
Other codes (F,S,T)
O-words (SUBROUTINE, CONDITION…)
Comments (LOGCREATE,LOG…)
Operators (+,-,EQ,GT,AND…)
G-code functions (Exists, Sin, Cos, Inc, Dec…)
Expression functions (infoIsInitialized, infoMachinePosition…)

 

Complete list of gcode commands and system parameters is available in PlanetCNC TNG G-code reference manual. This document is located in Doc folder of PlanetCNC TNG main installation folder. 

 

Simple g-code programs (i.e. toolpaths) can be easily written manually. For this purpose we recommend that users gets at least familiar with g-code. Get to know groups of g-code commands, syntax, format and programming guidelines. Even if user does not have an intention of manually writing his g-code programs, it can be in great help when debugging and understanding program and machine behaviour.

 

We really encourage our users that they explore PlanetCNC TNG scripts, they are a really great source for discovering different types of gcode programming and programming approaches. Single script code can offer a lot of new knowledge for a curious CNC beginner as also for a well rounded programmer.

More about accessing and configuration of scripts can be read here:
Accessing script files in PlanetCNC TNG

Using o-words with PlanetCNC TNG software: Loop blocks

You can use loop o-words with PlanetCNC TNG.

Sometimes you need to execute line(s) of g-code in a loop while evaluating specific condition.  When condition evaluates to false, program will exit loop. This comes useful for e.g. repetitive motion sequences, parameter manipulation etc…

O-word loop commands consist of:
O-do – Begin loop block
O-while – End loop block [or condition evaluation]
O-endwhile – End loop block
O-break – Exit loop block immediately
O-continue – Skip to next condition evaluation of  the while condition

You can use two types of loops: While – Endwhile or Do – While.

While – Endwhile:
Evaluates condition on the beginning of loop and then executes the lines of code inside the loop.

Do – While:
First executes the lines of code inside the loop and then evaluates condition at the end of loop.

Example of Do – While loop:

%
 #1 = 1
 o100 do
 (print, #1)
 #1 = [#1+1]
 o100 while[#1 LE 10]
 (print,loop finished)
 %

The content of the loop will repeat for as long as while condition at the end will remain true. Which means that as soon as parameter #1 exceeds value of 10, program will exit the loop and print

loop finished

 

Example of While – Endwhile loop:

%
#1 = 1
o100 while [#1 LE 10]
 (print, #1)
 #1 = [#1+1]
o100 endwhile
 (print,loop finished)
%

The content of the loop will repeat for as long as while condition at the beginning will remain true. Which means that as soon as parameter #1 exceeds value of 10, program will exit the loop and print

loop finished

Example of break used in a Do – While loop:

%
#<A> = [2**0]
#<B> = 0
#1 = 0
o100 do
 (print, #1)
 #1 = [#1+1]
 G04 P1
 o200 if [AND[#<A>, #<_hw_input>]]
  #<B> = 1
  o100 break
 o200 endif
o100 while[#1 LE 10]

o300 if [#<B> EQ 0]
 (print,loop finished)
 o300 else 
 (print,preemptive loop break)
o300 endif
%

The content of the loop will repeat for as long as input 1 of controller is not active and while condition at the end remains true. Which means that as long as input 1 remains un-active, counter will count to 10 and program will exit the loop normally and print:

loop finished

As soon as input becomes active during counting, program will exit loop and print:

preemptive loop break

Using o-words with PlanetCNC TNG software: Conditional statements

You can use o-word conditional statements with PlanetCNC TNG.

O-word conditional statement consist of  if, elseif, else and endif keywords.

All keywords of the same conditional statement should use same o-word number.

Example of if…endif conditional statement:

%
#1=10
o100 if [#1 EQ 10]
 (PRINT,Condition is true)
o100 endif
%

Parameter #1 is assigned value 10. o100 if statement checks if parameter #1 equals (EQ) value 10. Because condition is true, program executes print command that is included in this conditional statement. o100 if statement is ended with o100 endif.

This code will display in Log:

Example of if, else…endif conditional statement:

%
#1=10
o100 if [#1 EQ 9]
(PRINT,10 equals 9)
o100 else
(PRINT,10 does not equal 9)
o100 endif
%

Paramter #1 is assigned value 1o. o100 if statement checks if parameter #1 equals (EQ) value 9. Because condition is not true, program jumps to o100 else statement and executes print command unconditionally.

This code will display in Log:

 

Example of if, elseif…endif conditional statement:

%
 #1=10
 o100 if [#1 GT 20]
 (PRINT,10 is greater than 20)
 o100 elseif [#1 LT 20]
 (PRINT,10 is less than 20)
 o100 endif
 %

Paramter #1 is assigned value 1o. o100 if statement checks if parameter #1 is greater  than (GT) value 20. Because condition is not true program jumps to o100 elseif statement where its checked if parameter #1 is less then (LT) value 20. Because condition is true, program executes print command that is included in o100 elseif conditional statement. Also note how if, elseif and endif keywords use same o-word number.

This code will display in Log:

Using o-words with PlanetCNC TNG software: Subroutines

Some CNC jobs demand repetition of the same motion over and over again, e.g.: drilling of a 100 holes. If we want to re-use the existing g-code pattern throughout the main program,  we can use subroutines.

Subroutine is basically a program block which is executed the moment it gets called from main program.

Subroutine program can be located within the same g-code program from where it gets called, or it can be standalone program file.

Subroutine o-word commands:
o-sub – Begin subroutine
o-endsub – End subroutine
o-call – Call subroutine
o-return – Exit subroutine

 

o-call:
Subroutine is called using o-call command.

o-sub and o-endsub:
Subroutine program block is defined with o-sub and o-endsub brackets. Everything within these brackets will be executed when related subroutine is called.

When o-endsub is encountered, program jumps back to the line where subroutine was called and continues with execution or remaining main program.

o-return :
User can achieve the same effect as o-endsub also with the use of o-return command.

 

Example of subroutine call:
Program below will call three subroutines from main program.
First and second subroutine will print to log window while third one will print nothing since o-return command will be used.

To observe the subroutine behavior open log window: Help/Show Log

 

%
(Main program)
(PRINT,Start main program)

(PRINT,Calling subroutine 1)
o100 call
(PRINT,End of subroutine 1, return to main program)

(PRINT,Calling subroutine 2)
o101 call
(PRINT,End of subroutine 2, return to main program)

(PRINT,Calling subroutine 3)
o102 call
(PRINT,Preemptive end of subroutine 3,o-return command was used)

o100 sub
(PRINT,Subroutine 1)
o100 endsub

o101 sub
(PRINT,Subroutine 2)
o101 endsub

o102 sub
o102 return
(PRINT,This should never be printed)
o102 endsub
%

Log window will display this:

User can also call external subroutine program files.
In such case, syntax is slightly different than when calling subroutines that are located withing the same g-code program.

Subroutine program file location is defined in settings: File/Settings/Program Options-> G-code folders. Insert pathway to files location:

 

Subroutine program file should have an filename.sub file extension.

Subroutine program file code is defined with o<filename> sub and o<filename> endsub brackets.
When o-endsub is encountered, program jumps back to the line where subroutine was called and continues with program execution. User can achieve the same effect with the use of o-Return command.

Subroutine program file is called using o<filename>call command.

 

Example of subroutine file call:

Create file: Sub_example.sub

Open it with text editor and write:

o<Sub_example> sub
(PRINT,Subroutine file program)
o<Sub_example> endsub

Main program will call subroutine file:

%
(PRINT, call subroutine file)
o<Sub_example> call
(PRINT,This should be printed last)
%

Program above will call external subroutine file from main program.
To observe subroutine file behavior open log terminal: Help/Show Log

Log window will display this:

Using LOG command with PlanetCNC TNG software

If you want to save your variable and parameter values or any other log data in a form of a file, you can use LOG command.

LOG: Writes to LOG file
LOGCREATE: Creates new LOG file.
LOGOPEN: Adds content to previously created LOG file
LOGCLOSE: Closes LOG file

 

Example 1: G-code program will create LOG file where desired data will be saved.

%
(LOGCREATE,DataLOG.txt)  
(LOG,This text is saved in "DataLOG.txt" file)
(LOGCLOSE)
%

 

Example 2: G-code program will create two separate LOG files where data will be saved.

%
(LOGCREATE,DataLOG 1.txt)
(LOG,This text is saved in "DataLOG 1.txt" file)
(LOGCLOSE)

(LOGCREATE,DataLOG 2.txt)
(LOG,This text is saved in "DataLOG 2.txt" file)
(LOGCLOSE)

(LOGOPEN,DataLOG 1.txt)
(LOG,This text is also saved in "DataLOG 1.txt" file)
(LOGCLOSE)

(LOGOPEN,DataLOG 2.txt)
(LOG,This text is also saved in "DataLOG 2.txt" file)
(LOGCLOSE)
%

Example 3: G-code program will create LOG file where value of machine work position will be saved. This is a great way to “track” and store values of desired parameter.

%
G00 X0
(LOGCREATE,Work PositionLOG.txt) 
(LOG,Work position start:#<_x>)
(LOGCLOSE) 
G00 X100
(LOGOPEN,Work PositionLOG.txt) 
(LOG,Work position end:#<_x>)
(LOGCLOSE)
%

 

Created LOG files are located in main installation folder of PlanetCNC TNG. User can also explicitly tell where created LOG file will be located.

 

 

 

Using o-words with PlanetCNC TNG software

With PlanetCNC TNG it is possible to control g-code program flow. For this purpose you can use o-word g-codes.

o-words are formed as blocks and can be, based on their functionality, categorized into 4 groups:

SUBROUTINE
(subroutine block)

CONDITION
(if..endif,elseif,else…block)

LOOP
(do…while, ehile..endwhile loop block)

REPEAT
(repeat…endrepeat block)

 

During this multipart tutorial series we will try to explain the use and behaviour of each particular O-word group.

To understand the working principles and behaviour of a different o-word block we would recommend that user first gets
familliar with the PRINT command.

 

Using the G04 g-code with PlanetCNC TNG software

In machining it is sometimes necessary to stop the motion of all axes for a given amount of time (for example to let the spindle come up to speed or wait for the coolant to start flowing). This is called dwell. It’s activated with the G04 command. The time is specified using a P-word and a number seconds (the number is a float so fractions of a second can be used).
For example: G04 P3.7

A common place to use the G04 dwell command is when starting a spindle of a machine. Because it can’t accelerate instantly to the desired speed we need to allow it some time to speed up before starting to cut the material. An example of code that waits 5 seconds after starting the spindle at 10000 RPM is here:
M03 S10000
G04 P5