Filament_sensor.cpp 17 KB

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