G-Code

Revised:  9/18/2012         Subject to Revisions

Subject Matter Description

This section will include various topics about G-Code programming of the Sherline CNC Lathe and Milling machines.  G-Code is a very broadly used industry standard programming language used for a large portion of CNC machines.  Not all features of the language are usable for the Sherline tools, generally those dealing with spindle speed, tool synchronization with spindle, tool changing and other similar options are not used as the Sherline tools have fewer features tied back to the CNC computer.

The Sherline lathe has two stepper motor driven axis and manual spindle speed control.  The two axis are the cross-slide (X axis) and lead screw (Y axis). 

The milling machine has four stepper motor driven axis, X, Y, Z and A and manual spindle speed control.  X in the horizontal side to side axis.  Y is the horizontal in and out axis.  Z is the vertical up and down axis.  A is the rotary table which may be mounted on top of the X axis.

G-Code is capable of driving many more axis plus the spindle speed controls and other features of high end CNC machines.  G-Code has many features and capabilities common to other computer programming languages such as math, variables, sub-routines, etc.  In general it is sort of like programming languages such as Basic, Fortran and others.  It has been simplified somewhat relative to those languages but can perform many functions since it drives a full scale computer. 

The author is an engineer and has had significant use of computer languages to run machines and perform engineering tasks.  Languages used include Assembly for IBM, HP  mini-computers, Intel and other micro-processors running company produced items and factory machines, Basic, Fortran, Microsoft Visual Basic and Visual C-Plus, Microsoft Office Visual Basic macro language.  Having this background made the transition to G-Code relatively quick and painless.  It is still necessary to learn what works best on the lathe and mill however. 

This section will in general not be a tutorial on the language, but instead will focus on how the author learned how to best implement G-Code with the Sherline lathe and milling machines.  As this was written the author had already started learning using the Sherline tutorial and first couple of lathe projects, the tender truck axle and wheels.  During these projects various strengths and limitations of G-Code and the machines were observed.  Also, the author does not have extensive first hand experience with a lathe and virtually none with a milling machine, so how they respond best will be a learning experience.

Lathe Axis Definition

The lathe has two moving assemblies, the crosslide and lead screw.  The cutting tool is mounted on the crosslide and the crosslide moves towards or away from the work on the leadscrew.  The crosslide movement is X axis and leadscrew is Y axis.  Movement of the crosslide away from the operator is positive X and movement of the leadscrew away from the work is positive Y.  The axis positive directions are shown in the photo.

Sherline Lathe Axis Direction Definitions for G-Code
The lathe spindle speed is manually controlled using the pot and switch on the control box shown at top left in the photo next.  As the spindle turns the work piece the cutting tool is moved across the work up and down in the photo by the crosslide drive stepper.  Similarly the leadscrew drive stepper moves the crosslide and therefore the tool towards or away from the work piece.  Both steppers may move simultaneously or one at a time depending on g-code programming.  Also, when the stepper drive is turned off manual handwheels may be used to move the tool.  The operator can position the tool and make cuts if desired or position the tool tip to a particular place prior to starting the g-code program.

Closer View of Lathe Working Area Near Spindle
 
One particular problem to resolve is alignment of the tool cutting tip relative to the lathe spindle axis and and work piece face.   Visual alignment is feasible, but very difficult even with optical magnification.  The author has tried that method and found it hard to repeat the settings.  Another method tried by the author is to determine when the tool tip makes electrical contact using a multimeter set for ohms continuity.  In that mode the multimeter beeps when contact is made.  Using manually controlled stepping of the CNC controller tool tip contact can be repeated within a couple of tenths of a thousandth of an inch of stepper motion.  Fortunately the tool holder on the crosslide does not have continuity with the work on the spindle.  This method will work only for metals however.  Plastics such as Delrin, Teflon, ABS and others will have to aligned visually.   The set up for metal work pieces is shown in the photo below.  The black clip at the top left and red clip at bottom right connect to the multimeter.

Determining Surface Touch Between Tool and Work With Multimeter

