Filament_sensor.h 15 KB

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