planner.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. /*
  2. planner.c - buffers movement commands and manages the acceleration profile plan
  3. Part of Grbl
  4. Copyright (c) 2009-2011 Simen Svale Skogsrud
  5. Grbl is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. Grbl is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with Grbl. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. /* The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis. */
  17. /*
  18. Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
  19. s == speed, a == acceleration, t == time, d == distance
  20. Basic definitions:
  21. Speed[s_, a_, t_] := s + (a*t)
  22. Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
  23. Distance to reach a specific speed with a constant acceleration:
  24. Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
  25. d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
  26. Speed after a given distance of travel with constant acceleration:
  27. Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
  28. m -> Sqrt[2 a d + s^2]
  29. DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
  30. When to start braking (di) to reach a specified destionation speed (s2) after accelerating
  31. from initial speed s1 without ever stopping at a plateau:
  32. Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
  33. di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
  34. IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
  35. */
  36. #include "Marlin.h"
  37. #include "planner.h"
  38. #include "stepper.h"
  39. #include "temperature.h"
  40. #include "ultralcd.h"
  41. #include "language.h"
  42. #ifdef MESH_BED_LEVELING
  43. #include "mesh_bed_leveling.h"
  44. #include "mesh_bed_calibration.h"
  45. #endif
  46. //===========================================================================
  47. //=============================public variables ============================
  48. //===========================================================================
  49. unsigned long minsegmenttime;
  50. float max_feedrate[NUM_AXIS]; // set the max speeds
  51. float axis_steps_per_unit[NUM_AXIS];
  52. unsigned long max_acceleration_units_per_sq_second[NUM_AXIS]; // Use M201 to override by software
  53. float minimumfeedrate;
  54. float acceleration; // Normal acceleration mm/s^2 THIS IS THE DEFAULT ACCELERATION for all moves. M204 SXXXX
  55. float retract_acceleration; // mm/s^2 filament pull-pack and push-forward while standing still in the other axis M204 TXXXX
  56. float max_xy_jerk; //speed than can be stopped at once, if i understand correctly.
  57. float max_z_jerk;
  58. float max_e_jerk;
  59. float mintravelfeedrate;
  60. unsigned long axis_steps_per_sqr_second[NUM_AXIS];
  61. #ifdef ENABLE_AUTO_BED_LEVELING
  62. // this holds the required transform to compensate for bed level
  63. matrix_3x3 plan_bed_level_matrix = {
  64. 1.0, 0.0, 0.0,
  65. 0.0, 1.0, 0.0,
  66. 0.0, 0.0, 1.0,
  67. };
  68. #endif // #ifdef ENABLE_AUTO_BED_LEVELING
  69. // The current position of the tool in absolute steps
  70. long position[NUM_AXIS]; //rescaled from extern when axis_steps_per_unit are changed by gcode
  71. static float previous_speed[NUM_AXIS]; // Speed of previous path line segment
  72. static float previous_nominal_speed; // Nominal speed of previous path line segment
  73. #ifdef AUTOTEMP
  74. float autotemp_max=250;
  75. float autotemp_min=210;
  76. float autotemp_factor=0.1;
  77. bool autotemp_enabled=false;
  78. #endif
  79. unsigned char g_uc_extruder_last_move[3] = {0,0,0};
  80. //===========================================================================
  81. //=================semi-private variables, used in inline functions =====
  82. //===========================================================================
  83. block_t block_buffer[BLOCK_BUFFER_SIZE]; // A ring buffer for motion instfructions
  84. volatile unsigned char block_buffer_head; // Index of the next block to be pushed
  85. volatile unsigned char block_buffer_tail; // Index of the block to process now
  86. //===========================================================================
  87. //=============================private variables ============================
  88. //===========================================================================
  89. #ifdef PREVENT_DANGEROUS_EXTRUDE
  90. float extrude_min_temp=EXTRUDE_MINTEMP;
  91. #endif
  92. #ifdef FILAMENT_SENSOR
  93. static char meas_sample; //temporary variable to hold filament measurement sample
  94. #endif
  95. // Returns the index of the next block in the ring buffer
  96. // NOTE: Removed modulo (%) operator, which uses an expensive divide and multiplication.
  97. static inline int8_t next_block_index(int8_t block_index) {
  98. if (++ block_index == BLOCK_BUFFER_SIZE)
  99. block_index = 0;
  100. return block_index;
  101. }
  102. // Returns the index of the previous block in the ring buffer
  103. static inline int8_t prev_block_index(int8_t block_index) {
  104. if (block_index == 0)
  105. block_index = BLOCK_BUFFER_SIZE;
  106. -- block_index;
  107. return block_index;
  108. }
  109. //===========================================================================
  110. //=============================functions ============================
  111. //===========================================================================
  112. // Calculates the distance (not time) it takes to accelerate from initial_rate to target_rate using the
  113. // given acceleration:
  114. FORCE_INLINE float estimate_acceleration_distance(float initial_rate, float target_rate, float acceleration)
  115. {
  116. if (acceleration!=0) {
  117. return((target_rate*target_rate-initial_rate*initial_rate)/
  118. (2.0*acceleration));
  119. }
  120. else {
  121. return 0.0; // acceleration was 0, set acceleration distance to 0
  122. }
  123. }
  124. // This function gives you the point at which you must start braking (at the rate of -acceleration) if
  125. // you started at speed initial_rate and accelerated until this point and want to end at the final_rate after
  126. // a total travel of distance. This can be used to compute the intersection point between acceleration and
  127. // deceleration in the cases where the trapezoid has no plateau (i.e. never reaches maximum speed)
  128. FORCE_INLINE float intersection_distance(float initial_rate, float final_rate, float acceleration, float distance)
  129. {
  130. if (acceleration!=0) {
  131. return((2.0*acceleration*distance-initial_rate*initial_rate+final_rate*final_rate)/
  132. (4.0*acceleration) );
  133. }
  134. else {
  135. return 0.0; // acceleration was 0, set intersection distance to 0
  136. }
  137. }
  138. // Calculates trapezoid parameters so that the entry- and exit-speed is compensated by the provided factors.
  139. void calculate_trapezoid_for_block(block_t *block, float entry_factor, float exit_factor) {
  140. unsigned long initial_rate = ceil(block->nominal_rate*entry_factor); // (step/min)
  141. unsigned long final_rate = ceil(block->nominal_rate*exit_factor); // (step/min)
  142. // Limit minimal step rate (Otherwise the timer will overflow.)
  143. if(initial_rate <120) {
  144. initial_rate=120;
  145. }
  146. if(final_rate < 120) {
  147. final_rate=120;
  148. }
  149. long acceleration = block->acceleration_st;
  150. int32_t accelerate_steps =
  151. ceil(estimate_acceleration_distance(initial_rate, block->nominal_rate, acceleration));
  152. int32_t decelerate_steps =
  153. floor(estimate_acceleration_distance(block->nominal_rate, final_rate, -acceleration));
  154. // Calculate the size of Plateau of Nominal Rate.
  155. int32_t plateau_steps = block->step_event_count-accelerate_steps-decelerate_steps;
  156. // Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will
  157. // have to use intersection_distance() to calculate when to abort acceleration and start braking
  158. // in order to reach the final_rate exactly at the end of this block.
  159. if (plateau_steps < 0) {
  160. accelerate_steps = ceil(intersection_distance(initial_rate, final_rate, acceleration, block->step_event_count));
  161. accelerate_steps = max(accelerate_steps,0); // Check limits due to numerical round-off
  162. accelerate_steps = min((uint32_t)accelerate_steps,block->step_event_count);//(We can cast here to unsigned, because the above line ensures that we are above zero)
  163. plateau_steps = 0;
  164. }
  165. #ifdef ADVANCE
  166. volatile long initial_advance = block->advance*entry_factor*entry_factor;
  167. volatile long final_advance = block->advance*exit_factor*exit_factor;
  168. #endif // ADVANCE
  169. // block->accelerate_until = accelerate_steps;
  170. // block->decelerate_after = accelerate_steps+plateau_steps;
  171. CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section
  172. if (! block->busy) { // Don't update variables if block is busy.
  173. block->accelerate_until = accelerate_steps;
  174. block->decelerate_after = accelerate_steps+plateau_steps;
  175. block->initial_rate = initial_rate;
  176. block->final_rate = final_rate;
  177. #ifdef ADVANCE
  178. block->initial_advance = initial_advance;
  179. block->final_advance = final_advance;
  180. #endif //ADVANCE
  181. }
  182. CRITICAL_SECTION_END;
  183. }
  184. // Calculates the maximum allowable entry speed, when you must be able to reach target_velocity using the
  185. // decceleration within the allotted distance.
  186. FORCE_INLINE float max_allowable_entry_speed(float decceleration, float target_velocity, float distance)
  187. {
  188. // assert(decceleration < 0);
  189. return sqrt(target_velocity*target_velocity-2*decceleration*distance);
  190. }
  191. // Recalculates the motion plan according to the following algorithm:
  192. //
  193. // 1. Go over every block in reverse order and calculate a junction speed reduction (i.e. block_t.entry_factor)
  194. // so that:
  195. // a. The junction jerk is within the set limit
  196. // b. No speed reduction within one block requires faster deceleration than the one, true constant
  197. // acceleration.
  198. // 2. Go over every block in chronological order and dial down junction speed reduction values if
  199. // a. The speed increase within one block would require faster accelleration than the one, true
  200. // constant acceleration.
  201. //
  202. // When these stages are complete all blocks have an entry_factor that will allow all speed changes to
  203. // be performed using only the one, true constant acceleration, and where no junction jerk is jerkier than
  204. // the set limit. Finally it will:
  205. //
  206. // 3. Recalculate trapezoids for all blocks.
  207. void planner_recalculate(const float &safe_final_speed)
  208. {
  209. // Reverse pass
  210. // Make a local copy of block_buffer_tail, because the interrupt can alter it
  211. // by consuming the blocks, therefore shortening the queue.
  212. unsigned char tail = block_buffer_tail;
  213. uint8_t block_index;
  214. block_t *prev, *current, *next;
  215. // SERIAL_ECHOLNPGM("planner_recalculate - 1");
  216. // At least three blocks are in the queue?
  217. unsigned char n_blocks = (block_buffer_head + BLOCK_BUFFER_SIZE - tail) & (BLOCK_BUFFER_SIZE - 1);
  218. if (n_blocks >= 3) {
  219. // Initialize the last tripple of blocks.
  220. block_index = prev_block_index(block_buffer_head);
  221. next = block_buffer + block_index;
  222. current = block_buffer + (block_index = prev_block_index(block_index));
  223. // No need to recalculate the last block, it has already been set by the plan_buffer_line() function.
  224. // Vojtech thinks, that one shall not touch the entry speed of the very first block as well, because
  225. // 1) it may already be running at the stepper interrupt,
  226. // 2) there is no way to limit it when going in the forward direction.
  227. while (block_index != tail) {
  228. if (current->flag & BLOCK_FLAG_START_FROM_FULL_HALT) {
  229. // Don't modify the entry velocity of the starting block.
  230. // Also don't modify the trapezoids before this block, they are finalized already, prepared
  231. // for the stepper interrupt routine to use them.
  232. tail = block_index;
  233. // Update the number of blocks to process.
  234. n_blocks = (block_buffer_head + BLOCK_BUFFER_SIZE - tail) & (BLOCK_BUFFER_SIZE - 1);
  235. SERIAL_ECHOLNPGM("BLOCK_FLAG_START_FROM_FULL_HALT");
  236. break;
  237. }
  238. // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
  239. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
  240. // check for maximum allowable speed reductions to ensure maximum possible planned speed.
  241. if (current->entry_speed != current->max_entry_speed) {
  242. // assert(current->entry_speed < current->max_entry_speed);
  243. // Entry speed could be increased up to the max_entry_speed, limited by the length of the current
  244. // segment and the maximum acceleration allowed for this segment.
  245. // If nominal length true, max junction speed is guaranteed to be reached even if decelerating to a jerk-from-zero velocity.
  246. // Only compute for max allowable speed if block is decelerating and nominal length is false.
  247. current->entry_speed = ((current->flag & BLOCK_FLAG_NOMINAL_LENGTH) || current->max_entry_speed <= next->entry_speed) ?
  248. current->max_entry_speed :
  249. min(current->max_entry_speed, max_allowable_entry_speed(-current->acceleration,next->entry_speed,current->millimeters));
  250. current->flag |= BLOCK_FLAG_RECALCULATE;
  251. }
  252. next = current;
  253. current = block_buffer + (block_index = prev_block_index(block_index));
  254. }
  255. }
  256. // SERIAL_ECHOLNPGM("planner_recalculate - 2");
  257. // Forward pass and recalculate the trapezoids.
  258. if (n_blocks >= 2) {
  259. // Better to limit the velocities using the already processed block, if it is available, so rather use the saved tail.
  260. block_index = tail;
  261. prev = block_buffer + block_index;
  262. current = block_buffer + (block_index = next_block_index(block_index));
  263. do {
  264. // If the previous block is an acceleration block, but it is not long enough to complete the
  265. // full speed change within the block, we need to adjust the entry speed accordingly. Entry
  266. // speeds have already been reset, maximized, and reverse planned by reverse planner.
  267. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
  268. if (! (prev->flag & BLOCK_FLAG_NOMINAL_LENGTH) && prev->entry_speed < current->entry_speed) {
  269. float entry_speed = min(current->entry_speed, max_allowable_entry_speed(-prev->acceleration,prev->entry_speed,prev->millimeters));
  270. // Check for junction speed change
  271. if (current->entry_speed != entry_speed) {
  272. current->entry_speed = entry_speed;
  273. current->flag |= BLOCK_FLAG_RECALCULATE;
  274. }
  275. }
  276. // Recalculate if current block entry or exit junction speed has changed.
  277. if ((prev->flag | current->flag) & BLOCK_FLAG_RECALCULATE) {
  278. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  279. calculate_trapezoid_for_block(prev, prev->entry_speed/prev->nominal_speed, current->entry_speed/prev->nominal_speed);
  280. // Reset current only to ensure next trapezoid is computed.
  281. prev->flag &= ~BLOCK_FLAG_RECALCULATE;
  282. }
  283. prev = current;
  284. current = block_buffer + (block_index = next_block_index(block_index));
  285. } while (block_index != block_buffer_head);
  286. }
  287. // SERIAL_ECHOLNPGM("planner_recalculate - 3");
  288. // Last/newest block in buffer. Exit speed is set with safe_final_speed. Always recalculated.
  289. current = block_buffer + prev_block_index(block_buffer_head);
  290. calculate_trapezoid_for_block(current, current->entry_speed/current->nominal_speed, safe_final_speed/current->nominal_speed);
  291. current->flag &= ~BLOCK_FLAG_RECALCULATE;
  292. // SERIAL_ECHOLNPGM("planner_recalculate - 4");
  293. }
  294. void plan_init() {
  295. block_buffer_head = 0;
  296. block_buffer_tail = 0;
  297. memset(position, 0, sizeof(position)); // clear position
  298. previous_speed[0] = 0.0;
  299. previous_speed[1] = 0.0;
  300. previous_speed[2] = 0.0;
  301. previous_speed[3] = 0.0;
  302. previous_nominal_speed = 0.0;
  303. }
  304. #ifdef AUTOTEMP
  305. void getHighESpeed()
  306. {
  307. static float oldt=0;
  308. if(!autotemp_enabled){
  309. return;
  310. }
  311. if(degTargetHotend0()+2<autotemp_min) { //probably temperature set to zero.
  312. return; //do nothing
  313. }
  314. float high=0.0;
  315. uint8_t block_index = block_buffer_tail;
  316. while(block_index != block_buffer_head) {
  317. if((block_buffer[block_index].steps_x != 0) ||
  318. (block_buffer[block_index].steps_y != 0) ||
  319. (block_buffer[block_index].steps_z != 0)) {
  320. float se=(float(block_buffer[block_index].steps_e)/float(block_buffer[block_index].step_event_count))*block_buffer[block_index].nominal_speed;
  321. //se; mm/sec;
  322. if(se>high)
  323. {
  324. high=se;
  325. }
  326. }
  327. block_index = (block_index+1) & (BLOCK_BUFFER_SIZE - 1);
  328. }
  329. float g=autotemp_min+high*autotemp_factor;
  330. float t=g;
  331. if(t<autotemp_min)
  332. t=autotemp_min;
  333. if(t>autotemp_max)
  334. t=autotemp_max;
  335. if(oldt>t)
  336. {
  337. t=AUTOTEMP_OLDWEIGHT*oldt+(1-AUTOTEMP_OLDWEIGHT)*t;
  338. }
  339. oldt=t;
  340. setTargetHotend0(t);
  341. }
  342. #endif
  343. void check_axes_activity()
  344. {
  345. unsigned char x_active = 0;
  346. unsigned char y_active = 0;
  347. unsigned char z_active = 0;
  348. unsigned char e_active = 0;
  349. unsigned char tail_fan_speed = fanSpeed;
  350. block_t *block;
  351. if(block_buffer_tail != block_buffer_head)
  352. {
  353. uint8_t block_index = block_buffer_tail;
  354. tail_fan_speed = block_buffer[block_index].fan_speed;
  355. while(block_index != block_buffer_head)
  356. {
  357. block = &block_buffer[block_index];
  358. if(block->steps_x != 0) x_active++;
  359. if(block->steps_y != 0) y_active++;
  360. if(block->steps_z != 0) z_active++;
  361. if(block->steps_e != 0) e_active++;
  362. block_index = (block_index+1) & (BLOCK_BUFFER_SIZE - 1);
  363. }
  364. }
  365. if((DISABLE_X) && (x_active == 0)) disable_x();
  366. if((DISABLE_Y) && (y_active == 0)) disable_y();
  367. if((DISABLE_Z) && (z_active == 0)) disable_z();
  368. if((DISABLE_E) && (e_active == 0))
  369. {
  370. disable_e0();
  371. disable_e1();
  372. disable_e2();
  373. }
  374. #if defined(FAN_PIN) && FAN_PIN > -1
  375. #ifdef FAN_KICKSTART_TIME
  376. static unsigned long fan_kick_end;
  377. if (tail_fan_speed) {
  378. if (fan_kick_end == 0) {
  379. // Just starting up fan - run at full power.
  380. fan_kick_end = millis() + FAN_KICKSTART_TIME;
  381. tail_fan_speed = 255;
  382. } else if (fan_kick_end > millis())
  383. // Fan still spinning up.
  384. tail_fan_speed = 255;
  385. } else {
  386. fan_kick_end = 0;
  387. }
  388. #endif//FAN_KICKSTART_TIME
  389. #ifdef FAN_SOFT_PWM
  390. fanSpeedSoftPwm = tail_fan_speed;
  391. #else
  392. analogWrite(FAN_PIN,tail_fan_speed);
  393. #endif//!FAN_SOFT_PWM
  394. #endif//FAN_PIN > -1
  395. #ifdef AUTOTEMP
  396. getHighESpeed();
  397. #endif
  398. }
  399. float junction_deviation = 0.1;
  400. // Add a new linear movement to the buffer. steps_x, _y and _z is the absolute position in
  401. // mm. Microseconds specify how many microseconds the move should take to perform. To aid acceleration
  402. // calculation the caller must also provide the physical length of the line in millimeters.
  403. void plan_buffer_line(float x, float y, float z, const float &e, float feed_rate, const uint8_t &extruder)
  404. {
  405. // Calculate the buffer head after we push this byte
  406. int next_buffer_head = next_block_index(block_buffer_head);
  407. // If the buffer is full: good! That means we are well ahead of the robot.
  408. // Rest here until there is room in the buffer.
  409. while(block_buffer_tail == next_buffer_head)
  410. {
  411. manage_heater();
  412. // Vojtech: Don't disable motors inside the planner!
  413. manage_inactivity(false);
  414. lcd_update();
  415. }
  416. #ifdef ENABLE_AUTO_BED_LEVELING
  417. apply_rotation_xyz(plan_bed_level_matrix, x, y, z);
  418. #endif // ENABLE_AUTO_BED_LEVELING
  419. // Apply the machine correction matrix.
  420. {
  421. #if 0
  422. SERIAL_ECHOPGM("Planner, current position - servos: ");
  423. MYSERIAL.print(st_get_position_mm(X_AXIS), 5);
  424. SERIAL_ECHOPGM(", ");
  425. MYSERIAL.print(st_get_position_mm(Y_AXIS), 5);
  426. SERIAL_ECHOPGM(", ");
  427. MYSERIAL.print(st_get_position_mm(Z_AXIS), 5);
  428. SERIAL_ECHOLNPGM("");
  429. SERIAL_ECHOPGM("Planner, target position, initial: ");
  430. MYSERIAL.print(x, 5);
  431. SERIAL_ECHOPGM(", ");
  432. MYSERIAL.print(y, 5);
  433. SERIAL_ECHOLNPGM("");
  434. SERIAL_ECHOPGM("Planner, world2machine: ");
  435. MYSERIAL.print(world2machine_rotation_and_skew[0][0], 5);
  436. SERIAL_ECHOPGM(", ");
  437. MYSERIAL.print(world2machine_rotation_and_skew[0][1], 5);
  438. SERIAL_ECHOPGM(", ");
  439. MYSERIAL.print(world2machine_rotation_and_skew[1][0], 5);
  440. SERIAL_ECHOPGM(", ");
  441. MYSERIAL.print(world2machine_rotation_and_skew[1][1], 5);
  442. SERIAL_ECHOLNPGM("");
  443. SERIAL_ECHOPGM("Planner, offset: ");
  444. MYSERIAL.print(world2machine_shift[0], 5);
  445. SERIAL_ECHOPGM(", ");
  446. MYSERIAL.print(world2machine_shift[1], 5);
  447. SERIAL_ECHOLNPGM("");
  448. #endif
  449. world2machine(x, y);
  450. #if 0
  451. SERIAL_ECHOPGM("Planner, target position, corrected: ");
  452. MYSERIAL.print(x, 5);
  453. SERIAL_ECHOPGM(", ");
  454. MYSERIAL.print(y, 5);
  455. SERIAL_ECHOLNPGM("");
  456. #endif
  457. }
  458. // The target position of the tool in absolute steps
  459. // Calculate target position in absolute steps
  460. //this should be done after the wait, because otherwise a M92 code within the gcode disrupts this calculation somehow
  461. long target[4];
  462. target[X_AXIS] = lround(x*axis_steps_per_unit[X_AXIS]);
  463. target[Y_AXIS] = lround(y*axis_steps_per_unit[Y_AXIS]);
  464. #ifdef MESH_BED_LEVELING
  465. if (mbl.active){
  466. target[Z_AXIS] = lround((z+mbl.get_z(x, y))*axis_steps_per_unit[Z_AXIS]);
  467. }else{
  468. target[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);
  469. }
  470. #else
  471. target[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);
  472. #endif // ENABLE_MESH_BED_LEVELING
  473. target[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]);
  474. #ifdef PREVENT_DANGEROUS_EXTRUDE
  475. if(target[E_AXIS]!=position[E_AXIS])
  476. {
  477. if(degHotend(active_extruder)<extrude_min_temp)
  478. {
  479. position[E_AXIS]=target[E_AXIS]; //behave as if the move really took place, but ignore E part
  480. SERIAL_ECHO_START;
  481. SERIAL_ECHOLNRPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  482. }
  483. #ifdef PREVENT_LENGTHY_EXTRUDE
  484. if(labs(target[E_AXIS]-position[E_AXIS])>axis_steps_per_unit[E_AXIS]*EXTRUDE_MAXLENGTH)
  485. {
  486. position[E_AXIS]=target[E_AXIS]; //behave as if the move really took place, but ignore E part
  487. SERIAL_ECHO_START;
  488. SERIAL_ECHOLNRPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  489. }
  490. #endif
  491. }
  492. #endif
  493. // Prepare to set up new block
  494. block_t *block = &block_buffer[block_buffer_head];
  495. // Mark block as not busy (Not executed by the stepper interrupt, could be still tinkered with.)
  496. block->busy = false;
  497. // Number of steps for each axis
  498. #ifndef COREXY
  499. // default non-h-bot planning
  500. block->steps_x = labs(target[X_AXIS]-position[X_AXIS]);
  501. block->steps_y = labs(target[Y_AXIS]-position[Y_AXIS]);
  502. #else
  503. // corexy planning
  504. // these equations follow the form of the dA and dB equations on http://www.corexy.com/theory.html
  505. block->steps_x = labs((target[X_AXIS]-position[X_AXIS]) + (target[Y_AXIS]-position[Y_AXIS]));
  506. block->steps_y = labs((target[X_AXIS]-position[X_AXIS]) - (target[Y_AXIS]-position[Y_AXIS]));
  507. #endif
  508. block->steps_z = labs(target[Z_AXIS]-position[Z_AXIS]);
  509. block->steps_e = labs(target[E_AXIS]-position[E_AXIS]);
  510. block->steps_e *= volumetric_multiplier[active_extruder];
  511. block->steps_e *= extrudemultiply;
  512. block->steps_e /= 100;
  513. block->step_event_count = max(block->steps_x, max(block->steps_y, max(block->steps_z, block->steps_e)));
  514. // Bail if this is a zero-length block
  515. if (block->step_event_count <= dropsegments)
  516. {
  517. return;
  518. }
  519. block->fan_speed = fanSpeed;
  520. // Compute direction bits for this block
  521. block->direction_bits = 0;
  522. #ifndef COREXY
  523. if (target[X_AXIS] < position[X_AXIS])
  524. {
  525. block->direction_bits |= (1<<X_AXIS);
  526. }
  527. if (target[Y_AXIS] < position[Y_AXIS])
  528. {
  529. block->direction_bits |= (1<<Y_AXIS);
  530. }
  531. #else
  532. if ((target[X_AXIS]-position[X_AXIS]) + (target[Y_AXIS]-position[Y_AXIS]) < 0)
  533. {
  534. block->direction_bits |= (1<<X_AXIS);
  535. }
  536. if ((target[X_AXIS]-position[X_AXIS]) - (target[Y_AXIS]-position[Y_AXIS]) < 0)
  537. {
  538. block->direction_bits |= (1<<Y_AXIS);
  539. }
  540. #endif
  541. if (target[Z_AXIS] < position[Z_AXIS])
  542. {
  543. block->direction_bits |= (1<<Z_AXIS);
  544. }
  545. if (target[E_AXIS] < position[E_AXIS])
  546. {
  547. block->direction_bits |= (1<<E_AXIS);
  548. }
  549. block->active_extruder = extruder;
  550. //enable active axes
  551. #ifdef COREXY
  552. if((block->steps_x != 0) || (block->steps_y != 0))
  553. {
  554. enable_x();
  555. enable_y();
  556. }
  557. #else
  558. if(block->steps_x != 0) enable_x();
  559. if(block->steps_y != 0) enable_y();
  560. #endif
  561. #ifndef Z_LATE_ENABLE
  562. if(block->steps_z != 0) enable_z();
  563. #endif
  564. // Enable extruder(s)
  565. if(block->steps_e != 0)
  566. {
  567. if (DISABLE_INACTIVE_EXTRUDER) //enable only selected extruder
  568. {
  569. if(g_uc_extruder_last_move[0] > 0) g_uc_extruder_last_move[0]--;
  570. if(g_uc_extruder_last_move[1] > 0) g_uc_extruder_last_move[1]--;
  571. if(g_uc_extruder_last_move[2] > 0) g_uc_extruder_last_move[2]--;
  572. switch(extruder)
  573. {
  574. case 0:
  575. enable_e0();
  576. g_uc_extruder_last_move[0] = BLOCK_BUFFER_SIZE*2;
  577. if(g_uc_extruder_last_move[1] == 0) disable_e1();
  578. if(g_uc_extruder_last_move[2] == 0) disable_e2();
  579. break;
  580. case 1:
  581. enable_e1();
  582. g_uc_extruder_last_move[1] = BLOCK_BUFFER_SIZE*2;
  583. if(g_uc_extruder_last_move[0] == 0) disable_e0();
  584. if(g_uc_extruder_last_move[2] == 0) disable_e2();
  585. break;
  586. case 2:
  587. enable_e2();
  588. g_uc_extruder_last_move[2] = BLOCK_BUFFER_SIZE*2;
  589. if(g_uc_extruder_last_move[0] == 0) disable_e0();
  590. if(g_uc_extruder_last_move[1] == 0) disable_e1();
  591. break;
  592. }
  593. }
  594. else //enable all
  595. {
  596. enable_e0();
  597. enable_e1();
  598. enable_e2();
  599. }
  600. }
  601. if (block->steps_e == 0)
  602. {
  603. if(feed_rate<mintravelfeedrate) feed_rate=mintravelfeedrate;
  604. }
  605. else
  606. {
  607. if(feed_rate<minimumfeedrate) feed_rate=minimumfeedrate;
  608. }
  609. /* This part of the code calculates the total length of the movement.
  610. For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  611. But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  612. and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  613. So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  614. Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  615. */
  616. #ifndef COREXY
  617. float delta_mm[4];
  618. delta_mm[X_AXIS] = (target[X_AXIS]-position[X_AXIS])/axis_steps_per_unit[X_AXIS];
  619. delta_mm[Y_AXIS] = (target[Y_AXIS]-position[Y_AXIS])/axis_steps_per_unit[Y_AXIS];
  620. #else
  621. float delta_mm[6];
  622. delta_mm[X_HEAD] = (target[X_AXIS]-position[X_AXIS])/axis_steps_per_unit[X_AXIS];
  623. delta_mm[Y_HEAD] = (target[Y_AXIS]-position[Y_AXIS])/axis_steps_per_unit[Y_AXIS];
  624. delta_mm[X_AXIS] = ((target[X_AXIS]-position[X_AXIS]) + (target[Y_AXIS]-position[Y_AXIS]))/axis_steps_per_unit[X_AXIS];
  625. delta_mm[Y_AXIS] = ((target[X_AXIS]-position[X_AXIS]) - (target[Y_AXIS]-position[Y_AXIS]))/axis_steps_per_unit[Y_AXIS];
  626. #endif
  627. delta_mm[Z_AXIS] = (target[Z_AXIS]-position[Z_AXIS])/axis_steps_per_unit[Z_AXIS];
  628. delta_mm[E_AXIS] = ((target[E_AXIS]-position[E_AXIS])/axis_steps_per_unit[E_AXIS])*volumetric_multiplier[active_extruder]*extrudemultiply/100.0;
  629. if ( block->steps_x <=dropsegments && block->steps_y <=dropsegments && block->steps_z <=dropsegments )
  630. {
  631. block->millimeters = fabs(delta_mm[E_AXIS]);
  632. }
  633. else
  634. {
  635. #ifndef COREXY
  636. block->millimeters = sqrt(square(delta_mm[X_AXIS]) + square(delta_mm[Y_AXIS]) + square(delta_mm[Z_AXIS]));
  637. #else
  638. block->millimeters = sqrt(square(delta_mm[X_HEAD]) + square(delta_mm[Y_HEAD]) + square(delta_mm[Z_AXIS]));
  639. #endif
  640. }
  641. float inverse_millimeters = 1.0/block->millimeters; // Inverse millimeters to remove multiple divides
  642. // Calculate speed in mm/second for each axis. No divide by zero due to previous checks.
  643. float inverse_second = feed_rate * inverse_millimeters;
  644. int moves_queued = moves_planned();
  645. // slow down when de buffer starts to empty, rather than wait at the corner for a buffer refill
  646. #ifdef SLOWDOWN
  647. //FIXME Vojtech: Why moves_queued > 1? Why not >=1?
  648. // Can we somehow differentiate the filling of the buffer at the start of a g-code from a buffer draining situation?
  649. if (moves_queued > 1 && moves_queued < (BLOCK_BUFFER_SIZE >> 1)) {
  650. // segment time in micro seconds
  651. unsigned long segment_time = lround(1000000.0/inverse_second);
  652. if (segment_time < minsegmenttime)
  653. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  654. inverse_second=1000000.0/(segment_time+lround(2*(minsegmenttime-segment_time)/moves_queued));
  655. }
  656. #endif // SLOWDOWN
  657. block->nominal_speed = block->millimeters * inverse_second; // (mm/sec) Always > 0
  658. block->nominal_rate = ceil(block->step_event_count * inverse_second); // (step/sec) Always > 0
  659. #ifdef FILAMENT_SENSOR
  660. //FMM update ring buffer used for delay with filament measurements
  661. if((extruder==FILAMENT_SENSOR_EXTRUDER_NUM) && (delay_index2 > -1)) //only for extruder with filament sensor and if ring buffer is initialized
  662. {
  663. delay_dist = delay_dist + delta_mm[E_AXIS]; //increment counter with next move in e axis
  664. while (delay_dist >= (10*(MAX_MEASUREMENT_DELAY+1))) //check if counter is over max buffer size in mm
  665. delay_dist = delay_dist - 10*(MAX_MEASUREMENT_DELAY+1); //loop around the buffer
  666. while (delay_dist<0)
  667. delay_dist = delay_dist + 10*(MAX_MEASUREMENT_DELAY+1); //loop around the buffer
  668. delay_index1=delay_dist/10.0; //calculate index
  669. //ensure the number is within range of the array after converting from floating point
  670. if(delay_index1<0)
  671. delay_index1=0;
  672. else if (delay_index1>MAX_MEASUREMENT_DELAY)
  673. delay_index1=MAX_MEASUREMENT_DELAY;
  674. if(delay_index1 != delay_index2) //moved index
  675. {
  676. meas_sample=widthFil_to_size_ratio()-100; //subtract off 100 to reduce magnitude - to store in a signed char
  677. }
  678. while( delay_index1 != delay_index2)
  679. {
  680. delay_index2 = delay_index2 + 1;
  681. if(delay_index2>MAX_MEASUREMENT_DELAY)
  682. delay_index2=delay_index2-(MAX_MEASUREMENT_DELAY+1); //loop around buffer when incrementing
  683. if(delay_index2<0)
  684. delay_index2=0;
  685. else if (delay_index2>MAX_MEASUREMENT_DELAY)
  686. delay_index2=MAX_MEASUREMENT_DELAY;
  687. measurement_delay[delay_index2]=meas_sample;
  688. }
  689. }
  690. #endif
  691. // Calculate and limit speed in mm/sec for each axis
  692. float current_speed[4];
  693. float speed_factor = 1.0; //factor <=1 do decrease speed
  694. for(int i=0; i < 4; i++)
  695. {
  696. current_speed[i] = delta_mm[i] * inverse_second;
  697. if(fabs(current_speed[i]) > max_feedrate[i])
  698. speed_factor = min(speed_factor, max_feedrate[i] / fabs(current_speed[i]));
  699. }
  700. // Correct the speed
  701. if( speed_factor < 1.0)
  702. {
  703. for(unsigned char i=0; i < 4; i++)
  704. {
  705. current_speed[i] *= speed_factor;
  706. }
  707. block->nominal_speed *= speed_factor;
  708. block->nominal_rate *= speed_factor;
  709. }
  710. // Compute and limit the acceleration rate for the trapezoid generator.
  711. float steps_per_mm = block->step_event_count/block->millimeters;
  712. if(block->steps_x == 0 && block->steps_y == 0 && block->steps_z == 0)
  713. {
  714. block->acceleration_st = ceil(retract_acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  715. }
  716. else
  717. {
  718. block->acceleration_st = ceil(acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  719. // Limit acceleration per axis
  720. //FIXME Vojtech: One shall rather limit a projection of the acceleration vector instead of using the limit.
  721. if(((float)block->acceleration_st * (float)block->steps_x / (float)block->step_event_count) > axis_steps_per_sqr_second[X_AXIS])
  722. block->acceleration_st = axis_steps_per_sqr_second[X_AXIS];
  723. if(((float)block->acceleration_st * (float)block->steps_y / (float)block->step_event_count) > axis_steps_per_sqr_second[Y_AXIS])
  724. block->acceleration_st = axis_steps_per_sqr_second[Y_AXIS];
  725. if(((float)block->acceleration_st * (float)block->steps_e / (float)block->step_event_count) > axis_steps_per_sqr_second[E_AXIS])
  726. block->acceleration_st = axis_steps_per_sqr_second[E_AXIS];
  727. if(((float)block->acceleration_st * (float)block->steps_z / (float)block->step_event_count ) > axis_steps_per_sqr_second[Z_AXIS])
  728. block->acceleration_st = axis_steps_per_sqr_second[Z_AXIS];
  729. }
  730. block->acceleration = block->acceleration_st / steps_per_mm;
  731. block->acceleration_rate = (long)((float)block->acceleration_st * (16777216.0 / (F_CPU / 8.0)));
  732. #if 0 // Use old jerk for now
  733. // Compute path unit vector
  734. double unit_vec[3];
  735. unit_vec[X_AXIS] = delta_mm[X_AXIS]*inverse_millimeters;
  736. unit_vec[Y_AXIS] = delta_mm[Y_AXIS]*inverse_millimeters;
  737. unit_vec[Z_AXIS] = delta_mm[Z_AXIS]*inverse_millimeters;
  738. // Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  739. // Let a circle be tangent to both previous and current path line segments, where the junction
  740. // deviation is defined as the distance from the junction to the closest edge of the circle,
  741. // colinear with the circle center. The circular segment joining the two paths represents the
  742. // path of centripetal acceleration. Solve for max velocity based on max acceleration about the
  743. // radius of the circle, defined indirectly by junction deviation. This may be also viewed as
  744. // path width or max_jerk in the previous grbl version. This approach does not actually deviate
  745. // from path, but used as a robust way to compute cornering speeds, as it takes into account the
  746. // nonlinearities of both the junction angle and junction velocity.
  747. double vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed
  748. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  749. if ((block_buffer_head != block_buffer_tail) && (previous_nominal_speed > 0.0)) {
  750. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  751. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  752. double cos_theta = - previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
  753. - previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
  754. - previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS] ;
  755. // Skip and use default max junction speed for 0 degree acute junction.
  756. if (cos_theta < 0.95) {
  757. vmax_junction = min(previous_nominal_speed,block->nominal_speed);
  758. // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds.
  759. if (cos_theta > -0.95) {
  760. // Compute maximum junction velocity based on maximum acceleration and junction deviation
  761. double sin_theta_d2 = sqrt(0.5*(1.0-cos_theta)); // Trig half angle identity. Always positive.
  762. vmax_junction = min(vmax_junction,
  763. sqrt(block->acceleration * junction_deviation * sin_theta_d2/(1.0-sin_theta_d2)) );
  764. }
  765. }
  766. }
  767. #endif
  768. // Start with a safe speed.
  769. //Vojtech: This code tries to limit the initial jerk to half of the maximum jerk value.
  770. //The code is not quite correct. It is pessimistic as it shall limit a projection of the jerk into each axis,
  771. //but when the current code clamps, it clamps as if the movement is done in a single axis only.
  772. float vmax_junction = max_xy_jerk/2.f;
  773. if(fabs(current_speed[Z_AXIS]) > max_z_jerk/2.f)
  774. vmax_junction = min(vmax_junction, max_z_jerk/2.f);
  775. if(fabs(current_speed[E_AXIS]) > max_e_jerk/2.f)
  776. vmax_junction = min(vmax_junction, max_e_jerk/2.f);
  777. vmax_junction = min(vmax_junction, block->nominal_speed);
  778. // Safe speed is the speed, from which the machine may halt to stop immediately.
  779. float safe_speed = vmax_junction;
  780. //FIXME Vojtech: Why only if at least two lines are planned in the queue?
  781. // Is it because we don't want to tinker with the first buffer line, which
  782. // is likely to be executed by the stepper interrupt routine soon?
  783. if (moves_queued > 1 && previous_nominal_speed > 0.0001f) {
  784. #if 1
  785. float jerk;
  786. {
  787. float dx = current_speed[X_AXIS]-previous_speed[X_AXIS];
  788. float dy = current_speed[Y_AXIS]-previous_speed[Y_AXIS];
  789. jerk = sqrt(dx*dx+dy*dy);
  790. }
  791. float vmax_junction_factor = 1.0;
  792. // if((fabs(previous_speed[X_AXIS]) > 0.0001) || (fabs(previous_speed[Y_AXIS]) > 0.0001)) {
  793. vmax_junction = block->nominal_speed;
  794. // }
  795. if (jerk > max_xy_jerk)
  796. vmax_junction_factor = max_xy_jerk/jerk;
  797. jerk = fabs(current_speed[Z_AXIS] - previous_speed[Z_AXIS]);
  798. if (jerk > max_z_jerk)
  799. vmax_junction_factor = min(vmax_junction_factor, max_z_jerk/jerk);
  800. jerk = fabs(current_speed[E_AXIS] - previous_speed[E_AXIS]);
  801. if (jerk > max_e_jerk)
  802. vmax_junction_factor = min(vmax_junction_factor, max_e_jerk/jerk);
  803. //FIXME Vojtech: Why is this asymmetric in regard to the previous nominal speed and the current nominal speed?
  804. vmax_junction = min(previous_nominal_speed, vmax_junction * vmax_junction_factor); // Limit speed to max previous speed
  805. #else
  806. // Estimate a maximum velocity allowed at a joint of two successive segments.
  807. // If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
  808. // then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
  809. // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
  810. bool prev_speed_larger = previous_nominal_speed > block->nominal_speed;
  811. float smaller_speed_factor = prev_speed_larger ? (block->nominal_speed / previous_nominal_speed) : (previous_nominal_speed / block->nominal_speed);
  812. // Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
  813. vmax_junction = prev_speed_larger ? block->nominal_speed : previous_nominal_speed;
  814. // Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
  815. float v_factor_exit = prev_speed_larger ? smaller_speed_factor : 1.f;
  816. float v_factor_entry = prev_speed_larger ? 1.f : smaller_speed_factor;
  817. // First limit the jerk in the XY plane.
  818. float jerk;
  819. {
  820. // Estimate the jerk as if the entry / exit velocity of the two successive segment was limited to the minimum of their nominal velocities.
  821. // If coasting, then the segment transition velocity will define the exit / entry velocities of the successive segments
  822. // and the jerk defined by the following formula will be always lower.
  823. float dx = prev_speed_larger ? (current_speed[X_AXIS] - smaller_speed_factor * previous_speed[X_AXIS]) : (smaller_speed_factor * current_speed[X_AXIS] - previous_speed[X_AXIS]);
  824. float dy = prev_speed_larger ? (current_speed[Y_AXIS] - smaller_speed_factor * previous_speed[Y_AXIS]) : (smaller_speed_factor * current_speed[Y_AXIS] - previous_speed[Y_AXIS]);
  825. jerk = sqrt(dx*dx+dy*dy);
  826. }
  827. if (jerk > max_xy_jerk) {
  828. // Limit the entry / exit velocities to respect the XY jerk limits.
  829. v_factor_exit = v_factor_entry = max_xy_jerk / jerk;
  830. if (prev_speed_larger)
  831. v_factor_exit *= smaller_speed_factor;
  832. else
  833. v_factor_entry *= smaller_speed_factor;
  834. }
  835. // Now limit the Z and E axes. We have to differentiate coasting from the reversal of an axis movement, or a full stop.
  836. float v_exit = previous_speed[Z_AXIS] * v_factor_exit;
  837. float v_entry = current_speed [Z_AXIS] * v_factor_entry;
  838. jerk = (v_exit > v_entry) ?
  839. ((v_entry > 0.f || v_exit < 0.f) ?
  840. // coasting
  841. (v_exit - v_entry) :
  842. // axis reversal
  843. max(v_exit, - v_entry)) :
  844. // v_exit <= v_entry
  845. ((v_entry < 0.f || v_exit > 0.f) ?
  846. // coasting
  847. (v_entry - v_exit) :
  848. // axis reversal
  849. max(- v_exit, v_entry));
  850. if (jerk > max_z_jerk / 2.f) {
  851. float c = (max_z_jerk / 2.f) / jerk;
  852. v_factor_exit *= c;
  853. v_factor_entry *= c;
  854. }
  855. // Limit the E axis.
  856. v_exit = previous_speed[E_AXIS] * v_factor_exit;
  857. v_entry = current_speed [E_AXIS] * v_factor_entry;
  858. jerk = (v_exit > v_entry) ?
  859. ((v_entry > 0.f || v_exit < 0.f) ?
  860. // coasting
  861. (v_exit - v_entry) :
  862. // axis reversal
  863. max(v_exit, - v_entry)) :
  864. // v_exit <= v_entry
  865. ((v_entry < 0.f || v_exit > 0.f) ?
  866. // coasting
  867. (v_entry - v_exit) :
  868. // axis reversal
  869. max(- v_exit, v_entry));
  870. if (jerk > max_e_jerk / 2.f) {
  871. float c = (max_e_jerk / 2.f) / jerk;
  872. v_factor_exit *= c;
  873. v_factor_entry *= c;
  874. }
  875. // Now the transition velocity is known as nominal * v_factor. Compare the transition velocity against the "safe" velocoties.
  876. // If the transition velocity is below the exit / enter safe velocity, the machine is no more cruising, therefore
  877. // the safe velocities shall be used.
  878. #endif
  879. }
  880. // Max entry speed of this block equals the max exit speed of the previous block.
  881. block->max_entry_speed = vmax_junction;
  882. // Initialize block entry speed. Compute based on deceleration to safe_speed.
  883. double v_allowable = max_allowable_entry_speed(-block->acceleration,safe_speed,block->millimeters);
  884. block->entry_speed = min(vmax_junction, v_allowable);
  885. // Initialize planner efficiency flags
  886. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  887. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  888. // the current block and next block junction speeds are guaranteed to always be at their maximum
  889. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  890. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  891. // the reverse and forward planners, the corresponding block junction speed will always be at the
  892. // the maximum junction speed and may always be ignored for any speed reduction checks.
  893. // Always calculate trapezoid for new block
  894. block->flag = (block->nominal_speed <= v_allowable) ? (BLOCK_FLAG_NOMINAL_LENGTH | BLOCK_FLAG_RECALCULATE) : BLOCK_FLAG_RECALCULATE;
  895. // Update previous path unit_vector and nominal speed
  896. memcpy(previous_speed, current_speed, sizeof(previous_speed)); // previous_speed[] = current_speed[]
  897. previous_nominal_speed = block->nominal_speed;
  898. #ifdef ADVANCE
  899. // Calculate advance rate
  900. if((block->steps_e == 0) || (block->steps_x == 0 && block->steps_y == 0 && block->steps_z == 0)) {
  901. block->advance_rate = 0;
  902. block->advance = 0;
  903. }
  904. else {
  905. long acc_dist = estimate_acceleration_distance(0, block->nominal_rate, block->acceleration_st);
  906. float advance = (STEPS_PER_CUBIC_MM_E * EXTRUDER_ADVANCE_K) *
  907. (current_speed[E_AXIS] * current_speed[E_AXIS] * EXTRUSION_AREA * EXTRUSION_AREA)*256;
  908. block->advance = advance;
  909. if(acc_dist == 0) {
  910. block->advance_rate = 0;
  911. }
  912. else {
  913. block->advance_rate = advance / (float)acc_dist;
  914. }
  915. }
  916. /*
  917. SERIAL_ECHO_START;
  918. SERIAL_ECHOPGM("advance :");
  919. SERIAL_ECHO(block->advance/256.0);
  920. SERIAL_ECHOPGM("advance rate :");
  921. SERIAL_ECHOLN(block->advance_rate/256.0);
  922. */
  923. #endif // ADVANCE
  924. calculate_trapezoid_for_block(block, block->entry_speed/block->nominal_speed, safe_speed/block->nominal_speed);
  925. // Move the buffer head. From now the block may be picked up by the stepper interrupt controller.
  926. block_buffer_head = next_buffer_head;
  927. // Update position
  928. memcpy(position, target, sizeof(target)); // position[] = target[]
  929. // Recalculate the trapezoids to maximize speed at the segment transitions while respecting
  930. // the machine limits (maximum acceleration and maximum jerk).
  931. // This runs asynchronously with the stepper interrupt controller, which may
  932. // interfere with the process.
  933. planner_recalculate(safe_speed);
  934. st_wake_up();
  935. }
  936. #ifdef ENABLE_AUTO_BED_LEVELING
  937. vector_3 plan_get_position() {
  938. vector_3 position = vector_3(st_get_position_mm(X_AXIS), st_get_position_mm(Y_AXIS), st_get_position_mm(Z_AXIS));
  939. //position.debug("in plan_get position");
  940. //plan_bed_level_matrix.debug("in plan_get bed_level");
  941. matrix_3x3 inverse = matrix_3x3::transpose(plan_bed_level_matrix);
  942. //inverse.debug("in plan_get inverse");
  943. position.apply_rotation(inverse);
  944. //position.debug("after rotation");
  945. return position;
  946. }
  947. #endif // ENABLE_AUTO_BED_LEVELING
  948. void plan_set_position(float x, float y, float z, const float &e)
  949. {
  950. #ifdef ENABLE_AUTO_BED_LEVELING
  951. apply_rotation_xyz(plan_bed_level_matrix, x, y, z);
  952. #endif // ENABLE_AUTO_BED_LEVELING
  953. // Apply the machine correction matrix.
  954. {
  955. float tmpx = x;
  956. float tmpy = y;
  957. x = world2machine_rotation_and_skew[0][0] * tmpx + world2machine_rotation_and_skew[0][1] * tmpy + world2machine_shift[0];
  958. y = world2machine_rotation_and_skew[1][0] * tmpx + world2machine_rotation_and_skew[1][1] * tmpy + world2machine_shift[1];
  959. }
  960. position[X_AXIS] = lround(x*axis_steps_per_unit[X_AXIS]);
  961. position[Y_AXIS] = lround(y*axis_steps_per_unit[Y_AXIS]);
  962. #ifdef MESH_BED_LEVELING
  963. if (mbl.active){
  964. position[Z_AXIS] = lround((z+mbl.get_z(x, y))*axis_steps_per_unit[Z_AXIS]);
  965. }else{
  966. position[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);
  967. }
  968. #else
  969. position[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);
  970. #endif // ENABLE_MESH_BED_LEVELING
  971. position[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]);
  972. st_set_position(position[X_AXIS], position[Y_AXIS], position[Z_AXIS], position[E_AXIS]);
  973. previous_nominal_speed = 0.0; // Resets planner junction speeds. Assumes start from rest.
  974. previous_speed[0] = 0.0;
  975. previous_speed[1] = 0.0;
  976. previous_speed[2] = 0.0;
  977. previous_speed[3] = 0.0;
  978. }
  979. // Only useful in the bed leveling routine, when the mesh bed leveling is off.
  980. void plan_set_z_position(const float &z)
  981. {
  982. position[Z_AXIS] = lround(z*axis_steps_per_unit[Z_AXIS]);
  983. st_set_position(position[X_AXIS], position[Y_AXIS], position[Z_AXIS], position[E_AXIS]);
  984. }
  985. void plan_set_e_position(const float &e)
  986. {
  987. position[E_AXIS] = lround(e*axis_steps_per_unit[E_AXIS]);
  988. st_set_e_position(position[E_AXIS]);
  989. }
  990. #ifdef PREVENT_DANGEROUS_EXTRUDE
  991. void set_extrude_min_temp(float temp)
  992. {
  993. extrude_min_temp=temp;
  994. }
  995. #endif
  996. // Calculate the steps/s^2 acceleration rates, based on the mm/s^s
  997. void reset_acceleration_rates()
  998. {
  999. for(int8_t i=0; i < NUM_AXIS; i++)
  1000. {
  1001. axis_steps_per_sqr_second[i] = max_acceleration_units_per_sq_second[i] * axis_steps_per_unit[i];
  1002. }
  1003. }