//Simple Probe for Zero
//This routine probes in negative Z at the current XY location
//Z offsets for G54 to G59 are then re-written to the new Z0

double ZRetractHeight =5;  //Height above Z0 to which probe will retract
double CoarseRate = 300; //Feedrate for initial probing
double FineRate = 200;  //Feedrate for fine probing
double Zmin = -50; //maximum probing distance

double PlateThickness = 12.3;  //thickness of the probing plate
double MaterialOffset = 0; //compensation for part thickness

double CombinedOffset = PlateThickness - MaterialOffset;  //really for use later when PlateThickness and MaterialOffset are DROs

if(!exec.GetLED(56)||!exec.GetLED(57)||!exec.GetLED(58)) // If machine was not homed then it is not smart to do this, stop here...
{
  MessageBox.Show("The machine was not yet homed, home the machine before setting Z-zero");
  exec.Stop();
  return;
}


exec.Code("G91 G31 Z" + Zmin + "F" + CoarseRate); // Probe Z quickly to get rough height
while(exec.IsMoving()){}
exec.Wait(200);

exec.Code ("G00 Z" + 5); // Retract 5mm above the plate
while(exec.IsMoving()){}
exec.Wait(100);

exec.Code("G31 Z" + Zmin + "F" + FineRate); // Probe Z slowly for better resolution
while(exec.IsMoving()){}
exec.Wait(200);

exec.mainform.sumoffsetcontrol1.G54.newCzinput(CombinedOffset);  // Set G54 to new Zzero
exec.mainform.sumoffsetcontrol1.G55.newCzinput(CombinedOffset);  // Set G55 to new Zzero	
exec.mainform.sumoffsetcontrol1.G56.newCzinput(CombinedOffset);  // Set G56 to new Zzero
exec.mainform.sumoffsetcontrol1.G57.newCzinput(CombinedOffset);  // Set G57 to new Zzero
exec.mainform.sumoffsetcontrol1.G58.newCzinput(CombinedOffset);  // Set G58 to new Zzero
exec.mainform.sumoffsetcontrol1.G59.newCzinput(CombinedOffset);  // Set G59 to new Zzero

exec.Code ("G00 Z" + ZRetractHeight); //Retract Z axis
while(exec.IsMoving()){}
exec.Wait(200);
exec.Code ("G90");
