Filament_sensor.cpp 18 KB

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