Filament_sensor.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. #include <avr/pgmspace.h>
  2. #include <stdio.h>
  3. #include <util/atomic.h>
  4. #include "Filament_sensor.h"
  5. #include "Timer.h"
  6. #include "cardreader.h"
  7. #include "eeprom.h"
  8. #include "menu.h"
  9. #include "temperature.h"
  10. #include "ultralcd.h"
  11. #ifdef FILAMENT_SENSOR
  12. FSensorBlockRunout::FSensorBlockRunout() {
  13. fsensor.setRunoutEnabled(false); //suppress filament runouts while loading filament.
  14. fsensor.setAutoLoadEnabled(false); //suppress filament autoloads while loading filament.
  15. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  16. fsensor.setJamDetectionEnabled(false); //suppress filament jam detection while loading filament.
  17. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  18. // SERIAL_ECHOLNPGM("FSBlockRunout");
  19. }
  20. FSensorBlockRunout::~FSensorBlockRunout() {
  21. fsensor.settings_init(); // restore filament runout state.
  22. // SERIAL_ECHOLNPGM("FSUnBlockRunout");
  23. }
  24. # if FILAMENT_SENSOR_TYPE == FSENSOR_IR
  25. IR_sensor fsensor;
  26. # elif FILAMENT_SENSOR_TYPE == FSENSOR_IR_ANALOG
  27. IR_sensor_analog fsensor;
  28. # elif FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125
  29. PAT9125_sensor fsensor;
  30. # endif
  31. #else // FILAMENT_SENSOR
  32. FSensorBlockRunout::FSensorBlockRunout() { }
  33. FSensorBlockRunout::~FSensorBlockRunout() { }
  34. #endif // FILAMENT_SENSOR
  35. void Filament_sensor::setEnabled(bool enabled) {
  36. eeprom_update_byte((uint8_t *)EEPROM_FSENSOR, enabled);
  37. if (enabled) {
  38. init();
  39. } else {
  40. deinit();
  41. }
  42. }
  43. void Filament_sensor::setAutoLoadEnabled(bool state, bool updateEEPROM) {
  44. autoLoadEnabled = state;
  45. if (updateEEPROM) {
  46. eeprom_update_byte((uint8_t *)EEPROM_FSENS_AUTOLOAD_ENABLED, state);
  47. }
  48. }
  49. void Filament_sensor::setRunoutEnabled(bool state, bool updateEEPROM) {
  50. runoutEnabled = state;
  51. if (updateEEPROM) {
  52. eeprom_update_byte((uint8_t *)EEPROM_FSENS_RUNOUT_ENABLED, state);
  53. }
  54. }
  55. void Filament_sensor::setActionOnError(SensorActionOnError state, bool updateEEPROM) {
  56. sensorActionOnError = state;
  57. if (updateEEPROM) {
  58. eeprom_update_byte((uint8_t *)EEPROM_FSENSOR_ACTION_NA, (uint8_t)state);
  59. }
  60. }
  61. void Filament_sensor::settings_init_common() {
  62. bool enabled = eeprom_read_byte((uint8_t *)EEPROM_FSENSOR);
  63. if ((state != State::disabled) != enabled) {
  64. state = enabled ? State::initializing : State::disabled;
  65. }
  66. autoLoadEnabled = eeprom_read_byte((uint8_t *)EEPROM_FSENS_AUTOLOAD_ENABLED);
  67. runoutEnabled = eeprom_read_byte((uint8_t *)EEPROM_FSENS_RUNOUT_ENABLED);
  68. sensorActionOnError = (SensorActionOnError)eeprom_read_byte((uint8_t *)EEPROM_FSENSOR_ACTION_NA);
  69. if (sensorActionOnError == SensorActionOnError::_Undef) {
  70. sensorActionOnError = SensorActionOnError::_Continue;
  71. }
  72. }
  73. bool Filament_sensor::checkFilamentEvents() {
  74. if (state != State::ready)
  75. return false;
  76. if (eventBlankingTimer.running() && !eventBlankingTimer.expired(100)) { // event blanking for 100ms
  77. return false;
  78. }
  79. bool newFilamentPresent = getFilamentPresent();
  80. if (oldFilamentPresent != newFilamentPresent) {
  81. oldFilamentPresent = newFilamentPresent;
  82. eventBlankingTimer.start();
  83. if (newFilamentPresent) { // filament insertion
  84. puts_P(PSTR("filament inserted"));
  85. triggerFilamentInserted();
  86. postponedLoadEvent = true;
  87. } else { // filament removal
  88. puts_P(PSTR("filament removed"));
  89. triggerFilamentRemoved();
  90. }
  91. return true;
  92. }
  93. return false;
  94. }
  95. void Filament_sensor::triggerFilamentInserted() {
  96. if (autoLoadEnabled
  97. && (eFilamentAction == FilamentAction::None)
  98. && (! MMU2::mmu2.Enabled() ) // quick and dirty hack to prevent spurious runouts while the MMU is in charge
  99. && !(
  100. moves_planned()
  101. || IS_SD_PRINTING
  102. || usb_timer.running()
  103. || (lcd_commands_type == LcdCommands::Layer1Cal)
  104. || eeprom_read_byte((uint8_t *)EEPROM_WIZARD_ACTIVE)
  105. )
  106. ) {
  107. filAutoLoad();
  108. }
  109. }
  110. void Filament_sensor::triggerFilamentRemoved() {
  111. // SERIAL_ECHOLNPGM("triggerFilamentRemoved");
  112. if (runoutEnabled
  113. && (! MMU2::mmu2.Enabled() ) // quick and dirty hack to prevent spurious runouts just before the toolchange
  114. && (eFilamentAction == FilamentAction::None)
  115. && !saved_printing
  116. && (
  117. moves_planned()
  118. || IS_SD_PRINTING
  119. || usb_timer.running()
  120. || (lcd_commands_type == LcdCommands::Layer1Cal)
  121. || eeprom_read_byte((uint8_t *)EEPROM_WIZARD_ACTIVE)
  122. )
  123. ){
  124. // SERIAL_ECHOPGM("runoutEnabled="); SERIAL_ECHOLN((int)runoutEnabled);
  125. // SERIAL_ECHOPGM("eFilamentAction="); SERIAL_ECHOLN((int)eFilamentAction);
  126. // SERIAL_ECHOPGM("saved_printing="); SERIAL_ECHOLN((int)saved_printing);
  127. filRunout();
  128. }
  129. }
  130. void Filament_sensor::filAutoLoad() {
  131. eFilamentAction = FilamentAction::AutoLoad;
  132. if (target_temperature[0] >= EXTRUDE_MINTEMP) {
  133. bFilamentPreheatState = true;
  134. menu_submenu(mFilamentItemForce);
  135. } else {
  136. menu_submenu(lcd_generic_preheat_menu);
  137. lcd_timeoutToStatus.start();
  138. }
  139. }
  140. void Filament_sensor::filRunout() {
  141. // SERIAL_ECHOLNPGM("filRunout");
  142. runoutEnabled = false;
  143. autoLoadEnabled = false;
  144. stop_and_save_print_to_ram(0, 0);
  145. restore_print_from_ram_and_continue(0);
  146. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, eeprom_read_byte((uint8_t *)EEPROM_FERROR_COUNT) + 1);
  147. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, eeprom_read_word((uint16_t *)EEPROM_FERROR_COUNT_TOT) + 1);
  148. enquecommand_front_P((PSTR("M600")));
  149. }
  150. void Filament_sensor::triggerError() {
  151. state = State::error;
  152. /// some message, idk
  153. ; //
  154. }
  155. #if (FILAMENT_SENSOR_TYPE == FSENSOR_IR) || (FILAMENT_SENSOR_TYPE == FSENSOR_IR_ANALOG)
  156. void IR_sensor::init() {
  157. if (state == State::error) {
  158. deinit(); // deinit first if there was an error.
  159. }
  160. puts_P(PSTR("fsensor::init()"));
  161. SET_INPUT(IR_SENSOR_PIN); // input mode
  162. WRITE(IR_SENSOR_PIN, 1); // pullup
  163. settings_init(); // also sets the state to State::initializing
  164. }
  165. void IR_sensor::deinit() {
  166. puts_P(PSTR("fsensor::deinit()"));
  167. SET_INPUT(IR_SENSOR_PIN); // input mode
  168. WRITE(IR_SENSOR_PIN, 0); // no pullup
  169. state = State::disabled;
  170. }
  171. bool IR_sensor::update() {
  172. switch (state) {
  173. case State::initializing:
  174. state = State::ready; // the IR sensor gets ready instantly as it's just a gpio read operation.
  175. oldFilamentPresent =
  176. getFilamentPresent(); // initialize the current filament state so that we don't create a switching event right after the sensor is ready.
  177. // fallthru
  178. case State::ready: {
  179. postponedLoadEvent = false;
  180. bool event = checkFilamentEvents();
  181. ; //
  182. return event;
  183. } break;
  184. case State::disabled:
  185. case State::error:
  186. default:
  187. return false;
  188. }
  189. return false;
  190. }
  191. bool IR_sensor::getFilamentPresent() { return !READ(IR_SENSOR_PIN); }
  192. #ifdef FSENSOR_PROBING
  193. bool IR_sensor::probeOtherType() { return pat9125_probe(); }
  194. #endif
  195. void IR_sensor::settings_init() { Filament_sensor::settings_init_common(); }
  196. #if (FILAMENT_SENSOR_TYPE == FSENSOR_IR_ANALOG)
  197. void IR_sensor_analog::init() {
  198. IR_sensor::init();
  199. settings_init();
  200. }
  201. void IR_sensor_analog::deinit() { IR_sensor::deinit(); }
  202. bool IR_sensor_analog::update() {
  203. bool event = IR_sensor::update();
  204. if (state == State::ready) {
  205. if (voltReady) {
  206. voltReady = false;
  207. uint16_t volt = getVoltRaw();
  208. // printf_P(PSTR("newVoltRaw:%u\n"), volt / OVERSAMPLENR);
  209. // detect min-max, some long term sliding window for filtration may be added
  210. // avoiding floating point operations, thus computing in raw
  211. if (volt > maxVolt) {
  212. maxVolt = volt;
  213. } else if (volt < minVolt) {
  214. minVolt = volt;
  215. }
  216. //! The trouble is, I can hold the filament in the hole in such a way, that it creates the exact voltage
  217. //! to be detected as the new fsensor
  218. //! We can either fake it by extending the detection window to a looooong time
  219. //! or do some other countermeasures
  220. //! what we want to detect:
  221. //! if minvolt gets below ~0.3V, it means there is an old fsensor
  222. //! if maxvolt gets above 4.6V, it means we either have an old fsensor or broken cables/fsensor
  223. //! So I'm waiting for a situation, when minVolt gets to range <0, 1.5> and maxVolt gets into range <3.0, 5>
  224. //! If and only if minVolt is in range <0.3, 1.5> and maxVolt is in range <3.0, 4.6>, I'm considering a situation with the new fsensor
  225. if (minVolt >= IRsensor_Ldiode_TRESHOLD && minVolt <= IRsensor_Lmax_TRESHOLD && maxVolt >= IRsensor_Hmin_TRESHOLD &&
  226. maxVolt <= IRsensor_Hopen_TRESHOLD) {
  227. IR_ANALOG_Check(SensorRevision::_Old, SensorRevision::_Rev04);
  228. }
  229. //! If and only if minVolt is in range <0.0, 0.3> and maxVolt is in range <4.6, 5.0V>, I'm considering a situation with the old fsensor
  230. //! Note, we are not relying on one voltage here - getting just +5V can mean an old fsensor or a broken new sensor - that's why
  231. //! we need to have both voltages detected correctly to allow switching back to the old fsensor.
  232. else if (minVolt < IRsensor_Ldiode_TRESHOLD && maxVolt > IRsensor_Hopen_TRESHOLD && maxVolt <= IRsensor_VMax_TRESHOLD) {
  233. IR_ANALOG_Check(SensorRevision::_Rev04, SensorRevision::_Old);
  234. }
  235. if (!checkVoltage(volt)) {
  236. triggerError();
  237. }
  238. }
  239. }
  240. ; //
  241. return event;
  242. }
  243. void IR_sensor_analog::voltUpdate(uint16_t raw) { // to be called from the ADC ISR when a cycle is finished
  244. voltRaw = raw;
  245. voltReady = true;
  246. }
  247. uint16_t IR_sensor_analog::getVoltRaw() {
  248. uint16_t newVoltRaw;
  249. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { newVoltRaw = voltRaw; }
  250. return newVoltRaw;
  251. }
  252. void IR_sensor_analog::settings_init() {
  253. IR_sensor::settings_init();
  254. sensorRevision = (SensorRevision)eeprom_read_byte((uint8_t *)EEPROM_FSENSOR_PCB);
  255. }
  256. const char *IR_sensor_analog::getIRVersionText() {
  257. switch (sensorRevision) {
  258. case SensorRevision::_Old:
  259. return _T(MSG_IR_03_OR_OLDER);
  260. case SensorRevision::_Rev04:
  261. return _T(MSG_IR_04_OR_NEWER);
  262. default:
  263. return _T(MSG_IR_UNKNOWN);
  264. }
  265. }
  266. void IR_sensor_analog::setSensorRevision(SensorRevision rev, bool updateEEPROM) {
  267. sensorRevision = rev;
  268. if (updateEEPROM) {
  269. eeprom_update_byte((uint8_t *)EEPROM_FSENSOR_PCB, (uint8_t)rev);
  270. }
  271. }
  272. bool IR_sensor_analog::checkVoltage(uint16_t raw) {
  273. if (IRsensor_Lmax_TRESHOLD <= raw && raw <= IRsensor_Hmin_TRESHOLD) {
  274. /// If the voltage is in forbidden range, the fsensor is ok, but the lever is mounted improperly.
  275. /// Or the user is so creative so that he can hold a piece of fillament in the hole in such a genius way,
  276. /// that the IR fsensor reading is within 1.5 and 3V ... this would have been highly unusual
  277. /// and would have been considered more like a sabotage than normal printer operation
  278. if (voltageErrorCnt++ > 4) {
  279. puts_P(PSTR("fsensor in forbidden range 1.5-3V - check sensor"));
  280. return false;
  281. }
  282. } else {
  283. voltageErrorCnt = 0;
  284. }
  285. if (sensorRevision == SensorRevision::_Rev04) {
  286. /// newer IR sensor cannot normally produce 4.6-5V, this is considered a failure/bad mount
  287. if (IRsensor_Hopen_TRESHOLD <= raw && raw <= IRsensor_VMax_TRESHOLD) {
  288. puts_P(PSTR("fsensor v0.4 in fault range 4.6-5V - unconnected"));
  289. return false;
  290. }
  291. /// newer IR sensor cannot normally produce 0-0.3V, this is considered a failure
  292. #if 0 // Disabled as it has to be decided if we gonna use this or not.
  293. if(IRsensor_Hopen_TRESHOLD <= raw && raw <= IRsensor_VMax_TRESHOLD) {
  294. puts_P(PSTR("fsensor v0.4 in fault range 0.0-0.3V - wrong IR sensor"));
  295. return false;
  296. }
  297. #endif
  298. }
  299. /// If IR sensor is "uknown state" and filament is not loaded > 1.5V return false
  300. #if 0
  301. #error "I really think this code can't be enabled anymore because we are constantly checking this voltage."
  302. if((sensorRevision == SensorRevision::_Undef) && (raw > IRsensor_Lmax_TRESHOLD)) {
  303. puts_P(PSTR("Unknown IR sensor version and no filament loaded detected."));
  304. return false;
  305. }
  306. #endif
  307. // otherwise the IR fsensor is considered working correctly
  308. return true;
  309. }
  310. void IR_sensor_analog::IR_ANALOG_Check(SensorRevision isVersion, SensorRevision switchTo) {
  311. bool bTemp = (!CHECK_ALL_HEATERS);
  312. bTemp = bTemp && (menu_menu == lcd_status_screen);
  313. bTemp = bTemp && ((sensorRevision == isVersion) || (sensorRevision == SensorRevision::_Undef));
  314. bTemp = bTemp && (state == State::ready);
  315. if (bTemp) {
  316. nFSCheckCount++;
  317. if (nFSCheckCount > FS_CHECK_COUNT) {
  318. nFSCheckCount = 0; // not necessary
  319. setSensorRevision(switchTo, true);
  320. printf_IRSensorAnalogBoardChange();
  321. switch (switchTo) {
  322. case SensorRevision::_Old:
  323. lcd_setstatuspgm(_T(MSG_FS_V_03_OR_OLDER)); ////MSG_FS_V_03_OR_OLDER c=18
  324. break;
  325. case SensorRevision::_Rev04:
  326. lcd_setstatuspgm(_T(MSG_FS_V_04_OR_NEWER)); ////MSG_FS_V_04_OR_NEWER c=18
  327. break;
  328. default:
  329. break;
  330. }
  331. }
  332. } else {
  333. nFSCheckCount = 0;
  334. }
  335. }
  336. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_IR_ANALOG)
  337. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_IR) || (FILAMENT_SENSOR_TYPE == FSENSOR_IR_ANALOG)
  338. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  339. void PAT9125_sensor::init() {
  340. if (state == State::error) {
  341. deinit(); // deinit first if there was an error.
  342. }
  343. puts_P(PSTR("fsensor::init()"));
  344. settings_init(); // also sets the state to State::initializing
  345. calcChunkSteps(cs.axis_steps_per_unit[E_AXIS]); // for jam detection
  346. if (!pat9125_init()) {
  347. deinit();
  348. triggerError();
  349. ; //
  350. }
  351. #ifdef IR_SENSOR_PIN
  352. else if (!READ(IR_SENSOR_PIN)) {
  353. ; // MK3 fw on MK3S printer
  354. }
  355. #endif // IR_SENSOR_PIN
  356. }
  357. void PAT9125_sensor::deinit() {
  358. puts_P(PSTR("fsensor::deinit()"));
  359. ; //
  360. state = State::disabled;
  361. filter = 0;
  362. }
  363. bool PAT9125_sensor::update() {
  364. switch (state) {
  365. case State::initializing:
  366. if (!updatePAT9125()) {
  367. break; // still not stable. Stay in the initialization state.
  368. }
  369. oldFilamentPresent =
  370. getFilamentPresent(); // initialize the current filament state so that we don't create a switching event right after the sensor is ready.
  371. oldPos = pat9125_y;
  372. state = State::ready;
  373. break;
  374. case State::ready: {
  375. updatePAT9125();
  376. postponedLoadEvent = false;
  377. bool event = checkFilamentEvents();
  378. ; //
  379. return event;
  380. } break;
  381. case State::disabled:
  382. case State::error:
  383. default:
  384. return false;
  385. }
  386. return false;
  387. }
  388. #ifdef FSENSOR_PROBING
  389. bool PAT9125_sensor::probeOtherType() {
  390. SET_INPUT(IR_SENSOR_PIN); // input mode
  391. WRITE(IR_SENSOR_PIN, 1); // pullup
  392. _delay_us(100); // wait for the pullup to pull the line high (might be needed, not really sure. The internal pullups are quite weak and there might be a
  393. // long wire attached).
  394. bool fsensorDetected = !READ(IR_SENSOR_PIN);
  395. WRITE(IR_SENSOR_PIN, 0); // no pullup
  396. return fsensorDetected;
  397. }
  398. #endif
  399. void PAT9125_sensor::setJamDetectionEnabled(bool state, bool updateEEPROM) {
  400. jamDetection = state;
  401. oldPos = pat9125_y;
  402. resetStepCount();
  403. jamErrCnt = 0;
  404. if (updateEEPROM) {
  405. eeprom_update_byte((uint8_t *)EEPROM_FSENSOR_JAM_DETECTION, state);
  406. }
  407. }
  408. void PAT9125_sensor::settings_init() {
  409. puts_P(PSTR("settings_init"));
  410. Filament_sensor::settings_init_common();
  411. setJamDetectionEnabled(eeprom_read_byte((uint8_t *)EEPROM_FSENSOR_JAM_DETECTION));
  412. }
  413. int16_t PAT9125_sensor::getStepCount() {
  414. int16_t st_cnt;
  415. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { st_cnt = stepCount; }
  416. return st_cnt;
  417. }
  418. void PAT9125_sensor::resetStepCount() {
  419. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { stepCount = 0; }
  420. }
  421. void PAT9125_sensor::filJam() {
  422. runoutEnabled = false;
  423. autoLoadEnabled = false;
  424. jamDetection = false;
  425. stop_and_save_print_to_ram(0, 0);
  426. restore_print_from_ram_and_continue(0);
  427. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, eeprom_read_byte((uint8_t *)EEPROM_FERROR_COUNT) + 1);
  428. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, eeprom_read_word((uint16_t *)EEPROM_FERROR_COUNT_TOT) + 1);
  429. enquecommand_front_P((PSTR("M600")));
  430. }
  431. bool PAT9125_sensor::updatePAT9125() {
  432. if (jamDetection) {
  433. int16_t _stepCount = getStepCount();
  434. if (abs(_stepCount) >= chunkSteps) { // end of chunk. Check distance
  435. resetStepCount();
  436. if (!pat9125_update()) { // get up to date data. reinit on error.
  437. init(); // try to reinit.
  438. }
  439. bool fsDir = (pat9125_y - oldPos) > 0;
  440. bool stDir = _stepCount > 0;
  441. if (fsDir != stDir) {
  442. jamErrCnt++;
  443. } else if (jamErrCnt) {
  444. jamErrCnt--;
  445. }
  446. oldPos = pat9125_y;
  447. }
  448. if (jamErrCnt > 10) {
  449. jamErrCnt = 0;
  450. filJam();
  451. }
  452. }
  453. if (!pollingTimer.running() || pollingTimer.expired(pollingPeriod)) {
  454. pollingTimer.start();
  455. if (!pat9125_update()) {
  456. init(); // try to reinit.
  457. }
  458. bool present = (pat9125_s < 17) || (pat9125_s >= 17 && pat9125_b >= 50);
  459. if (present != filterFilPresent) {
  460. filter++;
  461. } else if (filter) {
  462. filter--;
  463. }
  464. if (filter >= filterCnt) {
  465. filter = 0;
  466. filterFilPresent = present;
  467. }
  468. }
  469. return (filter == 0); // return stability
  470. }
  471. #endif // #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)