Filament_sensor.cpp 18 KB

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