The work piece can be removed along with the  three jaw chuck shown in the above photo and replace with a dead center tool.  That tool comes to a point at the center of rotation of the lathe spindle and can be used with the multimeter method to locate the exact center of rotation.  It also can be used to set the leadscrew position relative to the spindle if desired.  Setting the tool tip relative to the dead center does not provide any alignment information relative to the face of the work piece however.  The dead center works good to determine the center of work since it spins on the lathe axis.  The crosslide X axis zero point set on the dead center point can therefore transfer exactly to the center of rotation of the workpiece providing a good X axis reference.  The face of the work piece is a better point of reference for the leadscrew Y axis.

Set Up to Map Tool Tip To Dead Center Tip
 
To locate the exact center of rotation of the lathe a dead center tool is inserted into the spindle taper.  The dead center rotates with it's point exactly at the center of spindle rotation.  To determine when contact is made between the tool tip and dead center a multimeter is set to the ohmmeter beep position so the operator can watch the manual controls on the CNC computer screen while stepping.

Close Up View Of Tool Tip Next To Dead Center Tip

The photo above shows the cutting tool tip just touching the dead center tip.  The dead center is the cone emerging from the spindle center.  It is inserted into a precision taper at the center of the spindle shaft.  The tool tip is precision ground to a near point as is the dead center.  The problem presented to the author is the need to locate the exact point where the cutting edge at the left side of the tip just reaches the cone tip while stepping from the right side of the photo towards the left.

The manual controls of the system and stepper motors move in small increments of 0.0001 inch (one-tenth of one-thousandth of an inch or 25.4 micro-meters or microns).The author tried a number of methods and settled on the one shown in the diagram below.

Diagram Showing Sequence of Steps To Locate Tip Extremes
 
The cross-slide is moved about 30 mils (30 thousandths of an inch) to the right side of the tip shown in the photo previously.  Then the Y leadscrew axis is moved eleven mils towards the the spindle.  It doesn't touch since the point of the tool is offset right.  The leadscrew is then moved back ten mils to establish motion in the positive direction while taking up about 3 mils of backlash.  The X crosslide axis is then moved back towards the lathe center in the left direction 24 mils again taking up about 3 mils of backlash.  At this point the mapping is about to begin.  The operator steps above must be done every time to condition the backlash of the lathe.
 
Next the spindle motor is set for a slow approximately one revolution per second rate.  The crosslide axis is then stepped slowly at about one step over one to two seconds while monitoring the multimeter beeper for what sounds like a scratching sound.  The sound occurs when the tool tip side nearest the dead center cone side is just brushing one another making light intermittent contact as the cone rotates.
 
Once contact is detected the leadscrew is moved away from the cone by one tenth mil or until the scratching stops.  It usually stops on one step.  The X axis is again stepped slowly towards the lathe center until contact is made again.  Once again the leadscrew is stepped away from the cone until the scratching stops.  This sequence of steps is repeated as shown in the diagram above until a extensive series of crosslide steps results on no further contact as shown on the diagram.  The last X and Y values are recorded as the tip to tip contact point.
 
A series of ten sequences were made to evaluate the shape of the curve and repeatability of the procedure.  The chart below shows that the pattern is slightly curved.  Note that for each tenth of a mil in leadscrew motion at the left of the chart about two to three tenths of a mil of crosslide motion occurs.  The taper on the cone indicates that it should be reversed.  The reason for the disparity is that we are mapping two small circle shapes passing along one another.  Towards the tip the a little over a mil of crosslide motion occurs for the very last step before no further contact occurs. 
 
The blue line is the pattern of the contact points while the red line indicates the standard deviation of the various readings.  The standard deviation is a very typical measure of the disparity of readings and a predictor of the potential repeatability of the process.  The best repeatability is towards the center of the measurement range in leadscrew direction.  The worst repeatability is at the very end.  A rule of thumb for engineering is that the expected repeatability will lie within a range of 3.3 times the standard deviation.  The best case is about +/-0.33 mils while the worst case for tip position is +/- about +/-2.97 mils.  Although the tip can be located this way, it is not very repeatable. 
 
Chart Showing Mapping Results of Ten Sequences
 
