rewrite extruder to handle new core system
[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 ALPHA_AXIS 0
36 #define BETA_AXIS 1
37 #define GAMMA_AXIS 2
38 #define X_AXIS 0
39 #define Y_AXIS 1
40 #define Z_AXIS 2
41
42 #define endstops_module_enable_checksum CHECKSUM("endstops_enable")
43 #define corexy_homing_checksum CHECKSUM("corexy_homing")
44 #define delta_homing_checksum CHECKSUM("delta_homing")
45 #define rdelta_homing_checksum CHECKSUM("rdelta_homing")
46 #define scara_homing_checksum CHECKSUM("scara_homing")
47
48 #define alpha_min_endstop_checksum CHECKSUM("alpha_min_endstop")
49 #define beta_min_endstop_checksum CHECKSUM("beta_min_endstop")
50 #define gamma_min_endstop_checksum CHECKSUM("gamma_min_endstop")
51
52 #define alpha_max_endstop_checksum CHECKSUM("alpha_max_endstop")
53 #define beta_max_endstop_checksum CHECKSUM("beta_max_endstop")
54 #define gamma_max_endstop_checksum CHECKSUM("gamma_max_endstop")
55
56 #define alpha_trim_checksum CHECKSUM("alpha_trim")
57 #define beta_trim_checksum CHECKSUM("beta_trim")
58 #define gamma_trim_checksum CHECKSUM("gamma_trim")
59
60 // these values are in steps and should be deprecated
61 #define alpha_fast_homing_rate_checksum CHECKSUM("alpha_fast_homing_rate")
62 #define beta_fast_homing_rate_checksum CHECKSUM("beta_fast_homing_rate")
63 #define gamma_fast_homing_rate_checksum CHECKSUM("gamma_fast_homing_rate")
64
65 #define alpha_slow_homing_rate_checksum CHECKSUM("alpha_slow_homing_rate")
66 #define beta_slow_homing_rate_checksum CHECKSUM("beta_slow_homing_rate")
67 #define gamma_slow_homing_rate_checksum CHECKSUM("gamma_slow_homing_rate")
68
69 #define alpha_homing_retract_checksum CHECKSUM("alpha_homing_retract")
70 #define beta_homing_retract_checksum CHECKSUM("beta_homing_retract")
71 #define gamma_homing_retract_checksum CHECKSUM("gamma_homing_retract")
72
73 // same as above but in user friendly mm/s and mm
74 #define alpha_fast_homing_rate_mm_checksum CHECKSUM("alpha_fast_homing_rate_mm_s")
75 #define beta_fast_homing_rate_mm_checksum CHECKSUM("beta_fast_homing_rate_mm_s")
76 #define gamma_fast_homing_rate_mm_checksum CHECKSUM("gamma_fast_homing_rate_mm_s")
77
78 #define alpha_slow_homing_rate_mm_checksum CHECKSUM("alpha_slow_homing_rate_mm_s")
79 #define beta_slow_homing_rate_mm_checksum CHECKSUM("beta_slow_homing_rate_mm_s")
80 #define gamma_slow_homing_rate_mm_checksum CHECKSUM("gamma_slow_homing_rate_mm_s")
81
82 #define alpha_homing_retract_mm_checksum CHECKSUM("alpha_homing_retract_mm")
83 #define beta_homing_retract_mm_checksum CHECKSUM("beta_homing_retract_mm")
84 #define gamma_homing_retract_mm_checksum CHECKSUM("gamma_homing_retract_mm")
85
86 #define endstop_debounce_count_checksum CHECKSUM("endstop_debounce_count")
87 #define endstop_debounce_ms_checksum CHECKSUM("endstop_debounce_ms")
88
89 #define alpha_homing_direction_checksum CHECKSUM("alpha_homing_direction")
90 #define beta_homing_direction_checksum CHECKSUM("beta_homing_direction")
91 #define gamma_homing_direction_checksum CHECKSUM("gamma_homing_direction")
92 #define home_to_max_checksum CHECKSUM("home_to_max")
93 #define home_to_min_checksum CHECKSUM("home_to_min")
94 #define alpha_min_checksum CHECKSUM("alpha_min")
95 #define beta_min_checksum CHECKSUM("beta_min")
96 #define gamma_min_checksum CHECKSUM("gamma_min")
97
98 #define alpha_max_checksum CHECKSUM("alpha_max")
99 #define beta_max_checksum CHECKSUM("beta_max")
100 #define gamma_max_checksum CHECKSUM("gamma_max")
101
102 #define alpha_limit_enable_checksum CHECKSUM("alpha_limit_enable")
103 #define beta_limit_enable_checksum CHECKSUM("beta_limit_enable")
104 #define gamma_limit_enable_checksum CHECKSUM("gamma_limit_enable")
105
106 #define homing_order_checksum CHECKSUM("homing_order")
107 #define move_to_origin_checksum CHECKSUM("move_to_origin_after_home")
108
109 #define STEPPER THEROBOT->actuators
110 #define STEPS_PER_MM(a) (STEPPER[a]->get_steps_per_mm())
111
112
113 // Homing States
114 enum {
115 MOVING_TO_ENDSTOP_FAST, // homing move
116 MOVING_TO_ENDSTOP_SLOW, // homing move
117 MOVING_BACK, // homing move
118 NOT_HOMING,
119 BACK_OFF_HOME,
120 MOVE_TO_ORIGIN,
121 LIMIT_TRIGGERED
122 };
123
124 Endstops::Endstops()
125 {
126 this->status = NOT_HOMING;
127 home_offset[0] = home_offset[1] = home_offset[2] = 0.0F;
128 debounce.fill(0);
129 }
130
131 void Endstops::on_module_loaded()
132 {
133 // Do not do anything if not enabled
134 if ( THEKERNEL->config->value( endstops_module_enable_checksum )->by_default(true)->as_bool() == false ) {
135 delete this;
136 return;
137 }
138
139 register_for_event(ON_GCODE_RECEIVED);
140 register_for_event(ON_GET_PUBLIC_DATA);
141 register_for_event(ON_SET_PUBLIC_DATA);
142
143 // Settings
144 this->load_config();
145
146 THEKERNEL->slow_ticker->attach(1000, this, &Endstops::read_endstops);
147 }
148
149 // Get config
150 void Endstops::load_config()
151 {
152 this->pins[0].from_string( THEKERNEL->config->value(alpha_min_endstop_checksum )->by_default("nc" )->as_string())->as_input();
153 this->pins[1].from_string( THEKERNEL->config->value(beta_min_endstop_checksum )->by_default("nc" )->as_string())->as_input();
154 this->pins[2].from_string( THEKERNEL->config->value(gamma_min_endstop_checksum )->by_default("nc" )->as_string())->as_input();
155 this->pins[3].from_string( THEKERNEL->config->value(alpha_max_endstop_checksum )->by_default("nc" )->as_string())->as_input();
156 this->pins[4].from_string( THEKERNEL->config->value(beta_max_endstop_checksum )->by_default("nc" )->as_string())->as_input();
157 this->pins[5].from_string( THEKERNEL->config->value(gamma_max_endstop_checksum )->by_default("nc" )->as_string())->as_input();
158
159 // These are the old ones in steps still here for backwards compatibility
160 this->fast_rates[0] = THEKERNEL->config->value(alpha_fast_homing_rate_checksum )->by_default(4000 )->as_number() / STEPS_PER_MM(0);
161 this->fast_rates[1] = THEKERNEL->config->value(beta_fast_homing_rate_checksum )->by_default(4000 )->as_number() / STEPS_PER_MM(1);
162 this->fast_rates[2] = THEKERNEL->config->value(gamma_fast_homing_rate_checksum )->by_default(6400 )->as_number() / STEPS_PER_MM(2);
163 this->slow_rates[0] = THEKERNEL->config->value(alpha_slow_homing_rate_checksum )->by_default(2000 )->as_number() / STEPS_PER_MM(0);
164 this->slow_rates[1] = THEKERNEL->config->value(beta_slow_homing_rate_checksum )->by_default(2000 )->as_number() / STEPS_PER_MM(1);
165 this->slow_rates[2] = THEKERNEL->config->value(gamma_slow_homing_rate_checksum )->by_default(3200 )->as_number() / STEPS_PER_MM(2);
166 this->retract_mm[0] = THEKERNEL->config->value(alpha_homing_retract_checksum )->by_default(400 )->as_number() / STEPS_PER_MM(0);
167 this->retract_mm[1] = THEKERNEL->config->value(beta_homing_retract_checksum )->by_default(400 )->as_number() / STEPS_PER_MM(1);
168 this->retract_mm[2] = THEKERNEL->config->value(gamma_homing_retract_checksum )->by_default(1600 )->as_number() / STEPS_PER_MM(2);
169
170 // newer mm based config values override the old ones, convert to steps/mm and steps, defaults to what was set in the older config settings above
171 this->fast_rates[0] = THEKERNEL->config->value(alpha_fast_homing_rate_mm_checksum )->by_default(this->fast_rates[0])->as_number();
172 this->fast_rates[1] = THEKERNEL->config->value(beta_fast_homing_rate_mm_checksum )->by_default(this->fast_rates[1])->as_number();
173 this->fast_rates[2] = THEKERNEL->config->value(gamma_fast_homing_rate_mm_checksum )->by_default(this->fast_rates[2])->as_number();
174 this->slow_rates[0] = THEKERNEL->config->value(alpha_slow_homing_rate_mm_checksum )->by_default(this->slow_rates[0])->as_number();
175 this->slow_rates[1] = THEKERNEL->config->value(beta_slow_homing_rate_mm_checksum )->by_default(this->slow_rates[1])->as_number();
176 this->slow_rates[2] = THEKERNEL->config->value(gamma_slow_homing_rate_mm_checksum )->by_default(this->slow_rates[2])->as_number();
177 this->retract_mm[0] = THEKERNEL->config->value(alpha_homing_retract_mm_checksum )->by_default(this->retract_mm[0])->as_number();
178 this->retract_mm[1] = THEKERNEL->config->value(beta_homing_retract_mm_checksum )->by_default(this->retract_mm[1])->as_number();
179 this->retract_mm[2] = THEKERNEL->config->value(gamma_homing_retract_mm_checksum )->by_default(this->retract_mm[2])->as_number();
180
181 // NOTE the debouce count is in milliseconds so probably does not need to beset anymore
182 this->debounce_ms = THEKERNEL->config->value(endstop_debounce_ms_checksum )->by_default(0)->as_number();
183 this->debounce_count = THEKERNEL->config->value(endstop_debounce_count_checksum )->by_default(100)->as_number();
184
185 // get homing direction and convert to boolean where true is home to min, and false is home to max
186 int home_dir = get_checksum(THEKERNEL->config->value(alpha_homing_direction_checksum)->by_default("home_to_min")->as_string());
187 this->home_direction[0] = home_dir != home_to_max_checksum;
188
189 home_dir = get_checksum(THEKERNEL->config->value(beta_homing_direction_checksum)->by_default("home_to_min")->as_string());
190 this->home_direction[1] = home_dir != home_to_max_checksum;
191
192 home_dir = get_checksum(THEKERNEL->config->value(gamma_homing_direction_checksum)->by_default("home_to_min")->as_string());
193 this->home_direction[2] = home_dir != home_to_max_checksum;
194
195 this->homing_position[0] = this->home_direction[0] ? THEKERNEL->config->value(alpha_min_checksum)->by_default(0)->as_number() : THEKERNEL->config->value(alpha_max_checksum)->by_default(200)->as_number();
196 this->homing_position[1] = this->home_direction[1] ? THEKERNEL->config->value(beta_min_checksum )->by_default(0)->as_number() : THEKERNEL->config->value(beta_max_checksum )->by_default(200)->as_number();
197 this->homing_position[2] = this->home_direction[2] ? THEKERNEL->config->value(gamma_min_checksum)->by_default(0)->as_number() : THEKERNEL->config->value(gamma_max_checksum)->by_default(200)->as_number();
198
199 // used to set maximum movement on homing
200 this->alpha_max= THEKERNEL->config->value(alpha_max_checksum)->by_default(500)->as_number();
201 this->beta_max= THEKERNEL->config->value(beta_max_checksum)->by_default(500)->as_number();
202 this->gamma_max= THEKERNEL->config->value(gamma_max_checksum)->by_default(500)->as_number();
203
204 this->is_corexy = THEKERNEL->config->value(corexy_homing_checksum)->by_default(false)->as_bool();
205 this->is_delta = THEKERNEL->config->value(delta_homing_checksum)->by_default(false)->as_bool();
206 this->is_rdelta = THEKERNEL->config->value(rdelta_homing_checksum)->by_default(false)->as_bool();
207 this->is_scara = THEKERNEL->config->value(scara_homing_checksum)->by_default(false)->as_bool();
208
209 // see if an order has been specified, must be three characters, XYZ or YXZ etc
210 string order = THEKERNEL->config->value(homing_order_checksum)->by_default("")->as_string();
211 this->homing_order = 0;
212 if(order.size() == 3 && !(this->is_delta || this->is_rdelta)) {
213 int shift = 0;
214 for(auto c : order) {
215 uint8_t i = toupper(c) - 'X';
216 if(i > 2) { // bad value
217 this->homing_order = 0;
218 break;
219 }
220 homing_order |= (i << shift);
221 shift += 2;
222 }
223 }
224
225 // endstop trim used by deltas to do soft adjusting
226 // on a delta homing to max, a negative trim value will move the carriage down, and a positive will move it up
227 this->trim_mm[0] = THEKERNEL->config->value(alpha_trim_checksum )->by_default(0 )->as_number();
228 this->trim_mm[1] = THEKERNEL->config->value(beta_trim_checksum )->by_default(0 )->as_number();
229 this->trim_mm[2] = THEKERNEL->config->value(gamma_trim_checksum )->by_default(0 )->as_number();
230
231 // limits enabled
232 this->limit_enable[X_AXIS] = THEKERNEL->config->value(alpha_limit_enable_checksum)->by_default(false)->as_bool();
233 this->limit_enable[Y_AXIS] = THEKERNEL->config->value(beta_limit_enable_checksum)->by_default(false)->as_bool();
234 this->limit_enable[Z_AXIS] = THEKERNEL->config->value(gamma_limit_enable_checksum)->by_default(false)->as_bool();
235
236 // set to true by default for deltas due to trim, false on cartesians
237 this->move_to_origin_after_home = THEKERNEL->config->value(move_to_origin_checksum)->by_default(is_delta)->as_bool();
238
239 if(this->limit_enable[X_AXIS] || this->limit_enable[Y_AXIS] || this->limit_enable[Z_AXIS]) {
240 register_for_event(ON_IDLE);
241 if(this->is_delta || this->is_rdelta) {
242 // we must enable all the limits not just one
243 this->limit_enable[X_AXIS] = true;
244 this->limit_enable[Y_AXIS] = true;
245 this->limit_enable[Z_AXIS] = true;
246 }
247 }
248
249 //
250 if(this->is_delta || this->is_rdelta) {
251 // some things must be the same or they will die, so force it here to avoid config errors
252 this->fast_rates[1] = this->fast_rates[2] = this->fast_rates[0];
253 this->slow_rates[1] = this->slow_rates[2] = this->slow_rates[0];
254 this->retract_mm[1] = this->retract_mm[2] = this->retract_mm[0];
255 this->home_direction[1] = this->home_direction[2] = this->home_direction[0];
256 // NOTE homing_position for rdelta is the angle of the actuator not the cartesian position
257 if(!this->is_rdelta) this->homing_position[0] = this->homing_position[1] = 0;
258 }
259 }
260
261 bool Endstops::debounced_get(int pin)
262 {
263 uint8_t debounce = 0;
264 while(this->pins[pin].get()) {
265 if ( ++debounce >= this->debounce_count ) {
266 // pin triggered
267 return true;
268 }
269 }
270 return false;
271 }
272
273 static const char *endstop_names[] = {"min_x", "min_y", "min_z", "max_x", "max_y", "max_z"};
274
275 void Endstops::on_idle(void *argument)
276 {
277 if(this->status == LIMIT_TRIGGERED) {
278 // if we were in limit triggered see if it has been cleared
279 for( int c = X_AXIS; c <= Z_AXIS; c++ ) {
280 if(this->limit_enable[c]) {
281 std::array<int, 2> minmax{{0, 3}};
282 // check min and max endstops
283 for (int i : minmax) {
284 int n = c + i;
285 if(this->pins[n].get()) {
286 // still triggered, so exit
287 bounce_cnt = 0;
288 return;
289 }
290 }
291 }
292 }
293 if(++bounce_cnt > 10) { // can use less as it calls on_idle in between
294 // clear the state
295 this->status = NOT_HOMING;
296 }
297 return;
298
299 } else if(this->status != NOT_HOMING) {
300 // don't check while homing
301 return;
302 }
303
304 for( int c = X_AXIS; c <= Z_AXIS; c++ ) {
305 if(this->limit_enable[c] && STEPPER[c]->is_moving()) {
306 std::array<int, 2> minmax{{0, 3}};
307 // check min and max endstops
308 for (int i : minmax) {
309 int n = c + i;
310 if(debounced_get(n)) {
311 // endstop triggered
312 THEKERNEL->streams->printf("Limit switch %s was hit - reset or M999 required\n", endstop_names[n]);
313 this->status = LIMIT_TRIGGERED;
314 // disables heaters and motors, ignores incoming Gcode and flushes block queue
315 THEKERNEL->call_event(ON_HALT, nullptr);
316 return;
317 }
318 }
319 }
320 }
321 }
322
323 // if limit switches are enabled, then we must move off of the endstop otherwise we won't be able to move
324 // checks if triggered and only backs off if triggered
325 void Endstops::back_off_home(std::bitset<3> axis)
326 {
327 std::vector<std::pair<char, float>> params;
328 this->status = BACK_OFF_HOME;
329
330 // these are handled differently
331 if(is_delta) {
332 // Move off of the endstop using a regular relative move in Z only
333 params.push_back({'Z', this->retract_mm[Z_AXIS] * (this->home_direction[Z_AXIS] ? 1 : -1)});
334
335 } else {
336 // cartesians, concatenate all the moves we need to do into one gcode
337 for( int c = X_AXIS; c <= Z_AXIS; c++ ) {
338 if(!axis[c]) continue; // only for axes we asked to move
339
340 // if not triggered no need to move off
341 if(this->limit_enable[c] && debounced_get(c + (this->home_direction[c] ? 0 : 3)) ) {
342 params.push_back({c + 'X', this->retract_mm[c] * (this->home_direction[c] ? 1 : -1)});
343 }
344 }
345 }
346
347 if(!params.empty()) {
348 // Move off of the endstop using a regular relative move
349 params.insert(params.begin(), {'G', 0});
350 // use X slow rate to move, Z should have a max speed set anyway
351 params.push_back({'F', this->slow_rates[X_AXIS] * 60.0F});
352 char gcode_buf[64];
353 append_parameters(gcode_buf, params, sizeof(gcode_buf));
354 Gcode gc(gcode_buf, &(StreamOutput::NullStream));
355 THEROBOT->push_state();
356 THEROBOT->absolute_mode = false; // needs to be relative mode
357 THEROBOT->on_gcode_received(&gc); // send to robot directly
358 // Wait for above to finish
359 THEKERNEL->conveyor->wait_for_empty_queue();
360 THEROBOT->pop_state();
361 }
362
363 this->status = NOT_HOMING;
364 }
365
366 // If enabled will move the head to 0,0 after homing, but only if X and Y were set to home
367 void Endstops::move_to_origin()
368 {
369 if(!(axis_to_home[X_AXIS] && axis_to_home[Y_AXIS])) return; // ignore if X and Y not homing
370
371 // Do we need to check if we are already at 0,0? probably not as the G0 will not do anything if we are
372 // float pos[3]; THEROBOT->get_axis_position(pos); if(pos[0] == 0 && pos[1] == 0) return;
373
374 this->status = MOVE_TO_ORIGIN;
375 // Move to center using a regular move, use slower of X and Y fast rate
376 float rate = std::min(this->fast_rates[0], this->fast_rates[1]) * 60.0F;
377 char buf[32];
378 snprintf(buf, sizeof(buf), "G53 G0 X0 Y0 F%1.4f", rate); // must use machine coordinates in case G92 or WCS is in effect
379 THEROBOT->push_state();
380 struct SerialMessage message;
381 message.message = buf;
382 message.stream = &(StreamOutput::NullStream);
383 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message ); // as it is a multi G code command
384 // Wait for above to finish
385 THEKERNEL->conveyor->wait_for_empty_queue();
386 THEROBOT->pop_state();
387 this->status = NOT_HOMING;
388 }
389
390 // Called every millisecond in an ISR
391 uint32_t Endstops::read_endstops(uint32_t dummy)
392 {
393 if(this->status != MOVING_TO_ENDSTOP_SLOW && this->status != MOVING_TO_ENDSTOP_FAST) return 0; // not doing anything we need to monitor for
394
395 if(!is_corexy) {
396 // check each axis
397 for ( int m = X_AXIS; m <= Z_AXIS; m++ ) {
398 if(STEPPER[m]->is_moving()) {
399 // if it is moving then we check the associated endstop, and debounce it
400 if(this->pins[m + (this->home_direction[m] ? 0 : 3)].get()) {
401 if(debounce[m] < debounce_ms) {
402 debounce[m]++;
403 } else {
404 // we signal the motor to stop, which will preempt any moves on that axis
405 STEPPER[m]->stop_moving();
406 }
407
408 } else {
409 // The endstop was not hit yet
410 debounce[m] = 0;
411 }
412 }
413 }
414
415 } else {
416 // corexy is different as the actuators are not directly related to the XY axis
417 // so we check the axis that is currently homing then stop all motors
418 for ( int m = X_AXIS; m <= Z_AXIS; m++ ) {
419 if(axis_to_home[m]) {
420 if(this->pins[m + (this->home_direction[m] ? 0 : 3)].get()) {
421 if(debounce[m] < debounce_ms) {
422 debounce[m]++;
423 } else {
424 // 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
425 STEPPER[X_AXIS]->stop_moving();
426 STEPPER[Y_AXIS]->stop_moving();
427 STEPPER[Z_AXIS]->stop_moving();
428 }
429
430 } else {
431 // The endstop was not hit yet
432 debounce[m] = 0;
433 }
434 }
435 }
436 }
437
438 return 0;
439 }
440
441 void Endstops::home(std::bitset<3> a)
442 {
443 // reset debounce counts
444 debounce.fill(0);
445
446 this->axis_to_home= a;
447
448 // Start moving the axes to the origin
449 this->status = MOVING_TO_ENDSTOP_FAST;
450
451 THEROBOT->disable_segmentation= true; // we must disable segmentation as this won't work with it enabled
452 if(axis_to_home[X_AXIS] && axis_to_home[Y_AXIS]) {
453 // Home XY first so as not to slow them down by homing Z at the same time
454 float delta[3] {alpha_max*2, beta_max*2, 0};
455 if(this->home_direction[X_AXIS]) delta[X_AXIS]= -delta[X_AXIS];
456 if(this->home_direction[Y_AXIS]) delta[Y_AXIS]= -delta[Y_AXIS];
457 float feed_rate = std::min(fast_rates[X_AXIS], fast_rates[Y_AXIS]);
458 THEROBOT->solo_move(delta, feed_rate, 3);
459
460 // Wait for XY to have homed
461 THECONVEYOR->wait_for_empty_queue();
462
463 } else if(axis_to_home[X_AXIS]) {
464 // now home X only
465 float delta[3] {alpha_max*2, 0, 0};
466 if(this->home_direction[X_AXIS]) delta[X_AXIS]= -delta[X_AXIS];
467 THEROBOT->solo_move(delta, fast_rates[X_AXIS], 3);
468 // wait for X
469 THECONVEYOR->wait_for_empty_queue();
470
471 } else if(axis_to_home[Y_AXIS]) {
472 // now home Y only
473 float delta[3] {0, beta_max*2, 0};
474 if(this->home_direction[Y_AXIS]) delta[Y_AXIS]= -delta[Y_AXIS];
475 THEROBOT->solo_move(delta, fast_rates[Y_AXIS], 3);
476 // wait for Y
477 THECONVEYOR->wait_for_empty_queue();
478 }
479
480 if(axis_to_home[Z_AXIS]) {
481 // now home z
482 float delta[3] {0, 0, gamma_max*2}; // we go twice the maxz just in case it was set incorrectly
483 if(this->home_direction[Z_AXIS]) delta[Z_AXIS]= -delta[Z_AXIS];
484 THEROBOT->solo_move(delta, fast_rates[Z_AXIS], 3);
485 // wait for Z
486 THECONVEYOR->wait_for_empty_queue();
487 }
488
489 // TODO should check that the endstops were hit and it did not stop short for some reason
490
491 // Move back a small distance for all homing axis
492 this->status = MOVING_BACK;
493 float delta[3]{0,0,0};
494 // use minimum feed rate of all three axes that are being homed (sub optimal, but necessary)
495 float feed_rate= slow_rates[X_AXIS];
496 for ( int c = X_AXIS; c <= Z_AXIS; c++ ) {
497 if(axis_to_home[c]) {
498 delta[c]= this->retract_mm[c];
499 if(!this->home_direction[c]) delta[c]= -delta[c];
500 feed_rate= std::min(slow_rates[c], feed_rate);
501 }
502 }
503
504 THEROBOT->solo_move(delta, feed_rate, 3);
505 // wait until finished
506 THECONVEYOR->wait_for_empty_queue();
507
508 // Start moving the axes to the origin slowly
509 this->status = MOVING_TO_ENDSTOP_SLOW;
510 for ( int c = X_AXIS; c <= Z_AXIS; c++ ) {
511 if(axis_to_home[c]) {
512 delta[c]= this->retract_mm[c];
513 if(this->home_direction[c]) delta[c]= -delta[c];
514 }else{
515 delta[c]= 0;
516 }
517 }
518 THEROBOT->solo_move(delta, feed_rate, 3);
519 // wait until finished
520 THECONVEYOR->wait_for_empty_queue();
521
522 THEROBOT->disable_segmentation= false; // we must disable segmentation as this won't work with it enabled
523
524 this->status = NOT_HOMING;
525 }
526
527 void Endstops::process_home_command(Gcode* gcode)
528 {
529 if( (gcode->subcode == 0 && THEKERNEL->is_grbl_mode()) || (gcode->subcode == 2 && !THEKERNEL->is_grbl_mode()) ) {
530 // G28 in grbl mode or G28.2 in normal mode will do a rapid to the predefined position
531 // TODO spec says if XYZ specified move to them first then move to MCS of specifed axis
532 char buf[32];
533 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
534 struct SerialMessage message;
535 message.message = buf;
536 message.stream = &(StreamOutput::NullStream);
537 THEKERNEL->call_event(ON_CONSOLE_LINE_RECEIVED, &message ); // as it is a multi G code command
538 return;
539
540 } else if(THEKERNEL->is_grbl_mode() && gcode->subcode == 2) { // G28.2 in grbl mode forces homing (triggered by $H)
541 // fall through so it does homing cycle
542
543 } else if(gcode->subcode == 1) { // G28.1 set pre defined position
544 // saves current position in absolute machine coordinates
545 THEROBOT->get_axis_position(saved_position);
546 return;
547
548 } else if(gcode->subcode == 3) { // G28.3 is a smoothie special it sets manual homing
549 if(gcode->get_num_args() == 0) {
550 THEROBOT->reset_axis_position(0, 0, 0);
551 } else {
552 // do a manual homing based on given coordinates, no endstops required
553 if(gcode->has_letter('X')) THEROBOT->reset_axis_position(gcode->get_value('X'), X_AXIS);
554 if(gcode->has_letter('Y')) THEROBOT->reset_axis_position(gcode->get_value('Y'), Y_AXIS);
555 if(gcode->has_letter('Z')) THEROBOT->reset_axis_position(gcode->get_value('Z'), Z_AXIS);
556 }
557 return;
558
559 } else if(gcode->subcode == 4) { // G28.4 is a smoothie special it sets manual homing based on the actuator position (used for rotary delta)
560 // do a manual homing based on given coordinates, no endstops required, NOTE does not support the multi actuator hack
561 ActuatorCoordinates ac;
562 if(gcode->has_letter('A')) ac[0] = gcode->get_value('A');
563 if(gcode->has_letter('B')) ac[1] = gcode->get_value('B');
564 if(gcode->has_letter('C')) ac[2] = gcode->get_value('C');
565 THEROBOT->reset_actuator_position(ac);
566 return;
567
568 } else if(THEKERNEL->is_grbl_mode()) {
569 gcode->stream->printf("error:Unsupported command\n");
570 return;
571 }
572
573 // G28 is received, we have homing to do
574
575 // First wait for the queue to be empty
576 THEKERNEL->conveyor->wait_for_empty_queue();
577
578 // deltas, scaras always home Z axis only
579 bool home_in_z = this->is_delta || this->is_rdelta || this->is_scara;
580
581 // figure out which axis to home
582 bitset<3> haxis;
583 haxis.reset();
584
585 if(!home_in_z) { // ie not a delta
586 bool axis_speced = ( gcode->has_letter('X') || gcode->has_letter('Y') || gcode->has_letter('Z') );
587 // only enable homing if the endstop is defined,
588 for ( int c = X_AXIS; c <= Z_AXIS; c++ ) {
589 if (this->pins[c + (this->home_direction[c] ? 0 : 3)].connected() && (!axis_speced || gcode->has_letter(c + 'X')) ) {
590 haxis.set(c);
591 }
592 }
593
594 } else {
595 // Only Z axis homes (even though all actuators move this is handled by arm solution)
596 haxis.set(Z_AXIS);
597 }
598
599 // save current actuator position so we can report how far we moved
600 ActuatorCoordinates start_pos{
601 THEROBOT->actuators[X_AXIS]->get_current_position(),
602 THEROBOT->actuators[Y_AXIS]->get_current_position(),
603 THEROBOT->actuators[Z_AXIS]->get_current_position()
604 };
605
606 // do the actual homing
607 if(homing_order != 0) {
608 // if an order has been specified do it in the specified order
609 // homing order is 0b00ccbbaa where aa is 0,1,2 to specify the first axis, bb is the second and cc is the third
610 // eg 0b00100001 would be Y X Z, 0b00100100 would be X Y Z
611 for (uint8_t m = homing_order; m != 0; m >>= 2) {
612 int a= (m & 0x03); // axis to home
613 if(haxis[a]) { // if axis is selected to home
614 std::bitset<3> bs;
615 bs.set(a);
616 home(bs);
617 }
618 // check if on_halt (eg kill)
619 if(THEKERNEL->is_halted()) break;
620 }
621
622 } else if(is_corexy) {
623 // corexy must home each axis individually
624 for (int a = X_AXIS; a <= Z_AXIS; ++a) {
625 if(haxis[a]) {
626 std::bitset<3> bs;
627 bs.set(a);
628 home(bs);
629 }
630 }
631
632 } else {
633 // they could all home at the same time
634 home(haxis);
635 }
636
637 // check if on_halt (eg kill)
638 if(THEKERNEL->is_halted()) {
639 if(!THEKERNEL->is_grbl_mode()) {
640 THEKERNEL->streams->printf("Homing cycle aborted by kill\n");
641 }
642 return;
643 }
644
645 // set the last probe position to the actuator units moved during this home
646 THEROBOT->set_last_probe_position(
647 std::make_tuple(
648 start_pos[0] - THEROBOT->actuators[0]->get_current_position(),
649 start_pos[1] - THEROBOT->actuators[1]->get_current_position(),
650 start_pos[2] - THEROBOT->actuators[2]->get_current_position(),
651 0));
652
653 if(home_in_z) { // deltas only
654 // Here's where we would have been if the endstops were perfectly trimmed
655 // NOTE on a rotary delta home_offset is actuator position in degrees when homed and
656 // home_offset is the theta offset for each actuator, so M206 is used to set theta offset for each actuator in degrees
657 float ideal_position[3] = {
658 this->homing_position[X_AXIS] + this->home_offset[X_AXIS],
659 this->homing_position[Y_AXIS] + this->home_offset[Y_AXIS],
660 this->homing_position[Z_AXIS] + this->home_offset[Z_AXIS]
661 };
662
663 bool has_endstop_trim = this->is_delta || this->is_scara;
664 if (has_endstop_trim) {
665 ActuatorCoordinates ideal_actuator_position;
666 THEROBOT->arm_solution->cartesian_to_actuator(ideal_position, ideal_actuator_position);
667
668 // We are actually not at the ideal position, but a trim away
669 ActuatorCoordinates real_actuator_position = {
670 ideal_actuator_position[X_AXIS] - this->trim_mm[X_AXIS],
671 ideal_actuator_position[Y_AXIS] - this->trim_mm[Y_AXIS],
672 ideal_actuator_position[Z_AXIS] - this->trim_mm[Z_AXIS]
673 };
674
675 float real_position[3];
676 THEROBOT->arm_solution->actuator_to_cartesian(real_actuator_position, real_position);
677 // Reset the actuator positions to correspond our real position
678 THEROBOT->reset_axis_position(real_position[0], real_position[1], real_position[2]);
679
680 } else {
681 // without endstop trim, real_position == ideal_position
682 if(is_rdelta) {
683 // with a rotary delta we set the actuators angle then use the FK to calculate the resulting cartesian coordinates
684 ActuatorCoordinates real_actuator_position = {ideal_position[0], ideal_position[1], ideal_position[2]};
685 THEROBOT->reset_actuator_position(real_actuator_position);
686
687 } else {
688 // Reset the actuator positions to correspond our real position
689 THEROBOT->reset_axis_position(ideal_position[0], ideal_position[1], ideal_position[2]);
690 }
691 }
692
693 } else {
694 // Zero the ax(i/e)s position, add in the home offset
695 for ( int c = X_AXIS; c <= Z_AXIS; c++ ) {
696 if (axis_to_home[c]) {
697 THEROBOT->reset_axis_position(this->homing_position[c] + this->home_offset[c], c);
698 }
699 }
700 }
701
702 // on some systems where 0,0 is bed center it is nice to have home goto 0,0 after homing
703 // default is off for cartesian on for deltas
704 if(!is_delta) {
705 // NOTE a rotary delta usually has optical or hall-effect endstops so it is safe to go past them a little bit
706 if(this->move_to_origin_after_home) move_to_origin();
707 // if limit switches are enabled we must back off endstop after setting home
708 back_off_home(haxis);
709
710 } else if(this->move_to_origin_after_home || this->limit_enable[X_AXIS]) {
711 // 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
712 // also need to back off endstops if limits are enabled
713 back_off_home(haxis);
714 if(this->move_to_origin_after_home) move_to_origin();
715 }
716 }
717
718 void Endstops::set_homing_offset(Gcode *gcode)
719 {
720 // Similar to M206 and G92 but sets Homing offsets based on current position
721 float cartesian[3];
722 THEROBOT->get_axis_position(cartesian); // get actual position from robot
723 if (gcode->has_letter('X')) {
724 home_offset[0] -= (cartesian[X_AXIS] - gcode->get_value('X'));
725 THEROBOT->reset_axis_position(gcode->get_value('X'), X_AXIS);
726 }
727 if (gcode->has_letter('Y')) {
728 home_offset[1] -= (cartesian[Y_AXIS] - gcode->get_value('Y'));
729 THEROBOT->reset_axis_position(gcode->get_value('Y'), Y_AXIS);
730 }
731 if (gcode->has_letter('Z')) {
732 home_offset[2] -= (cartesian[Z_AXIS] - gcode->get_value('Z'));
733 THEROBOT->reset_axis_position(gcode->get_value('Z'), Z_AXIS);
734 }
735
736 gcode->stream->printf("Homing Offset: X %5.3f Y %5.3f Z %5.3f\n", home_offset[0], home_offset[1], home_offset[2]);
737 }
738
739 // Start homing sequences by response to GCode commands
740 void Endstops::on_gcode_received(void *argument)
741 {
742 Gcode *gcode = static_cast<Gcode *>(argument);
743 if ( gcode->has_g && gcode->g == 28) {
744 process_home_command(gcode);
745
746 } else if (gcode->has_m) {
747
748 switch (gcode->m) {
749 case 119: {
750 for (int i = 0; i < 6; ++i) {
751 if(this->pins[i].connected())
752 gcode->stream->printf("%s:%d ", endstop_names[i], this->pins[i].get());
753 }
754 gcode->add_nl = true;
755
756 }
757 break;
758
759 case 206: // M206 - set homing offset
760 if(is_rdelta) return; // RotaryDeltaCalibration module will handle this
761
762 if (gcode->has_letter('X')) home_offset[0] = gcode->get_value('X');
763 if (gcode->has_letter('Y')) home_offset[1] = gcode->get_value('Y');
764 if (gcode->has_letter('Z')) home_offset[2] = gcode->get_value('Z');
765 gcode->stream->printf("X %5.3f Y %5.3f Z %5.3f\n", home_offset[0], home_offset[1], home_offset[2]);
766 break;
767
768 case 306: // set homing offset based on current position
769 if(is_rdelta) return; // RotaryDeltaCalibration module will handle this
770
771 set_homing_offset(gcode);
772 break;
773
774 case 500: // save settings
775 case 503: // print settings
776 if(!is_rdelta)
777 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]);
778 else
779 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]);
780
781 if (this->is_delta || this->is_scara) {
782 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]);
783 gcode->stream->printf(";Max Z\nM665 Z%1.3f\n", this->homing_position[2]);
784 }
785 if(saved_position[X_AXIS] != 0 || saved_position[Y_AXIS] != 0) {
786 gcode->stream->printf(";predefined position:\nG28.1 X%1.4f Y%1.4f Z%1.4f\n", saved_position[X_AXIS], saved_position[Y_AXIS], saved_position[Z_AXIS]);
787 }
788 break;
789
790 case 665:
791 if (this->is_delta || this->is_scara) { // M665 - set max gamma/z height
792 float gamma_max = this->homing_position[2];
793 if (gcode->has_letter('Z')) {
794 this->homing_position[2] = gamma_max = gcode->get_value('Z');
795 }
796 gcode->stream->printf("Max Z %8.3f ", gamma_max);
797 gcode->add_nl = true;
798 }
799 break;
800
801 case 666:
802 if(this->is_delta || this->is_scara) { // M666 - set trim for each axis in mm, NB negative mm trim is down
803 if (gcode->has_letter('X')) trim_mm[0] = gcode->get_value('X');
804 if (gcode->has_letter('Y')) trim_mm[1] = gcode->get_value('Y');
805 if (gcode->has_letter('Z')) trim_mm[2] = gcode->get_value('Z');
806
807 // print the current trim values in mm
808 gcode->stream->printf("X: %5.3f Y: %5.3f Z: %5.3f\n", trim_mm[0], trim_mm[1], trim_mm[2]);
809
810 }
811 break;
812
813 }
814 }
815 }
816
817 void Endstops::on_get_public_data(void* argument)
818 {
819 PublicDataRequest* pdr = static_cast<PublicDataRequest*>(argument);
820
821 if(!pdr->starts_with(endstops_checksum)) return;
822
823 if(pdr->second_element_is(trim_checksum)) {
824 pdr->set_data_ptr(&this->trim_mm);
825 pdr->set_taken();
826
827 } else if(pdr->second_element_is(home_offset_checksum)) {
828 pdr->set_data_ptr(&this->home_offset);
829 pdr->set_taken();
830
831 } else if(pdr->second_element_is(saved_position_checksum)) {
832 pdr->set_data_ptr(&this->saved_position);
833 pdr->set_taken();
834
835 } else if(pdr->second_element_is(get_homing_status_checksum)) {
836 bool *homing = static_cast<bool *>(pdr->get_data_ptr());
837 *homing = this->status != NOT_HOMING;
838 pdr->set_taken();
839 }
840 }
841
842 void Endstops::on_set_public_data(void* argument)
843 {
844 PublicDataRequest* pdr = static_cast<PublicDataRequest*>(argument);
845
846 if(!pdr->starts_with(endstops_checksum)) return;
847
848 if(pdr->second_element_is(trim_checksum)) {
849 float *t = static_cast<float*>(pdr->get_data_ptr());
850 this->trim_mm[0] = t[0];
851 this->trim_mm[1] = t[1];
852 this->trim_mm[2] = t[2];
853 pdr->set_taken();
854
855 } else if(pdr->second_element_is(home_offset_checksum)) {
856 float *t = static_cast<float*>(pdr->get_data_ptr());
857 if(!isnan(t[0])) this->home_offset[0] = t[0];
858 if(!isnan(t[1])) this->home_offset[1] = t[1];
859 if(!isnan(t[2])) this->home_offset[2] = t[2];
860 }
861 }