Merge pull request #1055 from wolfmanjm/merge-abc-with-homing
[clinton/Smoothieware.git] / src / modules / robot / Robot.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) with additions from Sungeun K. Jeon (https://github.com/chamnit/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
11 #include "Robot.h"
12 #include "Planner.h"
13 #include "Conveyor.h"
14 #include "Pin.h"
15 #include "StepperMotor.h"
16 #include "Gcode.h"
17 #include "PublicDataRequest.h"
18 #include "PublicData.h"
19 #include "arm_solutions/BaseSolution.h"
20 #include "arm_solutions/CartesianSolution.h"
21 #include "arm_solutions/RotatableCartesianSolution.h"
22 #include "arm_solutions/LinearDeltaSolution.h"
23 #include "arm_solutions/RotaryDeltaSolution.h"
24 #include "arm_solutions/HBotSolution.h"
25 #include "arm_solutions/CoreXZSolution.h"
26 #include "arm_solutions/MorganSCARASolution.h"
27 #include "StepTicker.h"
28 #include "checksumm.h"
29 #include "utils.h"
30 #include "ConfigValue.h"
31 #include "libs/StreamOutput.h"
32 #include "StreamOutputPool.h"
33 #include "ExtruderPublicAccess.h"
34 #include "GcodeDispatch.h"
35 #include "ActuatorCoordinates.h"
36
37 #include "mbed.h" // for us_ticker_read()
38 #include "mri.h"
39
40 #include <fastmath.h>
41 #include <string>
42 #include <algorithm>
43
44 #define default_seek_rate_checksum CHECKSUM("default_seek_rate")
45 #define default_feed_rate_checksum CHECKSUM("default_feed_rate")
46 #define mm_per_line_segment_checksum CHECKSUM("mm_per_line_segment")
47 #define delta_segments_per_second_checksum CHECKSUM("delta_segments_per_second")
48 #define mm_per_arc_segment_checksum CHECKSUM("mm_per_arc_segment")
49 #define mm_max_arc_error_checksum CHECKSUM("mm_max_arc_error")
50 #define arc_correction_checksum CHECKSUM("arc_correction")
51 #define x_axis_max_speed_checksum CHECKSUM("x_axis_max_speed")
52 #define y_axis_max_speed_checksum CHECKSUM("y_axis_max_speed")
53 #define z_axis_max_speed_checksum CHECKSUM("z_axis_max_speed")
54 #define segment_z_moves_checksum CHECKSUM("segment_z_moves")
55 #define save_g92_checksum CHECKSUM("save_g92")
56 #define set_g92_checksum CHECKSUM("set_g92")
57
58 // arm solutions
59 #define arm_solution_checksum CHECKSUM("arm_solution")
60 #define cartesian_checksum CHECKSUM("cartesian")
61 #define rotatable_cartesian_checksum CHECKSUM("rotatable_cartesian")
62 #define rostock_checksum CHECKSUM("rostock")
63 #define linear_delta_checksum CHECKSUM("linear_delta")
64 #define rotary_delta_checksum CHECKSUM("rotary_delta")
65 #define delta_checksum CHECKSUM("delta")
66 #define hbot_checksum CHECKSUM("hbot")
67 #define corexy_checksum CHECKSUM("corexy")
68 #define corexz_checksum CHECKSUM("corexz")
69 #define kossel_checksum CHECKSUM("kossel")
70 #define morgan_checksum CHECKSUM("morgan")
71
72 // new-style actuator stuff
73 #define actuator_checksum CHEKCSUM("actuator")
74
75 #define step_pin_checksum CHECKSUM("step_pin")
76 #define dir_pin_checksum CHEKCSUM("dir_pin")
77 #define en_pin_checksum CHECKSUM("en_pin")
78
79 #define steps_per_mm_checksum CHECKSUM("steps_per_mm")
80 #define max_rate_checksum CHECKSUM("max_rate")
81 #define acceleration_checksum CHECKSUM("acceleration")
82 #define z_acceleration_checksum CHECKSUM("z_acceleration")
83
84 #define alpha_checksum CHECKSUM("alpha")
85 #define beta_checksum CHECKSUM("beta")
86 #define gamma_checksum CHECKSUM("gamma")
87
88 #define laser_module_default_power_checksum CHECKSUM("laser_module_default_power")
89
90 #define ARC_ANGULAR_TRAVEL_EPSILON 5E-7F // Float (radians)
91 #define PI 3.14159265358979323846F // force to be float, do not use M_PI
92
93 // The Robot converts GCodes into actual movements, and then adds them to the Planner, which passes them to the Conveyor so they can be added to the queue
94 // It takes care of cutting arcs into segments, same thing for line that are too long
95
96 Robot::Robot()
97 {
98 this->inch_mode = false;
99 this->absolute_mode = true;
100 this->e_absolute_mode = true;
101 this->select_plane(X_AXIS, Y_AXIS, Z_AXIS);
102 memset(this->machine_position, 0, sizeof machine_position);
103 memset(this->compensated_machine_position, 0, sizeof compensated_machine_position);
104 this->arm_solution = NULL;
105 seconds_per_minute = 60.0F;
106 this->clearToolOffset();
107 this->compensationTransform = nullptr;
108 this->get_e_scale_fnc= nullptr;
109 this->wcs_offsets.fill(wcs_t(0.0F, 0.0F, 0.0F));
110 this->g92_offset = wcs_t(0.0F, 0.0F, 0.0F);
111 this->next_command_is_MCS = false;
112 this->disable_segmentation= false;
113 this->disable_arm_solution= false;
114 this->n_motors= 0;
115 }
116
117 //Called when the module has just been loaded
118 void Robot::on_module_loaded()
119 {
120 this->register_for_event(ON_GCODE_RECEIVED);
121
122 // Configuration
123 this->load_config();
124 }
125
126 #define ACTUATOR_CHECKSUMS(X) { \
127 CHECKSUM(X "_step_pin"), \
128 CHECKSUM(X "_dir_pin"), \
129 CHECKSUM(X "_en_pin"), \
130 CHECKSUM(X "_steps_per_mm"), \
131 CHECKSUM(X "_max_rate"), \
132 CHECKSUM(X "_acceleration") \
133 }
134
135 void Robot::load_config()
136 {
137 // Arm solutions are used to convert positions in millimeters into position in steps for each stepper motor.
138 // While for a cartesian arm solution, this is a simple multiplication, in other, less simple cases, there is some serious math to be done.
139 // To make adding those solution easier, they have their own, separate object.
140 // Here we read the config to find out which arm solution to use
141 if (this->arm_solution) delete this->arm_solution;
142 int solution_checksum = get_checksum(THEKERNEL->config->value(arm_solution_checksum)->by_default("cartesian")->as_string());
143 // Note checksums are not const expressions when in debug mode, so don't use switch
144 if(solution_checksum == hbot_checksum || solution_checksum == corexy_checksum) {
145 this->arm_solution = new HBotSolution(THEKERNEL->config);
146
147 } else if(solution_checksum == corexz_checksum) {
148 this->arm_solution = new CoreXZSolution(THEKERNEL->config);
149
150 } else if(solution_checksum == rostock_checksum || solution_checksum == kossel_checksum || solution_checksum == delta_checksum || solution_checksum == linear_delta_checksum) {
151 this->arm_solution = new LinearDeltaSolution(THEKERNEL->config);
152
153 } else if(solution_checksum == rotatable_cartesian_checksum) {
154 this->arm_solution = new RotatableCartesianSolution(THEKERNEL->config);
155
156 } else if(solution_checksum == rotary_delta_checksum) {
157 this->arm_solution = new RotaryDeltaSolution(THEKERNEL->config);
158
159 } else if(solution_checksum == morgan_checksum) {
160 this->arm_solution = new MorganSCARASolution(THEKERNEL->config);
161
162 } else if(solution_checksum == cartesian_checksum) {
163 this->arm_solution = new CartesianSolution(THEKERNEL->config);
164
165 } else {
166 this->arm_solution = new CartesianSolution(THEKERNEL->config);
167 }
168
169 this->feed_rate = THEKERNEL->config->value(default_feed_rate_checksum )->by_default( 100.0F)->as_number();
170 this->seek_rate = THEKERNEL->config->value(default_seek_rate_checksum )->by_default( 100.0F)->as_number();
171 this->mm_per_line_segment = THEKERNEL->config->value(mm_per_line_segment_checksum )->by_default( 0.0F)->as_number();
172 this->delta_segments_per_second = THEKERNEL->config->value(delta_segments_per_second_checksum )->by_default(0.0f )->as_number();
173 this->mm_per_arc_segment = THEKERNEL->config->value(mm_per_arc_segment_checksum )->by_default( 0.0f)->as_number();
174 this->mm_max_arc_error = THEKERNEL->config->value(mm_max_arc_error_checksum )->by_default( 0.01f)->as_number();
175 this->arc_correction = THEKERNEL->config->value(arc_correction_checksum )->by_default( 5 )->as_number();
176
177 // in mm/sec but specified in config as mm/min
178 this->max_speeds[X_AXIS] = THEKERNEL->config->value(x_axis_max_speed_checksum )->by_default(60000.0F)->as_number() / 60.0F;
179 this->max_speeds[Y_AXIS] = THEKERNEL->config->value(y_axis_max_speed_checksum )->by_default(60000.0F)->as_number() / 60.0F;
180 this->max_speeds[Z_AXIS] = THEKERNEL->config->value(z_axis_max_speed_checksum )->by_default( 300.0F)->as_number() / 60.0F;
181
182 this->segment_z_moves = THEKERNEL->config->value(segment_z_moves_checksum )->by_default(true)->as_bool();
183 this->save_g92 = THEKERNEL->config->value(save_g92_checksum )->by_default(false)->as_bool();
184 string g92 = THEKERNEL->config->value(set_g92_checksum )->by_default("")->as_string();
185 if(!g92.empty()) {
186 // optional setting for a fixed G92 offset
187 std::vector<float> t= parse_number_list(g92.c_str());
188 if(t.size() == 3) {
189 g92_offset = wcs_t(t[0], t[1], t[2]);
190 }
191 }
192
193 // default s value for laser
194 this->s_value = THEKERNEL->config->value(laser_module_default_power_checksum)->by_default(0.8F)->as_number();
195
196 // Make our Primary XYZ StepperMotors, and potentially A B C
197 uint16_t const checksums[][6] = {
198 ACTUATOR_CHECKSUMS("alpha"), // X
199 ACTUATOR_CHECKSUMS("beta"), // Y
200 ACTUATOR_CHECKSUMS("gamma"), // Z
201 #if MAX_ROBOT_ACTUATORS > 3
202 ACTUATOR_CHECKSUMS("delta"), // A
203 #if MAX_ROBOT_ACTUATORS > 4
204 ACTUATOR_CHECKSUMS("epsilon"), // B
205 #if MAX_ROBOT_ACTUATORS > 5
206 ACTUATOR_CHECKSUMS("zeta") // C
207 #endif
208 #endif
209 #endif
210 };
211
212 // default acceleration setting, can be overriden with newer per axis settings
213 this->default_acceleration= THEKERNEL->config->value(acceleration_checksum)->by_default(100.0F )->as_number(); // Acceleration is in mm/s^2
214
215 // make each motor
216 for (size_t a = 0; a < MAX_ROBOT_ACTUATORS; a++) {
217 Pin pins[3]; //step, dir, enable
218 for (size_t i = 0; i < 3; i++) {
219 pins[i].from_string(THEKERNEL->config->value(checksums[a][i])->by_default("nc")->as_string())->as_output();
220 }
221
222 if(!pins[0].connected() || !pins[1].connected() || !pins[2].connected()) {
223 if(a <= Z_AXIS) THEKERNEL->streams->printf("FATAL: motor %d is not defined in config\n", 'X'+a);
224 break; // if any pin is not defined then the axis is not defined (and axis need to be defined in contiguous order)
225 }
226
227 StepperMotor *sm = new StepperMotor(pins[0], pins[1], pins[2]);
228 // register this motor (NB This must be 0,1,2) of the actuators array
229 uint8_t n= register_motor(sm);
230 if(n != a) {
231 // this is a fatal error
232 THEKERNEL->streams->printf("FATAL: motor %d does not match index %d\n", n, a);
233 __debugbreak();
234 }
235
236 actuators[a]->change_steps_per_mm(THEKERNEL->config->value(checksums[a][3])->by_default(a == 2 ? 2560.0F : 80.0F)->as_number());
237 actuators[a]->set_max_rate(THEKERNEL->config->value(checksums[a][4])->by_default(30000.0F)->as_number()/60.0F); // it is in mm/min and converted to mm/sec
238 actuators[a]->set_acceleration(THEKERNEL->config->value(checksums[a][5])->by_default(NAN)->as_number()); // mm/secs²
239 }
240
241 check_max_actuator_speeds(); // check the configs are sane
242
243 // if we have not specified a z acceleration see if the legacy config was set
244 if(isnan(actuators[Z_AXIS]->get_acceleration())) {
245 float acc= THEKERNEL->config->value(z_acceleration_checksum)->by_default(NAN)->as_number(); // disabled by default
246 if(!isnan(acc)) {
247 actuators[Z_AXIS]->set_acceleration(acc);
248 }
249 }
250
251 // initialise actuator positions to current cartesian position (X0 Y0 Z0)
252 // so the first move can be correct if homing is not performed
253 ActuatorCoordinates actuator_pos;
254 arm_solution->cartesian_to_actuator(machine_position, actuator_pos);
255 for (size_t i = 0; i < n_motors; i++)
256 actuators[i]->change_last_milestone(actuator_pos[i]);
257
258 //this->clearToolOffset();
259 }
260
261 uint8_t Robot::register_motor(StepperMotor *motor)
262 {
263 // register this motor with the step ticker
264 THEKERNEL->step_ticker->register_motor(motor);
265 if(n_motors >= k_max_actuators) {
266 // this is a fatal error
267 THEKERNEL->streams->printf("FATAL: too many motors, increase k_max_actuators\n");
268 __debugbreak();
269 }
270 actuators.push_back(motor);
271 motor->set_motor_id(n_motors);
272 return n_motors++;
273 }
274
275 void Robot::push_state()
276 {
277 bool am = this->absolute_mode;
278 bool em = this->e_absolute_mode;
279 bool im = this->inch_mode;
280 saved_state_t s(this->feed_rate, this->seek_rate, am, em, im, current_wcs);
281 state_stack.push(s);
282 }
283
284 void Robot::pop_state()
285 {
286 if(!state_stack.empty()) {
287 auto s = state_stack.top();
288 state_stack.pop();
289 this->feed_rate = std::get<0>(s);
290 this->seek_rate = std::get<1>(s);
291 this->absolute_mode = std::get<2>(s);
292 this->e_absolute_mode = std::get<3>(s);
293 this->inch_mode = std::get<4>(s);
294 this->current_wcs = std::get<5>(s);
295 }
296 }
297
298 std::vector<Robot::wcs_t> Robot::get_wcs_state() const
299 {
300 std::vector<wcs_t> v;
301 v.push_back(wcs_t(current_wcs, MAX_WCS, 0));
302 for(auto& i : wcs_offsets) {
303 v.push_back(i);
304 }
305 v.push_back(g92_offset);
306 v.push_back(tool_offset);
307 return v;
308 }
309
310 void Robot::get_current_machine_position(float *pos) const
311 {
312 // get real time current actuator position in mm
313 ActuatorCoordinates current_position{
314 actuators[X_AXIS]->get_current_position(),
315 actuators[Y_AXIS]->get_current_position(),
316 actuators[Z_AXIS]->get_current_position()
317 };
318
319 // get machine position from the actuator position using FK
320 arm_solution->actuator_to_cartesian(current_position, pos);
321 }
322
323 int Robot::print_position(uint8_t subcode, char *buf, size_t bufsize) const
324 {
325 // M114.1 is a new way to do this (similar to how GRBL does it).
326 // it returns the realtime position based on the current step position of the actuators.
327 // this does require a FK to get a machine position from the actuator position
328 // and then invert all the transforms to get a workspace position from machine position
329 // M114 just does it the old way uses machine_position and does inverse transforms to get the requested position
330 int n = 0;
331 if(subcode == 0) { // M114 print WCS
332 wcs_t pos= mcs2wcs(machine_position);
333 n = snprintf(buf, bufsize, "C: X:%1.4f Y:%1.4f Z:%1.4f", from_millimeters(std::get<X_AXIS>(pos)), from_millimeters(std::get<Y_AXIS>(pos)), from_millimeters(std::get<Z_AXIS>(pos)));
334
335 } else if(subcode == 4) {
336 // M114.4 print last milestone
337 n = snprintf(buf, bufsize, "MP: X:%1.4f Y:%1.4f Z:%1.4f", machine_position[X_AXIS], machine_position[Y_AXIS], machine_position[Z_AXIS]);
338
339 } else if(subcode == 5) {
340 // M114.5 print last machine position (which should be the same as M114.1 if axis are not moving and no level compensation)
341 // will differ from LMS by the compensation at the current position otherwise
342 n = snprintf(buf, bufsize, "CMP: X:%1.4f Y:%1.4f Z:%1.4f", compensated_machine_position[X_AXIS], compensated_machine_position[Y_AXIS], compensated_machine_position[Z_AXIS]);
343
344 } else {
345 // get real time positions
346 float mpos[3];
347 get_current_machine_position(mpos);
348
349 // current_position/mpos includes the compensation transform so we need to get the inverse to get actual position
350 if(compensationTransform) compensationTransform(mpos, true); // get inverse compensation transform
351
352 if(subcode == 1) { // M114.1 print realtime WCS
353 wcs_t pos= mcs2wcs(mpos);
354 n = snprintf(buf, bufsize, "WCS: X:%1.4f Y:%1.4f Z:%1.4f", from_millimeters(std::get<X_AXIS>(pos)), from_millimeters(std::get<Y_AXIS>(pos)), from_millimeters(std::get<Z_AXIS>(pos)));
355
356 } else if(subcode == 2) { // M114.2 print realtime Machine coordinate system
357 n = snprintf(buf, bufsize, "MCS: X:%1.4f Y:%1.4f Z:%1.4f", mpos[X_AXIS], mpos[Y_AXIS], mpos[Z_AXIS]);
358
359 } else if(subcode == 3) { // M114.3 print realtime actuator position
360 // get real time current actuator position in mm
361 ActuatorCoordinates current_position{
362 actuators[X_AXIS]->get_current_position(),
363 actuators[Y_AXIS]->get_current_position(),
364 actuators[Z_AXIS]->get_current_position()
365 };
366 n = snprintf(buf, bufsize, "APOS: X:%1.4f Y:%1.4f Z:%1.4f", current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
367 }
368 }
369
370 #if MAX_ROBOT_ACTUATORS > 3
371 // deal with the ABC axis
372 for (int i = A_AXIS; i < n_motors; ++i) {
373 if(actuators[i]->is_extruder()) continue; // don't show an extruder as that will be E
374 if(subcode == 4) { // M114.4 print last milestone
375 n += snprintf(&buf[n], bufsize-n, " %c:%1.4f", 'A'+i-A_AXIS, machine_position[i]);
376
377 }else if(subcode == 2 || subcode == 3) { // M114.2/M114.3 print actuator position which is the same as machine position for ABC
378 // current actuator position
379 n += snprintf(&buf[n], bufsize-n, " %c:%1.4f", 'A'+i-A_AXIS, actuators[i]->get_current_position());
380 }
381 }
382 #endif
383
384 return n;
385 }
386
387 // converts current last milestone (machine position without compensation transform) to work coordinate system (inverse transform)
388 Robot::wcs_t Robot::mcs2wcs(const Robot::wcs_t& pos) const
389 {
390 return std::make_tuple(
391 std::get<X_AXIS>(pos) - std::get<X_AXIS>(wcs_offsets[current_wcs]) + std::get<X_AXIS>(g92_offset) - std::get<X_AXIS>(tool_offset),
392 std::get<Y_AXIS>(pos) - std::get<Y_AXIS>(wcs_offsets[current_wcs]) + std::get<Y_AXIS>(g92_offset) - std::get<Y_AXIS>(tool_offset),
393 std::get<Z_AXIS>(pos) - std::get<Z_AXIS>(wcs_offsets[current_wcs]) + std::get<Z_AXIS>(g92_offset) - std::get<Z_AXIS>(tool_offset)
394 );
395 }
396
397 // this does a sanity check that actuator speeds do not exceed steps rate capability
398 // we will override the actuator max_rate if the combination of max_rate and steps/sec exceeds base_stepping_frequency
399 void Robot::check_max_actuator_speeds()
400 {
401 for (size_t i = 0; i < n_motors; i++) {
402 float step_freq = actuators[i]->get_max_rate() * actuators[i]->get_steps_per_mm();
403 if (step_freq > THEKERNEL->base_stepping_frequency) {
404 actuators[i]->set_max_rate(floorf(THEKERNEL->base_stepping_frequency / actuators[i]->get_steps_per_mm()));
405 THEKERNEL->streams->printf("WARNING: actuator %d rate exceeds base_stepping_frequency * ..._steps_per_mm: %f, setting to %f\n", i, step_freq, actuators[i]->get_max_rate());
406 }
407 }
408 }
409
410 //A GCode has been received
411 //See if the current Gcode line has some orders for us
412 void Robot::on_gcode_received(void *argument)
413 {
414 Gcode *gcode = static_cast<Gcode *>(argument);
415
416 enum MOTION_MODE_T motion_mode= NONE;
417
418 if( gcode->has_g) {
419 switch( gcode->g ) {
420 case 0: motion_mode = SEEK; break;
421 case 1: motion_mode = LINEAR; break;
422 case 2: motion_mode = CW_ARC; break;
423 case 3: motion_mode = CCW_ARC; break;
424 case 4: { // G4 pause
425 uint32_t delay_ms = 0;
426 if (gcode->has_letter('P')) {
427 delay_ms = gcode->get_int('P');
428 }
429 if (gcode->has_letter('S')) {
430 delay_ms += gcode->get_int('S') * 1000;
431 }
432 if (delay_ms > 0) {
433 // drain queue
434 THEKERNEL->conveyor->wait_for_idle();
435 // wait for specified time
436 uint32_t start = us_ticker_read(); // mbed call
437 while ((us_ticker_read() - start) < delay_ms * 1000) {
438 THEKERNEL->call_event(ON_IDLE, this);
439 if(THEKERNEL->is_halted()) return;
440 }
441 }
442 }
443 break;
444
445 case 10: // G10 L2 [L20] Pn Xn Yn Zn set WCS
446 if(gcode->has_letter('L') && (gcode->get_int('L') == 2 || gcode->get_int('L') == 20) && gcode->has_letter('P')) {
447 size_t n = gcode->get_uint('P');
448 if(n == 0) n = current_wcs; // set current coordinate system
449 else --n;
450 if(n < MAX_WCS) {
451 float x, y, z;
452 std::tie(x, y, z) = wcs_offsets[n];
453 if(gcode->get_int('L') == 20) {
454 // this makes the current machine position (less compensation transform) the offset
455 // get current position in WCS
456 wcs_t pos= mcs2wcs(machine_position);
457
458 if(gcode->has_letter('X')){
459 x -= to_millimeters(gcode->get_value('X')) - std::get<X_AXIS>(pos);
460 }
461
462 if(gcode->has_letter('Y')){
463 y -= to_millimeters(gcode->get_value('Y')) - std::get<Y_AXIS>(pos);
464 }
465 if(gcode->has_letter('Z')) {
466 z -= to_millimeters(gcode->get_value('Z')) - std::get<Z_AXIS>(pos);
467 }
468
469 } else {
470 if(absolute_mode) {
471 // the value is the offset from machine zero
472 if(gcode->has_letter('X')) x = to_millimeters(gcode->get_value('X'));
473 if(gcode->has_letter('Y')) y = to_millimeters(gcode->get_value('Y'));
474 if(gcode->has_letter('Z')) z = to_millimeters(gcode->get_value('Z'));
475 }else{
476 if(gcode->has_letter('X')) x += to_millimeters(gcode->get_value('X'));
477 if(gcode->has_letter('Y')) y += to_millimeters(gcode->get_value('Y'));
478 if(gcode->has_letter('Z')) z += to_millimeters(gcode->get_value('Z'));
479 }
480 }
481 wcs_offsets[n] = wcs_t(x, y, z);
482 }
483 }
484 break;
485
486 case 17: this->select_plane(X_AXIS, Y_AXIS, Z_AXIS); break;
487 case 18: this->select_plane(X_AXIS, Z_AXIS, Y_AXIS); break;
488 case 19: this->select_plane(Y_AXIS, Z_AXIS, X_AXIS); break;
489 case 20: this->inch_mode = true; break;
490 case 21: this->inch_mode = false; break;
491
492 case 54: case 55: case 56: case 57: case 58: case 59:
493 // select WCS 0-8: G54..G59, G59.1, G59.2, G59.3
494 current_wcs = gcode->g - 54;
495 if(gcode->g == 59 && gcode->subcode > 0) {
496 current_wcs += gcode->subcode;
497 if(current_wcs >= MAX_WCS) current_wcs = MAX_WCS - 1;
498 }
499 break;
500
501 case 90: this->absolute_mode = true; this->e_absolute_mode = true; break;
502 case 91: this->absolute_mode = false; this->e_absolute_mode = false; break;
503
504 case 92: {
505 if(gcode->subcode == 1 || gcode->subcode == 2 || gcode->get_num_args() == 0) {
506 // reset G92 offsets to 0
507 g92_offset = wcs_t(0, 0, 0);
508
509 } else if(gcode->subcode == 3) {
510 // initialize G92 to the specified values, only used for saving it with M500
511 float x= 0, y= 0, z= 0;
512 if(gcode->has_letter('X')) x= gcode->get_value('X');
513 if(gcode->has_letter('Y')) y= gcode->get_value('Y');
514 if(gcode->has_letter('Z')) z= gcode->get_value('Z');
515 g92_offset = wcs_t(x, y, z);
516
517 } else {
518 // standard setting of the g92 offsets, making current WCS position whatever the coordinate arguments are
519 float x, y, z;
520 std::tie(x, y, z) = g92_offset;
521 // get current position in WCS
522 wcs_t pos= mcs2wcs(machine_position);
523
524 // adjust g92 offset to make the current wpos == the value requested
525 if(gcode->has_letter('X')){
526 x += to_millimeters(gcode->get_value('X')) - std::get<X_AXIS>(pos);
527 }
528 if(gcode->has_letter('Y')){
529 y += to_millimeters(gcode->get_value('Y')) - std::get<Y_AXIS>(pos);
530 }
531 if(gcode->has_letter('Z')) {
532 z += to_millimeters(gcode->get_value('Z')) - std::get<Z_AXIS>(pos);
533 }
534 g92_offset = wcs_t(x, y, z);
535 }
536
537 #if MAX_ROBOT_ACTUATORS > 3
538 if(gcode->subcode == 0 && (gcode->has_letter('E') || gcode->get_num_args() == 0)){
539 // reset the E position, legacy for 3d Printers to be reprap compatible
540 // find the selected extruder
541 int selected_extruder= get_active_extruder();
542 if(selected_extruder > 0) {
543 float e= gcode->has_letter('E') ? gcode->get_value('E') : 0;
544 machine_position[selected_extruder]= compensated_machine_position[selected_extruder]= e;
545 actuators[selected_extruder]->change_last_milestone(get_e_scale_fnc ? e*get_e_scale_fnc() : e);
546 }
547 }
548 #endif
549
550 return;
551 }
552 }
553
554 } else if( gcode->has_m) {
555 switch( gcode->m ) {
556 // case 0: // M0 feed hold, (M0.1 is release feed hold, except we are in feed hold)
557 // if(THEKERNEL->is_grbl_mode()) THEKERNEL->set_feed_hold(gcode->subcode == 0);
558 // break;
559
560 case 30: // M30 end of program in grbl mode (otherwise it is delete sdcard file)
561 if(!THEKERNEL->is_grbl_mode()) break;
562 // fall through to M2
563 case 2: // M2 end of program
564 current_wcs = 0;
565 absolute_mode = true;
566 break;
567 case 17:
568 THEKERNEL->call_event(ON_ENABLE, (void*)1); // turn all enable pins on
569 break;
570
571 case 18: // this allows individual motors to be turned off, no parameters falls through to turn all off
572 if(gcode->get_num_args() > 0) {
573 // bitmap of motors to turn off, where bit 1:X, 2:Y, 3:Z, 4:A, 5:B, 6:C
574 uint32_t bm= 0;
575 for (int i = 0; i < n_motors; ++i) {
576 char axis= (i <= Z_AXIS ? 'X'+i : 'A'+(i-3));
577 if(gcode->has_letter(axis)) bm |= (0x02<<i); // set appropriate bit
578 }
579 // handle E parameter as currently selected extruder ABC
580 if(gcode->has_letter('E')) {
581 // find first selected extruder
582 int i= get_active_extruder();
583 if(i > 0) {
584 bm |= (0x02<<i); // set appropriate bit
585 }
586 }
587
588 THEKERNEL->conveyor->wait_for_idle();
589 THEKERNEL->call_event(ON_ENABLE, (void *)bm);
590 break;
591 }
592 // fall through
593 case 84:
594 THEKERNEL->conveyor->wait_for_idle();
595 THEKERNEL->call_event(ON_ENABLE, nullptr); // turn all enable pins off
596 break;
597
598 case 82: e_absolute_mode= true; break;
599 case 83: e_absolute_mode= false; break;
600
601 case 92: // M92 - set steps per mm
602 for (int i = 0; i < n_motors; ++i) {
603 char axis= (i <= Z_AXIS ? 'X'+i : 'A'+(i-A_AXIS));
604 if(gcode->has_letter(axis)) {
605 actuators[i]->change_steps_per_mm(this->to_millimeters(gcode->get_value(axis)));
606 }
607 gcode->stream->printf("%c:%f ", axis, actuators[i]->get_steps_per_mm());
608 }
609 gcode->add_nl = true;
610 check_max_actuator_speeds();
611 return;
612
613 case 114:{
614 char buf[64];
615 int n= print_position(gcode->subcode, buf, sizeof buf);
616 if(n > 0) gcode->txt_after_ok.append(buf, n);
617 return;
618 }
619
620 case 120: // push state
621 push_state();
622 break;
623
624 case 121: // pop state
625 pop_state();
626 break;
627
628 case 203: // M203 Set maximum feedrates in mm/sec, M203.1 set maximum actuator feedrates
629 if(gcode->get_num_args() == 0) {
630 for (size_t i = X_AXIS; i <= Z_AXIS; i++) {
631 gcode->stream->printf(" %c: %g ", 'X' + i, gcode->subcode == 0 ? this->max_speeds[i] : actuators[i]->get_max_rate());
632 }
633 if(gcode->subcode == 1) {
634 for (size_t i = A_AXIS; i < n_motors; i++) {
635 gcode->stream->printf(" %c: %g ", 'A' + i - A_AXIS, actuators[i]->get_max_rate());
636 }
637 }
638
639 gcode->add_nl = true;
640
641 }else{
642 for (size_t i = X_AXIS; i <= Z_AXIS; i++) {
643 if (gcode->has_letter('X' + i)) {
644 float v= gcode->get_value('X'+i);
645 if(gcode->subcode == 0) this->max_speeds[i]= v;
646 else if(gcode->subcode == 1) actuators[i]->set_max_rate(v);
647 }
648 }
649
650 if(gcode->subcode == 1) {
651 // ABC axis only handle actuator max speeds
652 for (size_t i = A_AXIS; i < n_motors; i++) {
653 if(actuators[i]->is_extruder()) continue; //extruders handle this themselves
654 int c= 'A' + i - A_AXIS;
655 if(gcode->has_letter(c)) {
656 float v= gcode->get_value(c);
657 actuators[i]->set_max_rate(v);
658 }
659 }
660 }
661
662
663 // this format is deprecated
664 if(gcode->subcode == 0 && (gcode->has_letter('A') || gcode->has_letter('B') || gcode->has_letter('C'))) {
665 gcode->stream->printf("NOTE this format is deprecated, Use M203.1 instead\n");
666 for (size_t i = X_AXIS; i <= Z_AXIS; i++) {
667 if (gcode->has_letter('A' + i)) {
668 float v= gcode->get_value('A'+i);
669 actuators[i]->set_max_rate(v);
670 }
671 }
672 }
673
674 if(gcode->subcode == 1) check_max_actuator_speeds();
675 }
676 break;
677
678 case 204: // M204 Snnn - set default acceleration to nnn, Xnnn Ynnn Znnn sets axis specific acceleration
679 if (gcode->has_letter('S')) {
680 float acc = gcode->get_value('S'); // mm/s^2
681 // enforce minimum
682 if (acc < 1.0F) acc = 1.0F;
683 this->default_acceleration = acc;
684 }
685 for (int i = 0; i < n_motors; ++i) {
686 if(actuators[i]->is_extruder()) continue; //extruders handle this themselves
687 char axis= (i <= Z_AXIS ? 'X'+i : 'A'+(i-A_AXIS));
688 if(gcode->has_letter(axis)) {
689 float acc = gcode->get_value(axis); // mm/s^2
690 // enforce positive
691 if (acc <= 0.0F) acc = NAN;
692 actuators[i]->set_acceleration(acc);
693 }
694 }
695 break;
696
697 case 205: // M205 Xnnn - set junction deviation, Z - set Z junction deviation, Snnn - Set minimum planner speed
698 if (gcode->has_letter('X')) {
699 float jd = gcode->get_value('X');
700 // enforce minimum
701 if (jd < 0.0F)
702 jd = 0.0F;
703 THEKERNEL->planner->junction_deviation = jd;
704 }
705 if (gcode->has_letter('Z')) {
706 float jd = gcode->get_value('Z');
707 // enforce minimum, -1 disables it and uses regular junction deviation
708 if (jd <= -1.0F)
709 jd = NAN;
710 THEKERNEL->planner->z_junction_deviation = jd;
711 }
712 if (gcode->has_letter('S')) {
713 float mps = gcode->get_value('S');
714 // enforce minimum
715 if (mps < 0.0F)
716 mps = 0.0F;
717 THEKERNEL->planner->minimum_planner_speed = mps;
718 }
719 break;
720
721 case 220: // M220 - speed override percentage
722 if (gcode->has_letter('S')) {
723 float factor = gcode->get_value('S');
724 // enforce minimum 10% speed
725 if (factor < 10.0F)
726 factor = 10.0F;
727 // enforce maximum 10x speed
728 if (factor > 1000.0F)
729 factor = 1000.0F;
730
731 seconds_per_minute = 6000.0F / factor;
732 } else {
733 gcode->stream->printf("Speed factor at %6.2f %%\n", 6000.0F / seconds_per_minute);
734 }
735 break;
736
737 case 400: // wait until all moves are done up to this point
738 THEKERNEL->conveyor->wait_for_idle();
739 break;
740
741 case 500: // M500 saves some volatile settings to config override file
742 case 503: { // M503 just prints the settings
743 gcode->stream->printf(";Steps per unit:\nM92 ");
744 for (int i = 0; i < n_motors; ++i) {
745 if(actuators[i]->is_extruder()) continue; //extruders handle this themselves
746 char axis= (i <= Z_AXIS ? 'X'+i : 'A'+(i-A_AXIS));
747 gcode->stream->printf("%c%1.5f ", axis, actuators[i]->get_steps_per_mm());
748 }
749 gcode->stream->printf("\n");
750
751 // only print if not NAN
752 gcode->stream->printf(";Acceleration mm/sec^2:\nM204 S%1.5f ", default_acceleration);
753 for (int i = 0; i < n_motors; ++i) {
754 if(actuators[i]->is_extruder()) continue; // extruders handle this themselves
755 char axis= (i <= Z_AXIS ? 'X'+i : 'A'+(i-A_AXIS));
756 if(!isnan(actuators[i]->get_acceleration())) gcode->stream->printf("%c%1.5f ", axis, actuators[i]->get_acceleration());
757 }
758 gcode->stream->printf("\n");
759
760 gcode->stream->printf(";X- Junction Deviation, Z- Z junction deviation, S - Minimum Planner speed mm/sec:\nM205 X%1.5f Z%1.5f S%1.5f\n", THEKERNEL->planner->junction_deviation, isnan(THEKERNEL->planner->z_junction_deviation)?-1:THEKERNEL->planner->z_junction_deviation, THEKERNEL->planner->minimum_planner_speed);
761
762 gcode->stream->printf(";Max cartesian feedrates in mm/sec:\nM203 X%1.5f Y%1.5f Z%1.5f\n", this->max_speeds[X_AXIS], this->max_speeds[Y_AXIS], this->max_speeds[Z_AXIS]);
763
764 gcode->stream->printf(";Max actuator feedrates in mm/sec:\nM203.1 ");
765 for (int i = 0; i < n_motors; ++i) {
766 if(actuators[i]->is_extruder()) continue; // extruders handle this themselves
767 char axis= (i <= Z_AXIS ? 'X'+i : 'A'+(i-A_AXIS));
768 gcode->stream->printf("%c%1.5f ", axis, actuators[i]->get_max_rate());
769 }
770 gcode->stream->printf("\n");
771
772 // get or save any arm solution specific optional values
773 BaseSolution::arm_options_t options;
774 if(arm_solution->get_optional(options) && !options.empty()) {
775 gcode->stream->printf(";Optional arm solution specific settings:\nM665");
776 for(auto &i : options) {
777 gcode->stream->printf(" %c%1.4f", i.first, i.second);
778 }
779 gcode->stream->printf("\n");
780 }
781
782 // save wcs_offsets and current_wcs
783 // TODO this may need to be done whenever they change to be compliant
784 gcode->stream->printf(";WCS settings\n");
785 gcode->stream->printf("%s\n", wcs2gcode(current_wcs).c_str());
786 int n = 1;
787 for(auto &i : wcs_offsets) {
788 if(i != wcs_t(0, 0, 0)) {
789 float x, y, z;
790 std::tie(x, y, z) = i;
791 gcode->stream->printf("G10 L2 P%d X%f Y%f Z%f ; %s\n", n, x, y, z, wcs2gcode(n-1).c_str());
792 }
793 ++n;
794 }
795 if(save_g92) {
796 // linuxcnc saves G92, so we do too if configured, default is to not save to maintain backward compatibility
797 // also it needs to be used to set Z0 on rotary deltas as M206/306 can't be used, so saving it is necessary in that case
798 if(g92_offset != wcs_t(0, 0, 0)) {
799 float x, y, z;
800 std::tie(x, y, z) = g92_offset;
801 gcode->stream->printf("G92.3 X%f Y%f Z%f\n", x, y, z); // sets G92 to the specified values
802 }
803 }
804 }
805 break;
806
807 case 665: { // M665 set optional arm solution variables based on arm solution.
808 // the parameter args could be any letter each arm solution only accepts certain ones
809 BaseSolution::arm_options_t options = gcode->get_args();
810 options.erase('S'); // don't include the S
811 options.erase('U'); // don't include the U
812 if(options.size() > 0) {
813 // set the specified options
814 arm_solution->set_optional(options);
815 }
816 options.clear();
817 if(arm_solution->get_optional(options)) {
818 // foreach optional value
819 for(auto &i : options) {
820 // print all current values of supported options
821 gcode->stream->printf("%c: %8.4f ", i.first, i.second);
822 gcode->add_nl = true;
823 }
824 }
825
826 if(gcode->has_letter('S')) { // set delta segments per second, not saved by M500
827 this->delta_segments_per_second = gcode->get_value('S');
828 gcode->stream->printf("Delta segments set to %8.4f segs/sec\n", this->delta_segments_per_second);
829
830 } else if(gcode->has_letter('U')) { // or set mm_per_line_segment, not saved by M500
831 this->mm_per_line_segment = gcode->get_value('U');
832 this->delta_segments_per_second = 0;
833 gcode->stream->printf("mm per line segment set to %8.4f\n", this->mm_per_line_segment);
834 }
835
836 break;
837 }
838 }
839 }
840
841 if( motion_mode != NONE) {
842 is_g123= motion_mode != SEEK;
843 process_move(gcode, motion_mode);
844
845 }else{
846 is_g123= false;
847 }
848
849 next_command_is_MCS = false; // must be on same line as G0 or G1
850 }
851
852 int Robot::get_active_extruder() const
853 {
854 for (int i = E_AXIS; i < n_motors; ++i) {
855 // find first selected extruder
856 if(actuators[i]->is_extruder() && actuators[i]->is_selected()) return i;
857 }
858 return 0;
859 }
860
861 // process a G0/G1/G2/G3
862 void Robot::process_move(Gcode *gcode, enum MOTION_MODE_T motion_mode)
863 {
864 // we have a G0/G1/G2/G3 so extract parameters and apply offsets to get machine coordinate target
865 // get XYZ and one E (which goes to the selected extruder)
866 float param[4]{NAN, NAN, NAN, NAN};
867
868 // process primary axis
869 for(int i= X_AXIS; i <= Z_AXIS; ++i) {
870 char letter= 'X'+i;
871 if( gcode->has_letter(letter) ) {
872 param[i] = this->to_millimeters(gcode->get_value(letter));
873 }
874 }
875
876 float offset[3]{0,0,0};
877 for(char letter = 'I'; letter <= 'K'; letter++) {
878 if( gcode->has_letter(letter) ) {
879 offset[letter - 'I'] = this->to_millimeters(gcode->get_value(letter));
880 }
881 }
882
883 // calculate target in machine coordinates (less compensation transform which needs to be done after segmentation)
884 float target[n_motors];
885 memcpy(target, machine_position, n_motors*sizeof(float));
886
887 if(!next_command_is_MCS) {
888 if(this->absolute_mode) {
889 // apply wcs offsets and g92 offset and tool offset
890 if(!isnan(param[X_AXIS])) {
891 target[X_AXIS]= param[X_AXIS] + std::get<X_AXIS>(wcs_offsets[current_wcs]) - std::get<X_AXIS>(g92_offset) + std::get<X_AXIS>(tool_offset);
892 }
893
894 if(!isnan(param[Y_AXIS])) {
895 target[Y_AXIS]= param[Y_AXIS] + std::get<Y_AXIS>(wcs_offsets[current_wcs]) - std::get<Y_AXIS>(g92_offset) + std::get<Y_AXIS>(tool_offset);
896 }
897
898 if(!isnan(param[Z_AXIS])) {
899 target[Z_AXIS]= param[Z_AXIS] + std::get<Z_AXIS>(wcs_offsets[current_wcs]) - std::get<Z_AXIS>(g92_offset) + std::get<Z_AXIS>(tool_offset);
900 }
901
902 }else{
903 // they are deltas from the machine_position if specified
904 for(int i= X_AXIS; i <= Z_AXIS; ++i) {
905 if(!isnan(param[i])) target[i] = param[i] + machine_position[i];
906 }
907 }
908
909 }else{
910 // already in machine coordinates, we do not add tool offset for that
911 for(int i= X_AXIS; i <= Z_AXIS; ++i) {
912 if(!isnan(param[i])) target[i] = param[i];
913 }
914 }
915
916 float delta_e= NAN;
917
918 #if MAX_ROBOT_ACTUATORS > 3
919 // process extruder parameters, for active extruder only (only one active extruder at a time)
920 int selected_extruder= 0;
921 if(gcode->has_letter('E')) {
922 selected_extruder= get_active_extruder();
923 param[E_AXIS]= gcode->get_value('E');
924 }
925
926 // do E for the selected extruder
927 if(selected_extruder > 0 && !isnan(param[E_AXIS])) {
928 if(this->e_absolute_mode) {
929 target[selected_extruder]= param[E_AXIS];
930 delta_e= target[selected_extruder] - machine_position[selected_extruder];
931 }else{
932 delta_e= param[E_AXIS];
933 target[selected_extruder] = delta_e + machine_position[selected_extruder];
934 }
935 }
936
937 // process ABC axis, this is mutually exclusive to using E for an extruder, so if E is used and A then the results are undefined
938 for (int i = A_AXIS; i < n_motors; ++i) {
939 char letter= 'A'+i-A_AXIS;
940 if(gcode->has_letter(letter)) {
941 float p= gcode->get_value(letter);
942 if(this->absolute_mode) {
943 target[i]= p;
944 }else{
945 target[i]= p + machine_position[i];
946 }
947 }
948 }
949 #endif
950
951 if( gcode->has_letter('F') ) {
952 if( motion_mode == SEEK )
953 this->seek_rate = this->to_millimeters( gcode->get_value('F') );
954 else
955 this->feed_rate = this->to_millimeters( gcode->get_value('F') );
956 }
957
958 // S is modal When specified on a G0/1/2/3 command
959 if(gcode->has_letter('S')) s_value= gcode->get_value('S');
960
961 bool moved= false;
962
963 // Perform any physical actions
964 switch(motion_mode) {
965 case NONE: break;
966
967 case SEEK:
968 moved= this->append_line(gcode, target, this->seek_rate / seconds_per_minute, delta_e );
969 break;
970
971 case LINEAR:
972 moved= this->append_line(gcode, target, this->feed_rate / seconds_per_minute, delta_e );
973 break;
974
975 case CW_ARC:
976 case CCW_ARC:
977 // Note arcs are not currently supported by extruder based machines, as 3D slicers do not use arcs (G2/G3)
978 moved= this->compute_arc(gcode, offset, target, motion_mode);
979 break;
980 }
981
982 if(moved) {
983 // set machine_position to the calculated target
984 memcpy(machine_position, target, n_motors*sizeof(float));
985 }
986 }
987
988 // reset the machine position for all axis. Used for homing.
989 // after homing we supply the cartesian coordinates that the head is at when homed,
990 // however for Z this is the compensated machine position (if enabled)
991 // So we need to apply the inverse compensation transform to the supplied coordinates to get the correct machine position
992 // this will make the results from M114 and ? consistent after homing.
993 // This works for cases where the Z endstop is fixed on the Z actuator and is the same regardless of where XY are.
994 void Robot::reset_axis_position(float x, float y, float z)
995 {
996 // set both the same initially
997 compensated_machine_position[X_AXIS]= machine_position[X_AXIS] = x;
998 compensated_machine_position[Y_AXIS]= machine_position[Y_AXIS] = y;
999 compensated_machine_position[Z_AXIS]= machine_position[Z_AXIS] = z;
1000
1001 if(compensationTransform) {
1002 // apply inverse transform to get machine_position
1003 compensationTransform(machine_position, true);
1004 }
1005
1006 // now set the actuator positions based on the supplied compensated position
1007 ActuatorCoordinates actuator_pos;
1008 arm_solution->cartesian_to_actuator(this->compensated_machine_position, actuator_pos);
1009 for (size_t i = X_AXIS; i <= Z_AXIS; i++)
1010 actuators[i]->change_last_milestone(actuator_pos[i]);
1011 }
1012
1013 // Reset the position for an axis (used in homing, and to reset extruder after suspend)
1014 void Robot::reset_axis_position(float position, int axis)
1015 {
1016 compensated_machine_position[axis] = position;
1017 if(axis <= Z_AXIS) {
1018 reset_axis_position(compensated_machine_position[X_AXIS], compensated_machine_position[Y_AXIS], compensated_machine_position[Z_AXIS]);
1019
1020 #if MAX_ROBOT_ACTUATORS > 3
1021 }else if(axis < n_motors) {
1022 // ABC and/or extruders need to be set as there is no arm solution for them
1023 machine_position[axis]= compensated_machine_position[axis]= position;
1024 actuators[axis]->change_last_milestone(machine_position[axis]);
1025 #endif
1026 }
1027 }
1028
1029 // similar to reset_axis_position but directly sets the actuator positions in actuators units (eg mm for cartesian, degrees for rotary delta)
1030 // then sets the axis positions to match. currently only called from Endstops.cpp and RotaryDeltaCalibration.cpp
1031 void Robot::reset_actuator_position(const ActuatorCoordinates &ac)
1032 {
1033 for (size_t i = X_AXIS; i <= Z_AXIS; i++) {
1034 if(!isnan(ac[i])) actuators[i]->change_last_milestone(ac[i]);
1035 }
1036
1037 // now correct axis positions then recorrect actuator to account for rounding
1038 reset_position_from_current_actuator_position();
1039 }
1040
1041 // Use FK to find out where actuator is and reset to match
1042 // TODO maybe we should only reset axis that are being homed unless this is due to a ON_HALT
1043 void Robot::reset_position_from_current_actuator_position()
1044 {
1045 ActuatorCoordinates actuator_pos;
1046 for (size_t i = X_AXIS; i < n_motors; i++) {
1047 // NOTE actuator::current_position is curently NOT the same as actuator::machine_position after an abrupt abort
1048 actuator_pos[i] = actuators[i]->get_current_position();
1049 }
1050
1051 // discover machine position from where actuators actually are
1052 arm_solution->actuator_to_cartesian(actuator_pos, compensated_machine_position);
1053 memcpy(machine_position, compensated_machine_position, sizeof machine_position);
1054
1055 // compensated_machine_position includes the compensation transform so we need to get the inverse to get actual machine_position
1056 if(compensationTransform) compensationTransform(machine_position, true); // get inverse compensation transform
1057
1058 // now reset actuator::machine_position, NOTE this may lose a little precision as FK is not always entirely accurate.
1059 // NOTE This is required to sync the machine position with the actuator position, we do a somewhat redundant cartesian_to_actuator() call
1060 // to get everything in perfect sync.
1061 arm_solution->cartesian_to_actuator(compensated_machine_position, actuator_pos);
1062 for (size_t i = X_AXIS; i <= Z_AXIS; i++) {
1063 actuators[i]->change_last_milestone(actuator_pos[i]);
1064 }
1065
1066 // Handle extruders and/or ABC axis
1067 #if MAX_ROBOT_ACTUATORS > 3
1068 for (int i = A_AXIS; i < n_motors; i++) {
1069 // ABC and/or extruders just need to set machine_position and compensated_machine_position
1070 float ap= actuator_pos[i];
1071 if(actuators[i]->is_extruder() && get_e_scale_fnc) ap /= get_e_scale_fnc(); // inverse E scale if there is one and this is an extruder
1072 machine_position[i]= compensated_machine_position[i]= ap;
1073 actuators[i]->change_last_milestone(actuator_pos[i]); // this updates the last_milestone in the actuator
1074 }
1075 #endif
1076 }
1077
1078 // Convert target (in machine coordinates) to machine_position, then convert to actuator position and append this to the planner
1079 // target is in machine coordinates without the compensation transform, however we save a compensated_machine_position that includes
1080 // all transforms and is what we actually convert to actuator positions
1081 bool Robot::append_milestone(const float target[], float rate_mm_s)
1082 {
1083 float deltas[n_motors];
1084 float transformed_target[n_motors]; // adjust target for bed compensation
1085 float unit_vec[N_PRIMARY_AXIS];
1086
1087 // unity transform by default
1088 memcpy(transformed_target, target, n_motors*sizeof(float));
1089
1090 // check function pointer and call if set to transform the target to compensate for bed
1091 if(compensationTransform) {
1092 // some compensation strategies can transform XYZ, some just change Z
1093 compensationTransform(transformed_target, false);
1094 }
1095
1096 bool move= false;
1097 float sos= 0; // sum of squares for just primary axis (XYZ usually)
1098
1099 // find distance moved by each axis, use transformed target from the current compensated machine position
1100 for (size_t i = 0; i < n_motors; i++) {
1101 deltas[i] = transformed_target[i] - compensated_machine_position[i];
1102 if(deltas[i] == 0) continue;
1103 // at least one non zero delta
1104 move = true;
1105 if(i < N_PRIMARY_AXIS) {
1106 sos += powf(deltas[i], 2);
1107 }
1108 }
1109
1110 // nothing moved
1111 if(!move) return false;
1112
1113 // see if this is a primary axis move or not
1114 bool auxilliary_move= true;
1115 for (int i = 0; i < N_PRIMARY_AXIS; ++i) {
1116 if(deltas[i] != 0) {
1117 auxilliary_move= false;
1118 break;
1119 }
1120 }
1121
1122 // total movement, use XYZ if a primary axis otherwise we calculate distance for E after scaling to mm
1123 float distance= auxilliary_move ? 0 : sqrtf(sos);
1124
1125 // it is unlikely but we need to protect against divide by zero, so ignore insanely small moves here
1126 // as the last milestone won't be updated we do not actually lose any moves as they will be accounted for in the next move
1127 if(!auxilliary_move && distance < 0.00001F) return false;
1128
1129
1130 if(!auxilliary_move) {
1131 for (size_t i = X_AXIS; i < N_PRIMARY_AXIS; i++) {
1132 // find distance unit vector for primary axis only
1133 unit_vec[i] = deltas[i] / distance;
1134
1135 // Do not move faster than the configured cartesian limits for XYZ
1136 if ( max_speeds[i] > 0 ) {
1137 float axis_speed = fabsf(unit_vec[i] * rate_mm_s);
1138
1139 if (axis_speed > max_speeds[i])
1140 rate_mm_s *= ( max_speeds[i] / axis_speed );
1141 }
1142 }
1143 }
1144
1145 // find actuator position given the machine position, use actual adjusted target
1146 ActuatorCoordinates actuator_pos;
1147 if(!disable_arm_solution) {
1148 arm_solution->cartesian_to_actuator( transformed_target, actuator_pos );
1149
1150 }else{
1151 // basically the same as cartesian, would be used for special homing situations like for scara
1152 for (size_t i = X_AXIS; i <= Z_AXIS; i++) {
1153 actuator_pos[i] = transformed_target[i];
1154 }
1155 }
1156
1157 #if MAX_ROBOT_ACTUATORS > 3
1158 sos= 0;
1159 // for the extruders just copy the position, and possibly scale it from mm³ to mm
1160 for (size_t i = E_AXIS; i < n_motors; i++) {
1161 actuator_pos[i]= transformed_target[i];
1162 if(actuators[i]->is_extruder() && get_e_scale_fnc) {
1163 // NOTE this relies on the fact only one extruder is active at a time
1164 // scale for volumetric or flow rate
1165 // TODO is this correct? scaling the absolute target? what if the scale changes?
1166 // for volumetric it basically converts mm³ to mm, but what about flow rate?
1167 actuator_pos[i] *= get_e_scale_fnc();
1168 }
1169 if(auxilliary_move) {
1170 // for E only moves we need to use the scaled E to calculate the distance
1171 sos += pow(actuator_pos[i] - actuators[i]->get_last_milestone(), 2);
1172 }
1173 }
1174 if(auxilliary_move) {
1175 distance= sqrtf(sos); // distance in mm of the e move
1176 if(distance < 0.00001F) return false;
1177 }
1178 #endif
1179
1180 // use default acceleration to start with
1181 float acceleration = default_acceleration;
1182
1183 float isecs = rate_mm_s / distance;
1184
1185 // check per-actuator speed limits
1186 for (size_t actuator = 0; actuator < n_motors; actuator++) {
1187 float d = fabsf(actuator_pos[actuator] - actuators[actuator]->get_last_milestone());
1188 if(d == 0 || !actuators[actuator]->is_selected()) continue; // no movement for this actuator
1189
1190 float actuator_rate= d * isecs;
1191 if (actuator_rate > actuators[actuator]->get_max_rate()) {
1192 rate_mm_s *= (actuators[actuator]->get_max_rate() / actuator_rate);
1193 isecs = rate_mm_s / distance;
1194 }
1195
1196 // adjust acceleration to lowest found, for now just primary axis unless it is an auxiliary move
1197 // TODO we may need to do all of them, check E won't limit XYZ.. it does on long E moves, but not checking it could exceed the E acceleration.
1198 if(auxilliary_move || actuator < N_PRIMARY_AXIS) {
1199 float ma = actuators[actuator]->get_acceleration(); // in mm/sec²
1200 if(!isnan(ma)) { // if axis does not have acceleration set then it uses the default_acceleration
1201 float ca = fabsf((d/distance) * acceleration);
1202 if (ca > ma) {
1203 acceleration *= ( ma / ca );
1204 }
1205 }
1206 }
1207 }
1208
1209 // Append the block to the planner
1210 // NOTE that distance here should be either the distance travelled by the XYZ axis, or the E mm travel if a solo E move
1211 if(THEKERNEL->planner->append_block( actuator_pos, n_motors, rate_mm_s, distance, auxilliary_move ? nullptr : unit_vec, acceleration, s_value, is_g123)) {
1212 // this is the new compensated machine position
1213 memcpy(this->compensated_machine_position, transformed_target, n_motors*sizeof(float));
1214 return true;
1215 }
1216
1217 // no actual move
1218 return false;
1219 }
1220
1221 // Used to plan a single move used by things like endstops when homing, zprobe, extruder firmware retracts etc.
1222 bool Robot::delta_move(const float *delta, float rate_mm_s, uint8_t naxis)
1223 {
1224 if(THEKERNEL->is_halted()) return false;
1225
1226 // catch negative or zero feed rates
1227 if(rate_mm_s <= 0.0F) {
1228 return false;
1229 }
1230
1231 // get the absolute target position, default is current machine_position
1232 float target[n_motors];
1233 memcpy(target, machine_position, n_motors*sizeof(float));
1234
1235 // add in the deltas to get new target
1236 for (int i= 0; i < naxis; i++) {
1237 target[i] += delta[i];
1238 }
1239
1240 // submit for planning and if moved update machine_position
1241 if(append_milestone(target, rate_mm_s)) {
1242 memcpy(machine_position, target, n_motors*sizeof(float));
1243 return true;
1244 }
1245
1246 return false;
1247 }
1248
1249 // Append a move to the queue ( cutting it into segments if needed )
1250 bool Robot::append_line(Gcode *gcode, const float target[], float rate_mm_s, float delta_e)
1251 {
1252 // catch negative or zero feed rates and return the same error as GRBL does
1253 if(rate_mm_s <= 0.0F) {
1254 gcode->is_error= true;
1255 gcode->txt_after_ok= (rate_mm_s == 0 ? "Undefined feed rate" : "feed rate < 0");
1256 return false;
1257 }
1258
1259 // Find out the distance for this move in XYZ in MCS
1260 float millimeters_of_travel = sqrtf(powf( target[X_AXIS] - machine_position[X_AXIS], 2 ) + powf( target[Y_AXIS] - machine_position[Y_AXIS], 2 ) + powf( target[Z_AXIS] - machine_position[Z_AXIS], 2 ));
1261
1262 if(millimeters_of_travel < 0.00001F) {
1263 // we have no movement in XYZ, probably E only extrude or retract
1264 return this->append_milestone(target, rate_mm_s);
1265 }
1266
1267 /*
1268 For extruders, we need to do some extra work to limit the volumetric rate if specified...
1269 If using volumetric limts we need to be using volumetric extrusion for this to work as Ennn needs to be in mm³ not mm
1270 We ask Extruder to do all the work but we need to pass in the relevant data.
1271 NOTE we need to do this before we segment the line (for deltas)
1272 */
1273 if(!isnan(delta_e) && gcode->has_g && gcode->g == 1) {
1274 float data[2]= {delta_e, rate_mm_s / millimeters_of_travel};
1275 if(PublicData::set_value(extruder_checksum, target_checksum, data)) {
1276 rate_mm_s *= data[1]; // adjust the feedrate
1277 }
1278 }
1279
1280 // We cut the line into smaller segments. This is only needed on a cartesian robot for zgrid, but always necessary for robots with rotational axes like Deltas.
1281 // In delta robots either mm_per_line_segment can be used OR delta_segments_per_second
1282 // The latter is more efficient and avoids splitting fast long lines into very small segments, like initial z move to 0, it is what Johanns Marlin delta port does
1283 uint16_t segments;
1284
1285 if(this->disable_segmentation || (!segment_z_moves && !gcode->has_letter('X') && !gcode->has_letter('Y'))) {
1286 segments= 1;
1287
1288 } else if(this->delta_segments_per_second > 1.0F) {
1289 // enabled if set to something > 1, it is set to 0.0 by default
1290 // segment based on current speed and requested segments per second
1291 // the faster the travel speed the fewer segments needed
1292 // NOTE rate is mm/sec and we take into account any speed override
1293 float seconds = millimeters_of_travel / rate_mm_s;
1294 segments = max(1.0F, ceilf(this->delta_segments_per_second * seconds));
1295 // TODO if we are only moving in Z on a delta we don't really need to segment at all
1296
1297 } else {
1298 if(this->mm_per_line_segment == 0.0F) {
1299 segments = 1; // don't split it up
1300 } else {
1301 segments = ceilf( millimeters_of_travel / this->mm_per_line_segment);
1302 }
1303 }
1304
1305 bool moved= false;
1306 if (segments > 1) {
1307 // A vector to keep track of the endpoint of each segment
1308 float segment_delta[n_motors];
1309 float segment_end[n_motors];
1310 memcpy(segment_end, machine_position, n_motors*sizeof(float));
1311
1312 // How far do we move each segment?
1313 for (int i = 0; i < n_motors; i++)
1314 segment_delta[i] = (target[i] - machine_position[i]) / segments;
1315
1316 // segment 0 is already done - it's the end point of the previous move so we start at segment 1
1317 // We always add another point after this loop so we stop at segments-1, ie i < segments
1318 for (int i = 1; i < segments; i++) {
1319 if(THEKERNEL->is_halted()) return false; // don't queue any more segments
1320 for (int i = 0; i < n_motors; i++)
1321 segment_end[i] += segment_delta[i];
1322
1323 // Append the end of this segment to the queue
1324 bool b= this->append_milestone(segment_end, rate_mm_s);
1325 moved= moved || b;
1326 }
1327 }
1328
1329 // Append the end of this full move to the queue
1330 if(this->append_milestone(target, rate_mm_s)) moved= true;
1331
1332 this->next_command_is_MCS = false; // always reset this
1333
1334 return moved;
1335 }
1336
1337
1338 // Append an arc to the queue ( cutting it into segments as needed )
1339 // TODO does not support any E parameters so cannot be used for 3D printing.
1340 bool Robot::append_arc(Gcode * gcode, const float target[], const float offset[], float radius, bool is_clockwise )
1341 {
1342 float rate_mm_s= this->feed_rate / seconds_per_minute;
1343 // catch negative or zero feed rates and return the same error as GRBL does
1344 if(rate_mm_s <= 0.0F) {
1345 gcode->is_error= true;
1346 gcode->txt_after_ok= (rate_mm_s == 0 ? "Undefined feed rate" : "feed rate < 0");
1347 return false;
1348 }
1349
1350 // Scary math
1351 float center_axis0 = this->machine_position[this->plane_axis_0] + offset[this->plane_axis_0];
1352 float center_axis1 = this->machine_position[this->plane_axis_1] + offset[this->plane_axis_1];
1353 float linear_travel = target[this->plane_axis_2] - this->machine_position[this->plane_axis_2];
1354 float r_axis0 = -offset[this->plane_axis_0]; // Radius vector from center to current location
1355 float r_axis1 = -offset[this->plane_axis_1];
1356 float rt_axis0 = target[this->plane_axis_0] - center_axis0;
1357 float rt_axis1 = target[this->plane_axis_1] - center_axis1;
1358
1359 // Patch from GRBL Firmware - Christoph Baumann 04072015
1360 // CCW angle between position and target from circle center. Only one atan2() trig computation required.
1361 float angular_travel = atan2f(r_axis0 * rt_axis1 - r_axis1 * rt_axis0, r_axis0 * rt_axis0 + r_axis1 * rt_axis1);
1362 if (is_clockwise) { // Correct atan2 output per direction
1363 if (angular_travel >= -ARC_ANGULAR_TRAVEL_EPSILON) { angular_travel -= (2 * PI); }
1364 } else {
1365 if (angular_travel <= ARC_ANGULAR_TRAVEL_EPSILON) { angular_travel += (2 * PI); }
1366 }
1367
1368 // Find the distance for this gcode
1369 float millimeters_of_travel = hypotf(angular_travel * radius, fabsf(linear_travel));
1370
1371 // We don't care about non-XYZ moves ( for example the extruder produces some of those )
1372 if( millimeters_of_travel < 0.00001F ) {
1373 return false;
1374 }
1375
1376 // limit segments by maximum arc error
1377 float arc_segment = this->mm_per_arc_segment;
1378 if ((this->mm_max_arc_error > 0) && (2 * radius > this->mm_max_arc_error)) {
1379 float min_err_segment = 2 * sqrtf((this->mm_max_arc_error * (2 * radius - this->mm_max_arc_error)));
1380 if (this->mm_per_arc_segment < min_err_segment) {
1381 arc_segment = min_err_segment;
1382 }
1383 }
1384 // Figure out how many segments for this gcode
1385 // TODO for deltas we need to make sure we are at least as many segments as requested, also if mm_per_line_segment is set we need to use the
1386 uint16_t segments = ceilf(millimeters_of_travel / arc_segment);
1387
1388 //printf("Radius %f - Segment Length %f - Number of Segments %d\r\n",radius,arc_segment,segments); // Testing Purposes ONLY
1389 float theta_per_segment = angular_travel / segments;
1390 float linear_per_segment = linear_travel / segments;
1391
1392 /* Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
1393 and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
1394 r_T = [cos(phi) -sin(phi);
1395 sin(phi) cos(phi] * r ;
1396 For arc generation, the center of the circle is the axis of rotation and the radius vector is
1397 defined from the circle center to the initial position. Each line segment is formed by successive
1398 vector rotations. This requires only two cos() and sin() computations to form the rotation
1399 matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
1400 all float numbers are single precision on the Arduino. (True float precision will not have
1401 round off issues for CNC applications.) Single precision error can accumulate to be greater than
1402 tool precision in some cases. Therefore, arc path correction is implemented.
1403
1404 Small angle approximation may be used to reduce computation overhead further. This approximation
1405 holds for everything, but very small circles and large mm_per_arc_segment values. In other words,
1406 theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
1407 to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
1408 numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
1409 issue for CNC machines with the single precision Arduino calculations.
1410 This approximation also allows mc_arc to immediately insert a line segment into the planner
1411 without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
1412 a correction, the planner should have caught up to the lag caused by the initial mc_arc overhead.
1413 This is important when there are successive arc motions.
1414 */
1415 // Vector rotation matrix values
1416 float cos_T = 1 - 0.5F * theta_per_segment * theta_per_segment; // Small angle approximation
1417 float sin_T = theta_per_segment;
1418
1419 // TODO we need to handle the ABC axis here by segmenting them
1420 float arc_target[3];
1421 float sin_Ti;
1422 float cos_Ti;
1423 float r_axisi;
1424 uint16_t i;
1425 int8_t count = 0;
1426
1427 // Initialize the linear axis
1428 arc_target[this->plane_axis_2] = this->machine_position[this->plane_axis_2];
1429
1430 bool moved= false;
1431 for (i = 1; i < segments; i++) { // Increment (segments-1)
1432 if(THEKERNEL->is_halted()) return false; // don't queue any more segments
1433
1434 if (count < this->arc_correction ) {
1435 // Apply vector rotation matrix
1436 r_axisi = r_axis0 * sin_T + r_axis1 * cos_T;
1437 r_axis0 = r_axis0 * cos_T - r_axis1 * sin_T;
1438 r_axis1 = r_axisi;
1439 count++;
1440 } else {
1441 // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
1442 // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
1443 cos_Ti = cosf(i * theta_per_segment);
1444 sin_Ti = sinf(i * theta_per_segment);
1445 r_axis0 = -offset[this->plane_axis_0] * cos_Ti + offset[this->plane_axis_1] * sin_Ti;
1446 r_axis1 = -offset[this->plane_axis_0] * sin_Ti - offset[this->plane_axis_1] * cos_Ti;
1447 count = 0;
1448 }
1449
1450 // Update arc_target location
1451 arc_target[this->plane_axis_0] = center_axis0 + r_axis0;
1452 arc_target[this->plane_axis_1] = center_axis1 + r_axis1;
1453 arc_target[this->plane_axis_2] += linear_per_segment;
1454
1455 // Append this segment to the queue
1456 bool b= this->append_milestone(arc_target, rate_mm_s);
1457 moved= moved || b;
1458 }
1459
1460 // Ensure last segment arrives at target location.
1461 if(this->append_milestone(target, rate_mm_s)) moved= true;
1462
1463 return moved;
1464 }
1465
1466 // Do the math for an arc and add it to the queue
1467 bool Robot::compute_arc(Gcode * gcode, const float offset[], const float target[], enum MOTION_MODE_T motion_mode)
1468 {
1469
1470 // Find the radius
1471 float radius = hypotf(offset[this->plane_axis_0], offset[this->plane_axis_1]);
1472
1473 // Set clockwise/counter-clockwise sign for mc_arc computations
1474 bool is_clockwise = false;
1475 if( motion_mode == CW_ARC ) {
1476 is_clockwise = true;
1477 }
1478
1479 // Append arc
1480 return this->append_arc(gcode, target, offset, radius, is_clockwise );
1481 }
1482
1483
1484 float Robot::theta(float x, float y)
1485 {
1486 float t = atanf(x / fabs(y));
1487 if (y > 0) {
1488 return(t);
1489 } else {
1490 if (t > 0) {
1491 return(PI - t);
1492 } else {
1493 return(-PI - t);
1494 }
1495 }
1496 }
1497
1498 void Robot::select_plane(uint8_t axis_0, uint8_t axis_1, uint8_t axis_2)
1499 {
1500 this->plane_axis_0 = axis_0;
1501 this->plane_axis_1 = axis_1;
1502 this->plane_axis_2 = axis_2;
1503 }
1504
1505 void Robot::clearToolOffset()
1506 {
1507 this->tool_offset= wcs_t(0,0,0);
1508 }
1509
1510 void Robot::setToolOffset(const float offset[3])
1511 {
1512 this->tool_offset= wcs_t(offset[0], offset[1], offset[2]);
1513 }
1514
1515 float Robot::get_feed_rate() const
1516 {
1517 return THEKERNEL->gcode_dispatch->get_modal_command() == 0 ? seek_rate : feed_rate;
1518 }