Filament_sensor.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. fsensor.init();
  39. } else {
  40. fsensor.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 = fsensor.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() != 0
  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() != 0
  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. fsensor.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. // initialize the current filament state so that we don't create a switching event right after the sensor is ready.
  176. oldFilamentPresent = fsensor.getFilamentPresent();
  177. [[fallthrough]];
  178. case State::ready: {
  179. postponedLoadEvent = false;
  180. return checkFilamentEvents();
  181. } break;
  182. case State::disabled:
  183. case State::error:
  184. default:
  185. return false;
  186. }
  187. return false;
  188. }
  189. #ifdef FSENSOR_PROBING
  190. bool IR_sensor::probeOtherType() { return pat9125_probe(); }
  191. #endif
  192. void IR_sensor::settings_init() { Filament_sensor::settings_init_common(); }
  193. #if (FILAMENT_SENSOR_TYPE == FSENSOR_IR_ANALOG)
  194. void IR_sensor_analog::init() {
  195. IR_sensor::init();
  196. IR_sensor::settings_init();
  197. sensorRevision = (SensorRevision)eeprom_read_byte((uint8_t *)EEPROM_FSENSOR_PCB);
  198. }
  199. bool IR_sensor_analog::update() {
  200. bool event = IR_sensor::update();
  201. if (state == State::ready) {
  202. if (getVoltReady()) {
  203. clearVoltReady();
  204. uint16_t volt = getVoltRaw();
  205. // printf_P(PSTR("newVoltRaw:%u\n"), volt / OVERSAMPLENR);
  206. // detect min-max, some long term sliding window for filtration may be added
  207. // avoiding floating point operations, thus computing in raw
  208. if (volt > maxVolt) {
  209. maxVolt = volt;
  210. } else if (volt < minVolt) {
  211. minVolt = volt;
  212. }
  213. //! The trouble is, I can hold the filament in the hole in such a way, that it creates the exact voltage
  214. //! to be detected as the new fsensor
  215. //! We can either fake it by extending the detection window to a looooong time
  216. //! or do some other countermeasures
  217. //! what we want to detect:
  218. //! if minvolt gets below ~0.3V, it means there is an old fsensor
  219. //! if maxvolt gets above 4.6V, it means we either have an old fsensor or broken cables/fsensor
  220. //! So I'm waiting for a situation, when minVolt gets to range <0, 1.5> and maxVolt gets into range <3.0, 5>
  221. //! 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
  222. if (minVolt >= IRsensor_Ldiode_TRESHOLD && minVolt <= IRsensor_Lmax_TRESHOLD && maxVolt >= IRsensor_Hmin_TRESHOLD &&
  223. maxVolt <= IRsensor_Hopen_TRESHOLD) {
  224. IR_ANALOG_Check(SensorRevision::_Old, SensorRevision::_Rev04);
  225. }
  226. //! 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
  227. //! 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
  228. //! we need to have both voltages detected correctly to allow switching back to the old fsensor.
  229. else if (minVolt < IRsensor_Ldiode_TRESHOLD && maxVolt > IRsensor_Hopen_TRESHOLD && maxVolt <= IRsensor_VMax_TRESHOLD) {
  230. IR_ANALOG_Check(SensorRevision::_Rev04, SensorRevision::_Old);
  231. }
  232. if (!checkVoltage(volt)) {
  233. triggerError();
  234. }
  235. }
  236. }
  237. ; //
  238. return event;
  239. }
  240. void IR_sensor_analog::voltUpdate(uint16_t raw) { // to be called from the ADC ISR when a cycle is finished
  241. voltRaw = raw;
  242. voltReady = true;
  243. }
  244. uint16_t IR_sensor_analog::getVoltRaw() {
  245. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { return voltRaw; }
  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. bool IR_sensor_analog::getVoltReady() const {
  302. ATOMIC_BLOCK(ATOMIC_RESTORESTATE){ return voltReady; }
  303. }
  304. void IR_sensor_analog::clearVoltReady(){
  305. ATOMIC_BLOCK(ATOMIC_RESTORESTATE){ voltReady = false; }
  306. }
  307. void IR_sensor_analog::IR_ANALOG_Check(SensorRevision isVersion, SensorRevision switchTo) {
  308. bool bTemp = (!CHECK_ALL_HEATERS);
  309. bTemp = bTemp && (menu_menu == lcd_status_screen);
  310. bTemp = bTemp && ((sensorRevision == isVersion) || (sensorRevision == SensorRevision::_Undef));
  311. bTemp = bTemp && (state == State::ready);
  312. if (bTemp) {
  313. nFSCheckCount++;
  314. if (nFSCheckCount > FS_CHECK_COUNT) {
  315. nFSCheckCount = 0; // not necessary
  316. setSensorRevision(switchTo, true);
  317. printf_IRSensorAnalogBoardChange();
  318. switch (switchTo) {
  319. case SensorRevision::_Old:
  320. lcd_setstatuspgm(_T(MSG_FS_V_03_OR_OLDER)); ////MSG_FS_V_03_OR_OLDER c=18
  321. break;
  322. case SensorRevision::_Rev04:
  323. lcd_setstatuspgm(_T(MSG_FS_V_04_OR_NEWER)); ////MSG_FS_V_04_OR_NEWER c=18
  324. break;
  325. default:
  326. break;
  327. }
  328. }
  329. } else {
  330. nFSCheckCount = 0;
  331. }
  332. }
  333. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_IR_ANALOG)
  334. #endif //(FILAMENT_SENSOR_TYPE == FSENSOR_IR) || (FILAMENT_SENSOR_TYPE == FSENSOR_IR_ANALOG)
  335. #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)
  336. void PAT9125_sensor::init() {
  337. if (state == State::error) {
  338. deinit(); // deinit first if there was an error.
  339. }
  340. // puts_P(PSTR("fsensor::init()"));
  341. settings_init(); // also sets the state to State::initializing
  342. calcChunkSteps(cs.axis_steps_per_unit[E_AXIS]); // for jam detection
  343. if (!pat9125_init()) {
  344. deinit();
  345. triggerError();
  346. ; //
  347. }
  348. #ifdef IR_SENSOR_PIN
  349. else if (!READ(IR_SENSOR_PIN)) {
  350. ; // MK3 fw on MK3S printer
  351. }
  352. #endif // IR_SENSOR_PIN
  353. }
  354. void PAT9125_sensor::deinit() {
  355. // puts_P(PSTR("fsensor::deinit()"));
  356. ; //
  357. state = State::disabled;
  358. filter = 0;
  359. }
  360. bool PAT9125_sensor::update() {
  361. switch (state) {
  362. case State::initializing:
  363. if (!updatePAT9125()) {
  364. break; // still not stable. Stay in the initialization state.
  365. }
  366. oldFilamentPresent =
  367. getFilamentPresent(); // initialize the current filament state so that we don't create a switching event right after the sensor is ready.
  368. oldPos = pat9125_y;
  369. state = State::ready;
  370. break;
  371. case State::ready: {
  372. updatePAT9125();
  373. postponedLoadEvent = false;
  374. bool event = checkFilamentEvents();
  375. ; //
  376. return event;
  377. } break;
  378. case State::disabled:
  379. case State::error:
  380. default:
  381. return false;
  382. }
  383. return false;
  384. }
  385. #ifdef FSENSOR_PROBING
  386. bool PAT9125_sensor::probeOtherType() {
  387. SET_INPUT(IR_SENSOR_PIN); // input mode
  388. WRITE(IR_SENSOR_PIN, 1); // pullup
  389. _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
  390. // long wire attached).
  391. bool fsensorDetected = !READ(IR_SENSOR_PIN);
  392. WRITE(IR_SENSOR_PIN, 0); // no pullup
  393. return fsensorDetected;
  394. }
  395. #endif
  396. void PAT9125_sensor::setJamDetectionEnabled(bool state, bool updateEEPROM) {
  397. jamDetection = state;
  398. oldPos = pat9125_y;
  399. resetStepCount();
  400. jamErrCnt = 0;
  401. if (updateEEPROM) {
  402. eeprom_update_byte((uint8_t *)EEPROM_FSENSOR_JAM_DETECTION, state);
  403. }
  404. }
  405. void PAT9125_sensor::settings_init() {
  406. // puts_P(PSTR("settings_init"));
  407. Filament_sensor::settings_init_common();
  408. setJamDetectionEnabled(eeprom_read_byte((uint8_t *)EEPROM_FSENSOR_JAM_DETECTION));
  409. }
  410. int16_t PAT9125_sensor::getStepCount() {
  411. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { return stepCount; }
  412. }
  413. void PAT9125_sensor::resetStepCount() {
  414. ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { stepCount = 0; }
  415. }
  416. void PAT9125_sensor::filJam() {
  417. runoutEnabled = false;
  418. autoLoadEnabled = false;
  419. jamDetection = false;
  420. stop_and_save_print_to_ram(0, 0);
  421. restore_print_from_ram_and_continue(0);
  422. eeprom_update_byte((uint8_t *)EEPROM_FERROR_COUNT, eeprom_read_byte((uint8_t *)EEPROM_FERROR_COUNT) + 1);
  423. eeprom_update_word((uint16_t *)EEPROM_FERROR_COUNT_TOT, eeprom_read_word((uint16_t *)EEPROM_FERROR_COUNT_TOT) + 1);
  424. enquecommand_front_P((PSTR("M600")));
  425. }
  426. bool PAT9125_sensor::updatePAT9125() {
  427. if (jamDetection) {
  428. int16_t _stepCount = getStepCount();
  429. if (abs(_stepCount) >= chunkSteps) { // end of chunk. Check distance
  430. resetStepCount();
  431. if (!pat9125_update()) { // get up to date data. reinit on error.
  432. init(); // try to reinit.
  433. }
  434. bool fsDir = (pat9125_y - oldPos) > 0;
  435. bool stDir = _stepCount > 0;
  436. if (fsDir != stDir) {
  437. jamErrCnt++;
  438. } else if (jamErrCnt) {
  439. jamErrCnt--;
  440. }
  441. oldPos = pat9125_y;
  442. }
  443. if (jamErrCnt > 10) {
  444. jamErrCnt = 0;
  445. filJam();
  446. }
  447. }
  448. if (!pollingTimer.running() || pollingTimer.expired(pollingPeriod)) {
  449. pollingTimer.start();
  450. if (!pat9125_update()) {
  451. init(); // try to reinit.
  452. }
  453. bool present = (pat9125_s < 17) || (pat9125_s >= 17 && pat9125_b >= 50);
  454. if (present != filterFilPresent) {
  455. filter++;
  456. } else if (filter) {
  457. filter--;
  458. }
  459. if (filter >= filterCnt) {
  460. filter = 0;
  461. filterFilPresent = present;
  462. }
  463. }
  464. return (filter == 0); // return stability
  465. }
  466. #endif // #if (FILAMENT_SENSOR_TYPE == FSENSOR_PAT9125)