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