Filament_sensor.h 15 KB

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