Filament_sensor.cpp 17 KB

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