You are probably wondering what this effort has to do with G-Code.  G-Code implemented on the Sherline CNC lathe requires that a reference position be established physically and that location given a reference value.  The g-code program is then written around that point of reference so that the physical motion of the lathe moves in a known way relative to the work piece.  The Sherline CNC lathe does not have an independent absolute reference.  The very first step in g-code written for Sherline CNC lathe is to move from a known starting value to a home position.  This can be done either as an absolute value or a relative value.
 
When the author begins showing g-code snippets one of the first portions of a program will accomplish this movement.  The operator therefore MUST physically position the crosslide and leadscrew and enter the defined values for those locations into the program in some manner.   It is convenient to use the work piece face opposite the spindle for the leadscrew reference point.  The crosslide reference point can be the lathe center as was evaluated in this section or perhaps a point on the the lathe such as a known diameter surface or a known portion of the work piece.  
 
The starting position of the program should not be near the work piece, so the operator would then determine another safe location away from the work piece and use the CNC manual stepper controls to position the crosslide and leadscrew accordingly.  He can then re-set the values to desired ones by turning off the stepper motor drive and operating the manual controls to step the program values to ones that match the program.
 
So much for establishing the reference points.  The lathe and likewise the mill do not have a fixed reference value for the steppers.  The reference points can be set anywhere within the range of motion of the moving parts of the machines.  Of course those points must bear a known relationship to the work piece otherwise things will go awry.
 

Designing A Contouring G-Code Program

Setting Up The Alibre CAD Framework

After a part has been designed the cross sections to be machined are identified.  When using a lathe to fashion a part the Alibre design file uses one or more templates that are rotated to carve the part to shape.  Those templates are used to develop the g-code program.  The author has learned that a good method during design is to define a series of 10 mil layers that intersect the final outline to determine the locations where cuts will start and end and their depth if other than the 10 mil value.  Often a sequence of 10 mil cuts does not intersect critical features leaving a smaller cut depth for a portion of the part.
 
 Tender Truck Wheel Cross Section
 
The tender truck wheel will be used to illustrate the process used to develop g-code for a contoured part.  The wheel is machined in a number of steps.  The outside of the wheel at the left has an inner contour which will be used.  The other contours are the wheel rim and flange region and the inner portion of the inside of the wheel.  The center bore to mate with the axle is made with a boring tool.
 
Section of Axle Bored Work Piece With Outside Contour Template
 
The first steps prior to contouring are to turn the work piece to the diameter of the tip of the flange and bore the axle hole.  After that the outside of the wheel inner contour is done.  This will be followed in the blog to show principles of the g-code program developments.  The final shape of the contour is shown in the above graphic in red overlayed on the green cross section representing the work piece at this stage of machining.  The many black notes are critical dimensions that cannot be readily seen at this scale.  Think of the contour as a cutting tool that shapes the wheel stock as it turns on the lathe.
 
View of Design CAD Sketch Showing Construction Lines
 
By turning off the green cross section and somewhat enlarging the CAD view more of the construction lines can be seen along with dimension information.  A curved contour is built in a number of layers, each at 10 mils of cutting depth.  Construction lines on the drawing above show that quite a few 10 mil layers are needed to follow the curving contour of the section on the outer portion of the wheel.  The final shape is shown in red while the many vertical dotted lines are the individual 10 mil thick cut lines. 
 
The design of the construction lines is arranged so that a final 5 mil thick portion will be left all along the final pattern for the last cut.  That last cut will be one continuous cut from center up to rim with the tool positioned along the red outline without stop.  Otherwise each 10 mil layer is cut along it's respective construction line to within 5 mils of the red curve line.  Each layer is cut from a point nearest the center of rotation to beyond the rim. 
 
Enlarged View of a Portion of The CAD Drawing
 
The above view of an enlarged CAD drawing section shows the dotted construction lines representing the cut lines and a series of termination points near the red final outline.  Along the left are accurate X crosslide tool tip dimensions from a reference point.  These dimensions will generally be directly used in the g-code program.   In this CAD configuration the dimensions along the left are X dimensions from the center of lathe spindle rotation.  At other portions of the drawing Y leadscrew dimensions from the face of the work piece are shown.  These two points are defined as X=0.0 and Y=0.0. 

Home Position

