Filament_sensor.h 18 KB

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