Filament_sensor.h 13 KB

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