The lathe will not be started at X=0 and Y=0 however as this would make it difficult to set spindle speed and avoid inadvertent cuts on the work piece.  Another position will be defined as home position, perhaps several inches away from the work piece along the leadscrew Y axis.  The X crosslide home could be defined as X=0 once the cutting tool is positioned well away from the work piece.  The particular position chosen is arbitrary.  The author sets Y about 3 to 4 inches away to allow changing or adjusting the work piece.  Since the center and face of the work piece were calibrated as X=0 and Y=0 respectively, those values are retained to agree with the CAD design dimensions in the diagrams above.  That minimizes the opportunity for dimension adjustment errors.
 
Since moving the Y leadscrew axis is positive away from the work piece, in this example home will be defined as X=0 and Y=3.  The default unit of measure for the author's Sherline CNC lathe is the inch.  Interestingly the home command in g-code is very similar to the definition.  It is:
 
x0 y3
 
In g-code placing the numerical value immediately following the axis letter is all that is required to cause the lathe to move to that location.  A word of explanation here, the author customarily uses absolute positioning in programs.  Alternatively g-code can also use relative positioning.  In such a case one has to know the previous position before a position command to get the tool to the correct location.  There are instances where relative positioning is desirable and will be used.  In g-code one can issue a simple command to switch between the modes.  The assure that the machine starts in a known programming configuration a preamble line of code elements is placed at the front of the code.  The author uses:
 
g01 g20 g40 g80 g49 g90 f2
 
Each of the numbers preceded by a letter g are mode commands.  The preamble is selected to ensure that the operating mode of the program is in a known configuration.  The prevalence of these mode commands with the g in front is likely why the program language is called g-code.  The modes above are:
 
g01:     Linear Interpolation
            Positioning commands between points where more than one axis occurs are linearly interpolated in proportional values related to the distance between the points so that a motion is a straight line between the points.  This can involve one to many axis.  On the Sherline lathe it will be two axis while on the mill it can be three or four axis (the fourth axis is the optional angle table).

g20:     Inch System Selection
          The author's lathe is physically set up for inch related measurements on the handwheels.  The CNC computer however can be set to tread the stepper motions as inch or metric. 

g40:     Cancel Cutter Diameter Compensation
           For either the lathe or milling machine cutter tool diameter can be defined on a table and automatic tool diameter compensation applied so that the tool path center line is adjusted away from the target path by half the tool tip diameter.  In the case of the lathe the author has elected to not use compensation as the tool tip is very small, nearly a point.  On the milling machine or when using larger tools on the lathe the compensation would prove to be helpful.

g80:     Cancel Motion Mode (Includes Canned Cycles)
          In case a prior program invoked a canned cycle such as drilling or boring it is good to make sure that any residual cycles are canceled.

g49:     Cancel Tool Length Offset
          Particularly on the milling machine tool length offset can be set on a tool table.  This could also be used on the lathe.  The author elected to cancel any of this mode that might be a residual from a prior run.

g90:     Absolute Distance Mode
          This is the command that sets up the program to use absolute positioning. 

f2:     Feed Rate
          Correct use of the g01 mode requires that a feed rate be set.  The numerical value defaults to units per minute, inches in this case because of the g20 mode.  The feed rate may be changed throughout the program as needed.

Notice that many modes can be contained on a single line of code along with other commands such as feed rate and positions as well.  The codes can all be on separate lines if it makes the program more understandable.  Some modes are mutually exclusive and may not exist on the same line.  In such a case the last of those that are exclusive will be used for the next series of commands until another change is made.
 
Finally the author will use the above two lines to drive the lathe at the start of the program, the preamble first then the home position command.  Near the beginning of the program those two lines will appear, they could be combined but the author keeps them separate to assist in reminding him of the need to get them right.  Don't want the lathe running amok.   
 

Anatomy of a G-Code Program

G-Code must begin and end with a % sign.  Between the beginning and ending sign any of the various commands can be stated.  Line numbers are optional.  Sherline recommends ommitting line numbers as they confuse you when you read the program.  Another recommendation is that the last statement just before the final % sign be the command m0.  Thus a program looks like this:
 
                      %
                      g01 g20 g40 g80 g49 g90 f2 
                      .
                      .
                      .
                      .
                      .
                     m0
                    %
 
