Filament_sensor.cpp 17 KB

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