My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

I2CPositionEncoder.cpp 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016, 2017 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. //todo: add support for multiple encoders on a single axis
  23. //todo: add z axis auto-leveling
  24. //todo: consolidate some of the related M codes?
  25. //todo: add endstop-replacement mode?
  26. //todo: try faster I2C speed; tweak TWI_FREQ (400000L, or faster?); or just TWBR = ((CPU_FREQ / 400000L) - 16) / 2;
  27. //todo: consider Marlin-optimized Wire library; i.e. MarlinWire, like MarlinSerial
  28. #include "MarlinConfig.h"
  29. #if ENABLED(I2C_POSITION_ENCODERS)
  30. #include "Marlin.h"
  31. #include "temperature.h"
  32. #include "stepper.h"
  33. #include "I2CPositionEncoder.h"
  34. #include "gcode.h"
  35. #include <Wire.h>
  36. void I2CPositionEncoder::init(uint8_t address, AxisEnum axis) {
  37. encoderAxis = axis;
  38. i2cAddress = address;
  39. initialised++;
  40. SERIAL_ECHOPAIR("Seetting up encoder on ", axis_codes[encoderAxis]);
  41. SERIAL_ECHOLNPAIR(" axis, addr = ", address);
  42. position = get_position();
  43. }
  44. void I2CPositionEncoder::update() {
  45. if (!initialised || !homed || !active) return; //check encoder is set up and active
  46. position = get_position();
  47. //we don't want to stop things just because the encoder missed a message,
  48. //so we only care about responses that indicate bad magnetic strength
  49. if (!passes_test(false)) { //check encoder data is good
  50. lastErrorTime = millis();
  51. /*
  52. if (trusted) { //commented out as part of the note below
  53. trusted = false;
  54. SERIAL_ECHOPGM("Fault detected on ");
  55. SERIAL_ECHO(axis_codes[encoderAxis]);
  56. SERIAL_ECHOLNPGM(" axis encoder. Disengaging error correction until module is trusted again.");
  57. }
  58. */
  59. return;
  60. }
  61. if (!trusted) {
  62. /**
  63. * This is commented out because it introduces error and can cause bad print quality.
  64. *
  65. * This code is intended to manage situations where the encoder has reported bad magnetic strength.
  66. * This indicates that the magnetic strip was too far away from the sensor to reliably track position.
  67. * When this happens, this code resets the offset based on where the printer thinks it is. This has been
  68. * shown to introduce errors in actual position which result in drifting prints and poor print quality.
  69. * Perhaps a better method would be to disable correction on the axis with a problem, report it to the
  70. * user via the status leds on the encoder module and prompt the user to re-home the axis at which point
  71. * the encoder would be re-enabled.
  72. */
  73. /*
  74. // If the magnetic strength has been good for a certain time, start trusting the module again
  75. if (millis() - lastErrorTime > I2CPE_TIME_TRUSTED) {
  76. trusted = true;
  77. SERIAL_ECHOPGM("Untrusted encoder module on ");
  78. SERIAL_ECHO(axis_codes[encoderAxis]);
  79. SERIAL_ECHOLNPGM(" axis has been fault-free for set duration, reinstating error correction.");
  80. //the encoder likely lost its place when the error occured, so we'll reset and use the printer's
  81. //idea of where it the axis is to re-initialise
  82. double position = stepper.get_axis_position_mm(encoderAxis);
  83. long positionInTicks = position * get_ticks_unit();
  84. //shift position from previous to current position
  85. zeroOffset -= (positionInTicks - get_position());
  86. #if defined(I2CPE_DEBUG)
  87. SERIAL_ECHOPGM("Current position is ");
  88. SERIAL_ECHOLN(position);
  89. SERIAL_ECHOPGM("Position in encoder ticks is ");
  90. SERIAL_ECHOLN(positionInTicks);
  91. SERIAL_ECHOPGM("New zero-offset of ");
  92. SERIAL_ECHOLN(zeroOffset);
  93. SERIAL_ECHOPGM("New position reads as ");
  94. SERIAL_ECHO(get_position());
  95. SERIAL_ECHOPGM("(");
  96. SERIAL_ECHO(mm_from_count(get_position()));
  97. SERIAL_ECHOLNPGM(")");
  98. #endif
  99. }
  100. */
  101. return;
  102. }
  103. lastPosition = position;
  104. millis_t positionTime = millis();
  105. //only do error correction if setup and enabled
  106. if (ec && ecMethod != I2CPE_ECM_NONE) {
  107. #if defined(I2CPE_EC_THRESH_PROPORTIONAL)
  108. millis_t deltaTime = positionTime - lastPositionTime;
  109. unsigned long distance = abs(position - lastPosition);
  110. unsigned long speed = distance / deltaTime;
  111. float threshold = constrain(speed / 50, 1, 50) * ecThreshold;
  112. #else
  113. float threshold = get_error_correct_threshold();
  114. #endif
  115. //check error
  116. #if ENABLED(I2CPE_ERR_ROLLING_AVERAGE)
  117. double sum = 0, diffSum = 0;
  118. errIdx = (errIdx >= I2CPE_ERR_ARRAY_SIZE - 1) ? 0 : errIdx + 1;
  119. err[errIdx] = get_axis_error_steps(false);
  120. LOOP_L_N(i, I2CPE_ERR_ARRAY_SIZE) {
  121. sum += err[i];
  122. if (i) diffSum += abs(err[i-1] - err[i]);
  123. }
  124. long error = (long)(sum/(I2CPE_ERR_ARRAY_SIZE + 1)); //calculate average for error
  125. #else
  126. long error = get_axis_error_steps(false);
  127. #endif
  128. //SERIAL_ECHOPGM("Axis err*r steps: ");
  129. //SERIAL_ECHOLN(error);
  130. #if defined(I2CPE_ERR_THRESH_ABORT)
  131. if (labs(error) > I2CPE_ERR_THRESH_ABORT * planner.axis_steps_per_mm[encoderAxis]) {
  132. //kill("Significant Error");
  133. SERIAL_ECHOPGM("Axis error greater than set threshold, aborting!");
  134. SERIAL_ECHOLN(error);
  135. safe_delay(5000);
  136. }
  137. #endif
  138. #if ENABLED(I2CPE_ERR_ROLLING_AVERAGE)
  139. if (errIdx == 0) {
  140. // in order to correct for "error" but avoid correcting for noise and non skips
  141. // it must be > threshold and have a difference average of < 10 and be < 2000 steps
  142. if (labs(error) > threshold * planner.axis_steps_per_mm[encoderAxis] &&
  143. diffSum < 10 * (I2CPE_ERR_ARRAY_SIZE - 1) && labs(error) < 2000) { //Check for persistent error (skip)
  144. SERIAL_ECHO(axis_codes[encoderAxis]);
  145. SERIAL_ECHOPAIR(" diffSum: ", diffSum / (I2CPE_ERR_ARRAY_SIZE - 1));
  146. SERIAL_ECHOPAIR(" - err detected: ", error / planner.axis_steps_per_mm[encoderAxis]);
  147. SERIAL_ECHOLNPGM("mm; correcting!");
  148. thermalManager.babystepsTodo[encoderAxis] = -LROUND(error);
  149. }
  150. }
  151. #else
  152. if (labs(error) > threshold * planner.axis_steps_per_mm[encoderAxis]) {
  153. //SERIAL_ECHOLN(error);
  154. //SERIAL_ECHOLN(position);
  155. thermalManager.babystepsTodo[encoderAxis] = -LROUND(error/2);
  156. }
  157. #endif
  158. if (labs(error) > I2CPE_ERR_CNT_THRESH * planner.axis_steps_per_mm[encoderAxis]) {
  159. const millis_t ms = millis();
  160. if (ELAPSED(ms, nextErrorCountTime)) {
  161. SERIAL_ECHOPAIR("Large error on ", axis_codes[encoderAxis]);
  162. SERIAL_ECHOPAIR(" axis. error: ", (int)error);
  163. SERIAL_ECHOLNPAIR("; diffSum: ", diffSum);
  164. errorCount++;
  165. nextErrorCountTime = ms + I2CPE_ERR_CNT_DEBOUNCE_MS;
  166. }
  167. }
  168. }
  169. lastPositionTime = positionTime;
  170. }
  171. void I2CPositionEncoder::set_homed() {
  172. if (active) {
  173. reset(); // Reset module's offset to zero (so current position is homed / zero)
  174. delay(10);
  175. zeroOffset = get_raw_count();
  176. homed++;
  177. trusted++;
  178. #if defined(I2CPE_DEBUG)
  179. SERIAL_ECHO(axis_codes[encoderAxis]);
  180. SERIAL_ECHOPAIR(" axis encoder homed, offset of ", zeroOffset);
  181. SERIAL_ECHOLNPGM(" ticks.");
  182. #endif
  183. }
  184. }
  185. bool I2CPositionEncoder::passes_test(bool report) {
  186. if (H == I2CPE_MAG_SIG_GOOD) {
  187. if (report) {
  188. SERIAL_ECHO(axis_codes[encoderAxis]);
  189. SERIAL_ECHOLNPGM(" axis encoder passes test; field strength good.");
  190. }
  191. return true;
  192. } else if (H == I2CPE_MAG_SIG_MID) {
  193. if (report) {
  194. SERIAL_ECHOPAIR("Warning, ", axis_codes[encoderAxis]);
  195. SERIAL_ECHOLNPGM(" axis encoder passes test; field strength fair.");
  196. }
  197. return true;
  198. } else if (H == I2CPE_MAG_SIG_BAD) {
  199. if (report) {
  200. SERIAL_ECHOPAIR("Warning, ", axis_codes[encoderAxis]);
  201. SERIAL_ECHOLNPGM(" axis magnetic strip not detected!");
  202. }
  203. return false;
  204. }
  205. if (report) {
  206. SERIAL_ECHOPAIR("Warning, ", axis_codes[encoderAxis]);
  207. SERIAL_ECHOLNPGM(" axis encoder not detected!");
  208. }
  209. return false;
  210. }
  211. double I2CPositionEncoder::get_axis_error_mm(bool report) {
  212. double target, actual, error;
  213. target = stepper.get_axis_position_mm(encoderAxis);
  214. actual = mm_from_count(position);
  215. error = actual - target;
  216. if (labs(error) > 10000) error = 0; // ?
  217. if (report) {
  218. SERIAL_ECHO(axis_codes[encoderAxis]);
  219. SERIAL_ECHOPAIR(" axis target: ", target);
  220. SERIAL_ECHOPAIR(", actual: ", actual);
  221. SERIAL_ECHOLNPAIR(", error : ",error);
  222. }
  223. return error;
  224. }
  225. long I2CPositionEncoder::get_axis_error_steps(bool report) {
  226. if (!active) {
  227. if (report) {
  228. SERIAL_ECHO(axis_codes[encoderAxis]);
  229. SERIAL_ECHOLNPGM(" axis encoder not active!");
  230. }
  231. return 0;
  232. }
  233. float stepperTicksPerUnit;
  234. long encoderTicks = position, encoderCountInStepperTicksScaled;
  235. //long stepperTicks = stepper.position(encoderAxis);
  236. // With a rotary encoder we're concerned with ticks/rev; whereas with a linear we're concerned with ticks/mm
  237. stepperTicksPerUnit = (type == I2CPE_ENC_TYPE_ROTARY) ? stepperTicks : planner.axis_steps_per_mm[encoderAxis];
  238. //convert both 'ticks' into same units / base
  239. encoderCountInStepperTicksScaled = LROUND((stepperTicksPerUnit * encoderTicks) / encoderTicksPerUnit);
  240. long target = stepper.position(encoderAxis),
  241. error = (encoderCountInStepperTicksScaled - target);
  242. //suppress discontinuities (might be caused by bad I2C readings...?)
  243. bool suppressOutput = (labs(error - errorPrev) > 100);
  244. if (report) {
  245. SERIAL_ECHO(axis_codes[encoderAxis]);
  246. SERIAL_ECHOPAIR(" axis target: ", target);
  247. SERIAL_ECHOPAIR(", actual: ", encoderCountInStepperTicksScaled);
  248. SERIAL_ECHOLNPAIR(", error : ", error);
  249. if (suppressOutput) SERIAL_ECHOLNPGM("Discontinuity detected, suppressing error.");
  250. }
  251. errorPrev = error;
  252. return (suppressOutput ? 0 : error);
  253. }
  254. long I2CPositionEncoder::get_raw_count() {
  255. uint8_t index = 0;
  256. i2cLong encoderCount;
  257. encoderCount.val = 0x00;
  258. if (Wire.requestFrom((int)i2cAddress, 3) != 3) {
  259. //houston, we have a problem...
  260. H = I2CPE_MAG_SIG_NF;
  261. return 0;
  262. }
  263. while (Wire.available())
  264. encoderCount.bval[index++] = (uint8_t)Wire.read();
  265. //extract the magnetic strength
  266. H = (B00000011 & (encoderCount.bval[2] >> 6));
  267. //extract sign bit; sign = (encoderCount.bval[2] & B00100000);
  268. //set all upper bits to the sign value to overwrite H
  269. encoderCount.val = (encoderCount.bval[2] & B00100000) ? (encoderCount.val | 0xFFC00000) : (encoderCount.val & 0x003FFFFF);
  270. if (invert) encoderCount.val *= -1;
  271. return encoderCount.val;
  272. }
  273. bool I2CPositionEncoder::test_axis() {
  274. //only works on XYZ cartesian machines for the time being
  275. if (!(encoderAxis == X_AXIS || encoderAxis == Y_AXIS || encoderAxis == Z_AXIS)) return false;
  276. int feedrate;
  277. float startPosition, endPosition;
  278. float startCoord[NUM_AXIS] = {0}, endCoord[NUM_AXIS] = {0};
  279. startPosition = soft_endstop_min[encoderAxis] + 10;
  280. endPosition = soft_endstop_max[encoderAxis] - 10;
  281. feedrate = (int)MMM_TO_MMS((encoderAxis == Z_AXIS) ? HOMING_FEEDRATE_Z : HOMING_FEEDRATE_XY);
  282. ec = false;
  283. LOOP_NA(i) {
  284. startCoord[i] = stepper.get_axis_position_mm((AxisEnum)i);
  285. endCoord[i] = stepper.get_axis_position_mm((AxisEnum)i);
  286. }
  287. startCoord[encoderAxis] = startPosition;
  288. endCoord[encoderAxis] = endPosition;
  289. stepper.synchronize();
  290. planner.buffer_line(startCoord[X_AXIS],startCoord[Y_AXIS],startCoord[Z_AXIS],
  291. stepper.get_axis_position_mm(E_AXIS), feedrate, 0);
  292. stepper.synchronize();
  293. // if the module isn't currently trusted, wait until it is (or until it should be if things are working)
  294. if (!trusted) {
  295. long startWaitingTime = millis();
  296. while (!trusted && millis() - startWaitingTime < I2CPE_TIME_TRUSTED)
  297. safe_delay(500);
  298. }
  299. if (trusted) { // if trusted, commence test
  300. planner.buffer_line(endCoord[X_AXIS], endCoord[Y_AXIS], endCoord[Z_AXIS],
  301. stepper.get_axis_position_mm(E_AXIS), feedrate, 0);
  302. stepper.synchronize();
  303. }
  304. return trusted;
  305. }
  306. void I2CPositionEncoder::calibrate_steps_mm(int iter) {
  307. if (type != I2CPE_ENC_TYPE_LINEAR) {
  308. SERIAL_ECHOLNPGM("Steps per mm calibration is only available using linear encoders.");
  309. return;
  310. }
  311. if (!(encoderAxis == X_AXIS || encoderAxis == Y_AXIS || encoderAxis == Z_AXIS)) {
  312. SERIAL_ECHOLNPGM("Automatic steps / mm calibration not supported for this axis.");
  313. return;
  314. }
  315. float oldStepsMm, newStepsMm,
  316. startDistance, endDistance,
  317. travelDistance, travelledDistance, total = 0,
  318. startCoord[NUM_AXIS] = {0}, endCoord[NUM_AXIS] = {0};
  319. double feedrate;
  320. long startCount, stopCount;
  321. feedrate = MMM_TO_MMS((encoderAxis == Z_AXIS) ? HOMING_FEEDRATE_Z : HOMING_FEEDRATE_XY);
  322. bool oldec = ec;
  323. ec = false;
  324. startDistance = 20;
  325. endDistance = soft_endstop_max[encoderAxis] - 20;
  326. travelDistance = endDistance - startDistance;
  327. LOOP_NA(i) {
  328. startCoord[i] = stepper.get_axis_position_mm((AxisEnum)i);
  329. endCoord[i] = stepper.get_axis_position_mm((AxisEnum)i);
  330. }
  331. startCoord[encoderAxis] = startDistance;
  332. endCoord[encoderAxis] = endDistance;
  333. LOOP_L_N(i, iter) {
  334. stepper.synchronize();
  335. planner.buffer_line(startCoord[X_AXIS],startCoord[Y_AXIS],startCoord[Z_AXIS],
  336. stepper.get_axis_position_mm(E_AXIS), feedrate, 0);
  337. stepper.synchronize();
  338. delay(250);
  339. startCount = get_position();
  340. //do_blocking_move_to(endCoord[X_AXIS],endCoord[Y_AXIS],endCoord[Z_AXIS]);
  341. planner.buffer_line(endCoord[X_AXIS],endCoord[Y_AXIS],endCoord[Z_AXIS],
  342. stepper.get_axis_position_mm(E_AXIS), feedrate, 0);
  343. stepper.synchronize();
  344. //Read encoder distance
  345. delay(250);
  346. stopCount = get_position();
  347. travelledDistance = mm_from_count(abs(stopCount - startCount));
  348. SERIAL_ECHOPAIR("Attempted to travel: ", travelDistance);
  349. SERIAL_ECHOLNPGM("mm.");
  350. SERIAL_ECHOPAIR("Actually travelled: ", travelledDistance);
  351. SERIAL_ECHOLNPGM("mm.");
  352. //Calculate new axis steps per unit
  353. oldStepsMm = planner.axis_steps_per_mm[encoderAxis];
  354. newStepsMm = (oldStepsMm * travelDistance) / travelledDistance;
  355. SERIAL_ECHOLNPAIR("Old steps per mm: ", oldStepsMm);
  356. SERIAL_ECHOLNPAIR("New steps per mm: ", newStepsMm);
  357. //Save new value
  358. planner.axis_steps_per_mm[encoderAxis] = newStepsMm;
  359. if (iter > 1) {
  360. total += newStepsMm;
  361. // swap start and end points so next loop runs from current position
  362. float tempCoord = startCoord[encoderAxis];
  363. startCoord[encoderAxis] = endCoord[encoderAxis];
  364. endCoord[encoderAxis] = tempCoord;
  365. }
  366. }
  367. if (iter > 1) {
  368. total /= (float)iter;
  369. SERIAL_ECHOLNPAIR("Average steps per mm: ", total);
  370. }
  371. ec = oldec;
  372. SERIAL_ECHOLNPGM("Calculated steps per mm has been set. Please save to EEPROM (M500) if you wish to keep these values.");
  373. }
  374. void I2CPositionEncoder::reset() {
  375. Wire.beginTransmission(i2cAddress);
  376. Wire.write(I2CPE_RESET_COUNT);
  377. Wire.endTransmission();
  378. #if ENABLED(I2CPE_ERR_ROLLING_AVERAGE)
  379. ZERO(err);
  380. #endif
  381. }
  382. void I2CPositionEncodersMgr::init() {
  383. Wire.begin();
  384. #if I2CPE_ENCODER_CNT > 0
  385. uint8_t i = 0;
  386. encoders[i].init(I2CPE_ENC_1_ADDR, I2CPE_ENC_1_AXIS);
  387. #if defined(I2CPE_ENC_1_TYPE)
  388. encoders[i].set_type(I2CPE_ENC_1_TYPE);
  389. #endif
  390. #if defined(I2CPE_ENC_1_TICKS_UNIT)
  391. encoders[i].set_ticks_unit(I2CPE_ENC_1_TICKS_UNIT);
  392. #endif
  393. #if defined(I2CPE_ENC_1_TICKS_REV)
  394. encoders[i].set_stepper_ticks(I2CPE_ENC_1_TICKS_REV);
  395. #endif
  396. #if defined(I2CPE_ENC_1_INVERT)
  397. encoders[i].set_inverted(I2CPE_ENC_1_INVERT);
  398. #endif
  399. #if defined(I2CPE_ENC_1_EC_METHOD)
  400. encoders[i].set_ec_method(I2CPE_ENC_1_EC_METHOD);
  401. #endif
  402. #if defined(I2CPE_ENC_1_EC_THRESH)
  403. encoders[i].set_ec_threshold(I2CPE_ENC_1_EC_THRESH);
  404. #endif
  405. encoders[i].set_active(encoders[i].passes_test(true));
  406. #if (I2CPE_ENC_1_AXIS == E_AXIS)
  407. encoders[i].set_homed();
  408. #endif
  409. #endif
  410. #if I2CPE_ENCODER_CNT > 1
  411. i++;
  412. encoders[i].init(I2CPE_ENC_2_ADDR, I2CPE_ENC_2_AXIS);
  413. #if defined(I2CPE_ENC_2_TYPE)
  414. encoders[i].set_type(I2CPE_ENC_2_TYPE);
  415. #endif
  416. #if defined(I2CPE_ENC_2_TICKS_UNIT)
  417. encoders[i].set_ticks_unit(I2CPE_ENC_2_TICKS_UNIT);
  418. #endif
  419. #if defined(I2CPE_ENC_2_TICKS_REV)
  420. encoders[i].set_stepper_ticks(I2CPE_ENC_2_TICKS_REV);
  421. #endif
  422. #if defined(I2CPE_ENC_2_INVERT)
  423. encoders[i].set_inverted(I2CPE_ENC_2_INVERT);
  424. #endif
  425. #if defined(I2CPE_ENC_2_EC_METHOD)
  426. encoders[i].set_ec_method(I2CPE_ENC_2_EC_METHOD);
  427. #endif
  428. #if defined(I2CPE_ENC_2_EC_THRESH)
  429. encoders[i].set_ec_threshold(I2CPE_ENC_2_EC_THRESH);
  430. #endif
  431. encoders[i].set_active(encoders[i].passes_test(true));
  432. #if (I2CPE_ENC_2_AXIS == E_AXIS)
  433. encoders[i].set_homed();
  434. #endif
  435. #endif
  436. #if I2CPE_ENCODER_CNT > 2
  437. i++;
  438. encoders[i].init(I2CPE_ENC_3_ADDR, I2CPE_ENC_3_AXIS);
  439. #if defined(I2CPE_ENC_3_TYPE)
  440. encoders[i].set_type(I2CPE_ENC_3_TYPE);
  441. #endif
  442. #if defined(I2CPE_ENC_3_TICKS_UNIT)
  443. encoders[i].set_ticks_unit(I2CPE_ENC_3_TICKS_UNIT);
  444. #endif
  445. #if defined(I2CPE_ENC_3_TICKS_REV)
  446. encoders[i].set_stepper_ticks(I2CPE_ENC_3_TICKS_REV);
  447. #endif
  448. #if defined(I2CPE_ENC_3_INVERT)
  449. encoders[i].set_inverted(I2CPE_ENC_3_INVERT);
  450. #endif
  451. #if defined(I2CPE_ENC_3_EC_METHOD)
  452. encoders[i].set_ec_method(I2CPE_ENC_3_EC_METHOD);
  453. #endif
  454. #if defined(I2CPE_ENC_3_EC_THRESH)
  455. encoders[i].set_ec_threshold(I2CPE_ENC_3_EC_THRESH);
  456. #endif
  457. encoders[i].set_active(encoders[i].passes_test(true));
  458. #if (I2CPE_ENC_3_AXIS == E_AXIS)
  459. encoders[i].set_homed();
  460. #endif
  461. #endif
  462. #if I2CPE_ENCODER_CNT > 3
  463. i++;
  464. encoders[i].init(I2CPE_ENC_4_ADDR, I2CPE_ENC_4_AXIS);
  465. #if defined(I2CPE_ENC_4_TYPE)
  466. encoders[i].set_type(I2CPE_ENC_4_TYPE);
  467. #endif
  468. #if defined(I2CPE_ENC_4_TICKS_UNIT)
  469. encoders[i].set_ticks_unit(I2CPE_ENC_4_TICKS_UNIT);
  470. #endif
  471. #if defined(I2CPE_ENC_4_TICKS_REV)
  472. encoders[i].set_stepper_ticks(I2CPE_ENC_4_TICKS_REV);
  473. #endif
  474. #if defined(I2CPE_ENC_4_INVERT)
  475. encoders[i].set_inverted(I2CPE_ENC_4_INVERT);
  476. #endif
  477. #if defined(I2CPE_ENC_4_EC_METHOD)
  478. encoders[i].set_ec_method(I2CPE_ENC_4_EC_METHOD);
  479. #endif
  480. #if defined(I2CPE_ENC_4_EC_THRESH)
  481. encoders[i].set_ec_threshold(I2CPE_ENC_4_EC_THRESH);
  482. #endif
  483. encoders[i].set_active(encoders[i].passes_test(true));
  484. #if (I2CPE_ENC_4_AXIS == E_AXIS)
  485. encoders[i].set_homed();
  486. #endif
  487. #endif
  488. #if I2CPE_ENCODER_CNT > 4
  489. i++;
  490. encoders[i].init(I2CPE_ENC_5_ADDR, I2CPE_ENC_5_AXIS);
  491. #if defined(I2CPE_ENC_5_TYPE)
  492. encoders[i].set_type(I2CPE_ENC_5_TYPE);
  493. #endif
  494. #if defined(I2CPE_ENC_5_TICKS_UNIT)
  495. encoders[i].set_ticks_unit(I2CPE_ENC_5_TICKS_UNIT);
  496. #endif
  497. #if defined(I2CPE_ENC_5_TICKS_REV)
  498. encoders[i].set_stepper_ticks(I2CPE_ENC_5_TICKS_REV);
  499. #endif
  500. #if defined(I2CPE_ENC_5_INVERT)
  501. encoders[i].set_inverted(I2CPE_ENC_5_INVERT);
  502. #endif
  503. #if defined(I2CPE_ENC_5_EC_METHOD)
  504. encoders[i].set_ec_method(I2CPE_ENC_5_EC_METHOD);
  505. #endif
  506. #if defined(I2CPE_ENC_5_EC_THRESH)
  507. encoders[i].set_ec_threshold(I2CPE_ENC_5_EC_THRESH);
  508. #endif
  509. encoders[i].set_active(encoders[i].passes_test(true));
  510. #if (I2CPE_ENC_5_AXIS == E_AXIS)
  511. encoders[i].set_homed();
  512. #endif
  513. #endif
  514. }
  515. void I2CPositionEncodersMgr::report_position(uint8_t idx, bool units, bool noOffset) {
  516. CHECK_IDX
  517. if (units) {
  518. SERIAL_ECHOLN(noOffset ? encoders[idx].mm_from_count(encoders[idx].get_raw_count()) : encoders[idx].get_position_mm());
  519. } else {
  520. if (noOffset) {
  521. long raw_count = encoders[idx].get_raw_count();
  522. SERIAL_ECHO(axis_codes[encoders[idx].get_axis()]);
  523. SERIAL_ECHOPGM(" ");
  524. for (uint8_t j = 31; j > 0; j--)
  525. SERIAL_ECHO((bool)(0x00000001 & (raw_count >> j)));
  526. SERIAL_ECHO((bool)(0x00000001 & (raw_count)));
  527. SERIAL_ECHOLNPAIR(" ", raw_count);
  528. } else
  529. SERIAL_ECHOLN(encoders[idx].get_position());
  530. }
  531. }
  532. void I2CPositionEncodersMgr::change_module_address(uint8_t oldaddr, uint8_t newaddr) {
  533. // First check 'new' address is not in use
  534. Wire.beginTransmission(newaddr);
  535. if (!Wire.endTransmission()) {
  536. SERIAL_ECHOPAIR("?There is already a device with that address on the I2C bus! (", newaddr);
  537. SERIAL_ECHOLNPGM(")");
  538. return;
  539. }
  540. // Now check that we can find the module on the oldaddr address
  541. Wire.beginTransmission(oldaddr);
  542. if (Wire.endTransmission()) {
  543. SERIAL_ECHOPAIR("?No module detected at this address! (", oldaddr);
  544. SERIAL_ECHOLNPGM(")");
  545. return;
  546. }
  547. SERIAL_ECHOPAIR("Module found at ", oldaddr);
  548. SERIAL_ECHOLNPAIR(", changing address to ", newaddr);
  549. // Change the modules address
  550. Wire.beginTransmission(oldaddr);
  551. Wire.write(I2CPE_SET_ADDR);
  552. Wire.write(newaddr);
  553. Wire.endTransmission();
  554. SERIAL_ECHOLNPGM("Address changed, resetting and waiting for confirmation..");
  555. // Wait for the module to reset (can probably be improved by polling address with a timeout).
  556. safe_delay(I2CPE_REBOOT_TIME);
  557. // Look for the module at the new address.
  558. Wire.beginTransmission(newaddr);
  559. if (Wire.endTransmission()) {
  560. SERIAL_ECHOLNPGM("Address change failed! Check encoder module.");
  561. return;
  562. }
  563. SERIAL_ECHOLNPGM("Address change successful!");
  564. // Now, if this module is configured, find which encoder instance it's supposed to correspond to
  565. // and enable it (it will likely have failed initialisation on power-up, before the address change).
  566. int8_t idx = idx_from_addr(newaddr);
  567. if (idx >= 0 && !encoders[idx].get_active()) {
  568. SERIAL_ECHO(axis_codes[encoders[idx].get_axis()]);
  569. SERIAL_ECHOLNPGM(" axis encoder was not detected on printer startup. Trying again.");
  570. encoders[idx].set_active(encoders[idx].passes_test(true));
  571. }
  572. }
  573. void I2CPositionEncodersMgr::report_module_firmware(uint8_t address) {
  574. // First check there is a module
  575. Wire.beginTransmission(address);
  576. if (Wire.endTransmission()) {
  577. SERIAL_ECHOPAIR("?No module detected at this address! (", address);
  578. SERIAL_ECHOLNPGM(")");
  579. return;
  580. }
  581. SERIAL_ECHOPAIR("Requesting version info from module at address ", address);
  582. SERIAL_ECHOPGM(":\n");
  583. Wire.beginTransmission(address);
  584. Wire.write(I2CPE_SET_REPORT_MODE);
  585. Wire.write(I2CPE_REPORT_VERSION);
  586. Wire.endTransmission();
  587. // Read value
  588. if (Wire.requestFrom((int)address, 32)) {
  589. char c;
  590. while (Wire.available() > 0 && (c = (char)Wire.read()) > 0)
  591. SERIAL_ECHO(c);
  592. SERIAL_EOL();
  593. }
  594. // Set module back to normal (distance) mode
  595. Wire.beginTransmission((int)address);
  596. Wire.write(I2CPE_SET_REPORT_MODE);
  597. Wire.write(I2CPE_REPORT_DISTANCE);
  598. Wire.endTransmission();
  599. }
  600. int8_t I2CPositionEncodersMgr::parse() {
  601. I2CPE_addr = 0;
  602. if (parser.seen('A')) {
  603. if (!parser.has_value()) {
  604. SERIAL_PROTOCOLLNPGM("?A seen, but no address specified! [30-200]");
  605. return I2CPE_PARSE_ERR;
  606. };
  607. I2CPE_addr = parser.value_byte();
  608. if (!WITHIN(I2CPE_addr, 30, 200)) { // reserve the first 30 and last 55
  609. SERIAL_PROTOCOLLNPGM("?Address out of range. [30-200]");
  610. return I2CPE_PARSE_ERR;
  611. }
  612. I2CPE_idx = idx_from_addr(I2CPE_addr);
  613. if (!WITHIN(I2CPE_idx, 0, I2CPE_ENCODER_CNT - 1)) {
  614. SERIAL_PROTOCOLLNPGM("?No device with this address!");
  615. return I2CPE_PARSE_ERR;
  616. }
  617. } else if (parser.seenval('I')) {
  618. if (!parser.has_value()) {
  619. SERIAL_PROTOCOLLNPAIR("?I seen, but no index specified! [0-", I2CPE_ENCODER_CNT - 1);
  620. SERIAL_ECHOLNPGM("]");
  621. return I2CPE_PARSE_ERR;
  622. };
  623. I2CPE_idx = parser.value_byte();
  624. if (!WITHIN(I2CPE_idx, 0, I2CPE_ENCODER_CNT - 1)) {
  625. SERIAL_PROTOCOLLNPAIR("?Index out of range. [0-", I2CPE_ENCODER_CNT - 1);
  626. SERIAL_ECHOLNPGM("]");
  627. return I2CPE_PARSE_ERR;
  628. }
  629. I2CPE_addr = encoders[I2CPE_idx].get_address();
  630. } else {
  631. I2CPE_idx = -1;
  632. }
  633. I2CPE_anyaxis = parser.seen_axis();
  634. return I2CPE_PARSE_OK;
  635. };
  636. /**
  637. * M860: Report the position(s) of position encoder module(s).
  638. *
  639. * A<addr> Module I2C address. [30, 200].
  640. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1]
  641. * O Include homed zero-offset in returned position.
  642. * U Units in mm or raw step count.
  643. *
  644. * If A or I not specified:
  645. * X Report on X axis encoder, if present.
  646. * Y Report on Y axis encoder, if present.
  647. * Z Report on Z axis encoder, if present.
  648. * E Report on E axis encoder, if present.
  649. *
  650. */
  651. void I2CPositionEncodersMgr::M860() {
  652. if (parse()) return;
  653. bool hasU = parser.seen('U'), hasO = parser.seen('O');
  654. if (I2CPE_idx < 0) {
  655. int8_t idx;
  656. LOOP_XYZE(i) {
  657. if ((!I2CPE_anyaxis || parser.seen(axis_codes[i])) && ((idx = idx_from_axis(AxisEnum(i))) >= 0))
  658. report_position((uint8_t)idx, hasU, hasO);
  659. }
  660. } else report_position((uint8_t)I2CPE_idx, hasU, hasO);
  661. }
  662. /**
  663. * M861: Report the status of position encoder modules.
  664. *
  665. * A<addr> Module I2C address. [30, 200].
  666. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1]
  667. *
  668. * If A or I not specified:
  669. * X Report on X axis encoder, if present.
  670. * Y Report on Y axis encoder, if present.
  671. * Z Report on Z axis encoder, if present.
  672. * E Report on E axis encoder, if present.
  673. *
  674. */
  675. void I2CPositionEncodersMgr::M861() {
  676. if (parse()) return;
  677. if (I2CPE_idx < 0) {
  678. int8_t idx;
  679. LOOP_XYZE(i) {
  680. if ((!I2CPE_anyaxis || parser.seen(axis_codes[i])) && ((idx = idx_from_axis(AxisEnum(i))) >= 0))
  681. report_status((uint8_t)idx);
  682. }
  683. } else report_status((uint8_t)I2CPE_idx);
  684. }
  685. /**
  686. * M862: Perform an axis continuity test for position encoder
  687. * modules.
  688. *
  689. * A<addr> Module I2C address. [30, 200].
  690. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1]
  691. *
  692. * If A or I not specified:
  693. * X Report on X axis encoder, if present.
  694. * Y Report on Y axis encoder, if present.
  695. * Z Report on Z axis encoder, if present.
  696. * E Report on E axis encoder, if present.
  697. *
  698. */
  699. void I2CPositionEncodersMgr::M862() {
  700. if (parse()) return;
  701. if (I2CPE_idx < 0) {
  702. int8_t idx;
  703. LOOP_XYZE(i) {
  704. if ((!I2CPE_anyaxis || parser.seen(axis_codes[i])) && ((idx = idx_from_axis(AxisEnum(i))) >= 0))
  705. test_axis((uint8_t)idx);
  706. }
  707. } else test_axis((uint8_t)I2CPE_idx);
  708. }
  709. /**
  710. * M863: Perform steps-per-mm calibration for
  711. * position encoder modules.
  712. *
  713. * A<addr> Module I2C address. [30, 200].
  714. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1]
  715. * P Number of rePeats/iterations.
  716. *
  717. * If A or I not specified:
  718. * X Report on X axis encoder, if present.
  719. * Y Report on Y axis encoder, if present.
  720. * Z Report on Z axis encoder, if present.
  721. * E Report on E axis encoder, if present.
  722. *
  723. */
  724. void I2CPositionEncodersMgr::M863() {
  725. if (parse()) return;
  726. int iterations = parser.seenval('P') ? constrain(parser.value_byte(), 1, 10) : 1;
  727. if (I2CPE_idx < 0) {
  728. int8_t idx;
  729. LOOP_XYZE(i) {
  730. if ((!I2CPE_anyaxis || parser.seen(axis_codes[i])) && ((idx = idx_from_axis(AxisEnum(i))) >= 0))
  731. calibrate_steps_mm((uint8_t)idx, iterations);
  732. }
  733. } else calibrate_steps_mm((uint8_t)I2CPE_idx, iterations);
  734. }
  735. /**
  736. * M864: Change position encoder module I2C address.
  737. *
  738. * A<addr> Module current/old I2C address. If not present,
  739. * assumes default address (030). [30, 200].
  740. * N<addr> Module new I2C address. [30, 200].
  741. *
  742. * If N not specified:
  743. * X Use I2CPE_PRESET_ADDR_X (030).
  744. * Y Use I2CPE_PRESET_ADDR_Y (031).
  745. * Z Use I2CPE_PRESET_ADDR_Z (032).
  746. * E Use I2CPE_PRESET_ADDR_E (033).
  747. */
  748. void I2CPositionEncodersMgr::M864() {
  749. uint8_t newAddress;
  750. if (parse()) return;
  751. if (!I2CPE_addr) I2CPE_addr = I2CPE_PRESET_ADDR_X;
  752. if (parser.seen('N')) {
  753. if (!parser.has_value()) {
  754. SERIAL_PROTOCOLLNPGM("?N seen, but no address specified! [30-200]");
  755. return;
  756. };
  757. newAddress = parser.value_byte();
  758. if (!WITHIN(newAddress, 30, 200)) {
  759. SERIAL_PROTOCOLLNPGM("?New address out of range. [30-200]");
  760. return;
  761. }
  762. } else if (!I2CPE_anyaxis) {
  763. SERIAL_PROTOCOLLNPGM("?You must specify N or [XYZE].");
  764. return;
  765. } else {
  766. if (parser.seen('X')) newAddress = I2CPE_PRESET_ADDR_X;
  767. else if (parser.seen('Y')) newAddress = I2CPE_PRESET_ADDR_Y;
  768. else if (parser.seen('Z')) newAddress = I2CPE_PRESET_ADDR_Z;
  769. else if (parser.seen('E')) newAddress = I2CPE_PRESET_ADDR_E;
  770. else return;
  771. }
  772. SERIAL_ECHOPAIR("Changing module at address ", I2CPE_addr);
  773. SERIAL_ECHOLNPAIR(" to address ", newAddress);
  774. change_module_address(I2CPE_addr, newAddress);
  775. }
  776. /**
  777. * M865: Check position encoder module firmware version.
  778. *
  779. * A<addr> Module I2C address. [30, 200].
  780. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1].
  781. *
  782. * If A or I not specified:
  783. * X Check X axis encoder, if present.
  784. * Y Check Y axis encoder, if present.
  785. * Z Check Z axis encoder, if present.
  786. * E Check E axis encoder, if present.
  787. */
  788. void I2CPositionEncodersMgr::M865() {
  789. if (parse()) return;
  790. if (!I2CPE_addr) {
  791. int8_t idx;
  792. LOOP_XYZE(i) {
  793. if ((!I2CPE_anyaxis || parser.seen(axis_codes[i])) && ((idx = idx_from_axis(AxisEnum(i))) >= 0))
  794. report_module_firmware(encoders[idx].get_address());
  795. }
  796. } else report_module_firmware(I2CPE_addr);
  797. }
  798. /**
  799. * M866: Report or reset position encoder module error
  800. * count.
  801. *
  802. * A<addr> Module I2C address. [30, 200].
  803. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1].
  804. * R Reset error counter.
  805. *
  806. * If A or I not specified:
  807. * X Act on X axis encoder, if present.
  808. * Y Act on Y axis encoder, if present.
  809. * Z Act on Z axis encoder, if present.
  810. * E Act on E axis encoder, if present.
  811. */
  812. void I2CPositionEncodersMgr::M866() {
  813. if (parse()) return;
  814. bool hasR = parser.seen('R');
  815. if (I2CPE_idx < 0) {
  816. int8_t idx;
  817. LOOP_XYZE(i) {
  818. if ((!I2CPE_anyaxis || parser.seen(axis_codes[i])) && ((idx = idx_from_axis(AxisEnum(i))) >= 0)) {
  819. if (hasR) reset_error_count((uint8_t)idx, AxisEnum(i));
  820. else report_error_count((uint8_t)idx, AxisEnum(i));
  821. }
  822. }
  823. } else {
  824. if (hasR) reset_error_count((uint8_t)I2CPE_idx, encoders[I2CPE_idx].get_axis());
  825. else report_error_count((uint8_t)I2CPE_idx, encoders[I2CPE_idx].get_axis());
  826. }
  827. }
  828. /**
  829. * M867: Enable/disable or toggle error correction for position encoder modules.
  830. *
  831. * A<addr> Module I2C address. [30, 200].
  832. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1].
  833. * S<1|0> Enable/disable error correction. 1 enables, 0 disables. If not
  834. * supplied, toggle.
  835. *
  836. * If A or I not specified:
  837. * X Act on X axis encoder, if present.
  838. * Y Act on Y axis encoder, if present.
  839. * Z Act on Z axis encoder, if present.
  840. * E Act on E axis encoder, if present.
  841. */
  842. void I2CPositionEncodersMgr::M867() {
  843. if (parse()) return;
  844. int8_t onoff = parser.seenval('S') ? parser.value_int() : -1;
  845. if (I2CPE_idx < 0) {
  846. int8_t idx;
  847. LOOP_XYZE(i) {
  848. if ((!I2CPE_anyaxis || parser.seen(axis_codes[i])) && ((idx = idx_from_axis(AxisEnum(i))) >= 0)) {
  849. if (onoff == -1) enable_ec((uint8_t)idx, !encoders[idx].get_ec_enabled(), AxisEnum(i));
  850. else enable_ec((uint8_t)idx, (bool)onoff, AxisEnum(i));
  851. }
  852. }
  853. } else {
  854. if (onoff == -1) enable_ec((uint8_t)I2CPE_idx, !encoders[I2CPE_idx].get_ec_enabled(), encoders[I2CPE_idx].get_axis());
  855. else enable_ec((uint8_t)I2CPE_idx, (bool)onoff, encoders[I2CPE_idx].get_axis());
  856. }
  857. }
  858. /**
  859. * M868: Report or set position encoder module error correction
  860. * threshold.
  861. *
  862. * A<addr> Module I2C address. [30, 200].
  863. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1].
  864. * T New error correction threshold.
  865. *
  866. * If A not specified:
  867. * X Act on X axis encoder, if present.
  868. * Y Act on Y axis encoder, if present.
  869. * Z Act on Z axis encoder, if present.
  870. * E Act on E axis encoder, if present.
  871. */
  872. void I2CPositionEncodersMgr::M868() {
  873. if (parse()) return;
  874. float newThreshold = parser.seenval('T') ? parser.value_float() : -9999;
  875. if (I2CPE_idx < 0) {
  876. int8_t idx;
  877. LOOP_XYZE(i) {
  878. if ((!I2CPE_anyaxis || parser.seen(axis_codes[i])) && ((idx = idx_from_axis(AxisEnum(i))) >= 0)) {
  879. if (newThreshold != -9999) set_ec_threshold((uint8_t)idx, newThreshold, encoders[idx].get_axis());
  880. else get_ec_threshold((uint8_t)idx, encoders[idx].get_axis());
  881. }
  882. }
  883. } else {
  884. if (newThreshold != -9999) set_ec_threshold((uint8_t)I2CPE_idx, newThreshold, encoders[I2CPE_idx].get_axis());
  885. else get_ec_threshold((uint8_t)I2CPE_idx, encoders[I2CPE_idx].get_axis());
  886. }
  887. }
  888. /**
  889. * M869: Report position encoder module error.
  890. *
  891. * A<addr> Module I2C address. [30, 200].
  892. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1].
  893. *
  894. * If A not specified:
  895. * X Act on X axis encoder, if present.
  896. * Y Act on Y axis encoder, if present.
  897. * Z Act on Z axis encoder, if present.
  898. * E Act on E axis encoder, if present.
  899. */
  900. void I2CPositionEncodersMgr::M869() {
  901. if (parse()) return;
  902. if (I2CPE_idx < 0) {
  903. int8_t idx;
  904. LOOP_XYZE(i) {
  905. if ((!I2CPE_anyaxis || parser.seen(axis_codes[i])) && ((idx = idx_from_axis(AxisEnum(i))) >= 0))
  906. report_error((uint8_t)idx);
  907. }
  908. } else report_error((uint8_t)I2CPE_idx);
  909. }
  910. #endif