Merge branch 'fix/inverse-transform' into feature/e-endstop
[clinton/Smoothieware.git] / src / modules / tools / endstops / Endstops.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 "libs/Module.h"
9 #include "libs/Kernel.h"
10 #include "modules/communication/utils/Gcode.h"
11 #include "modules/robot/Conveyor.h"
12 #include "modules/robot/ActuatorCoordinates.h"
13 #include "Endstops.h"
14 #include "libs/nuts_bolts.h"
15 #include "libs/Pin.h"
16 #include "libs/StepperMotor.h"
17 #include "wait_api.h" // mbed.h lib
18 #include "Robot.h"
19 #include "Config.h"
20 #include "SlowTicker.h"
21 #include "Planner.h"
22 #include "checksumm.h"
23 #include "utils.h"
24 #include "ConfigValue.h"
25 #include "libs/StreamOutput.h"
26 #include "PublicDataRequest.h"
27 #include "EndstopsPublicAccess.h"
28 #include "StreamOutputPool.h"
29 #include "StepTicker.h"
30 #include "BaseSolution.h"
31 #include "SerialMessage.h"
32
33 #include <ctype.h>
34
35 #define endstops_module_enable_checksum CHECKSUM("endstops_enable")
36 #define corexy_homing_checksum CHECKSUM("corexy_homing")
37 #define delta_homing_checksum CHECKSUM("delta_homing")
38 #define rdelta_homing_checksum CHECKSUM("rdelta_homing")
39 #define scara_homing_checksum CHECKSUM("scara_homing")
40
41 #define alpha_trim_checksum CHECKSUM("alpha_trim")
42 #define beta_trim_checksum CHECKSUM("beta_trim")
43 #define gamma_trim_checksum CHECKSUM("gamma_trim")
44
45 #define endstop_debounce_count_checksum CHECKSUM("endstop_debounce_count")
46 #define endstop_debounce_ms_checksum CHECKSUM("endstop_debounce_ms")
47
48 #define alpha_limit_enable_checksum CHECKSUM("alpha_limit_enable")
49 #define beta_limit_enable_checksum CHECKSUM("beta_limit_enable")
50 #define gamma_limit_enable_checksum CHECKSUM("gamma_limit_enable")
51
52 #define home_z_first_checksum CHECKSUM("home_z_first")
53 #define homing_order_checksum CHECKSUM("homing_order")
54 #define move_to_origin_checksum CHECKSUM("move_to_origin_after_home")
55
56 #define STEPPER THEROBOT->actuators
57 #define STEPS_PER_MM(a) (STEPPER[a]->get_steps_per_mm())
58
59 #define ENDSTOP_CHECKSUMS(X) { \
60 CHECKSUM(X "_min_endstop"), \
61 CHECKSUM(X "_max_endstop"), \
62 CHECKSUM(X "_max_travel"), \
63 CHECKSUM(X "_fast_homing_rate_mm_s"), \
64 CHECKSUM(X "_slow_homing_rate_mm_s"), \
65 CHECKSUM(X "_homing_retract_mm"), \
66 CHECKSUM(X "_homing_direction"), \
67 CHECKSUM(X "_min"), \
68 CHECKSUM(X "_max") \
69 }
70
71 // checksum defns
72 enum DEFNS {MIN_PIN, MAX_PIN, MAX_TRAVEL, FAST_RATE, SLOW_RATE, RETRACT, DIRECTION, MIN, MAX, NDEFNS};
73 enum PINS {MIN_X, MIN_Y, MIN_Z, MIN_A, MIN_B, MIN_C, MAX_X, MAX_Y, MAX_Z, MAX_A, MAX_B, MAX_C};
74
75 // Homing States
76 enum STATES {
77 MOVING_TO_ENDSTOP_FAST, // homing move
78 MOVING_TO_ENDSTOP_SLOW, // homing move
79 MOVING_BACK, // homing move
80 NOT_HOMING,
81 BACK_OFF_HOME,
82 MOVE_TO_ORIGIN,
83 LIMIT_TRIGGERED
84 };
85
86 static const char *endstop_names[] = {"min_x", "min_y", "min_z", "max_x", "max_y", "max_z"};
87 static const char axis_letters[] = {'X', 'Y', 'Z', 'A', 'B', 'C'};
88
89 Endstops::Endstops()
90 {
91 this->status = NOT_HOMING;
92 home_offset[0] = home_offset[1] = home_offset[2] = 0.0F;
93 debounce.fill(0);
94 homed.reset();
95 }
96
97 void Endstops::on_module_loaded()
98 {
99 // Do not do anything if not enabled
100 if ( THEKERNEL->config->value( endstops_module_enable_checksum )->by_default(true)->as_bool() == false ) {
101 delete this;
102 return;
103 }
104
105 register_for_event(ON_GCODE_RECEIVED);
106 register_for_event(ON_GET_PUBLIC_DATA);
107 register_for_event(ON_SET_PUBLIC_DATA);
108
109 // Settings
110 this->load_config();
111
112 THEKERNEL->slow_ticker->attach(1000, this, &Endstops::read_endstops);
113 }
114
115 // Get config
116 void Endstops::load_config()
117 {
118 uint16_t const checksums[][NDEFNS] = {
119 ENDSTOP_CHECKSUMS("alpha"), // X
120 ENDSTOP_CHECKSUMS("beta"), // Y
121 ENDSTOP_CHECKSUMS("gamma"), // Z
122 ENDSTOP_CHECKSUMS("delta"), // A
123 ENDSTOP_CHECKSUMS("epsilon"), // B
124 ENDSTOP_CHECKSUMS("zeta") // C
125 };
126
127 for (int i = X_AXIS; i <= C_AXIS; ++i) { // X_AXIS to C_AXIS
128 // pin definitions for X Y Z A B C min/max pins
129 bool found= false;
130 for (int j = MIN_PIN; j <= MAX_PIN; ++j) {
131 Pin *p= new Pin();
132 p->from_string(THEKERNEL->config->value(checksums[i][j])->by_default("nc" )->as_string())->as_input();
133 if(p->connected()){
134 // max pins have MSB set so 0x01 is Y_MIN and 0x81 is Y_MAX
135 uint8_t n= (j == MAX_PIN) ? 0x80 | i : i;
136 pins[n]= p; // this is a map
137 found= true;
138 }else{
139 delete p;
140 }
141 }
142
143 // if we are reding ABC pins and none defined no need to setup rest of config
144 if(i > Z_AXIS && !found) break;
145
146 // rates in mm/sec
147 this->fast_rates[i]= THEKERNEL->config->value(checksums[i][FAST_RATE])->by_default(100)->as_number();
148 this->slow_rates[i]= THEKERNEL->config->value(checksums[i][SLOW_RATE])->by_default(10)->as_number();
149
150 // retracts in mm
151 this->retract_mm[i]= THEKERNEL->config->value(checksums[i][RETRACT])->by_default(5)->as_number();
152
153 // get homing direction and convert to boolean where true is home to min, and false is home to max
154 this->home_direction[i]= THEKERNEL->config->value(checksums[i][DIRECTION])->by_default("home_to_min")->as_string() != "home_to_max";
155
156 // homing cartesian position
157 this->homing_position[i]= this->home_direction[i] ? THEKERNEL->config->value(checksums[i][MIN])->by_default(0)->as_number() : THEKERNEL->config->value(checksums[i][MAX])->by_default(200)->as_number();
158 }
159
160 // NOTE the debounce count is in milliseconds so probably does not need to beset anymore
161 this->debounce_ms= THEKERNEL->config->value(endstop_debounce_ms_checksum)->by_default(0)->as_number();
162 this->debounce_count= THEKERNEL->config->value(endstop_debounce_count_checksum)->by_default(100)->as_number();
163
164
165 // used to set maximum movement on homing, set by alpha_max_travel if defined
166 // for backward compatibility uses alpha_max if not defined.
167 // TO BE deprecated
168 this->alpha_max= THEKERNEL->config->value(checksums[X_AXIS][MAX])->by_default(500)->as_number();
169 this->beta_max= THEKERNEL->config->value(checksums[Y_AXIS][MAX])->by_default(500)->as_number();
170 this->gamma_max= THEKERNEL->config->value(checksums[Z_AXIS][MAX])->by_default(500)->as_number();
171
172 this->alpha_max= THEKERNEL->config->value(checksums[X_AXIS][MAX_TRAVEL])->by_default(alpha_max*2)->as_number();
173 this->beta_max= THEKERNEL->config->value(checksums[Y_AXIS][MAX_TRAVEL])->by_default(beta_max*2)->as_number();
174 this->gamma_max= THEKERNEL->config->value(checksums[Z_AXIS][MAX_TRAVEL])->by_default(gamma_max*2)->as_number();
175
176 this->is_corexy = THEKERNEL->config->value(corexy_homing_checksum)->by_default(false)->as_bool();
177 this->is_delta = THEKERNEL->config->value(delta_homing_checksum)->by_default(false)->as_bool();
178 this->is_rdelta = THEKERNEL->config->value(rdelta_homing_checksum)->by_default(false)->as_bool();
179 this->is_scara = THEKERNEL->config->value(scara_homing_checksum)->by_default(false)->as_bool();
180
181 this->home_z_first = THEKERNEL->config->value(home_z_first_checksum)->by_default(false)->as_bool();
182
183 // see if an order has been specified, must be three characters, XYZ or YXZ etc
184 string order = THEKERNEL->config->value(homing_order_checksum)->by_default("")->as_string();
185 this->homing_order = 0;
186 if(order.size() == 3 && !(this->is_delta || this->is_rdelta)) {
187 int shift = 0;
188 for(auto c : order) {
189 uint8_t i = toupper(c) - 'X';
190 if(i > 2) { // bad value
191 this->homing_order = 0;
192 break;
193 }
194 homing_order |= (i << shift);
195 shift += 2;
196 }
197 }
198
199 // endstop trim used by deltas to do soft adjusting
200 // on a delta homing to max, a negative trim value will move the carriage down, and a positive will move it up
201 this->trim_mm[0] = THEKERNEL->config->value(alpha_trim_checksum )->by_default(0 )->as_number();
202 this->trim_mm[1] = THEKERNEL->config->value(beta_trim_checksum )->by_default(0 )->as_number();
203 this->trim_mm[2] = THEKERNEL->config->value(gamma_trim_checksum )->by_default(0 )->as_number();
204
205 // limits enabled
206 this->limit_enable[X_AXIS] = THEKERNEL->config->value(alpha_limit_enable_checksum)->by_default(false)->as_bool();
207 this->limit_enable[Y_AXIS] = THEKERNEL->config->value(beta_limit_enable_checksum)->by_default(false)->as_bool();
208 this->limit_enable[Z_AXIS] = THEKERNEL->config->value(gamma_limit_enable_checksum)->by_default(false)->as_bool();
209
210 // set to true by default for deltas due to trim, false on cartesians
211 this->move_to_origin_after_home = THEKERNEL->config->value(move_to_origin_checksum)->by_default(is_delta)->as_bool();
212
213 if(this->limit_enable[X_AXIS] || this->limit_enable[Y_AXIS] || this->limit_enable[Z_AXIS]) {
214 register_for_event(ON_IDLE);
215 if(this->is_delta || this->is_rdelta) {
216 // we must enable all the limits not just one
217 this->limit_enable[X_AXIS] = true;
218 this->limit_enable[Y_AXIS] = true;
219 this->limit_enable[Z_AXIS] = true;
220 }
221 }
222
223 //
224 if(this->is_delta || this->is_rdelta) {
225 // some things must be the same or they will die, so force it here to avoid config errors
226 this->fast_rates[1] = this->fast_rates[2] = this->fast_rates[0];
227 this->slow_rates[1] = this->slow_rates[2] = this->slow_rates[0];
228 this->retract_mm[1] = this->retract_mm[2] = this->retract_mm[0];
229 this->home_direction[1] = this->home_direction[2] = this->home_direction[0];
230 // NOTE homing_position for rdelta is the angle of the actuator not the cartesian position
231 if(!this->is_rdelta) this->homing_position[0] = this->homing_position[1] = 0;
232 }
233 }
234
235 bool Endstops::debounced_get(uint8_t pin)
236 {
237 auto p= pins.find(pin);
238 if(p == pins.end()) return false;
239 uint8_t debounce = 0;
240 while(p->second->get()) {
241 if ( ++debounce >= this->debounce_count ) {
242 // pin triggered
243 return true;
244 }
245 }
246 return false;
247 }
248
249 void Endstops::on_idle(void *argument)
250 {
251 if(this->status == LIMIT_TRIGGERED) {
252 // if we were in limit triggered see if it has been cleared
253 for( int c = X_AXIS; c <= Z_AXIS; c++ ) {
254 if(this->limit_enable[c]) {
255 std::array<int, 2> minmax{{c, 0x80|c}};
256 // check min and max endstops
257 for (int i : minmax) {
258 auto p= pins.find(i);
259 if(p != pins.end() && p->second->get()) {
260 // still triggered, so exit
261 bounce_cnt = 0;
262 return;
263 }
264 }
265 }
266 }
267 if(++bounce_cnt > 10) { // can use less as it calls on_idle in between
268 // clear the state
269 this->status = NOT_HOMING;
270 }
271 return;
272
273 } else if(this->status != NOT_HOMING) {
274 // don't check while homing
275 return;
276 }
277
278 for( int c = X_AXIS; c <= Z_AXIS; c++ ) {
279 if(this->limit_enable[c] && STEPPER[c]->is_moving()) {
280 std::array<int, 2> minmax{{c, 0x80|c}};
281 // check min and max endstops
282 for (int i : minmax) {
283 if(debounced_get(i)) {
284 // endstop triggered
285 int n= i&0x80 ? i+3 : i;
286 THEKERNEL->streams->printf("Limit switch %s was hit - reset or M999 required\n", endstop_names[n]);
287 this->status = LIMIT_TRIGGERED;
288 // disables heaters and motors, ignores incoming Gcode and flushes block queue
289 THEKERNEL->call_event(ON_HALT, nullptr);
290 return;
291 }
292 }
293 }
294 }
295 }
296
297 // if limit switches are enabled, then we must move off of the endstop otherwise we won't be able to move
298 // checks if triggered and only backs off if triggered
299 void Endstops::back_off_home(std::bitset<6> axis)
300 {
301 std::vector<std::pair<char, float>> params;
302 this->status = BACK_OFF_HOME;
303
304 // these are handled differently
305 if(is_delta) {
306 // Move off of the endstop using a regular relative move in Z only
307 params.push_back({'Z', this->retract_mm[Z_AXIS] * (this->home_direction[Z_AXIS] ? 1 : -1)});
308
309 } else {
310 // cartesians, concatenate all the moves we need to do into one gcode
311 for( int c = X_AXIS; c <= Z_AXIS; c++ ) {
312 if(!axis[c]) continue; // only for axes we asked to move
313
314 // if not triggered no need to move off
315 if(this->limit_enable[c] && debounced_get(c + (this->home_direction[c] ? 0 : 3)) ) {
316 params.push_back({c + 'X', this->retract_mm[c] * (this->home_direction[c] ? 1 : -1)});
317 }
318 }
319 }
320
321 if(!params.empty()) {
322 // Move off of the endstop using a regular relative move
323 params.insert(params.begin(), {'G', 0});
324 // use X slow rate to move, Z should have a max speed set anyway
325 params.push_back({'F', this->slow_rates[X_AXIS] * 60.0F});
326 char gcode_buf[64];
327 append_parameters(gcode_buf, params, sizeof(gcode_buf));
328 Gcode gc(gcode_buf, &(StreamOutput::NullStream));
329 THEROBOT->push_state();
330 THEROBOT->inch_mode = false; // needs to be in mm
331 THEROBOT->absolute_mode = false; // needs to be relative mode
332 THEROBOT->on_gcode_received(&gc); // send to robot directly
333 // Wait for above to finish
334 THECONVEYOR->wait_for_idle();
335 THEROBOT->pop_state();
336 }
337
338 this->status = NOT_HOMING;
339 }
340
341 // If enabled will move the head to 0,0 after homing, but only if X and Y were set to home
342 void Endstops::move_to_origin(std::bitset<6> axis)
343 {
344 if(!is_delta && (!axis[X_AXIS] || !axis[Y_AXIS])) return; // ignore if X and Y not homing, unless delta
345
346 // Do we need to check if we are already at 0,0? probably not as the G0 will not do anything if we are
347 // float pos[3]; THEROBOT->get_axis_position(pos); if(pos[0] == 0 && pos[1] == 0) return;
348
349 this->status = MOVE_TO_ORIGIN;
350 // Move to center using a regular move, use slower of X and Y fast rate
351 float rate = std::min(this->fast_rates[0], this->fast_rates[1]) * 60.0F;
352 char buf[32];
353 THEROBOT->push_state();
354 THEROBOT->inch_mode = false; // needs to be in mm
355 THEROBOT->absolute_mode = true;
356 snprintf(buf, sizeof(buf), "G53 G0 X0 Y0 F%1.4f", rate); // must use machine coordinates in case G92 or WCS is in effect
357 struct SerialMessage message;
358 message.message = buf;
359 message.stream = &(StreamOutput::NullStream);
360 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message ); // as it is a multi G code command
361 // Wait for above to finish
362 THECONVEYOR->wait_for_idle();
363 THEROBOT->pop_state();
364 this->status = NOT_HOMING;
365 }
366
367 // Called every millisecond in an ISR
368 uint32_t Endstops::read_endstops(uint32_t dummy)
369 {
370 if(this->status != MOVING_TO_ENDSTOP_SLOW && this->status != MOVING_TO_ENDSTOP_FAST) return 0; // not doing anything we need to monitor for
371
372 if(!is_corexy) {
373 // check each axis
374 for ( int m = X_AXIS; m <= C_AXIS; m++ ) { // check XYZABC
375 auto p= pins.find(this->home_direction[m] ? m : 0x80|m);
376 if(p == pins.end()) continue;
377
378 if(STEPPER[m]->is_moving()) {
379 // if it is moving then we check the associated endstop, and debounce it
380 if(p->second->get()) {
381 if(debounce[m] < debounce_ms) {
382 debounce[m]++;
383 } else {
384 // we signal the motor to stop, which will preempt any moves on that axis
385 STEPPER[m]->stop_moving();
386 }
387
388 } else {
389 // The endstop was not hit yet
390 debounce[m] = 0;
391 }
392 }
393 }
394
395 } else {
396 // corexy is different as the actuators are not directly related to the XY axis
397 // so we check the axis that is currently homing then stop all motors
398 for ( int m = X_AXIS; m <= C_AXIS; m++ ) {
399 auto p= pins.find(this->home_direction[m] ? m : 0x80|m);
400 if(p == pins.end()) continue;
401 if(axis_to_home[m]) {
402 if(p->second->get()) {
403 if(debounce[m] < debounce_ms) {
404 debounce[m]++;
405 } else {
406 // we signal all the motors to stop, as on corexy X and Y motors will move for X and Y axis homing and we only hom eone axis at a time
407 STEPPER[X_AXIS]->stop_moving();
408 STEPPER[Y_AXIS]->stop_moving();
409 STEPPER[Z_AXIS]->stop_moving();
410 }
411
412 } else {
413 // The endstop was not hit yet
414 debounce[m] = 0;
415 }
416 }
417 }
418 }
419
420 return 0;
421 }
422
423 void Endstops::home_xy()
424 {
425 if(axis_to_home[X_AXIS] && axis_to_home[Y_AXIS]) {
426 // Home XY first so as not to slow them down by homing Z at the same time
427 float delta[3] {alpha_max, beta_max, 0};
428 if(this->home_direction[X_AXIS]) delta[X_AXIS]= -delta[X_AXIS];
429 if(this->home_direction[Y_AXIS]) delta[Y_AXIS]= -delta[Y_AXIS];
430 float feed_rate = std::min(fast_rates[X_AXIS], fast_rates[Y_AXIS]);
431 THEROBOT->delta_move(delta, feed_rate, 3);
432
433 } else if(axis_to_home[X_AXIS]) {
434 // now home X only
435 float delta[3] {alpha_max, 0, 0};
436 if(this->home_direction[X_AXIS]) delta[X_AXIS]= -delta[X_AXIS];
437 THEROBOT->delta_move(delta, fast_rates[X_AXIS], 3);
438
439 } else if(axis_to_home[Y_AXIS]) {
440 // now home Y only
441 float delta[3] {0, beta_max, 0};
442 if(this->home_direction[Y_AXIS]) delta[Y_AXIS]= -delta[Y_AXIS];
443 THEROBOT->delta_move(delta, fast_rates[Y_AXIS], 3);
444 }
445
446 // Wait for axis to have homed
447 THECONVEYOR->wait_for_idle();
448 }
449
450 void Endstops::home(std::bitset<6> a)
451 {
452 // reset debounce counts
453 debounce.fill(0);
454
455 // turn off any compensation transform so Z does not move as XY home
456 auto savect= THEROBOT->compensationTransform;
457 THEROBOT->compensationTransform= nullptr;
458
459 this->axis_to_home= a;
460
461 // Start moving the axes to the origin
462 this->status = MOVING_TO_ENDSTOP_FAST;
463
464 THEROBOT->disable_segmentation= true; // we must disable segmentation as this won't work with it enabled
465
466 if(!home_z_first) home_xy();
467
468 if(axis_to_home[Z_AXIS]) {
469 // now home z
470 float delta[3] {0, 0, gamma_max}; // we go the max z
471 if(this->home_direction[Z_AXIS]) delta[Z_AXIS]= -delta[Z_AXIS];
472 THEROBOT->delta_move(delta, fast_rates[Z_AXIS], 3);
473 // wait for Z
474 THECONVEYOR->wait_for_idle();
475 }
476
477 if(home_z_first) home_xy();
478
479 //TODO need to add BC
480 if(axis_to_home[A_AXIS]) {
481 // now home A
482 float delta[4] {0, 0, 0, epsilon_max}; // we go the max A
483 if(this->home_direction[A_AXIS]) delta[A_AXIS]= -delta[A_AXIS];
484 THEROBOT->delta_move(delta, fast_rates[A_AXIS], 4);
485 // wait for Z
486 THECONVEYOR->wait_for_idle();
487 }
488
489
490 // TODO should check that the endstops were hit and it did not stop short for some reason
491 // we did not complete movement the full distance if we hit the endstops
492 THEROBOT->reset_position_from_current_actuator_position();
493
494 // Move back a small distance for all homing axis
495 this->status = MOVING_BACK;
496 float delta[3]{0,0,0};
497 // use minimum feed rate of all three axes that are being homed (sub optimal, but necessary)
498 float feed_rate= slow_rates[X_AXIS];
499 for ( int c = X_AXIS; c <= Z_AXIS; c++ ) {
500 if(axis_to_home[c]) {
501 delta[c]= this->retract_mm[c];
502 if(!this->home_direction[c]) delta[c]= -delta[c];
503 feed_rate= std::min(slow_rates[c], feed_rate);
504 }
505 }
506
507 THEROBOT->delta_move(delta, feed_rate, 3);
508 // wait until finished
509 THECONVEYOR->wait_for_idle();
510
511 // Start moving the axes towards the endstops slowly
512 this->status = MOVING_TO_ENDSTOP_SLOW;
513 for ( int c = X_AXIS; c <= Z_AXIS; c++ ) {
514 if(axis_to_home[c]) {
515 delta[c]= this->retract_mm[c]*2; // move further than we moved off to make sure we hit it cleanly
516 if(this->home_direction[c]) delta[c]= -delta[c];
517 }else{
518 delta[c]= 0;
519 }
520 }
521 THEROBOT->delta_move(delta, feed_rate, 3);
522 // wait until finished
523 THECONVEYOR->wait_for_idle();
524
525 // TODO should check that the endstops were hit and it did not stop short for some reason
526 // we did not complete movement the full distance if we hit the endstops
527 THEROBOT->reset_position_from_current_actuator_position();
528
529 THEROBOT->disable_segmentation= false;
530
531 // restore compensationTransform
532 THEROBOT->compensationTransform= savect;
533
534 this->status = NOT_HOMING;
535 }
536
537 void Endstops::process_home_command(Gcode* gcode)
538 {
539 if( (gcode->subcode == 0 && THEKERNEL->is_grbl_mode()) || (gcode->subcode == 2 && !THEKERNEL->is_grbl_mode()) ) {
540 // G28 in grbl mode or G28.2 in normal mode will do a rapid to the predefined position
541 // TODO spec says if XYZ specified move to them first then move to MCS of specifed axis
542 THEROBOT->push_state();
543 THEROBOT->inch_mode = false; // needs to be in mm
544 THEROBOT->absolute_mode = true;
545 char buf[32];
546 snprintf(buf, sizeof(buf), "G53 G0 X%f Y%f", saved_position[X_AXIS], saved_position[Y_AXIS]); // must use machine coordinates in case G92 or WCS is in effect
547 struct SerialMessage message;
548 message.message = buf;
549 message.stream = &(StreamOutput::NullStream);
550 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message ); // as it is a multi G code command
551 // Wait for above to finish
552 THECONVEYOR->wait_for_idle();
553 THEROBOT->pop_state();
554 return;
555
556 } else if(THEKERNEL->is_grbl_mode() && gcode->subcode == 2) { // G28.2 in grbl mode forces homing (triggered by $H)
557 // fall through so it does homing cycle
558
559 } else if(gcode->subcode == 1) { // G28.1 set pre defined position
560 // saves current position in absolute machine coordinates
561 THEROBOT->get_axis_position(saved_position); // Only XY are used
562 // Note the following is only meant to be used for recovering a saved position from config-override
563 // Not a standard Gcode and not to be relied on
564 if (gcode->has_letter('X')) saved_position[X_AXIS] = gcode->get_value('X');
565 if (gcode->has_letter('Y')) saved_position[Y_AXIS] = gcode->get_value('Y');
566 return;
567
568 } else if(gcode->subcode == 3) { // G28.3 is a smoothie special it sets manual homing
569 if(gcode->get_num_args() == 0) {
570 THEROBOT->reset_axis_position(0, 0, 0);
571 homed.set();
572 } else {
573 // do a manual homing based on given coordinates, no endstops required
574 if(gcode->has_letter('X')){ THEROBOT->reset_axis_position(gcode->get_value('X'), X_AXIS); homed.set(X_AXIS); }
575 if(gcode->has_letter('Y')){ THEROBOT->reset_axis_position(gcode->get_value('Y'), Y_AXIS); homed.set(Y_AXIS); }
576 if(gcode->has_letter('Z')){ THEROBOT->reset_axis_position(gcode->get_value('Z'), Z_AXIS); homed.set(Z_AXIS); }
577 }
578 return;
579
580 } else if(gcode->subcode == 4) { // G28.4 is a smoothie special it sets manual homing based on the actuator position (used for rotary delta)
581 // do a manual homing based on given coordinates, no endstops required
582 ActuatorCoordinates ac{NAN, NAN, NAN};
583 if(gcode->has_letter('X')){ ac[0] = gcode->get_value('X'); homed.set(X_AXIS); }
584 if(gcode->has_letter('Y')){ ac[1] = gcode->get_value('Y'); homed.set(Y_AXIS); }
585 if(gcode->has_letter('Z')){ ac[2] = gcode->get_value('Z'); homed.set(Z_AXIS); }
586 THEROBOT->reset_actuator_position(ac);
587 return;
588
589 } else if(gcode->subcode == 5) { // G28.5 is a smoothie special it clears the homed flag for the specified axis, or all if not specifed
590 if(gcode->get_num_args() == 0) {
591 homed.reset();
592 } else {
593 if(gcode->has_letter('X')) homed.reset(X_AXIS);
594 if(gcode->has_letter('Y')) homed.reset(Y_AXIS);
595 if(gcode->has_letter('Z')) homed.reset(Z_AXIS);
596 }
597 return;
598
599 } else if(gcode->subcode == 6) { // G28.6 is a smoothie special it shows the homing status of each axis
600 for (int i = 0; i < 3; ++i) {
601 gcode->stream->printf("%c:%d ", 'X'+i, homed.test(i));
602 }
603 gcode->add_nl= true;
604 return;
605
606 } else if(THEKERNEL->is_grbl_mode()) {
607 gcode->stream->printf("error:Unsupported command\n");
608 return;
609 }
610
611 // G28 is received, we have homing to do
612
613 // First wait for the queue to be empty
614 THECONVEYOR->wait_for_idle();
615
616 // deltas always home Z axis only, which moves all three actuators
617 bool home_in_z = this->is_delta || this->is_rdelta;
618
619 // figure out which axis to home
620 bitset<6> haxis;
621 haxis.reset();
622
623 if(!home_in_z) { // ie not a delta
624 bool axis_speced = (gcode->has_letter('X') || gcode->has_letter('Y') || gcode->has_letter('Z') ||
625 gcode->has_letter('A') || gcode->has_letter('B') || gcode->has_letter('C'));
626 // only enable homing if the endstop is defined,
627 for ( int c = X_AXIS; c <= C_AXIS; c++ ) {
628 auto p= pins.find(this->home_direction[c] ? c : 0x80|c);
629 if(p != pins.end() && (!axis_speced || gcode->has_letter(axis_letters[c])) ) {
630 haxis.set(c);
631 // now reset axis to 0 as we do not know what state we are in
632 THEROBOT->reset_axis_position(0, c);
633 }
634 }
635
636 } else {
637 // Only Z axis homes (even though all actuators move this is handled by arm solution)
638 haxis.set(Z_AXIS);
639 // we also set the kinematics to a known good position, this is necessary for a rotary delta, but doesn't hurt for linear delta
640 THEROBOT->reset_axis_position(0, 0, 0);
641 }
642
643 // do the actual homing
644 if(homing_order != 0) {
645 // if an order has been specified do it in the specified order
646 // homing order is 0b00ccbbaa where aa is 0,1,2 to specify the first axis, bb is the second and cc is the third
647 // eg 0b00100001 would be Y X Z, 0b00100100 would be X Y Z
648 for (uint8_t m = homing_order; m != 0; m >>= 2) {
649 int a= (m & 0x03); // axis to home
650 if(haxis[a]) { // if axis is selected to home
651 std::bitset<6> bs;
652 bs.set(a);
653 home(bs);
654 }
655 // check if on_halt (eg kill)
656 if(THEKERNEL->is_halted()) break;
657 }
658
659 } else if(is_corexy) {
660 // corexy must home each axis individually
661 for (int a = X_AXIS; a <= C_AXIS; ++a) {
662 if(haxis[a]) {
663 std::bitset<6> bs;
664 bs.set(a);
665 home(bs);
666 }
667 }
668
669 } else {
670 // they could all home at the same time
671 home(haxis);
672 }
673
674 // check if on_halt (eg kill)
675 if(THEKERNEL->is_halted()) {
676 if(!THEKERNEL->is_grbl_mode()) {
677 THEKERNEL->streams->printf("Homing cycle aborted by kill\n");
678 }
679 homed.reset();
680 return;
681 }
682
683 if(home_in_z) { // deltas only
684 // Here's where we would have been if the endstops were perfectly trimmed
685 // NOTE on a rotary delta home_offset is actuator position in degrees when homed and
686 // home_offset is the theta offset for each actuator, so M206 is used to set theta offset for each actuator in degrees
687 // FIXME not sure this will work with compensation transforms on.
688 float ideal_position[3] = {
689 this->homing_position[X_AXIS] + this->home_offset[X_AXIS],
690 this->homing_position[Y_AXIS] + this->home_offset[Y_AXIS],
691 this->homing_position[Z_AXIS] + this->home_offset[Z_AXIS]
692 };
693
694 bool has_endstop_trim = this->is_delta;
695 if (has_endstop_trim) {
696 ActuatorCoordinates ideal_actuator_position;
697 THEROBOT->arm_solution->cartesian_to_actuator(ideal_position, ideal_actuator_position);
698
699 // We are actually not at the ideal position, but a trim away
700 ActuatorCoordinates real_actuator_position = {
701 ideal_actuator_position[X_AXIS] - this->trim_mm[X_AXIS],
702 ideal_actuator_position[Y_AXIS] - this->trim_mm[Y_AXIS],
703 ideal_actuator_position[Z_AXIS] - this->trim_mm[Z_AXIS]
704 };
705
706 float real_position[3];
707 THEROBOT->arm_solution->actuator_to_cartesian(real_actuator_position, real_position);
708 // Reset the actuator positions to correspond our real position
709 THEROBOT->reset_axis_position(real_position[0], real_position[1], real_position[2]);
710
711 } else {
712 // without endstop trim, real_position == ideal_position
713 if(is_rdelta) {
714 // with a rotary delta we set the actuators angle then use the FK to calculate the resulting cartesian coordinates
715 ActuatorCoordinates real_actuator_position = {ideal_position[0], ideal_position[1], ideal_position[2]};
716 THEROBOT->reset_actuator_position(real_actuator_position);
717
718 } else {
719 // Reset the actuator positions to correspond our real position
720 THEROBOT->reset_axis_position(ideal_position[0], ideal_position[1], ideal_position[2]);
721 }
722 }
723
724 homed.set(); // for deltas we say all axis are homed even though it was only Z
725
726 } else {
727 // Zero the ax(i/e)s position, add in the home offset
728 // NOTE that if compensation is active the Z will be set based on where XY are, so make sure XY are homed first then Z
729 // so XY are at a known consistent position. (especially true if using a proximity probe)
730 for ( int c = X_AXIS; c <= C_AXIS; c++ ) {
731 if (haxis[c]) { // if we requested this axis to home
732 THEROBOT->reset_axis_position(this->homing_position[c] + this->home_offset[c], c);
733 // set flag indicating axis was homed, it stays set once set until H/W reset or unhomed
734 homed.set(c);
735 }
736 }
737 }
738
739 // on some systems where 0,0 is bed center it is nice to have home goto 0,0 after homing
740 // default is off for cartesian on for deltas
741 if(!is_delta) {
742 // NOTE a rotary delta usually has optical or hall-effect endstops so it is safe to go past them a little bit
743 if(this->move_to_origin_after_home) move_to_origin(haxis);
744 // if limit switches are enabled we must back off endstop after setting home
745 back_off_home(haxis);
746
747 } else if(this->move_to_origin_after_home || this->limit_enable[X_AXIS]) {
748 // deltas are not left at 0,0 because of the trim settings, so move to 0,0 if requested, but we need to back off endstops first
749 // also need to back off endstops if limits are enabled
750 back_off_home(haxis);
751 if(this->move_to_origin_after_home) move_to_origin(haxis);
752 }
753 }
754
755 void Endstops::set_homing_offset(Gcode *gcode)
756 {
757 // Similar to M206 but sets Homing offsets based on current MCS position
758 // Basically it finds the delta between the current MCS position and the requested position and adds it to the homing offset
759 // then will not let it be set again until that axis is homed.
760 float pos[3];
761 THEROBOT->get_axis_position(pos);
762
763 if (gcode->has_letter('X')) {
764 if(!homed[X_AXIS]) {
765 gcode->stream->printf("error: Axis X must be homed before setting Homing offset\n");
766 return;
767 }
768 home_offset[0] += (THEROBOT->to_millimeters(gcode->get_value('X')) - pos[X_AXIS]);
769 homed.reset(X_AXIS); // force it to be homed
770 }
771 if (gcode->has_letter('Y')) {
772 if(!homed[Y_AXIS]) {
773 gcode->stream->printf("error: Axis Y must be homed before setting Homing offset\n");
774 return;
775 }
776 home_offset[1] += (THEROBOT->to_millimeters(gcode->get_value('Y')) - pos[Y_AXIS]);
777 homed.reset(Y_AXIS); // force it to be homed
778 }
779 if (gcode->has_letter('Z')) {
780 if(!homed[Z_AXIS]) {
781 gcode->stream->printf("error: Axis Z must be homed before setting Homing offset\n");
782 return;
783 }
784 home_offset[2] += (THEROBOT->to_millimeters(gcode->get_value('Z')) - pos[Z_AXIS]);
785 homed.reset(Z_AXIS); // force it to be homed
786 }
787
788 gcode->stream->printf("Homing Offset: X %5.3f Y %5.3f Z %5.3f will take effect next home\n", home_offset[0], home_offset[1], home_offset[2]);
789 }
790
791 // Start homing sequences by response to GCode commands
792 void Endstops::on_gcode_received(void *argument)
793 {
794 Gcode *gcode = static_cast<Gcode *>(argument);
795 if ( gcode->has_g && gcode->g == 28) {
796 process_home_command(gcode);
797
798 } else if (gcode->has_m) {
799
800 switch (gcode->m) {
801 case 119: {
802 for(auto& p : pins) {
803 if(p.second->connected()) {
804 int i= (p.first&0x80) ? (p.first&0x7F) + 3 : p.first;
805 gcode->stream->printf("%s:%d ", endstop_names[i], p.second->get());
806 }
807 }
808 gcode->add_nl = true;
809 }
810 break;
811
812 case 206: // M206 - set homing offset
813 if(is_rdelta) return; // RotaryDeltaCalibration module will handle this
814
815 if (gcode->has_letter('X')) home_offset[0] = gcode->get_value('X');
816 if (gcode->has_letter('Y')) home_offset[1] = gcode->get_value('Y');
817 if (gcode->has_letter('Z')) home_offset[2] = gcode->get_value('Z');
818 gcode->stream->printf("X %5.3f Y %5.3f Z %5.3f will take effect next home\n", home_offset[0], home_offset[1], home_offset[2]);
819 break;
820
821 case 306: // set homing offset based on current position
822 if(is_rdelta) return; // RotaryDeltaCalibration module will handle this
823
824 set_homing_offset(gcode);
825 break;
826
827 case 500: // save settings
828 case 503: // print settings
829 if(!is_rdelta)
830 gcode->stream->printf(";Home offset (mm):\nM206 X%1.2f Y%1.2f Z%1.2f\n", home_offset[0], home_offset[1], home_offset[2]);
831 else
832 gcode->stream->printf(";Theta offset (degrees):\nM206 A%1.5f B%1.5f C%1.5f\n", home_offset[0], home_offset[1], home_offset[2]);
833
834 if (this->is_delta || this->is_scara) {
835 gcode->stream->printf(";Trim (mm):\nM666 X%1.3f Y%1.3f Z%1.3f\n", trim_mm[0], trim_mm[1], trim_mm[2]);
836 gcode->stream->printf(";Max Z\nM665 Z%1.3f\n", this->homing_position[2]);
837 }
838 if(saved_position[X_AXIS] != 0 || saved_position[Y_AXIS] != 0) {
839 gcode->stream->printf(";predefined position:\nG28.1 X%1.4f Y%1.4f\n", saved_position[X_AXIS], saved_position[Y_AXIS]);
840 }
841 break;
842
843 case 665:
844 if (this->is_delta || this->is_scara) { // M665 - set max gamma/z height
845 float gamma_max = this->homing_position[2];
846 if (gcode->has_letter('Z')) {
847 this->homing_position[2] = gamma_max = gcode->get_value('Z');
848 }
849 gcode->stream->printf("Max Z %8.3f ", gamma_max);
850 gcode->add_nl = true;
851 }
852 break;
853
854 case 666:
855 if(this->is_delta || this->is_scara) { // M666 - set trim for each axis in mm, NB negative mm trim is down
856 if (gcode->has_letter('X')) trim_mm[0] = gcode->get_value('X');
857 if (gcode->has_letter('Y')) trim_mm[1] = gcode->get_value('Y');
858 if (gcode->has_letter('Z')) trim_mm[2] = gcode->get_value('Z');
859
860 // print the current trim values in mm
861 gcode->stream->printf("X: %5.3f Y: %5.3f Z: %5.3f\n", trim_mm[0], trim_mm[1], trim_mm[2]);
862
863 }
864 break;
865
866 }
867 }
868 }
869
870 void Endstops::on_get_public_data(void* argument)
871 {
872 PublicDataRequest* pdr = static_cast<PublicDataRequest*>(argument);
873
874 if(!pdr->starts_with(endstops_checksum)) return;
875
876 if(pdr->second_element_is(trim_checksum)) {
877 pdr->set_data_ptr(&this->trim_mm);
878 pdr->set_taken();
879
880 } else if(pdr->second_element_is(home_offset_checksum)) {
881 pdr->set_data_ptr(&this->home_offset);
882 pdr->set_taken();
883
884 } else if(pdr->second_element_is(saved_position_checksum)) {
885 pdr->set_data_ptr(&this->saved_position);
886 pdr->set_taken();
887
888 } else if(pdr->second_element_is(get_homing_status_checksum)) {
889 bool *homing = static_cast<bool *>(pdr->get_data_ptr());
890 *homing = this->status != NOT_HOMING;
891 pdr->set_taken();
892 }
893 }
894
895 void Endstops::on_set_public_data(void* argument)
896 {
897 PublicDataRequest* pdr = static_cast<PublicDataRequest*>(argument);
898
899 if(!pdr->starts_with(endstops_checksum)) return;
900
901 if(pdr->second_element_is(trim_checksum)) {
902 float *t = static_cast<float*>(pdr->get_data_ptr());
903 this->trim_mm[0] = t[0];
904 this->trim_mm[1] = t[1];
905 this->trim_mm[2] = t[2];
906 pdr->set_taken();
907
908 } else if(pdr->second_element_is(home_offset_checksum)) {
909 float *t = static_cast<float*>(pdr->get_data_ptr());
910 if(!isnan(t[0])) this->home_offset[0] = t[0];
911 if(!isnan(t[1])) this->home_offset[1] = t[1];
912 if(!isnan(t[2])) this->home_offset[2] = t[2];
913 }
914 }