Another common occurence in a g-code program is the inclusion of comments.  Comments are very important in a computer program as they provide a way to explain lines and sections of code.  In g-code comments can occur anywhere including ahead or behind the % signs, on separate lines and before or after code sections.   Comments are any kind of text between a pair of parenthesis.  The author places a comment just ahead of the first % sign giving the file name and a brief description.  For example:
 
                    (Tender Truck Wheel External Inside Contour)
                    %




                    g01 g20 g40 g80 g49 g90 f2
                    .

                    .
                    .
                    .
                   .
                   m0
                  %
 
Another g-code feature used extensively by the author are named parameters.  Global named parameters are the most common invoked.  Such parameters consist of an initial #<_ set of symbols and a closing > sign.  Between the opening and closing symbols the programmer can enter one or more sets of text names linked together with the _ symbol.  In most of the author's programs named parameters are used to define the home position in absolute values.  The values are inches.  For example:
 
                    #<_home_x = 0.0
                    #<_home_y = 3.0000          (start and return to 3" away from work piece)
 
Each parameter is set equal to a particular value as shown above.  Note that the author added a descriptive comment for the #<_home_y parameter.  Parameters can also contain math expressions that compute the parameter value from numbers and previously stated parameters.  An expression consists on a series of parameters and numbers linked by +, -, * and / symbols that define addition, subtraction, multiplication and division respectivelly.  The entire expression is contained inside a set of squre brackets, [ and ].  One relationship that occurs to the author is to define the face of the work piece using an expression in relationship to the home position.  That way the author can cut several parts from the stock rod and the new value for the face of each piece entered into the program.  By doing so the new value will appear in only one location.  For example:
 
                    #<_Work_Piece_Face> = [#<_home_y - 3.000]
 
The author orders a program with all or most parameters right after the opening preamble code line.  Generally each parameter should be either self defining or commented so a future effort to delve into the program or modify it will not require an extensive reverse engineering effort to determine how the program works.
 
In addition to parameters defining home and work piece values they are also used to define where each cut begins and ends.  That way cut points can be readily located and revised if the design should change.  The author makes contours as a series of 10 mil deep cuts.  In this instance the cutting tool will be oriented as a sharp point with the tool tip forming an arrow point aimed directly at the work piece face and the axis parallel to the lathe axis. 
 
The arrow point sides are angled back at about 33 degrees on each side forming an overall 66 degree angle.  Cutting of the work piece will occur at the point and sides so the steepest angle relative to the face will be the same as the tool arrow point sides, 33 degrees.  The same angle relative to the lathe turning axis is of course 33 degrees.   Relative to the face the steepest angle is 67 degrees.  The cutting tool could be oriented in various angles relative to the lathe axis.  The author selected this orientation so that the angles relative to the face would be balanced on both sides of the cutting point. 
 
The construction lines on the Alibre CAD design provide a series of points.  The author sets up the g-code statements in a sequence of cuts.  Each cut starts at or near the center of the work piece in the X axis and cuts in a sequence of slopes and straight lines towards the outer edge of the work piece.  The maximum depth of any cut will be 0.010 or 10 mils.   A typical cut has an X and Y starting point, a possible straight cut in X towards the rim, a slope cut of simultaneous X and Y to a Y depth, a straight cut in X towards the rim, a slope cut outward from the Y depth and perhaps additional straight X cuts towards the rim.  Some cuts may be simple straight cuts only in X. 
 
Each cut then has a sequence of points each with a pair of X and Y values.  Where the starting and ending X or Y values are the same, the move will be a straight cut in one axis alone.  When both X and Y values change between the start and end of a cut move the result is a sloping line in both X and Y.  Each move will be encoded as one of the following forms.
 
                    xnnnnn                (a move in x only.  The string of nnnnn represents the value)
                    ynnnnn                (a move in y alone)
                    xnnnnn ynnnnn  (a slope where both x and y change values)
 
The string of nnnnn's above can be a number, parameter or expression.  The first move in the author's programs is to go home in case the lathe is positioned off that point.  That generallly will appear as follows:
 
                    y#<_home_y           (return to y home away from work piece first)
                    x#<_home_x          (return to x home)
 
