Filament_sensor.cpp 18 KB

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