Merge remote-tracking branch 'upstream/edge' into upstreamedge
[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 "Stepper.h"
19 #include "checksumm.h"
20 #include "ConfigValue.h"
21 #include "SlowTicker.h"
22 #include "Planner.h"
23 #include "SerialMessage.h"
24 #include "PublicDataRequest.h"
25 #include "EndstopsPublicAccess.h"
26 #include "PublicData.h"
27 #include "LevelingStrategy.h"
28 #include "StepTicker.h"
29 #include "utils.h"
30
31 // strategies we know about
32 #include "DeltaCalibrationStrategy.h"
33 #include "ThreePointStrategy.h"
34 #include "ZGridStrategy.h"
35 #include "DeltaGridStrategy.h"
36
37 #define enable_checksum CHECKSUM("enable")
38 #define probe_pin_checksum CHECKSUM("probe_pin")
39 #define debounce_count_checksum CHECKSUM("debounce_count")
40 #define slow_feedrate_checksum CHECKSUM("slow_feedrate")
41 #define fast_feedrate_checksum CHECKSUM("fast_feedrate")
42 #define return_feedrate_checksum CHECKSUM("return_feedrate")
43 #define probe_height_checksum CHECKSUM("probe_height")
44 #define gamma_max_checksum CHECKSUM("gamma_max")
45 #define reverse_z_direction_checksum CHECKSUM("reverse_z")
46
47 // from endstop section
48 #define delta_homing_checksum CHECKSUM("delta_homing")
49 #define rdelta_homing_checksum CHECKSUM("rdelta_homing")
50
51 #define X_AXIS 0
52 #define Y_AXIS 1
53 #define Z_AXIS 2
54
55 #define STEPPER THEKERNEL->robot->actuators
56 #define STEPS_PER_MM(a) (STEPPER[a]->get_steps_per_mm())
57 #define Z_STEPS_PER_MM STEPS_PER_MM(Z_AXIS)
58
59 #define abs(a) ((a<0) ? -a : a)
60
61 void ZProbe::on_module_loaded()
62 {
63 // if the module is disabled -> do nothing
64 if(!THEKERNEL->config->value( zprobe_checksum, enable_checksum )->by_default(false)->as_bool()) {
65 // as this module is not needed free up the resource
66 delete this;
67 return;
68 }
69
70 // load settings
71 this->on_config_reload(this);
72 // register event-handlers
73 register_for_event(ON_GCODE_RECEIVED);
74
75 THEKERNEL->step_ticker->register_acceleration_tick_handler([this](){acceleration_tick(); });
76
77 // we read the probe in this timer, currently only for G38 probes.
78 probing= false;
79 THEKERNEL->slow_ticker->attach(1000, this, &ZProbe::read_probe);
80 }
81
82 void ZProbe::on_config_reload(void *argument)
83 {
84 this->pin.from_string( THEKERNEL->config->value(zprobe_checksum, probe_pin_checksum)->by_default("nc" )->as_string())->as_input();
85 this->debounce_count = THEKERNEL->config->value(zprobe_checksum, debounce_count_checksum)->by_default(0 )->as_number();
86
87 // get strategies to load
88 vector<uint16_t> modules;
89 THEKERNEL->config->get_module_list( &modules, leveling_strategy_checksum);
90 for( auto cs : modules ){
91 if( THEKERNEL->config->value(leveling_strategy_checksum, cs, enable_checksum )->as_bool() ){
92 bool found= false;
93 // check with each known strategy and load it if it matches
94 switch(cs) {
95 case delta_calibration_strategy_checksum:
96 this->strategies.push_back(new DeltaCalibrationStrategy(this));
97 found= true;
98 break;
99
100 case three_point_leveling_strategy_checksum:
101 // NOTE this strategy is mutually exclusive with the delta calibration strategy
102 this->strategies.push_back(new ThreePointStrategy(this));
103 found= true;
104 break;
105
106 case ZGrid_leveling_checksum:
107 this->strategies.push_back(new ZGridStrategy(this));
108 found= true;
109 break;
110
111 case delta_grid_leveling_strategy_checksum:
112 this->strategies.push_back(new DeltaGridStrategy(this));
113 found= true;
114 break;
115 }
116 if(found) this->strategies.back()->handleConfig();
117 }
118 }
119
120 // need to know if we need to use delta kinematics for homing
121 this->is_delta = THEKERNEL->config->value(delta_homing_checksum)->by_default(false)->as_bool();
122 this->is_rdelta = THEKERNEL->config->value(rdelta_homing_checksum)->by_default(false)->as_bool();
123
124 // default for backwards compatibility add DeltaCalibrationStrategy if a delta
125 // will be deprecated
126 if(this->strategies.empty()) {
127 if(this->is_delta) {
128 this->strategies.push_back(new DeltaCalibrationStrategy(this));
129 this->strategies.back()->handleConfig();
130 }
131 }
132
133 this->probe_height = THEKERNEL->config->value(zprobe_checksum, probe_height_checksum)->by_default(5.0F)->as_number();
134 this->slow_feedrate = THEKERNEL->config->value(zprobe_checksum, slow_feedrate_checksum)->by_default(5)->as_number(); // feedrate in mm/sec
135 this->fast_feedrate = THEKERNEL->config->value(zprobe_checksum, fast_feedrate_checksum)->by_default(100)->as_number(); // feedrate in mm/sec
136 this->return_feedrate = THEKERNEL->config->value(zprobe_checksum, return_feedrate_checksum)->by_default(0)->as_number(); // feedrate in mm/sec
137 this->reverse_z = THEKERNEL->config->value(zprobe_checksum, reverse_z_direction_checksum)->by_default(false)->as_bool(); // Z probe moves in reverse direction
138 this->max_z = THEKERNEL->config->value(gamma_max_checksum)->by_default(500)->as_number(); // maximum zprobe distance
139 }
140
141 bool ZProbe::wait_for_probe(int& steps)
142 {
143 unsigned int debounce = 0;
144 while(true) {
145 THEKERNEL->call_event(ON_IDLE);
146 if(THEKERNEL->is_halted()){
147 // aborted by kill
148 return false;
149 }
150
151 bool delta= is_delta || is_rdelta;
152
153 // if no stepper is moving, moves are finished and there was no touch
154 if( !STEPPER[Z_AXIS]->is_moving() && (!delta || (!STEPPER[Y_AXIS]->is_moving() && !STEPPER[Z_AXIS]->is_moving())) ) {
155 return false;
156 }
157
158 // if the probe is active...
159 if( this->pin.get() ) {
160 //...increase debounce counter...
161 if( debounce < debounce_count) {
162 // ...but only if the counter hasn't reached the max. value
163 debounce++;
164 } else {
165 // ...otherwise stop the steppers, return its remaining steps
166 if(STEPPER[Z_AXIS]->is_moving()){
167 steps= STEPPER[Z_AXIS]->get_stepped();
168 STEPPER[Z_AXIS]->move(0, 0);
169 }
170 if(delta) {
171 for( int i = X_AXIS; i <= Y_AXIS; i++ ) {
172 if ( STEPPER[i]->is_moving() ) {
173 STEPPER[i]->move(0, 0);
174 }
175 }
176 }
177 return true;
178 }
179 } else {
180 // The probe was not hit yet, reset debounce counter
181 debounce = 0;
182 }
183 }
184 }
185
186 // single probe with custom feedrate
187 // returns boolean value indicating if probe was triggered
188 bool ZProbe::run_probe(int& steps, float feedrate, float max_dist, bool reverse)
189 {
190 // not a block move so disable the last tick setting
191 for ( int c = X_AXIS; c <= Z_AXIS; c++ ) {
192 STEPPER[c]->set_moved_last_block(false);
193 }
194
195 // Enable the motors
196 THEKERNEL->stepper->turn_enable_pins_on();
197 this->current_feedrate = feedrate * Z_STEPS_PER_MM; // steps/sec
198 float maxz= max_dist < 0 ? this->max_z*2 : max_dist;
199
200 // move Z down
201 bool dir= (!reverse_z != reverse); // xor
202 STEPPER[Z_AXIS]->move(dir, maxz * Z_STEPS_PER_MM, 0); // probe in specified direction, no more than maxz
203 if(this->is_delta || this->is_rdelta) {
204 // for delta need to move all three actuators
205 STEPPER[X_AXIS]->move(dir, maxz * STEPS_PER_MM(X_AXIS), 0);
206 STEPPER[Y_AXIS]->move(dir, maxz * STEPS_PER_MM(Y_AXIS), 0);
207 }
208
209 // start acceleration processing
210 this->running = true;
211
212 bool r = wait_for_probe(steps);
213 this->running = false;
214 STEPPER[X_AXIS]->move(0, 0);
215 STEPPER[Y_AXIS]->move(0, 0);
216 STEPPER[Z_AXIS]->move(0, 0);
217 return r;
218 }
219
220 bool ZProbe::return_probe(int steps, bool reverse)
221 {
222 // move probe back to where it was
223
224 float fr;
225 if(this->return_feedrate != 0) { // use return_feedrate if set
226 fr = this->return_feedrate;
227 } else {
228 fr = this->slow_feedrate*2; // nominally twice slow feedrate
229 if(fr > this->fast_feedrate) fr = this->fast_feedrate; // unless that is greater than fast feedrate
230 }
231
232 this->current_feedrate = fr * Z_STEPS_PER_MM; // feedrate in steps/sec
233 bool dir= ((steps < 0) != reverse_z); // xor
234
235 if(reverse) dir= !dir;
236 steps= abs(steps);
237
238 bool delta= (this->is_delta || this->is_rdelta);
239 STEPPER[Z_AXIS]->move(dir, steps, 0);
240 if(delta) {
241 STEPPER[X_AXIS]->move(dir, steps, 0);
242 STEPPER[Y_AXIS]->move(dir, steps, 0);
243 }
244
245 this->running = true;
246 while(STEPPER[Z_AXIS]->is_moving() || (delta && (STEPPER[X_AXIS]->is_moving() || STEPPER[Y_AXIS]->is_moving())) ) {
247 // wait for it to complete
248 THEKERNEL->call_event(ON_IDLE);
249 if(THEKERNEL->is_halted()){
250 // aborted by kill
251 break;
252 }
253 }
254
255 this->running = false;
256 STEPPER[X_AXIS]->move(0, 0);
257 STEPPER[Y_AXIS]->move(0, 0);
258 STEPPER[Z_AXIS]->move(0, 0);
259
260 return true;
261 }
262
263 bool ZProbe::doProbeAt(int &steps, float x, float y)
264 {
265 int s;
266 // move to xy
267 coordinated_move(x, y, NAN, getFastFeedrate());
268 if(!run_probe(s)) return false;
269
270 // return to original Z
271 return_probe(s);
272 steps = s;
273
274 return true;
275 }
276
277 float ZProbe::probeDistance(float x, float y)
278 {
279 int s;
280 if(!doProbeAt(s, x, y)) return NAN;
281 return zsteps_to_mm(s);
282 }
283
284 void ZProbe::on_gcode_received(void *argument)
285 {
286 Gcode *gcode = static_cast<Gcode *>(argument);
287
288 if( gcode->has_g && gcode->g >= 29 && gcode->g <= 32) {
289
290 // make sure the probe is defined and not already triggered before moving motors
291 if(!this->pin.connected()) {
292 gcode->stream->printf("ZProbe not connected.\n");
293 return;
294 }
295 if(this->pin.get()) {
296 gcode->stream->printf("ZProbe triggered before move, aborting command.\n");
297 return;
298 }
299
300 if( gcode->g == 30 ) { // simple Z probe
301 // first wait for an empty queue i.e. no moves left
302 THEKERNEL->conveyor->wait_for_empty_queue();
303
304 int steps;
305 bool probe_result;
306 bool reverse= (gcode->has_letter('R') && gcode->get_value('R') != 0); // specify to probe in reverse direction
307 float rate= gcode->has_letter('F') ? gcode->get_value('F') / 60 : this->slow_feedrate;
308 probe_result = run_probe(steps, rate, -1, reverse);
309
310 if(probe_result) {
311 // the result is in actuator coordinates and raw steps
312 gcode->stream->printf("Z:%1.4f C:%d\n", zsteps_to_mm(steps), steps);
313
314 // set the last probe position to the current actuator units
315 THEKERNEL->robot->set_last_probe_position(std::make_tuple(
316 THEKERNEL->robot->actuators[X_AXIS]->get_current_position(),
317 THEKERNEL->robot->actuators[Y_AXIS]->get_current_position(),
318 THEKERNEL->robot->actuators[Z_AXIS]->get_current_position(),
319 1));
320
321 // move back to where it started, unless a Z is specified (and not a rotary delta)
322 if(gcode->has_letter('Z') && !is_rdelta) {
323 // set Z to the specified value, and leave probe where it is
324 THEKERNEL->robot->reset_axis_position(gcode->get_value('Z'), Z_AXIS);
325
326 } else {
327 // return to pre probe position
328 return_probe(steps, reverse);
329 }
330
331 } else {
332 gcode->stream->printf("ZProbe not triggered\n");
333 THEKERNEL->robot->set_last_probe_position(std::make_tuple(
334 THEKERNEL->robot->actuators[X_AXIS]->get_current_position(),
335 THEKERNEL->robot->actuators[Y_AXIS]->get_current_position(),
336 THEKERNEL->robot->actuators[Z_AXIS]->get_current_position(),
337 0));
338 }
339
340 } else {
341 if(!gcode->has_letter('P')) {
342 // find the first strategy to handle the gcode
343 for(auto s : strategies){
344 if(s->handleGcode(gcode)) {
345 return;
346 }
347 }
348 gcode->stream->printf("No strategy found to handle G%d\n", gcode->g);
349
350 }else{
351 // P paramater selects which strategy to send the code to
352 // they are loaded in the order they are defined in config, 0 being the first, 1 being the second and so on.
353 uint16_t i= gcode->get_value('P');
354 if(i < strategies.size()) {
355 if(!strategies[i]->handleGcode(gcode)){
356 gcode->stream->printf("strategy #%d did not handle G%d\n", i, gcode->g);
357 }
358 return;
359
360 }else{
361 gcode->stream->printf("strategy #%d is not loaded\n", i);
362 }
363 }
364 }
365
366 } else if(gcode->has_g && gcode->g == 38 ) { // G38.2 Straight Probe with error, G38.3 straight probe without error
367 // linuxcnc/grbl style probe http://www.linuxcnc.org/docs/2.5/html/gcode/gcode.html#sec:G38-probe
368 if(gcode->subcode != 2 && gcode->subcode != 3) {
369 gcode->stream->printf("error:Only G38.2 and G38.3 are supported\n");
370 return;
371 }
372
373 // make sure the probe is defined and not already triggered before moving motors
374 if(!this->pin.connected()) {
375 gcode->stream->printf("error:ZProbe not connected.\n");
376 return;
377 }
378
379 if(this->pin.get()) {
380 gcode->stream->printf("error:ZProbe triggered before move, aborting command.\n");
381 return;
382 }
383
384 // first wait for an empty queue i.e. no moves left
385 THEKERNEL->conveyor->wait_for_empty_queue();
386
387 // turn off any compensation transform
388 auto savect= THEKERNEL->robot->compensationTransform;
389 THEKERNEL->robot->compensationTransform= nullptr;
390
391 if(gcode->has_letter('X')) {
392 // probe in the X axis
393 probe_XYZ(gcode, X_AXIS);
394
395 }else if(gcode->has_letter('Y')) {
396 // probe in the Y axis
397 probe_XYZ(gcode, Y_AXIS);
398
399 }else if(gcode->has_letter('Z')) {
400 // probe in the Z axis
401 probe_XYZ(gcode, Z_AXIS);
402
403 }else{
404 gcode->stream->printf("error:at least one of X Y or Z must be specified\n");
405 }
406
407 // restore compensationTransform
408 THEKERNEL->robot->compensationTransform= savect;
409
410 return;
411
412 } else if(gcode->has_m) {
413 // M code processing here
414 int c;
415 switch (gcode->m) {
416 case 119:
417 c = this->pin.get();
418 gcode->stream->printf(" Probe: %d", c);
419 gcode->add_nl = true;
420 break;
421
422 case 670:
423 if (gcode->has_letter('S')) this->slow_feedrate = gcode->get_value('S');
424 if (gcode->has_letter('K')) this->fast_feedrate = gcode->get_value('K');
425 if (gcode->has_letter('R')) this->return_feedrate = gcode->get_value('R');
426 if (gcode->has_letter('Z')) this->max_z = gcode->get_value('Z');
427 if (gcode->has_letter('H')) this->probe_height = gcode->get_value('H');
428 if (gcode->has_letter('I')) { // NOTE this is temporary and toggles the invertion status of the pin
429 invert_override= (gcode->get_value('I') != 0);
430 pin.set_inverting(pin.is_inverting() != invert_override); // XOR so inverted pin is not inverted and vice versa
431 }
432 break;
433
434 case 500: // save settings
435 case 503: // print settings
436 gcode->stream->printf(";Probe feedrates Slow/fast(K)/Return (mm/sec) max_z (mm) height (mm):\nM670 S%1.2f K%1.2f R%1.2f Z%1.2f H%1.2f\n",
437 this->slow_feedrate, this->fast_feedrate, this->return_feedrate, this->max_z, this->probe_height);
438
439 // fall through is intended so leveling strategies can handle m-codes too
440
441 default:
442 for(auto s : strategies){
443 if(s->handleGcode(gcode)) {
444 return;
445 }
446 }
447 }
448 }
449 }
450
451 uint32_t ZProbe::read_probe(uint32_t dummy)
452 {
453 if(!probing || probe_detected) return 0;
454
455 // TODO add debounce/noise filter
456 if(this->pin.get()) {
457 probe_detected= true;
458 // now tell all the stepper_motors to stop
459 for(auto &a : THEKERNEL->robot->actuators) a->force_finish_move();
460 }
461 return 0;
462 }
463
464 // special way to probe in the X or Y or Z direction using planned moves, should work with any kinematics
465 void ZProbe::probe_XYZ(Gcode *gcode, int axis)
466 {
467 // enable the probe checking in the timer
468 probing= true;
469 probe_detected= false;
470 THEKERNEL->robot->disable_segmentation= true; // we must disable segmentation as this won't work with it enabled (beware on deltas probing in X or Y)
471
472 // get probe feedrate if specified
473 float rate = (gcode->has_letter('F')) ? gcode->get_value('F')*60 : this->slow_feedrate;
474
475 // do a regular move which will stop as soon as the probe is triggered, or the distance is reached
476 switch(axis) {
477 case X_AXIS: coordinated_move(gcode->get_value('X'), 0, 0, rate, true); break;
478 case Y_AXIS: coordinated_move(0, gcode->get_value('Y'), 0, rate, true); break;
479 case Z_AXIS: coordinated_move(0, 0, gcode->get_value('Z'), rate, true); break;
480 }
481
482 // coordinated_move returns when the move is finished
483
484 // disable probe checking
485 probing= false;
486 THEKERNEL->robot->disable_segmentation= false;
487
488 float pos[3];
489 {
490 // get the current position
491 ActuatorCoordinates current_position{
492 THEKERNEL->robot->actuators[X_AXIS]->get_current_position(),
493 THEKERNEL->robot->actuators[Y_AXIS]->get_current_position(),
494 THEKERNEL->robot->actuators[Z_AXIS]->get_current_position()
495 };
496
497 // get machine position from the actuator position using FK
498 THEKERNEL->robot->arm_solution->actuator_to_cartesian(current_position, pos);
499 }
500
501 uint8_t probeok= this->probe_detected ? 1 : 0;
502
503 // print results using the GRBL format
504 gcode->stream->printf("[PRB:%1.3f,%1.3f,%1.3f:%d]\n", pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], probeok);
505 THEKERNEL->robot->set_last_probe_position(std::make_tuple(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], probeok));
506
507 if(!probeok && gcode->subcode == 2) {
508 // issue error if probe was not triggered and subcode == 2
509 gcode->stream->printf("ALARM:Probe fail\n");
510 THEKERNEL->call_event(ON_HALT, nullptr);
511
512 }else if(probeok){
513 // if the probe stopped the move we need to correct the last_milestone as it did not reach where it thought
514 THEKERNEL->robot->reset_position_from_current_actuator_position();
515 }
516 }
517
518 // Called periodically to change the speed to match acceleration
519 void ZProbe::acceleration_tick(void)
520 {
521 if(!this->running) return; // nothing to do
522 if(STEPPER[Z_AXIS]->is_moving()) accelerate(Z_AXIS);
523
524 if(is_delta || is_rdelta) {
525 // deltas needs to move all actuators
526 for ( int c = X_AXIS; c <= Y_AXIS; c++ ) {
527 if( !STEPPER[c]->is_moving() ) continue;
528 accelerate(c);
529 }
530 }
531
532 return;
533 }
534
535 void ZProbe::accelerate(int c)
536 { uint32_t current_rate = STEPPER[c]->get_steps_per_second();
537 uint32_t target_rate = floorf(this->current_feedrate);
538
539 // Z may have a different acceleration to X and Y
540 float acc= (c==Z_AXIS) ? THEKERNEL->planner->get_z_acceleration() : THEKERNEL->planner->get_acceleration();
541 if( current_rate < target_rate ) {
542 uint32_t rate_increase = floorf((acc / THEKERNEL->acceleration_ticks_per_second) * STEPS_PER_MM(c));
543 current_rate = min( target_rate, current_rate + rate_increase );
544 }
545 if( current_rate > target_rate ) {
546 current_rate = target_rate;
547 }
548
549 // steps per second
550 STEPPER[c]->set_speed(current_rate);
551 }
552
553 // issue a coordinated move directly to robot, and return when done
554 // Only move the coordinates that are passed in as not nan
555 // NOTE must use G53 to force move in machine coordiantes and ignore any WCS offsetts
556 void ZProbe::coordinated_move(float x, float y, float z, float feedrate, bool relative)
557 {
558 char buf[32];
559 char cmd[64];
560
561 if(relative) strcpy(cmd, "G91 G0 ");
562 else strcpy(cmd, "G53 G0 "); // G53 forces movement in machine coordinate system
563
564 if(!isnan(x)) {
565 int n = snprintf(buf, sizeof(buf), " X%1.3f", x);
566 strncat(cmd, buf, n);
567 }
568 if(!isnan(y)) {
569 int n = snprintf(buf, sizeof(buf), " Y%1.3f", y);
570 strncat(cmd, buf, n);
571 }
572 if(!isnan(z)) {
573 int n = snprintf(buf, sizeof(buf), " Z%1.3f", z);
574 strncat(cmd, buf, n);
575 }
576
577 // use specified feedrate (mm/sec)
578 int n = snprintf(buf, sizeof(buf), " F%1.1f", feedrate * 60); // feed rate is converted to mm/min
579 strncat(cmd, buf, n);
580 if(relative) strcat(cmd, " G90");
581
582 //THEKERNEL->streams->printf("DEBUG: move: %s\n", cmd);
583
584 // send as a command line as may have multiple G codes in it
585 struct SerialMessage message;
586 message.message = cmd;
587 message.stream = &(StreamOutput::NullStream);
588 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message );
589 THEKERNEL->conveyor->wait_for_empty_queue();
590 }
591
592 // issue home command
593 void ZProbe::home()
594 {
595 Gcode gc("G28", &(StreamOutput::NullStream));
596 THEKERNEL->call_event(ON_GCODE_RECEIVED, &gc);
597 }
598
599 float ZProbe::zsteps_to_mm(float steps)
600 {
601 return steps / Z_STEPS_PER_MM;
602 }