Once the tool tip is at home, it will then be positioned at two rates towards the first cut.  The initial move is a a fast positioning rate (set by a parameter) followed by a slow approach rate (also set by a parameter).  The move is to the point where the cut will start.  The rate then switches to the cutting rate appropriate for the particular portion of the cut.  There might be a differenct rate for straight cuts in x, in y, slopes and radius cuts.  A radius cut is an continuous arc where both x and y are continuously changing so the tool tip describes and arc that ends at a particular point with a particular radius beginning at the end of the previous move.  Each of the cutting rates are set by parameters, for example:
 
                 #<_position_rate> = 20
                 #<_approach_rate> = 2
                 #<_x_cut_rate> = 0.3
                 #<_y_cut_rate> = 0.2
                 #<_slope_cut_rate> = 0.25
                 #<_arc_cut_rate> = 0.13

Before beginning the define the cut statements the overall program structure looks as follows without centering the text for emphasis.  The actual code will look like:

(Tender Truck Wheel External Inside Contour)
%




g01 g20 g40 g80 g49 g90 f2
.
.
(PARAMETERS)
#<_home_x = 0.0
#<_home_y = 3.0000 (start and return to 3" away from work piece)
#<_Work_Piece_Face> = [#<_home_y - 3.000]
.
(Additional parameters as needed)
.


#<_position_rate> = 20
#<_approach_rate> = 2
#<_x_cut_rate> = 0.3
#<_y_cut_rate> = 0.2
#<_slope_cut_rate> = 0.25
#<_arc_cut_rate> = 0.13
.
.
(Additional parameters for cut point data)

.



(BEGIN CUTTING SEQUENCE)
(go home initially)                   
y#<_home_y (return to y home away from work piece first)
x#<_home_x (return to x home)
.            
.
(Cuts go in middle of program)
.
.
.
(Go home after completing cuts)
g0          (set mode for rapid positioning)
y#<_home_y (return to y home away from work piece first)
x#<_home_x (return to x home)
m0
%
       

Defining the contour cuts 

Once the rates are set the next step is to define the set of points for each cut.  The first cut for this exercise the is a simple straight cut from the inside bore to the edge of the work piece.  The bore is 0.250" and the edge is 0.125" from the lathe center line.  The work piece is a section of one and one-quarter inch aluminum stock material.  It is prudent in this case for the x start to be inside the bore a bit and end slightly beyond the maximum outer edge of the work piece.  X values are radius values and half of the respective diameters.  The x values for the cut are defined as follows:
 
                    #<_cut_1_x_start> = 0.1050          (start 20 mils inside bore)
                    #<_cut_1_x_end> = 0.6500           (end 25 mils beyond stock radius)
 
The y axis presents a somewhat different set of problems.  Since y begins at the home position movements are divided into two phases, rapid positioning towards the work piece, a slower approach to where the y cut will start.  For those moves two sets of start and end are used.  Since the y moves will be prior to the x moves in the author's program the moves will be in y only.  Two y parameters are used, the end for the rapid move and end of the approach move.
 
                  #<_cut_1_y_position_end> = 0.0200     (end the positioning 20 mils from face)
                  #<_cut_1_y_approach_end> = 0.0000  (end the approach at the face)
 
Since the first cut will be made straight from start to end it will only be necessary to make the moves as follows:
 
                 f#<_position_rate>                      (set feed rate for positioning)                
                 y#<_cut_1_y_position_end>        (end the positioning 20 mils to face)       
                 f#<_approach_rate>                    (slow for approach to work piece)
                 x #<_cut_1_x_start>                    (start 20 mils inside bore)
                 y#<_cut_1_y_approach_end>     (end the approach at the face
                f#<_x_cut_rate>                           (tool move is in x only)               
                x#<_cut_1_x_end>                       (end 25 mils beyond stock radius)
 
Each move statement begins with the axis letter followed by a number, parameter or expression.  In the above example for cut 1 the author used parameters.   In summation, a move sequence for a cut begins with a move to the starting point followed by a cutting move or moves between various points.

The author will not go through every cut in this level of detail.  It would be instructive however to show two other cuts, one of the cuts with slopes and the final cut to the template which invokes several radius cuts.   
 
 
 

No comments:

Post a Comment

Constructive Comments Welcome