Filament_sensor.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { return voltRaw; }
  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. bool IR_sensor_analog::getVoltReady() const {
  303. ATOMIC_BLOCK(ATOMIC_RESTORESTATE){ return voltReady; }
  304. }
  305. void IR_sensor_analog::clearVoltReady(){
  306. ATOMIC_BLOCK(ATOMIC_RESTORESTATE){ voltReady = false; }
  307. }
  308. void IR_sensor_analog::IR_ANALOG_Check(SensorRevision isVersion, SensorRevision switchTo) {
  309. bool bTemp = (!CHECK_ALL_HEATERS);
  310. bTemp = bTemp && (menu_menu == lcd_status_screen);
  311. bTemp = bTemp && ((sensorRevision == isVersion) || (sensorRevision == SensorRevision::_Undef));
  312. bTemp = bTemp && (state == State::ready);
  313. if (bTemp) {
  314. nFSCheckCount++;
  315. if (nFSCheckCount > FS_CHECK_COUNT) {
  316. nFSCheckCount = 0; // not necessary
  317. setSensorRevision(switchTo, true);
  318. printf_IRSensorAnalogBoardChange();
  319. switch (switchTo) {
  320. case SensorRevision::_Old:
  321. lcd_setstatuspgm(_T(MSG_IR_03_OR_OLDER));
  322. break;
  323. case SensorRevision::_Rev04:
  324. lcd_setstatuspgm(_T(MSG_IR_04_OR_NEWER));
  325. break;
  326. default:
  327. break;
  328. }
  329. }
  330. } else {
  331. nFSCheckCount = 0;
  332. }
  333. }
  334. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_IR_ANALOG)
  335. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_IR) || (FILAMENT_SENSOR_TYPE == FSENSOR_IR_ANALOG)
  336. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  337. void PAT9125_sensor::init() {
  338. if (state == State::error) {
  339. deinit(); // deinit first if there was an error.
  340. }
  341. // puts_P(PSTR("fsensor::init()"));
  342. settings_init(); // also sets the state to State::initializing
  343. calcChunkSteps(cs.axis_steps_per_unit[E_AXIS]); // for jam detection
  344. if (!pat9125_init()) {
  345. deinit();
  346. triggerError();
  347. ; //
  348. }
  349. #ifdef IR_SENSOR_PIN
  350. else if (!READ(IR_SENSOR_PIN)) {
  351. ; // MK3 fw on MK3S printer
  352. }
  353. #endif // IR_SENSOR_PIN
  354. }
  355. void PAT9125_sensor::deinit() {
  356. // puts_P(PSTR("fsensor::deinit()"));
  357. ; //
  358. state = State::disabled;
  359. filter = 0;
  360. }
  361. bool PAT9125_sensor::update() {
  362. switch (state) {
  363. case State::initializing:
  364. if (!updatePAT9125()) {
  365. break; // still not stable. Stay in the initialization state.
  366. }
  367. oldFilamentPresent =
  368. getFilamentPresent(); // initialize the current filament state so that we don't create a switching event right after the sensor is ready.
  369. oldPos = pat9125_y;
  370. state = State::ready;
  371. break;
  372. case State::ready: {
  373. updatePAT9125();
  374. postponedLoadEvent = false;
  375. bool event = checkFilamentEvents();
  376. ; //
  377. return event;
  378. } break;
  379. case State::disabled:
  380. case State::error:
  381. default:
  382. return false;
  383. }
  384. return false;
  385. }
  386. #ifdef FSENSOR_PROBING
  387. bool PAT9125_sensor::probeOtherType() {
  388. SET_INPUT(IR_SENSOR_PIN); // input mode
  389. WRITE(IR_SENSOR_PIN, 1); // pullup
  390. _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
  391. // long wire attached).
  392. bool fsensorDetected = !READ(IR_SENSOR_PIN);
  393. WRITE(IR_SENSOR_PIN, 0); // no pullup
  394. return fsensorDetected;
  395. }
  396. #endif
  397. void PAT9125_sensor::setJamDetectionEnabled(bool state, bool updateEEPROM) {
  398. jamDetection = state;
  399. oldPos = pat9125_y;
  400. resetStepCount();
  401. jamErrCnt = 0;
  402. if (updateEEPROM) {
  403. eeprom_update_byte((uint8_t *)EEPROM_FSENSOR_JAM_DETECTION, state);
  404. }
  405. }
  406. void PAT9125_sensor::settings_init() {
  407. // puts_P(PSTR("settings_init"));
  408. Filament_sensor::settings_init_common();
  409. setJamDetectionEnabled(eeprom_read_byte((uint8_t *)EEPROM_FSENSOR_JAM_DETECTION));
  410. }
  411. int16_t PAT9125_sensor::getStepCount() {
  412. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { return stepCount; }
  413. }
  414. void PAT9125_sensor::resetStepCount() {
  415. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { stepCount = 0; }
  416. }
  417. void PAT9125_sensor::filJam() {
  418. runoutEnabled = false;
  419. autoLoadEnabled = false;
  420. jamDetection = false;
  421. stop_and_save_print_to_ram(0, 0);
  422. restore_print_from_ram_and_continue(0);
  423. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, eeprom_read_byte((uint8_t *)EEPROM_FERROR_COUNT) + 1);
  424. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, eeprom_read_word((uint16_t *)EEPROM_FERROR_COUNT_TOT) + 1);
  425. enquecommand_front_P((PSTR("M600")));
  426. }
  427. bool PAT9125_sensor::updatePAT9125() {
  428. if (jamDetection) {
  429. int16_t _stepCount = getStepCount();
  430. if (abs(_stepCount) >= chunkSteps) { // end of chunk. Check distance
  431. resetStepCount();
  432. if (!pat9125_update()) { // get up to date data. reinit on error.
  433. init(); // try to reinit.
  434. }
  435. bool fsDir = (pat9125_y - oldPos) > 0;
  436. bool stDir = _stepCount > 0;
  437. if (fsDir != stDir) {
  438. jamErrCnt++;
  439. } else if (jamErrCnt) {
  440. jamErrCnt--;
  441. }
  442. oldPos = pat9125_y;
  443. }
  444. if (jamErrCnt > 10) {
  445. jamErrCnt = 0;
  446. filJam();
  447. }
  448. }
  449. if (!pollingTimer.running() || pollingTimer.expired(pollingPeriod)) {
  450. pollingTimer.start();
  451. if (!pat9125_update()) {
  452. init(); // try to reinit.
  453. }
  454. bool present = (pat9125_s < 17) || (pat9125_s >= 17 && pat9125_b >= 50);
  455. if (present != filterFilPresent) {
  456. filter++;
  457. } else if (filter) {
  458. filter--;
  459. }
  460. if (filter >= filterCnt) {
  461. filter = 0;
  462. filterFilPresent = present;
  463. }
  464. }
  465. return (filter == 0); // return stability
  466. }
  467. #endif // #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)