Filament_sensor.h 16 KB

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