Merge pull request #313 from powertomato/feature/mri_all_locations
[clinton/Smoothieware.git] / src / modules / robot / Robot.cpp
CommitLineData
df27a6a3 1/*
aab6cbba 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)
4cff3ded
AW
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.
df27a6a3 5 You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
4cff3ded
AW
6*/
7
8#include "libs/Module.h"
9#include "libs/Kernel.h"
10#include <string>
11using std::string;
4cff3ded
AW
12#include <math.h>
13#include "Planner.h"
3fceb8eb 14#include "Conveyor.h"
4cff3ded
AW
15#include "Robot.h"
16#include "libs/nuts_bolts.h"
feb204be 17#include "libs/Pin.h"
670fa10b 18#include "libs/StepperMotor.h"
4cff3ded 19#include "../communication/utils/Gcode.h"
5647f709 20#include "PublicDataRequest.h"
4cff3ded
AW
21#include "arm_solutions/BaseSolution.h"
22#include "arm_solutions/CartesianSolution.h"
c41d6d95 23#include "arm_solutions/RotatableCartesianSolution.h"
4e04bcd3 24#include "arm_solutions/RostockSolution.h"
2c7ab192 25#include "arm_solutions/JohannKosselSolution.h"
bdaaa75d 26#include "arm_solutions/HBotSolution.h"
4cff3ded 27
43424972
JM
28#define default_seek_rate_checksum CHECKSUM("default_seek_rate")
29#define default_feed_rate_checksum CHECKSUM("default_feed_rate")
30#define mm_per_line_segment_checksum CHECKSUM("mm_per_line_segment")
31#define delta_segments_per_second_checksum CHECKSUM("delta_segments_per_second")
32#define mm_per_arc_segment_checksum CHECKSUM("mm_per_arc_segment")
33#define arc_correction_checksum CHECKSUM("arc_correction")
34#define x_axis_max_speed_checksum CHECKSUM("x_axis_max_speed")
35#define y_axis_max_speed_checksum CHECKSUM("y_axis_max_speed")
36#define z_axis_max_speed_checksum CHECKSUM("z_axis_max_speed")
37
38// arm solutions
39#define arm_solution_checksum CHECKSUM("arm_solution")
40#define cartesian_checksum CHECKSUM("cartesian")
41#define rotatable_cartesian_checksum CHECKSUM("rotatable_cartesian")
42#define rostock_checksum CHECKSUM("rostock")
43#define delta_checksum CHECKSUM("delta")
44#define hbot_checksum CHECKSUM("hbot")
45#define corexy_checksum CHECKSUM("corexy")
46#define kossel_checksum CHECKSUM("kossel")
47
edac9072
AW
48// 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
49// It takes care of cutting arcs into segments, same thing for line that are too long
41fd89e0 50#define max(a,b) (((a) > (b)) ? (a) : (b))
edac9072 51
4cff3ded 52Robot::Robot(){
a1b7e9f0 53 this->inch_mode = false;
0e8b102e 54 this->absolute_mode = true;
df27a6a3 55 this->motion_mode = MOTION_MODE_SEEK;
4cff3ded
AW
56 this->select_plane(X_AXIS, Y_AXIS, Z_AXIS);
57 clear_vector(this->current_position);
df27a6a3 58 clear_vector(this->last_milestone);
0b804a41 59 this->arm_solution = NULL;
7369629d 60 seconds_per_minute = 60.0;
4cff3ded
AW
61}
62
63//Called when the module has just been loaded
64void Robot::on_module_loaded() {
476dcb96 65 register_for_event(ON_CONFIG_RELOAD);
4cff3ded 66 this->register_for_event(ON_GCODE_RECEIVED);
b55cfff1
JM
67 this->register_for_event(ON_GET_PUBLIC_DATA);
68 this->register_for_event(ON_SET_PUBLIC_DATA);
4cff3ded
AW
69
70 // Configuration
da24d6ae 71 this->on_config_reload(this);
feb204be
AW
72
73 // Make our 3 StepperMotors
314ab8f7
MM
74 this->alpha_stepper_motor = THEKERNEL->step_ticker->add_stepper_motor( new StepperMotor(&alpha_step_pin,&alpha_dir_pin,&alpha_en_pin) );
75 this->beta_stepper_motor = THEKERNEL->step_ticker->add_stepper_motor( new StepperMotor(&beta_step_pin, &beta_dir_pin, &beta_en_pin ) );
76 this->gamma_stepper_motor = THEKERNEL->step_ticker->add_stepper_motor( new StepperMotor(&gamma_step_pin,&gamma_dir_pin,&gamma_en_pin) );
feb204be 77
da24d6ae
AW
78}
79
80void Robot::on_config_reload(void* argument){
5984acdf 81
edac9072
AW
82 // Arm solutions are used to convert positions in millimeters into position in steps for each stepper motor.
83 // While for a cartesian arm solution, this is a simple multiplication, in other, less simple cases, there is some serious math to be done.
84 // To make adding those solution easier, they have their own, separate object.
5984acdf 85 // Here we read the config to find out which arm solution to use
0b804a41 86 if (this->arm_solution) delete this->arm_solution;
314ab8f7 87 int solution_checksum = get_checksum(THEKERNEL->config->value(arm_solution_checksum)->by_default("cartesian")->as_string());
d149c730 88 // Note checksums are not const expressions when in debug mode, so don't use switch
98761c28 89 if(solution_checksum == hbot_checksum || solution_checksum == corexy_checksum) {
314ab8f7 90 this->arm_solution = new HBotSolution(THEKERNEL->config);
bdaaa75d
L
91
92 }else if(solution_checksum == rostock_checksum) {
314ab8f7 93 this->arm_solution = new RostockSolution(THEKERNEL->config);
73a4e3c0 94
2c7ab192 95 }else if(solution_checksum == kossel_checksum) {
314ab8f7 96 this->arm_solution = new JohannKosselSolution(THEKERNEL->config);
2c7ab192 97
d149c730 98 }else if(solution_checksum == delta_checksum) {
4a0c8e14 99 // place holder for now
314ab8f7 100 this->arm_solution = new RostockSolution(THEKERNEL->config);
73a4e3c0 101
b73a756d 102 }else if(solution_checksum == rotatable_cartesian_checksum) {
314ab8f7 103 this->arm_solution = new RotatableCartesianSolution(THEKERNEL->config);
b73a756d 104
d149c730 105 }else if(solution_checksum == cartesian_checksum) {
314ab8f7 106 this->arm_solution = new CartesianSolution(THEKERNEL->config);
73a4e3c0 107
d149c730 108 }else{
314ab8f7 109 this->arm_solution = new CartesianSolution(THEKERNEL->config);
d149c730 110 }
73a4e3c0 111
0b804a41 112
314ab8f7
MM
113 this->feed_rate = THEKERNEL->config->value(default_feed_rate_checksum )->by_default(100 )->as_number() / 60;
114 this->seek_rate = THEKERNEL->config->value(default_seek_rate_checksum )->by_default(100 )->as_number() / 60;
1ad23cd3
MM
115 this->mm_per_line_segment = THEKERNEL->config->value(mm_per_line_segment_checksum )->by_default(0.0f )->as_number();
116 this->delta_segments_per_second = THEKERNEL->config->value(delta_segments_per_second_checksum )->by_default(0.0f )->as_number();
117 this->mm_per_arc_segment = THEKERNEL->config->value(mm_per_arc_segment_checksum )->by_default(0.5f )->as_number();
314ab8f7
MM
118 this->arc_correction = THEKERNEL->config->value(arc_correction_checksum )->by_default(5 )->as_number();
119 this->max_speeds[X_AXIS] = THEKERNEL->config->value(x_axis_max_speed_checksum )->by_default(60000 )->as_number();
120 this->max_speeds[Y_AXIS] = THEKERNEL->config->value(y_axis_max_speed_checksum )->by_default(60000 )->as_number();
121 this->max_speeds[Z_AXIS] = THEKERNEL->config->value(z_axis_max_speed_checksum )->by_default(300 )->as_number();
122 this->alpha_step_pin.from_string( THEKERNEL->config->value(alpha_step_pin_checksum )->by_default("2.0" )->as_string())->as_output();
123 this->alpha_dir_pin.from_string( THEKERNEL->config->value(alpha_dir_pin_checksum )->by_default("0.5" )->as_string())->as_output();
124 this->alpha_en_pin.from_string( THEKERNEL->config->value(alpha_en_pin_checksum )->by_default("0.4" )->as_string())->as_output();
125 this->beta_step_pin.from_string( THEKERNEL->config->value(beta_step_pin_checksum )->by_default("2.1" )->as_string())->as_output();
126 this->gamma_step_pin.from_string( THEKERNEL->config->value(gamma_step_pin_checksum )->by_default("2.2" )->as_string())->as_output();
127 this->gamma_dir_pin.from_string( THEKERNEL->config->value(gamma_dir_pin_checksum )->by_default("0.20" )->as_string())->as_output();
128 this->gamma_en_pin.from_string( THEKERNEL->config->value(gamma_en_pin_checksum )->by_default("0.19" )->as_string())->as_output();
129 this->beta_dir_pin.from_string( THEKERNEL->config->value(beta_dir_pin_checksum )->by_default("0.11" )->as_string())->as_output();
130 this->beta_en_pin.from_string( THEKERNEL->config->value(beta_en_pin_checksum )->by_default("0.10" )->as_string())->as_output();
feb204be 131
4cff3ded
AW
132}
133
5647f709 134void Robot::on_get_public_data(void* argument){
b55cfff1
JM
135 PublicDataRequest* pdr = static_cast<PublicDataRequest*>(argument);
136
137 if(!pdr->starts_with(robot_checksum)) return;
138
139 if(pdr->second_element_is(speed_override_percent_checksum)) {
1ad23cd3 140 static float return_data;
58d6d841 141 return_data= 100*this->seconds_per_minute/60;
b55cfff1
JM
142 pdr->set_data_ptr(&return_data);
143 pdr->set_taken();
98761c28 144
b55cfff1 145 }else if(pdr->second_element_is(current_position_checksum)) {
1ad23cd3 146 static float return_data[3];
b55cfff1
JM
147 return_data[0]= from_millimeters(this->current_position[0]);
148 return_data[1]= from_millimeters(this->current_position[1]);
149 return_data[2]= from_millimeters(this->current_position[2]);
150
151 pdr->set_data_ptr(&return_data);
98761c28 152 pdr->set_taken();
b55cfff1 153 }
5647f709
JM
154}
155
156void Robot::on_set_public_data(void* argument){
b55cfff1 157 PublicDataRequest* pdr = static_cast<PublicDataRequest*>(argument);
5647f709 158
b55cfff1 159 if(!pdr->starts_with(robot_checksum)) return;
5647f709 160
b55cfff1 161 if(pdr->second_element_is(speed_override_percent_checksum)) {
7a522ccc 162 // NOTE do not use this while printing!
1ad23cd3 163 float t= *static_cast<float*>(pdr->get_data_ptr());
98761c28
JM
164 // enforce minimum 10% speed
165 if (t < 10.0) t= 10.0;
166
35089dc7 167 this->seconds_per_minute= t * 0.6;
b55cfff1
JM
168 pdr->set_taken();
169 }
5647f709
JM
170}
171
4cff3ded 172//A GCode has been received
edac9072 173//See if the current Gcode line has some orders for us
4cff3ded
AW
174void Robot::on_gcode_received(void * argument){
175 Gcode* gcode = static_cast<Gcode*>(argument);
6bc4a00a 176
4cff3ded
AW
177 //Temp variables, constant properties are stored in the object
178 uint8_t next_action = NEXT_ACTION_DEFAULT;
23c90ba6 179 this->motion_mode = -1;
4cff3ded
AW
180
181 //G-letter Gcodes are mostly what the Robot module is interrested in, other modules also catch the gcode event and do stuff accordingly
3c4f2dd8
AW
182 if( gcode->has_g){
183 switch( gcode->g ){
74b6303c
DD
184 case 0: this->motion_mode = MOTION_MODE_SEEK; gcode->mark_as_taken(); break;
185 case 1: this->motion_mode = MOTION_MODE_LINEAR; gcode->mark_as_taken(); break;
186 case 2: this->motion_mode = MOTION_MODE_CW_ARC; gcode->mark_as_taken(); break;
187 case 3: this->motion_mode = MOTION_MODE_CCW_ARC; gcode->mark_as_taken(); break;
188 case 17: this->select_plane(X_AXIS, Y_AXIS, Z_AXIS); gcode->mark_as_taken(); break;
189 case 18: this->select_plane(X_AXIS, Z_AXIS, Y_AXIS); gcode->mark_as_taken(); break;
190 case 19: this->select_plane(Y_AXIS, Z_AXIS, X_AXIS); gcode->mark_as_taken(); break;
191 case 20: this->inch_mode = true; gcode->mark_as_taken(); break;
192 case 21: this->inch_mode = false; gcode->mark_as_taken(); break;
193 case 90: this->absolute_mode = true; gcode->mark_as_taken(); break;
194 case 91: this->absolute_mode = false; gcode->mark_as_taken(); break;
0b804a41 195 case 92: {
6bc4a00a 196 if(gcode->get_num_args() == 0){
8a23b271 197 clear_vector(this->last_milestone);
6bc4a00a 198 }else{
eaf8a8a8
BG
199 for (char letter = 'X'; letter <= 'Z'; letter++){
200 if ( gcode->has_letter(letter) )
6bc4a00a 201 this->last_milestone[letter-'X'] = this->to_millimeters(gcode->get_value(letter));
eaf8a8a8 202 }
6bc4a00a 203 }
1ad23cd3 204 memcpy(this->current_position, this->last_milestone, sizeof(float)*3); // current_position[] = last_milestone[];
314ab8f7 205 this->arm_solution->millimeters_to_steps(this->current_position, THEKERNEL->planner->position);
74b6303c 206 gcode->mark_as_taken();
6bc4a00a
MM
207 return; // TODO: Wait until queue empty
208 }
209 }
3c4f2dd8 210 }else if( gcode->has_m){
1ad23cd3 211 float steps[3];
33e4cc02 212 switch( gcode->m ){
0fb5b438 213 case 92: // M92 - set steps per mm
0fb5b438
MM
214 this->arm_solution->get_steps_per_millimeter(steps);
215 if (gcode->has_letter('X'))
216 steps[0] = this->to_millimeters(gcode->get_value('X'));
217 if (gcode->has_letter('Y'))
218 steps[1] = this->to_millimeters(gcode->get_value('Y'));
219 if (gcode->has_letter('Z'))
220 steps[2] = this->to_millimeters(gcode->get_value('Z'));
7369629d
MM
221 if (gcode->has_letter('F'))
222 seconds_per_minute = gcode->get_value('F');
0fb5b438
MM
223 this->arm_solution->set_steps_per_millimeter(steps);
224 // update current position in steps
314ab8f7 225 this->arm_solution->millimeters_to_steps(this->current_position, THEKERNEL->planner->position);
7369629d 226 gcode->stream->printf("X:%g Y:%g Z:%g F:%g ", steps[0], steps[1], steps[2], seconds_per_minute);
0fb5b438 227 gcode->add_nl = true;
74b6303c 228 gcode->mark_as_taken();
0fb5b438 229 return;
58d6d841 230 case 114: gcode->stream->printf("C: X:%1.3f Y:%1.3f Z:%1.3f ",
bce9410e
MM
231 from_millimeters(this->current_position[0]),
232 from_millimeters(this->current_position[1]),
233 from_millimeters(this->current_position[2]));
6989211c 234 gcode->add_nl = true;
74b6303c 235 gcode->mark_as_taken();
6989211c 236 return;
33e4cc02 237
494dc541 238 // TODO I'm not sure if the following is safe to do here, or should it go on the block queue?
d4ee6ee2
JM
239 case 204: // M204 Snnn - set acceleration to nnn, NB only Snnn is currently supported
240 gcode->mark_as_taken();
241 if (gcode->has_letter('S'))
242 {
1ad23cd3 243 float acc= gcode->get_value('S') * 60 * 60; // mm/min^2
d4ee6ee2
JM
244 // enforce minimum
245 if (acc < 1.0)
246 acc = 1.0;
314ab8f7 247 THEKERNEL->planner->acceleration= acc;
d4ee6ee2
JM
248 }
249 break;
250
8b69c90d 251 case 205: // M205 Xnnn - set junction deviation Snnn - Set minimum planner speed
d4ee6ee2
JM
252 gcode->mark_as_taken();
253 if (gcode->has_letter('X'))
254 {
1ad23cd3 255 float jd= gcode->get_value('X');
d4ee6ee2 256 // enforce minimum
8b69c90d
JM
257 if (jd < 0.0F)
258 jd = 0.0F;
314ab8f7 259 THEKERNEL->planner->junction_deviation= jd;
d4ee6ee2 260 }
8b69c90d
JM
261 if (gcode->has_letter('S'))
262 {
263 float mps= gcode->get_value('S');
264 // enforce minimum
265 if (mps < 0.0F)
266 mps = 0.0F;
267 THEKERNEL->planner->minimum_planner_speed= mps;
268 }
d4ee6ee2 269 break;
98761c28 270
7369629d 271 case 220: // M220 - speed override percentage
74b6303c 272 gcode->mark_as_taken();
7369629d
MM
273 if (gcode->has_letter('S'))
274 {
1ad23cd3 275 float factor = gcode->get_value('S');
98761c28
JM
276 // enforce minimum 10% speed
277 if (factor < 10.0)
278 factor = 10.0;
7369629d
MM
279 seconds_per_minute = factor * 0.6;
280 }
b4f56013 281 break;
ec4773e5 282
494dc541
JM
283 case 400: // wait until all moves are done up to this point
284 gcode->mark_as_taken();
314ab8f7 285 THEKERNEL->conveyor->wait_for_empty_queue();
494dc541
JM
286 break;
287
33e4cc02
JM
288 case 500: // M500 saves some volatile settings to config override file
289 case 503: // M503 just prints the settings
290 this->arm_solution->get_steps_per_millimeter(steps);
adf89655 291 gcode->stream->printf(";Steps per unit:\nM92 X%1.5f Y%1.5f Z%1.5f\n", steps[0], steps[1], steps[2]);
314ab8f7 292 gcode->stream->printf(";Acceleration mm/sec^2:\nM204 S%1.5f\n", THEKERNEL->planner->acceleration/3600);
8b69c90d 293 gcode->stream->printf(";X- Junction Deviation, S - Minimum Planner speed:\nM205 X%1.5f S%1.5f\n", THEKERNEL->planner->junction_deviation, THEKERNEL->planner->minimum_planner_speed);
33e4cc02
JM
294 gcode->mark_as_taken();
295 break;
296
ec4773e5
JM
297 case 665: // M665 set optional arm solution variables based on arm solution
298 gcode->mark_as_taken();
299 // the parameter args could be any letter so try each one
300 for(char c='A';c<='Z';c++) {
1ad23cd3 301 float v;
ec4773e5
JM
302 bool supported= arm_solution->get_optional(c, &v); // retrieve current value if supported
303
304 if(supported && gcode->has_letter(c)) { // set new value if supported
305 v= gcode->get_value(c);
306 arm_solution->set_optional(c, v);
307 }
308 if(supported) { // print all current values of supported options
5523c05d
JM
309 gcode->stream->printf("%c %8.3f ", c, v);
310 gcode->add_nl = true;
ec4773e5
JM
311 }
312 }
313 break;
314
6989211c 315 }
494dc541
JM
316 }
317
c83887ea
MM
318 if( this->motion_mode < 0)
319 return;
6bc4a00a 320
4cff3ded 321 //Get parameters
1ad23cd3 322 float target[3], offset[3];
df27a6a3 323 clear_vector(target); clear_vector(offset);
6bc4a00a 324
4cff3ded 325 memcpy(target, this->current_position, sizeof(target)); //default to last target
6bc4a00a 326
df27a6a3 327 for(char letter = 'I'; letter <= 'K'; letter++){ if( gcode->has_letter(letter) ){ offset[letter-'I'] = this->to_millimeters(gcode->get_value(letter)); } }
a63da33c 328 for(char letter = 'X'; letter <= 'Z'; letter++){ if( gcode->has_letter(letter) ){ target[letter-'X'] = this->to_millimeters(gcode->get_value(letter)) + ( this->absolute_mode ? 0 : target[letter-'X']); } }
6bc4a00a 329
7369629d
MM
330 if( gcode->has_letter('F') )
331 {
332 if( this->motion_mode == MOTION_MODE_SEEK )
333 this->seek_rate = this->to_millimeters( gcode->get_value('F') ) / 60.0;
334 else
335 this->feed_rate = this->to_millimeters( gcode->get_value('F') ) / 60.0;
336 }
6bc4a00a 337
4cff3ded
AW
338 //Perform any physical actions
339 switch( next_action ){
340 case NEXT_ACTION_DEFAULT:
341 switch(this->motion_mode){
342 case MOTION_MODE_CANCEL: break;
436a2cd1
AW
343 case MOTION_MODE_SEEK : this->append_line(gcode, target, this->seek_rate ); break;
344 case MOTION_MODE_LINEAR: this->append_line(gcode, target, this->feed_rate ); break;
df27a6a3 345 case MOTION_MODE_CW_ARC: case MOTION_MODE_CCW_ARC: this->compute_arc(gcode, offset, target ); break;
4cff3ded
AW
346 }
347 break;
348 }
13e4a3f9 349
4cff3ded
AW
350 // As far as the parser is concerned, the position is now == target. In reality the
351 // motion control system might still be processing the action and the real tool position
352 // in any intermediate location.
1ad23cd3 353 memcpy(this->current_position, target, sizeof(float)*3); // this->position[] = target[];
4cff3ded 354
edac9072
AW
355}
356
5984acdf 357// We received a new gcode, and one of the functions
edac9072
AW
358// determined the distance for that given gcode. So now we can attach this gcode to the right block
359// and continue
360void Robot::distance_in_gcode_is_known(Gcode* gcode){
361
362 //If the queue is empty, execute immediatly, otherwise attach to the last added block
314ab8f7
MM
363 if( THEKERNEL->conveyor->queue.size() == 0 ){
364 THEKERNEL->call_event(ON_GCODE_EXECUTE, gcode );
edac9072 365 }else{
314ab8f7 366 Block* block = THEKERNEL->conveyor->queue.get_ref( THEKERNEL->conveyor->queue.size() - 1 );
edac9072
AW
367 block->append_gcode(gcode);
368 }
369
370}
371
372// Reset the position for all axes ( used in homing and G92 stuff )
1ad23cd3 373void Robot::reset_axis_position(float position, int axis) {
edac9072 374 this->last_milestone[axis] = this->current_position[axis] = position;
314ab8f7 375 this->arm_solution->millimeters_to_steps(this->current_position, THEKERNEL->planner->position);
4cff3ded
AW
376}
377
edac9072 378
4cff3ded 379// Convert target from millimeters to steps, and append this to the planner
1ad23cd3 380void Robot::append_milestone( float target[], float rate ){
4cff3ded 381 int steps[3]; //Holds the result of the conversion
6bc4a00a 382
edac9072 383 // We use an arm solution object so exotic arm solutions can be used and neatly abstracted
4cff3ded 384 this->arm_solution->millimeters_to_steps( target, steps );
6bc4a00a 385
1ad23cd3 386 float deltas[3];
aab6cbba
AW
387 for(int axis=X_AXIS;axis<=Z_AXIS;axis++){deltas[axis]=target[axis]-this->last_milestone[axis];}
388
edac9072 389 // Compute how long this move moves, so we can attach it to the block for later use
13addf09 390 float millimeters_of_travel = sqrtf( pow( deltas[X_AXIS], 2 ) + pow( deltas[Y_AXIS], 2 ) + pow( deltas[Z_AXIS], 2 ) );
7b470506 391
edac9072 392 // Do not move faster than the configured limits
7b470506 393 for(int axis=X_AXIS;axis<=Z_AXIS;axis++){
df27a6a3 394 if( this->max_speeds[axis] > 0 ){
1ad23cd3 395 float axis_speed = ( fabs(deltas[axis]) / ( millimeters_of_travel / rate )) * seconds_per_minute;
df27a6a3
MM
396 if( axis_speed > this->max_speeds[axis] ){
397 rate = rate * ( this->max_speeds[axis] / axis_speed );
436a2cd1 398 }
7b470506
AW
399 }
400 }
4cff3ded 401
edac9072 402 // Append the block to the planner
314ab8f7 403 THEKERNEL->planner->append_block( steps, rate * seconds_per_minute, millimeters_of_travel, deltas );
4cff3ded 404
edac9072 405 // Update the last_milestone to the current target for the next time we use last_milestone
1ad23cd3 406 memcpy(this->last_milestone, target, sizeof(float)*3); // this->last_milestone[] = target[];
4cff3ded
AW
407
408}
409
edac9072 410// Append a move to the queue ( cutting it into segments if needed )
1ad23cd3 411void Robot::append_line(Gcode* gcode, float target[], float rate ){
4cff3ded 412
edac9072 413 // Find out the distance for this gcode
13addf09 414 gcode->millimeters_of_travel = sqrtf( pow( target[X_AXIS]-this->current_position[X_AXIS], 2 ) + pow( target[Y_AXIS]-this->current_position[Y_AXIS], 2 ) + pow( target[Z_AXIS]-this->current_position[Z_AXIS], 2 ) );
4cff3ded 415
edac9072 416 // We ignore non-moves ( for example, extruder moves are not XYZ moves )
95b4885b
JM
417 if( gcode->millimeters_of_travel < 0.0001 ){
418 // an extruder only move means we stopped so we need to tell planner that previous speed and unitvector are zero
419 THEKERNEL->planner->previous_nominal_speed = 0;
420 clear_vector_float(THEKERNEL->planner->previous_unit_vec);
421 return;
422 }
436a2cd1 423
edac9072 424 // Mark the gcode as having a known distance
5dcb2ff3 425 this->distance_in_gcode_is_known( gcode );
436a2cd1 426
4a0c8e14
JM
427 // We cut the line into smaller segments. This is not usefull in a cartesian robot, but necessary for robots with rotational axes.
428 // In cartesian robot, a high "mm_per_line_segment" setting will prevent waste.
429 // In delta robots either mm_per_line_segment can be used OR delta_segments_per_second 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
4a0c8e14 430 uint16_t segments;
5984acdf 431
4a0c8e14
JM
432 if(this->delta_segments_per_second > 1.0) {
433 // enabled if set to something > 1, it is set to 0.0 by default
434 // segment based on current speed and requested segments per second
435 // the faster the travel speed the fewer segments needed
436 // NOTE rate is mm/sec and we take into account any speed override
437 float seconds = 60.0/seconds_per_minute * gcode->millimeters_of_travel / rate;
438 segments= max(1, ceil(this->delta_segments_per_second * seconds));
439 // TODO if we are only moving in Z on a delta we don't really need to segment at all
5984acdf 440
4a0c8e14
JM
441 }else{
442 if(this->mm_per_line_segment == 0.0){
443 segments= 1; // don't split it up
444 }else{
445 segments = ceil( gcode->millimeters_of_travel/ this->mm_per_line_segment);
446 }
447 }
5984acdf 448
4cff3ded 449 // A vector to keep track of the endpoint of each segment
1ad23cd3 450 float temp_target[3];
4cff3ded 451 //Initialize axes
1ad23cd3 452 memcpy( temp_target, this->current_position, sizeof(float)*3); // temp_target[] = this->current_position[];
4cff3ded
AW
453
454 //For each segment
455 for( int i=0; i<segments-1; i++ ){
df27a6a3 456 for(int axis=X_AXIS; axis <= Z_AXIS; axis++ ){ temp_target[axis] += ( target[axis]-this->current_position[axis] )/segments; }
5984acdf 457 // Append the end of this segment to the queue
df27a6a3 458 this->append_milestone(temp_target, rate);
4cff3ded 459 }
5984acdf
MM
460
461 // Append the end of this full move to the queue
4cff3ded
AW
462 this->append_milestone(target, rate);
463}
464
4cff3ded 465
edac9072 466// Append an arc to the queue ( cutting it into segments as needed )
1ad23cd3 467void Robot::append_arc(Gcode* gcode, float target[], float offset[], float radius, bool is_clockwise ){
aab6cbba 468
edac9072 469 // Scary math
1ad23cd3
MM
470 float center_axis0 = this->current_position[this->plane_axis_0] + offset[this->plane_axis_0];
471 float center_axis1 = this->current_position[this->plane_axis_1] + offset[this->plane_axis_1];
472 float linear_travel = target[this->plane_axis_2] - this->current_position[this->plane_axis_2];
473 float r_axis0 = -offset[this->plane_axis_0]; // Radius vector from center to current location
474 float r_axis1 = -offset[this->plane_axis_1];
475 float rt_axis0 = target[this->plane_axis_0] - center_axis0;
476 float rt_axis1 = target[this->plane_axis_1] - center_axis1;
aab6cbba
AW
477
478 // CCW angle between position and target from circle center. Only one atan2() trig computation required.
1ad23cd3 479 float angular_travel = atan2(r_axis0*rt_axis1-r_axis1*rt_axis0, r_axis0*rt_axis0+r_axis1*rt_axis1);
aab6cbba
AW
480 if (angular_travel < 0) { angular_travel += 2*M_PI; }
481 if (is_clockwise) { angular_travel -= 2*M_PI; }
482
edac9072 483 // Find the distance for this gcode
13addf09 484 gcode->millimeters_of_travel = hypotf(angular_travel*radius, fabs(linear_travel));
436a2cd1 485
edac9072 486 // We don't care about non-XYZ moves ( for example the extruder produces some of those )
5dcb2ff3
AW
487 if( gcode->millimeters_of_travel < 0.0001 ){ return; }
488
edac9072 489 // Mark the gcode as having a known distance
d149c730 490 this->distance_in_gcode_is_known( gcode );
5984acdf
MM
491
492 // Figure out how many segments for this gcode
436a2cd1 493 uint16_t segments = floor(gcode->millimeters_of_travel/this->mm_per_arc_segment);
aab6cbba 494
1ad23cd3
MM
495 float theta_per_segment = angular_travel/segments;
496 float linear_per_segment = linear_travel/segments;
aab6cbba
AW
497
498 /* Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
499 and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
500 r_T = [cos(phi) -sin(phi);
501 sin(phi) cos(phi] * r ;
502 For arc generation, the center of the circle is the axis of rotation and the radius vector is
503 defined from the circle center to the initial position. Each line segment is formed by successive
504 vector rotations. This requires only two cos() and sin() computations to form the rotation
505 matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
1ad23cd3 506 all float numbers are single precision on the Arduino. (True float precision will not have
aab6cbba
AW
507 round off issues for CNC applications.) Single precision error can accumulate to be greater than
508 tool precision in some cases. Therefore, arc path correction is implemented.
509
510 Small angle approximation may be used to reduce computation overhead further. This approximation
511 holds for everything, but very small circles and large mm_per_arc_segment values. In other words,
512 theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
513 to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
514 numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
515 issue for CNC machines with the single precision Arduino calculations.
516 This approximation also allows mc_arc to immediately insert a line segment into the planner
517 without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
518 a correction, the planner should have caught up to the lag caused by the initial mc_arc overhead.
519 This is important when there are successive arc motions.
520 */
521 // Vector rotation matrix values
1ad23cd3
MM
522 float cos_T = 1-0.5*theta_per_segment*theta_per_segment; // Small angle approximation
523 float sin_T = theta_per_segment;
aab6cbba 524
1ad23cd3
MM
525 float arc_target[3];
526 float sin_Ti;
527 float cos_Ti;
528 float r_axisi;
aab6cbba
AW
529 uint16_t i;
530 int8_t count = 0;
531
532 // Initialize the linear axis
533 arc_target[this->plane_axis_2] = this->current_position[this->plane_axis_2];
534
535 for (i = 1; i<segments; i++) { // Increment (segments-1)
536
b66fb830 537 if (count < this->arc_correction ) {
aab6cbba
AW
538 // Apply vector rotation matrix
539 r_axisi = r_axis0*sin_T + r_axis1*cos_T;
540 r_axis0 = r_axis0*cos_T - r_axis1*sin_T;
541 r_axis1 = r_axisi;
542 count++;
543 } else {
544 // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
545 // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
13addf09
MM
546 cos_Ti = cosf(i*theta_per_segment);
547 sin_Ti = sinf(i*theta_per_segment);
aab6cbba
AW
548 r_axis0 = -offset[this->plane_axis_0]*cos_Ti + offset[this->plane_axis_1]*sin_Ti;
549 r_axis1 = -offset[this->plane_axis_0]*sin_Ti - offset[this->plane_axis_1]*cos_Ti;
550 count = 0;
551 }
552
553 // Update arc_target location
554 arc_target[this->plane_axis_0] = center_axis0 + r_axis0;
555 arc_target[this->plane_axis_1] = center_axis1 + r_axis1;
556 arc_target[this->plane_axis_2] += linear_per_segment;
edac9072
AW
557
558 // Append this segment to the queue
aab6cbba
AW
559 this->append_milestone(arc_target, this->feed_rate);
560
561 }
edac9072 562
aab6cbba
AW
563 // Ensure last segment arrives at target location.
564 this->append_milestone(target, this->feed_rate);
565}
566
edac9072 567// Do the math for an arc and add it to the queue
1ad23cd3 568void Robot::compute_arc(Gcode* gcode, float offset[], float target[]){
aab6cbba
AW
569
570 // Find the radius
13addf09 571 float radius = hypotf(offset[this->plane_axis_0], offset[this->plane_axis_1]);
aab6cbba
AW
572
573 // Set clockwise/counter-clockwise sign for mc_arc computations
574 bool is_clockwise = false;
df27a6a3 575 if( this->motion_mode == MOTION_MODE_CW_ARC ){ is_clockwise = true; }
aab6cbba
AW
576
577 // Append arc
436a2cd1 578 this->append_arc(gcode, target, offset, radius, is_clockwise );
aab6cbba
AW
579
580}
581
582
1ad23cd3 583float Robot::theta(float x, float y){
71c21c73 584 float t = atanf(x/fabs(y));
4cff3ded
AW
585 if (y>0) {return(t);} else {if (t>0){return(M_PI-t);} else {return(-M_PI-t);}}
586}
587
588void Robot::select_plane(uint8_t axis_0, uint8_t axis_1, uint8_t axis_2){
589 this->plane_axis_0 = axis_0;
590 this->plane_axis_1 = axis_1;
591 this->plane_axis_2 = axis_2;
592}
593
594