My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

planner.cpp 45KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * planner.cpp
  24. *
  25. * Buffer movement commands and manage the acceleration profile plan
  26. *
  27. * Derived from Grbl
  28. * Copyright (c) 2009-2011 Simen Svale Skogsrud
  29. *
  30. * The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis.
  31. *
  32. *
  33. * Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
  34. *
  35. * s == speed, a == acceleration, t == time, d == distance
  36. *
  37. * Basic definitions:
  38. * Speed[s_, a_, t_] := s + (a*t)
  39. * Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
  40. *
  41. * Distance to reach a specific speed with a constant acceleration:
  42. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
  43. * d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
  44. *
  45. * Speed after a given distance of travel with constant acceleration:
  46. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
  47. * m -> Sqrt[2 a d + s^2]
  48. *
  49. * DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
  50. *
  51. * When to start braking (di) to reach a specified destination speed (s2) after accelerating
  52. * from initial speed s1 without ever stopping at a plateau:
  53. * Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
  54. * di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
  55. *
  56. * IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
  57. *
  58. */
  59. #include "planner.h"
  60. #include "stepper.h"
  61. #include "temperature.h"
  62. #include "ultralcd.h"
  63. #include "language.h"
  64. #include "Marlin.h"
  65. #if ENABLED(MESH_BED_LEVELING)
  66. #include "mesh_bed_leveling.h"
  67. #endif
  68. Planner planner;
  69. // public:
  70. /**
  71. * A ring buffer of moves described in steps
  72. */
  73. block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
  74. volatile uint8_t Planner::block_buffer_head = 0; // Index of the next block to be pushed
  75. volatile uint8_t Planner::block_buffer_tail = 0;
  76. float Planner::max_feedrate_mm_s[NUM_AXIS], // Max speeds in mm per second
  77. Planner::axis_steps_per_mm[NUM_AXIS],
  78. Planner::steps_to_mm[NUM_AXIS];
  79. unsigned long Planner::max_acceleration_steps_per_s2[NUM_AXIS],
  80. Planner::max_acceleration_mm_per_s2[NUM_AXIS]; // Use M201 to override by software
  81. millis_t Planner::min_segment_time;
  82. float Planner::min_feedrate_mm_s,
  83. Planner::acceleration, // Normal acceleration mm/s^2 DEFAULT ACCELERATION for all printing moves. M204 SXXXX
  84. Planner::retract_acceleration, // Retract acceleration mm/s^2 filament pull-back and push-forward while standing still in the other axes M204 TXXXX
  85. Planner::travel_acceleration, // Travel acceleration mm/s^2 DEFAULT ACCELERATION for all NON printing moves. M204 MXXXX
  86. Planner::max_xy_jerk, // The largest speed change requiring no acceleration
  87. Planner::max_z_jerk,
  88. Planner::max_e_jerk,
  89. Planner::min_travel_feedrate_mm_s;
  90. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  91. matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
  92. #endif
  93. #if ENABLED(AUTOTEMP)
  94. float Planner::autotemp_max = 250,
  95. Planner::autotemp_min = 210,
  96. Planner::autotemp_factor = 0.1;
  97. bool Planner::autotemp_enabled = false;
  98. #endif
  99. // private:
  100. long Planner::position[NUM_AXIS] = { 0 };
  101. float Planner::previous_speed[NUM_AXIS],
  102. Planner::previous_nominal_speed;
  103. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  104. uint8_t Planner::g_uc_extruder_last_move[EXTRUDERS] = { 0 };
  105. #endif // DISABLE_INACTIVE_EXTRUDER
  106. #ifdef XY_FREQUENCY_LIMIT
  107. // Old direction bits. Used for speed calculations
  108. unsigned char Planner::old_direction_bits = 0;
  109. // Segment times (in µs). Used for speed calculations
  110. long Planner::axis_segment_time[2][3] = { {MAX_FREQ_TIME + 1, 0, 0}, {MAX_FREQ_TIME + 1, 0, 0} };
  111. #endif
  112. /**
  113. * Class and Instance Methods
  114. */
  115. Planner::Planner() { init(); }
  116. void Planner::init() {
  117. block_buffer_head = block_buffer_tail = 0;
  118. memset(position, 0, sizeof(position)); // clear position
  119. LOOP_XYZE(i) previous_speed[i] = 0.0;
  120. previous_nominal_speed = 0.0;
  121. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  122. bed_level_matrix.set_to_identity();
  123. #endif
  124. }
  125. /**
  126. * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
  127. * by the provided factors.
  128. */
  129. void Planner::calculate_trapezoid_for_block(block_t* block, float entry_factor, float exit_factor) {
  130. unsigned long initial_rate = ceil(block->nominal_rate * entry_factor),
  131. final_rate = ceil(block->nominal_rate * exit_factor); // (steps per second)
  132. // Limit minimal step rate (Otherwise the timer will overflow.)
  133. NOLESS(initial_rate, 120);
  134. NOLESS(final_rate, 120);
  135. long accel = block->acceleration_steps_per_s2;
  136. int32_t accelerate_steps = ceil(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel));
  137. int32_t decelerate_steps = floor(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel));
  138. // Calculate the size of Plateau of Nominal Rate.
  139. int32_t plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
  140. // Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will
  141. // have to use intersection_distance() to calculate when to abort accel and start braking
  142. // in order to reach the final_rate exactly at the end of this block.
  143. if (plateau_steps < 0) {
  144. accelerate_steps = ceil(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
  145. accelerate_steps = max(accelerate_steps, 0); // Check limits due to numerical round-off
  146. 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)
  147. plateau_steps = 0;
  148. }
  149. #if ENABLED(ADVANCE)
  150. volatile long initial_advance = block->advance * sq(entry_factor);
  151. volatile long final_advance = block->advance * sq(exit_factor);
  152. #endif // ADVANCE
  153. // block->accelerate_until = accelerate_steps;
  154. // block->decelerate_after = accelerate_steps+plateau_steps;
  155. CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section
  156. if (!block->busy) { // Don't update variables if block is busy.
  157. block->accelerate_until = accelerate_steps;
  158. block->decelerate_after = accelerate_steps + plateau_steps;
  159. block->initial_rate = initial_rate;
  160. block->final_rate = final_rate;
  161. #if ENABLED(ADVANCE)
  162. block->initial_advance = initial_advance;
  163. block->final_advance = final_advance;
  164. #endif
  165. }
  166. CRITICAL_SECTION_END;
  167. }
  168. // "Junction jerk" in this context is the immediate change in speed at the junction of two blocks.
  169. // This method will calculate the junction jerk as the euclidean distance between the nominal
  170. // velocities of the respective blocks.
  171. //inline float junction_jerk(block_t *before, block_t *after) {
  172. // return sqrt(
  173. // pow((before->speed_x-after->speed_x), 2)+pow((before->speed_y-after->speed_y), 2));
  174. //}
  175. // The kernel called by recalculate() when scanning the plan from last to first entry.
  176. void Planner::reverse_pass_kernel(block_t* current, block_t* next) {
  177. if (!current) return;
  178. if (next) {
  179. // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
  180. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
  181. // check for maximum allowable speed reductions to ensure maximum possible planned speed.
  182. float max_entry_speed = current->max_entry_speed;
  183. if (current->entry_speed != max_entry_speed) {
  184. // If nominal length true, max junction speed is guaranteed to be reached. Only compute
  185. // for max allowable speed if block is decelerating and nominal length is false.
  186. if (!current->nominal_length_flag && max_entry_speed > next->entry_speed) {
  187. current->entry_speed = min(max_entry_speed,
  188. max_allowable_speed(-current->acceleration, next->entry_speed, current->millimeters));
  189. }
  190. else {
  191. current->entry_speed = max_entry_speed;
  192. }
  193. current->recalculate_flag = true;
  194. }
  195. } // Skip last block. Already initialized and set for recalculation.
  196. }
  197. /**
  198. * recalculate() needs to go over the current plan twice.
  199. * Once in reverse and once forward. This implements the reverse pass.
  200. */
  201. void Planner::reverse_pass() {
  202. if (movesplanned() > 3) {
  203. block_t* block[3] = { NULL, NULL, NULL };
  204. // Make a local copy of block_buffer_tail, because the interrupt can alter it
  205. CRITICAL_SECTION_START;
  206. uint8_t tail = block_buffer_tail;
  207. CRITICAL_SECTION_END
  208. uint8_t b = BLOCK_MOD(block_buffer_head - 3);
  209. while (b != tail) {
  210. b = prev_block_index(b);
  211. block[2] = block[1];
  212. block[1] = block[0];
  213. block[0] = &block_buffer[b];
  214. reverse_pass_kernel(block[1], block[2]);
  215. }
  216. }
  217. }
  218. // The kernel called by recalculate() when scanning the plan from first to last entry.
  219. void Planner::forward_pass_kernel(block_t* previous, block_t* current) {
  220. if (!previous) return;
  221. // If the previous block is an acceleration block, but it is not long enough to complete the
  222. // full speed change within the block, we need to adjust the entry speed accordingly. Entry
  223. // speeds have already been reset, maximized, and reverse planned by reverse planner.
  224. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
  225. if (!previous->nominal_length_flag) {
  226. if (previous->entry_speed < current->entry_speed) {
  227. double entry_speed = min(current->entry_speed,
  228. max_allowable_speed(-previous->acceleration, previous->entry_speed, previous->millimeters));
  229. // Check for junction speed change
  230. if (current->entry_speed != entry_speed) {
  231. current->entry_speed = entry_speed;
  232. current->recalculate_flag = true;
  233. }
  234. }
  235. }
  236. }
  237. /**
  238. * recalculate() needs to go over the current plan twice.
  239. * Once in reverse and once forward. This implements the forward pass.
  240. */
  241. void Planner::forward_pass() {
  242. block_t* block[3] = { NULL, NULL, NULL };
  243. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  244. block[0] = block[1];
  245. block[1] = block[2];
  246. block[2] = &block_buffer[b];
  247. forward_pass_kernel(block[0], block[1]);
  248. }
  249. forward_pass_kernel(block[1], block[2]);
  250. }
  251. /**
  252. * Recalculate the trapezoid speed profiles for all blocks in the plan
  253. * according to the entry_factor for each junction. Must be called by
  254. * recalculate() after updating the blocks.
  255. */
  256. void Planner::recalculate_trapezoids() {
  257. int8_t block_index = block_buffer_tail;
  258. block_t* current;
  259. block_t* next = NULL;
  260. while (block_index != block_buffer_head) {
  261. current = next;
  262. next = &block_buffer[block_index];
  263. if (current) {
  264. // Recalculate if current block entry or exit junction speed has changed.
  265. if (current->recalculate_flag || next->recalculate_flag) {
  266. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  267. float nom = current->nominal_speed;
  268. calculate_trapezoid_for_block(current, current->entry_speed / nom, next->entry_speed / nom);
  269. current->recalculate_flag = false; // Reset current only to ensure next trapezoid is computed
  270. }
  271. }
  272. block_index = next_block_index(block_index);
  273. }
  274. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  275. if (next) {
  276. float nom = next->nominal_speed;
  277. calculate_trapezoid_for_block(next, next->entry_speed / nom, (MINIMUM_PLANNER_SPEED) / nom);
  278. next->recalculate_flag = false;
  279. }
  280. }
  281. /*
  282. * Recalculate the motion plan according to the following algorithm:
  283. *
  284. * 1. Go over every block in reverse order...
  285. *
  286. * Calculate a junction speed reduction (block_t.entry_factor) so:
  287. *
  288. * a. The junction jerk is within the set limit, and
  289. *
  290. * b. No speed reduction within one block requires faster
  291. * deceleration than the one, true constant acceleration.
  292. *
  293. * 2. Go over every block in chronological order...
  294. *
  295. * Dial down junction speed reduction values if:
  296. * a. The speed increase within one block would require faster
  297. * acceleration than the one, true constant acceleration.
  298. *
  299. * After that, all blocks will have an entry_factor allowing all speed changes to
  300. * be performed using only the one, true constant acceleration, and where no junction
  301. * jerk is jerkier than the set limit, Jerky. Finally it will:
  302. *
  303. * 3. Recalculate "trapezoids" for all blocks.
  304. */
  305. void Planner::recalculate() {
  306. reverse_pass();
  307. forward_pass();
  308. recalculate_trapezoids();
  309. }
  310. #if ENABLED(AUTOTEMP)
  311. void Planner::getHighESpeed() {
  312. static float oldt = 0;
  313. if (!autotemp_enabled) return;
  314. if (thermalManager.degTargetHotend(0) + 2 < autotemp_min) return; // probably temperature set to zero.
  315. float high = 0.0;
  316. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  317. block_t* block = &block_buffer[b];
  318. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS]) {
  319. float se = (float)block->steps[E_AXIS] / block->step_event_count * block->nominal_speed; // mm/sec;
  320. NOLESS(high, se);
  321. }
  322. }
  323. float t = autotemp_min + high * autotemp_factor;
  324. t = constrain(t, autotemp_min, autotemp_max);
  325. if (oldt > t) {
  326. t *= (1 - (AUTOTEMP_OLDWEIGHT));
  327. t += (AUTOTEMP_OLDWEIGHT) * oldt;
  328. }
  329. oldt = t;
  330. thermalManager.setTargetHotend(t, 0);
  331. }
  332. #endif //AUTOTEMP
  333. /**
  334. * Maintain fans, paste extruder pressure,
  335. */
  336. void Planner::check_axes_activity() {
  337. unsigned char axis_active[NUM_AXIS] = { 0 },
  338. tail_fan_speed[FAN_COUNT];
  339. #if FAN_COUNT > 0
  340. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = fanSpeeds[i];
  341. #endif
  342. #if ENABLED(BARICUDA)
  343. #if HAS_HEATER_1
  344. unsigned char tail_valve_pressure = baricuda_valve_pressure;
  345. #endif
  346. #if HAS_HEATER_2
  347. unsigned char tail_e_to_p_pressure = baricuda_e_to_p_pressure;
  348. #endif
  349. #endif
  350. if (blocks_queued()) {
  351. #if FAN_COUNT > 0
  352. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = block_buffer[block_buffer_tail].fan_speed[i];
  353. #endif
  354. block_t* block;
  355. #if ENABLED(BARICUDA)
  356. block = &block_buffer[block_buffer_tail];
  357. #if HAS_HEATER_1
  358. tail_valve_pressure = block->valve_pressure;
  359. #endif
  360. #if HAS_HEATER_2
  361. tail_e_to_p_pressure = block->e_to_p_pressure;
  362. #endif
  363. #endif
  364. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  365. block = &block_buffer[b];
  366. LOOP_XYZE(i) if (block->steps[i]) axis_active[i]++;
  367. }
  368. }
  369. #if ENABLED(DISABLE_X)
  370. if (!axis_active[X_AXIS]) disable_x();
  371. #endif
  372. #if ENABLED(DISABLE_Y)
  373. if (!axis_active[Y_AXIS]) disable_y();
  374. #endif
  375. #if ENABLED(DISABLE_Z)
  376. if (!axis_active[Z_AXIS]) disable_z();
  377. #endif
  378. #if ENABLED(DISABLE_E)
  379. if (!axis_active[E_AXIS]) {
  380. disable_e0();
  381. disable_e1();
  382. disable_e2();
  383. disable_e3();
  384. }
  385. #endif
  386. #if FAN_COUNT > 0
  387. #if defined(FAN_MIN_PWM)
  388. #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? ( FAN_MIN_PWM + (tail_fan_speed[f] * (255 - FAN_MIN_PWM)) / 255 ) : 0)
  389. #else
  390. #define CALC_FAN_SPEED(f) tail_fan_speed[f]
  391. #endif
  392. #ifdef FAN_KICKSTART_TIME
  393. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  394. #define KICKSTART_FAN(f) \
  395. if (tail_fan_speed[f]) { \
  396. millis_t ms = millis(); \
  397. if (fan_kick_end[f] == 0) { \
  398. fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
  399. tail_fan_speed[f] = 255; \
  400. } else { \
  401. if (PENDING(ms, fan_kick_end[f])) { \
  402. tail_fan_speed[f] = 255; \
  403. } \
  404. } \
  405. } else { \
  406. fan_kick_end[f] = 0; \
  407. }
  408. #if HAS_FAN0
  409. KICKSTART_FAN(0);
  410. #endif
  411. #if HAS_FAN1
  412. KICKSTART_FAN(1);
  413. #endif
  414. #if HAS_FAN2
  415. KICKSTART_FAN(2);
  416. #endif
  417. #endif //FAN_KICKSTART_TIME
  418. #if ENABLED(FAN_SOFT_PWM)
  419. #if HAS_FAN0
  420. thermalManager.fanSpeedSoftPwm[0] = CALC_FAN_SPEED(0);
  421. #endif
  422. #if HAS_FAN1
  423. thermalManager.fanSpeedSoftPwm[1] = CALC_FAN_SPEED(1);
  424. #endif
  425. #if HAS_FAN2
  426. thermalManager.fanSpeedSoftPwm[2] = CALC_FAN_SPEED(2);
  427. #endif
  428. #else
  429. #if HAS_FAN0
  430. analogWrite(FAN_PIN, CALC_FAN_SPEED(0));
  431. #endif
  432. #if HAS_FAN1
  433. analogWrite(FAN1_PIN, CALC_FAN_SPEED(1));
  434. #endif
  435. #if HAS_FAN2
  436. analogWrite(FAN2_PIN, CALC_FAN_SPEED(2));
  437. #endif
  438. #endif
  439. #endif // FAN_COUNT > 0
  440. #if ENABLED(AUTOTEMP)
  441. getHighESpeed();
  442. #endif
  443. #if ENABLED(BARICUDA)
  444. #if HAS_HEATER_1
  445. analogWrite(HEATER_1_PIN, tail_valve_pressure);
  446. #endif
  447. #if HAS_HEATER_2
  448. analogWrite(HEATER_2_PIN, tail_e_to_p_pressure);
  449. #endif
  450. #endif
  451. }
  452. /**
  453. * Planner::buffer_line
  454. *
  455. * Add a new linear movement to the buffer.
  456. *
  457. * x,y,z,e - target position in mm
  458. * fr_mm_s - (target) speed of the move
  459. * extruder - target extruder
  460. */
  461. #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING)
  462. void Planner::buffer_line(float x, float y, float z, const float& e, float fr_mm_s, const uint8_t extruder)
  463. #else
  464. void Planner::buffer_line(const float& x, const float& y, const float& z, const float& e, float fr_mm_s, const uint8_t extruder)
  465. #endif // AUTO_BED_LEVELING_FEATURE
  466. {
  467. // Calculate the buffer head after we push this byte
  468. int next_buffer_head = next_block_index(block_buffer_head);
  469. // If the buffer is full: good! That means we are well ahead of the robot.
  470. // Rest here until there is room in the buffer.
  471. while (block_buffer_tail == next_buffer_head) idle();
  472. #if ENABLED(MESH_BED_LEVELING)
  473. if (mbl.active())
  474. z += mbl.get_z(x - home_offset[X_AXIS], y - home_offset[Y_AXIS]);
  475. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  476. apply_rotation_xyz(bed_level_matrix, x, y, z);
  477. #endif
  478. // The target position of the tool in absolute steps
  479. // Calculate target position in absolute steps
  480. //this should be done after the wait, because otherwise a M92 code within the gcode disrupts this calculation somehow
  481. long target[NUM_AXIS] = {
  482. lround(x * axis_steps_per_mm[X_AXIS]),
  483. lround(y * axis_steps_per_mm[Y_AXIS]),
  484. lround(z * axis_steps_per_mm[Z_AXIS]),
  485. lround(e * axis_steps_per_mm[E_AXIS])
  486. };
  487. long dx = target[X_AXIS] - position[X_AXIS],
  488. dy = target[Y_AXIS] - position[Y_AXIS],
  489. dz = target[Z_AXIS] - position[Z_AXIS];
  490. /*
  491. SERIAL_ECHO_START;
  492. SERIAL_ECHOPAIR("Planner X:", x);
  493. SERIAL_ECHOPAIR(" (", dx);
  494. SERIAL_ECHOPAIR(") Y:", y);
  495. SERIAL_ECHOPAIR(" (", dy);
  496. SERIAL_ECHOPAIR(") Z:", z);
  497. SERIAL_ECHOPAIR(" (", dz);
  498. SERIAL_ECHOLNPGM(")");
  499. //*/
  500. // DRYRUN ignores all temperature constraints and assures that the extruder is instantly satisfied
  501. if (DEBUGGING(DRYRUN))
  502. position[E_AXIS] = target[E_AXIS];
  503. long de = target[E_AXIS] - position[E_AXIS];
  504. #if ENABLED(PREVENT_COLD_EXTRUSION)
  505. if (de) {
  506. if (thermalManager.tooColdToExtrude(extruder)) {
  507. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  508. de = 0; // no difference
  509. SERIAL_ECHO_START;
  510. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  511. }
  512. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  513. if (labs(de) > axis_steps_per_mm[E_AXIS] * (EXTRUDE_MAXLENGTH)) {
  514. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  515. de = 0; // no difference
  516. SERIAL_ECHO_START;
  517. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  518. }
  519. #endif
  520. }
  521. #endif
  522. // Prepare to set up new block
  523. block_t* block = &block_buffer[block_buffer_head];
  524. // Mark block as not busy (Not executed by the stepper interrupt)
  525. block->busy = false;
  526. // Number of steps for each axis
  527. #if ENABLED(COREXY)
  528. // corexy planning
  529. // these equations follow the form of the dA and dB equations on http://www.corexy.com/theory.html
  530. block->steps[A_AXIS] = labs(dx + dy);
  531. block->steps[B_AXIS] = labs(dx - dy);
  532. block->steps[Z_AXIS] = labs(dz);
  533. #elif ENABLED(COREXZ)
  534. // corexz planning
  535. block->steps[A_AXIS] = labs(dx + dz);
  536. block->steps[Y_AXIS] = labs(dy);
  537. block->steps[C_AXIS] = labs(dx - dz);
  538. #elif ENABLED(COREYZ)
  539. // coreyz planning
  540. block->steps[X_AXIS] = labs(dx);
  541. block->steps[B_AXIS] = labs(dy + dz);
  542. block->steps[C_AXIS] = labs(dy - dz);
  543. #else
  544. // default non-h-bot planning
  545. block->steps[X_AXIS] = labs(dx);
  546. block->steps[Y_AXIS] = labs(dy);
  547. block->steps[Z_AXIS] = labs(dz);
  548. #endif
  549. block->steps[E_AXIS] = labs(de) * volumetric_multiplier[extruder] * flow_percentage[extruder] * 0.01 + 0.5;
  550. block->step_event_count = MAX4(block->steps[X_AXIS], block->steps[Y_AXIS], block->steps[Z_AXIS], block->steps[E_AXIS]);
  551. // Bail if this is a zero-length block
  552. if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return;
  553. // For a mixing extruder, get a magnified step_event_count for each
  554. #if ENABLED(MIXING_EXTRUDER)
  555. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  556. block->mix_event_count[i] = (mixing_factor[i] < 0.0001) ? 0 : block->step_event_count / mixing_factor[i];
  557. #endif
  558. #if FAN_COUNT > 0
  559. for (uint8_t i = 0; i < FAN_COUNT; i++) block->fan_speed[i] = fanSpeeds[i];
  560. #endif
  561. #if ENABLED(BARICUDA)
  562. block->valve_pressure = baricuda_valve_pressure;
  563. block->e_to_p_pressure = baricuda_e_to_p_pressure;
  564. #endif
  565. // Compute direction bits for this block
  566. uint8_t db = 0;
  567. #if ENABLED(COREXY)
  568. if (dx < 0) SBI(db, X_HEAD); // Save the real Extruder (head) direction in X Axis
  569. if (dy < 0) SBI(db, Y_HEAD); // ...and Y
  570. if (dz < 0) SBI(db, Z_AXIS);
  571. if (dx + dy < 0) SBI(db, A_AXIS); // Motor A direction
  572. if (dx - dy < 0) SBI(db, B_AXIS); // Motor B direction
  573. #elif ENABLED(COREXZ)
  574. if (dx < 0) SBI(db, X_HEAD); // Save the real Extruder (head) direction in X Axis
  575. if (dy < 0) SBI(db, Y_AXIS);
  576. if (dz < 0) SBI(db, Z_HEAD); // ...and Z
  577. if (dx + dz < 0) SBI(db, A_AXIS); // Motor A direction
  578. if (dx - dz < 0) SBI(db, C_AXIS); // Motor C direction
  579. #elif ENABLED(COREYZ)
  580. if (dx < 0) SBI(db, X_AXIS);
  581. if (dy < 0) SBI(db, Y_HEAD); // Save the real Extruder (head) direction in Y Axis
  582. if (dz < 0) SBI(db, Z_HEAD); // ...and Z
  583. if (dy + dz < 0) SBI(db, B_AXIS); // Motor B direction
  584. if (dy - dz < 0) SBI(db, C_AXIS); // Motor C direction
  585. #else
  586. if (dx < 0) SBI(db, X_AXIS);
  587. if (dy < 0) SBI(db, Y_AXIS);
  588. if (dz < 0) SBI(db, Z_AXIS);
  589. #endif
  590. if (de < 0) SBI(db, E_AXIS);
  591. block->direction_bits = db;
  592. block->active_extruder = extruder;
  593. //enable active axes
  594. #if ENABLED(COREXY)
  595. if (block->steps[A_AXIS] || block->steps[B_AXIS]) {
  596. enable_x();
  597. enable_y();
  598. }
  599. #if DISABLED(Z_LATE_ENABLE)
  600. if (block->steps[Z_AXIS]) enable_z();
  601. #endif
  602. #elif ENABLED(COREXZ)
  603. if (block->steps[A_AXIS] || block->steps[C_AXIS]) {
  604. enable_x();
  605. enable_z();
  606. }
  607. if (block->steps[Y_AXIS]) enable_y();
  608. #else
  609. if (block->steps[X_AXIS]) enable_x();
  610. if (block->steps[Y_AXIS]) enable_y();
  611. #if DISABLED(Z_LATE_ENABLE)
  612. if (block->steps[Z_AXIS]) enable_z();
  613. #endif
  614. #endif
  615. // Enable extruder(s)
  616. if (block->steps[E_AXIS]) {
  617. #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
  618. for (int i = 0; i < EXTRUDERS; i++)
  619. if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
  620. switch(extruder) {
  621. case 0:
  622. enable_e0();
  623. #if ENABLED(DUAL_X_CARRIAGE)
  624. if (extruder_duplication_enabled) {
  625. enable_e1();
  626. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  627. }
  628. #endif
  629. g_uc_extruder_last_move[0] = (BLOCK_BUFFER_SIZE) * 2;
  630. #if EXTRUDERS > 1
  631. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  632. #if EXTRUDERS > 2
  633. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  634. #if EXTRUDERS > 3
  635. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  636. #endif
  637. #endif
  638. #endif
  639. break;
  640. #if EXTRUDERS > 1
  641. case 1:
  642. enable_e1();
  643. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  644. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  645. #if EXTRUDERS > 2
  646. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  647. #if EXTRUDERS > 3
  648. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  649. #endif
  650. #endif
  651. break;
  652. #if EXTRUDERS > 2
  653. case 2:
  654. enable_e2();
  655. g_uc_extruder_last_move[2] = (BLOCK_BUFFER_SIZE) * 2;
  656. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  657. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  658. #if EXTRUDERS > 3
  659. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  660. #endif
  661. break;
  662. #if EXTRUDERS > 3
  663. case 3:
  664. enable_e3();
  665. g_uc_extruder_last_move[3] = (BLOCK_BUFFER_SIZE) * 2;
  666. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  667. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  668. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  669. break;
  670. #endif // EXTRUDERS > 3
  671. #endif // EXTRUDERS > 2
  672. #endif // EXTRUDERS > 1
  673. }
  674. #else
  675. enable_e0();
  676. enable_e1();
  677. enable_e2();
  678. enable_e3();
  679. #endif
  680. }
  681. if (block->steps[E_AXIS])
  682. NOLESS(fr_mm_s, min_feedrate_mm_s);
  683. else
  684. NOLESS(fr_mm_s, min_travel_feedrate_mm_s);
  685. /**
  686. * This part of the code calculates the total length of the movement.
  687. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  688. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  689. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  690. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  691. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  692. */
  693. #if ENABLED(COREXY) || ENABLED(COREXZ) || ENABLED(COREYZ)
  694. float delta_mm[7];
  695. #if ENABLED(COREXY)
  696. delta_mm[X_HEAD] = dx * steps_to_mm[A_AXIS];
  697. delta_mm[Y_HEAD] = dy * steps_to_mm[B_AXIS];
  698. delta_mm[Z_AXIS] = dz * steps_to_mm[Z_AXIS];
  699. delta_mm[A_AXIS] = (dx + dy) * steps_to_mm[A_AXIS];
  700. delta_mm[B_AXIS] = (dx - dy) * steps_to_mm[B_AXIS];
  701. #elif ENABLED(COREXZ)
  702. delta_mm[X_HEAD] = dx * steps_to_mm[A_AXIS];
  703. delta_mm[Y_AXIS] = dy * steps_to_mm[Y_AXIS];
  704. delta_mm[Z_HEAD] = dz * steps_to_mm[C_AXIS];
  705. delta_mm[A_AXIS] = (dx + dz) * steps_to_mm[A_AXIS];
  706. delta_mm[C_AXIS] = (dx - dz) * steps_to_mm[C_AXIS];
  707. #elif ENABLED(COREYZ)
  708. delta_mm[X_AXIS] = dx * steps_to_mm[X_AXIS];
  709. delta_mm[Y_HEAD] = dy * steps_to_mm[B_AXIS];
  710. delta_mm[Z_HEAD] = dz * steps_to_mm[C_AXIS];
  711. delta_mm[B_AXIS] = (dy + dz) * steps_to_mm[B_AXIS];
  712. delta_mm[C_AXIS] = (dy - dz) * steps_to_mm[C_AXIS];
  713. #endif
  714. #else
  715. float delta_mm[4];
  716. delta_mm[X_AXIS] = dx * steps_to_mm[X_AXIS];
  717. delta_mm[Y_AXIS] = dy * steps_to_mm[Y_AXIS];
  718. delta_mm[Z_AXIS] = dz * steps_to_mm[Z_AXIS];
  719. #endif
  720. delta_mm[E_AXIS] = 0.01 * (de * steps_to_mm[E_AXIS]) * volumetric_multiplier[extruder] * flow_percentage[extruder];
  721. if (block->steps[X_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[Y_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[Z_AXIS] < MIN_STEPS_PER_SEGMENT) {
  722. block->millimeters = fabs(delta_mm[E_AXIS]);
  723. }
  724. else {
  725. block->millimeters = sqrt(
  726. #if ENABLED(COREXY)
  727. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_AXIS])
  728. #elif ENABLED(COREXZ)
  729. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_HEAD])
  730. #elif ENABLED(COREYZ)
  731. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_HEAD])
  732. #else
  733. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_AXIS])
  734. #endif
  735. );
  736. }
  737. float inverse_millimeters = 1.0 / block->millimeters; // Inverse millimeters to remove multiple divides
  738. // Calculate moves/second for this move. No divide by zero due to previous checks.
  739. float inverse_mm_s = fr_mm_s * inverse_millimeters;
  740. int moves_queued = movesplanned();
  741. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  742. #if ENABLED(OLD_SLOWDOWN) || ENABLED(SLOWDOWN)
  743. bool mq = moves_queued > 1 && moves_queued < (BLOCK_BUFFER_SIZE) / 2;
  744. #if ENABLED(OLD_SLOWDOWN)
  745. if (mq) fr_mm_s *= 2.0 * moves_queued / (BLOCK_BUFFER_SIZE);
  746. #endif
  747. #if ENABLED(SLOWDOWN)
  748. // segment time im micro seconds
  749. unsigned long segment_time = lround(1000000.0/inverse_mm_s);
  750. if (mq) {
  751. if (segment_time < min_segment_time) {
  752. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  753. inverse_mm_s = 1000000.0 / (segment_time + lround(2 * (min_segment_time - segment_time) / moves_queued));
  754. #ifdef XY_FREQUENCY_LIMIT
  755. segment_time = lround(1000000.0 / inverse_mm_s);
  756. #endif
  757. }
  758. }
  759. #endif
  760. #endif
  761. block->nominal_speed = block->millimeters * inverse_mm_s; // (mm/sec) Always > 0
  762. block->nominal_rate = ceil(block->step_event_count * inverse_mm_s); // (step/sec) Always > 0
  763. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  764. static float filwidth_e_count = 0, filwidth_delay_dist = 0;
  765. //FMM update ring buffer used for delay with filament measurements
  766. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM && filwidth_delay_index2 >= 0) { //only for extruder with filament sensor and if ring buffer is initialized
  767. const int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10;
  768. // increment counters with next move in e axis
  769. filwidth_e_count += delta_mm[E_AXIS];
  770. filwidth_delay_dist += delta_mm[E_AXIS];
  771. // Only get new measurements on forward E movement
  772. if (filwidth_e_count > 0.0001) {
  773. // Loop the delay distance counter (modulus by the mm length)
  774. while (filwidth_delay_dist >= MMD_MM) filwidth_delay_dist -= MMD_MM;
  775. // Convert into an index into the measurement array
  776. filwidth_delay_index1 = (int)(filwidth_delay_dist * 0.1 + 0.0001);
  777. // If the index has changed (must have gone forward)...
  778. if (filwidth_delay_index1 != filwidth_delay_index2) {
  779. filwidth_e_count = 0; // Reset the E movement counter
  780. int8_t meas_sample = thermalManager.widthFil_to_size_ratio() - 100; // Subtract 100 to reduce magnitude - to store in a signed char
  781. do {
  782. filwidth_delay_index2 = (filwidth_delay_index2 + 1) % MMD_CM; // The next unused slot
  783. measurement_delay[filwidth_delay_index2] = meas_sample; // Store the measurement
  784. } while (filwidth_delay_index1 != filwidth_delay_index2); // More slots to fill?
  785. }
  786. }
  787. }
  788. #endif
  789. // Calculate and limit speed in mm/sec for each axis
  790. float current_speed[NUM_AXIS];
  791. float speed_factor = 1.0; //factor <=1 do decrease speed
  792. LOOP_XYZE(i) {
  793. current_speed[i] = delta_mm[i] * inverse_mm_s;
  794. float cs = fabs(current_speed[i]), mf = max_feedrate_mm_s[i];
  795. if (cs > mf) speed_factor = min(speed_factor, mf / cs);
  796. }
  797. // Max segement time in us.
  798. #ifdef XY_FREQUENCY_LIMIT
  799. // Check and limit the xy direction change frequency
  800. unsigned char direction_change = block->direction_bits ^ old_direction_bits;
  801. old_direction_bits = block->direction_bits;
  802. segment_time = lround((float)segment_time / speed_factor);
  803. long xs0 = axis_segment_time[X_AXIS][0],
  804. xs1 = axis_segment_time[X_AXIS][1],
  805. xs2 = axis_segment_time[X_AXIS][2],
  806. ys0 = axis_segment_time[Y_AXIS][0],
  807. ys1 = axis_segment_time[Y_AXIS][1],
  808. ys2 = axis_segment_time[Y_AXIS][2];
  809. if (TEST(direction_change, X_AXIS)) {
  810. xs2 = axis_segment_time[X_AXIS][2] = xs1;
  811. xs1 = axis_segment_time[X_AXIS][1] = xs0;
  812. xs0 = 0;
  813. }
  814. xs0 = axis_segment_time[X_AXIS][0] = xs0 + segment_time;
  815. if (TEST(direction_change, Y_AXIS)) {
  816. ys2 = axis_segment_time[Y_AXIS][2] = axis_segment_time[Y_AXIS][1];
  817. ys1 = axis_segment_time[Y_AXIS][1] = axis_segment_time[Y_AXIS][0];
  818. ys0 = 0;
  819. }
  820. ys0 = axis_segment_time[Y_AXIS][0] = ys0 + segment_time;
  821. long max_x_segment_time = MAX3(xs0, xs1, xs2),
  822. max_y_segment_time = MAX3(ys0, ys1, ys2),
  823. min_xy_segment_time = min(max_x_segment_time, max_y_segment_time);
  824. if (min_xy_segment_time < MAX_FREQ_TIME) {
  825. float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME);
  826. speed_factor = min(speed_factor, low_sf);
  827. }
  828. #endif // XY_FREQUENCY_LIMIT
  829. // Correct the speed
  830. if (speed_factor < 1.0) {
  831. LOOP_XYZE(i) current_speed[i] *= speed_factor;
  832. block->nominal_speed *= speed_factor;
  833. block->nominal_rate *= speed_factor;
  834. }
  835. // Compute and limit the acceleration rate for the trapezoid generator.
  836. float steps_per_mm = block->step_event_count / block->millimeters;
  837. if (!block->steps[X_AXIS] && !block->steps[Y_AXIS] && !block->steps[Z_AXIS]) {
  838. block->acceleration_steps_per_s2 = ceil(retract_acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  839. }
  840. else {
  841. // Limit acceleration per axis
  842. block->acceleration_steps_per_s2 = ceil((block->steps[E_AXIS] ? acceleration : travel_acceleration) * steps_per_mm);
  843. if (max_acceleration_steps_per_s2[X_AXIS] < (block->acceleration_steps_per_s2 * block->steps[X_AXIS]) / block->step_event_count)
  844. block->acceleration_steps_per_s2 = (max_acceleration_steps_per_s2[X_AXIS] * block->step_event_count) / block->steps[X_AXIS];
  845. if (max_acceleration_steps_per_s2[Y_AXIS] < (block->acceleration_steps_per_s2 * block->steps[Y_AXIS]) / block->step_event_count)
  846. block->acceleration_steps_per_s2 = (max_acceleration_steps_per_s2[Y_AXIS] * block->step_event_count) / block->steps[Y_AXIS];
  847. if (max_acceleration_steps_per_s2[Z_AXIS] < (block->acceleration_steps_per_s2 * block->steps[Z_AXIS]) / block->step_event_count)
  848. block->acceleration_steps_per_s2 = (max_acceleration_steps_per_s2[Z_AXIS] * block->step_event_count) / block->steps[Z_AXIS];
  849. if (max_acceleration_steps_per_s2[E_AXIS] < (block->acceleration_steps_per_s2 * block->steps[E_AXIS]) / block->step_event_count)
  850. block->acceleration_steps_per_s2 = (max_acceleration_steps_per_s2[E_AXIS] * block->step_event_count) / block->steps[E_AXIS];
  851. }
  852. block->acceleration = block->acceleration_steps_per_s2 / steps_per_mm;
  853. block->acceleration_rate = (long)(block->acceleration_steps_per_s2 * 16777216.0 / ((F_CPU) * 0.125));
  854. #if 0 // Use old jerk for now
  855. float junction_deviation = 0.1;
  856. // Compute path unit vector
  857. double unit_vec[XYZ];
  858. unit_vec[X_AXIS] = delta_mm[X_AXIS] * inverse_millimeters;
  859. unit_vec[Y_AXIS] = delta_mm[Y_AXIS] * inverse_millimeters;
  860. unit_vec[Z_AXIS] = delta_mm[Z_AXIS] * inverse_millimeters;
  861. // Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  862. // Let a circle be tangent to both previous and current path line segments, where the junction
  863. // deviation is defined as the distance from the junction to the closest edge of the circle,
  864. // collinear with the circle center. The circular segment joining the two paths represents the
  865. // path of centripetal acceleration. Solve for max velocity based on max acceleration about the
  866. // radius of the circle, defined indirectly by junction deviation. This may be also viewed as
  867. // path width or max_jerk in the previous grbl version. This approach does not actually deviate
  868. // from path, but used as a robust way to compute cornering speeds, as it takes into account the
  869. // nonlinearities of both the junction angle and junction velocity.
  870. double vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed
  871. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  872. if ((block_buffer_head != block_buffer_tail) && (previous_nominal_speed > 0.0)) {
  873. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  874. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  875. double cos_theta = - previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
  876. - previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
  877. - previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS] ;
  878. // Skip and use default max junction speed for 0 degree acute junction.
  879. if (cos_theta < 0.95) {
  880. vmax_junction = min(previous_nominal_speed, block->nominal_speed);
  881. // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds.
  882. if (cos_theta > -0.95) {
  883. // Compute maximum junction velocity based on maximum acceleration and junction deviation
  884. double sin_theta_d2 = sqrt(0.5 * (1.0 - cos_theta)); // Trig half angle identity. Always positive.
  885. vmax_junction = min(vmax_junction,
  886. sqrt(block->acceleration * junction_deviation * sin_theta_d2 / (1.0 - sin_theta_d2)));
  887. }
  888. }
  889. }
  890. #endif
  891. // Start with a safe speed
  892. float vmax_junction = max_xy_jerk * 0.5,
  893. vmax_junction_factor = 1.0,
  894. mz2 = max_z_jerk * 0.5,
  895. me2 = max_e_jerk * 0.5,
  896. csz = current_speed[Z_AXIS],
  897. cse = current_speed[E_AXIS];
  898. if (fabs(csz) > mz2) vmax_junction = min(vmax_junction, mz2);
  899. if (fabs(cse) > me2) vmax_junction = min(vmax_junction, me2);
  900. vmax_junction = min(vmax_junction, block->nominal_speed);
  901. float safe_speed = vmax_junction;
  902. if ((moves_queued > 1) && (previous_nominal_speed > 0.0001)) {
  903. float dsx = current_speed[X_AXIS] - previous_speed[X_AXIS],
  904. dsy = current_speed[Y_AXIS] - previous_speed[Y_AXIS],
  905. dsz = fabs(csz - previous_speed[Z_AXIS]),
  906. dse = fabs(cse - previous_speed[E_AXIS]),
  907. jerk = HYPOT(dsx, dsy);
  908. // if ((fabs(previous_speed[X_AXIS]) > 0.0001) || (fabs(previous_speed[Y_AXIS]) > 0.0001)) {
  909. vmax_junction = block->nominal_speed;
  910. // }
  911. if (jerk > max_xy_jerk) vmax_junction_factor = max_xy_jerk / jerk;
  912. if (dsz > max_z_jerk) vmax_junction_factor = min(vmax_junction_factor, max_z_jerk / dsz);
  913. if (dse > max_e_jerk) vmax_junction_factor = min(vmax_junction_factor, max_e_jerk / dse);
  914. vmax_junction = min(previous_nominal_speed, vmax_junction * vmax_junction_factor); // Limit speed to max previous speed
  915. }
  916. block->max_entry_speed = vmax_junction;
  917. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  918. double v_allowable = max_allowable_speed(-block->acceleration, MINIMUM_PLANNER_SPEED, block->millimeters);
  919. block->entry_speed = min(vmax_junction, v_allowable);
  920. // Initialize planner efficiency flags
  921. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  922. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  923. // the current block and next block junction speeds are guaranteed to always be at their maximum
  924. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  925. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  926. // the reverse and forward planners, the corresponding block junction speed will always be at the
  927. // the maximum junction speed and may always be ignored for any speed reduction checks.
  928. block->nominal_length_flag = (block->nominal_speed <= v_allowable);
  929. block->recalculate_flag = true; // Always calculate trapezoid for new block
  930. // Update previous path unit_vector and nominal speed
  931. LOOP_XYZE(i) previous_speed[i] = current_speed[i];
  932. previous_nominal_speed = block->nominal_speed;
  933. #if ENABLED(LIN_ADVANCE)
  934. // block->steps[E_AXIS] == block->step_event_count: A problem occurs when there's a very tiny move before a retract.
  935. // In this case, the retract and the move will be executed together.
  936. // This leads to an enormous number of advance steps due to a huge e_acceleration.
  937. // The math is correct, but you don't want a retract move done with advance!
  938. // So this situation is filtered out here.
  939. if (!block->steps[E_AXIS] || (!block->steps[X_AXIS] && !block->steps[Y_AXIS] && !block->steps[Z_AXIS]) || stepper.get_advance_k() == 0 || (uint32_t) block->steps[E_AXIS] == block->step_event_count) {
  940. block->use_advance_lead = false;
  941. }
  942. else {
  943. block->use_advance_lead = true;
  944. block->e_speed_multiplier8 = (block->steps[E_AXIS] << 8) / block->step_event_count;
  945. }
  946. #elif ENABLED(ADVANCE)
  947. // Calculate advance rate
  948. if (!block->steps[E_AXIS] || (!block->steps[X_AXIS] && !block->steps[Y_AXIS] && !block->steps[Z_AXIS])) {
  949. block->advance_rate = 0;
  950. block->advance = 0;
  951. }
  952. else {
  953. long acc_dist = estimate_acceleration_distance(0, block->nominal_rate, block->acceleration_steps_per_s2);
  954. float advance = ((STEPS_PER_CUBIC_MM_E) * (EXTRUDER_ADVANCE_K)) * HYPOT(cse, EXTRUSION_AREA) * 256;
  955. block->advance = advance;
  956. block->advance_rate = acc_dist ? advance / (float)acc_dist : 0;
  957. }
  958. /**
  959. SERIAL_ECHO_START;
  960. SERIAL_ECHOPGM("advance :");
  961. SERIAL_ECHO(block->advance/256.0);
  962. SERIAL_ECHOPGM("advance rate :");
  963. SERIAL_ECHOLN(block->advance_rate/256.0);
  964. */
  965. #endif // ADVANCE or LIN_ADVANCE
  966. calculate_trapezoid_for_block(block, block->entry_speed / block->nominal_speed, safe_speed / block->nominal_speed);
  967. // Move buffer head
  968. block_buffer_head = next_buffer_head;
  969. // Update position
  970. LOOP_XYZE(i) position[i] = target[i];
  971. recalculate();
  972. stepper.wake_up();
  973. } // buffer_line()
  974. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && DISABLED(DELTA)
  975. /**
  976. * Get the XYZ position of the steppers as a vector_3.
  977. *
  978. * On CORE machines XYZ is derived from ABC.
  979. */
  980. vector_3 Planner::adjusted_position() {
  981. vector_3 pos = vector_3(stepper.get_axis_position_mm(X_AXIS), stepper.get_axis_position_mm(Y_AXIS), stepper.get_axis_position_mm(Z_AXIS));
  982. //pos.debug("in Planner::adjusted_position");
  983. //bed_level_matrix.debug("in Planner::adjusted_position");
  984. matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
  985. //inverse.debug("in Planner::inverse");
  986. pos.apply_rotation(inverse);
  987. //pos.debug("after rotation");
  988. return pos;
  989. }
  990. #endif // AUTO_BED_LEVELING_FEATURE && !DELTA
  991. /**
  992. * Directly set the planner XYZ position (hence the stepper positions).
  993. *
  994. * On CORE machines stepper ABC will be translated from the given XYZ.
  995. */
  996. #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING)
  997. void Planner::set_position_mm(float x, float y, float z, const float& e)
  998. #else
  999. void Planner::set_position_mm(const float& x, const float& y, const float& z, const float& e)
  1000. #endif // AUTO_BED_LEVELING_FEATURE || MESH_BED_LEVELING
  1001. {
  1002. #if ENABLED(MESH_BED_LEVELING)
  1003. if (mbl.active())
  1004. z += mbl.get_z(RAW_X_POSITION(x), RAW_Y_POSITION(y));
  1005. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  1006. apply_rotation_xyz(bed_level_matrix, x, y, z);
  1007. #endif
  1008. long nx = position[X_AXIS] = lround(x * axis_steps_per_mm[X_AXIS]),
  1009. ny = position[Y_AXIS] = lround(y * axis_steps_per_mm[Y_AXIS]),
  1010. nz = position[Z_AXIS] = lround(z * axis_steps_per_mm[Z_AXIS]),
  1011. ne = position[E_AXIS] = lround(e * axis_steps_per_mm[E_AXIS]);
  1012. stepper.set_position(nx, ny, nz, ne);
  1013. previous_nominal_speed = 0.0; // Resets planner junction speeds. Assumes start from rest.
  1014. LOOP_XYZE(i) previous_speed[i] = 0.0;
  1015. }
  1016. /**
  1017. * Directly set the planner E position (hence the stepper E position).
  1018. */
  1019. void Planner::set_e_position_mm(const float& e) {
  1020. position[E_AXIS] = lround(e * axis_steps_per_mm[E_AXIS]);
  1021. stepper.set_e_position(position[E_AXIS]);
  1022. previous_speed[E_AXIS] = 0.0;
  1023. }
  1024. // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
  1025. void Planner::reset_acceleration_rates() {
  1026. LOOP_XYZE(i)
  1027. max_acceleration_steps_per_s2[i] = max_acceleration_mm_per_s2[i] * axis_steps_per_mm[i];
  1028. }
  1029. // Recalculate position, steps_to_mm if axis_steps_per_mm changes!
  1030. void Planner::refresh_positioning() {
  1031. LOOP_XYZE(i) steps_to_mm[i] = 1.0 / axis_steps_per_mm[i];
  1032. #if ENABLED(DELTA) || ENABLED(SCARA)
  1033. inverse_kinematics(current_position);
  1034. set_position_mm(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], current_position[E_AXIS]);
  1035. #else
  1036. set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1037. #endif
  1038. reset_acceleration_rates();
  1039. }
  1040. #if ENABLED(AUTOTEMP)
  1041. void Planner::autotemp_M109() {
  1042. autotemp_enabled = code_seen('F');
  1043. if (autotemp_enabled) autotemp_factor = code_value_temp_diff();
  1044. if (code_seen('S')) autotemp_min = code_value_temp_abs();
  1045. if (code_seen('B')) autotemp_max = code_value_temp_abs();
  1046. }
  1047. #endif