Filament_sensor.h 16 KB

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