84f1691809e62807a89b4cf3f7fbcfab420df750
[clinton/Smoothieware.git] / src / modules / tools / zprobe / ZProbe.cpp
1 /*
2 This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
3 Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
4 Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
5 You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
6 */
7
8 #include "ZProbe.h"
9
10 #include "Kernel.h"
11 #include "BaseSolution.h"
12 #include "Config.h"
13 #include "Robot.h"
14 #include "StepperMotor.h"
15 #include "StreamOutputPool.h"
16 #include "Gcode.h"
17 #include "Conveyor.h"
18 #include "checksumm.h"
19 #include "ConfigValue.h"
20 #include "SlowTicker.h"
21 #include "Planner.h"
22 #include "SerialMessage.h"
23 #include "PublicDataRequest.h"
24 #include "EndstopsPublicAccess.h"
25 #include "PublicData.h"
26 #include "LevelingStrategy.h"
27 #include "StepTicker.h"
28 #include "utils.h"
29
30 // strategies we know about
31 #include "DeltaCalibrationStrategy.h"
32 #include "ThreePointStrategy.h"
33 #include "DeltaGridStrategy.h"
34 #include "CartGridStrategy.h"
35
36 #define enable_checksum CHECKSUM("enable")
37 #define probe_pin_checksum CHECKSUM("probe_pin")
38 #define debounce_ms_checksum CHECKSUM("debounce_ms")
39 #define slow_feedrate_checksum CHECKSUM("slow_feedrate")
40 #define fast_feedrate_checksum CHECKSUM("fast_feedrate")
41 #define return_feedrate_checksum CHECKSUM("return_feedrate")
42 #define probe_height_checksum CHECKSUM("probe_height")
43 #define gamma_max_checksum CHECKSUM("gamma_max")
44 #define max_z_checksum CHECKSUM("max_z")
45 #define reverse_z_direction_checksum CHECKSUM("reverse_z")
46 #define dwell_before_probing_checksum CHECKSUM("dwell_before_probing")
47
48 // from endstop section
49 #define delta_homing_checksum CHECKSUM("delta_homing")
50 #define rdelta_homing_checksum CHECKSUM("rdelta_homing")
51
52 #define X_AXIS 0
53 #define Y_AXIS 1
54 #define Z_AXIS 2
55
56 #define STEPPER THEROBOT->actuators
57 #define STEPS_PER_MM(a) (STEPPER[a]->get_steps_per_mm())
58 #define Z_STEPS_PER_MM STEPS_PER_MM(Z_AXIS)
59
60 void ZProbe::on_module_loaded()
61 {
62 // if the module is disabled -> do nothing
63 if(!THEKERNEL->config->value( zprobe_checksum, enable_checksum )->by_default(false)->as_bool()) {
64 // as this module is not needed free up the resource
65 delete this;
66 return;
67 }
68
69 // load settings
70 this->config_load();
71 // register event-handlers
72 register_for_event(ON_GCODE_RECEIVED);
73
74 // we read the probe in this timer
75 probing= false;
76 THEKERNEL->slow_ticker->attach(1000, this, &ZProbe::read_probe);
77 }
78
79 void ZProbe::config_load()
80 {
81 this->pin.from_string( THEKERNEL->config->value(zprobe_checksum, probe_pin_checksum)->by_default("nc" )->as_string())->as_input();
82 this->debounce_ms = THEKERNEL->config->value(zprobe_checksum, debounce_ms_checksum)->by_default(0 )->as_number();
83
84 // get strategies to load
85 vector<uint16_t> modules;
86 THEKERNEL->config->get_module_list( &modules, leveling_strategy_checksum);
87 for( auto cs : modules ){
88 if( THEKERNEL->config->value(leveling_strategy_checksum, cs, enable_checksum )->as_bool() ){
89 bool found= false;
90 LevelingStrategy *ls= nullptr;
91
92 // check with each known strategy and load it if it matches
93 switch(cs) {
94 case delta_calibration_strategy_checksum:
95 ls= new DeltaCalibrationStrategy(this);
96 found= true;
97 break;
98
99 case three_point_leveling_strategy_checksum:
100 // NOTE this strategy is mutually exclusive with the delta calibration strategy
101 ls= new ThreePointStrategy(this);
102 found= true;
103 break;
104
105 case delta_grid_leveling_strategy_checksum:
106 ls= new DeltaGridStrategy(this);
107 found= true;
108 break;
109
110 case cart_grid_leveling_strategy_checksum:
111 ls= new CartGridStrategy(this);
112 found= true;
113 break;
114 }
115 if(found) {
116 if(ls->handleConfig()) {
117 this->strategies.push_back(ls);
118 }else{
119 delete ls;
120 }
121 }
122 }
123 }
124
125 // need to know if we need to use delta kinematics for homing
126 this->is_delta = THEKERNEL->config->value(delta_homing_checksum)->by_default(false)->as_bool();
127 this->is_rdelta = THEKERNEL->config->value(rdelta_homing_checksum)->by_default(false)->as_bool();
128
129 // default for backwards compatibility add DeltaCalibrationStrategy if a delta
130 // may be deprecated
131 if(this->strategies.empty()) {
132 if(this->is_delta) {
133 this->strategies.push_back(new DeltaCalibrationStrategy(this));
134 this->strategies.back()->handleConfig();
135 }
136 }
137
138 this->probe_height = THEKERNEL->config->value(zprobe_checksum, probe_height_checksum)->by_default(5.0F)->as_number();
139 this->slow_feedrate = THEKERNEL->config->value(zprobe_checksum, slow_feedrate_checksum)->by_default(5)->as_number(); // feedrate in mm/sec
140 this->fast_feedrate = THEKERNEL->config->value(zprobe_checksum, fast_feedrate_checksum)->by_default(100)->as_number(); // feedrate in mm/sec
141 this->return_feedrate = THEKERNEL->config->value(zprobe_checksum, return_feedrate_checksum)->by_default(0)->as_number(); // feedrate in mm/sec
142 this->reverse_z = THEKERNEL->config->value(zprobe_checksum, reverse_z_direction_checksum)->by_default(false)->as_bool(); // Z probe moves in reverse direction
143 this->max_z = THEKERNEL->config->value(zprobe_checksum, max_z_checksum)->by_default(NAN)->as_number(); // maximum zprobe distance
144 if(isnan(this->max_z)){
145 this->max_z = THEKERNEL->config->value(gamma_max_checksum)->by_default(200)->as_number(); // maximum zprobe distance
146 }
147 this->dwell_before_probing = THEKERNEL->config->value(zprobe_checksum, dwell_before_probing_checksum)->by_default(0)->as_number(); // dwell time in seconds before probing
148
149 }
150
151 uint32_t ZProbe::read_probe(uint32_t dummy)
152 {
153 if(!probing || probe_detected) return 0;
154
155 // we check all axis as it maybe a G38.2 X10 for instance, not just a probe in Z
156 if(STEPPER[X_AXIS]->is_moving() || STEPPER[Y_AXIS]->is_moving() || STEPPER[Z_AXIS]->is_moving()) {
157 // if it is moving then we check the probe, and debounce it
158 if(this->pin.get()) {
159 if(debounce < debounce_ms) {
160 debounce++;
161 } else {
162 // we signal the motors to stop, which will preempt any moves on that axis
163 // we do all motors as it may be a delta
164 for(auto &a : THEROBOT->actuators) a->stop_moving();
165 probe_detected= true;
166 debounce= 0;
167 }
168
169 } else {
170 // The endstop was not hit yet
171 debounce= 0;
172 }
173 }
174
175 return 0;
176 }
177
178 // single probe in Z with custom feedrate
179 // returns boolean value indicating if probe was triggered
180 bool ZProbe::run_probe(float& mm, float feedrate, float max_dist, bool reverse)
181 {
182 if(dwell_before_probing > .0001F) safe_delay_ms(dwell_before_probing*1000);
183
184 if(this->pin.get()) {
185 // probe already triggered so abort
186 return false;
187 }
188
189 float maxz= max_dist < 0 ? this->max_z*2 : max_dist;
190
191 probing= true;
192 probe_detected= false;
193 debounce= 0;
194
195 // save current actuator position so we can report how far we moved
196 float z_start_pos= THEROBOT->actuators[Z_AXIS]->get_current_position();
197
198 // move Z down
199 bool dir= (!reverse_z != reverse); // xor
200 float delta[3]= {0,0,0};
201 delta[Z_AXIS]= dir ? -maxz : maxz;
202 THEROBOT->delta_move(delta, feedrate, 3);
203
204 // wait until finished
205 THECONVEYOR->wait_for_idle();
206
207 // now see how far we moved, get delta in z we moved
208 // NOTE this works for deltas as well as all three actuators move the same amount in Z
209 mm= z_start_pos - THEROBOT->actuators[2]->get_current_position();
210
211 // set the last probe position to the actuator units moved during this home
212 THEROBOT->set_last_probe_position(std::make_tuple(0, 0, mm, probe_detected?1:0));
213
214 probing= false;
215
216 if(probe_detected) {
217 // if the probe stopped the move we need to correct the last_milestone as it did not reach where it thought
218 THEROBOT->reset_position_from_current_actuator_position();
219 }
220
221 return probe_detected;
222 }
223
224 // do probe then return to start position
225 bool ZProbe::run_probe_return(float& mm, float feedrate, float max_dist, bool reverse)
226 {
227 float save_z_pos= THEROBOT->get_axis_position(Z_AXIS);
228
229 bool ok= run_probe(mm, feedrate, max_dist, reverse);
230
231 // move probe back to where it was
232 float fr;
233 if(this->return_feedrate != 0) { // use return_feedrate if set
234 fr = this->return_feedrate;
235 } else {
236 fr = this->slow_feedrate*2; // nominally twice slow feedrate
237 if(fr > this->fast_feedrate) fr = this->fast_feedrate; // unless that is greater than fast feedrate
238 }
239
240 // absolute move back to saved starting position
241 coordinated_move(NAN, NAN, save_z_pos, fr, false);
242
243 return ok;
244 }
245
246 bool ZProbe::doProbeAt(float &mm, float x, float y)
247 {
248 // move to xy
249 coordinated_move(x, y, NAN, getFastFeedrate());
250 return run_probe_return(mm, slow_feedrate);
251 }
252
253 void ZProbe::on_gcode_received(void *argument)
254 {
255 Gcode *gcode = static_cast<Gcode *>(argument);
256
257 if( gcode->has_g && gcode->g >= 29 && gcode->g <= 32) {
258
259 // make sure the probe is defined and not already triggered before moving motors
260 if(!this->pin.connected()) {
261 gcode->stream->printf("ZProbe pin not configured.\n");
262 return;
263 }
264
265 if(this->pin.get()) {
266 gcode->stream->printf("ZProbe triggered before move, aborting command.\n");
267 return;
268 }
269
270 if( gcode->g == 30 ) { // simple Z probe
271 // first wait for all moves to finish
272 THEKERNEL->conveyor->wait_for_idle();
273
274 bool set_z= (gcode->has_letter('Z') && !is_rdelta);
275 bool probe_result;
276 bool reverse= (gcode->has_letter('R') && gcode->get_value('R') != 0); // specify to probe in reverse direction
277 float rate= gcode->has_letter('F') ? gcode->get_value('F') / 60 : this->slow_feedrate;
278 float mm;
279
280 // if not setting Z then return probe to where it started, otherwise leave it where it is
281 probe_result = (set_z ? run_probe(mm, rate, -1, reverse) : run_probe_return(mm, rate, -1, reverse));
282
283 if(probe_result) {
284 // the result is in actuator coordinates moved
285 gcode->stream->printf("Z:%1.4f\n", THEKERNEL->robot->from_millimeters(mm));
286
287 if(set_z) {
288 // set current Z to the specified value, shortcut for G92 Znnn
289 char buf[32];
290 int n = snprintf(buf, sizeof(buf), "G92 Z%f", gcode->get_value('Z'));
291 string g(buf, n);
292 Gcode gc(g, &(StreamOutput::NullStream));
293 THEKERNEL->call_event(ON_GCODE_RECEIVED, &gc);
294 }
295
296 } else {
297 gcode->stream->printf("ZProbe not triggered\n");
298 }
299
300 } else {
301 if(!gcode->has_letter('P')) {
302 // find the first strategy to handle the gcode
303 for(auto s : strategies){
304 if(s->handleGcode(gcode)) {
305 return;
306 }
307 }
308 gcode->stream->printf("No strategy found to handle G%d\n", gcode->g);
309
310 }else{
311 // P paramater selects which strategy to send the code to
312 // they are loaded in the order they are defined in config, 0 being the first, 1 being the second and so on.
313 uint16_t i= gcode->get_value('P');
314 if(i < strategies.size()) {
315 if(!strategies[i]->handleGcode(gcode)){
316 gcode->stream->printf("strategy #%d did not handle G%d\n", i, gcode->g);
317 }
318 return;
319
320 }else{
321 gcode->stream->printf("strategy #%d is not loaded\n", i);
322 }
323 }
324 }
325
326 } else if(gcode->has_g && gcode->g == 38 ) { // G38.2 Straight Probe with error, G38.3 straight probe without error
327 // linuxcnc/grbl style probe http://www.linuxcnc.org/docs/2.5/html/gcode/gcode.html#sec:G38-probe
328 if(gcode->subcode != 2 && gcode->subcode != 3) {
329 gcode->stream->printf("error:Only G38.2 and G38.3 are supported\n");
330 return;
331 }
332
333 // make sure the probe is defined and not already triggered before moving motors
334 if(!this->pin.connected()) {
335 gcode->stream->printf("error:ZProbe not connected.\n");
336 return;
337 }
338
339 if(this->pin.get()) {
340 gcode->stream->printf("error:ZProbe triggered before move, aborting command.\n");
341 return;
342 }
343
344 // first wait for all moves to finish
345 THEKERNEL->conveyor->wait_for_idle();
346
347 float x= NAN, y=NAN, z=NAN;
348 if(gcode->has_letter('X')) {
349 x= gcode->get_value('X');
350 }
351
352 if(gcode->has_letter('Y')) {
353 y= gcode->get_value('Y');
354 }
355
356 if(gcode->has_letter('Z')) {
357 z= gcode->get_value('Z');
358 }
359
360 if(isnan(x) && isnan(y) && isnan(z)) {
361 gcode->stream->printf("error:at least one of X Y or Z must be specified\n");
362 return;
363 }
364
365 probe_XYZ(gcode, x, y, z);
366
367 return;
368
369 } else if(gcode->has_m) {
370 // M code processing here
371 int c;
372 switch (gcode->m) {
373 case 119:
374 c = this->pin.get();
375 gcode->stream->printf(" Probe: %d", c);
376 gcode->add_nl = true;
377 break;
378
379 case 670:
380 if (gcode->has_letter('S')) this->slow_feedrate = gcode->get_value('S');
381 if (gcode->has_letter('K')) this->fast_feedrate = gcode->get_value('K');
382 if (gcode->has_letter('R')) this->return_feedrate = gcode->get_value('R');
383 if (gcode->has_letter('Z')) this->max_z = gcode->get_value('Z');
384 if (gcode->has_letter('H')) this->probe_height = gcode->get_value('H');
385 if (gcode->has_letter('I')) { // NOTE this is temporary and toggles the invertion status of the pin
386 invert_override= (gcode->get_value('I') != 0);
387 pin.set_inverting(pin.is_inverting() != invert_override); // XOR so inverted pin is not inverted and vice versa
388 }
389 if (gcode->has_letter('D')) this->dwell_before_probing = gcode->get_value('D');
390 break;
391
392 case 500: // save settings
393 case 503: // print settings
394 gcode->stream->printf(";Probe feedrates Slow/fast(K)/Return (mm/sec) max_z (mm) height (mm) dwell (s):\nM670 S%1.2f K%1.2f R%1.2f Z%1.2f H%1.2f D%1.2f\n",
395 this->slow_feedrate, this->fast_feedrate, this->return_feedrate, this->max_z, this->probe_height, this->dwell_before_probing);
396
397 // fall through is intended so leveling strategies can handle m-codes too
398
399 default:
400 for(auto s : strategies){
401 if(s->handleGcode(gcode)) {
402 return;
403 }
404 }
405 }
406 }
407 }
408
409 // special way to probe in the X or Y or Z direction using planned moves, should work with any kinematics
410 void ZProbe::probe_XYZ(Gcode *gcode, float x, float y, float z)
411 {
412 // enable the probe checking in the timer
413 probing= true;
414 probe_detected= false;
415 THEROBOT->disable_segmentation= true; // we must disable segmentation as this won't work with it enabled (beware on deltas probing in X or Y)
416
417 // get probe feedrate in mm/min and convert to mm/sec if specified
418 float rate = (gcode->has_letter('F')) ? gcode->get_value('F')/60 : this->slow_feedrate;
419
420 // do a regular move which will stop as soon as the probe is triggered, or the distance is reached
421 coordinated_move(x, y, z, rate, true);
422
423 // coordinated_move returns when the move is finished
424
425 // disable probe checking
426 probing= false;
427 THEROBOT->disable_segmentation= false;
428
429 // if the probe stopped the move we need to correct the last_milestone as it did not reach where it thought
430 // this also sets last_milestone to the machine coordinates it stopped at
431 THEROBOT->reset_position_from_current_actuator_position();
432 float pos[3];
433 THEROBOT->get_axis_position(pos, 3);
434
435 uint8_t probeok= this->probe_detected ? 1 : 0;
436
437 // print results using the GRBL format
438 gcode->stream->printf("[PRB:%1.3f,%1.3f,%1.3f:%d]\n", THEKERNEL->robot->from_millimeters(pos[X_AXIS]), THEKERNEL->robot->from_millimeters(pos[Y_AXIS]), THEKERNEL->robot->from_millimeters(pos[Z_AXIS]), probeok);
439 THEROBOT->set_last_probe_position(std::make_tuple(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], probeok));
440
441 if(probeok == 0 && gcode->subcode == 2) {
442 // issue error if probe was not triggered and subcode == 2
443 gcode->stream->printf("ALARM: Probe fail\n");
444 THEKERNEL->call_event(ON_HALT, nullptr);
445 }
446 }
447
448 // issue a coordinated move directly to robot, and return when done
449 // Only move the coordinates that are passed in as not nan
450 // NOTE must use G53 to force move in machine coordinates and ignore any WCS offsets
451 void ZProbe::coordinated_move(float x, float y, float z, float feedrate, bool relative)
452 {
453 #define CMDLEN 128
454 char *cmd= new char[CMDLEN]; // use heap here to reduce stack usage
455
456 if(relative) strcpy(cmd, "G91 G0 ");
457 else strcpy(cmd, "G53 G0 "); // G53 forces movement in machine coordinate system
458
459 if(!isnan(x)) {
460 size_t n= strlen(cmd);
461 snprintf(&cmd[n], CMDLEN-n, " X%1.3f", x);
462 }
463 if(!isnan(y)) {
464 size_t n= strlen(cmd);
465 snprintf(&cmd[n], CMDLEN-n, " Y%1.3f", y);
466 }
467 if(!isnan(z)) {
468 size_t n= strlen(cmd);
469 snprintf(&cmd[n], CMDLEN-n, " Z%1.3f", z);
470 }
471
472 {
473 size_t n= strlen(cmd);
474 // use specified feedrate (mm/sec)
475 snprintf(&cmd[n], CMDLEN-n, " F%1.1f", feedrate * 60); // feed rate is converted to mm/min
476 }
477
478 if(relative) strcat(cmd, " G90");
479
480 //THEKERNEL->streams->printf("DEBUG: move: %s: %u\n", cmd, strlen(cmd));
481
482 // send as a command line as may have multiple G codes in it
483 THEROBOT->push_state();
484 struct SerialMessage message;
485 message.message = cmd;
486 delete [] cmd;
487
488 message.stream = &(StreamOutput::NullStream);
489 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message );
490 THEKERNEL->conveyor->wait_for_idle();
491 THEROBOT->pop_state();
492
493 }
494
495 // issue home command
496 void ZProbe::home()
497 {
498 Gcode gc(THEKERNEL->is_grbl_mode() ? "G28.2" : "G28", &(StreamOutput::NullStream));
499 THEKERNEL->call_event(ON_GCODE_RECEIVED, &gc);
500 }