Filament_sensor.h 14 KB

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