diff --git a/src/core/boards.h b/src/core/boards.h new file mode 100644 index 0000000..55cab84 --- /dev/null +++ b/src/core/boards.h @@ -0,0 +1,475 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "macros.h" + +#define BOARD_UNKNOWN -1 + +// +// RAMPS 1.3 / 1.4 - ATmega1280, ATmega2560 +// + +#define BOARD_RAMPS_OLD 1000 // MEGA/RAMPS up to 1.2 + +#define BOARD_RAMPS_13_EFB 1010 // RAMPS 1.3 (Power outputs: Hotend, Fan, Bed) +#define BOARD_RAMPS_13_EEB 1011 // RAMPS 1.3 (Power outputs: Hotend0, Hotend1, Bed) +#define BOARD_RAMPS_13_EFF 1012 // RAMPS 1.3 (Power outputs: Hotend, Fan0, Fan1) +#define BOARD_RAMPS_13_EEF 1013 // RAMPS 1.3 (Power outputs: Hotend0, Hotend1, Fan) +#define BOARD_RAMPS_13_SF 1014 // RAMPS 1.3 (Power outputs: Spindle, Controller Fan) + +#define BOARD_RAMPS_14_EFB 1020 // RAMPS 1.4 (Power outputs: Hotend, Fan, Bed) +#define BOARD_RAMPS_14_EEB 1021 // RAMPS 1.4 (Power outputs: Hotend0, Hotend1, Bed) +#define BOARD_RAMPS_14_EFF 1022 // RAMPS 1.4 (Power outputs: Hotend, Fan0, Fan1) +#define BOARD_RAMPS_14_EEF 1023 // RAMPS 1.4 (Power outputs: Hotend0, Hotend1, Fan) +#define BOARD_RAMPS_14_SF 1024 // RAMPS 1.4 (Power outputs: Spindle, Controller Fan) + +#define BOARD_RAMPS_PLUS_EFB 1030 // RAMPS Plus 3DYMY (Power outputs: Hotend, Fan, Bed) +#define BOARD_RAMPS_PLUS_EEB 1031 // RAMPS Plus 3DYMY (Power outputs: Hotend0, Hotend1, Bed) +#define BOARD_RAMPS_PLUS_EFF 1032 // RAMPS Plus 3DYMY (Power outputs: Hotend, Fan0, Fan1) +#define BOARD_RAMPS_PLUS_EEF 1033 // RAMPS Plus 3DYMY (Power outputs: Hotend0, Hotend1, Fan) +#define BOARD_RAMPS_PLUS_SF 1034 // RAMPS Plus 3DYMY (Power outputs: Spindle, Controller Fan) + +// +// RAMPS Derivatives - ATmega1280, ATmega2560 +// + +#define BOARD_3DRAG 1100 // 3Drag Controller +#define BOARD_K8200 1101 // Velleman K8200 Controller (derived from 3Drag Controller) +#define BOARD_K8400 1102 // Velleman K8400 Controller (derived from 3Drag Controller) +#define BOARD_K8600 1103 // Velleman K8600 Controller (Vertex Nano) +#define BOARD_K8800 1104 // Velleman K8800 Controller (Vertex Delta) +#define BOARD_BAM_DICE 1105 // 2PrintBeta BAM&DICE with STK drivers +#define BOARD_BAM_DICE_DUE 1106 // 2PrintBeta BAM&DICE Due with STK drivers +#define BOARD_MKS_BASE 1107 // MKS BASE v1.0 +#define BOARD_MKS_BASE_14 1108 // MKS BASE v1.4 with Allegro A4982 stepper drivers +#define BOARD_MKS_BASE_15 1109 // MKS BASE v1.5 with Allegro A4982 stepper drivers +#define BOARD_MKS_BASE_16 1110 // MKS BASE v1.6 with Allegro A4982 stepper drivers +#define BOARD_MKS_BASE_HEROIC 1111 // MKS BASE 1.0 with Heroic HR4982 stepper drivers +#define BOARD_MKS_GEN_13 1112 // MKS GEN v1.3 or 1.4 +#define BOARD_MKS_GEN_L 1113 // MKS GEN L +#define BOARD_KFB_2 1114 // BigTreeTech or BIQU KFB2.0 +#define BOARD_ZRIB_V20 1115 // zrib V2.0 (Chinese RAMPS replica) +#define BOARD_ZRIB_V52 1116 // zrib V5.2 (Chinese RAMPS replica) +#define BOARD_FELIX2 1117 // Felix 2.0+ Electronics Board (RAMPS like) +#define BOARD_RIGIDBOARD 1118 // Invent-A-Part RigidBoard +#define BOARD_RIGIDBOARD_V2 1119 // Invent-A-Part RigidBoard V2 +#define BOARD_SAINSMART_2IN1 1120 // Sainsmart 2-in-1 board +#define BOARD_ULTIMAKER 1121 // Ultimaker +#define BOARD_ULTIMAKER_OLD 1122 // Ultimaker (Older electronics. Pre 1.5.4. This is rare) +#define BOARD_AZTEEG_X3 1123 // Azteeg X3 +#define BOARD_AZTEEG_X3_PRO 1124 // Azteeg X3 Pro +#define BOARD_ULTIMAIN_2 1125 // Ultimainboard 2.x (Uses TEMP_SENSOR 20) +#define BOARD_RUMBA 1126 // Rumba +#define BOARD_RUMBA_RAISE3D 1127 // Raise3D N series Rumba derivative +#define BOARD_RL200 1128 // Rapide Lite 200 (v1, low-cost RUMBA clone with drv) +#define BOARD_FORMBOT_TREX2PLUS 1129 // Formbot T-Rex 2 Plus +#define BOARD_FORMBOT_TREX3 1130 // Formbot T-Rex 3 +#define BOARD_FORMBOT_RAPTOR 1131 // Formbot Raptor +#define BOARD_FORMBOT_RAPTOR2 1132 // Formbot Raptor 2 +#define BOARD_BQ_ZUM_MEGA_3D 1133 // bq ZUM Mega 3D +#define BOARD_MAKEBOARD_MINI 1134 // MakeBoard Mini v2.1.2 by MicroMake +#define BOARD_TRIGORILLA_13 1135 // TriGorilla Anycubic version 1.3-based on RAMPS EFB +#define BOARD_TRIGORILLA_14 1136 // ... Ver 1.4 +#define BOARD_TRIGORILLA_14_11 1137 // ... Rev 1.1 (new servo pin order) +#define BOARD_RAMPS_ENDER_4 1138 // Creality: Ender-4, CR-8 +#define BOARD_RAMPS_CREALITY 1139 // Creality: CR10S, CR20, CR-X +#define BOARD_DAGOMA_F5 1140 // Dagoma F5 +#define BOARD_FYSETC_F6_13 1141 // FYSETC F6 1.3 +#define BOARD_FYSETC_F6_14 1142 // FYSETC F6 1.4 +#define BOARD_DUPLICATOR_I3_PLUS 1143 // Wanhao Duplicator i3 Plus +#define BOARD_VORON 1144 // VORON Design +#define BOARD_TRONXY_V3_1_0 1145 // Tronxy TRONXY-V3-1.0 +#define BOARD_Z_BOLT_X_SERIES 1146 // Z-Bolt X Series +#define BOARD_TT_OSCAR 1147 // TT OSCAR +#define BOARD_OVERLORD 1148 // Overlord/Overlord Pro +#define BOARD_HJC2560C_REV1 1149 // ADIMLab Gantry v1 +#define BOARD_HJC2560C_REV2 1150 // ADIMLab Gantry v2 +#define BOARD_TANGO 1151 // BIQU Tango V1 +#define BOARD_MKS_GEN_L_V2 1152 // MKS GEN L V2 +#define BOARD_MKS_GEN_L_V21 1153 // MKS GEN L V2.1 +#define BOARD_COPYMASTER_3D 1154 // Copymaster 3D +#define BOARD_ORTUR_4 1155 // Ortur 4 +#define BOARD_TENLOG_D3_HERO 1156 // Tenlog D3 Hero IDEX printer +#define BOARD_RAMPS_S_12_EEFB 1157 // Ramps S 1.2 by Sakul.cz (Power outputs: Hotend0, Hotend1, Fan, Bed) +#define BOARD_RAMPS_S_12_EEEB 1158 // Ramps S 1.2 by Sakul.cz (Power outputs: Hotend0, Hotend1, Hotend2, Bed) +#define BOARD_RAMPS_S_12_EFFB 1159 // Ramps S 1.2 by Sakul.cz (Power outputs: Hotend, Fan0, Fan1, Bed) +#define BOARD_LONGER3D_LK1_PRO 1160 // Longer LK1 PRO / Alfawise U20 Pro (PRO version) +#define BOARD_LONGER3D_LKx_PRO 1161 // Longer LKx PRO / Alfawise Uxx Pro (PRO version) +#define BOARD_ZRIB_V53 1162 // Zonestar zrib V5.3 (Chinese RAMPS replica) +#define BOARD_PXMALION_CORE_I3 1163 // Pxmalion Core I3 + +// +// RAMBo and derivatives +// + +#define BOARD_RAMBO 1200 // Rambo +#define BOARD_MINIRAMBO 1201 // Mini-Rambo +#define BOARD_MINIRAMBO_10A 1202 // Mini-Rambo 1.0a +#define BOARD_EINSY_RAMBO 1203 // Einsy Rambo +#define BOARD_EINSY_RETRO 1204 // Einsy Retro +#define BOARD_SCOOVO_X9H 1205 // abee Scoovo X9H +#define BOARD_RAMBO_THINKERV2 1206 // ThinkerV2 + +// +// Other ATmega1280, ATmega2560 +// + +#define BOARD_CNCONTROLS_11 1300 // Cartesio CN Controls V11 +#define BOARD_CNCONTROLS_12 1301 // Cartesio CN Controls V12 +#define BOARD_CNCONTROLS_15 1302 // Cartesio CN Controls V15 +#define BOARD_CHEAPTRONIC 1303 // Cheaptronic v1.0 +#define BOARD_CHEAPTRONIC_V2 1304 // Cheaptronic v2.0 +#define BOARD_MIGHTYBOARD_REVE 1305 // Makerbot Mightyboard Revision E +#define BOARD_MEGATRONICS 1306 // Megatronics +#define BOARD_MEGATRONICS_2 1307 // Megatronics v2.0 +#define BOARD_MEGATRONICS_3 1308 // Megatronics v3.0 +#define BOARD_MEGATRONICS_31 1309 // Megatronics v3.1 +#define BOARD_MEGATRONICS_32 1310 // Megatronics v3.2 +#define BOARD_ELEFU_3 1311 // Elefu Ra Board (v3) +#define BOARD_LEAPFROG 1312 // Leapfrog +#define BOARD_MEGACONTROLLER 1313 // Mega controller +#define BOARD_GT2560_REV_A 1314 // Geeetech GT2560 Rev A +#define BOARD_GT2560_REV_A_PLUS 1315 // Geeetech GT2560 Rev A+ (with auto level probe) +#define BOARD_GT2560_REV_B 1316 // Geeetech GT2560 Rev B +#define BOARD_GT2560_V3 1317 // Geeetech GT2560 Rev B for A10(M/T/D) +#define BOARD_GT2560_V4 1318 // Geeetech GT2560 Rev B for A10(M/T/D) +#define BOARD_GT2560_V3_MC2 1319 // Geeetech GT2560 Rev B for Mecreator2 +#define BOARD_GT2560_V3_A20 1320 // Geeetech GT2560 Rev B for A20(M/T/D) +#define BOARD_EINSTART_S 1321 // Einstart retrofit +#define BOARD_WANHAO_ONEPLUS 1322 // Wanhao 0ne+ i3 Mini +#define BOARD_LEAPFROG_XEED2015 1323 // Leapfrog Xeed 2015 +#define BOARD_PICA_REVB 1324 // PICA Shield (original version) +#define BOARD_PICA 1325 // PICA Shield (rev C or later) +#define BOARD_INTAMSYS40 1326 // Intamsys 4.0 (Funmat HT) +#define BOARD_MALYAN_M180 1327 // Malyan M180 Mainboard Version 2 (no display function, direct G-code only) +#define BOARD_GT2560_V4_A20 1328 // Geeetech GT2560 Rev B for A20(M/T/D) +#define BOARD_PROTONEER_CNC_SHIELD_V3 1329 // Mega controller & Protoneer CNC Shield V3.00 +#define BOARD_WEEDO_62A 1330 // WEEDO 62A board (TINA2, Monoprice Cadet, etc.) + +// +// ATmega1281, ATmega2561 +// + +#define BOARD_MINITRONICS 1400 // Minitronics v1.0/1.1 +#define BOARD_SILVER_GATE 1401 // Silvergate v1.0 + +// +// Sanguinololu and Derivatives - ATmega644P, ATmega1284P +// + +#define BOARD_SANGUINOLOLU_11 1500 // Sanguinololu < 1.2 +#define BOARD_SANGUINOLOLU_12 1501 // Sanguinololu 1.2 and above +#define BOARD_MELZI 1502 // Melzi +#define BOARD_MELZI_V2 1503 // Melzi V2 +#define BOARD_MELZI_MAKR3D 1504 // Melzi with ATmega1284 (MaKr3d version) +#define BOARD_MELZI_CREALITY 1505 // Melzi Creality3D (for CR-10 etc) +#define BOARD_MELZI_MALYAN 1506 // Melzi Malyan M150 +#define BOARD_MELZI_TRONXY 1507 // Tronxy X5S +#define BOARD_STB_11 1508 // STB V1.1 +#define BOARD_AZTEEG_X1 1509 // Azteeg X1 +#define BOARD_ANET_10 1510 // Anet 1.0 (Melzi clone) +#define BOARD_ZMIB_V2 1511 // ZoneStar ZMIB V2 + +// +// Other ATmega644P, ATmega644, ATmega1284P +// + +#define BOARD_GEN3_MONOLITHIC 1600 // Gen3 Monolithic Electronics +#define BOARD_GEN3_PLUS 1601 // Gen3+ +#define BOARD_GEN6 1602 // Gen6 +#define BOARD_GEN6_DELUXE 1603 // Gen6 deluxe +#define BOARD_GEN7_CUSTOM 1604 // Gen7 custom (Alfons3 Version) https://github.com/Alfons3/Generation_7_Electronics +#define BOARD_GEN7_12 1605 // Gen7 v1.1, v1.2 +#define BOARD_GEN7_13 1606 // Gen7 v1.3 +#define BOARD_GEN7_14 1607 // Gen7 v1.4 +#define BOARD_OMCA_A 1608 // Alpha OMCA +#define BOARD_OMCA 1609 // Final OMCA +#define BOARD_SETHI 1610 // Sethi 3D_1 + +// +// Teensyduino - AT90USB1286, AT90USB1286P +// + +#define BOARD_TEENSYLU 1700 // Teensylu +#define BOARD_PRINTRBOARD 1701 // Printrboard (AT90USB1286) +#define BOARD_PRINTRBOARD_REVF 1702 // Printrboard Revision F (AT90USB1286) +#define BOARD_BRAINWAVE 1703 // Brainwave (AT90USB646) +#define BOARD_BRAINWAVE_PRO 1704 // Brainwave Pro (AT90USB1286) +#define BOARD_SAV_MKI 1705 // SAV Mk-I (AT90USB1286) +#define BOARD_TEENSY2 1706 // Teensy++2.0 (AT90USB1286) +#define BOARD_5DPRINT 1707 // 5DPrint D8 Driver Board + +// +// LPC1768 ARM Cortex M3 +// + +#define BOARD_RAMPS_14_RE_ARM_EFB 2000 // Re-ARM with RAMPS 1.4 (Power outputs: Hotend, Fan, Bed) +#define BOARD_RAMPS_14_RE_ARM_EEB 2001 // Re-ARM with RAMPS 1.4 (Power outputs: Hotend0, Hotend1, Bed) +#define BOARD_RAMPS_14_RE_ARM_EFF 2002 // Re-ARM with RAMPS 1.4 (Power outputs: Hotend, Fan0, Fan1) +#define BOARD_RAMPS_14_RE_ARM_EEF 2003 // Re-ARM with RAMPS 1.4 (Power outputs: Hotend0, Hotend1, Fan) +#define BOARD_RAMPS_14_RE_ARM_SF 2004 // Re-ARM with RAMPS 1.4 (Power outputs: Spindle, Controller Fan) +#define BOARD_MKS_SBASE 2005 // MKS-Sbase +#define BOARD_AZSMZ_MINI 2006 // AZSMZ Mini +#define BOARD_BIQU_BQ111_A4 2007 // BIQU BQ111-A4 +#define BOARD_SELENA_COMPACT 2008 // Selena Compact +#define BOARD_BIQU_B300_V1_0 2009 // BIQU B300_V1.0 +#define BOARD_MKS_SGEN_L 2010 // MKS-SGen-L +#define BOARD_GMARSH_X6_REV1 2011 // GMARSH X6, revision 1 prototype +#define BOARD_BTT_SKR_V1_1 2012 // BigTreeTech SKR v1.1 +#define BOARD_BTT_SKR_V1_3 2013 // BigTreeTech SKR v1.3 +#define BOARD_BTT_SKR_V1_4 2014 // BigTreeTech SKR v1.4 +#define BOARD_EMOTRONIC 2015 // eMotion-Tech eMotronic + +// +// LPC1769 ARM Cortex M3 +// + +#define BOARD_MKS_SGEN 2500 // MKS-SGen +#define BOARD_AZTEEG_X5_GT 2501 // Azteeg X5 GT +#define BOARD_AZTEEG_X5_MINI 2502 // Azteeg X5 Mini +#define BOARD_AZTEEG_X5_MINI_WIFI 2503 // Azteeg X5 Mini Wifi +#define BOARD_COHESION3D_REMIX 2504 // Cohesion3D ReMix +#define BOARD_COHESION3D_MINI 2505 // Cohesion3D Mini +#define BOARD_SMOOTHIEBOARD 2506 // Smoothieboard +#define BOARD_TH3D_EZBOARD 2507 // TH3D EZBoard v1.0 +#define BOARD_BTT_SKR_V1_4_TURBO 2508 // BigTreeTech SKR v1.4 TURBO +#define BOARD_MKS_SGEN_L_V2 2509 // MKS SGEN_L V2 +#define BOARD_BTT_SKR_E3_TURBO 2510 // BigTreeTech SKR E3 Turbo +#define BOARD_FLY_CDY 2511 // FLYmaker FLY CDY + +// +// SAM3X8E ARM Cortex M3 +// + +#define BOARD_DUE3DOM 3000 // DUE3DOM for Arduino DUE +#define BOARD_DUE3DOM_MINI 3001 // DUE3DOM MINI for Arduino DUE +#define BOARD_RADDS 3002 // RADDS +#define BOARD_RAMPS_FD_V1 3003 // RAMPS-FD v1 +#define BOARD_RAMPS_FD_V2 3004 // RAMPS-FD v2 +#define BOARD_RAMPS_SMART_EFB 3005 // RAMPS-SMART (Power outputs: Hotend, Fan, Bed) +#define BOARD_RAMPS_SMART_EEB 3006 // RAMPS-SMART (Power outputs: Hotend0, Hotend1, Bed) +#define BOARD_RAMPS_SMART_EFF 3007 // RAMPS-SMART (Power outputs: Hotend, Fan0, Fan1) +#define BOARD_RAMPS_SMART_EEF 3008 // RAMPS-SMART (Power outputs: Hotend0, Hotend1, Fan) +#define BOARD_RAMPS_SMART_SF 3009 // RAMPS-SMART (Power outputs: Spindle, Controller Fan) +#define BOARD_RAMPS_DUO_EFB 3010 // RAMPS Duo (Power outputs: Hotend, Fan, Bed) +#define BOARD_RAMPS_DUO_EEB 3011 // RAMPS Duo (Power outputs: Hotend0, Hotend1, Bed) +#define BOARD_RAMPS_DUO_EFF 3012 // RAMPS Duo (Power outputs: Hotend, Fan0, Fan1) +#define BOARD_RAMPS_DUO_EEF 3013 // RAMPS Duo (Power outputs: Hotend0, Hotend1, Fan) +#define BOARD_RAMPS_DUO_SF 3014 // RAMPS Duo (Power outputs: Spindle, Controller Fan) +#define BOARD_RAMPS4DUE_EFB 3015 // RAMPS4DUE (Power outputs: Hotend, Fan, Bed) +#define BOARD_RAMPS4DUE_EEB 3016 // RAMPS4DUE (Power outputs: Hotend0, Hotend1, Bed) +#define BOARD_RAMPS4DUE_EFF 3017 // RAMPS4DUE (Power outputs: Hotend, Fan0, Fan1) +#define BOARD_RAMPS4DUE_EEF 3018 // RAMPS4DUE (Power outputs: Hotend0, Hotend1, Fan) +#define BOARD_RAMPS4DUE_SF 3019 // RAMPS4DUE (Power outputs: Spindle, Controller Fan) +#define BOARD_RURAMPS4D_11 3020 // RuRAMPS4Duo v1.1 +#define BOARD_RURAMPS4D_13 3021 // RuRAMPS4Duo v1.3 +#define BOARD_ULTRATRONICS_PRO 3022 // ReprapWorld Ultratronics Pro V1.0 +#define BOARD_ARCHIM1 3023 // UltiMachine Archim1 (with DRV8825 drivers) +#define BOARD_ARCHIM2 3024 // UltiMachine Archim2 (with TMC2130 drivers) +#define BOARD_ALLIGATOR 3025 // Alligator Board R2 +#define BOARD_CNCONTROLS_15D 3026 // Cartesio CN Controls V15 on DUE +#define BOARD_KRATOS32 3027 // K.3D Kratos32 (Arduino Due Shield) + +// +// SAM3X8C ARM Cortex M3 +// + +#define BOARD_PRINTRBOARD_G2 3100 // Printrboard G2 +#define BOARD_ADSK 3101 // Arduino DUE Shield Kit (ADSK) + +// +// STM32 ARM Cortex-M3 +// + +#define BOARD_MALYAN_M200_V2 4000 // STM32F070CB controller +#define BOARD_MALYAN_M300 4001 // STM32F070-based delta +#define BOARD_STM32F103RE 4002 // STM32F103RE Libmaple-based STM32F1 controller +#define BOARD_MALYAN_M200 4003 // STM32C8 Libmaple-based STM32F1 controller +#define BOARD_STM3R_MINI 4004 // STM32F103RE Libmaple-based STM32F1 controller +#define BOARD_GTM32_PRO_VB 4005 // STM32F103VE controller +#define BOARD_GTM32_MINI 4006 // STM32F103VE controller +#define BOARD_GTM32_MINI_A30 4007 // STM32F103VE controller +#define BOARD_GTM32_REV_B 4008 // STM32F103VE controller +#define BOARD_MORPHEUS 4009 // STM32F103C8 / STM32F103CB Libmaple-based STM32F1 controller +#define BOARD_CHITU3D 4010 // Chitu3D (STM32F103RE) +#define BOARD_MKS_ROBIN 4011 // MKS Robin (STM32F103ZE) +#define BOARD_MKS_ROBIN_MINI 4012 // MKS Robin Mini (STM32F103VE) +#define BOARD_MKS_ROBIN_NANO 4013 // MKS Robin Nano (STM32F103VE) +#define BOARD_MKS_ROBIN_NANO_V2 4014 // MKS Robin Nano V2 (STM32F103VE) +#define BOARD_MKS_ROBIN_LITE 4015 // MKS Robin Lite/Lite2 (STM32F103RC) +#define BOARD_MKS_ROBIN_LITE3 4016 // MKS Robin Lite3 (STM32F103RC) +#define BOARD_MKS_ROBIN_PRO 4017 // MKS Robin Pro (STM32F103ZE) +#define BOARD_MKS_ROBIN_E3 4018 // MKS Robin E3 (STM32F103RC) +#define BOARD_MKS_ROBIN_E3_V1_1 4019 // MKS Robin E3 V1.1 (STM32F103RC) +#define BOARD_MKS_ROBIN_E3D 4020 // MKS Robin E3D (STM32F103RC) +#define BOARD_MKS_ROBIN_E3D_V1_1 4021 // MKS Robin E3D V1.1 (STM32F103RC) +#define BOARD_MKS_ROBIN_E3P 4022 // MKS Robin E3p (STM32F103VE) +#define BOARD_BTT_SKR_MINI_V1_1 4023 // BigTreeTech SKR Mini v1.1 (STM32F103RC) +#define BOARD_BTT_SKR_MINI_E3_V1_0 4024 // BigTreeTech SKR Mini E3 (STM32F103RC) +#define BOARD_BTT_SKR_MINI_E3_V1_2 4025 // BigTreeTech SKR Mini E3 V1.2 (STM32F103RC) +#define BOARD_BTT_SKR_MINI_E3_V2_0 4026 // BigTreeTech SKR Mini E3 V2.0 (STM32F103RC / STM32F103RE) +#define BOARD_BTT_SKR_MINI_E3_V3_0 4027 // BigTreeTech SKR Mini E3 V3.0 (STM32G0B1RE) +#define BOARD_BTT_SKR_MINI_MZ_V1_0 4028 // BigTreeTech SKR Mini MZ V1.0 (STM32F103RC) +#define BOARD_BTT_SKR_E3_DIP 4029 // BigTreeTech SKR E3 DIP V1.0 (STM32F103RC / STM32F103RE) +#define BOARD_BTT_SKR_CR6 4030 // BigTreeTech SKR CR6 v1.0 (STM32F103RE) +#define BOARD_JGAURORA_A5S_A1 4031 // JGAurora A5S A1 (STM32F103ZE) +#define BOARD_FYSETC_AIO_II 4032 // FYSETC AIO_II (STM32F103RC) +#define BOARD_FYSETC_CHEETAH 4033 // FYSETC Cheetah (STM32F103RC) +#define BOARD_FYSETC_CHEETAH_V12 4034 // FYSETC Cheetah V1.2 (STM32F103RC) +#define BOARD_LONGER3D_LK 4035 // Longer3D LK1/2 - Alfawise U20/U20+/U30 (STM32F103VE) +#define BOARD_CCROBOT_MEEB_3DP 4036 // ccrobot-online.com MEEB_3DP (STM32F103RC) +#define BOARD_CHITU3D_V5 4037 // Chitu3D TronXY X5SA V5 Board (STM32F103ZE) +#define BOARD_CHITU3D_V6 4038 // Chitu3D TronXY X5SA V6 Board (STM32F103ZE) +#define BOARD_CHITU3D_V9 4039 // Chitu3D TronXY X5SA V9 Board (STM32F103ZE) +#define BOARD_CREALITY_V4 4040 // Creality v4.x (STM32F103RC / STM32F103RE) +#define BOARD_CREALITY_V422 4041 // Creality v4.2.2 (STM32F103RC / STM32F103RE) +#define BOARD_CREALITY_V423 4042 // Creality v4.2.3 (STM32F103RC / STM32F103RE) +#define BOARD_CREALITY_V425 4043 // Creality v4.2.5 (STM32F103RC / STM32F103RE) +#define BOARD_CREALITY_V427 4044 // Creality v4.2.7 (STM32F103RC / STM32F103RE) +#define BOARD_CREALITY_V4210 4045 // Creality v4.2.10 (STM32F103RC / STM32F103RE) as found in the CR-30 +#define BOARD_CREALITY_V431 4046 // Creality v4.3.1 (STM32F103RC / STM32F103RE) +#define BOARD_CREALITY_V431_A 4047 // Creality v4.3.1a (STM32F103RC / STM32F103RE) +#define BOARD_CREALITY_V431_B 4048 // Creality v4.3.1b (STM32F103RC / STM32F103RE) +#define BOARD_CREALITY_V431_C 4049 // Creality v4.3.1c (STM32F103RC / STM32F103RE) +#define BOARD_CREALITY_V431_D 4050 // Creality v4.3.1d (STM32F103RC / STM32F103RE) +#define BOARD_CREALITY_V452 4051 // Creality v4.5.2 (STM32F103RC / STM32F103RE) +#define BOARD_CREALITY_V453 4052 // Creality v4.5.3 (STM32F103RC / STM32F103RE) +#define BOARD_CREALITY_V24S1 4053 // Creality v2.4.S1 (STM32F103RC / STM32F103RE) v101 as found in the Ender-7 +#define BOARD_CREALITY_V24S1_301 4054 // Creality v2.4.S1_301 (STM32F103RC / STM32F103RE) v301 as found in the Ender-3 S1 +#define BOARD_CREALITY_V25S1 4055 // Creality v2.5.S1 (STM32F103RE) as found in the CR-10 Smart Pro +#define BOARD_TRIGORILLA_PRO 4056 // Trigorilla Pro (STM32F103ZE) +#define BOARD_FLY_MINI 4057 // FLYmaker FLY MINI (STM32F103RC) +#define BOARD_FLSUN_HISPEED 4058 // FLSUN HiSpeedV1 (STM32F103VE) +#define BOARD_BEAST 4059 // STM32F103RE Libmaple-based controller +#define BOARD_MINGDA_MPX_ARM_MINI 4060 // STM32F103ZE Mingda MD-16 +#define BOARD_GTM32_PRO_VD 4061 // STM32F103VE controller +#define BOARD_ZONESTAR_ZM3E2 4062 // Zonestar ZM3E2 (STM32F103RC) +#define BOARD_ZONESTAR_ZM3E4 4063 // Zonestar ZM3E4 V1 (STM32F103VC) +#define BOARD_ZONESTAR_ZM3E4V2 4064 // Zonestar ZM3E4 V2 (STM32F103VC) +#define BOARD_ERYONE_ERY32_MINI 4065 // Eryone Ery32 mini (STM32F103VE) +#define BOARD_PANDA_PI_V29 4066 // Panda Pi V2.9 - Standalone (STM32F103RC) + +// +// ARM Cortex-M4F +// + +#define BOARD_TEENSY31_32 4100 // Teensy3.1 and Teensy3.2 +#define BOARD_TEENSY35_36 4101 // Teensy3.5 and Teensy3.6 + +// +// STM32 ARM Cortex-M4F +// + +#define BOARD_ARMED 4200 // Arm'ed STM32F4-based controller +#define BOARD_RUMBA32_V1_0 4201 // RUMBA32 STM32F446VE based controller from Aus3D +#define BOARD_RUMBA32_V1_1 4202 // RUMBA32 STM32F446VE based controller from Aus3D +#define BOARD_RUMBA32_MKS 4203 // RUMBA32 STM32F446VE based controller from Makerbase +#define BOARD_RUMBA32_BTT 4204 // RUMBA32 STM32F446VE based controller from BIGTREETECH +#define BOARD_BLACK_STM32F407VE 4205 // BLACK_STM32F407VE +#define BOARD_BLACK_STM32F407ZE 4206 // BLACK_STM32F407ZE +#define BOARD_STEVAL_3DP001V1 4207 // STEVAL-3DP001V1 3D PRINTER BOARD +#define BOARD_BTT_SKR_PRO_V1_1 4208 // BigTreeTech SKR Pro v1.1 (STM32F407ZG) +#define BOARD_BTT_SKR_PRO_V1_2 4209 // BigTreeTech SKR Pro v1.2 (STM32F407ZG) +#define BOARD_BTT_BTT002_V1_0 4210 // BigTreeTech BTT002 v1.0 (STM32F407VG) +#define BOARD_BTT_E3_RRF 4211 // BigTreeTech E3 RRF (STM32F407VG) +#define BOARD_BTT_SKR_V2_0_REV_A 4212 // BigTreeTech SKR v2.0 Rev A (STM32F407VG) +#define BOARD_BTT_SKR_V2_0_REV_B 4213 // BigTreeTech SKR v2.0 Rev B (STM32F407VG/STM32F429VG) +#define BOARD_BTT_GTR_V1_0 4214 // BigTreeTech GTR v1.0 (STM32F407IGT) +#define BOARD_BTT_OCTOPUS_V1_0 4215 // BigTreeTech Octopus v1.0 (STM32F446ZE) +#define BOARD_BTT_OCTOPUS_V1_1 4216 // BigTreeTech Octopus v1.1 (STM32F446ZE) +#define BOARD_BTT_OCTOPUS_PRO_V1_0 4217 // BigTreeTech Octopus Pro v1.0 (STM32F446ZE / STM32F429ZG) +#define BOARD_LERDGE_K 4218 // Lerdge K (STM32F407ZG) +#define BOARD_LERDGE_S 4219 // Lerdge S (STM32F407VE) +#define BOARD_LERDGE_X 4220 // Lerdge X (STM32F407VE) +#define BOARD_VAKE403D 4221 // VAkE 403D (STM32F446VE) +#define BOARD_FYSETC_S6 4222 // FYSETC S6 (STM32F446VE) +#define BOARD_FYSETC_S6_V2_0 4223 // FYSETC S6 v2.0 (STM32F446VE) +#define BOARD_FYSETC_SPIDER 4224 // FYSETC Spider (STM32F446VE) +#define BOARD_FLYF407ZG 4225 // FLYmaker FLYF407ZG (STM32F407ZG) +#define BOARD_MKS_ROBIN2 4226 // MKS_ROBIN2 (STM32F407ZE) +#define BOARD_MKS_ROBIN_PRO_V2 4227 // MKS Robin Pro V2 (STM32F407VE) +#define BOARD_MKS_ROBIN_NANO_V3 4228 // MKS Robin Nano V3 (STM32F407VG) +#define BOARD_MKS_ROBIN_NANO_V3_1 4229 // MKS Robin Nano V3.1 (STM32F407VE) +#define BOARD_MKS_MONSTER8_V1 4230 // MKS Monster8 V1 (STM32F407VE) +#define BOARD_MKS_MONSTER8_V2 4231 // MKS Monster8 V2 (STM32F407VE) +#define BOARD_ANET_ET4 4232 // ANET ET4 V1.x (STM32F407VG) +#define BOARD_ANET_ET4P 4233 // ANET ET4P V1.x (STM32F407VG) +#define BOARD_FYSETC_CHEETAH_V20 4234 // FYSETC Cheetah V2.0 (STM32F401RC) +#define BOARD_TH3D_EZBOARD_V2 4235 // TH3D EZBoard v2.0 (STM32F405RG) +#define BOARD_OPULO_LUMEN_REV3 4236 // Opulo Lumen PnP Controller REV3 (STM32F407VE / STM32F407VG) +#define BOARD_MKS_ROBIN_NANO_V1_3_F4 4237 // MKS Robin Nano V1.3 and MKS Robin Nano-S V1.3 (STM32F407VE) +#define BOARD_MKS_EAGLE 4238 // MKS Eagle (STM32F407VE) +#define BOARD_ARTILLERY_RUBY 4239 // Artillery Ruby (STM32F401RC) +#define BOARD_FYSETC_SPIDER_V2_2 4240 // FYSETC Spider V2.2 (STM32F446VE) +#define BOARD_CREALITY_V24S1_301F4 4241 // Creality v2.4.S1_301F4 (STM32F401RC) as found in the Ender-3 S1 F4 + +// +// ARM Cortex M7 +// + +#define BOARD_REMRAM_V1 5000 // RemRam v1 +#define BOARD_TEENSY41 5001 // Teensy 4.1 +#define BOARD_T41U5XBB 5002 // T41U5XBB Teensy 4.1 breakout board +#define BOARD_NUCLEO_F767ZI 5003 // ST NUCLEO-F767ZI Dev Board +#define BOARD_BTT_SKR_SE_BX_V2 5004 // BigTreeTech SKR SE BX V2.0 (STM32H743II) +#define BOARD_BTT_SKR_SE_BX_V3 5005 // BigTreeTech SKR SE BX V3.0 (STM32H743II) +#define BOARD_BTT_SKR_V3_0 5006 // BigTreeTech SKR V3.0 (STM32H743VG) +#define BOARD_BTT_SKR_V3_0_EZ 5007 // BigTreeTech SKR V3.0 EZ (STM32H743VG) + +// +// Espressif ESP32 WiFi +// + +#define BOARD_ESPRESSIF_ESP32 6000 // Generic ESP32 +#define BOARD_MRR_ESPA 6001 // MRR ESPA based on ESP32 (native pins only) +#define BOARD_MRR_ESPE 6002 // MRR ESPE based on ESP32 (with I2S stepper stream) +#define BOARD_E4D_BOX 6003 // E4d@BOX +#define BOARD_RESP32_CUSTOM 6004 // Rutilea ESP32 custom board +#define BOARD_FYSETC_E4 6005 // FYSETC E4 +#define BOARD_PANDA_ZHU 6006 // Panda_ZHU +#define BOARD_PANDA_M4 6007 // Panda_M4 +#define BOARD_MKS_TINYBEE 6008 // MKS TinyBee based on ESP32 (with I2S stepper stream) +#define BOARD_ENWI_ESPNP 6009 // enwi ESPNP based on ESP32 (with I2S stepper stream) + +// +// SAMD51 ARM Cortex M4 +// + +#define BOARD_AGCM4_RAMPS_144 6100 // RAMPS 1.4.4 +#define BOARD_BRICOLEMON_V1_0 6101 // Bricolemon +#define BOARD_BRICOLEMON_LITE_V1_0 6102 // Bricolemon Lite + +// +// Custom board +// + +#define BOARD_CUSTOM 9998 // Custom pins definition for development and/or rare boards + +// +// Simulations +// + +#define BOARD_LINUX_RAMPS 9999 + +#define _MB_1(B) (defined(BOARD_##B) && MOTHERBOARD==BOARD_##B) +#define MB(V...) DO(MB,||,V) diff --git a/src/core/bug_on.h b/src/core/bug_on.h new file mode 100644 index 0000000..7f1243e --- /dev/null +++ b/src/core/bug_on.h @@ -0,0 +1,39 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Copyright (c) 2021 X-Ryl669 [https://blog.cyril.by] + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +// We need SERIAL_ECHOPGM and macros.h +#include "serial.h" + +#if ENABLED(POSTMORTEM_DEBUGGING) + // Useful macro for stopping the CPU on an unexpected condition + // This is used like SERIAL_ECHOPGM, that is: a key-value call of the local variables you want + // to dump to the serial port before stopping the CPU. + // \/ Don't replace by SERIAL_ECHOPGM since ONLY_FILENAME cannot be transformed to a PGM string on Arduino and it breaks building + #define BUG_ON(V...) do { SERIAL_ECHO(ONLY_FILENAME); SERIAL_ECHO(__LINE__); SERIAL_ECHOLNPGM(": "); SERIAL_ECHOLNPGM(V); SERIAL_FLUSHTX(); *(char*)0 = 42; } while(0) +#elif ENABLED(MARLIN_DEV_MODE) + // Don't stop the CPU here, but at least dump the bug on the serial port + // \/ Don't replace by SERIAL_ECHOPGM since ONLY_FILENAME cannot be transformed to a PGM string on Arduino and it breaks building + #define BUG_ON(V...) do { SERIAL_ECHO(ONLY_FILENAME); SERIAL_ECHO(__LINE__); SERIAL_ECHOLNPGM(": BUG!"); SERIAL_ECHOLNPGM(V); SERIAL_FLUSHTX(); } while(0) +#else + // Release mode, let's ignore the bug + #define BUG_ON(V...) NOOP +#endif diff --git a/src/core/debug_out.h b/src/core/debug_out.h new file mode 100644 index 0000000..eb1c91e --- /dev/null +++ b/src/core/debug_out.h @@ -0,0 +1,120 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +// +// Serial aliases for debugging. +// Include this header after defining DEBUG_OUT +// (or not) in a given .cpp file +// + +#undef DEBUG_SECTION +#undef DEBUG_ECHO_START +#undef DEBUG_ERROR_START +#undef DEBUG_CHAR +#undef DEBUG_ECHO +#undef DEBUG_DECIMAL +#undef DEBUG_ECHO_F +#undef DEBUG_ECHOLN +#undef DEBUG_ECHOPGM +#undef DEBUG_ECHOLNPGM +#undef DEBUG_ECHOF +#undef DEBUG_ECHOLNF +#undef DEBUG_ECHOPGM_P +#undef DEBUG_ECHOLNPGM_P +#undef DEBUG_ECHOPAIR_F +#undef DEBUG_ECHOPAIR_F_P +#undef DEBUG_ECHOLNPAIR_F +#undef DEBUG_ECHOLNPAIR_F_P +#undef DEBUG_ECHO_MSG +#undef DEBUG_ERROR_MSG +#undef DEBUG_EOL +#undef DEBUG_FLUSH +#undef DEBUG_POS +#undef DEBUG_XYZ +#undef DEBUG_DELAY +#undef DEBUG_SYNCHRONIZE + +#if DEBUG_OUT + + #include "debug_section.h" + #define DEBUG_SECTION(N,S,D) SectionLog N(F(S),D) + + #define DEBUG_ECHO_START SERIAL_ECHO_START + #define DEBUG_ERROR_START SERIAL_ERROR_START + #define DEBUG_CHAR SERIAL_CHAR + #define DEBUG_ECHO SERIAL_ECHO + #define DEBUG_DECIMAL SERIAL_DECIMAL + #define DEBUG_ECHO_F SERIAL_ECHO_F + #define DEBUG_ECHOLN SERIAL_ECHOLN + #define DEBUG_ECHOPGM SERIAL_ECHOPGM + #define DEBUG_ECHOLNPGM SERIAL_ECHOLNPGM + #define DEBUG_ECHOF SERIAL_ECHOF + #define DEBUG_ECHOLNF SERIAL_ECHOLNF + #define DEBUG_ECHOPGM SERIAL_ECHOPGM + #define DEBUG_ECHOPGM_P SERIAL_ECHOPGM_P + #define DEBUG_ECHOPAIR_F SERIAL_ECHOPAIR_F + #define DEBUG_ECHOPAIR_F_P SERIAL_ECHOPAIR_F_P + #define DEBUG_ECHOLNPGM SERIAL_ECHOLNPGM + #define DEBUG_ECHOLNPGM_P SERIAL_ECHOLNPGM_P + #define DEBUG_ECHOLNPAIR_F SERIAL_ECHOLNPAIR_F + #define DEBUG_ECHOLNPAIR_F_P SERIAL_ECHOLNPAIR_F_P + #define DEBUG_ECHO_MSG SERIAL_ECHO_MSG + #define DEBUG_ERROR_MSG SERIAL_ERROR_MSG + #define DEBUG_EOL SERIAL_EOL + #define DEBUG_FLUSH SERIAL_FLUSH + #define DEBUG_POS SERIAL_POS + #define DEBUG_XYZ SERIAL_XYZ + #define DEBUG_DELAY(ms) serial_delay(ms) + #define DEBUG_SYNCHRONIZE() planner.synchronize() + +#else + + #define DEBUG_SECTION(...) NOOP + #define DEBUG_ECHO_START() NOOP + #define DEBUG_ERROR_START() NOOP + #define DEBUG_CHAR(...) NOOP + #define DEBUG_ECHO(...) NOOP + #define DEBUG_DECIMAL(...) NOOP + #define DEBUG_ECHO_F(...) NOOP + #define DEBUG_ECHOLN(...) NOOP + #define DEBUG_ECHOPGM(...) NOOP + #define DEBUG_ECHOLNPGM(...) NOOP + #define DEBUG_ECHOF(...) NOOP + #define DEBUG_ECHOLNF(...) NOOP + #define DEBUG_ECHOPGM_P(...) NOOP + #define DEBUG_ECHOLNPGM_P(...) NOOP + #define DEBUG_ECHOPAIR_F(...) NOOP + #define DEBUG_ECHOPAIR_F_P(...) NOOP + #define DEBUG_ECHOLNPAIR_F(...) NOOP + #define DEBUG_ECHOLNPAIR_F_P(...) NOOP + #define DEBUG_ECHO_MSG(...) NOOP + #define DEBUG_ERROR_MSG(...) NOOP + #define DEBUG_EOL() NOOP + #define DEBUG_FLUSH() NOOP + #define DEBUG_POS(...) NOOP + #define DEBUG_XYZ(...) NOOP + #define DEBUG_DELAY(...) NOOP + #define DEBUG_SYNCHRONIZE() NOOP + +#endif + +#undef DEBUG_OUT diff --git a/src/core/debug_section.h b/src/core/debug_section.h new file mode 100644 index 0000000..6e23d9e --- /dev/null +++ b/src/core/debug_section.h @@ -0,0 +1,49 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "serial.h" +#include "../module/motion.h" + +class SectionLog { +public: + SectionLog(FSTR_P const fmsg=nullptr, bool inbug=true) { + the_msg = fmsg; + if ((debug = inbug)) echo_msg(F(">>>")); + } + + ~SectionLog() { if (debug) echo_msg(F("<<<")); } + +private: + FSTR_P the_msg; + bool debug; + + void echo_msg(FSTR_P const fpre) { + SERIAL_ECHOF(fpre); + if (the_msg) { + SERIAL_CHAR(' '); + SERIAL_ECHOF(the_msg); + } + SERIAL_CHAR(' '); + print_pos(current_position); + } +}; diff --git a/src/core/drivers.h b/src/core/drivers.h new file mode 100644 index 0000000..f6a8f0f --- /dev/null +++ b/src/core/drivers.h @@ -0,0 +1,203 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +// +// Included by MarlinConfigPre.h ahead of Configuration_adv.h. +// Don't use #if in this file for anything not defined early! +// + +#define _A4988 0x4988 +#define _A5984 0x5984 +#define _DRV8825 0x8825 +#define _LV8729 0x8729 +#define _L6470 0x6470 +#define _L6474 0x6474 +#define _L6480 0x6480 +#define _POWERSTEP01 0xF00D +#define _TB6560 0x6560 +#define _TB6600 0x6600 +#define _TMC2100 0x2100 +#define _TMC2130 0x2130A +#define _TMC2130_STANDALONE 0x2130B +#define _TMC2160 0x2160A +#define _TMC2160_STANDALONE 0x2160B +#define _TMC2208 0x2208A +#define _TMC2208_STANDALONE 0x2208B +#define _TMC2209 0x2209A +#define _TMC2209_STANDALONE 0x2209B +#define _TMC26X 0x2600A +#define _TMC26X_STANDALONE 0x2600B +#define _TMC2660 0x2660A +#define _TMC2660_STANDALONE 0x2660B +#define _TMC5130 0x5130A +#define _TMC5130_STANDALONE 0x5130B +#define _TMC5160 0x5160A +#define _TMC5160_STANDALONE 0x5160B + +#define _DRIVER_ID(V) _CAT(_, V) +#define _AXIS_DRIVER_TYPE(A,T) (_DRIVER_ID(A##_DRIVER_TYPE) == _DRIVER_ID(T)) + +#define AXIS_DRIVER_TYPE_X(T) _AXIS_DRIVER_TYPE(X,T) +#define AXIS_DRIVER_TYPE_Y(T) _AXIS_DRIVER_TYPE(Y,T) +#define AXIS_DRIVER_TYPE_Z(T) _AXIS_DRIVER_TYPE(Z,T) +#define AXIS_DRIVER_TYPE_I(T) _AXIS_DRIVER_TYPE(I,T) +#define AXIS_DRIVER_TYPE_J(T) _AXIS_DRIVER_TYPE(J,T) +#define AXIS_DRIVER_TYPE_K(T) _AXIS_DRIVER_TYPE(K,T) + +#define AXIS_DRIVER_TYPE_X2(T) (HAS_X2_STEPPER && _AXIS_DRIVER_TYPE(X2,T)) +#define AXIS_DRIVER_TYPE_Y2(T) (HAS_DUAL_Y_STEPPERS && _AXIS_DRIVER_TYPE(Y2,T)) +#define AXIS_DRIVER_TYPE_Z2(T) (NUM_Z_STEPPERS >= 2 && _AXIS_DRIVER_TYPE(Z2,T)) +#define AXIS_DRIVER_TYPE_Z3(T) (NUM_Z_STEPPERS >= 3 && _AXIS_DRIVER_TYPE(Z3,T)) +#define AXIS_DRIVER_TYPE_Z4(T) (NUM_Z_STEPPERS >= 4 && _AXIS_DRIVER_TYPE(Z4,T)) + +#define AXIS_DRIVER_TYPE_E(N,T) (E_STEPPERS > N && _AXIS_DRIVER_TYPE(E##N,T)) +#define AXIS_DRIVER_TYPE_E0(T) AXIS_DRIVER_TYPE_E(0,T) +#define AXIS_DRIVER_TYPE_E1(T) AXIS_DRIVER_TYPE_E(1,T) +#define AXIS_DRIVER_TYPE_E2(T) AXIS_DRIVER_TYPE_E(2,T) +#define AXIS_DRIVER_TYPE_E3(T) AXIS_DRIVER_TYPE_E(3,T) +#define AXIS_DRIVER_TYPE_E4(T) AXIS_DRIVER_TYPE_E(4,T) +#define AXIS_DRIVER_TYPE_E5(T) AXIS_DRIVER_TYPE_E(5,T) +#define AXIS_DRIVER_TYPE_E6(T) AXIS_DRIVER_TYPE_E(6,T) +#define AXIS_DRIVER_TYPE_E7(T) AXIS_DRIVER_TYPE_E(7,T) + +#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T) + +#define _OR_ADTE(N,T) || AXIS_DRIVER_TYPE_E(N,T) +#define HAS_E_DRIVER(T) (0 RREPEAT2(E_STEPPERS, _OR_ADTE, T)) + +#define HAS_DRIVER(T) ( AXIS_DRIVER_TYPE_X(T) || AXIS_DRIVER_TYPE_Y(T) || AXIS_DRIVER_TYPE_Z(T) \ + || AXIS_DRIVER_TYPE_I(T) || AXIS_DRIVER_TYPE_J(T) || AXIS_DRIVER_TYPE_K(T) \ + || AXIS_DRIVER_TYPE_X2(T) || AXIS_DRIVER_TYPE_Y2(T) || AXIS_DRIVER_TYPE_Z2(T) \ + || AXIS_DRIVER_TYPE_Z3(T) || AXIS_DRIVER_TYPE_Z4(T) || HAS_E_DRIVER(T) ) + +// +// Trinamic Stepper Drivers +// + +// Test for supported TMC drivers that require advanced configuration +// Does not match standalone configurations +#if ( HAS_DRIVER(TMC2130) || HAS_DRIVER(TMC2160) \ + || HAS_DRIVER(TMC2208) || HAS_DRIVER(TMC2209) \ + || HAS_DRIVER(TMC2660) \ + || HAS_DRIVER(TMC5130) || HAS_DRIVER(TMC5160) ) + #define HAS_TRINAMIC_CONFIG 1 +#endif + +#define HAS_TRINAMIC HAS_TRINAMIC_CONFIG + +#if ( HAS_DRIVER(TMC2130_STANDALONE) || HAS_DRIVER(TMC2160_STANDALONE) \ + || HAS_DRIVER(TMC2208_STANDALONE) || HAS_DRIVER(TMC2209_STANDALONE) \ + || HAS_DRIVER(TMC26X_STANDALONE) || HAS_DRIVER(TMC2660_STANDALONE) \ + || HAS_DRIVER(TMC5130_STANDALONE) || HAS_DRIVER(TMC5160_STANDALONE) ) + #define HAS_TRINAMIC_STANDALONE 1 +#endif + +#if HAS_DRIVER(TMC2130) || HAS_DRIVER(TMC2160) || HAS_DRIVER(TMC5130) || HAS_DRIVER(TMC5160) + #define HAS_TMCX1X0 1 +#endif + +#if HAS_DRIVER(TMC2208) || HAS_DRIVER(TMC2209) + #define HAS_TMC220x 1 +#endif + +#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130) || AXIS_DRIVER_TYPE(A,TMC2160) \ + || AXIS_DRIVER_TYPE(A,TMC2208) || AXIS_DRIVER_TYPE(A,TMC2209) \ + || AXIS_DRIVER_TYPE(A,TMC2660) \ + || AXIS_DRIVER_TYPE(A,TMC5130) || AXIS_DRIVER_TYPE(A,TMC5160) ) + +// Test for a driver that uses SPI - this allows checking whether a _CS_ pin +// is considered sensitive +#define AXIS_HAS_SPI(A) ( AXIS_DRIVER_TYPE(A,TMC2130) || AXIS_DRIVER_TYPE(A,TMC2160) \ + || AXIS_DRIVER_TYPE(A,TMC26X) || AXIS_DRIVER_TYPE(A,TMC2660) \ + || AXIS_DRIVER_TYPE(A,TMC5130) || AXIS_DRIVER_TYPE(A,TMC5160) ) + +#define AXIS_HAS_UART(A) ( AXIS_DRIVER_TYPE(A,TMC2208) || AXIS_DRIVER_TYPE(A,TMC2209) ) + +#define AXIS_HAS_RXTX AXIS_HAS_UART + +#define AXIS_HAS_HW_SERIAL(A) ( AXIS_HAS_UART(A) && defined(A##_HARDWARE_SERIAL) ) +#define AXIS_HAS_SW_SERIAL(A) ( AXIS_HAS_UART(A) && !defined(A##_HARDWARE_SERIAL) ) + +#define AXIS_HAS_STALLGUARD(A) ( AXIS_DRIVER_TYPE(A,TMC2130) || AXIS_DRIVER_TYPE(A,TMC2160) \ + || AXIS_DRIVER_TYPE(A,TMC2209) \ + || AXIS_DRIVER_TYPE(A,TMC2660) \ + || AXIS_DRIVER_TYPE(A,TMC5130) || AXIS_DRIVER_TYPE(A,TMC5160) ) + +#define AXIS_HAS_STEALTHCHOP(A) ( AXIS_DRIVER_TYPE(A,TMC2130) || AXIS_DRIVER_TYPE(A,TMC2160) \ + || AXIS_DRIVER_TYPE(A,TMC2208) || AXIS_DRIVER_TYPE(A,TMC2209) \ + || AXIS_DRIVER_TYPE(A,TMC5130) || AXIS_DRIVER_TYPE(A,TMC5160) ) + +#define AXIS_HAS_SG_RESULT(A) ( AXIS_DRIVER_TYPE(A,TMC2130) || AXIS_DRIVER_TYPE(A,TMC2160) \ + || AXIS_DRIVER_TYPE(A,TMC2208) || AXIS_DRIVER_TYPE(A,TMC2209) ) + +#define AXIS_HAS_COOLSTEP(A) ( AXIS_DRIVER_TYPE(A,TMC2130) \ + || AXIS_DRIVER_TYPE(A,TMC2209) \ + || AXIS_DRIVER_TYPE(A,TMC5130) || AXIS_DRIVER_TYPE(A,TMC5160) ) + +#define _OR_EAH(N,T) || AXIS_HAS_##T(E##N) +#define E_AXIS_HAS(T) (0 _OR_EAH(0,T) _OR_EAH(1,T) _OR_EAH(2,T) _OR_EAH(3,T) _OR_EAH(4,T) _OR_EAH(5,T) _OR_EAH(6,T) _OR_EAH(7,T)) + +#define ANY_AXIS_HAS(T) ( AXIS_HAS_##T(X) || AXIS_HAS_##T(X2) \ + || AXIS_HAS_##T(Y) || AXIS_HAS_##T(Y2) \ + || AXIS_HAS_##T(Z) || AXIS_HAS_##T(Z2) || AXIS_HAS_##T(Z3) || AXIS_HAS_##T(Z4) \ + || AXIS_HAS_##T(I) || AXIS_HAS_##T(J) || AXIS_HAS_##T(K) \ + || E_AXIS_HAS(T) ) + +#if ANY_AXIS_HAS(STEALTHCHOP) + #define HAS_STEALTHCHOP 1 +#endif +#if ANY_AXIS_HAS(STALLGUARD) + #define HAS_STALLGUARD 1 +#endif +#if ANY_AXIS_HAS(SG_RESULT) + #define HAS_SG_RESULT 1 +#endif +#if ANY_AXIS_HAS(COOLSTEP) + #define HAS_COOLSTEP 1 +#endif +#if ANY_AXIS_HAS(RXTX) + #define HAS_TMC_UART 1 +#endif +#if ANY_AXIS_HAS(SPI) + #define HAS_TMC_SPI 1 +#endif + +// +// TMC26XX Stepper Drivers +// +#if HAS_DRIVER(TMC26X) + #define HAS_TMC26X 1 +#endif + +// +// L64XX Stepper Drivers +// + +#if HAS_DRIVER(L6470) || HAS_DRIVER(L6474) || HAS_DRIVER(L6480) || HAS_DRIVER(POWERSTEP01) + #define HAS_L64XX 1 +#endif +#if HAS_L64XX && !HAS_DRIVER(L6474) + #define HAS_L64XX_NOT_L6474 1 +#endif + +#define AXIS_IS_L64XX(A) (AXIS_DRIVER_TYPE_##A(L6470) || AXIS_DRIVER_TYPE_##A(L6474) || AXIS_DRIVER_TYPE_##A(L6480) || AXIS_DRIVER_TYPE_##A(POWERSTEP01)) diff --git a/src/core/language.h b/src/core/language.h new file mode 100644 index 0000000..f225f91 --- /dev/null +++ b/src/core/language.h @@ -0,0 +1,564 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" + +#define _UxGT(a) a + +// Fallback if no language is set. DON'T CHANGE +#ifndef LCD_LANGUAGE + #define LCD_LANGUAGE en +#endif + +// For character-based LCD controllers (DISPLAY_CHARSET_HD44780) +#define JAPANESE 1 +#define WESTERN 2 +#define CYRILLIC 3 + +// NOTE: IF YOU CHANGE LANGUAGE FILES OR MERGE A FILE WITH CHANGES +// +// ==> ALWAYS TRY TO COMPILE MARLIN WITH/WITHOUT "ULTIPANEL" / "ULTRA_LCD" / "SDSUPPORT" #define IN "Configuration.h" +// ==> ALSO TRY ALL AVAILABLE LANGUAGE OPTIONS +// See also https://marlinfw.org/docs/development/lcd_language.html + +// Languages +// an Aragonese +// bg Bulgarian +// ca Catalan +// cz Czech +// da Danish +// de German +// el Greek (Greece) +// el_CY Greek (Cyprus) +// en English +// es Spanish +// eu Basque-Euskera +// fi Finnish +// fr French +// gl Galician +// hr Croatian +// hu Hungarian +// it Italian +// jp_kana Japanese +// ko_KR Korean (South Korea) +// nl Dutch +// pl Polish +// pt Portuguese +// pt_br Portuguese (Brazilian) +// ro Romanian +// ru Russian +// sk Slovak +// sv Swedish +// tr Turkish +// uk Ukrainian +// vi Vietnamese +// zh_CN Chinese (Simplified) +// zh_TW Chinese (Traditional) + +#ifdef DEFAULT_SOURCE_CODE_URL + #undef SOURCE_CODE_URL + #define SOURCE_CODE_URL DEFAULT_SOURCE_CODE_URL +#endif + +#ifdef CUSTOM_MACHINE_NAME + #undef MACHINE_NAME + #define MACHINE_NAME CUSTOM_MACHINE_NAME +#elif defined(DEFAULT_MACHINE_NAME) + #undef MACHINE_NAME + #define MACHINE_NAME DEFAULT_MACHINE_NAME +#endif + +#ifndef MACHINE_UUID + #define MACHINE_UUID DEFAULT_MACHINE_UUID +#endif + +#define MARLIN_WEBSITE_URL "marlinfw.org" + +//#if !defined(STRING_SPLASH_LINE3) && defined(WEBSITE_URL) +// #define STRING_SPLASH_LINE3 WEBSITE_URL +//#endif + +// +// Common Serial Console Messages +// Don't change these strings because serial hosts look for them. +// + +#define STR_ENQUEUEING "enqueueing \"" +#define STR_POWERUP "PowerUp" +#define STR_POWEROFF "PowerOff" +#define STR_EXTERNAL_RESET " External Reset" +#define STR_BROWNOUT_RESET " Brown out Reset" +#define STR_WATCHDOG_RESET " Watchdog Reset" +#define STR_SOFTWARE_RESET " Software Reset" +#define STR_FREE_MEMORY " Free Memory: " +#define STR_PLANNER_BUFFER_BYTES " PlannerBufferBytes: " +#define STR_OK "ok" +#define STR_WAIT "wait" +#define STR_STATS "Stats: " +#define STR_FILE_SAVED "Done saving file." +#define STR_ERR_LINE_NO "Line Number is not Last Line Number+1, Last Line: " +#define STR_ERR_CHECKSUM_MISMATCH "checksum mismatch, Last Line: " +#define STR_ERR_NO_CHECKSUM "No Checksum with line number, Last Line: " +#define STR_FILE_PRINTED "Done printing file" +#define STR_NO_MEDIA "No media" +#define STR_BEGIN_FILE_LIST "Begin file list" +#define STR_END_FILE_LIST "End file list" +#define STR_INVALID_EXTRUDER "Invalid extruder" +#define STR_INVALID_E_STEPPER "Invalid E stepper" +#define STR_E_STEPPER_NOT_SPECIFIED "E stepper not specified" +#define STR_INVALID_SOLENOID "Invalid solenoid" +#define STR_COUNT_X " Count X:" +#define STR_COUNT_A " Count A:" +#define STR_WATCHDOG_FIRED "Watchdog timeout. Reset required." +#define STR_ERR_KILLED "Printer halted. kill() called!" +#define STR_FLOWMETER_FAULT "Coolant flow fault. Flowmeter safety is active. Attention required." +#define STR_ERR_STOPPED "Printer stopped due to errors. Fix the error and use M999 to restart. (Temperature is reset. Set it after restarting)" +#define STR_ERR_SERIAL_MISMATCH "Serial status mismatch" +#define STR_BUSY_PROCESSING "busy: processing" +#define STR_BUSY_PAUSED_FOR_USER "busy: paused for user" +#define STR_BUSY_PAUSED_FOR_INPUT "busy: paused for input" +#define STR_Z_MOVE_COMP "Z_move_comp" +#define STR_RESEND "Resend: " +#define STR_UNKNOWN_COMMAND "Unknown command: \"" +#define STR_ACTIVE_EXTRUDER "Active Extruder: " +#define STR_ERR_FANSPEED "Fan speed E" + +#define STR_PROBE_OFFSET "Probe Offset" +#define STR_SKEW_MIN "min_skew_factor: " +#define STR_SKEW_MAX "max_skew_factor: " +#define STR_ERR_MATERIAL_INDEX "M145 S out of range (0-1)" +#define STR_ERR_M421_PARAMETERS "M421 incorrect parameter usage" +#define STR_ERR_BAD_PLANE_MODE "G5 requires XY plane mode" +#define STR_ERR_MESH_XY "Mesh point out of range" +#define STR_ERR_ARC_ARGS "G2/G3 bad parameters" +#define STR_ERR_PROTECTED_PIN "Protected Pin" +#define STR_ERR_M420_FAILED "Failed to enable Bed Leveling" +#define STR_ERR_M428_TOO_FAR "Too far from reference point" +#define STR_ERR_M303_DISABLED "PIDTEMP disabled" +#define STR_M119_REPORT "Reporting endstop status" +#define STR_ON "ON" +#define STR_OFF "OFF" +#define STR_ENDSTOP_HIT "TRIGGERED" +#define STR_ENDSTOP_OPEN "open" +#define STR_DUPLICATION_MODE "Duplication mode: " +#define STR_SOFT_MIN " Min: " +#define STR_SOFT_MAX " Max: " + +#define STR_SAVED_POS "Position saved" +#define STR_RESTORING_POS "Restoring position" +#define STR_INVALID_POS_SLOT "Invalid slot. Total: " +#define STR_DONE "Done." + +#define STR_SD_CANT_OPEN_SUBDIR "Cannot open subdir " +#define STR_SD_INIT_FAIL "No SD card" +#define STR_SD_VOL_INIT_FAIL "volume.init failed" +#define STR_SD_OPENROOT_FAIL "openRoot failed" +#define STR_SD_CARD_OK "SD card ok" +#define STR_SD_WORKDIR_FAIL "workDir open failed" +#define STR_SD_OPEN_FILE_FAIL "open failed, File: " +#define STR_SD_FILE_OPENED "File opened: " +#define STR_SD_SIZE " Size: " +#define STR_SD_FILE_SELECTED "File selected" +#define STR_SD_WRITE_TO_FILE "Writing to file: " +#define STR_SD_PRINTING_BYTE "SD printing byte " +#define STR_SD_NOT_PRINTING "Not SD printing" +#define STR_SD_ERR_WRITE_TO_FILE "error writing to file" +#define STR_SD_ERR_READ "SD read error" +#define STR_SD_CANT_ENTER_SUBDIR "Cannot enter subdir: " + +#define STR_ENDSTOPS_HIT "endstops hit: " +#define STR_ERR_COLD_EXTRUDE_STOP " cold extrusion prevented" +#define STR_ERR_LONG_EXTRUDE_STOP " too long extrusion prevented" +#define STR_ERR_HOTEND_TOO_COLD "Hotend too cold" +#define STR_ERR_EEPROM_WRITE "Error writing to EEPROM!" + +#define STR_FILAMENT_CHANGE_HEAT_LCD "Press button to heat nozzle" +#define STR_FILAMENT_CHANGE_INSERT_LCD "Insert filament and press button" +#define STR_FILAMENT_CHANGE_WAIT_LCD "Press button to resume" +#define STR_FILAMENT_CHANGE_HEAT_M108 "Send M108 to heat nozzle" +#define STR_FILAMENT_CHANGE_INSERT_M108 "Insert filament and send M108" +#define STR_FILAMENT_CHANGE_WAIT_M108 "Send M108 to resume" + +#define STR_STOP_PRE "!! STOP called because of " +#define STR_STOP_POST " error - restart with M999" +#define STR_STOP_BLTOUCH "BLTouch" +#define STR_STOP_UNHOMED "unhomed" +#define STR_KILL_PRE "!! KILL caused by " +#define STR_KILL_INACTIVE_TIME "too much inactive time - current command: " +#define STR_KILL_BUTTON "KILL button/pin" + +// temperature.cpp strings +#define STR_PID_AUTOTUNE "PID Autotune" +#define STR_PID_AUTOTUNE_START " start" +#define STR_PID_BAD_HEATER_ID " failed! Bad heater id" +#define STR_PID_TEMP_TOO_HIGH " failed! Temperature too high" +#define STR_PID_TIMEOUT " failed! timeout" +#define STR_BIAS " bias: " +#define STR_D_COLON " d: " +#define STR_T_MIN " min: " +#define STR_T_MAX " max: " +#define STR_KU " Ku: " +#define STR_TU " Tu: " +#define STR_CLASSIC_PID " Classic PID " +#define STR_KP " Kp: " +#define STR_KI " Ki: " +#define STR_KD " Kd: " +#define STR_PID_AUTOTUNE_FINISHED " finished! Put the last Kp, Ki and Kd constants from below into Configuration.h" +#define STR_PID_DEBUG " PID_DEBUG " +#define STR_PID_DEBUG_INPUT ": Input " +#define STR_PID_DEBUG_OUTPUT " Output " +#define STR_INVALID_EXTRUDER_NUM " - Invalid extruder number !" +#define STR_MPC_AUTOTUNE "MPC Autotune" +#define STR_MPC_AUTOTUNE_START " start for " STR_E +#define STR_MPC_AUTOTUNE_INTERRUPTED " interrupted!" +#define STR_MPC_AUTOTUNE_FINISHED " finished! Put the constants below into Configuration.h" +#define STR_MPC_COOLING_TO_AMBIENT "Cooling to ambient" +#define STR_MPC_HEATING_PAST_200 "Heating to over 200C" +#define STR_MPC_MEASURING_AMBIENT "Measuring ambient heatloss at " +#define STR_MPC_TEMPERATURE_ERROR "Temperature error" + +#define STR_HEATER_BED "bed" +#define STR_HEATER_CHAMBER "chamber" +#define STR_COOLER "cooler" +#define STR_MOTHERBOARD "motherboard" +#define STR_PROBE "probe" +#define STR_REDUNDANT "redundant " +#define STR_LASER_TEMP "laser temperature" + +#define STR_STOPPED_HEATER ", system stopped! Heater_ID: " +#define STR_REDUNDANCY "Heater switched off. Temperature difference between temp sensors is too high !" +#define STR_T_HEATING_FAILED "Heating failed" +#define STR_T_THERMAL_RUNAWAY "Thermal Runaway" +#define STR_T_MALFUNCTION "Thermal Malfunction" +#define STR_T_MAXTEMP "MAXTEMP triggered" +#define STR_T_MINTEMP "MINTEMP triggered" +#define STR_ERR_PROBING_FAILED "Probing Failed" +#define STR_ZPROBE_OUT_SER "Z Probe Past Bed" + +// Debug +#define STR_DEBUG_PREFIX "DEBUG:" +#define STR_DEBUG_OFF "off" +#define STR_DEBUG_ECHO "ECHO" +#define STR_DEBUG_INFO "INFO" +#define STR_DEBUG_ERRORS "ERRORS" +#define STR_DEBUG_DRYRUN "DRYRUN" +#define STR_DEBUG_COMMUNICATION "COMMUNICATION" +#define STR_DEBUG_DETAIL "DETAIL" + +#define STR_PRINTER_LOCKED "Printer locked! (Unlock with M511 or LCD)" +#define STR_WRONG_PASSWORD "Incorrect Password" +#define STR_PASSWORD_TOO_LONG "Password too long" +#define STR_PASSWORD_REMOVED "Password removed" +#define STR_REMINDER_SAVE_SETTINGS "Remember to save!" +#define STR_PASSWORD_SET "Password is " + +// Settings Report Strings +#define STR_Z_AUTO_ALIGN "Z Auto-Align" +#define STR_BACKLASH_COMPENSATION "Backlash compensation" +#define STR_S_SEG_PER_SEC "S" +#define STR_DELTA_SETTINGS "Delta (L R H S XYZ ABC)" +#define STR_SCARA_SETTINGS "SCARA" +#define STR_POLARGRAPH_SETTINGS "Polargraph" +#define STR_SCARA_P_T_Z "P T Z" +#define STR_ENDSTOP_ADJUSTMENT "Endstop adjustment" +#define STR_SKEW_FACTOR "Skew Factor" +#define STR_FILAMENT_SETTINGS "Filament settings" +#define STR_MAX_ACCELERATION "Max Acceleration (units/s2)" +#define STR_MAX_FEEDRATES "Max feedrates (units/s)" +#define STR_ACCELERATION_P_R_T "Acceleration (units/s2) (P R T)" +#define STR_TOOL_CHANGING "Tool-changing" +#define STR_HOTEND_OFFSETS "Hotend offsets" +#define STR_SERVO_ANGLES "Servo Angles" +#define STR_HOTEND_PID "Hotend PID" +#define STR_BED_PID "Bed PID" +#define STR_CHAMBER_PID "Chamber PID" +#define STR_STEPS_PER_UNIT "Steps per unit" +#define STR_LINEAR_ADVANCE "Linear Advance" +#define STR_CONTROLLER_FAN "Controller Fan" +#define STR_STEPPER_MOTOR_CURRENTS "Stepper motor currents" +#define STR_RETRACT_S_F_Z "Retract (S F Z)" +#define STR_RECOVER_S_F "Recover (S F)" +#define STR_AUTO_RETRACT_S "Auto-Retract (S)" +#define STR_FILAMENT_LOAD_UNLOAD "Filament load/unload" +#define STR_POWER_LOSS_RECOVERY "Power-loss recovery" +#define STR_FILAMENT_RUNOUT_SENSOR "Filament runout sensor" +#define STR_DRIVER_STEPPING_MODE "Driver stepping mode" +#define STR_STEPPER_DRIVER_CURRENT "Stepper driver current" +#define STR_HYBRID_THRESHOLD "Hybrid Threshold" +#define STR_STALLGUARD_THRESHOLD "StallGuard threshold" +#define STR_HOME_OFFSET "Home offset" +#define STR_SOFT_ENDSTOPS "Soft endstops" +#define STR_MATERIAL_HEATUP "Material heatup parameters" +#define STR_LCD_CONTRAST "LCD Contrast" +#define STR_LCD_BRIGHTNESS "LCD Brightness" +#define STR_DISPLAY_SLEEP "Display Sleep" +#define STR_UI_LANGUAGE "UI Language" +#define STR_Z_PROBE_OFFSET "Z-Probe Offset" +#define STR_TEMPERATURE_UNITS "Temperature Units" +#define STR_USER_THERMISTORS "User thermistors" +#define STR_DELAYED_POWEROFF "Delayed poweroff" + +// +// Endstop Names used by Endstops::report_states +// +#define STR_X_MIN "x_min" +#define STR_X_MAX "x_max" +#define STR_X2_MIN "x2_min" +#define STR_X2_MAX "x2_max" + +#if HAS_Y_AXIS + #define STR_Y_MIN "y_min" + #define STR_Y_MAX "y_max" + #define STR_Y2_MIN "y2_min" + #define STR_Y2_MAX "y2_max" +#endif + +#if HAS_Z_AXIS + #define STR_Z_MIN "z_min" + #define STR_Z_MAX "z_max" + #define STR_Z2_MIN "z2_min" + #define STR_Z2_MAX "z2_max" + #define STR_Z3_MIN "z3_min" + #define STR_Z3_MAX "z3_max" + #define STR_Z4_MIN "z4_min" + #define STR_Z4_MAX "z4_max" +#endif + +#define STR_Z_PROBE "z_probe" +#define STR_PROBE_EN "probe_en" +#define STR_FILAMENT "filament" + +// General axis names +#define STR_X "X" +#define STR_Y "Y" +#define STR_Z "Z" +#define STR_E "E" +#if IS_KINEMATIC + #define STR_A "A" + #define STR_B "B" + #define STR_C "C" +#else + #define STR_A "X" + #define STR_B "Y" + #define STR_C "Z" +#endif +#define STR_X2 "X2" +#define STR_Y2 "Y2" +#define STR_Z2 "Z2" +#define STR_Z3 "Z3" +#define STR_Z4 "Z4" + +// Extra Axis and Endstop Names +#if HAS_I_AXIS + #if AXIS4_NAME == 'A' + #define STR_I "A" + #define STR_I_MIN "a_min" + #define STR_I_MAX "a_max" + #elif AXIS4_NAME == 'B' + #define STR_I "B" + #define STR_I_MIN "b_min" + #define STR_I_MAX "b_max" + #elif AXIS4_NAME == 'C' + #define STR_I "C" + #define STR_I_MIN "c_min" + #define STR_I_MAX "c_max" + #elif AXIS4_NAME == 'U' + #define STR_I "U" + #define STR_I_MIN "u_min" + #define STR_I_MAX "u_max" + #elif AXIS4_NAME == 'V' + #define STR_I "V" + #define STR_I_MIN "v_min" + #define STR_I_MAX "v_max" + #elif AXIS4_NAME == 'W' + #define STR_I "W" + #define STR_I_MIN "w_min" + #define STR_I_MAX "w_max" + #else + #error "AXIS4_NAME can only be one of 'A', 'B', 'C', 'U', 'V', or 'W'." + #endif +#else + #define STR_I "" +#endif + +#if HAS_J_AXIS + #if AXIS5_NAME == 'B' + #define STR_J "B" + #define STR_J_MIN "b_min" + #define STR_J_MAX "b_max" + #elif AXIS5_NAME == 'C' + #define STR_J "C" + #define STR_J_MIN "c_min" + #define STR_J_MAX "c_max" + #elif AXIS5_NAME == 'U' + #define STR_J "U" + #define STR_J_MIN "u_min" + #define STR_J_MAX "u_max" + #elif AXIS5_NAME == 'V' + #define STR_J "V" + #define STR_J_MIN "v_min" + #define STR_J_MAX "v_max" + #elif AXIS5_NAME == 'W' + #define STR_J "W" + #define STR_J_MIN "w_min" + #define STR_J_MAX "w_max" + #else + #error "AXIS5_NAME can only be one of 'B', 'C', 'U', 'V', or 'W'." + #endif +#else + #define STR_J "" +#endif + +#if HAS_K_AXIS + #if AXIS6_NAME == 'C' + #define STR_K "C" + #define STR_K_MIN "c_min" + #define STR_K_MAX "c_max" + #elif AXIS6_NAME == 'U' + #define STR_K "U" + #define STR_K_MIN "u_min" + #define STR_K_MAX "u_max" + #elif AXIS6_NAME == 'V' + #define STR_K "V" + #define STR_K_MIN "v_min" + #define STR_K_MAX "v_max" + #elif AXIS6_NAME == 'W' + #define STR_K "W" + #define STR_K_MIN "w_min" + #define STR_K_MAX "w_max" + #else + #error "AXIS6_NAME can only be one of 'C', 'U', 'V', or 'W'." + #endif +#else + #define STR_K "" +#endif + +#if EITHER(HAS_MARLINUI_HD44780, IS_TFTGLCD_PANEL) + + // Custom characters defined in the first 8 characters of the LCD + #define LCD_STR_BEDTEMP "\x00" // Print only as a char. This will have 'unexpected' results when used in a string! + #define LCD_STR_DEGREE "\x01" + #define LCD_STR_THERMOMETER "\x02" // Still used with string concatenation + #define LCD_STR_UPLEVEL "\x03" + #define LCD_STR_REFRESH "\x04" + #define LCD_STR_FOLDER "\x05" + #define LCD_STR_FEEDRATE "\x06" + #define LCD_STR_CLOCK "\x07" + #define LCD_STR_ARROW_RIGHT ">" /* from the default character set */ + +#else + // + // Custom characters from Marlin_symbols.fon which was merged into ISO10646-0-3.bdf + // \x00 intentionally skipped to avoid problems in strings + // + #define LCD_STR_REFRESH "\x01" + #define LCD_STR_FOLDER "\x02" + #define LCD_STR_ARROW_RIGHT "\x03" + #define LCD_STR_UPLEVEL "\x04" + #define LCD_STR_CLOCK "\x05" + #define LCD_STR_FEEDRATE "\x06" + #define LCD_STR_BEDTEMP "\x07" + #define LCD_STR_THERMOMETER "\x08" + #define LCD_STR_DEGREE "\x09" + + #define LCD_STR_SPECIAL_MAX '\x09' + // Maximum here is 0x1F because 0x20 is ' ' (space) and the normal charsets begin. + // Better stay below 0x10 because DISPLAY_CHARSET_HD44780_WESTERN begins here. + + // Symbol characters + #define LCD_STR_FILAM_DIA "\xF8" + #define LCD_STR_FILAM_MUL "\xA4" + +#endif + +/** + * Tool indexes for LCD display only + * + * By convention the LCD shows "E1" for the first extruder. + * However, internal to Marlin E0/T0 is the first tool, and + * most board silkscreens say "E0." Zero-based labels will + * make these indexes consistent but this defies expectation. + */ +#if ENABLED(NUMBER_TOOLS_FROM_0) + #define LCD_FIRST_TOOL 0 + #define STR_N0 "0" + #define STR_N1 "1" + #define STR_N2 "2" + #define STR_N3 "3" + #define STR_N4 "4" + #define STR_N5 "5" + #define STR_N6 "6" + #define STR_N7 "7" +#else + #define LCD_FIRST_TOOL 1 + #define STR_N0 "1" + #define STR_N1 "2" + #define STR_N2 "3" + #define STR_N3 "4" + #define STR_N4 "5" + #define STR_N5 "6" + #define STR_N6 "7" + #define STR_N7 "8" +#endif + +#define STR_E0 STR_E STR_N0 +#define STR_E1 STR_E STR_N1 +#define STR_E2 STR_E STR_N2 +#define STR_E3 STR_E STR_N3 +#define STR_E4 STR_E STR_N4 +#define STR_E5 STR_E STR_N5 +#define STR_E6 STR_E STR_N6 +#define STR_E7 STR_E STR_N7 + +// Include localized LCD Menu Messages + +#define LANGUAGE_DATA_INCL_(M) STRINGIFY_(fontdata/langdata_##M.h) +#define LANGUAGE_DATA_INCL(M) LANGUAGE_DATA_INCL_(M) + +#define LANGUAGE_INCL_(M) STRINGIFY_(../lcd/language/language_##M.h) +#define LANGUAGE_INCL(M) LANGUAGE_INCL_(M) + +// Use superscripts, if possible. Evaluated at point of use. +#define SUPERSCRIPT_TWO TERN(NOT_EXTENDED_ISO10646_1_5X7, "^2", "²") +#define SUPERSCRIPT_THREE TERN(NOT_EXTENDED_ISO10646_1_5X7, "^3", "³") + +#include "multi_language.h" // Allow multiple languages + +#include "../lcd/language/language_en.h" +#include LANGUAGE_INCL(LCD_LANGUAGE) +#include LANGUAGE_INCL(LCD_LANGUAGE_2) +#include LANGUAGE_INCL(LCD_LANGUAGE_3) +#include LANGUAGE_INCL(LCD_LANGUAGE_4) +#include LANGUAGE_INCL(LCD_LANGUAGE_5) + +#if NONE(DISPLAY_CHARSET_ISO10646_1, \ + DISPLAY_CHARSET_ISO10646_5, \ + DISPLAY_CHARSET_ISO10646_KANA, \ + DISPLAY_CHARSET_ISO10646_GREEK, \ + DISPLAY_CHARSET_ISO10646_CN, \ + DISPLAY_CHARSET_ISO10646_TR, \ + DISPLAY_CHARSET_ISO10646_PL, \ + DISPLAY_CHARSET_ISO10646_CZ, \ + DISPLAY_CHARSET_ISO10646_SK) + #define DISPLAY_CHARSET_ISO10646_1 // use the better font on full graphic displays. +#endif diff --git a/src/core/macros.h b/src/core/macros.h new file mode 100644 index 0000000..ad06763 --- /dev/null +++ b/src/core/macros.h @@ -0,0 +1,720 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#if !defined(__has_include) + #define __has_include(...) 1 +#endif + +#define ABCE 4 +#define XYZE 4 +#define ABC 3 +#define XYZ 3 +#define XY 2 + +#define _AXIS(A) (A##_AXIS) + +#define _XSTOP_ 0x01 +#define _YSTOP_ 0x02 +#define _ZSTOP_ 0x03 +#define _ISTOP_ 0x04 +#define _JSTOP_ 0x05 +#define _KSTOP_ 0x06 +#define _XMIN_ 0x11 +#define _YMIN_ 0x12 +#define _ZMIN_ 0x13 +#define _IMIN_ 0x14 +#define _JMIN_ 0x15 +#define _KMIN_ 0x16 +#define _XMAX_ 0x21 +#define _YMAX_ 0x22 +#define _ZMAX_ 0x23 +#define _IMAX_ 0x24 +#define _JMAX_ 0x25 +#define _KMAX_ 0x26 +#define _XDIAG_ 0x31 +#define _YDIAG_ 0x32 +#define _ZDIAG_ 0x33 +#define _IDIAG_ 0x34 +#define _JDIAG_ 0x35 +#define _KDIAG_ 0x36 +#define _E0DIAG_ 0xE0 +#define _E1DIAG_ 0xE1 +#define _E2DIAG_ 0xE2 +#define _E3DIAG_ 0xE3 +#define _E4DIAG_ 0xE4 +#define _E5DIAG_ 0xE5 +#define _E6DIAG_ 0xE6 +#define _E7DIAG_ 0xE7 + +#define _FORCE_INLINE_ __attribute__((__always_inline__)) __inline__ +#define FORCE_INLINE __attribute__((always_inline)) inline +#define NO_INLINE __attribute__((noinline)) +#define _UNUSED __attribute__((unused)) +#define __O0 __attribute__((optimize("O0"))) +#define __Os __attribute__((optimize("Os"))) +#define __O1 __attribute__((optimize("O1"))) +#define __O2 __attribute__((optimize("O2"))) +#define __O3 __attribute__((optimize("O3"))) + +#define IS_CONSTEXPR(...) __builtin_constant_p(__VA_ARGS__) // Only valid solution with C++14. Should use std::is_constant_evaluated() in C++20 instead + +#ifndef UNUSED + #define UNUSED(x) ((void)(x)) +#endif + +// Clock speed factors +#if !defined(CYCLES_PER_MICROSECOND) && !defined(__STM32F1__) + #define CYCLES_PER_MICROSECOND (F_CPU / 1000000UL) // 16 or 20 on AVR +#endif + +// Nanoseconds per cycle +#define NANOSECONDS_PER_CYCLE (1000000000.0 / F_CPU) + +// Macros to make a string from a macro +#define STRINGIFY_(M) #M +#define STRINGIFY(M) STRINGIFY_(M) + +#define A(CODE) " " CODE "\n\t" +#define L(CODE) CODE ":\n\t" + +// Macros for bit masks +#undef _BV +#define _BV(n) (1<<(n)) +#define TEST(n,b) (!!((n)&_BV(b))) +#define SET_BIT_TO(N,B,TF) do{ if (TF) SBI(N,B); else CBI(N,B); }while(0) +#ifndef SBI + #define SBI(A,B) (A |= _BV(B)) +#endif +#ifndef CBI + #define CBI(A,B) (A &= ~_BV(B)) +#endif +#define TBI(N,B) (N ^= _BV(B)) +#define _BV32(b) (1UL << (b)) +#define TEST32(n,b) !!((n)&_BV32(b)) +#define SBI32(n,b) (n |= _BV32(b)) +#define CBI32(n,b) (n &= ~_BV32(b)) +#define TBI32(N,B) (N ^= _BV32(B)) + +#define cu(x) ({__typeof__(x) _x = (x); (_x)*(_x)*(_x);}) +#define RADIANS(d) ((d)*float(M_PI)/180.0f) +#define DEGREES(r) ((r)*180.0f/float(M_PI)) +#define HYPOT2(x,y) (sq(x)+sq(y)) +#define NORMSQ(x,y,z) (sq(x)+sq(y)+sq(z)) + +#define CIRCLE_AREA(R) (float(M_PI) * sq(float(R))) +#define CIRCLE_CIRC(R) (2 * float(M_PI) * float(R)) + +#define SIGN(a) ({__typeof__(a) _a = (a); (_a>0)-(_a<0);}) +#define IS_POWER_OF_2(x) ((x) && !((x) & ((x) - 1))) + +// Macros to constrain values +#ifdef __cplusplus + + // C++11 solution that is standards compliant. + template static constexpr void NOLESS(V& v, const N n) { + if (n > v) v = n; + } + template static constexpr void NOMORE(V& v, const N n) { + if (n < v) v = n; + } + template static constexpr void LIMIT(V& v, const N1 n1, const N2 n2) { + if (n1 > v) v = n1; + else if (n2 < v) v = n2; + } + +#else + + #define NOLESS(v, n) \ + do{ \ + __typeof__(v) _n = (n); \ + if (_n > v) v = _n; \ + }while(0) + + #define NOMORE(v, n) \ + do{ \ + __typeof__(v) _n = (n); \ + if (_n < v) v = _n; \ + }while(0) + + #define LIMIT(v, n1, n2) \ + do{ \ + __typeof__(v) _n1 = (n1); \ + __typeof__(v) _n2 = (n2); \ + if (_n1 > v) v = _n1; \ + else if (_n2 < v) v = _n2; \ + }while(0) + +#endif + +// Macros to chain up to 40 conditions +#define _DO_1(W,C,A) (_##W##_1(A)) +#define _DO_2(W,C,A,B) (_##W##_1(A) C _##W##_1(B)) +#define _DO_3(W,C,A,V...) (_##W##_1(A) C _DO_2(W,C,V)) +#define _DO_4(W,C,A,V...) (_##W##_1(A) C _DO_3(W,C,V)) +#define _DO_5(W,C,A,V...) (_##W##_1(A) C _DO_4(W,C,V)) +#define _DO_6(W,C,A,V...) (_##W##_1(A) C _DO_5(W,C,V)) +#define _DO_7(W,C,A,V...) (_##W##_1(A) C _DO_6(W,C,V)) +#define _DO_8(W,C,A,V...) (_##W##_1(A) C _DO_7(W,C,V)) +#define _DO_9(W,C,A,V...) (_##W##_1(A) C _DO_8(W,C,V)) +#define _DO_10(W,C,A,V...) (_##W##_1(A) C _DO_9(W,C,V)) +#define _DO_11(W,C,A,V...) (_##W##_1(A) C _DO_10(W,C,V)) +#define _DO_12(W,C,A,V...) (_##W##_1(A) C _DO_11(W,C,V)) +#define _DO_13(W,C,A,V...) (_##W##_1(A) C _DO_12(W,C,V)) +#define _DO_14(W,C,A,V...) (_##W##_1(A) C _DO_13(W,C,V)) +#define _DO_15(W,C,A,V...) (_##W##_1(A) C _DO_14(W,C,V)) +#define _DO_16(W,C,A,V...) (_##W##_1(A) C _DO_15(W,C,V)) +#define _DO_17(W,C,A,V...) (_##W##_1(A) C _DO_16(W,C,V)) +#define _DO_18(W,C,A,V...) (_##W##_1(A) C _DO_17(W,C,V)) +#define _DO_19(W,C,A,V...) (_##W##_1(A) C _DO_18(W,C,V)) +#define _DO_20(W,C,A,V...) (_##W##_1(A) C _DO_19(W,C,V)) +#define _DO_21(W,C,A,V...) (_##W##_1(A) C _DO_20(W,C,V)) +#define _DO_22(W,C,A,V...) (_##W##_1(A) C _DO_21(W,C,V)) +#define _DO_23(W,C,A,V...) (_##W##_1(A) C _DO_22(W,C,V)) +#define _DO_24(W,C,A,V...) (_##W##_1(A) C _DO_23(W,C,V)) +#define _DO_25(W,C,A,V...) (_##W##_1(A) C _DO_24(W,C,V)) +#define _DO_26(W,C,A,V...) (_##W##_1(A) C _DO_25(W,C,V)) +#define _DO_27(W,C,A,V...) (_##W##_1(A) C _DO_26(W,C,V)) +#define _DO_28(W,C,A,V...) (_##W##_1(A) C _DO_27(W,C,V)) +#define _DO_29(W,C,A,V...) (_##W##_1(A) C _DO_28(W,C,V)) +#define _DO_30(W,C,A,V...) (_##W##_1(A) C _DO_29(W,C,V)) +#define _DO_31(W,C,A,V...) (_##W##_1(A) C _DO_30(W,C,V)) +#define _DO_32(W,C,A,V...) (_##W##_1(A) C _DO_31(W,C,V)) +#define _DO_33(W,C,A,V...) (_##W##_1(A) C _DO_32(W,C,V)) +#define _DO_34(W,C,A,V...) (_##W##_1(A) C _DO_33(W,C,V)) +#define _DO_35(W,C,A,V...) (_##W##_1(A) C _DO_34(W,C,V)) +#define _DO_36(W,C,A,V...) (_##W##_1(A) C _DO_35(W,C,V)) +#define _DO_37(W,C,A,V...) (_##W##_1(A) C _DO_36(W,C,V)) +#define _DO_38(W,C,A,V...) (_##W##_1(A) C _DO_37(W,C,V)) +#define _DO_39(W,C,A,V...) (_##W##_1(A) C _DO_38(W,C,V)) +#define _DO_40(W,C,A,V...) (_##W##_1(A) C _DO_39(W,C,V)) +#define __DO_N(W,C,N,V...) _DO_##N(W,C,V) +#define _DO_N(W,C,N,V...) __DO_N(W,C,N,V) +#define DO(W,C,V...) (_DO_N(W,C,NUM_ARGS(V),V)) + +// Macros to support option testing +#define _CAT(a,V...) a##V +#define CAT(a,V...) _CAT(a,V) + +#define _ISENA_ ~,1 +#define _ISENA_1 ~,1 +#define _ISENA_0x1 ~,1 +#define _ISENA_true ~,1 +#define _ISENA(V...) IS_PROBE(V) + +#define _ENA_1(O) _ISENA(CAT(_IS,CAT(ENA_, O))) +#define _DIS_1(O) NOT(_ENA_1(O)) +#define ENABLED(V...) DO(ENA,&&,V) +#define DISABLED(V...) DO(DIS,&&,V) +#define COUNT_ENABLED(V...) DO(ENA,+,V) + +#define TERN(O,A,B) _TERN(_ENA_1(O),B,A) // OPTION ? 'A' : 'B' +#define TERN0(O,A) _TERN(_ENA_1(O),0,A) // OPTION ? 'A' : '0' +#define TERN1(O,A) _TERN(_ENA_1(O),1,A) // OPTION ? 'A' : '1' +#define TERN_(O,A) _TERN(_ENA_1(O),,A) // OPTION ? 'A' : '' +#define _TERN(E,V...) __TERN(_CAT(T_,E),V) // Prepend 'T_' to get 'T_0' or 'T_1' +#define __TERN(T,V...) ___TERN(_CAT(_NO,T),V) // Prepend '_NO' to get '_NOT_0' or '_NOT_1' +#define ___TERN(P,V...) THIRD(P,V) // If first argument has a comma, A. Else B. + +#define _OPTITEM(A...) A, +#define OPTITEM(O,A...) TERN_(O,DEFER4(_OPTITEM)(A)) +#define _OPTARG(A...) , A +#define OPTARG(O,A...) TERN_(O,DEFER4(_OPTARG)(A)) +#define _OPTCODE(A) A; +#define OPTCODE(O,A) TERN_(O,DEFER4(_OPTCODE)(A)) + +// Macros to avoid 'f + 0.0' which is not always optimized away. Minus included for symmetry. +// Compiler flags -fno-signed-zeros -ffinite-math-only also cover 'f * 1.0', 'f - f', etc. +#define PLUS_TERN0(O,A) _TERN(_ENA_1(O),,+ (A)) // OPTION ? '+ (A)' : '' +#define MINUS_TERN0(O,A) _TERN(_ENA_1(O),,- (A)) // OPTION ? '- (A)' : '' +#define SUM_TERN(O,B,A) ((B) PLUS_TERN0(O,A)) // ((B) (OPTION ? '+ (A)' : '')) +#define DIFF_TERN(O,B,A) ((B) MINUS_TERN0(O,A)) // ((B) (OPTION ? '- (A)' : '')) + +#define IF_ENABLED TERN_ +#define IF_DISABLED(O,A) TERN(O,,A) + +#define ANY(V...) !DISABLED(V) +#define NONE(V...) DISABLED(V) +#define ALL(V...) ENABLED(V) +#define BOTH(V1,V2) ALL(V1,V2) +#define EITHER(V1,V2) ANY(V1,V2) +#define MANY(V...) (COUNT_ENABLED(V) > 1) + +// Macros to support pins/buttons exist testing +#define PIN_EXISTS(PN) (defined(PN##_PIN) && PN##_PIN >= 0) +#define _PINEX_1 PIN_EXISTS +#define PINS_EXIST(V...) DO(PINEX,&&,V) +#define ANY_PIN(V...) DO(PINEX,||,V) + +#define BUTTON_EXISTS(BN) (defined(BTN_##BN) && BTN_##BN >= 0) +#define _BTNEX_1 BUTTON_EXISTS +#define BUTTONS_EXIST(V...) DO(BTNEX,&&,V) +#define ANY_BUTTON(V...) DO(BTNEX,||,V) + +#define WITHIN(N,L,H) ((N) >= (L) && (N) <= (H)) +#define ISEOL(C) ((C) == '\n' || (C) == '\r') +#define NUMERIC(a) WITHIN(a, '0', '9') +#define DECIMAL(a) (NUMERIC(a) || a == '.') +#define HEXCHR(a) (NUMERIC(a) ? (a) - '0' : WITHIN(a, 'a', 'f') ? ((a) - 'a' + 10) : WITHIN(a, 'A', 'F') ? ((a) - 'A' + 10) : -1) +#define NUMERIC_SIGNED(a) (NUMERIC(a) || (a) == '-' || (a) == '+') +#define DECIMAL_SIGNED(a) (DECIMAL(a) || (a) == '-' || (a) == '+') +#define COUNT(a) (sizeof(a)/sizeof(*a)) +#define ZERO(a) memset((void*)a,0,sizeof(a)) +#define COPY(a,b) do{ \ + static_assert(sizeof(a[0]) == sizeof(b[0]), "COPY: '" STRINGIFY(a) "' and '" STRINGIFY(b) "' types (sizes) don't match!"); \ + memcpy(&a[0],&b[0],_MIN(sizeof(a),sizeof(b))); \ + }while(0) + +#define CODE_16( A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,...) A; B; C; D; E; F; G; H; I; J; K; L; M; N; O; P +#define CODE_15( A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,...) A; B; C; D; E; F; G; H; I; J; K; L; M; N; O +#define CODE_14( A,B,C,D,E,F,G,H,I,J,K,L,M,N,...) A; B; C; D; E; F; G; H; I; J; K; L; M; N +#define CODE_13( A,B,C,D,E,F,G,H,I,J,K,L,M,...) A; B; C; D; E; F; G; H; I; J; K; L; M +#define CODE_12( A,B,C,D,E,F,G,H,I,J,K,L,...) A; B; C; D; E; F; G; H; I; J; K; L +#define CODE_11( A,B,C,D,E,F,G,H,I,J,K,...) A; B; C; D; E; F; G; H; I; J; K +#define CODE_10( A,B,C,D,E,F,G,H,I,J,...) A; B; C; D; E; F; G; H; I; J +#define CODE_9( A,B,C,D,E,F,G,H,I,...) A; B; C; D; E; F; G; H; I +#define CODE_8( A,B,C,D,E,F,G,H,...) A; B; C; D; E; F; G; H +#define CODE_7( A,B,C,D,E,F,G,...) A; B; C; D; E; F; G +#define CODE_6( A,B,C,D,E,F,...) A; B; C; D; E; F +#define CODE_5( A,B,C,D,E,...) A; B; C; D; E +#define CODE_4( A,B,C,D,...) A; B; C; D +#define CODE_3( A,B,C,...) A; B; C +#define CODE_2( A,B,...) A; B +#define CODE_1( A,...) A +#define CODE_0(...) +#define _CODE_N(N,V...) CODE_##N(V) +#define CODE_N(N,V...) _CODE_N(N,V) + +#define GANG_16(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,...) A B C D E F G H I J K L M N O P +#define GANG_15(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,...) A B C D E F G H I J K L M N O +#define GANG_14(A,B,C,D,E,F,G,H,I,J,K,L,M,N,...) A B C D E F G H I J K L M N +#define GANG_13(A,B,C,D,E,F,G,H,I,J,K,L,M...) A B C D E F G H I J K L M +#define GANG_12(A,B,C,D,E,F,G,H,I,J,K,L...) A B C D E F G H I J K L +#define GANG_11(A,B,C,D,E,F,G,H,I,J,K,...) A B C D E F G H I J K +#define GANG_10(A,B,C,D,E,F,G,H,I,J,...) A B C D E F G H I J +#define GANG_9( A,B,C,D,E,F,G,H,I,...) A B C D E F G H I +#define GANG_8( A,B,C,D,E,F,G,H,...) A B C D E F G H +#define GANG_7( A,B,C,D,E,F,G,...) A B C D E F G +#define GANG_6( A,B,C,D,E,F,...) A B C D E F +#define GANG_5( A,B,C,D,E,...) A B C D E +#define GANG_4( A,B,C,D,...) A B C D +#define GANG_3( A,B,C,...) A B C +#define GANG_2( A,B,...) A B +#define GANG_1( A,...) A +#define GANG_0(...) +#define _GANG_N(N,V...) GANG_##N(V) +#define GANG_N(N,V...) _GANG_N(N,V) +#define GANG_N_1(N,K) _GANG_N(N,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K) + +// Macros for initializing arrays +#define LIST_20(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T +#define LIST_19(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S +#define LIST_18(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R +#define LIST_17(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q +#define LIST_16(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P +#define LIST_15(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N,O +#define LIST_14(A,B,C,D,E,F,G,H,I,J,K,L,M,N,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N +#define LIST_13(A,B,C,D,E,F,G,H,I,J,K,L,M,...) A,B,C,D,E,F,G,H,I,J,K,L,M +#define LIST_12(A,B,C,D,E,F,G,H,I,J,K,L,...) A,B,C,D,E,F,G,H,I,J,K,L +#define LIST_11(A,B,C,D,E,F,G,H,I,J,K,...) A,B,C,D,E,F,G,H,I,J,K +#define LIST_10(A,B,C,D,E,F,G,H,I,J,...) A,B,C,D,E,F,G,H,I,J +#define LIST_9( A,B,C,D,E,F,G,H,I,...) A,B,C,D,E,F,G,H,I +#define LIST_8( A,B,C,D,E,F,G,H,...) A,B,C,D,E,F,G,H +#define LIST_7( A,B,C,D,E,F,G,...) A,B,C,D,E,F,G +#define LIST_6( A,B,C,D,E,F,...) A,B,C,D,E,F +#define LIST_5( A,B,C,D,E,...) A,B,C,D,E +#define LIST_4( A,B,C,D,...) A,B,C,D +#define LIST_3( A,B,C,...) A,B,C +#define LIST_2( A,B,...) A,B +#define LIST_1( A,...) A +#define LIST_0(...) + +#define _LIST_N(N,V...) LIST_##N(V) +#define LIST_N(N,V...) _LIST_N(N,V) +#define LIST_N_1(N,K) _LIST_N(N,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K,K) +#define ARRAY_N(N,V...) { _LIST_N(N,V) } +#define ARRAY_N_1(N,K) { LIST_N_1(N,K) } + +#define _JOIN_1(O) (O) +#define JOIN_N(N,C,V...) (DO(JOIN,C,LIST_N(N,V))) + +#define LOOP_S_LE_N(VAR, S, N) for (uint8_t VAR=(S); VAR<=(N); VAR++) +#define LOOP_S_L_N(VAR, S, N) for (uint8_t VAR=(S); VAR<(N); VAR++) +#define LOOP_LE_N(VAR, N) LOOP_S_LE_N(VAR, 0, N) +#define LOOP_L_N(VAR, N) LOOP_S_L_N(VAR, 0, N) + +#define NOOP (void(0)) + +#define CEILING(x,y) (((x) + (y) - 1) / (y)) + +#undef ABS +#ifdef __cplusplus + template static constexpr const T ABS(const T v) { return v >= 0 ? v : -v; } +#else + #define ABS(a) ({__typeof__(a) _a = (a); _a >= 0 ? _a : -_a;}) +#endif + +#define UNEAR_ZERO(x) ((x) < 0.000001f) +#define NEAR_ZERO(x) WITHIN(x, -0.000001f, 0.000001f) +#define NEAR(x,y) NEAR_ZERO((x)-(y)) + +#define RECIPROCAL(x) (NEAR_ZERO(x) ? 0 : (1 / float(x))) +#define FIXFLOAT(f) ({__typeof__(f) _f = (f); _f + (_f < 0 ? -0.0000005f : 0.0000005f);}) + +// +// Maths macros that can be overridden by HAL +// +#define ACOS(x) acosf(x) +#define ATAN2(y, x) atan2f(y, x) +#define POW(x, y) powf(x, y) +#define SQRT(x) sqrtf(x) +#define RSQRT(x) (1.0f / sqrtf(x)) +#define CEIL(x) ceilf(x) +#define FLOOR(x) floorf(x) +#define TRUNC(x) truncf(x) +#define LROUND(x) lroundf(x) +#define FMOD(x, y) fmodf(x, y) +#define HYPOT(x,y) SQRT(HYPOT2(x,y)) + +// Use NUM_ARGS(__VA_ARGS__) to get the number of variadic arguments +#define _NUM_ARGS(_,n,m,l,k,j,i,h,g,f,e,d,c,b,a,Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A,OUT,...) OUT +#define NUM_ARGS(V...) _NUM_ARGS(0,V,40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0) + +// Use TWO_ARGS(__VA_ARGS__) to get whether there are 1, 2, or >2 arguments +#define _TWO_ARGS(_,n,m,l,k,j,i,h,g,f,e,d,c,b,a,Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A,OUT,...) OUT +#define TWO_ARGS(V...) _TWO_ARGS(0,V,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,0) + +#ifdef __cplusplus + + #ifndef _MINMAX_H_ + #define _MINMAX_H_ + + extern "C++" { + + // C++11 solution that is standards compliant. Return type is deduced automatically + template static constexpr auto _MIN(const L lhs, const R rhs) -> decltype(lhs + rhs) { + return lhs < rhs ? lhs : rhs; + } + template static constexpr auto _MAX(const L lhs, const R rhs) -> decltype(lhs + rhs) { + return lhs > rhs ? lhs : rhs; + } + template static constexpr const T _MIN(T V, Ts... Vs) { return _MIN(V, _MIN(Vs...)); } + template static constexpr const T _MAX(T V, Ts... Vs) { return _MAX(V, _MAX(Vs...)); } + + } + + #endif + + // Allow manipulating enumeration value like flags without ugly cast everywhere + #define ENUM_FLAGS(T) \ + FORCE_INLINE constexpr T operator&(T x, T y) { return static_cast(static_cast(x) & static_cast(y)); } \ + FORCE_INLINE constexpr T operator|(T x, T y) { return static_cast(static_cast(x) | static_cast(y)); } \ + FORCE_INLINE constexpr T operator^(T x, T y) { return static_cast(static_cast(x) ^ static_cast(y)); } \ + FORCE_INLINE constexpr T operator~(T x) { return static_cast(~static_cast(x)); } \ + FORCE_INLINE T & operator&=(T &x, T y) { return x &= y; } \ + FORCE_INLINE T & operator|=(T &x, T y) { return x |= y; } \ + FORCE_INLINE T & operator^=(T &x, T y) { return x ^= y; } + + // C++11 solution that is standard compliant. is not available on all platform + namespace Private { + template struct enable_if { }; + template struct enable_if { typedef _Tp type; }; + + template struct is_same { enum { value = false }; }; + template struct is_same { enum { value = true }; }; + + template struct first_type_of { typedef T type; }; + template struct first_type_of { typedef T type; }; + } + // C++11 solution using SFINAE to detect the existence of a member in a class at compile time. + // It creates a HasMember structure containing 'value' set to true if the member exists + #define HAS_MEMBER_IMPL(Member) \ + namespace Private { \ + template struct HasMember_ ## Member { \ + template static Yes& test( decltype(&C::Member) ) ; \ + template static No& test(...); \ + enum { value = sizeof(test(0)) == sizeof(Yes) }; }; \ + } + + // Call the method if it exists, but do nothing if it does not. The method is detected at compile time. + // If the method exists, this is inlined and does not cost anything. Else, an "empty" wrapper is created, returning a default value + #define CALL_IF_EXISTS_IMPL(Return, Method, ...) \ + HAS_MEMBER_IMPL(Method) \ + namespace Private { \ + template FORCE_INLINE typename enable_if::value, Return>::type Call_ ## Method(T * t, Args... a) { return static_cast(t->Method(a...)); } \ + _UNUSED static Return Call_ ## Method(...) { return __VA_ARGS__; } \ + } + #define CALL_IF_EXISTS(Return, That, Method, ...) \ + static_cast(Private::Call_ ## Method(That, ##__VA_ARGS__)) + + // Compile-time string manipulation + namespace CompileTimeString { + // Simple compile-time parser to find the position of the end of a string + constexpr const char* findStringEnd(const char *str) { + return *str ? findStringEnd(str + 1) : str; + } + + // Check whether a string contains a specific character + constexpr bool contains(const char *str, const char ch) { + return *str == ch ? true : (*str ? contains(str + 1, ch) : false); + } + // Find the last position of the specific character (should be called with findStringEnd) + constexpr const char* findLastPos(const char *str, const char ch) { + return *str == ch ? (str + 1) : findLastPos(str - 1, ch); + } + // Compile-time evaluation of the last part of a file path + // Typically used to shorten the path to file in compiled strings + // CompileTimeString::baseName(__FILE__) returns "macros.h" and not /path/to/Marlin/src/core/macros.h + constexpr const char* baseName(const char *str) { + return contains(str, '/') ? findLastPos(findStringEnd(str), '/') : str; + } + + // Find the first occurrence of a character in a string (or return the last position in the string) + constexpr const char* findFirst(const char *str, const char ch) { + return *str == ch || *str == 0 ? (str + 1) : findFirst(str + 1, ch); + } + // Compute the string length at compile time + constexpr unsigned stringLen(const char *str) { + return *str == 0 ? 0 : 1 + stringLen(str + 1); + } + } + + #define ONLY_FILENAME CompileTimeString::baseName(__FILE__) + /** Get the templated type name. This does not depends on RTTI, but on the preprocessor, so it should be quite safe to use even on old compilers. + WARNING: DO NOT RENAME THIS FUNCTION (or change the text inside the function to match what the preprocessor will generate) + The name is chosen very short since the binary will store "const char* gtn(T*) [with T = YourTypeHere]" so avoid long function name here */ + template + inline const char* gtn(T*) { + // It works on GCC by instantiating __PRETTY_FUNCTION__ and parsing the result. So the syntax here is very limited to GCC output + constexpr unsigned verboseChatLen = sizeof("const char* gtn(T*) [with T = ") - 1; + static char templateType[sizeof(__PRETTY_FUNCTION__) - verboseChatLen] = {}; + __builtin_memcpy(templateType, __PRETTY_FUNCTION__ + verboseChatLen, sizeof(__PRETTY_FUNCTION__) - verboseChatLen - 2); + return templateType; + } + +#else + + #define __MIN_N(N,V...) MIN_##N(V) + #define _MIN_N(N,V...) __MIN_N(N,V) + #define _MIN_N_REF() _MIN_N + #define _MIN(V...) EVAL(_MIN_N(TWO_ARGS(V),V)) + #define MIN_2(a,b) ((a)<(b)?(a):(b)) + #define MIN_3(a,V...) MIN_2(a,DEFER2(_MIN_N_REF)()(TWO_ARGS(V),V)) + + #define __MAX_N(N,V...) MAX_##N(V) + #define _MAX_N(N,V...) __MAX_N(N,V) + #define _MAX_N_REF() _MAX_N + #define _MAX(V...) EVAL(_MAX_N(TWO_ARGS(V),V)) + #define MAX_2(a,b) ((a)>(b)?(a):(b)) + #define MAX_3(a,V...) MAX_2(a,DEFER2(_MAX_N_REF)()(TWO_ARGS(V),V)) + +#endif + +// Macros for adding +#define INC_0 1 +#define INC_1 2 +#define INC_2 3 +#define INC_3 4 +#define INC_4 5 +#define INC_5 6 +#define INC_6 7 +#define INC_7 8 +#define INC_8 9 +#define INC_9 10 +#define INC_10 11 +#define INC_11 12 +#define INC_12 13 +#define INC_13 14 +#define INC_14 15 +#define INC_15 16 +#define INC_16 17 +#define INC_17 18 +#define INC_18 19 +#define INC_19 20 +#define INC_20 21 +#define INCREMENT_(n) INC_##n +#define INCREMENT(n) INCREMENT_(n) + +#define ADD0(N) N +#define ADD1(N) INCREMENT_(N) +#define ADD2(N) ADD1(ADD1(N)) +#define ADD3(N) ADD1(ADD2(N)) +#define ADD4(N) ADD2(ADD2(N)) +#define ADD5(N) ADD2(ADD3(N)) +#define ADD6(N) ADD3(ADD3(N)) +#define ADD7(N) ADD3(ADD4(N)) +#define ADD8(N) ADD4(ADD4(N)) +#define ADD9(N) ADD4(ADD5(N)) +#define ADD10(N) ADD5(ADD5(N)) +#define SUM(A,B) _CAT(ADD,A)(B) +#define DOUBLE_(n) ADD##n(n) +#define DOUBLE(n) DOUBLE_(n) + +// Macros for subtracting +#define DEC_0 0 +#define DEC_1 0 +#define DEC_2 1 +#define DEC_3 2 +#define DEC_4 3 +#define DEC_5 4 +#define DEC_6 5 +#define DEC_7 6 +#define DEC_8 7 +#define DEC_9 8 +#define DEC_10 9 +#define DEC_11 10 +#define DEC_12 11 +#define DEC_13 12 +#define DEC_14 13 +#define DEC_15 14 +#define DECREMENT_(n) DEC_##n +#define DECREMENT(n) DECREMENT_(n) + +#define SUB0(N) N +#define SUB1(N) DECREMENT_(N) +#define SUB2(N) SUB1(SUB1(N)) +#define SUB3(N) SUB1(SUB2(N)) +#define SUB4(N) SUB2(SUB2(N)) +#define SUB5(N) SUB2(SUB3(N)) +#define SUB6(N) SUB3(SUB3(N)) +#define SUB7(N) SUB3(SUB4(N)) +#define SUB8(N) SUB4(SUB4(N)) +#define SUB9(N) SUB4(SUB5(N)) +#define SUB10(N) SUB5(SUB5(N)) + +// +// Primitives supporting precompiler REPEAT +// +#define FIRST(a,...) a +#define SECOND(a,b,...) b +#define THIRD(a,b,c,...) c + +// Defer expansion +#define EMPTY() +#define DEFER(M) M EMPTY() +#define DEFER2(M) M EMPTY EMPTY()() +#define DEFER3(M) M EMPTY EMPTY EMPTY()()() +#define DEFER4(M) M EMPTY EMPTY EMPTY EMPTY()()()() + +// Force define expansion +#define EVAL(V...) EVAL16(V) +#define EVAL1024(V...) EVAL512(EVAL512(V)) +#define EVAL512(V...) EVAL256(EVAL256(V)) +#define EVAL256(V...) EVAL128(EVAL128(V)) +#define EVAL128(V...) EVAL64(EVAL64(V)) +#define EVAL64(V...) EVAL32(EVAL32(V)) +#define EVAL32(V...) EVAL16(EVAL16(V)) +#define EVAL16(V...) EVAL8(EVAL8(V)) +#define EVAL8(V...) EVAL4(EVAL4(V)) +#define EVAL4(V...) EVAL2(EVAL2(V)) +#define EVAL2(V...) EVAL1(EVAL1(V)) +#define EVAL1(V...) V + +#define IS_PROBE(V...) SECOND(V, 0) // Get the second item passed, or 0 +#define PROBE() ~, 1 // Second item will be 1 if this is passed +#define _NOT_0 PROBE() +#define NOT(x) IS_PROBE(_CAT(_NOT_, x)) // NOT('0') gets '1'. Anything else gets '0'. +#define _BOOL(x) NOT(NOT(x)) // _BOOL('0') gets '0'. Anything else gets '1'. + +#define IF_ELSE(TF) _IF_ELSE(_BOOL(TF)) +#define _IF_ELSE(TF) _CAT(_IF_, TF) + +#define _IF_1(V...) V _IF_1_ELSE +#define _IF_0(...) _IF_0_ELSE + +#define _IF_1_ELSE(...) +#define _IF_0_ELSE(V...) V + +#define HAS_ARGS(V...) _BOOL(FIRST(_END_OF_ARGUMENTS_ V)()) +#define _END_OF_ARGUMENTS_() 0 + +// Simple Inline IF Macros, friendly to use in other macro definitions +#define IF(O, A, B) ((O) ? (A) : (B)) +#define IF_0(O, A) IF(O, A, 0) +#define IF_1(O, A) IF(O, A, 1) + +// +// REPEAT core macros. Recurse N times with ascending I. +// + +// Call OP(I) N times with ascending counter. +#define _REPEAT(_RPT_I,_RPT_N,_RPT_OP) \ + _RPT_OP(_RPT_I) \ + IF_ELSE(SUB1(_RPT_N)) \ + ( DEFER2(__REPEAT)()(ADD1(_RPT_I),SUB1(_RPT_N),_RPT_OP) ) \ + ( /* Do nothing */ ) +#define __REPEAT() _REPEAT + +// Call OP(I, ...) N times with ascending counter. +#define _REPEAT2(_RPT_I,_RPT_N,_RPT_OP,V...) \ + _RPT_OP(_RPT_I,V) \ + IF_ELSE(SUB1(_RPT_N)) \ + ( DEFER2(__REPEAT2)()(ADD1(_RPT_I),SUB1(_RPT_N),_RPT_OP,V) ) \ + ( /* Do nothing */ ) +#define __REPEAT2() _REPEAT2 + +// Repeat a macro passing S...N-1. +#define REPEAT_S(S,N,OP) EVAL(_REPEAT(S,SUB##S(N),OP)) +#define REPEAT(N,OP) REPEAT_S(0,N,OP) +#define REPEAT_1(N,OP) REPEAT_S(1,INCREMENT(N),OP) + +// Repeat a macro passing 0...N-1 plus additional arguments. +#define REPEAT2_S(S,N,OP,V...) EVAL(_REPEAT2(S,SUB##S(N),OP,V)) +#define REPEAT2(N,OP,V...) REPEAT2_S(0,N,OP,V) + +// Use RREPEAT macros with REPEAT macros for nesting +#define _RREPEAT(_RPT_I,_RPT_N,_RPT_OP) \ + _RPT_OP(_RPT_I) \ + IF_ELSE(SUB1(_RPT_N)) \ + ( DEFER2(__RREPEAT)()(ADD1(_RPT_I),SUB1(_RPT_N),_RPT_OP) ) \ + ( /* Do nothing */ ) +#define __RREPEAT() _RREPEAT +#define _RREPEAT2(_RPT_I,_RPT_N,_RPT_OP,V...) \ + _RPT_OP(_RPT_I,V) \ + IF_ELSE(SUB1(_RPT_N)) \ + ( DEFER2(__RREPEAT2)()(ADD1(_RPT_I),SUB1(_RPT_N),_RPT_OP,V) ) \ + ( /* Do nothing */ ) +#define __RREPEAT2() _RREPEAT2 +#define RREPEAT_S(S,N,OP) EVAL1024(_RREPEAT(S,SUB##S(N),OP)) +#define RREPEAT(N,OP) RREPEAT_S(0,N,OP) +#define RREPEAT2_S(S,N,OP,V...) EVAL1024(_RREPEAT2(S,SUB##S(N),OP,V)) +#define RREPEAT2(N,OP,V...) RREPEAT2_S(0,N,OP,V) + +// Call OP(A) with each item as an argument +#define _MAP(_MAP_OP,A,V...) \ + _MAP_OP(A) \ + IF_ELSE(HAS_ARGS(V)) \ + ( DEFER2(__MAP)()(_MAP_OP,V) ) \ + ( /* Do nothing */ ) +#define __MAP() _MAP + +#define MAP(OP,V...) EVAL(_MAP(OP,V)) + +// Emit a list of OP(A) with the given items +#define _MAPLIST(_MAP_OP,A,V...) \ + _MAP_OP(A) \ + IF_ELSE(HAS_ARGS(V)) \ + ( , DEFER2(__MAPLIST)()(_MAP_OP,V) ) \ + ( /* Do nothing */ ) +#define __MAPLIST() _MAPLIST + +#define MAPLIST(OP,V...) EVAL(_MAPLIST(OP,V)) diff --git a/src/core/millis_t.h b/src/core/millis_t.h new file mode 100644 index 0000000..95bc40e --- /dev/null +++ b/src/core/millis_t.h @@ -0,0 +1,33 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include + +typedef uint32_t millis_t; + +#define SEC_TO_MS(N) millis_t((N)*1000UL) +#define MIN_TO_MS(N) SEC_TO_MS((N)*60UL) +#define MS_TO_SEC(N) millis_t((N)/1000UL) + +#define PENDING(NOW,SOON) ((int32_t)(NOW-(SOON))<0) +#define ELAPSED(NOW,SOON) (!PENDING(NOW,SOON)) diff --git a/src/core/multi_language.h b/src/core/multi_language.h new file mode 100644 index 0000000..05a713e --- /dev/null +++ b/src/core/multi_language.h @@ -0,0 +1,93 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/******************************************************* + * multi_language.h * + * By Marcio Teixeira 2019 for Aleph Objects * + *******************************************************/ + +#include "../inc/MarlinConfigPre.h" + +typedef const char Language_Str[]; +#define LSTR PROGMEM Language_Str + +#ifdef LCD_LANGUAGE_5 + #define NUM_LANGUAGES 5 +#elif defined(LCD_LANGUAGE_4) + #define NUM_LANGUAGES 4 +#elif defined(LCD_LANGUAGE_3) + #define NUM_LANGUAGES 3 +#elif defined(LCD_LANGUAGE_2) + #define NUM_LANGUAGES 2 +#else + #define NUM_LANGUAGES 1 +#endif + +// Set unused languages equal to each other so the +// compiler can optimize away the conditionals. +#define LCD_LANGUAGE_1 LCD_LANGUAGE +#ifndef LCD_LANGUAGE_2 + #define LCD_LANGUAGE_2 LCD_LANGUAGE +#endif +#ifndef LCD_LANGUAGE_3 + #define LCD_LANGUAGE_3 LCD_LANGUAGE_2 +#endif +#ifndef LCD_LANGUAGE_4 + #define LCD_LANGUAGE_4 LCD_LANGUAGE_3 +#endif +#ifndef LCD_LANGUAGE_5 + #define LCD_LANGUAGE_5 LCD_LANGUAGE_4 +#endif + +#define _GET_LANG(LANG) Language_##LANG +#define GET_LANG(LANG) _GET_LANG(LANG) + +#if NUM_LANGUAGES > 1 + #define HAS_MULTI_LANGUAGE 1 + #define GET_TEXT(MSG) ( \ + ui.language == 4 ? GET_LANG(LCD_LANGUAGE_5)::MSG : \ + ui.language == 3 ? GET_LANG(LCD_LANGUAGE_4)::MSG : \ + ui.language == 2 ? GET_LANG(LCD_LANGUAGE_3)::MSG : \ + ui.language == 1 ? GET_LANG(LCD_LANGUAGE_2)::MSG : \ + GET_LANG(LCD_LANGUAGE )::MSG ) + #define MAX_LANG_CHARSIZE _MAX(GET_LANG(LCD_LANGUAGE )::CHARSIZE, \ + GET_LANG(LCD_LANGUAGE_2)::CHARSIZE, \ + GET_LANG(LCD_LANGUAGE_3)::CHARSIZE, \ + GET_LANG(LCD_LANGUAGE_4)::CHARSIZE, \ + GET_LANG(LCD_LANGUAGE_5)::CHARSIZE ) +#else + #define GET_TEXT(MSG) GET_LANG(LCD_LANGUAGE)::MSG + #define MAX_LANG_CHARSIZE LANG_CHARSIZE +#endif +#define GET_TEXT_F(MSG) FPSTR(GET_TEXT(MSG)) + +#define GET_EN_TEXT(MSG) GET_LANG(en)::MSG +#define GET_EN_TEXT_F(MSG) FPSTR(GET_EN_TEXT(MSG)) + +#define GET_LANGUAGE_NAME(INDEX) GET_LANG(LCD_LANGUAGE_##INDEX)::LANGUAGE +#define LANG_CHARSIZE GET_TEXT(CHARSIZE) +#define USE_WIDE_GLYPH (LANG_CHARSIZE > 2) + +#define MSG_1_LINE(A) A "\0" "\0" +#define MSG_2_LINE(A,B) A "\0" B "\0" +#define MSG_3_LINE(A,B,C) A "\0" B "\0" C diff --git a/src/core/serial.cpp b/src/core/serial.cpp new file mode 100644 index 0000000..990c892 --- /dev/null +++ b/src/core/serial.cpp @@ -0,0 +1,110 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "serial.h" +#include "../inc/MarlinConfig.h" + +#if HAS_ETHERNET + #include "../feature/ethernet.h" +#endif + +uint8_t marlin_debug_flags = MARLIN_DEBUG_NONE; + +// Commonly-used strings in serial output +PGMSTR(SP_A_STR, " A"); PGMSTR(SP_B_STR, " B"); PGMSTR(SP_C_STR, " C"); +PGMSTR(SP_P_STR, " P"); PGMSTR(SP_T_STR, " T"); PGMSTR(NUL_STR, ""); + +#define _N_STR(N) PGMSTR(N##_STR, STR_##N); +#define _N_LBL(N) PGMSTR(N##_LBL, STR_##N ":"); +#define _SP_N_STR(N) PGMSTR(SP_##N##_STR, " " STR_##N); +#define _SP_N_LBL(N) PGMSTR(SP_##N##_LBL, " " STR_##N ":"); +MAP(_N_STR, LOGICAL_AXIS_NAMES); MAP(_SP_N_STR, LOGICAL_AXIS_NAMES); +MAP(_N_LBL, LOGICAL_AXIS_NAMES); MAP(_SP_N_LBL, LOGICAL_AXIS_NAMES); + +// Hook Meatpack if it's enabled on the first leaf +#if ENABLED(MEATPACK_ON_SERIAL_PORT_1) + SerialLeafT1 mpSerial1(false, _SERIAL_LEAF_1); +#endif +#if ENABLED(MEATPACK_ON_SERIAL_PORT_2) + SerialLeafT2 mpSerial2(false, _SERIAL_LEAF_2); +#endif +#if ENABLED(MEATPACK_ON_SERIAL_PORT_3) + SerialLeafT3 mpSerial3(false, _SERIAL_LEAF_3); +#endif + +// Step 2: For multiserial, handle the second serial port as well +#if HAS_MULTI_SERIAL + #if HAS_ETHERNET + // We need a definition here + SerialLeafT2 msSerial2(ethernet.have_telnet_client, MYSERIAL2, false); + #endif + + #define __S_LEAF(N) ,SERIAL_LEAF_##N + #define _S_LEAF(N) __S_LEAF(N) + + SerialOutputT multiSerial( SERIAL_LEAF_1 REPEAT_S(2, INCREMENT(NUM_SERIAL), _S_LEAF) ); + + #undef __S_LEAF + #undef _S_LEAF + +#endif + +void serial_print_P(PGM_P str) { + while (const char c = pgm_read_byte(str++)) SERIAL_CHAR(c); +} + +void serial_echo_start() { serial_print(F("echo:")); } +void serial_error_start() { serial_print(F("Error:")); } + +void serial_spaces(uint8_t count) { count *= (PROPORTIONAL_FONT_RATIO); while (count--) SERIAL_CHAR(' '); } + +void serial_offset(const_float_t v, const uint8_t sp/*=0*/) { + if (v == 0 && sp == 1) + SERIAL_CHAR(' '); + else if (v > 0 || (v == 0 && sp == 2)) + SERIAL_CHAR('+'); + SERIAL_DECIMAL(v); +} + +void serial_ternary(const bool onoff, FSTR_P const pre, FSTR_P const on, FSTR_P const off, FSTR_P const post/*=nullptr*/) { + if (pre) serial_print(pre); + serial_print(onoff ? on : off); + if (post) serial_print(post); +} +void serialprint_onoff(const bool onoff) { serial_print(onoff ? F(STR_ON) : F(STR_OFF)); } +void serialprintln_onoff(const bool onoff) { serialprint_onoff(onoff); SERIAL_EOL(); } +void serialprint_truefalse(const bool tf) { serial_print(tf ? F("true") : F("false")); } + +void print_bin(uint16_t val) { + for (uint8_t i = 16; i--;) { + SERIAL_CHAR('0' + TEST(val, i)); + if (!(i & 0x3) && i) SERIAL_CHAR(' '); + } +} + +void print_pos(NUM_AXIS_ARGS(const_float_t), FSTR_P const prefix/*=nullptr*/, FSTR_P const suffix/*=nullptr*/) { + if (prefix) serial_print(prefix); + SERIAL_ECHOPGM_P( + LIST_N(DOUBLE(NUM_AXES), SP_X_STR, x, SP_Y_STR, y, SP_Z_STR, z, SP_I_STR, i, SP_J_STR, j, SP_K_STR, k) + ); + if (suffix) serial_print(suffix); else SERIAL_EOL(); +} diff --git a/src/core/serial.h b/src/core/serial.h new file mode 100644 index 0000000..c19bc08 --- /dev/null +++ b/src/core/serial.h @@ -0,0 +1,374 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" +#include "serial_hook.h" + +#if HAS_MEATPACK + #include "../feature/meatpack.h" +#endif + +// +// Debugging flags for use by M111 +// +enum MarlinDebugFlags : uint8_t { + MARLIN_DEBUG_NONE = 0, + MARLIN_DEBUG_ECHO = _BV(0), ///< Echo commands in order as they are processed + MARLIN_DEBUG_INFO = _BV(1), ///< Print messages for code that has debug output + MARLIN_DEBUG_ERRORS = _BV(2), ///< Not implemented + MARLIN_DEBUG_DRYRUN = _BV(3), ///< Ignore temperature setting and E movement commands + MARLIN_DEBUG_COMMUNICATION = _BV(4), ///< Not implemented + #if ENABLED(DEBUG_LEVELING_FEATURE) + MARLIN_DEBUG_LEVELING = _BV(5), ///< Print detailed output for homing and leveling + MARLIN_DEBUG_MESH_ADJUST = _BV(6), ///< UBL bed leveling + #else + MARLIN_DEBUG_LEVELING = 0, + MARLIN_DEBUG_MESH_ADJUST = 0, + #endif + MARLIN_DEBUG_ALL = 0xFF +}; + +extern uint8_t marlin_debug_flags; +#define DEBUGGING(F) (marlin_debug_flags & (MARLIN_DEBUG_## F)) + +// +// Serial redirection +// +// Step 1: Find out what the first serial leaf is +#if HAS_MULTI_SERIAL && defined(SERIAL_CATCHALL) + #define _SERIAL_LEAF_1 MYSERIAL +#else + #define _SERIAL_LEAF_1 MYSERIAL1 +#endif + +// Hook Meatpack if it's enabled on the first leaf +#if ENABLED(MEATPACK_ON_SERIAL_PORT_1) + typedef MeatpackSerial SerialLeafT1; + extern SerialLeafT1 mpSerial1; + #define SERIAL_LEAF_1 mpSerial1 +#else + #define SERIAL_LEAF_1 _SERIAL_LEAF_1 +#endif + +// Step 2: For multiserial wrap all serial ports in a single +// interface with the ability to output to multiple serial ports. +#if HAS_MULTI_SERIAL + #define _PORT_REDIRECT(n,p) REMEMBER(n,multiSerial.portMask,p) + #define _PORT_RESTORE(n) RESTORE(n) + #define SERIAL_ASSERT(P) if (multiSerial.portMask!=(P)) { debugger(); } + // If we have a catchall, use that directly + #ifdef SERIAL_CATCHALL + #define _SERIAL_LEAF_2 SERIAL_CATCHALL + #elif HAS_ETHERNET + typedef ConditionalSerial SerialLeafT2; // We need to create an instance here + extern SerialLeafT2 msSerial2; + #define _SERIAL_LEAF_2 msSerial2 + #else + #define _SERIAL_LEAF_2 MYSERIAL2 // Don't create a useless instance here, directly use the existing instance + #endif + + // Nothing complicated here + #define _SERIAL_LEAF_3 MYSERIAL3 + + // Hook Meatpack if it's enabled on the second leaf + #if ENABLED(MEATPACK_ON_SERIAL_PORT_2) + typedef MeatpackSerial SerialLeafT2; + extern SerialLeafT2 mpSerial2; + #define SERIAL_LEAF_2 mpSerial2 + #else + #define SERIAL_LEAF_2 _SERIAL_LEAF_2 + #endif + + // Hook Meatpack if it's enabled on the third leaf + #if ENABLED(MEATPACK_ON_SERIAL_PORT_3) + typedef MeatpackSerial SerialLeafT3; + extern SerialLeafT3 mpSerial3; + #define SERIAL_LEAF_3 mpSerial3 + #else + #define SERIAL_LEAF_3 _SERIAL_LEAF_3 + #endif + + #define __S_MULTI(N) decltype(SERIAL_LEAF_##N), + #define _S_MULTI(N) __S_MULTI(N) + + typedef MultiSerial< REPEAT_1(NUM_SERIAL, _S_MULTI) 0> SerialOutputT; + + #undef __S_MULTI + #undef _S_MULTI + + extern SerialOutputT multiSerial; + #define SERIAL_IMPL multiSerial +#else + #define _PORT_REDIRECT(n,p) NOOP + #define _PORT_RESTORE(n) NOOP + #define SERIAL_ASSERT(P) NOOP + #define SERIAL_IMPL SERIAL_LEAF_1 +#endif + +#define SERIAL_OUT(WHAT, V...) (void)SERIAL_IMPL.WHAT(V) + +#define PORT_REDIRECT(p) _PORT_REDIRECT(1,p) +#define PORT_RESTORE() _PORT_RESTORE(1) +#define SERIAL_PORTMASK(P) SerialMask::from(P) + +// +// SERIAL_CHAR - Print one or more individual chars +// +inline void SERIAL_CHAR(char a) { SERIAL_IMPL.write(a); } +template +void SERIAL_CHAR(char a, Args ... args) { SERIAL_IMPL.write(a); SERIAL_CHAR(args ...); } + +/** + * SERIAL_ECHO - Print a single string or value. + * Any numeric parameter (including char) is printed as a base-10 number. + * A string pointer or literal will be output as a string. + * + * NOTE: Use SERIAL_CHAR to print char as a single character. + */ +template +void SERIAL_ECHO(T x) { SERIAL_IMPL.print(x); } + +// Wrapper for ECHO commands to interpret a char +typedef struct SerialChar { char c; SerialChar(char n) : c(n) { } } serial_char_t; +inline void SERIAL_ECHO(serial_char_t x) { SERIAL_IMPL.write(x.c); } +#define AS_CHAR(C) serial_char_t(C) +#define AS_DIGIT(C) AS_CHAR('0' + (C)) + +template +void SERIAL_ECHOLN(T x) { SERIAL_IMPL.println(x); } + +// SERIAL_PRINT works like SERIAL_ECHO but also takes the numeric base +template +void SERIAL_PRINT(T x, U y) { SERIAL_IMPL.print(x, y); } + +template +void SERIAL_PRINTLN(T x, PrintBase y) { SERIAL_IMPL.println(x, y); } + +// Flush the serial port +inline void SERIAL_FLUSH() { SERIAL_IMPL.flush(); } +inline void SERIAL_FLUSHTX() { SERIAL_IMPL.flushTX(); } + +// Serial echo and error prefixes +#define SERIAL_ECHO_START() serial_echo_start() +#define SERIAL_ERROR_START() serial_error_start() + +// Serial end-of-line +#define SERIAL_EOL() SERIAL_CHAR('\n') + +// Print a single PROGMEM, PGM_P, or PSTR() string. +void serial_print_P(PGM_P str); +inline void serial_println_P(PGM_P str) { serial_print_P(str); SERIAL_EOL(); } + +// Print a single FSTR_P, F(), or FPSTR() string. +inline void serial_print(FSTR_P const fstr) { serial_print_P(FTOP(fstr)); } +inline void serial_println(FSTR_P const fstr) { serial_println_P(FTOP(fstr)); } + +// +// SERIAL_ECHOPGM... macros are used to output string-value pairs. +// + +// Print up to 20 pairs of values. Odd elements must be literal strings. +#define __SEP_N(N,V...) _SEP_##N(V) +#define _SEP_N(N,V...) __SEP_N(N,V) +#define _SEP_N_REF() _SEP_N +#define _SEP_1(s) serial_print(F(s)); +#define _SEP_2(s,v) serial_echopair(F(s),v); +#define _SEP_3(s,v,V...) _SEP_2(s,v); DEFER2(_SEP_N_REF)()(TWO_ARGS(V),V); +#define SERIAL_ECHOPGM(V...) do{ EVAL(_SEP_N(TWO_ARGS(V),V)); }while(0) + +// Print up to 20 pairs of values followed by newline. Odd elements must be literal strings. +#define __SELP_N(N,V...) _SELP_##N(V) +#define _SELP_N(N,V...) __SELP_N(N,V) +#define _SELP_N_REF() _SELP_N +#define _SELP_1(s) serial_print(F(s "\n")); +#define _SELP_2(s,v) serial_echolnpair(F(s),v); +#define _SELP_3(s,v,V...) _SEP_2(s,v); DEFER2(_SELP_N_REF)()(TWO_ARGS(V),V); +#define SERIAL_ECHOLNPGM(V...) do{ EVAL(_SELP_N(TWO_ARGS(V),V)); }while(0) + +// Print up to 20 pairs of values. Odd elements must be PSTR pointers. +#define __SEP_N_P(N,V...) _SEP_##N##_P(V) +#define _SEP_N_P(N,V...) __SEP_N_P(N,V) +#define _SEP_N_P_REF() _SEP_N_P +#define _SEP_1_P(p) serial_print_P(p); +#define _SEP_2_P(p,v) serial_echopair_P(p,v); +#define _SEP_3_P(p,v,V...) _SEP_2_P(p,v); DEFER2(_SEP_N_P_REF)()(TWO_ARGS(V),V); +#define SERIAL_ECHOPGM_P(V...) do{ EVAL(_SEP_N_P(TWO_ARGS(V),V)); }while(0) + +// Print up to 20 pairs of values followed by newline. Odd elements must be PSTR pointers. +#define __SELP_N_P(N,V...) _SELP_##N##_P(V) +#define _SELP_N_P(N,V...) __SELP_N_P(N,V) +#define _SELP_N_P_REF() _SELP_N_P +#define _SELP_1_P(p) serial_println_P(p) +#define _SELP_2_P(p,v) serial_echolnpair_P(p,v) +#define _SELP_3_P(p,v,V...) { _SEP_2_P(p,v); DEFER2(_SELP_N_P_REF)()(TWO_ARGS(V),V); } +#define SERIAL_ECHOLNPGM_P(V...) do{ EVAL(_SELP_N_P(TWO_ARGS(V),V)); }while(0) + +// Print up to 20 pairs of values. Odd elements must be FSTR_P, F(), or FPSTR(). +#define __SEP_N_F(N,V...) _SEP_##N##_F(V) +#define _SEP_N_F(N,V...) __SEP_N_F(N,V) +#define _SEP_N_F_REF() _SEP_N_F +#define _SEP_1_F(p) serial_print(p); +#define _SEP_2_F(p,v) serial_echopair(p,v); +#define _SEP_3_F(p,v,V...) _SEP_2_F(p,v); DEFER2(_SEP_N_F_REF)()(TWO_ARGS(V),V); +#define SERIAL_ECHOF(V...) do{ EVAL(_SEP_N_F(TWO_ARGS(V),V)); }while(0) + +// Print up to 20 pairs of values followed by newline. Odd elements must be FSTR_P, F(), or FPSTR(). +#define __SELP_N_F(N,V...) _SELP_##N##_F(V) +#define _SELP_N_F(N,V...) __SELP_N_F(N,V) +#define _SELP_N_F_REF() _SELP_N_F +#define _SELP_1_F(p) serial_println(p) +#define _SELP_2_F(p,v) serial_echolnpair(p,v) +#define _SELP_3_F(p,v,V...) { _SEP_2_F(p,v); DEFER2(_SELP_N_F_REF)()(TWO_ARGS(V),V); } +#define SERIAL_ECHOLNF(V...) do{ EVAL(_SELP_N_F(TWO_ARGS(V),V)); }while(0) + +#ifdef AllowDifferentTypeInList + + inline void SERIAL_ECHOLIST_IMPL() {} + template + void SERIAL_ECHOLIST_IMPL(T && t) { SERIAL_IMPL.print(t); } + + template + void SERIAL_ECHOLIST_IMPL(T && t, Args && ... args) { + SERIAL_IMPL.print(t); + serial_print(F(", ")); + SERIAL_ECHOLIST_IMPL(args...); + } + + template + void SERIAL_ECHOLIST(FSTR_P const str, Args && ... args) { + SERIAL_IMPL.print(FTOP(str)); + SERIAL_ECHOLIST_IMPL(args...); + } + +#else // Optimization if the listed type are all the same (seems to be the case in the codebase so use that instead) + + template + void SERIAL_ECHOLIST(FSTR_P const fstr, Args && ... args) { + serial_print(fstr); + typename Private::first_type_of::type values[] = { args... }; + constexpr size_t argsSize = sizeof...(args); + for (size_t i = 0; i < argsSize; i++) { + if (i) serial_print(F(", ")); + SERIAL_IMPL.print(values[i]); + } + } + +#endif + +// SERIAL_ECHO_F prints a floating point value with optional precision +inline void SERIAL_ECHO_F(EnsureDouble x, int digit=2) { SERIAL_IMPL.print(x, digit); } + +#define SERIAL_ECHOPAIR_F_P(P,V...) do{ serial_print_P(P); SERIAL_ECHO_F(V); }while(0) +#define SERIAL_ECHOLNPAIR_F_P(P,V...) do{ SERIAL_ECHOPAIR_F_P(P,V); SERIAL_EOL(); }while(0) + +#define SERIAL_ECHOPAIR_F_F(S,V...) do{ serial_print(S); SERIAL_ECHO_F(V); }while(0) +#define SERIAL_ECHOLNPAIR_F_F(S,V...) do{ SERIAL_ECHOPAIR_F_F(S,V); SERIAL_EOL(); }while(0) + +#define SERIAL_ECHOPAIR_F(S,V...) SERIAL_ECHOPAIR_F_F(F(S),V) +#define SERIAL_ECHOLNPAIR_F(V...) do{ SERIAL_ECHOPAIR_F(V); SERIAL_EOL(); }while(0) + +#define SERIAL_ECHO_MSG(V...) do{ SERIAL_ECHO_START(); SERIAL_ECHOLNPGM(V); }while(0) +#define SERIAL_ERROR_MSG(V...) do{ SERIAL_ERROR_START(); SERIAL_ECHOLNPGM(V); }while(0) + +#define SERIAL_ECHO_SP(C) serial_spaces(C) + +#define SERIAL_ECHO_TERNARY(TF, PRE, ON, OFF, POST) serial_ternary(TF, F(PRE), F(ON), F(OFF), F(POST)) + +#if SERIAL_FLOAT_PRECISION + #define SERIAL_DECIMAL(V) SERIAL_PRINT(V, SERIAL_FLOAT_PRECISION) +#else + #define SERIAL_DECIMAL(V) SERIAL_ECHO(V) +#endif + +// +// Functions for serial printing from PROGMEM. (Saves loads of SRAM.) +// +inline void serial_echopair_P(PGM_P const pstr, serial_char_t v) { serial_print_P(pstr); SERIAL_CHAR(v.c); } +inline void serial_echopair_P(PGM_P const pstr, float v) { serial_print_P(pstr); SERIAL_DECIMAL(v); } +inline void serial_echopair_P(PGM_P const pstr, double v) { serial_print_P(pstr); SERIAL_DECIMAL(v); } +//inline void serial_echopair_P(PGM_P const pstr, const char *v) { serial_print_P(pstr); SERIAL_ECHO(v); } +inline void serial_echopair_P(PGM_P const pstr, FSTR_P v) { serial_print_P(pstr); SERIAL_ECHOF(v); } + +// Default implementation for types without a specialization. Handles integers. +template +inline void serial_echopair_P(PGM_P const pstr, T v) { serial_print_P(pstr); SERIAL_ECHO(v); } + +// Add a newline. +template +inline void serial_echolnpair_P(PGM_P const pstr, T v) { serial_echopair_P(pstr, v); SERIAL_EOL(); } + +// Catch-all for __FlashStringHelper * +template +inline void serial_echopair(FSTR_P const fstr, T v) { serial_echopair_P(FTOP(fstr), v); } + +// Add a newline to the serial output +template +inline void serial_echolnpair(FSTR_P const fstr, T v) { serial_echolnpair_P(FTOP(fstr), v); } + +void serial_echo_start(); +void serial_error_start(); +void serial_ternary(const bool onoff, FSTR_P const pre, FSTR_P const on, FSTR_P const off, FSTR_P const post=nullptr); +void serialprint_onoff(const bool onoff); +void serialprintln_onoff(const bool onoff); +void serialprint_truefalse(const bool tf); +void serial_spaces(uint8_t count); +void serial_offset(const_float_t v, const uint8_t sp=0); // For v==0 draw space (sp==1) or plus (sp==2) + +void print_bin(const uint16_t val); +void print_pos(NUM_AXIS_ARGS(const_float_t), FSTR_P const prefix=nullptr, FSTR_P const suffix=nullptr); + +inline void print_pos(const xyz_pos_t &xyz, FSTR_P const prefix=nullptr, FSTR_P const suffix=nullptr) { + print_pos(NUM_AXIS_ELEM(xyz), prefix, suffix); +} + +#define SERIAL_POS(SUFFIX,VAR) do { print_pos(VAR, F(" " STRINGIFY(VAR) "="), F(" : " SUFFIX "\n")); }while(0) +#define SERIAL_XYZ(PREFIX,V...) do { print_pos(V, F(PREFIX)); }while(0) + +// +// Commonly-used strings in serial output +// + +#define _N_STR(N) N##_STR +#define _N_LBL(N) N##_LBL +#define _N_STR_A(N) _N_STR(N)[] +#define _N_LBL_A(N) _N_LBL(N)[] +#define _SP_N_STR(N) SP_##N##_STR +#define _SP_N_LBL(N) SP_##N##_LBL +#define _SP_N_STR_A(N) _SP_N_STR(N)[] +#define _SP_N_LBL_A(N) _SP_N_LBL(N)[] + +extern const char SP_A_STR[], SP_B_STR[], SP_C_STR[], SP_P_STR[], SP_T_STR[], NUL_STR[], + MAPLIST(_N_STR_A, LOGICAL_AXIS_NAMES), MAPLIST(_SP_N_STR_A, LOGICAL_AXIS_NAMES), + MAPLIST(_N_LBL_A, LOGICAL_AXIS_NAMES), MAPLIST(_SP_N_LBL_A, LOGICAL_AXIS_NAMES); + +PGM_P const SP_AXIS_LBL[] PROGMEM = { MAPLIST(_SP_N_LBL, LOGICAL_AXIS_NAMES) }; +PGM_P const SP_AXIS_STR[] PROGMEM = { MAPLIST(_SP_N_STR, LOGICAL_AXIS_NAMES) }; + +#undef _N_STR +#undef _N_LBL +#undef _N_STR_A +#undef _N_LBL_A +#undef _SP_N_STR +#undef _SP_N_LBL +#undef _SP_N_STR_A +#undef _SP_N_LBL_A diff --git a/src/core/serial_base.h b/src/core/serial_base.h new file mode 100644 index 0000000..a5abd67 --- /dev/null +++ b/src/core/serial_base.h @@ -0,0 +1,258 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(EMERGENCY_PARSER) + #include "../feature/e_parser.h" +#endif + +// Used in multiple places +// You can build it but not manipulate it. +// There are only few places where it's required to access the underlying member: GCodeQueue, SerialMask and MultiSerial +struct serial_index_t { + // A signed index, where -1 is a special case meaning no action (neither output or input) + int8_t index; + + // Check if the index is within the range [a ... b] + constexpr inline bool within(const int8_t a, const int8_t b) const { return WITHIN(index, a, b); } + constexpr inline bool valid() const { return WITHIN(index, 0, 7); } // At most, 8 bits + + // Construction is either from an index + constexpr serial_index_t(const int8_t index) : index(index) {} + + // Default to "no index" + constexpr serial_index_t() : index(-1) {} +}; + +// In order to catch usage errors in code, we make the base to encode number explicit +// If given a number (and not this enum), the compiler will reject the overload, falling back to the (double, digit) version +// We don't want hidden conversion of the first parameter to double, so it has to be as hard to do for the compiler as creating this enum +enum class PrintBase { + Dec = 10, + Hex = 16, + Oct = 8, + Bin = 2 +}; + +// A simple feature list enumeration +enum class SerialFeature { + None = 0x00, + MeatPack = 0x01, //!< Enabled when Meatpack is present + BinaryFileTransfer = 0x02, //!< Enabled for BinaryFile transfer support (in the future) + Virtual = 0x04, //!< Enabled for virtual serial port (like Telnet / Websocket / ...) + Hookable = 0x08, //!< Enabled if the serial class supports a setHook method +}; +ENUM_FLAGS(SerialFeature); + +// flushTX is not implemented in all HAL, so use SFINAE to call the method where it is. +CALL_IF_EXISTS_IMPL(void, flushTX); +CALL_IF_EXISTS_IMPL(bool, connected, true); +CALL_IF_EXISTS_IMPL(SerialFeature, features, SerialFeature::None); + +// A simple forward struct to prevent the compiler from selecting print(double, int) as a default overload +// for any type other than double/float. For double/float, a conversion exists so the call will be invisible. +struct EnsureDouble { + double a; + operator double() { return a; } + // If the compiler breaks on ambiguity here, it's likely because print(X, base) is called with X not a double/float, and + // a base that's not a PrintBase value. This code is made to detect the error. You MUST set a base explicitly like this: + // SERIAL_PRINT(v, PrintBase::Hex) + EnsureDouble(double a) : a(a) {} + EnsureDouble(float a) : a(a) {} +}; + +// Using Curiously-Recurring Template Pattern here to avoid virtual table cost when compiling. +// Since the real serial class is known at compile time, this results in the compiler writing +// a completely efficient code. +template +struct SerialBase { + #if ENABLED(EMERGENCY_PARSER) + const bool ep_enabled; + EmergencyParser::State emergency_state; + inline bool emergency_parser_enabled() { return ep_enabled; } + SerialBase(bool ep_capable) : ep_enabled(ep_capable), emergency_state(EmergencyParser::State::EP_RESET) {} + #else + SerialBase(const bool) {} + #endif + + #define SerialChild static_cast(this) + + // Static dispatch methods below: + // The most important method here is where it all ends to: + void write(uint8_t c) { SerialChild->write(c); } + + // Called when the parser finished processing an instruction, usually build to nothing + void msgDone() const { SerialChild->msgDone(); } + + // Called on initialization + void begin(const long baudRate) { SerialChild->begin(baudRate); } + + // Called on destruction + void end() { SerialChild->end(); } + + /** Check for available data from the port + @param index The port index, usually 0 */ + int available(serial_index_t index=0) const { return SerialChild->available(index); } + + /** Read a value from the port + @param index The port index, usually 0 */ + int read(serial_index_t index=0) { return SerialChild->read(index); } + + /** Combine the features of this serial instance and return it + @param index The port index, usually 0 */ + SerialFeature features(serial_index_t index=0) const { return static_cast(this)->features(index); } + + // Check if the serial port has a feature + bool has_feature(serial_index_t index, SerialFeature flag) const { return (features(index) & flag) != SerialFeature::None; } + + // Check if the serial port is connected (usually bypassed) + bool connected() const { return SerialChild->connected(); } + + // Redirect flush + void flush() { SerialChild->flush(); } + + // Not all implementation have a flushTX, so let's call them only if the child has the implementation + void flushTX() { CALL_IF_EXISTS(void, SerialChild, flushTX); } + + // Glue code here + void write(const char *str) { while (*str) write(*str++); } + void write(const uint8_t *buffer, size_t size) { while (size--) write(*buffer++); } + void print(char *str) { write(str); } + void print(const char *str) { write(str); } + // No default argument to avoid ambiguity + + // Define print for every fundamental integer type, to ensure that all redirect properly + // to the correct underlying implementation. + + // Prints are performed with a single size, to avoid needing multiple print functions. + // The fixed integer size used for prints will be the larger of long or a pointer. + #if __LONG_WIDTH__ >= __INTPTR_WIDTH__ + typedef long int_fixed_print_t; + typedef unsigned long uint_fixed_print_t; + #else + typedef intptr_t int_fixed_print_t; + typedef uintptr_t uint_fixed_print_t; + + FORCE_INLINE void print(intptr_t c, PrintBase base) { printNumber_signed(c, base); } + FORCE_INLINE void print(uintptr_t c, PrintBase base) { printNumber_unsigned(c, base); } + #endif + + FORCE_INLINE void print(char c, PrintBase base) { printNumber_signed(c, base); } + FORCE_INLINE void print(short c, PrintBase base) { printNumber_signed(c, base); } + FORCE_INLINE void print(int c, PrintBase base) { printNumber_signed(c, base); } + FORCE_INLINE void print(long c, PrintBase base) { printNumber_signed(c, base); } + FORCE_INLINE void print(unsigned char c, PrintBase base) { printNumber_unsigned(c, base); } + FORCE_INLINE void print(unsigned short c, PrintBase base) { printNumber_unsigned(c, base); } + FORCE_INLINE void print(unsigned int c, PrintBase base) { printNumber_unsigned(c, base); } + FORCE_INLINE void print(unsigned long c, PrintBase base) { printNumber_unsigned(c, base); } + + + void print(EnsureDouble c, int digits) { printFloat(c, digits); } + + // Forward the call to the former's method + + // Default implementation for anything without a specialization + // This handles integers since they are the most common + template + void print(T c) { print(c, PrintBase::Dec); } + + void print(float c) { print(c, 2); } + void print(double c) { print(c, 2); } + + void println(char *s) { print(s); println(); } + void println(const char *s) { print(s); println(); } + void println(float c, int digits) { print(c, digits); println(); } + void println(double c, int digits) { print(c, digits); println(); } + void println() { write('\r'); write('\n'); } + + // Default implementations for types without a specialization. Handles integers. + template + void println(T c, PrintBase base) { print(c, base); println(); } + + template + void println(T c) { println(c, PrintBase::Dec); } + + // Forward the call to the former's method + void println(float c) { println(c, 2); } + void println(double c) { println(c, 2); } + + // Print a number with the given base + NO_INLINE void printNumber_unsigned(uint_fixed_print_t n, PrintBase base) { + if (n) { + unsigned char buf[8 * sizeof(long)]; // Enough space for base 2 + int8_t i = 0; + while (n) { + buf[i++] = n % (uint_fixed_print_t)base; + n /= (uint_fixed_print_t)base; + } + while (i--) write((char)(buf[i] + (buf[i] < 10 ? '0' : 'A' - 10))); + } + else write('0'); + } + + NO_INLINE void printNumber_signed(int_fixed_print_t n, PrintBase base) { + if (base == PrintBase::Dec && n < 0) { + n = -n; // This works because all platforms Marlin's builds on are using 2-complement encoding for negative number + // On such CPU, changing the sign of a number is done by inverting the bits and adding one, so if n = 0x80000000 = -2147483648 then + // -n = 0x7FFFFFFF + 1 => 0x80000000 = 2147483648 (if interpreted as unsigned) or -2147483648 if interpreted as signed. + // On non 2-complement CPU, there would be no possible representation for 2147483648. + write('-'); + } + printNumber_unsigned((uint_fixed_print_t)n , base); + } + + // Print a decimal number + NO_INLINE void printFloat(double number, uint8_t digits) { + // Handle negative numbers + if (number < 0.0) { + write('-'); + number = -number; + } + + // Round correctly so that print(1.999, 2) prints as "2.00" + double rounding = 0.5; + LOOP_L_N(i, digits) rounding *= 0.1; + number += rounding; + + // Extract the integer part of the number and print it + unsigned long int_part = (unsigned long)number; + double remainder = number - (double)int_part; + printNumber_unsigned(int_part, PrintBase::Dec); + + // Print the decimal point, but only if there are digits beyond + if (digits) { + write('.'); + // Extract digits from the remainder one at a time + while (digits--) { + remainder *= 10.0; + unsigned long toPrint = (unsigned long)remainder; + printNumber_unsigned(toPrint, PrintBase::Dec); + remainder -= toPrint; + } + } + } +}; + +// All serial instances will be built by chaining the features required +// for the function in the form of a template type definition. diff --git a/src/core/serial_hook.h b/src/core/serial_hook.h new file mode 100644 index 0000000..65c553c --- /dev/null +++ b/src/core/serial_hook.h @@ -0,0 +1,308 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "serial_base.h" + +// A mask containing a bitmap of the serial port to act upon +// This is written to ensure a serial index is never used as a serial mask +class SerialMask { + uint8_t mask; + + // This constructor is private to ensure you can't convert an index to a mask + // The compiler will stop here if you are mixing index and mask in your code. + // If you need to, you'll have to use the explicit static "from" method here + SerialMask(const serial_index_t); + +public: + inline constexpr bool enabled(const SerialMask PortMask) const { return mask & PortMask.mask; } + inline constexpr SerialMask combine(const SerialMask other) const { return SerialMask(mask | other.mask); } + inline constexpr SerialMask operator<< (const int offset) const { return SerialMask(mask << offset); } + static SerialMask from(const serial_index_t index) { + if (index.valid()) return SerialMask(_BV(index.index)); + return SerialMask(0); // A invalid index mean no output + } + + constexpr SerialMask(const uint8_t mask) : mask(mask) {} + constexpr SerialMask(const SerialMask &rs) : mask(rs.mask) {} // Can't use = default here since not all frameworks support this + + SerialMask& operator=(const SerialMask &rs) { mask = rs.mask; return *this; } + + static constexpr uint8_t All = 0xFF; +}; + +// The most basic serial class: it dispatch to the base serial class with no hook whatsoever. This will compile to nothing but the base serial class +template +struct BaseSerial : public SerialBase< BaseSerial >, public SerialT { + typedef SerialBase< BaseSerial > BaseClassT; + + // It's required to implement a write method here to help compiler disambiguate what method to call + using SerialT::write; + using SerialT::flush; + + void msgDone() {} + + // We don't care about indices here, since if one can call us, it's the right index anyway + int available(serial_index_t) { return (int)SerialT::available(); } + int read(serial_index_t) { return (int)SerialT::read(); } + bool connected() { return CALL_IF_EXISTS(bool, static_cast(this), connected);; } + void flushTX() { CALL_IF_EXISTS(void, static_cast(this), flushTX); } + + SerialFeature features(serial_index_t index) const { return CALL_IF_EXISTS(SerialFeature, static_cast(this), features, index); } + + // Two implementations of the same method exist in both base classes so indicate the right one + using SerialT::available; + using SerialT::read; + using SerialT::begin; + using SerialT::end; + + using BaseClassT::print; + using BaseClassT::println; + + BaseSerial(const bool e) : BaseClassT(e) {} + + // Forward constructor + template + BaseSerial(const bool e, Args... args) : BaseClassT(e), SerialT(args...) {} +}; + +// A serial with a condition checked at runtime for its output +// A bit less efficient than static dispatching but since it's only used for ethernet's serial output right now, it's ok. +template +struct ConditionalSerial : public SerialBase< ConditionalSerial > { + typedef SerialBase< ConditionalSerial > BaseClassT; + + bool & condition; + SerialT & out; + NO_INLINE size_t write(uint8_t c) { if (condition) return out.write(c); return 0; } + void flush() { if (condition) out.flush(); } + void begin(long br) { out.begin(br); } + void end() { out.end(); } + + void msgDone() {} + bool connected() { return CALL_IF_EXISTS(bool, &out, connected); } + void flushTX() { CALL_IF_EXISTS(void, &out, flushTX); } + + int available(serial_index_t) { return (int)out.available(); } + int read(serial_index_t) { return (int)out.read(); } + int available() { return (int)out.available(); } + int read() { return (int)out.read(); } + SerialFeature features(serial_index_t index) const { return CALL_IF_EXISTS(SerialFeature, &out, features, index); } + + ConditionalSerial(bool & conditionVariable, SerialT & out, const bool e) : BaseClassT(e), condition(conditionVariable), out(out) {} +}; + +// A simple forward class that taking a reference to an existing serial instance (likely created in their respective framework) +template +struct ForwardSerial : public SerialBase< ForwardSerial > { + typedef SerialBase< ForwardSerial > BaseClassT; + + SerialT & out; + NO_INLINE size_t write(uint8_t c) { return out.write(c); } + void flush() { out.flush(); } + void begin(long br) { out.begin(br); } + void end() { out.end(); } + + void msgDone() {} + // Existing instances implement Arduino's operator bool, so use that if it's available + bool connected() { return Private::HasMember_connected::value ? CALL_IF_EXISTS(bool, &out, connected) : (bool)out; } + void flushTX() { CALL_IF_EXISTS(void, &out, flushTX); } + + int available(serial_index_t) { return (int)out.available(); } + int read(serial_index_t) { return (int)out.read(); } + int available() { return (int)out.available(); } + int read() { return (int)out.read(); } + SerialFeature features(serial_index_t index) const { return CALL_IF_EXISTS(SerialFeature, &out, features, index); } + + ForwardSerial(const bool e, SerialT & out) : BaseClassT(e), out(out) {} +}; + +// A class that can be hooked and unhooked at runtime, useful to capture the output of the serial interface +template +struct RuntimeSerial : public SerialBase< RuntimeSerial >, public SerialT { + typedef SerialBase< RuntimeSerial > BaseClassT; + typedef void (*WriteHook)(void * userPointer, uint8_t c); + typedef void (*EndOfMessageHook)(void * userPointer); + + WriteHook writeHook; + EndOfMessageHook eofHook; + void * userPointer; + + NO_INLINE size_t write(uint8_t c) { + if (writeHook) writeHook(userPointer, c); + return SerialT::write(c); + } + + NO_INLINE void msgDone() { + if (eofHook) eofHook(userPointer); + } + + int available(serial_index_t) { return (int)SerialT::available(); } + int read(serial_index_t) { return (int)SerialT::read(); } + using SerialT::available; + using SerialT::read; + using SerialT::flush; + using SerialT::begin; + using SerialT::end; + + using BaseClassT::print; + using BaseClassT::println; + + // Underlying implementation might use Arduino's bool operator + bool connected() { + return Private::HasMember_connected::value + ? CALL_IF_EXISTS(bool, static_cast(this), connected) + : static_cast(this)->operator bool(); + } + + void flushTX() { CALL_IF_EXISTS(void, static_cast(this), flushTX); } + + // Append Hookable for this class + SerialFeature features(serial_index_t index) const { return SerialFeature::Hookable | CALL_IF_EXISTS(SerialFeature, static_cast(this), features, index); } + + void setHook(WriteHook writeHook = 0, EndOfMessageHook eofHook = 0, void * userPointer = 0) { + // Order is important here as serial code can be called inside interrupts + // When setting a hook, the user pointer must be set first so if writeHook is called as soon as it's set, it'll be valid + if (userPointer) this->userPointer = userPointer; + this->writeHook = writeHook; + this->eofHook = eofHook; + // Order is important here because of asynchronous access here + // When unsetting a hook, the user pointer must be unset last so that any pending writeHook is still using the old pointer + if (!userPointer) this->userPointer = 0; + } + + RuntimeSerial(const bool e) : BaseClassT(e), writeHook(0), eofHook(0), userPointer(0) {} + + // Forward constructor + template + RuntimeSerial(const bool e, Args... args) : BaseClassT(e), SerialT(args...), writeHook(0), eofHook(0), userPointer(0) {} +}; + +#define _S_CLASS(N) class Serial##N##T, +#define _S_NAME(N) Serial##N##T, + +template < REPEAT(NUM_SERIAL, _S_CLASS) const uint8_t offset=0, const uint8_t step=1 > +struct MultiSerial : public SerialBase< MultiSerial< REPEAT(NUM_SERIAL, _S_NAME) offset, step > > { + typedef SerialBase< MultiSerial< REPEAT(NUM_SERIAL, _S_NAME) offset, step > > BaseClassT; + + #undef _S_CLASS + #undef _S_NAME + + SerialMask portMask; + + #define _S_DECLARE(N) Serial##N##T & serial##N; + REPEAT(NUM_SERIAL, _S_DECLARE); + #undef _S_DECLARE + + static constexpr uint8_t Usage = _BV(step) - 1; // A bit mask containing 'step' bits + + #define _OUT_PORT(N) (Usage << (offset + (step * N))), + static constexpr uint8_t output[] = { REPEAT(NUM_SERIAL, _OUT_PORT) }; + #undef _OUT_PORT + + #define _OUT_MASK(N) | output[N] + static constexpr uint8_t ALL = 0 REPEAT(NUM_SERIAL, _OUT_MASK); + #undef _OUT_MASK + + NO_INLINE void write(uint8_t c) { + #define _S_WRITE(N) if (portMask.enabled(output[N])) serial##N.write(c); + REPEAT(NUM_SERIAL, _S_WRITE); + #undef _S_WRITE + } + NO_INLINE void msgDone() { + #define _S_DONE(N) if (portMask.enabled(output[N])) serial##N.msgDone(); + REPEAT(NUM_SERIAL, _S_DONE); + #undef _S_DONE + } + int available(serial_index_t index) { + uint8_t pos = offset; + #define _S_AVAILABLE(N) if (index.within(pos, pos + step - 1)) return serial##N.available(index); else pos += step; + REPEAT(NUM_SERIAL, _S_AVAILABLE); + #undef _S_AVAILABLE + return false; + } + int read(serial_index_t index) { + uint8_t pos = offset; + #define _S_READ(N) if (index.within(pos, pos + step - 1)) return serial##N.read(index); else pos += step; + REPEAT(NUM_SERIAL, _S_READ); + #undef _S_READ + return -1; + } + void begin(const long br) { + #define _S_BEGIN(N) if (portMask.enabled(output[N])) serial##N.begin(br); + REPEAT(NUM_SERIAL, _S_BEGIN); + #undef _S_BEGIN + } + void end() { + #define _S_END(N) if (portMask.enabled(output[N])) serial##N.end(); + REPEAT(NUM_SERIAL, _S_END); + #undef _S_END + } + bool connected() { + bool ret = true; + #define _S_CONNECTED(N) if (portMask.enabled(output[N]) && !CALL_IF_EXISTS(bool, &serial##N, connected)) ret = false; + REPEAT(NUM_SERIAL, _S_CONNECTED); + #undef _S_CONNECTED + return ret; + } + + using BaseClassT::available; + using BaseClassT::read; + + // Redirect flush + NO_INLINE void flush() { + #define _S_FLUSH(N) if (portMask.enabled(output[N])) serial##N.flush(); + REPEAT(NUM_SERIAL, _S_FLUSH); + #undef _S_FLUSH + } + NO_INLINE void flushTX() { + #define _S_FLUSHTX(N) if (portMask.enabled(output[N])) CALL_IF_EXISTS(void, &serial0, flushTX); + REPEAT(NUM_SERIAL, _S_FLUSHTX); + #undef _S_FLUSHTX + } + + // Forward feature queries + SerialFeature features(serial_index_t index) const { + uint8_t pos = offset; + #define _S_FEATURES(N) if (index.within(pos, pos + step - 1)) return serial##N.features(index); else pos += step; + REPEAT(NUM_SERIAL, _S_FEATURES); + #undef _S_FEATURES + return SerialFeature::None; + } + + #define _S_REFS(N) Serial##N##T & serial##N, + #define _S_INIT(N) ,serial##N (serial##N) + + MultiSerial(REPEAT(NUM_SERIAL, _S_REFS) const SerialMask mask = ALL, const bool e = false) + : BaseClassT(e), portMask(mask) REPEAT(NUM_SERIAL, _S_INIT) {} + +}; + +// Build the actual serial object depending on current configuration +#define Serial1Class TERN(SERIAL_RUNTIME_HOOK, RuntimeSerial, BaseSerial) +#define ForwardSerial1Class TERN(SERIAL_RUNTIME_HOOK, RuntimeSerial, ForwardSerial) +#if HAS_MULTI_SERIAL + #define Serial2Class ConditionalSerial + #if NUM_SERIAL >= 3 + #define Serial3Class ConditionalSerial + #endif +#endif diff --git a/src/core/types.h b/src/core/types.h new file mode 100644 index 0000000..e3c4b9e --- /dev/null +++ b/src/core/types.h @@ -0,0 +1,743 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include +#include + +#include "../inc/MarlinConfigPre.h" + +// +// Conditional type assignment magic. For example... +// +// typename IF<(MYOPT==12), int, float>::type myvar; +// +template +struct IF { typedef R type; }; +template +struct IF { typedef L type; }; + +#define NUM_AXIS_GANG(V...) GANG_N(NUM_AXES, V) +#define NUM_AXIS_CODE(V...) CODE_N(NUM_AXES, V) +#define NUM_AXIS_LIST(V...) LIST_N(NUM_AXES, V) +#define NUM_AXIS_LIST_1(V) LIST_N_1(NUM_AXES, V) +#define NUM_AXIS_ARRAY(V...) { NUM_AXIS_LIST(V) } +#define NUM_AXIS_ARRAY_1(V) { NUM_AXIS_LIST_1(V) } +#define NUM_AXIS_ARGS(T...) NUM_AXIS_LIST(T x, T y, T z, T i, T j, T k) +#define NUM_AXIS_ELEM(O) NUM_AXIS_LIST(O.x, O.y, O.z, O.i, O.j, O.k) +#define NUM_AXIS_DEFS(T,V) NUM_AXIS_LIST(T x=V, T y=V, T z=V, T i=V, T j=V, T k=V) + +#define MAIN_AXIS_NAMES NUM_AXIS_LIST(X, Y, Z, I, J, K) +#define MAIN_AXIS_MAP(F) MAP(F, MAIN_AXIS_NAMES) +#define STR_AXES_MAIN NUM_AXIS_GANG("X", "Y", "Z", STR_I, STR_J, STR_K) + +#define LOGICAL_AXIS_GANG(E,V...) NUM_AXIS_GANG(V) GANG_ITEM_E(E) +#define LOGICAL_AXIS_CODE(E,V...) NUM_AXIS_CODE(V) CODE_ITEM_E(E) +#define LOGICAL_AXIS_LIST(E,V...) NUM_AXIS_LIST(V) LIST_ITEM_E(E) +#define LOGICAL_AXIS_LIST_1(V) NUM_AXIS_LIST_1(V) LIST_ITEM_E(V) +#define LOGICAL_AXIS_ARRAY(E,V...) { LOGICAL_AXIS_LIST(E,V) } +#define LOGICAL_AXIS_ARRAY_1(V) { LOGICAL_AXIS_LIST_1(V) } +#define LOGICAL_AXIS_ARGS(T...) LOGICAL_AXIS_LIST(T e, T x, T y, T z, T i, T j, T k) +#define LOGICAL_AXIS_ELEM(O) LOGICAL_AXIS_LIST(O.e, O.x, O.y, O.z, O.i, O.j, O.k) +#define LOGICAL_AXIS_DECL(T,V) LOGICAL_AXIS_LIST(T e=V, T x=V, T y=V, T z=V, T i=V, T j=V, T k=V) + +#define LOGICAL_AXIS_NAMES LOGICAL_AXIS_LIST(E, X, Y, Z, I, J, K) +#define LOGICAL_AXIS_MAP(F) MAP(F, LOGICAL_AXIS_NAMES) + +#define STR_AXES_LOGICAL LOGICAL_AXIS_GANG("E", "X", "Y", "Z", STR_I, STR_J, STR_K) + +#define XYZ_GANG(V...) GANG_N(PRIMARY_LINEAR_AXES, V) +#define XYZ_CODE(V...) CODE_N(PRIMARY_LINEAR_AXES, V) + +#define SECONDARY_AXIS_GANG(V...) GANG_N(SECONDARY_AXES, V) +#define SECONDARY_AXIS_CODE(V...) CODE_N(SECONDARY_AXES, V) + +#if HAS_EXTRUDERS + #define LIST_ITEM_E(N) , N + #define CODE_ITEM_E(N) ; N + #define GANG_ITEM_E(N) N +#else + #define LIST_ITEM_E(N) + #define CODE_ITEM_E(N) + #define GANG_ITEM_E(N) +#endif + +#define AXIS_COLLISION(L) (AXIS4_NAME == L || AXIS5_NAME == L || AXIS6_NAME == L) + +// General Flags for some number of states +template +struct Flags { + typedef typename IF<(N>8), uint16_t, uint8_t>::type bits_t; + typedef struct { bool b0:1, b1:1, b2:1, b3:1, b4:1, b5:1, b6:1, b7:1; } N8; + typedef struct { bool b0:1, b1:1, b2:1, b3:1, b4:1, b5:1, b6:1, b7:1, b8:1, b9:1, b10:1, b11:1, b12:1, b13:1, b14:1, b15:1; } N16; + union { + bits_t b; + typename IF<(N>8), N16, N8>::type flag; + }; + void reset() { b = 0; } + void set(const int n, const bool onoff) { onoff ? set(n) : clear(n); } + void set(const int n) { b |= (bits_t)_BV(n); } + void clear(const int n) { b &= ~(bits_t)_BV(n); } + bool test(const int n) const { return TEST(b, n); } + const bool operator[](const int n) { return test(n); } + const bool operator[](const int n) const { return test(n); } + int size() const { return sizeof(b); } +}; + +// Specialization for a single bool flag +template<> +struct Flags<1> { + bool b; + void reset() { b = false; } + void set(const int n, const bool onoff) { onoff ? set(n) : clear(n); } + void set(const int) { b = true; } + void clear(const int) { b = false; } + bool test(const int) const { return b; } + bool& operator[](const int) { return b; } + bool operator[](const int) const { return b; } + int size() const { return sizeof(b); } +}; + +typedef Flags<8> flags_8_t; +typedef Flags<16> flags_16_t; + +// Flags for some axis states, with per-axis aliases xyzijkuvwe +typedef struct AxisFlags { + union { + struct Flags flags; + struct { bool LOGICAL_AXIS_LIST(e:1, x:1, y:1, z:1, i:1, j:1, k:1, u:1, v:1, w:1); }; + }; + void reset() { flags.reset(); } + void set(const int n) { flags.set(n); } + void set(const int n, const bool onoff) { flags.set(n, onoff); } + void clear(const int n) { flags.clear(n); } + bool test(const int n) const { return flags.test(n); } + bool operator[](const int n) { return flags[n]; } + bool operator[](const int n) const { return flags[n]; } + int size() const { return sizeof(flags); } +} axis_flags_t; + +// +// Enumerated axis indices +// +// - X_AXIS, Y_AXIS, and Z_AXIS should be used for axes in Cartesian space +// - A_AXIS, B_AXIS, and C_AXIS should be used for Steppers, corresponding to XYZ on Cartesians +// - X_HEAD, Y_HEAD, and Z_HEAD should be used for Steppers on Core kinematics +// +enum AxisEnum : uint8_t { + + // Linear axes may be controlled directly or indirectly + NUM_AXIS_LIST(X_AXIS, Y_AXIS, Z_AXIS, I_AXIS, J_AXIS, K_AXIS) + + // Extruder axes may be considered distinctly + #define _EN_ITEM(N) , E##N##_AXIS + REPEAT(EXTRUDERS, _EN_ITEM) + #undef _EN_ITEM + + // Core also keeps toolhead directions + #if ANY(IS_CORE, MARKFORGED_XY, MARKFORGED_YX) + , X_HEAD, Y_HEAD, Z_HEAD + #endif + + // Distinct axes, including all E and Core + , NUM_AXIS_ENUMS + + // Most of the time we refer only to the single E_AXIS + #if HAS_EXTRUDERS + , E_AXIS = E0_AXIS + #endif + + // A, B, and C are for DELTA, SCARA, etc. + , A_AXIS = X_AXIS + #if HAS_Y_AXIS + , B_AXIS = Y_AXIS + #endif + #if HAS_Z_AXIS + , C_AXIS = Z_AXIS + #endif + + // To refer to all or none + , ALL_AXES_ENUM = 0xFE, NO_AXIS_ENUM = 0xFF +}; + +typedef IF<(NUM_AXIS_ENUMS > 8), uint16_t, uint8_t>::type axis_bits_t; + +// +// Loop over axes +// +#define LOOP_ABC(VAR) LOOP_S_LE_N(VAR, A_AXIS, C_AXIS) +#define LOOP_NUM_AXES(VAR) LOOP_S_L_N(VAR, X_AXIS, NUM_AXES) +#define LOOP_LOGICAL_AXES(VAR) LOOP_S_L_N(VAR, X_AXIS, LOGICAL_AXES) +#define LOOP_DISTINCT_AXES(VAR) LOOP_S_L_N(VAR, X_AXIS, DISTINCT_AXES) +#define LOOP_DISTINCT_E(VAR) LOOP_L_N(VAR, DISTINCT_E) + +// +// feedRate_t is just a humble float +// +typedef float feedRate_t; + +// +// celsius_t is the native unit of temperature. Signed to handle a disconnected thermistor value (-14). +// For more resolition (e.g., for a chocolate printer) this may later be changed to Celsius x 100 +// +typedef uint16_t raw_adc_t; +typedef int16_t celsius_t; +typedef float celsius_float_t; + +// +// On AVR pointers are only 2 bytes so use 'const float &' for 'const float' +// +#ifdef __AVR__ + typedef const float & const_float_t; +#else + typedef const float const_float_t; +#endif +typedef const_float_t const_feedRate_t; +typedef const_float_t const_celsius_float_t; + +// Conversion macros +#define MMM_TO_MMS(MM_M) feedRate_t(static_cast(MM_M) / 60.0f) +#define MMS_TO_MMM(MM_S) (static_cast(MM_S) * 60.0f) + +// +// Coordinates structures for XY, XYZ, XYZE... +// + +// Helpers +#define _RECIP(N) ((N) ? 1.0f / static_cast(N) : 0.0f) +#define _ABS(N) ((N) < 0 ? -(N) : (N)) +#define _LS(N) (N = (T)(uint32_t(N) << v)) +#define _RS(N) (N = (T)(uint32_t(N) >> v)) +#define FI FORCE_INLINE + +// Forward declarations +template struct XYval; +template struct XYZval; +template struct XYZEval; + +typedef struct XYval xy_bool_t; +typedef struct XYZval xyz_bool_t; +typedef struct XYZEval xyze_bool_t; + +typedef struct XYval xy_char_t; +typedef struct XYZval xyz_char_t; +typedef struct XYZEval xyze_char_t; + +typedef struct XYval xy_uchar_t; +typedef struct XYZval xyz_uchar_t; +typedef struct XYZEval xyze_uchar_t; + +typedef struct XYval xy_int8_t; +typedef struct XYZval xyz_int8_t; +typedef struct XYZEval xyze_int8_t; + +typedef struct XYval xy_uint8_t; +typedef struct XYZval xyz_uint8_t; +typedef struct XYZEval xyze_uint8_t; + +typedef struct XYval xy_int_t; +typedef struct XYZval xyz_int_t; +typedef struct XYZEval xyze_int_t; + +typedef struct XYval xy_uint_t; +typedef struct XYZval xyz_uint_t; +typedef struct XYZEval xyze_uint_t; + +typedef struct XYval xy_long_t; +typedef struct XYZval xyz_long_t; +typedef struct XYZEval xyze_long_t; + +typedef struct XYval xy_ulong_t; +typedef struct XYZval xyz_ulong_t; +typedef struct XYZEval xyze_ulong_t; + +typedef struct XYZval xyz_vlong_t; +typedef struct XYZEval xyze_vlong_t; + +typedef struct XYval xy_float_t; +typedef struct XYZval xyz_float_t; +typedef struct XYZEval xyze_float_t; + +typedef struct XYval xy_feedrate_t; +typedef struct XYZval xyz_feedrate_t; +typedef struct XYZEval xyze_feedrate_t; + +typedef xy_uint8_t xy_byte_t; +typedef xyz_uint8_t xyz_byte_t; +typedef xyze_uint8_t xyze_byte_t; + +typedef xyz_long_t abc_long_t; +typedef xyze_long_t abce_long_t; +typedef xyz_ulong_t abc_ulong_t; +typedef xyze_ulong_t abce_ulong_t; + +typedef xy_float_t xy_pos_t; +typedef xyz_float_t xyz_pos_t; +typedef xyze_float_t xyze_pos_t; + +typedef xy_float_t ab_float_t; +typedef xyz_float_t abc_float_t; +typedef xyze_float_t abce_float_t; + +typedef ab_float_t ab_pos_t; +typedef abc_float_t abc_pos_t; +typedef abce_float_t abce_pos_t; + +// External conversion methods +void toLogical(xy_pos_t &raw); +void toLogical(xyz_pos_t &raw); +void toLogical(xyze_pos_t &raw); +void toNative(xy_pos_t &raw); +void toNative(xyz_pos_t &raw); +void toNative(xyze_pos_t &raw); + +// +// Paired XY coordinates, counters, flags, etc. +// +template +struct XYval { + union { + struct { T x, y; }; + struct { T a, b; }; + T pos[2]; + }; + + // Set all to 0 + FI void reset() { x = y = 0; } + + // Setters taking struct types and arrays + FI void set(const T px) { x = px; } + #if HAS_Y_AXIS + FI void set(const T px, const T py) { x = px; y = py; } + FI void set(const T (&arr)[XY]) { x = arr[0]; y = arr[1]; } + #endif + #if NUM_AXES > XY + FI void set(const T (&arr)[NUM_AXES]) { x = arr[0]; y = arr[1]; } + #endif + #if LOGICAL_AXES > NUM_AXES + FI void set(const T (&arr)[LOGICAL_AXES]) { x = arr[0]; y = arr[1]; } + #if DISTINCT_AXES > LOGICAL_AXES + FI void set(const T (&arr)[DISTINCT_AXES]) { x = arr[0]; y = arr[1]; } + #endif + #endif + + // Length reduced to one dimension + FI T magnitude() const { return (T)sqrtf(x*x + y*y); } + // Pointer to the data as a simple array + FI operator T* () { return pos; } + // If any element is true then it's true + FI operator bool() { return x || y; } + + // Explicit copy and copies with conversion + FI XYval copy() const { return *this; } + FI XYval ABS() const { return { T(_ABS(x)), T(_ABS(y)) }; } + FI XYval asInt() { return { int16_t(x), int16_t(y) }; } + FI XYval asInt() const { return { int16_t(x), int16_t(y) }; } + FI XYval asLong() { return { int32_t(x), int32_t(y) }; } + FI XYval asLong() const { return { int32_t(x), int32_t(y) }; } + FI XYval ROUNDL() { return { int32_t(LROUND(x)), int32_t(LROUND(y)) }; } + FI XYval ROUNDL() const { return { int32_t(LROUND(x)), int32_t(LROUND(y)) }; } + FI XYval asFloat() { return { static_cast(x), static_cast(y) }; } + FI XYval asFloat() const { return { static_cast(x), static_cast(y) }; } + FI XYval reciprocal() const { return { _RECIP(x), _RECIP(y) }; } + + // Marlin workspace shifting is done with G92 and M206 + FI XYval asLogical() const { XYval o = asFloat(); toLogical(o); return o; } + FI XYval asNative() const { XYval o = asFloat(); toNative(o); return o; } + + // Cast to a type with more fields by making a new object + FI operator XYZval() { return { x, y }; } + FI operator XYZval() const { return { x, y }; } + FI operator XYZEval() { return { x, y }; } + FI operator XYZEval() const { return { x, y }; } + + // Accessor via an AxisEnum (or any integer) [index] + FI T& operator[](const int n) { return pos[n]; } + FI const T& operator[](const int n) const { return pos[n]; } + + // Assignment operator overrides do the expected thing + FI XYval& operator= (const T v) { set(v, v ); return *this; } + FI XYval& operator= (const XYZval &rs) { set(rs.x, rs.y); return *this; } + FI XYval& operator= (const XYZEval &rs) { set(rs.x, rs.y); return *this; } + + // Override other operators to get intuitive behaviors + FI XYval operator+ (const XYval &rs) const { XYval ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; } + FI XYval operator+ (const XYval &rs) { XYval ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; } + FI XYval operator- (const XYval &rs) const { XYval ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; } + FI XYval operator- (const XYval &rs) { XYval ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; } + FI XYval operator* (const XYval &rs) const { XYval ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; } + FI XYval operator* (const XYval &rs) { XYval ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; } + FI XYval operator/ (const XYval &rs) const { XYval ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; } + FI XYval operator/ (const XYval &rs) { XYval ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; } + FI XYval operator+ (const XYZval &rs) const { XYval ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; } + FI XYval operator+ (const XYZval &rs) { XYval ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; } + FI XYval operator- (const XYZval &rs) const { XYval ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; } + FI XYval operator- (const XYZval &rs) { XYval ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; } + FI XYval operator* (const XYZval &rs) const { XYval ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; } + FI XYval operator* (const XYZval &rs) { XYval ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; } + FI XYval operator/ (const XYZval &rs) const { XYval ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; } + FI XYval operator/ (const XYZval &rs) { XYval ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; } + FI XYval operator+ (const XYZEval &rs) const { XYval ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; } + FI XYval operator+ (const XYZEval &rs) { XYval ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; } + FI XYval operator- (const XYZEval &rs) const { XYval ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; } + FI XYval operator- (const XYZEval &rs) { XYval ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; } + FI XYval operator* (const XYZEval &rs) const { XYval ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; } + FI XYval operator* (const XYZEval &rs) { XYval ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; } + FI XYval operator/ (const XYZEval &rs) const { XYval ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; } + FI XYval operator/ (const XYZEval &rs) { XYval ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; } + FI XYval operator* (const float &v) const { XYval ls = *this; ls.x *= v; ls.y *= v; return ls; } + FI XYval operator* (const float &v) { XYval ls = *this; ls.x *= v; ls.y *= v; return ls; } + FI XYval operator* (const int &v) const { XYval ls = *this; ls.x *= v; ls.y *= v; return ls; } + FI XYval operator* (const int &v) { XYval ls = *this; ls.x *= v; ls.y *= v; return ls; } + FI XYval operator/ (const float &v) const { XYval ls = *this; ls.x /= v; ls.y /= v; return ls; } + FI XYval operator/ (const float &v) { XYval ls = *this; ls.x /= v; ls.y /= v; return ls; } + FI XYval operator/ (const int &v) const { XYval ls = *this; ls.x /= v; ls.y /= v; return ls; } + FI XYval operator/ (const int &v) { XYval ls = *this; ls.x /= v; ls.y /= v; return ls; } + FI XYval operator>>(const int &v) const { XYval ls = *this; _RS(ls.x); _RS(ls.y); return ls; } + FI XYval operator>>(const int &v) { XYval ls = *this; _RS(ls.x); _RS(ls.y); return ls; } + FI XYval operator<<(const int &v) const { XYval ls = *this; _LS(ls.x); _LS(ls.y); return ls; } + FI XYval operator<<(const int &v) { XYval ls = *this; _LS(ls.x); _LS(ls.y); return ls; } + FI const XYval operator-() const { XYval o = *this; o.x = -x; o.y = -y; return o; } + FI XYval operator-() { XYval o = *this; o.x = -x; o.y = -y; return o; } + + // Modifier operators + FI XYval& operator+=(const XYval &rs) { x += rs.x; y += rs.y; return *this; } + FI XYval& operator-=(const XYval &rs) { x -= rs.x; y -= rs.y; return *this; } + FI XYval& operator*=(const XYval &rs) { x *= rs.x; y *= rs.y; return *this; } + FI XYval& operator+=(const XYZval &rs) { x += rs.x; y += rs.y; return *this; } + FI XYval& operator-=(const XYZval &rs) { x -= rs.x; y -= rs.y; return *this; } + FI XYval& operator*=(const XYZval &rs) { x *= rs.x; y *= rs.y; return *this; } + FI XYval& operator+=(const XYZEval &rs) { x += rs.x; y += rs.y; return *this; } + FI XYval& operator-=(const XYZEval &rs) { x -= rs.x; y -= rs.y; return *this; } + FI XYval& operator*=(const XYZEval &rs) { x *= rs.x; y *= rs.y; return *this; } + FI XYval& operator*=(const float &v) { x *= v; y *= v; return *this; } + FI XYval& operator*=(const int &v) { x *= v; y *= v; return *this; } + FI XYval& operator>>=(const int &v) { _RS(x); _RS(y); return *this; } + FI XYval& operator<<=(const int &v) { _LS(x); _LS(y); return *this; } + + // Exact comparisons. For floats a "NEAR" operation may be better. + FI bool operator==(const XYval &rs) { return x == rs.x && y == rs.y; } + FI bool operator==(const XYZval &rs) { return x == rs.x && y == rs.y; } + FI bool operator==(const XYZEval &rs) { return x == rs.x && y == rs.y; } + FI bool operator==(const XYval &rs) const { return x == rs.x && y == rs.y; } + FI bool operator==(const XYZval &rs) const { return x == rs.x && y == rs.y; } + FI bool operator==(const XYZEval &rs) const { return x == rs.x && y == rs.y; } + FI bool operator!=(const XYval &rs) { return !operator==(rs); } + FI bool operator!=(const XYZval &rs) { return !operator==(rs); } + FI bool operator!=(const XYZEval &rs) { return !operator==(rs); } + FI bool operator!=(const XYval &rs) const { return !operator==(rs); } + FI bool operator!=(const XYZval &rs) const { return !operator==(rs); } + FI bool operator!=(const XYZEval &rs) const { return !operator==(rs); } +}; + +// +// Linear Axes coordinates, counters, flags, etc. +// +template +struct XYZval { + union { + struct { T NUM_AXIS_ARGS(); }; + struct { T NUM_AXIS_LIST(a, b, c, _i, _j, _k); }; + T pos[NUM_AXES]; + }; + + // Set all to 0 + FI void reset() { NUM_AXIS_GANG(x =, y =, z =, i =, j =, k =) 0; } + + // Setters taking struct types and arrays + FI void set(const T px) { x = px; } + FI void set(const T px, const T py) { x = px; y = py; } + FI void set(const XYval pxy) { x = pxy.x; y = pxy.y; } + FI void set(const XYval pxy, const T pz) { NUM_AXIS_CODE(x = pxy.x, y = pxy.y, z = pz, NOOP, NOOP, NOOP); } + FI void set(const T (&arr)[XY]) { x = arr[0]; y = arr[1]; } + #if HAS_Z_AXIS + FI void set(const T (&arr)[NUM_AXES]) { NUM_AXIS_CODE(x = arr[0], y = arr[1], z = arr[2], i = arr[3], j = arr[4], k = arr[5]); } + FI void set(NUM_AXIS_ARGS(const T)) { NUM_AXIS_CODE(a = x, b = y, c = z, _i = i, _j = j, _k = k); } + #endif + #if LOGICAL_AXES > NUM_AXES + FI void set(const T (&arr)[LOGICAL_AXES]) { NUM_AXIS_CODE(x = arr[0], y = arr[1], z = arr[2], i = arr[3], j = arr[4], k = arr[5]); } + FI void set(LOGICAL_AXIS_ARGS(const T)) { NUM_AXIS_CODE(a = x, b = y, c = z, _i = i, _j = j, _k = k); } + #if DISTINCT_AXES > LOGICAL_AXES + FI void set(const T (&arr)[DISTINCT_AXES]) { NUM_AXIS_CODE(x = arr[0], y = arr[1], z = arr[2], i = arr[3], j = arr[4], k = arr[5]); } + #endif + #endif + #if HAS_I_AXIS + FI void set(const T px, const T py, const T pz) { x = px; y = py; z = pz; } + #endif + #if HAS_J_AXIS + FI void set(const T px, const T py, const T pz, const T pi) { x = px; y = py; z = pz; i = pi; } + #endif + #if HAS_K_AXIS + FI void set(const T px, const T py, const T pz, const T pi, const T pj) { x = px; y = py; z = pz; i = pi; j = pj; } + #endif + + // Length reduced to one dimension + FI T magnitude() const { return (T)sqrtf(NUM_AXIS_GANG(x*x, + y*y, + z*z, + i*i, + j*j, + k*k)); } + // Pointer to the data as a simple array + FI operator T* () { return pos; } + // If any element is true then it's true + FI operator bool() { return NUM_AXIS_GANG(x, || y, || z, || i, || j, || k); } + + // Explicit copy and copies with conversion + FI XYZval copy() const { XYZval o = *this; return o; } + FI XYZval ABS() const { return NUM_AXIS_ARRAY(T(_ABS(x)), T(_ABS(y)), T(_ABS(z)), T(_ABS(i)), T(_ABS(j)), T(_ABS(k))); } + FI XYZval asInt() { return NUM_AXIS_ARRAY(int16_t(x), int16_t(y), int16_t(z), int16_t(i), int16_t(j), int16_t(k)); } + FI XYZval asInt() const { return NUM_AXIS_ARRAY(int16_t(x), int16_t(y), int16_t(z), int16_t(i), int16_t(j), int16_t(k)); } + FI XYZval asLong() { return NUM_AXIS_ARRAY(int32_t(x), int32_t(y), int32_t(z), int32_t(i), int32_t(j), int32_t(k)); } + FI XYZval asLong() const { return NUM_AXIS_ARRAY(int32_t(x), int32_t(y), int32_t(z), int32_t(i), int32_t(j), int32_t(k)); } + FI XYZval ROUNDL() { return NUM_AXIS_ARRAY(int32_t(LROUND(x)), int32_t(LROUND(y)), int32_t(LROUND(z)), int32_t(LROUND(i)), int32_t(LROUND(j)), int32_t(LROUND(k))); } + FI XYZval ROUNDL() const { return NUM_AXIS_ARRAY(int32_t(LROUND(x)), int32_t(LROUND(y)), int32_t(LROUND(z)), int32_t(LROUND(i)), int32_t(LROUND(j)), int32_t(LROUND(k))); } + FI XYZval asFloat() { return NUM_AXIS_ARRAY(static_cast(x), static_cast(y), static_cast(z), static_cast(i), static_cast(j), static_cast(k)); } + FI XYZval asFloat() const { return NUM_AXIS_ARRAY(static_cast(x), static_cast(y), static_cast(z), static_cast(i), static_cast(j), static_cast(k)); } + FI XYZval reciprocal() const { return NUM_AXIS_ARRAY(_RECIP(x), _RECIP(y), _RECIP(z), _RECIP(i), _RECIP(j), _RECIP(k)); } + + // Marlin workspace shifting is done with G92 and M206 + FI XYZval asLogical() const { XYZval o = asFloat(); toLogical(o); return o; } + FI XYZval asNative() const { XYZval o = asFloat(); toNative(o); return o; } + + // In-place cast to types having fewer fields + FI operator XYval&() { return *(XYval*)this; } + FI operator const XYval&() const { return *(const XYval*)this; } + + // Cast to a type with more fields by making a new object + FI operator XYZEval() const { return NUM_AXIS_ARRAY(x, y, z, i, j, k); } + + // Accessor via an AxisEnum (or any integer) [index] + FI T& operator[](const int n) { return pos[n]; } + FI const T& operator[](const int n) const { return pos[n]; } + + // Assignment operator overrides do the expected thing + FI XYZval& operator= (const T v) { set(ARRAY_N_1(NUM_AXES, v)); return *this; } + FI XYZval& operator= (const XYval &rs) { set(rs.x, rs.y ); return *this; } + FI XYZval& operator= (const XYZEval &rs) { set(NUM_AXIS_ELEM(rs)); return *this; } + + // Override other operators to get intuitive behaviors + FI XYZval operator+ (const XYval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x += rs.x, ls.y += rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; } + FI XYZval operator+ (const XYval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x += rs.x, ls.y += rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; } + FI XYZval operator- (const XYval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x -= rs.x, ls.y -= rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; } + FI XYZval operator- (const XYval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x -= rs.x, ls.y -= rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; } + FI XYZval operator* (const XYval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x *= rs.x, ls.y *= rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; } + FI XYZval operator* (const XYval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x *= rs.x, ls.y *= rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; } + FI XYZval operator/ (const XYval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x /= rs.x, ls.y /= rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; } + FI XYZval operator/ (const XYval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x /= rs.x, ls.y /= rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; } + FI XYZval operator+ (const XYZval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x += rs.x, ls.y += rs.y, ls.z += rs.z, ls.i += rs.i, ls.j += rs.j, ls.k += rs.k); return ls; } + FI XYZval operator+ (const XYZval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x += rs.x, ls.y += rs.y, ls.z += rs.z, ls.i += rs.i, ls.j += rs.j, ls.k += rs.k); return ls; } + FI XYZval operator- (const XYZval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x -= rs.x, ls.y -= rs.y, ls.z -= rs.z, ls.i -= rs.i, ls.j -= rs.j, ls.k -= rs.k); return ls; } + FI XYZval operator- (const XYZval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x -= rs.x, ls.y -= rs.y, ls.z -= rs.z, ls.i -= rs.i, ls.j -= rs.j, ls.k -= rs.k); return ls; } + FI XYZval operator* (const XYZval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x *= rs.x, ls.y *= rs.y, ls.z *= rs.z, ls.i *= rs.i, ls.j *= rs.j, ls.k *= rs.k); return ls; } + FI XYZval operator* (const XYZval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x *= rs.x, ls.y *= rs.y, ls.z *= rs.z, ls.i *= rs.i, ls.j *= rs.j, ls.k *= rs.k); return ls; } + FI XYZval operator/ (const XYZval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x /= rs.x, ls.y /= rs.y, ls.z /= rs.z, ls.i /= rs.i, ls.j /= rs.j, ls.k /= rs.k); return ls; } + FI XYZval operator/ (const XYZval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x /= rs.x, ls.y /= rs.y, ls.z /= rs.z, ls.i /= rs.i, ls.j /= rs.j, ls.k /= rs.k); return ls; } + FI XYZval operator+ (const XYZEval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x += rs.x, ls.y += rs.y, ls.z += rs.z, ls.i += rs.i, ls.j += rs.j, ls.k += rs.k); return ls; } + FI XYZval operator+ (const XYZEval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x += rs.x, ls.y += rs.y, ls.z += rs.z, ls.i += rs.i, ls.j += rs.j, ls.k += rs.k); return ls; } + FI XYZval operator- (const XYZEval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x -= rs.x, ls.y -= rs.y, ls.z -= rs.z, ls.i -= rs.i, ls.j -= rs.j, ls.k -= rs.k); return ls; } + FI XYZval operator- (const XYZEval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x -= rs.x, ls.y -= rs.y, ls.z -= rs.z, ls.i -= rs.i, ls.j -= rs.j, ls.k -= rs.k); return ls; } + FI XYZval operator* (const XYZEval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x *= rs.x, ls.y *= rs.y, ls.z *= rs.z, ls.i *= rs.i, ls.j *= rs.j, ls.k *= rs.k); return ls; } + FI XYZval operator* (const XYZEval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x *= rs.x, ls.y *= rs.y, ls.z *= rs.z, ls.i *= rs.i, ls.j *= rs.j, ls.k *= rs.k); return ls; } + FI XYZval operator/ (const XYZEval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x /= rs.x, ls.y /= rs.y, ls.z /= rs.z, ls.i /= rs.i, ls.j /= rs.j, ls.k /= rs.k); return ls; } + FI XYZval operator/ (const XYZEval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x /= rs.x, ls.y /= rs.y, ls.z /= rs.z, ls.i /= rs.i, ls.j /= rs.j, ls.k /= rs.k); return ls; } + FI XYZval operator* (const float &v) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x *= v, ls.y *= v, ls.z *= v, ls.i *= v, ls.j *= v, ls.k *= v ); return ls; } + FI XYZval operator* (const float &v) { XYZval ls = *this; NUM_AXIS_CODE(ls.x *= v, ls.y *= v, ls.z *= v, ls.i *= v, ls.j *= v, ls.k *= v ); return ls; } + FI XYZval operator* (const int &v) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x *= v, ls.y *= v, ls.z *= v, ls.i *= v, ls.j *= v, ls.k *= v ); return ls; } + FI XYZval operator* (const int &v) { XYZval ls = *this; NUM_AXIS_CODE(ls.x *= v, ls.y *= v, ls.z *= v, ls.i *= v, ls.j *= v, ls.k *= v ); return ls; } + FI XYZval operator/ (const float &v) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x /= v, ls.y /= v, ls.z /= v, ls.i /= v, ls.j /= v, ls.k /= v ); return ls; } + FI XYZval operator/ (const float &v) { XYZval ls = *this; NUM_AXIS_CODE(ls.x /= v, ls.y /= v, ls.z /= v, ls.i /= v, ls.j /= v, ls.k /= v ); return ls; } + FI XYZval operator/ (const int &v) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x /= v, ls.y /= v, ls.z /= v, ls.i /= v, ls.j /= v, ls.k /= v ); return ls; } + FI XYZval operator/ (const int &v) { XYZval ls = *this; NUM_AXIS_CODE(ls.x /= v, ls.y /= v, ls.z /= v, ls.i /= v, ls.j /= v, ls.k /= v ); return ls; } + FI XYZval operator>>(const int &v) const { XYZval ls = *this; NUM_AXIS_CODE(_RS(ls.x), _RS(ls.y), _RS(ls.z), _RS(ls.i), _RS(ls.j), _RS(ls.k) ); return ls; } + FI XYZval operator>>(const int &v) { XYZval ls = *this; NUM_AXIS_CODE(_RS(ls.x), _RS(ls.y), _RS(ls.z), _RS(ls.i), _RS(ls.j), _RS(ls.k) ); return ls; } + FI XYZval operator<<(const int &v) const { XYZval ls = *this; NUM_AXIS_CODE(_LS(ls.x), _LS(ls.y), _LS(ls.z), _LS(ls.i), _LS(ls.j), _LS(ls.k) ); return ls; } + FI XYZval operator<<(const int &v) { XYZval ls = *this; NUM_AXIS_CODE(_LS(ls.x), _LS(ls.y), _LS(ls.z), _LS(ls.i), _LS(ls.j), _LS(ls.k) ); return ls; } + FI const XYZval operator-() const { XYZval o = *this; NUM_AXIS_CODE(o.x = -x, o.y = -y, o.z = -z, o.i = -i, o.j = -j, o.k = -k); return o; } + FI XYZval operator-() { XYZval o = *this; NUM_AXIS_CODE(o.x = -x, o.y = -y, o.z = -z, o.i = -i, o.j = -j, o.k = -k); return o; } + + // Modifier operators + FI XYZval& operator+=(const XYval &rs) { NUM_AXIS_CODE(x += rs.x, y += rs.y, NOOP, NOOP, NOOP, NOOP ); return *this; } + FI XYZval& operator-=(const XYval &rs) { NUM_AXIS_CODE(x -= rs.x, y -= rs.y, NOOP, NOOP, NOOP, NOOP ); return *this; } + FI XYZval& operator*=(const XYval &rs) { NUM_AXIS_CODE(x *= rs.x, y *= rs.y, NOOP, NOOP, NOOP, NOOP ); return *this; } + FI XYZval& operator/=(const XYval &rs) { NUM_AXIS_CODE(x /= rs.x, y /= rs.y, NOOP, NOOP, NOOP, NOOP ); return *this; } + FI XYZval& operator+=(const XYZval &rs) { NUM_AXIS_CODE(x += rs.x, y += rs.y, z += rs.z, i += rs.i, j += rs.j, k += rs.k); return *this; } + FI XYZval& operator-=(const XYZval &rs) { NUM_AXIS_CODE(x -= rs.x, y -= rs.y, z -= rs.z, i -= rs.i, j -= rs.j, k -= rs.k); return *this; } + FI XYZval& operator*=(const XYZval &rs) { NUM_AXIS_CODE(x *= rs.x, y *= rs.y, z *= rs.z, i *= rs.i, j *= rs.j, k *= rs.k); return *this; } + FI XYZval& operator/=(const XYZval &rs) { NUM_AXIS_CODE(x /= rs.x, y /= rs.y, z /= rs.z, i /= rs.i, j /= rs.j, k /= rs.k); return *this; } + FI XYZval& operator+=(const XYZEval &rs) { NUM_AXIS_CODE(x += rs.x, y += rs.y, z += rs.z, i += rs.i, j += rs.j, k += rs.k); return *this; } + FI XYZval& operator-=(const XYZEval &rs) { NUM_AXIS_CODE(x -= rs.x, y -= rs.y, z -= rs.z, i -= rs.i, j -= rs.j, k -= rs.k); return *this; } + FI XYZval& operator*=(const XYZEval &rs) { NUM_AXIS_CODE(x *= rs.x, y *= rs.y, z *= rs.z, i *= rs.i, j *= rs.j, k *= rs.k); return *this; } + FI XYZval& operator/=(const XYZEval &rs) { NUM_AXIS_CODE(x /= rs.x, y /= rs.y, z /= rs.z, i /= rs.i, j /= rs.j, k /= rs.k); return *this; } + FI XYZval& operator*=(const float &v) { NUM_AXIS_CODE(x *= v, y *= v, z *= v, i *= v, j *= v, k *= v); return *this; } + FI XYZval& operator*=(const int &v) { NUM_AXIS_CODE(x *= v, y *= v, z *= v, i *= v, j *= v, k *= v); return *this; } + FI XYZval& operator>>=(const int &v) { NUM_AXIS_CODE(_RS(x), _RS(y), _RS(z), _RS(i), _RS(j), _RS(k)); return *this; } + FI XYZval& operator<<=(const int &v) { NUM_AXIS_CODE(_LS(x), _LS(y), _LS(z), _LS(i), _LS(j), _LS(k)); return *this; } + + // Exact comparisons. For floats a "NEAR" operation may be better. + FI bool operator==(const XYZEval &rs) { return true NUM_AXIS_GANG(&& x == rs.x, && y == rs.y, && z == rs.z, && i == rs.i, && j == rs.j, && k == rs.k); } + FI bool operator==(const XYZEval &rs) const { return true NUM_AXIS_GANG(&& x == rs.x, && y == rs.y, && z == rs.z, && i == rs.i, && j == rs.j, && k == rs.k); } + FI bool operator!=(const XYZEval &rs) { return !operator==(rs); } + FI bool operator!=(const XYZEval &rs) const { return !operator==(rs); } +}; + +// +// Logical Axes coordinates, counters, etc. +// +template +struct XYZEval { + union { + struct { T LOGICAL_AXIS_ARGS(); }; + struct { T LOGICAL_AXIS_LIST(_e, a, b, c, _i, _j, _k); }; + T pos[LOGICAL_AXES]; + }; + // Reset all to 0 + FI void reset() { LOGICAL_AXIS_GANG(e =, x =, y =, z =, i =, j =, k =) 0; } + + // Setters for some number of linear axes, not all + FI void set(const T px) { x = px; } + FI void set(const T px, const T py) { x = px; y = py; } + #if HAS_I_AXIS + FI void set(const T px, const T py, const T pz) { x = px; y = py; z = pz; } + #endif + #if HAS_J_AXIS + FI void set(const T px, const T py, const T pz, const T pi) { x = px; y = py; z = pz; i = pi; } + #endif + #if HAS_K_AXIS + FI void set(const T px, const T py, const T pz, const T pi, const T pj) { x = px; y = py; z = pz; i = pi; j = pj; } + #endif + // Setters taking struct types and arrays + FI void set(const XYval pxy) { x = pxy.x; y = pxy.y; } + FI void set(const XYZval pxyz) { set(NUM_AXIS_ELEM(pxyz)); } + #if HAS_Z_AXIS + FI void set(NUM_AXIS_ARGS(const T)) { NUM_AXIS_CODE(a = x, b = y, c = z, _i = i, _j = j, _k = k); } + #endif + FI void set(const XYval pxy, const T pz) { set(pxy); TERN_(HAS_Z_AXIS, z = pz); } + #if LOGICAL_AXES > NUM_AXES + FI void set(const XYval pxy, const T pz, const T pe) { set(pxy, pz); e = pe; } + FI void set(const XYZval pxyz, const T pe) { set(pxyz); e = pe; } + FI void set(LOGICAL_AXIS_ARGS(const T)) { LOGICAL_AXIS_CODE(_e = e, a = x, b = y, c = z, _i = i, _j = j, _k = k); } + #endif + + // Length reduced to one dimension + FI T magnitude() const { return (T)sqrtf(LOGICAL_AXIS_GANG(+ e*e, + x*x, + y*y, + z*z, + i*i, + j*j, + k*k)); } + // Pointer to the data as a simple array + FI operator T* () { return pos; } + // If any element is true then it's true + FI operator bool() { return 0 LOGICAL_AXIS_GANG(|| e, || x, || y, || z, || i, || j, || k); } + + // Explicit copy and copies with conversion + FI XYZEval copy() const { XYZEval o = *this; return o; } + FI XYZEval ABS() const { return LOGICAL_AXIS_ARRAY(T(_ABS(e)), T(_ABS(x)), T(_ABS(y)), T(_ABS(z)), T(_ABS(i)), T(_ABS(j)), T(_ABS(k))); } + FI XYZEval asInt() { return LOGICAL_AXIS_ARRAY(int16_t(e), int16_t(x), int16_t(y), int16_t(z), int16_t(i), int16_t(j), int16_t(k)); } + FI XYZEval asInt() const { return LOGICAL_AXIS_ARRAY(int16_t(e), int16_t(x), int16_t(y), int16_t(z), int16_t(i), int16_t(j), int16_t(k)); } + FI XYZEval asLong() { return LOGICAL_AXIS_ARRAY(int32_t(e), int32_t(x), int32_t(y), int32_t(z), int32_t(i), int32_t(j), int32_t(k)); } + FI XYZEval asLong() const { return LOGICAL_AXIS_ARRAY(int32_t(e), int32_t(x), int32_t(y), int32_t(z), int32_t(i), int32_t(j), int32_t(k)); } + FI XYZEval ROUNDL() { return LOGICAL_AXIS_ARRAY(int32_t(LROUND(e)), int32_t(LROUND(x)), int32_t(LROUND(y)), int32_t(LROUND(z)), int32_t(LROUND(i)), int32_t(LROUND(j)), int32_t(LROUND(k))); } + FI XYZEval ROUNDL() const { return LOGICAL_AXIS_ARRAY(int32_t(LROUND(e)), int32_t(LROUND(x)), int32_t(LROUND(y)), int32_t(LROUND(z)), int32_t(LROUND(i)), int32_t(LROUND(j)), int32_t(LROUND(k))); } + FI XYZEval asFloat() { return LOGICAL_AXIS_ARRAY(static_cast(e), static_cast(x), static_cast(y), static_cast(z), static_cast(i), static_cast(j), static_cast(k)); } + FI XYZEval asFloat() const { return LOGICAL_AXIS_ARRAY(static_cast(e), static_cast(x), static_cast(y), static_cast(z), static_cast(i), static_cast(j), static_cast(k)); } + FI XYZEval reciprocal() const { return LOGICAL_AXIS_ARRAY(_RECIP(e), _RECIP(x), _RECIP(y), _RECIP(z), _RECIP(i), _RECIP(j), _RECIP(k)); } + + // Marlin workspace shifting is done with G92 and M206 + FI XYZEval asLogical() const { XYZEval o = asFloat(); toLogical(o); return o; } + FI XYZEval asNative() const { XYZEval o = asFloat(); toNative(o); return o; } + + // In-place cast to types having fewer fields + FI operator XYval&() { return *(XYval*)this; } + FI operator const XYval&() const { return *(const XYval*)this; } + FI operator XYZval&() { return *(XYZval*)this; } + FI operator const XYZval&() const { return *(const XYZval*)this; } + + // Accessor via an AxisEnum (or any integer) [index] + FI T& operator[](const int n) { return pos[n]; } + FI const T& operator[](const int n) const { return pos[n]; } + + // Assignment operator overrides do the expected thing + FI XYZEval& operator= (const T v) { set(LOGICAL_AXIS_LIST_1(v)); return *this; } + FI XYZEval& operator= (const XYval &rs) { set(rs.x, rs.y); return *this; } + FI XYZEval& operator= (const XYZval &rs) { set(NUM_AXIS_ELEM(rs)); return *this; } + + // Override other operators to get intuitive behaviors + FI XYZEval operator+ (const XYval &rs) const { XYZEval ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; } + FI XYZEval operator+ (const XYval &rs) { XYZEval ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; } + FI XYZEval operator- (const XYval &rs) const { XYZEval ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; } + FI XYZEval operator- (const XYval &rs) { XYZEval ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; } + FI XYZEval operator* (const XYval &rs) const { XYZEval ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; } + FI XYZEval operator* (const XYval &rs) { XYZEval ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; } + FI XYZEval operator/ (const XYval &rs) const { XYZEval ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; } + FI XYZEval operator/ (const XYval &rs) { XYZEval ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; } + FI XYZEval operator+ (const XYZval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x += rs.x, ls.y += rs.y, ls.z += rs.z, ls.i += rs.i, ls.j += rs.j, ls.k += rs.k); return ls; } + FI XYZEval operator+ (const XYZval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x += rs.x, ls.y += rs.y, ls.z += rs.z, ls.i += rs.i, ls.j += rs.j, ls.k += rs.k); return ls; } + FI XYZEval operator- (const XYZval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x -= rs.x, ls.y -= rs.y, ls.z -= rs.z, ls.i -= rs.i, ls.j -= rs.j, ls.k -= rs.k); return ls; } + FI XYZEval operator- (const XYZval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x -= rs.x, ls.y -= rs.y, ls.z -= rs.z, ls.i -= rs.i, ls.j -= rs.j, ls.k -= rs.k); return ls; } + FI XYZEval operator* (const XYZval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x *= rs.x, ls.y *= rs.y, ls.z *= rs.z, ls.i *= rs.i, ls.j *= rs.j, ls.k *= rs.k); return ls; } + FI XYZEval operator* (const XYZval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x *= rs.x, ls.y *= rs.y, ls.z *= rs.z, ls.i *= rs.i, ls.j *= rs.j, ls.k *= rs.k); return ls; } + FI XYZEval operator/ (const XYZval &rs) const { XYZval ls = *this; NUM_AXIS_CODE(ls.x /= rs.x, ls.y /= rs.y, ls.z /= rs.z, ls.i /= rs.i, ls.j /= rs.j, ls.k /= rs.k); return ls; } + FI XYZEval operator/ (const XYZval &rs) { XYZval ls = *this; NUM_AXIS_CODE(ls.x /= rs.x, ls.y /= rs.y, ls.z /= rs.z, ls.i /= rs.i, ls.j /= rs.j, ls.k /= rs.k); return ls; } + FI XYZEval operator+ (const XYZEval &rs) const { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e += rs.e, ls.x += rs.x, ls.y += rs.y, ls.z += rs.z, ls.i += rs.i, ls.j += rs.j, ls.k += rs.k); return ls; } + FI XYZEval operator+ (const XYZEval &rs) { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e += rs.e, ls.x += rs.x, ls.y += rs.y, ls.z += rs.z, ls.i += rs.i, ls.j += rs.j, ls.k += rs.k); return ls; } + FI XYZEval operator- (const XYZEval &rs) const { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e -= rs.e, ls.x -= rs.x, ls.y -= rs.y, ls.z -= rs.z, ls.i -= rs.i, ls.j -= rs.j, ls.k -= rs.k); return ls; } + FI XYZEval operator- (const XYZEval &rs) { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e -= rs.e, ls.x -= rs.x, ls.y -= rs.y, ls.z -= rs.z, ls.i -= rs.i, ls.j -= rs.j, ls.k -= rs.k); return ls; } + FI XYZEval operator* (const XYZEval &rs) const { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e *= rs.e, ls.x *= rs.x, ls.y *= rs.y, ls.z *= rs.z, ls.i *= rs.i, ls.j *= rs.j, ls.k *= rs.k); return ls; } + FI XYZEval operator* (const XYZEval &rs) { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e *= rs.e, ls.x *= rs.x, ls.y *= rs.y, ls.z *= rs.z, ls.i *= rs.i, ls.j *= rs.j, ls.k *= rs.k); return ls; } + FI XYZEval operator/ (const XYZEval &rs) const { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e /= rs.e, ls.x /= rs.x, ls.y /= rs.y, ls.z /= rs.z, ls.i /= rs.i, ls.j /= rs.j, ls.k /= rs.k); return ls; } + FI XYZEval operator/ (const XYZEval &rs) { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e /= rs.e, ls.x /= rs.x, ls.y /= rs.y, ls.z /= rs.z, ls.i /= rs.i, ls.j /= rs.j, ls.k /= rs.k); return ls; } + FI XYZEval operator* (const float &v) const { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e *= v, ls.x *= v, ls.y *= v, ls.z *= v, ls.i *= v, ls.j *= v, ls.k *= v ); return ls; } + FI XYZEval operator* (const float &v) { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e *= v, ls.x *= v, ls.y *= v, ls.z *= v, ls.i *= v, ls.j *= v, ls.k *= v ); return ls; } + FI XYZEval operator* (const int &v) const { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e *= v, ls.x *= v, ls.y *= v, ls.z *= v, ls.i *= v, ls.j *= v, ls.k *= v ); return ls; } + FI XYZEval operator* (const int &v) { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e *= v, ls.x *= v, ls.y *= v, ls.z *= v, ls.i *= v, ls.j *= v, ls.k *= v ); return ls; } + FI XYZEval operator/ (const float &v) const { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e /= v, ls.x /= v, ls.y /= v, ls.z /= v, ls.i /= v, ls.j /= v, ls.k /= v ); return ls; } + FI XYZEval operator/ (const float &v) { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e /= v, ls.x /= v, ls.y /= v, ls.z /= v, ls.i /= v, ls.j /= v, ls.k /= v ); return ls; } + FI XYZEval operator/ (const int &v) const { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e /= v, ls.x /= v, ls.y /= v, ls.z /= v, ls.i /= v, ls.j /= v, ls.k /= v ); return ls; } + FI XYZEval operator/ (const int &v) { XYZEval ls = *this; LOGICAL_AXIS_CODE(ls.e /= v, ls.x /= v, ls.y /= v, ls.z /= v, ls.i /= v, ls.j /= v, ls.k /= v ); return ls; } + FI XYZEval operator>>(const int &v) const { XYZEval ls = *this; LOGICAL_AXIS_CODE(_RS(ls.e), _RS(ls.x), _RS(ls.y), _RS(ls.z), _RS(ls.i), _RS(ls.j), _RS(ls.k) ); return ls; } + FI XYZEval operator>>(const int &v) { XYZEval ls = *this; LOGICAL_AXIS_CODE(_RS(ls.e), _RS(ls.x), _RS(ls.y), _RS(ls.z), _RS(ls.i), _RS(ls.j), _RS(ls.k) ); return ls; } + FI XYZEval operator<<(const int &v) const { XYZEval ls = *this; LOGICAL_AXIS_CODE(_LS(ls.e), _LS(ls.x), _LS(ls.y), _LS(ls.z), _LS(ls.i), _LS(ls.j), _LS(ls.k) ); return ls; } + FI XYZEval operator<<(const int &v) { XYZEval ls = *this; LOGICAL_AXIS_CODE(_LS(ls.e), _LS(ls.x), _LS(ls.y), _LS(ls.z), _LS(ls.i), _LS(ls.j), _LS(ls.k) ); return ls; } + FI const XYZEval operator-() const { return LOGICAL_AXIS_ARRAY(-e, -x, -y, -z, -i, -j, -k); } + FI XYZEval operator-() { return LOGICAL_AXIS_ARRAY(-e, -x, -y, -z, -i, -j, -k); } + + // Modifier operators + FI XYZEval& operator+=(const XYval &rs) { x += rs.x; y += rs.y; return *this; } + FI XYZEval& operator-=(const XYval &rs) { x -= rs.x; y -= rs.y; return *this; } + FI XYZEval& operator*=(const XYval &rs) { x *= rs.x; y *= rs.y; return *this; } + FI XYZEval& operator/=(const XYval &rs) { x /= rs.x; y /= rs.y; return *this; } + FI XYZEval& operator+=(const XYZval &rs) { NUM_AXIS_CODE(x += rs.x, y += rs.y, z += rs.z, i += rs.i, j += rs.j, k += rs.k); return *this; } + FI XYZEval& operator-=(const XYZval &rs) { NUM_AXIS_CODE(x -= rs.x, y -= rs.y, z -= rs.z, i -= rs.i, j -= rs.j, k -= rs.k); return *this; } + FI XYZEval& operator*=(const XYZval &rs) { NUM_AXIS_CODE(x *= rs.x, y *= rs.y, z *= rs.z, i *= rs.i, j *= rs.j, k *= rs.k); return *this; } + FI XYZEval& operator/=(const XYZval &rs) { NUM_AXIS_CODE(x /= rs.x, y /= rs.y, z /= rs.z, i /= rs.i, j /= rs.j, k /= rs.k); return *this; } + FI XYZEval& operator+=(const XYZEval &rs) { LOGICAL_AXIS_CODE(e += rs.e, x += rs.x, y += rs.y, z += rs.z, i += rs.i, j += rs.j, k += rs.k); return *this; } + FI XYZEval& operator-=(const XYZEval &rs) { LOGICAL_AXIS_CODE(e -= rs.e, x -= rs.x, y -= rs.y, z -= rs.z, i -= rs.i, j -= rs.j, k -= rs.k); return *this; } + FI XYZEval& operator*=(const XYZEval &rs) { LOGICAL_AXIS_CODE(e *= rs.e, x *= rs.x, y *= rs.y, z *= rs.z, i *= rs.i, j *= rs.j, k *= rs.k); return *this; } + FI XYZEval& operator/=(const XYZEval &rs) { LOGICAL_AXIS_CODE(e /= rs.e, x /= rs.x, y /= rs.y, z /= rs.z, i /= rs.i, j /= rs.j, k /= rs.k); return *this; } + FI XYZEval& operator*=(const T &v) { LOGICAL_AXIS_CODE(e *= v, x *= v, y *= v, z *= v, i *= v, j *= v, k *= v); return *this; } + FI XYZEval& operator>>=(const int &v) { LOGICAL_AXIS_CODE(_RS(e), _RS(x), _RS(y), _RS(z), _RS(i), _RS(j), _RS(k)); return *this; } + FI XYZEval& operator<<=(const int &v) { LOGICAL_AXIS_CODE(_LS(e), _LS(x), _LS(y), _LS(z), _LS(i), _LS(j), _LS(k)); return *this; } + + // Exact comparisons. For floats a "NEAR" operation may be better. + FI bool operator==(const XYZval &rs) { return true NUM_AXIS_GANG(&& x == rs.x, && y == rs.y, && z == rs.z, && i == rs.i, && j == rs.j, && k == rs.k); } + FI bool operator==(const XYZval &rs) const { return true NUM_AXIS_GANG(&& x == rs.x, && y == rs.y, && z == rs.z, && i == rs.i, && j == rs.j, && k == rs.k); } + FI bool operator!=(const XYZval &rs) { return !operator==(rs); } + FI bool operator!=(const XYZval &rs) const { return !operator==(rs); } +}; + +#undef _RECIP +#undef _ABS +#undef _LS +#undef _RS +#undef FI diff --git a/src/core/utility.cpp b/src/core/utility.cpp new file mode 100644 index 0000000..e4fd525 --- /dev/null +++ b/src/core/utility.cpp @@ -0,0 +1,178 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "utility.h" + +#include "../MarlinCore.h" +#include "../module/temperature.h" + +void safe_delay(millis_t ms) { + while (ms > 50) { + ms -= 50; + delay(50); + thermalManager.task(); + } + delay(ms); + thermalManager.task(); // This keeps us safe if too many small safe_delay() calls are made +} + +// A delay to provide brittle hosts time to receive bytes +#if ENABLED(SERIAL_OVERRUN_PROTECTION) + + #include "../gcode/gcode.h" // for set_autoreport_paused + + void serial_delay(const millis_t ms) { + const bool was = gcode.set_autoreport_paused(true); + safe_delay(ms); + gcode.set_autoreport_paused(was); + } +#endif + +#if ENABLED(DEBUG_LEVELING_FEATURE) + + #include "../module/probe.h" + #include "../module/motion.h" + #include "../module/planner.h" + #include "../libs/numtostr.h" + #include "../feature/bedlevel/bedlevel.h" + + void log_machine_info() { + SERIAL_ECHOLNPGM("Machine Type: " + TERN_(DELTA, "Delta") + TERN_(IS_SCARA, "SCARA") + TERN_(IS_CORE, "Core") + TERN_(MARKFORGED_XY, "MarkForgedXY") + TERN_(MARKFORGED_YX, "MarkForgedYX") + TERN_(IS_CARTESIAN, "Cartesian") + ); + + SERIAL_ECHOLNPGM("Probe: " + TERN_(PROBE_MANUALLY, "PROBE_MANUALLY") + TERN_(NOZZLE_AS_PROBE, "NOZZLE_AS_PROBE") + TERN_(FIX_MOUNTED_PROBE, "FIX_MOUNTED_PROBE") + TERN_(HAS_Z_SERVO_PROBE, TERN(BLTOUCH, "BLTOUCH", "SERVO PROBE")) + TERN_(TOUCH_MI_PROBE, "TOUCH_MI_PROBE") + TERN_(Z_PROBE_SLED, "Z_PROBE_SLED") + TERN_(Z_PROBE_ALLEN_KEY, "Z_PROBE_ALLEN_KEY") + TERN_(SOLENOID_PROBE, "SOLENOID_PROBE") + TERN_(MAGLEV4, "MAGLEV4") + IF_DISABLED(PROBE_SELECTED, "NONE") + ); + + #if HAS_BED_PROBE + + #if !HAS_PROBE_XY_OFFSET + SERIAL_ECHOPGM("Probe Offset X0 Y0 Z", probe.offset.z, " ("); + #else + SERIAL_ECHOPGM_P(PSTR("Probe Offset X"), probe.offset_xy.x, SP_Y_STR, probe.offset_xy.y, SP_Z_STR, probe.offset.z); + if (probe.offset_xy.x > 0) + SERIAL_ECHOPGM(" (Right"); + else if (probe.offset_xy.x < 0) + SERIAL_ECHOPGM(" (Left"); + else if (probe.offset_xy.y != 0) + SERIAL_ECHOPGM(" (Middle"); + else + SERIAL_ECHOPGM(" (Aligned With"); + + if (probe.offset_xy.y > 0) + SERIAL_ECHOF(F(TERN(IS_SCARA, "-Distal", "-Back"))); + else if (probe.offset_xy.y < 0) + SERIAL_ECHOF(F(TERN(IS_SCARA, "-Proximal", "-Front"))); + else if (probe.offset_xy.x != 0) + SERIAL_ECHOPGM("-Center"); + + SERIAL_ECHOPGM(" & "); + + #endif + + SERIAL_ECHOF(probe.offset.z < 0 ? F("Below") : probe.offset.z > 0 ? F("Above") : F("Same Z as")); + SERIAL_ECHOLNPGM(" Nozzle)"); + + #endif + + #if HAS_ABL_OR_UBL + SERIAL_ECHOPGM("Auto Bed Leveling: " + TERN_(AUTO_BED_LEVELING_LINEAR, "LINEAR") + TERN_(AUTO_BED_LEVELING_BILINEAR, "BILINEAR") + TERN_(AUTO_BED_LEVELING_3POINT, "3POINT") + TERN_(AUTO_BED_LEVELING_UBL, "UBL") + ); + + if (planner.leveling_active) { + SERIAL_ECHOLNPGM(" (enabled)"); + #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) + if (planner.z_fade_height) + SERIAL_ECHOLNPGM("Z Fade: ", planner.z_fade_height); + #endif + #if ABL_PLANAR + SERIAL_ECHOPGM("ABL Adjustment"); + LOOP_NUM_AXES(a) { + SERIAL_ECHOPGM_P((PGM_P)pgm_read_ptr(&SP_AXIS_STR[a])); + serial_offset(planner.get_axis_position_mm(AxisEnum(a)) - current_position[a]); + } + #else + #if ENABLED(AUTO_BED_LEVELING_UBL) + SERIAL_ECHOPGM("UBL Adjustment Z"); + #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) + SERIAL_ECHOPGM("ABL Adjustment Z"); + #endif + const float rz = bedlevel.get_z_correction(current_position); + SERIAL_ECHO(ftostr43sign(rz, '+')); + #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) + if (planner.z_fade_height) { + SERIAL_ECHOPGM(" (", ftostr43sign(rz * planner.fade_scaling_factor_for_z(current_position.z), '+')); + SERIAL_CHAR(')'); + } + #endif + #endif + } + else + SERIAL_ECHOLNPGM(" (disabled)"); + + SERIAL_EOL(); + + #elif ENABLED(MESH_BED_LEVELING) + + SERIAL_ECHOPGM("Mesh Bed Leveling"); + if (planner.leveling_active) { + SERIAL_ECHOLNPGM(" (enabled)"); + const float z_offset = bedlevel.get_z_offset(), + z_correction = bedlevel.get_z_correction(current_position); + SERIAL_ECHOPGM("MBL Adjustment Z", ftostr43sign(z_offset + z_correction, '+')); + #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) + if (planner.z_fade_height) { + SERIAL_ECHOPGM(" (", ftostr43sign( + z_offset + z_correction * planner.fade_scaling_factor_for_z(current_position.z), '+' + )); + SERIAL_CHAR(')'); + } + #endif + } + else + SERIAL_ECHOPGM(" (disabled)"); + + SERIAL_EOL(); + + #endif // MESH_BED_LEVELING + } + +#endif // DEBUG_LEVELING_FEATURE diff --git a/src/core/utility.h b/src/core/utility.h new file mode 100644 index 0000000..a3cd794 --- /dev/null +++ b/src/core/utility.h @@ -0,0 +1,94 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfigPre.h" +#include "../core/types.h" +#include "../core/millis_t.h" + +void safe_delay(millis_t ms); // Delay ensuring that temperatures are updated and the watchdog is kept alive. + +#if ENABLED(SERIAL_OVERRUN_PROTECTION) + void serial_delay(const millis_t ms); +#else + inline void serial_delay(const millis_t) {} +#endif + +#if (GRID_MAX_POINTS_X) && (GRID_MAX_POINTS_Y) + + // 16x16 bit arrays + template + struct FlagBits { + typename IF<(W>8), uint16_t, uint8_t>::type bits[H]; + void fill() { memset(bits, 0xFF, sizeof(bits)); } + void reset() { memset(bits, 0x00, sizeof(bits)); } + void unmark(const uint8_t x, const uint8_t y) { CBI(bits[y], x); } + void mark(const uint8_t x, const uint8_t y) { SBI(bits[y], x); } + bool marked(const uint8_t x, const uint8_t y) { return TEST(bits[y], x); } + inline void unmark(const xy_int8_t &xy) { unmark(xy.x, xy.y); } + inline void mark(const xy_int8_t &xy) { mark(xy.x, xy.y); } + inline bool marked(const xy_int8_t &xy) { return marked(xy.x, xy.y); } + }; + + typedef FlagBits MeshFlags; + +#endif + +#if ENABLED(DEBUG_LEVELING_FEATURE) + void log_machine_info(); +#else + #define log_machine_info() NOOP +#endif + +/** + * A restorer instance remembers a variable's value before setting a + * new value, then restores the old value when it goes out of scope. + * Put operator= on your type to get extended behavior on value change. + */ +template +class restorer { + T& ref_; + T val_; +public: + restorer(T& perm) : ref_(perm), val_(perm) {} + restorer(T& perm, T temp_val) : ref_(perm), val_(perm) { perm = temp_val; } + ~restorer() { restore(); } + inline void restore() { ref_ = val_; } +}; + +#define REMEMBER(N,X,V...) restorer<__typeof__(X)> restorer_##N(X, ##V) +#define RESTORE(N) restorer_##N.restore() + +// Converts from an uint8_t in the range of 0-255 to an uint8_t +// in the range 0-100 while avoiding rounding artifacts +constexpr uint8_t ui8_to_percent(const uint8_t i) { return (int(i) * 100 + 127) / 255; } + +// Axis names for G-code parsing, reports, etc. +const xyze_char_t axis_codes LOGICAL_AXIS_ARRAY('E', 'X', 'Y', 'Z', AXIS4_NAME, AXIS5_NAME, AXIS6_NAME); +#if NUM_AXES <= XYZ && !HAS_EXTRUDERS + #define AXIS_CHAR(A) ((char)('X' + A)) + #define IAXIS_CHAR AXIS_CHAR +#else + const xyze_char_t iaxis_codes LOGICAL_AXIS_ARRAY('E', 'X', 'Y', 'Z', 'I', 'J', 'K'); + #define AXIS_CHAR(A) axis_codes[A] + #define IAXIS_CHAR(A) iaxis_codes[A] +#endif diff --git a/src/feature/adc/adc_mcp3426.cpp b/src/feature/adc/adc_mcp3426.cpp new file mode 100644 index 0000000..49bb67e --- /dev/null +++ b/src/feature/adc/adc_mcp3426.cpp @@ -0,0 +1,104 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * adc_mcp3426.cpp - library for MicroChip MCP3426 I2C A/D converter + * + * For implementation details, please take a look at the datasheet: + * https://www.microchip.com/en-us/product/MCP3426 + */ + +#include "../../inc/MarlinConfig.h" + +#if ENABLED(HAS_MCP3426_ADC) + +#include "adc_mcp3426.h" + +// Read the ADC value from MCP342X on a specific channel +int16_t MCP3426::ReadValue(uint8_t channel, uint8_t gain, uint8_t address) { + Error = false; + + #if PINS_EXIST(I2C_SCL, I2C_SDA) && DISABLED(SOFT_I2C_EEPROM) + Wire.setSDA(pin_t(I2C_SDA_PIN)); + Wire.setSCL(pin_t(I2C_SCL_PIN)); + #endif + + Wire.begin(); // No address joins the BUS as the master + + Wire.beginTransmission(I2C_ADDRESS(address)); + + // Continuous Conversion Mode, 16 bit, Channel 1, Gain x4 + // 26 = 0b00011000 + // RXXCSSGG + // R = Ready Bit + // XX = Channel (00=1, 01=2, 10=3 (MCP3428), 11=4 (MCP3428)) + // C = Conversion Mode Bit (1= Continuous Conversion Mode (Default)) + // SS = Sample rate, 10=15 samples per second @ 16 bits + // GG = Gain 00 =x1 + uint8_t controlRegister = 0b00011000; + + if (channel == 2) controlRegister |= 0b00100000; // Select channel 2 + + if (gain == 2) + controlRegister |= 0b00000001; + else if (gain == 4) + controlRegister |= 0b00000010; + else if (gain == 8) + controlRegister |= 0b00000011; + + Wire.write(controlRegister); + if (Wire.endTransmission() != 0) { + Error = true; + return 0; + } + + const uint8_t len = 3; + uint8_t buffer[len] = {}; + + do { + Wire.requestFrom(I2C_ADDRESS(address), len); + if (Wire.available() != len) { + Error = true; + return 0; + } + + for (uint8_t i = 0; i < len; ++i) + buffer[i] = Wire.read(); + + // Is conversion ready, if not loop around again + } while ((buffer[2] & 0x80) != 0); + + union TwoBytesToInt16 { + uint8_t bytes[2]; + int16_t integervalue; + }; + TwoBytesToInt16 ConversionUnion; + + ConversionUnion.bytes[1] = buffer[0]; + ConversionUnion.bytes[0] = buffer[1]; + + return ConversionUnion.integervalue; +} + +MCP3426 mcp3426; + +#endif // HAS_MCP3426_ADC diff --git a/src/feature/adc/adc_mcp3426.h b/src/feature/adc/adc_mcp3426.h new file mode 100644 index 0000000..af48593 --- /dev/null +++ b/src/feature/adc/adc_mcp3426.h @@ -0,0 +1,38 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * Arduino library for MicroChip MCP3426 I2C A/D converter. + * https://www.microchip.com/en-us/product/MCP3426 + */ + +#include +#include + +class MCP3426 { + public: + int16_t ReadValue(uint8_t channel, uint8_t gain, uint8_t address); + bool Error; +}; + +extern MCP3426 mcp3426; diff --git a/src/feature/ammeter.cpp b/src/feature/ammeter.cpp new file mode 100644 index 0000000..71b84f1 --- /dev/null +++ b/src/feature/ammeter.cpp @@ -0,0 +1,54 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(I2C_AMMETER) + +#include "ammeter.h" + +#ifndef I2C_AMMETER_IMAX + #define I2C_AMMETER_IMAX 0.500 // Calibration range 500 Milliamps +#endif + +INA226 ina; + +Ammeter ammeter; + +float Ammeter::scale; +float Ammeter::current; + +void Ammeter::init() { + ina.begin(); + ina.configure(INA226_AVERAGES_16, INA226_BUS_CONV_TIME_1100US, INA226_SHUNT_CONV_TIME_1100US, INA226_MODE_SHUNT_BUS_CONT); + ina.calibrate(I2C_AMMETER_SHUNT_RESISTOR, I2C_AMMETER_IMAX); +} + +float Ammeter::read() { + scale = 1; + current = ina.readShuntCurrent(); + if (current <= 0.0001f) current = 0; // Clean up least-significant-bit amplification errors + if (current < 0.1f) scale = 1000; + return current * scale; +} + +#endif // I2C_AMMETER diff --git a/src/feature/ammeter.h b/src/feature/ammeter.h new file mode 100644 index 0000000..86f09bb --- /dev/null +++ b/src/feature/ammeter.h @@ -0,0 +1,39 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfigPre.h" + +#include +#include + +class Ammeter { +private: + static float scale; + +public: + static float current; + static void init(); + static float read(); +}; + +extern Ammeter ammeter; diff --git a/src/feature/babystep.cpp b/src/feature/babystep.cpp new file mode 100644 index 0000000..54ad958 --- /dev/null +++ b/src/feature/babystep.cpp @@ -0,0 +1,67 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(BABYSTEPPING) + +#include "babystep.h" +#include "../MarlinCore.h" +#include "../module/motion.h" // for axes_should_home() +#include "../module/planner.h" // for axis_steps_per_mm[] +#include "../module/stepper.h" + +#if ENABLED(BABYSTEP_ALWAYS_AVAILABLE) + #include "../gcode/gcode.h" +#endif + +Babystep babystep; + +volatile int16_t Babystep::steps[BS_AXIS_IND(Z_AXIS) + 1]; +#if ENABLED(BABYSTEP_DISPLAY_TOTAL) + int16_t Babystep::axis_total[BS_TOTAL_IND(Z_AXIS) + 1]; +#endif +int16_t Babystep::accum; + +void Babystep::step_axis(const AxisEnum axis) { + const int16_t curTodo = steps[BS_AXIS_IND(axis)]; // get rid of volatile for performance + if (curTodo) { + stepper.do_babystep((AxisEnum)axis, curTodo > 0); + if (curTodo > 0) steps[BS_AXIS_IND(axis)]--; else steps[BS_AXIS_IND(axis)]++; + } +} + +void Babystep::add_mm(const AxisEnum axis, const_float_t mm) { + add_steps(axis, mm * planner.settings.axis_steps_per_mm[axis]); +} + +void Babystep::add_steps(const AxisEnum axis, const int16_t distance) { + if (DISABLED(BABYSTEP_WITHOUT_HOMING) && axes_should_home(_BV(axis))) return; + + accum += distance; // Count up babysteps for the UI + steps[BS_AXIS_IND(axis)] += distance; + TERN_(BABYSTEP_DISPLAY_TOTAL, axis_total[BS_TOTAL_IND(axis)] += distance); + TERN_(BABYSTEP_ALWAYS_AVAILABLE, gcode.reset_stepper_timeout()); + TERN_(INTEGRATED_BABYSTEPPING, if (has_steps()) stepper.initiateBabystepping()); +} + +#endif // BABYSTEPPING diff --git a/src/feature/babystep.h b/src/feature/babystep.h new file mode 100644 index 0000000..5693afb --- /dev/null +++ b/src/feature/babystep.h @@ -0,0 +1,82 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(INTEGRATED_BABYSTEPPING) + #define BABYSTEPS_PER_SEC 1000UL + #define BABYSTEP_TICKS ((STEPPER_TIMER_RATE) / (BABYSTEPS_PER_SEC)) +#else + #define BABYSTEPS_PER_SEC 976UL + #define BABYSTEP_TICKS ((TEMP_TIMER_RATE) / (BABYSTEPS_PER_SEC)) +#endif + +#if IS_CORE || EITHER(BABYSTEP_XY, I2C_POSITION_ENCODERS) + #define BS_AXIS_IND(A) A + #define BS_AXIS(I) AxisEnum(I) +#else + #define BS_AXIS_IND(A) 0 + #define BS_AXIS(I) Z_AXIS +#endif + +#if ENABLED(BABYSTEP_DISPLAY_TOTAL) + #if ENABLED(BABYSTEP_XY) + #define BS_TOTAL_IND(A) A + #else + #define BS_TOTAL_IND(A) 0 + #endif +#endif + +class Babystep { +public: + static volatile int16_t steps[BS_AXIS_IND(Z_AXIS) + 1]; + static int16_t accum; // Total babysteps in current edit + + #if ENABLED(BABYSTEP_DISPLAY_TOTAL) + static int16_t axis_total[BS_TOTAL_IND(Z_AXIS) + 1]; // Total babysteps since G28 + static void reset_total(const AxisEnum axis) { + if (TERN1(BABYSTEP_XY, axis == Z_AXIS)) + axis_total[BS_TOTAL_IND(axis)] = 0; + } + #endif + + static void add_steps(const AxisEnum axis, const int16_t distance); + static void add_mm(const AxisEnum axis, const_float_t mm); + + static bool has_steps() { + return steps[BS_AXIS_IND(X_AXIS)] || steps[BS_AXIS_IND(Y_AXIS)] || steps[BS_AXIS_IND(Z_AXIS)]; + } + + // + // Called by the Temperature or Stepper ISR to + // apply accumulated babysteps to the axes. + // + static void task() { + LOOP_LE_N(i, BS_AXIS_IND(Z_AXIS)) step_axis(BS_AXIS(i)); + } + +private: + static void step_axis(const AxisEnum axis); +}; + +extern Babystep babystep; diff --git a/src/feature/backlash.cpp b/src/feature/backlash.cpp new file mode 100644 index 0000000..13e2cd9 --- /dev/null +++ b/src/feature/backlash.cpp @@ -0,0 +1,217 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(BACKLASH_COMPENSATION) + +#include "backlash.h" + +#include "../module/motion.h" +#include "../module/planner.h" + +axis_bits_t Backlash::last_direction_bits; +xyz_long_t Backlash::residual_error{0}; + +#ifdef BACKLASH_DISTANCE_MM + #if ENABLED(BACKLASH_GCODE) + xyz_float_t Backlash::distance_mm = BACKLASH_DISTANCE_MM; + #else + const xyz_float_t Backlash::distance_mm = BACKLASH_DISTANCE_MM; + #endif +#endif + +#if ENABLED(BACKLASH_GCODE) + uint8_t Backlash::correction = (BACKLASH_CORRECTION) * all_on; + #ifdef BACKLASH_SMOOTHING_MM + float Backlash::smoothing_mm = BACKLASH_SMOOTHING_MM; + #endif +#endif + +#if ENABLED(MEASURE_BACKLASH_WHEN_PROBING) + xyz_float_t Backlash::measured_mm{0}; + xyz_uint8_t Backlash::measured_count{0}; +#endif + +Backlash backlash; + +/** + * To minimize seams in the printed part, backlash correction only adds + * steps to the current segment (instead of creating a new segment, which + * causes discontinuities and print artifacts). + * + * With a non-zero BACKLASH_SMOOTHING_MM value the backlash correction is + * spread over multiple segments, smoothing out artifacts even more. + */ + +void Backlash::add_correction_steps(const int32_t &da, const int32_t &db, const int32_t &dc, const axis_bits_t dm, block_t * const block) { + axis_bits_t changed_dir = last_direction_bits ^ dm; + // Ignore direction change unless steps are taken in that direction + #if DISABLED(CORE_BACKLASH) || EITHER(MARKFORGED_XY, MARKFORGED_YX) + if (!da) CBI(changed_dir, X_AXIS); + if (!db) CBI(changed_dir, Y_AXIS); + if (!dc) CBI(changed_dir, Z_AXIS); + #elif CORE_IS_XY + if (!(da + db)) CBI(changed_dir, X_AXIS); + if (!(da - db)) CBI(changed_dir, Y_AXIS); + if (!dc) CBI(changed_dir, Z_AXIS); + #elif CORE_IS_XZ + if (!(da + dc)) CBI(changed_dir, X_AXIS); + if (!(da - dc)) CBI(changed_dir, Z_AXIS); + if (!db) CBI(changed_dir, Y_AXIS); + #elif CORE_IS_YZ + if (!(db + dc)) CBI(changed_dir, Y_AXIS); + if (!(db - dc)) CBI(changed_dir, Z_AXIS); + if (!da) CBI(changed_dir, X_AXIS); + #endif + last_direction_bits ^= changed_dir; + + if (!correction && !residual_error) return; + + #ifdef BACKLASH_SMOOTHING_MM + // The segment proportion is a value greater than 0.0 indicating how much residual_error + // is corrected for in this segment. The contribution is based on segment length and the + // smoothing distance. Since the computation of this proportion involves a floating point + // division, defer computation until needed. + float segment_proportion = 0; + #endif + + const float f_corr = float(correction) / all_on; + + LOOP_NUM_AXES(axis) { + if (distance_mm[axis]) { + const bool reverse = TEST(dm, axis); + + // When an axis changes direction, add axis backlash to the residual error + if (TEST(changed_dir, axis)) + residual_error[axis] += (reverse ? -f_corr : f_corr) * distance_mm[axis] * planner.settings.axis_steps_per_mm[axis]; + + // Decide how much of the residual error to correct in this segment + int32_t error_correction = residual_error[axis]; + if (reverse != (error_correction < 0)) + error_correction = 0; // Don't take up any backlash in this segment, as it would subtract steps + + #ifdef BACKLASH_SMOOTHING_MM + if (error_correction && smoothing_mm != 0) { + // Take up a portion of the residual_error in this segment + if (segment_proportion == 0) segment_proportion = _MIN(1.0f, block->millimeters / smoothing_mm); + error_correction = CEIL(segment_proportion * error_correction); + } + #endif + + // This correction reduces the residual error and adds block steps + if (error_correction) { + block->steps[axis] += ABS(error_correction); + #if ENABLED(CORE_BACKLASH) + switch (axis) { + case CORE_AXIS_1: + //block->steps[CORE_AXIS_2] += influence_distance_mm[axis] * planner.settings.axis_steps_per_mm[CORE_AXIS_2]; + //SERIAL_ECHOLNPGM("CORE_AXIS_1 dir change. distance=", distance_mm[axis], " r.err=", residual_error[axis], + // " da=", da, " db=", db, " block->steps[axis]=", block->steps[axis], " err_corr=", error_correction); + break; + case CORE_AXIS_2: + //block->steps[CORE_AXIS_1] += influence_distance_mm[axis] * planner.settings.axis_steps_per_mm[CORE_AXIS_1];; + //SERIAL_ECHOLNPGM("CORE_AXIS_2 dir change. distance=", distance_mm[axis], " r.err=", residual_error[axis], + // " da=", da, " db=", db, " block->steps[axis]=", block->steps[axis], " err_corr=", error_correction); + break; + case NORMAL_AXIS: break; + } + residual_error[axis] = 0; // No residual_error needed for next CORE block, I think... + #else + residual_error[axis] -= error_correction; + #endif + } + } + } +} + +int32_t Backlash::get_applied_steps(const AxisEnum axis) { + if (axis >= NUM_AXES) return 0; + + const bool reverse = TEST(last_direction_bits, axis); + + const int32_t residual_error_axis = residual_error[axis]; + + // At startup it is assumed the last move was forwards. So the applied + // steps will always be a non-positive number. + + if (!reverse) return -residual_error_axis; + + const float f_corr = float(correction) / all_on; + const int32_t full_error_axis = -f_corr * distance_mm[axis] * planner.settings.axis_steps_per_mm[axis]; + return full_error_axis - residual_error_axis; +} + +class Backlash::StepAdjuster { + private: + xyz_long_t applied_steps; + public: + StepAdjuster() { + LOOP_NUM_AXES(axis) applied_steps[axis] = backlash.get_applied_steps((AxisEnum)axis); + } + ~StepAdjuster() { + // after backlash compensation parameter changes, ensure applied step count does not change + LOOP_NUM_AXES(axis) residual_error[axis] += backlash.get_applied_steps((AxisEnum)axis) - applied_steps[axis]; + } +}; + +#if ENABLED(BACKLASH_GCODE) + + void Backlash::set_correction_uint8(const uint8_t v) { + StepAdjuster adjuster; + correction = v; + } + + void Backlash::set_distance_mm(const AxisEnum axis, const float v) { + StepAdjuster adjuster; + distance_mm[axis] = v; + } + + #ifdef BACKLASH_SMOOTHING_MM + void Backlash::set_smoothing_mm(const float v) { + StepAdjuster adjuster; + smoothing_mm = v; + } + #endif + +#endif + +#if ENABLED(MEASURE_BACKLASH_WHEN_PROBING) + + #include "../module/probe.h" + + // Measure Z backlash by raising nozzle in increments until probe deactivates + void Backlash::measure_with_probe() { + if (measured_count.z == 255) return; + + const float start_height = current_position.z; + while (current_position.z < (start_height + BACKLASH_MEASUREMENT_LIMIT) && PROBE_TRIGGERED()) + do_blocking_move_to_z(current_position.z + BACKLASH_MEASUREMENT_RESOLUTION, MMM_TO_MMS(BACKLASH_MEASUREMENT_FEEDRATE)); + + // The backlash from all probe points is averaged, so count the number of measurements + measured_mm.z += current_position.z - start_height; + measured_count.z++; + } + +#endif + +#endif // BACKLASH_COMPENSATION diff --git a/src/feature/backlash.h b/src/feature/backlash.h new file mode 100644 index 0000000..0bace52 --- /dev/null +++ b/src/feature/backlash.h @@ -0,0 +1,96 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfigPre.h" +#include "../module/planner.h" + +class Backlash { +public: + static constexpr uint8_t all_on = 0xFF, all_off = 0x00; + +private: + static axis_bits_t last_direction_bits; + static xyz_long_t residual_error; + + #if ENABLED(BACKLASH_GCODE) + static uint8_t correction; + static xyz_float_t distance_mm; + #ifdef BACKLASH_SMOOTHING_MM + static float smoothing_mm; + #endif + #else + static constexpr uint8_t correction = (BACKLASH_CORRECTION) * all_on; + static const xyz_float_t distance_mm; + #ifdef BACKLASH_SMOOTHING_MM + static constexpr float smoothing_mm = BACKLASH_SMOOTHING_MM; + #endif + #endif + + #if ENABLED(MEASURE_BACKLASH_WHEN_PROBING) + static xyz_float_t measured_mm; + static xyz_uint8_t measured_count; + #endif + + class StepAdjuster; + +public: + static float get_measurement(const AxisEnum a) { + UNUSED(a); + // Return the measurement averaged over all readings + return TERN(MEASURE_BACKLASH_WHEN_PROBING + , measured_count[a] > 0 ? measured_mm[a] / measured_count[a] : 0 + , 0 + ); + } + + static bool has_measurement(const AxisEnum a) { + UNUSED(a); + return TERN0(MEASURE_BACKLASH_WHEN_PROBING, measured_count[a] > 0); + } + + static bool has_any_measurement() { + return has_measurement(X_AXIS) || has_measurement(Y_AXIS) || has_measurement(Z_AXIS); + } + + static void add_correction_steps(const int32_t &da, const int32_t &db, const int32_t &dc, const axis_bits_t dm, block_t * const block); + static int32_t get_applied_steps(const AxisEnum axis); + + #if ENABLED(BACKLASH_GCODE) + static void set_correction_uint8(const uint8_t v); + static uint8_t get_correction_uint8() { return correction; } + static void set_correction(const float v) { set_correction_uint8(_MAX(0, _MIN(1.0, v)) * all_on + 0.5f); } + static float get_correction() { return float(get_correction_uint8()) / all_on; } + static void set_distance_mm(const AxisEnum axis, const float v); + static float get_distance_mm(const AxisEnum axis) {return distance_mm[axis];} + #ifdef BACKLASH_SMOOTHING_MM + static void set_smoothing_mm(const float v); + static float get_smoothing_mm() {return smoothing_mm;} + #endif + #endif + + #if ENABLED(MEASURE_BACKLASH_WHEN_PROBING) + static void measure_with_probe(); + #endif +}; + +extern Backlash backlash; diff --git a/src/feature/baricuda.cpp b/src/feature/baricuda.cpp new file mode 100644 index 0000000..5968917 --- /dev/null +++ b/src/feature/baricuda.cpp @@ -0,0 +1,32 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(BARICUDA) + +#include "baricuda.h" + +uint8_t baricuda_valve_pressure = 0, + baricuda_e_to_p_pressure = 0; + +#endif // BARICUDA diff --git a/src/feature/baricuda.h b/src/feature/baricuda.h new file mode 100644 index 0000000..f28d07d --- /dev/null +++ b/src/feature/baricuda.h @@ -0,0 +1,25 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +extern uint8_t baricuda_valve_pressure, + baricuda_e_to_p_pressure; diff --git a/src/feature/bedlevel/abl/bbl.cpp b/src/feature/bedlevel/abl/bbl.cpp new file mode 100644 index 0000000..be0e862 --- /dev/null +++ b/src/feature/bedlevel/abl/bbl.cpp @@ -0,0 +1,439 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../../../inc/MarlinConfig.h" + +#if ENABLED(AUTO_BED_LEVELING_BILINEAR) + +#include "../bedlevel.h" + +#include "../../../module/motion.h" + +#define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) +#include "../../../core/debug_out.h" + +#if ENABLED(EXTENSIBLE_UI) + #include "../../../lcd/extui/ui_api.h" +#endif + +LevelingBilinear bedlevel; + +xy_pos_t LevelingBilinear::grid_spacing, + LevelingBilinear::grid_start; +xy_float_t LevelingBilinear::grid_factor; +bed_mesh_t LevelingBilinear::z_values; +xy_pos_t LevelingBilinear::cached_rel; +xy_int8_t LevelingBilinear::cached_g; + +/** + * Extrapolate a single point from its neighbors + */ +void LevelingBilinear::extrapolate_one_point(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) { + if (!isnan(z_values[x][y])) return; + if (DEBUGGING(LEVELING)) { + DEBUG_ECHOPGM("Extrapolate ["); + if (x < 10) DEBUG_CHAR(' '); + DEBUG_ECHO(x); + DEBUG_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' '); + DEBUG_CHAR(' '); + if (y < 10) DEBUG_CHAR(' '); + DEBUG_ECHO(y); + DEBUG_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' '); + DEBUG_ECHOLNPGM("]"); + } + + // Get X neighbors, Y neighbors, and XY neighbors + const uint8_t x1 = x + xdir, y1 = y + ydir, x2 = x1 + xdir, y2 = y1 + ydir; + float a1 = z_values[x1][y ], a2 = z_values[x2][y ], + b1 = z_values[x ][y1], b2 = z_values[x ][y2], + c1 = z_values[x1][y1], c2 = z_values[x2][y2]; + + // Treat far unprobed points as zero, near as equal to far + if (isnan(a2)) a2 = 0.0; + if (isnan(a1)) a1 = a2; + if (isnan(b2)) b2 = 0.0; + if (isnan(b1)) b1 = b2; + if (isnan(c2)) c2 = 0.0; + if (isnan(c1)) c1 = c2; + + const float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2; + + // Take the average instead of the median + z_values[x][y] = (a + b + c) / 3.0; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y])); + + // Median is robust (ignores outliers). + // z_values[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c) + // : ((c < b) ? b : (a < c) ? a : c); +} + +//Enable this if your SCARA uses 180° of total area +//#define EXTRAPOLATE_FROM_EDGE + +#if ENABLED(EXTRAPOLATE_FROM_EDGE) + #if (GRID_MAX_POINTS_X) < (GRID_MAX_POINTS_Y) + #define HALF_IN_X + #elif (GRID_MAX_POINTS_Y) < (GRID_MAX_POINTS_X) + #define HALF_IN_Y + #endif +#endif + +void LevelingBilinear::reset() { + grid_start.reset(); + grid_spacing.reset(); + GRID_LOOP(x, y) { + z_values[x][y] = NAN; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, 0)); + } +} + +void LevelingBilinear::set_grid(const xy_pos_t& _grid_spacing, const xy_pos_t& _grid_start) { + grid_spacing = _grid_spacing; + grid_start = _grid_start; + grid_factor = grid_spacing.reciprocal(); +} + +/** + * Fill in the unprobed points (corners of circular print surface) + * using linear extrapolation, away from the center. + */ +void LevelingBilinear::extrapolate_unprobed_bed_level() { + #ifdef HALF_IN_X + constexpr uint8_t ctrx2 = 0, xend = GRID_MAX_POINTS_X - 1; + #else + constexpr uint8_t ctrx1 = (GRID_MAX_CELLS_X) / 2, // left-of-center + ctrx2 = (GRID_MAX_POINTS_X) / 2, // right-of-center + xend = ctrx1; + #endif + + #ifdef HALF_IN_Y + constexpr uint8_t ctry2 = 0, yend = GRID_MAX_POINTS_Y - 1; + #else + constexpr uint8_t ctry1 = (GRID_MAX_CELLS_Y) / 2, // top-of-center + ctry2 = (GRID_MAX_POINTS_Y) / 2, // bottom-of-center + yend = ctry1; + #endif + + LOOP_LE_N(xo, xend) + LOOP_LE_N(yo, yend) { + uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo; + #ifndef HALF_IN_X + const uint8_t x1 = ctrx1 - xo; + #endif + #ifndef HALF_IN_Y + const uint8_t y1 = ctry1 - yo; + #ifndef HALF_IN_X + extrapolate_one_point(x1, y1, +1, +1); // left-below + + + #endif + extrapolate_one_point(x2, y1, -1, +1); // right-below - + + #endif + #ifndef HALF_IN_X + extrapolate_one_point(x1, y2, +1, -1); // left-above + - + #endif + extrapolate_one_point(x2, y2, -1, -1); // right-above - - + } +} + +void LevelingBilinear::print_leveling_grid(const bed_mesh_t* _z_values /*= NULL*/) { + // print internal grid(s) or just the one passed as a parameter + SERIAL_ECHOLNPGM("Bilinear Leveling Grid:"); + print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 3, _z_values ? *_z_values[0] : z_values[0]); + + #if ENABLED(ABL_BILINEAR_SUBDIVISION) + if (!_z_values) { + SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:"); + print_2d_array(ABL_GRID_POINTS_VIRT_X, ABL_GRID_POINTS_VIRT_Y, 5, z_values_virt[0]); + } + #endif +} + +#if ENABLED(ABL_BILINEAR_SUBDIVISION) + + #define ABL_TEMP_POINTS_X (GRID_MAX_POINTS_X + 2) + #define ABL_TEMP_POINTS_Y (GRID_MAX_POINTS_Y + 2) + float LevelingBilinear::z_values_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y]; + xy_pos_t LevelingBilinear::grid_spacing_virt; + xy_float_t LevelingBilinear::grid_factor_virt; + + #define LINEAR_EXTRAPOLATION(E, I) ((E) * 2 - (I)) + float LevelingBilinear::bed_level_virt_coord(const uint8_t x, const uint8_t y) { + uint8_t ep = 0, ip = 1; + if (x > (GRID_MAX_POINTS_X) + 1 || y > (GRID_MAX_POINTS_Y) + 1) { + // The requested point requires extrapolating two points beyond the mesh. + // These values are only requested for the edges of the mesh, which are always an actual mesh point, + // and do not require interpolation. When interpolation is not needed, this "Mesh + 2" point is + // cancelled out in bed_level_virt_cmr and does not impact the result. Return 0.0 rather than + // making this function more complex by extrapolating two points. + return 0.0; + } + if (!x || x == ABL_TEMP_POINTS_X - 1) { + if (x) { + ep = (GRID_MAX_POINTS_X) - 1; + ip = GRID_MAX_CELLS_X - 1; + } + if (WITHIN(y, 1, ABL_TEMP_POINTS_Y - 2)) + return LINEAR_EXTRAPOLATION( + z_values[ep][y - 1], + z_values[ip][y - 1] + ); + else + return LINEAR_EXTRAPOLATION( + bed_level_virt_coord(ep + 1, y), + bed_level_virt_coord(ip + 1, y) + ); + } + if (!y || y == ABL_TEMP_POINTS_Y - 1) { + if (y) { + ep = (GRID_MAX_POINTS_Y) - 1; + ip = GRID_MAX_CELLS_Y - 1; + } + if (WITHIN(x, 1, ABL_TEMP_POINTS_X - 2)) + return LINEAR_EXTRAPOLATION( + z_values[x - 1][ep], + z_values[x - 1][ip] + ); + else + return LINEAR_EXTRAPOLATION( + bed_level_virt_coord(x, ep + 1), + bed_level_virt_coord(x, ip + 1) + ); + } + return z_values[x - 1][y - 1]; + } + + float LevelingBilinear::bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) { + return ( + p[i-1] * -t * sq(1 - t) + + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t)) + + p[i+1] * t * (1 + 4 * t - 3 * sq(t)) + - p[i+2] * sq(t) * (1 - t) + ) * 0.5f; + } + + float LevelingBilinear::bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const_float_t tx, const_float_t ty) { + float row[4], column[4]; + LOOP_L_N(i, 4) { + LOOP_L_N(j, 4) { + column[j] = bed_level_virt_coord(i + x - 1, j + y - 1); + } + row[i] = bed_level_virt_cmr(column, 1, ty); + } + return bed_level_virt_cmr(row, 1, tx); + } + + void LevelingBilinear::bed_level_virt_interpolate() { + grid_spacing_virt = grid_spacing / (BILINEAR_SUBDIVISIONS); + grid_factor_virt = grid_spacing_virt.reciprocal(); + LOOP_L_N(y, GRID_MAX_POINTS_Y) + LOOP_L_N(x, GRID_MAX_POINTS_X) + LOOP_L_N(ty, BILINEAR_SUBDIVISIONS) + LOOP_L_N(tx, BILINEAR_SUBDIVISIONS) { + if ((ty && y == (GRID_MAX_POINTS_Y) - 1) || (tx && x == (GRID_MAX_POINTS_X) - 1)) + continue; + z_values_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] = + bed_level_virt_2cmr( + x + 1, + y + 1, + (float)tx / (BILINEAR_SUBDIVISIONS), + (float)ty / (BILINEAR_SUBDIVISIONS) + ); + } + } + +#endif // ABL_BILINEAR_SUBDIVISION + +// Refresh after other values have been updated +void LevelingBilinear::refresh_bed_level() { + TERN_(ABL_BILINEAR_SUBDIVISION, bed_level_virt_interpolate()); + cached_rel.x = cached_rel.y = -999.999; + cached_g.x = cached_g.y = -99; +} + +#if ENABLED(ABL_BILINEAR_SUBDIVISION) + #define ABL_BG_SPACING(A) grid_spacing_virt.A + #define ABL_BG_FACTOR(A) grid_factor_virt.A + #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X + #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y + #define ABL_BG_GRID(X,Y) z_values_virt[X][Y] +#else + #define ABL_BG_SPACING(A) grid_spacing.A + #define ABL_BG_FACTOR(A) grid_factor.A + #define ABL_BG_POINTS_X GRID_MAX_POINTS_X + #define ABL_BG_POINTS_Y GRID_MAX_POINTS_Y + #define ABL_BG_GRID(X,Y) z_values[X][Y] +#endif + +// Get the Z adjustment for non-linear bed leveling +float LevelingBilinear::get_z_correction(const xy_pos_t &raw) { + + static float z1, d2, z3, d4, L, D; + + static xy_pos_t ratio; + + // Whole units for the grid line indices. Constrained within bounds. + static xy_int8_t thisg, nextg; + + // XY relative to the probed area + xy_pos_t rel = raw - grid_start.asFloat(); + + #if ENABLED(EXTRAPOLATE_BEYOND_GRID) + #define FAR_EDGE_OR_BOX 2 // Keep using the last grid box + #else + #define FAR_EDGE_OR_BOX 1 // Just use the grid far edge + #endif + + if (cached_rel.x != rel.x) { + cached_rel.x = rel.x; + ratio.x = rel.x * ABL_BG_FACTOR(x); + const float gx = constrain(FLOOR(ratio.x), 0, ABL_BG_POINTS_X - (FAR_EDGE_OR_BOX)); + ratio.x -= gx; // Subtract whole to get the ratio within the grid box + + #if DISABLED(EXTRAPOLATE_BEYOND_GRID) + // Beyond the grid maintain height at grid edges + NOLESS(ratio.x, 0); // Never <0 (>1 is ok when nextg.x==thisg.x) + #endif + + thisg.x = gx; + nextg.x = _MIN(thisg.x + 1, ABL_BG_POINTS_X - 1); + } + + if (cached_rel.y != rel.y || cached_g.x != thisg.x) { + + if (cached_rel.y != rel.y) { + cached_rel.y = rel.y; + ratio.y = rel.y * ABL_BG_FACTOR(y); + const float gy = constrain(FLOOR(ratio.y), 0, ABL_BG_POINTS_Y - (FAR_EDGE_OR_BOX)); + ratio.y -= gy; + + #if DISABLED(EXTRAPOLATE_BEYOND_GRID) + // Beyond the grid maintain height at grid edges + NOLESS(ratio.y, 0); // Never < 0.0. (> 1.0 is ok when nextg.y==thisg.y.) + #endif + + thisg.y = gy; + nextg.y = _MIN(thisg.y + 1, ABL_BG_POINTS_Y - 1); + } + + if (cached_g != thisg) { + cached_g = thisg; + // Z at the box corners + z1 = ABL_BG_GRID(thisg.x, thisg.y); // left-front + d2 = ABL_BG_GRID(thisg.x, nextg.y) - z1; // left-back (delta) + z3 = ABL_BG_GRID(nextg.x, thisg.y); // right-front + d4 = ABL_BG_GRID(nextg.x, nextg.y) - z3; // right-back (delta) + } + + // Bilinear interpolate. Needed since rel.y or thisg.x has changed. + L = z1 + d2 * ratio.y; // Linear interp. LF -> LB + const float R = z3 + d4 * ratio.y; // Linear interp. RF -> RB + + D = R - L; + } + + const float offset = L + ratio.x * D; // the offset almost always changes + + /* + static float last_offset = 0; + if (ABS(last_offset - offset) > 0.2) { + SERIAL_ECHOLNPGM("Sudden Shift at x=", rel.x, " / ", grid_spacing.x, " -> thisg.x=", thisg.x); + SERIAL_ECHOLNPGM(" y=", rel.y, " / ", grid_spacing.y, " -> thisg.y=", thisg.y); + SERIAL_ECHOLNPGM(" ratio.x=", ratio.x, " ratio.y=", ratio.y); + SERIAL_ECHOLNPGM(" z1=", z1, " z2=", z2, " z3=", z3, " z4=", z4); + SERIAL_ECHOLNPGM(" L=", L, " R=", R, " offset=", offset); + } + last_offset = offset; + //*/ + + return offset; +} + +#if IS_CARTESIAN && DISABLED(SEGMENT_LEVELED_MOVES) + + #define CELL_INDEX(A,V) ((V - grid_start.A) * ABL_BG_FACTOR(A)) + + /** + * Prepare a bilinear-leveled linear move on Cartesian, + * splitting the move where it crosses grid borders. + */ + void LevelingBilinear::line_to_destination(const_feedRate_t scaled_fr_mm_s, uint16_t x_splits, uint16_t y_splits) { + // Get current and destination cells for this line + xy_int_t c1 { CELL_INDEX(x, current_position.x), CELL_INDEX(y, current_position.y) }, + c2 { CELL_INDEX(x, destination.x), CELL_INDEX(y, destination.y) }; + LIMIT(c1.x, 0, ABL_BG_POINTS_X - 2); + LIMIT(c1.y, 0, ABL_BG_POINTS_Y - 2); + LIMIT(c2.x, 0, ABL_BG_POINTS_X - 2); + LIMIT(c2.y, 0, ABL_BG_POINTS_Y - 2); + + // Start and end in the same cell? No split needed. + if (c1 == c2) { + current_position = destination; + line_to_current_position(scaled_fr_mm_s); + return; + } + + #define LINE_SEGMENT_END(A) (current_position.A + (destination.A - current_position.A) * normalized_dist) + + float normalized_dist; + xyze_pos_t end; + const xy_int8_t gc { _MAX(c1.x, c2.x), _MAX(c1.y, c2.y) }; + + // Crosses on the X and not already split on this X? + // The x_splits flags are insurance against rounding errors. + if (c2.x != c1.x && TEST(x_splits, gc.x)) { + // Split on the X grid line + CBI(x_splits, gc.x); + end = destination; + destination.x = grid_start.x + ABL_BG_SPACING(x) * gc.x; + normalized_dist = (destination.x - current_position.x) / (end.x - current_position.x); + destination.y = LINE_SEGMENT_END(y); + } + // Crosses on the Y and not already split on this Y? + else if (c2.y != c1.y && TEST(y_splits, gc.y)) { + // Split on the Y grid line + CBI(y_splits, gc.y); + end = destination; + destination.y = grid_start.y + ABL_BG_SPACING(y) * gc.y; + normalized_dist = (destination.y - current_position.y) / (end.y - current_position.y); + destination.x = LINE_SEGMENT_END(x); + } + else { + // Must already have been split on these border(s) + // This should be a rare case. + current_position = destination; + line_to_current_position(scaled_fr_mm_s); + return; + } + + destination.z = LINE_SEGMENT_END(z); + destination.e = LINE_SEGMENT_END(e); + + // Do the split and look for more borders + line_to_destination(scaled_fr_mm_s, x_splits, y_splits); + + // Restore destination from stack + destination = end; + line_to_destination(scaled_fr_mm_s, x_splits, y_splits); + } + +#endif // IS_CARTESIAN && !SEGMENT_LEVELED_MOVES + +#endif // AUTO_BED_LEVELING_BILINEAR diff --git a/src/feature/bedlevel/abl/bbl.h b/src/feature/bedlevel/abl/bbl.h new file mode 100644 index 0000000..c2be4fe --- /dev/null +++ b/src/feature/bedlevel/abl/bbl.h @@ -0,0 +1,70 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../../../inc/MarlinConfigPre.h" + +class LevelingBilinear { +public: + static bed_mesh_t z_values; + static xy_pos_t grid_spacing, grid_start; + +private: + static xy_float_t grid_factor; + static xy_pos_t cached_rel; + static xy_int8_t cached_g; + + static void extrapolate_one_point(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir); + + #if ENABLED(ABL_BILINEAR_SUBDIVISION) + #define ABL_GRID_POINTS_VIRT_X (GRID_MAX_CELLS_X * (BILINEAR_SUBDIVISIONS) + 1) + #define ABL_GRID_POINTS_VIRT_Y (GRID_MAX_CELLS_Y * (BILINEAR_SUBDIVISIONS) + 1) + + static float z_values_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y]; + static xy_pos_t grid_spacing_virt; + static xy_float_t grid_factor_virt; + + static float bed_level_virt_coord(const uint8_t x, const uint8_t y); + static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t); + static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const_float_t tx, const_float_t ty); + static void bed_level_virt_interpolate(); + #endif + +public: + static void reset(); + static void set_grid(const xy_pos_t& _grid_spacing, const xy_pos_t& _grid_start); + static void extrapolate_unprobed_bed_level(); + static void print_leveling_grid(const bed_mesh_t* _z_values = NULL); + static void refresh_bed_level(); + static bool has_mesh() { return !!grid_spacing.x; } + static bool mesh_is_valid() { return has_mesh(); } + static float get_mesh_x(const uint8_t i) { return grid_start.x + i * grid_spacing.x; } + static float get_mesh_y(const uint8_t j) { return grid_start.y + j * grid_spacing.y; } + static float get_z_correction(const xy_pos_t &raw); + static constexpr float get_z_offset() { return 0.0f; } + + #if IS_CARTESIAN && DISABLED(SEGMENT_LEVELED_MOVES) + static void line_to_destination(const_feedRate_t scaled_fr_mm_s, uint16_t x_splits=0xFFFF, uint16_t y_splits=0xFFFF); + #endif +}; + +extern LevelingBilinear bedlevel; diff --git a/src/feature/bedlevel/bedlevel.cpp b/src/feature/bedlevel/bedlevel.cpp new file mode 100644 index 0000000..2207884 --- /dev/null +++ b/src/feature/bedlevel/bedlevel.cpp @@ -0,0 +1,217 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../../inc/MarlinConfig.h" + +#if HAS_LEVELING + +#include "bedlevel.h" +#include "../../module/planner.h" + +#if EITHER(MESH_BED_LEVELING, PROBE_MANUALLY) + #include "../../module/motion.h" +#endif + +#if ENABLED(PROBE_MANUALLY) + bool g29_in_progress = false; +#endif + +#if ENABLED(LCD_BED_LEVELING) + #include "../../lcd/marlinui.h" +#endif + +#define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) +#include "../../core/debug_out.h" + +#if ENABLED(EXTENSIBLE_UI) + #include "../../lcd/extui/ui_api.h" +#endif + +bool leveling_is_valid() { + return TERN1(HAS_MESH, bedlevel.mesh_is_valid()); +} + +/** + * Turn bed leveling on or off, correcting the current position. + * + * Disable: Current position = physical position + * Enable: Current position = "unleveled" physical position + */ +void set_bed_leveling_enabled(const bool enable/*=true*/) { + + const bool can_change = TERN1(AUTO_BED_LEVELING_BILINEAR, !enable || leveling_is_valid()); + + if (can_change && enable != planner.leveling_active) { + + auto _report_leveling = []{ + if (DEBUGGING(LEVELING)) { + if (planner.leveling_active) + DEBUG_POS("Leveling ON", current_position); + else + DEBUG_POS("Leveling OFF", current_position); + } + }; + + _report_leveling(); + planner.synchronize(); + + // Get the corrected leveled / unleveled position + planner.apply_modifiers(current_position); // Physical position with all modifiers + planner.leveling_active ^= true; // Toggle leveling between apply and unapply + planner.unapply_modifiers(current_position); // Logical position with modifiers removed + + sync_plan_position(); + _report_leveling(); + } +} + +TemporaryBedLevelingState::TemporaryBedLevelingState(const bool enable) : saved(planner.leveling_active) { + set_bed_leveling_enabled(enable); +} + +#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) + + void set_z_fade_height(const_float_t zfh, const bool do_report/*=true*/) { + + if (planner.z_fade_height == zfh) return; + + const bool leveling_was_active = planner.leveling_active; + set_bed_leveling_enabled(false); + + planner.set_z_fade_height(zfh); + + if (leveling_was_active) { + const xyz_pos_t oldpos = current_position; + set_bed_leveling_enabled(true); + if (do_report && oldpos != current_position) + report_current_position(); + } + } + +#endif // ENABLE_LEVELING_FADE_HEIGHT + +/** + * Reset calibration results to zero. + */ +void reset_bed_level() { + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("reset_bed_level"); + IF_DISABLED(AUTO_BED_LEVELING_UBL, set_bed_leveling_enabled(false)); + TERN_(HAS_MESH, bedlevel.reset()); + TERN_(ABL_PLANAR, planner.bed_level_matrix.set_to_identity()); +} + +#if EITHER(AUTO_BED_LEVELING_BILINEAR, MESH_BED_LEVELING) + + /** + * Enable to produce output in JSON format suitable + * for SCAD or JavaScript mesh visualizers. + * + * Visualize meshes in OpenSCAD using the included script. + * + * buildroot/shared/scripts/MarlinMesh.scad + */ + //#define SCAD_MESH_OUTPUT + + /** + * Print calibration results for plotting or manual frame adjustment. + */ + void print_2d_array(const uint8_t sx, const uint8_t sy, const uint8_t precision, const float *values) { + #ifndef SCAD_MESH_OUTPUT + LOOP_L_N(x, sx) { + serial_spaces(precision + (x < 10 ? 3 : 2)); + SERIAL_ECHO(x); + } + SERIAL_EOL(); + #endif + #ifdef SCAD_MESH_OUTPUT + SERIAL_ECHOLNPGM("measured_z = ["); // open 2D array + #endif + LOOP_L_N(y, sy) { + #ifdef SCAD_MESH_OUTPUT + SERIAL_ECHOPGM(" ["); // open sub-array + #else + if (y < 10) SERIAL_CHAR(' '); + SERIAL_ECHO(y); + #endif + LOOP_L_N(x, sx) { + SERIAL_CHAR(' '); + const float offset = values[x * sy + y]; + if (!isnan(offset)) { + if (offset >= 0) SERIAL_CHAR('+'); + SERIAL_ECHO_F(offset, int(precision)); + } + else { + #ifdef SCAD_MESH_OUTPUT + for (uint8_t i = 3; i < precision + 3; i++) + SERIAL_CHAR(' '); + SERIAL_ECHOPGM("NAN"); + #else + LOOP_L_N(i, precision + 3) + SERIAL_CHAR(i ? '=' : ' '); + #endif + } + #ifdef SCAD_MESH_OUTPUT + if (x < sx - 1) SERIAL_CHAR(','); + #endif + } + #ifdef SCAD_MESH_OUTPUT + SERIAL_ECHOPGM(" ]"); // close sub-array + if (y < sy - 1) SERIAL_CHAR(','); + #endif + SERIAL_EOL(); + } + #ifdef SCAD_MESH_OUTPUT + SERIAL_ECHOPGM("];"); // close 2D array + #endif + SERIAL_EOL(); + } + +#endif // AUTO_BED_LEVELING_BILINEAR || MESH_BED_LEVELING + +#if EITHER(MESH_BED_LEVELING, PROBE_MANUALLY) + + void _manual_goto_xy(const xy_pos_t &pos) { + + // Get the resting Z position for after the XY move + #ifdef MANUAL_PROBE_START_Z + constexpr float finalz = _MAX(0, MANUAL_PROBE_START_Z); // If a MANUAL_PROBE_START_Z value is set, always respect it + #else + #warning "It's recommended to set some MANUAL_PROBE_START_Z value for manual leveling." + #endif + #if Z_CLEARANCE_BETWEEN_MANUAL_PROBES > 0 // A probe/obstacle clearance exists so there is a raise: + #ifndef MANUAL_PROBE_START_Z + const float finalz = current_position.z; // - Use the current Z for starting-Z if no MANUAL_PROBE_START_Z was provided + #endif + do_blocking_move_to_xy_z(pos, Z_CLEARANCE_BETWEEN_MANUAL_PROBES); // - Raise Z, then move to the new XY + do_blocking_move_to_z(finalz); // - Lower down to the starting Z height, ready for adjustment! + #elif defined(MANUAL_PROBE_START_Z) // A starting-Z was provided, but there's no raise: + do_blocking_move_to_xy_z(pos, finalz); // - Move in XY then down to the starting Z height, ready for adjustment! + #else // Zero raise and no starting Z height either: + do_blocking_move_to_xy(pos); // - Move over with no raise, ready for adjustment! + #endif + + TERN_(LCD_BED_LEVELING, ui.wait_for_move = false); + } + +#endif // MESH_BED_LEVELING || PROBE_MANUALLY + +#endif // HAS_LEVELING diff --git a/src/feature/bedlevel/bedlevel.h b/src/feature/bedlevel/bedlevel.h new file mode 100644 index 0000000..aeafec1 --- /dev/null +++ b/src/feature/bedlevel/bedlevel.h @@ -0,0 +1,99 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../../inc/MarlinConfigPre.h" + +#if EITHER(RESTORE_LEVELING_AFTER_G28, ENABLE_LEVELING_AFTER_G28) + #define CAN_SET_LEVELING_AFTER_G28 1 +#endif + +#if ENABLED(PROBE_MANUALLY) + extern bool g29_in_progress; +#else + constexpr bool g29_in_progress = false; +#endif + +bool leveling_is_valid(); +void set_bed_leveling_enabled(const bool enable=true); +void reset_bed_level(); + +#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) + void set_z_fade_height(const_float_t zfh, const bool do_report=true); +#endif + +#if EITHER(MESH_BED_LEVELING, PROBE_MANUALLY) + void _manual_goto_xy(const xy_pos_t &pos); +#endif + +/** + * A class to save and change the bed leveling state, + * then restore it when it goes out of scope. + */ +class TemporaryBedLevelingState { + bool saved; + public: + TemporaryBedLevelingState(const bool enable); + ~TemporaryBedLevelingState() { set_bed_leveling_enabled(saved); } +}; +#define TEMPORARY_BED_LEVELING_STATE(enable) const TemporaryBedLevelingState tbls(enable) + +#if HAS_MESH + + typedef float bed_mesh_t[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y]; + + #if ENABLED(AUTO_BED_LEVELING_BILINEAR) + #include "abl/bbl.h" + #elif ENABLED(AUTO_BED_LEVELING_UBL) + #include "ubl/ubl.h" + #elif ENABLED(MESH_BED_LEVELING) + #include "mbl/mesh_bed_leveling.h" + #endif + + #if EITHER(AUTO_BED_LEVELING_BILINEAR, MESH_BED_LEVELING) + + #include + + typedef float (*element_2d_fn)(const uint8_t, const uint8_t); + + /** + * Print calibration results for plotting or manual frame adjustment. + */ + void print_2d_array(const uint8_t sx, const uint8_t sy, const uint8_t precision, const float *values); + + #endif + + struct mesh_index_pair { + xy_int8_t pos; + float distance; // When populated, the distance from the search location + void invalidate() { pos = -1; } + bool valid() const { return pos.x >= 0 && pos.y >= 0; } + #if ENABLED(AUTO_BED_LEVELING_UBL) + xy_pos_t meshpos() { + return { bedlevel.get_mesh_x(pos.x), bedlevel.get_mesh_y(pos.y) }; + } + #endif + operator xy_int8_t&() { return pos; } + operator const xy_int8_t&() const { return pos; } + }; + +#endif diff --git a/src/feature/bedlevel/hilbert_curve.cpp b/src/feature/bedlevel/hilbert_curve.cpp new file mode 100644 index 0000000..7474123 --- /dev/null +++ b/src/feature/bedlevel/hilbert_curve.cpp @@ -0,0 +1,110 @@ +/********************* + * hilbert_curve.cpp * + *********************/ + +/**************************************************************************** + * Written By Marcio Teixeira 2021 - SynDaver Labs, Inc. * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation, either version 3 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * To view a copy of the GNU General Public License, go to the following * + * location: . * + ****************************************************************************/ + +#include "../../inc/MarlinConfig.h" + +#if ENABLED(UBL_HILBERT_CURVE) + +#include "bedlevel.h" +#include "hilbert_curve.h" + +constexpr int8_t to_fix(int8_t v) { return v * 2; } +constexpr int8_t to_int(int8_t v) { return v / 2; } +constexpr uint8_t log2(uint8_t n) { return (n > 1) ? 1 + log2(n >> 1) : 0; } +constexpr uint8_t order(uint8_t n) { return uint8_t(log2(n - 1)) + 1; } +constexpr uint8_t ord = order(_MAX(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y)); +constexpr uint8_t dim = _BV(ord); + +static inline bool eval_candidate(int8_t x, int8_t y, hilbert_curve::callback_ptr func, void *data) { + // The print bed likely has fewer points than the full Hilbert + // curve, so cull unnecessary points + return x < (GRID_MAX_POINTS_X) && y < (GRID_MAX_POINTS_Y) ? func(x, y, data) : false; +} + +bool hilbert_curve::hilbert(int8_t x, int8_t y, int8_t xi, int8_t xj, int8_t yi, int8_t yj, uint8_t n, hilbert_curve::callback_ptr func, void *data) { + /** + * Hilbert space-filling curve implementation + * + * x and y : coordinates of the bottom left corner + * xi and xj : i and j components of the unit x vector of the frame + * yi and yj : i and j components of the unit y vector of the frame + * + * From: http://www.fundza.com/algorithmic/space_filling/hilbert/basics/index.html + */ + if (n) + return hilbert(x, y, yi/2, yj/2, xi/2, xj/2, n-1, func, data) || + hilbert(x+xi/2, y+xj/2, xi/2, xj/2, yi/2, yj/2, n-1, func, data) || + hilbert(x+xi/2+yi/2, y+xj/2+yj/2, xi/2, xj/2, yi/2, yj/2, n-1, func, data) || + hilbert(x+xi/2+yi, y+xj/2+yj, -yi/2, -yj/2, -xi/2, -xj/2, n-1, func, data); + else + return eval_candidate(to_int(x+(xi+yi)/2), to_int(y+(xj+yj)/2), func, data); +} + +/** + * Calls func(x, y, data) for all points in the Hilbert curve. + * If that function returns true, the search is terminated. + */ +bool hilbert_curve::search(hilbert_curve::callback_ptr func, void *data) { + return hilbert(to_fix(0), to_fix(0),to_fix(dim), to_fix(0), to_fix(0), to_fix(dim), ord, func, data); +} + +/* Helper function for starting the search at a particular point */ + +typedef struct { + uint8_t x, y; + bool found_1st; + hilbert_curve::callback_ptr func; + void *data; +} search_from_t; + +static bool search_from_helper(uint8_t x, uint8_t y, void *data) { + search_from_t *d = (search_from_t *) data; + if (d->x == x && d->y == y) + d->found_1st = true; + return d->found_1st ? d->func(x, y, d->data) : false; +} + +/** + * Same as search, except start at a specific grid intersection point. + */ +bool hilbert_curve::search_from(uint8_t x, uint8_t y, hilbert_curve::callback_ptr func, void *data) { + search_from_t d; + d.x = x; + d.y = y; + d.found_1st = false; + d.func = func; + d.data = data; + // Call twice to allow search to wrap back to the beginning and picked up points prior to the start. + return search(search_from_helper, &d) || search(search_from_helper, &d); +} + +/** + * Like search_from, but takes a bed position and starts from the nearest + * point on the Hilbert curve. + */ +bool hilbert_curve::search_from_closest(const xy_pos_t &pos, hilbert_curve::callback_ptr func, void *data) { + // Find closest grid intersection + const uint8_t grid_x = LROUND(constrain(float(pos.x - (MESH_MIN_X)) / (MESH_X_DIST), 0, (GRID_MAX_POINTS_X) - 1)); + const uint8_t grid_y = LROUND(constrain(float(pos.y - (MESH_MIN_Y)) / (MESH_Y_DIST), 0, (GRID_MAX_POINTS_Y) - 1)); + return search_from(grid_x, grid_y, func, data); +} + +#endif // UBL_HILBERT_CURVE diff --git a/src/feature/bedlevel/hilbert_curve.h b/src/feature/bedlevel/hilbert_curve.h new file mode 100644 index 0000000..a5dce8a --- /dev/null +++ b/src/feature/bedlevel/hilbert_curve.h @@ -0,0 +1,32 @@ +/******************* + * hilbert_curve.h * + *******************/ + +/**************************************************************************** + * Written By Marcio Teixeira 2021 - SynDaver Labs, Inc. * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation, either version 3 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * To view a copy of the GNU General Public License, go to the following * + * location: . * + ****************************************************************************/ + +#pragma once + +class hilbert_curve { + public: + typedef bool (*callback_ptr)(uint8_t x, uint8_t y, void *data); + static bool search(callback_ptr func, void *data); + static bool search_from(uint8_t x, uint8_t y, callback_ptr func, void *data); + static bool search_from_closest(const xy_pos_t &pos, callback_ptr func, void *data); + private: + static bool hilbert(int8_t x, int8_t y, int8_t xi, int8_t xj, int8_t yi, int8_t yj, uint8_t n, callback_ptr func, void *data); +}; diff --git a/src/feature/bedlevel/mbl/mesh_bed_leveling.cpp b/src/feature/bedlevel/mbl/mesh_bed_leveling.cpp new file mode 100644 index 0000000..193cbbf --- /dev/null +++ b/src/feature/bedlevel/mbl/mesh_bed_leveling.cpp @@ -0,0 +1,131 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../../../inc/MarlinConfig.h" + +#if ENABLED(MESH_BED_LEVELING) + + #include "../bedlevel.h" + + #include "../../../module/motion.h" + + #if ENABLED(EXTENSIBLE_UI) + #include "../../../lcd/extui/ui_api.h" + #endif + + mesh_bed_leveling bedlevel; + + float mesh_bed_leveling::z_offset, + mesh_bed_leveling::z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y], + mesh_bed_leveling::index_to_xpos[GRID_MAX_POINTS_X], + mesh_bed_leveling::index_to_ypos[GRID_MAX_POINTS_Y]; + + mesh_bed_leveling::mesh_bed_leveling() { + LOOP_L_N(i, GRID_MAX_POINTS_X) + index_to_xpos[i] = MESH_MIN_X + i * (MESH_X_DIST); + LOOP_L_N(i, GRID_MAX_POINTS_Y) + index_to_ypos[i] = MESH_MIN_Y + i * (MESH_Y_DIST); + reset(); + } + + void mesh_bed_leveling::reset() { + z_offset = 0; + ZERO(z_values); + #if ENABLED(EXTENSIBLE_UI) + GRID_LOOP(x, y) ExtUI::onMeshUpdate(x, y, 0); + #endif + } + + #if IS_CARTESIAN && DISABLED(SEGMENT_LEVELED_MOVES) + + /** + * Prepare a mesh-leveled linear move in a Cartesian setup, + * splitting the move where it crosses mesh borders. + */ + void mesh_bed_leveling::line_to_destination(const_feedRate_t scaled_fr_mm_s, uint8_t x_splits, uint8_t y_splits) { + // Get current and destination cells for this line + xy_int8_t scel = cell_indexes(current_position), ecel = cell_indexes(destination); + NOMORE(scel.x, GRID_MAX_CELLS_X - 1); + NOMORE(scel.y, GRID_MAX_CELLS_Y - 1); + NOMORE(ecel.x, GRID_MAX_CELLS_X - 1); + NOMORE(ecel.y, GRID_MAX_CELLS_Y - 1); + + // Start and end in the same cell? No split needed. + if (scel == ecel) { + current_position = destination; + line_to_current_position(scaled_fr_mm_s); + return; + } + + #define MBL_SEGMENT_END(A) (current_position.A + (destination.A - current_position.A) * normalized_dist) + + float normalized_dist; + xyze_pos_t dest; + const int8_t gcx = _MAX(scel.x, ecel.x), gcy = _MAX(scel.y, ecel.y); + + // Crosses on the X and not already split on this X? + // The x_splits flags are insurance against rounding errors. + if (ecel.x != scel.x && TEST(x_splits, gcx)) { + // Split on the X grid line + CBI(x_splits, gcx); + dest = destination; + destination.x = index_to_xpos[gcx]; + normalized_dist = (destination.x - current_position.x) / (dest.x - current_position.x); + destination.y = MBL_SEGMENT_END(y); + } + // Crosses on the Y and not already split on this Y? + else if (ecel.y != scel.y && TEST(y_splits, gcy)) { + // Split on the Y grid line + CBI(y_splits, gcy); + dest = destination; + destination.y = index_to_ypos[gcy]; + normalized_dist = (destination.y - current_position.y) / (dest.y - current_position.y); + destination.x = MBL_SEGMENT_END(x); + } + else { + // Must already have been split on these border(s) + // This should be a rare case. + current_position = destination; + line_to_current_position(scaled_fr_mm_s); + return; + } + + destination.z = MBL_SEGMENT_END(z); + destination.e = MBL_SEGMENT_END(e); + + // Do the split and look for more borders + line_to_destination(scaled_fr_mm_s, x_splits, y_splits); + + // Restore destination from stack + destination = dest; + line_to_destination(scaled_fr_mm_s, x_splits, y_splits); + } + + #endif // IS_CARTESIAN && !SEGMENT_LEVELED_MOVES + + void mesh_bed_leveling::report_mesh() { + SERIAL_ECHOPAIR_F(STRINGIFY(GRID_MAX_POINTS_X) "x" STRINGIFY(GRID_MAX_POINTS_Y) " mesh. Z offset: ", z_offset, 5); + SERIAL_ECHOLNPGM("\nMeasured points:"); + print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 5, z_values[0]); + } + +#endif // MESH_BED_LEVELING diff --git a/src/feature/bedlevel/mbl/mesh_bed_leveling.h b/src/feature/bedlevel/mbl/mesh_bed_leveling.h new file mode 100644 index 0000000..1a8e693 --- /dev/null +++ b/src/feature/bedlevel/mbl/mesh_bed_leveling.h @@ -0,0 +1,125 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../../../inc/MarlinConfig.h" + +enum MeshLevelingState : char { + MeshReport, // G29 S0 + MeshStart, // G29 S1 + MeshNext, // G29 S2 + MeshSet, // G29 S3 + MeshSetZOffset, // G29 S4 + MeshReset // G29 S5 +}; + +#define MESH_X_DIST (float(MESH_MAX_X - (MESH_MIN_X)) / (GRID_MAX_CELLS_X)) +#define MESH_Y_DIST (float(MESH_MAX_Y - (MESH_MIN_Y)) / (GRID_MAX_CELLS_Y)) + +class mesh_bed_leveling { +public: + static float z_offset, + z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y], + index_to_xpos[GRID_MAX_POINTS_X], + index_to_ypos[GRID_MAX_POINTS_Y]; + + mesh_bed_leveling(); + + static void report_mesh(); + + static void reset(); + + FORCE_INLINE static bool has_mesh() { + GRID_LOOP(x, y) if (z_values[x][y]) return true; + return false; + } + + static bool mesh_is_valid() { return has_mesh(); } + + static void set_z(const int8_t px, const int8_t py, const_float_t z) { z_values[px][py] = z; } + + static void zigzag(const int8_t index, int8_t &px, int8_t &py) { + px = index % (GRID_MAX_POINTS_X); + py = index / (GRID_MAX_POINTS_X); + if (py & 1) px = (GRID_MAX_POINTS_X) - 1 - px; // Zig zag + } + + static void set_zigzag_z(const int8_t index, const_float_t z) { + int8_t px, py; + zigzag(index, px, py); + set_z(px, py, z); + } + + static float get_mesh_x(const uint8_t i) { return index_to_xpos[i]; } + static float get_mesh_y(const uint8_t i) { return index_to_ypos[i]; } + + static int8_t cell_index_x(const_float_t x) { + int8_t cx = (x - (MESH_MIN_X)) * RECIPROCAL(MESH_X_DIST); + return constrain(cx, 0, GRID_MAX_CELLS_X - 1); + } + static int8_t cell_index_y(const_float_t y) { + int8_t cy = (y - (MESH_MIN_Y)) * RECIPROCAL(MESH_Y_DIST); + return constrain(cy, 0, GRID_MAX_CELLS_Y - 1); + } + static xy_int8_t cell_indexes(const_float_t x, const_float_t y) { + return { cell_index_x(x), cell_index_y(y) }; + } + static xy_int8_t cell_indexes(const xy_pos_t &xy) { return cell_indexes(xy.x, xy.y); } + + static int8_t probe_index_x(const_float_t x) { + int8_t px = (x - (MESH_MIN_X) + 0.5f * (MESH_X_DIST)) * RECIPROCAL(MESH_X_DIST); + return WITHIN(px, 0, (GRID_MAX_POINTS_X) - 1) ? px : -1; + } + static int8_t probe_index_y(const_float_t y) { + int8_t py = (y - (MESH_MIN_Y) + 0.5f * (MESH_Y_DIST)) * RECIPROCAL(MESH_Y_DIST); + return WITHIN(py, 0, (GRID_MAX_POINTS_Y) - 1) ? py : -1; + } + static xy_int8_t probe_indexes(const_float_t x, const_float_t y) { + return { probe_index_x(x), probe_index_y(y) }; + } + static xy_int8_t probe_indexes(const xy_pos_t &xy) { return probe_indexes(xy.x, xy.y); } + + static float calc_z0(const_float_t a0, const_float_t a1, const_float_t z1, const_float_t a2, const_float_t z2) { + const float delta_z = (z2 - z1) / (a2 - a1), + delta_a = a0 - a1; + return z1 + delta_a * delta_z; + } + + static float get_z_offset() { return z_offset; } + + static float get_z_correction(const xy_pos_t &pos) { + const xy_int8_t ind = cell_indexes(pos); + const float x1 = index_to_xpos[ind.x], x2 = index_to_xpos[ind.x+1], + y1 = index_to_xpos[ind.y], y2 = index_to_xpos[ind.y+1], + z1 = calc_z0(pos.x, x1, z_values[ind.x][ind.y ], x2, z_values[ind.x+1][ind.y ]), + z2 = calc_z0(pos.x, x1, z_values[ind.x][ind.y+1], x2, z_values[ind.x+1][ind.y+1]), + zf = calc_z0(pos.y, y1, z1, y2, z2); + + return zf; + } + + #if IS_CARTESIAN && DISABLED(SEGMENT_LEVELED_MOVES) + static void line_to_destination(const_feedRate_t scaled_fr_mm_s, uint8_t x_splits=0xFF, uint8_t y_splits=0xFF); + #endif +}; + +extern mesh_bed_leveling bedlevel; diff --git a/src/feature/bedlevel/ubl/ubl.cpp b/src/feature/bedlevel/ubl/ubl.cpp new file mode 100644 index 0000000..2aa50be --- /dev/null +++ b/src/feature/bedlevel/ubl/ubl.cpp @@ -0,0 +1,300 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../../../inc/MarlinConfig.h" + +#if ENABLED(AUTO_BED_LEVELING_UBL) + +#include "../bedlevel.h" + +unified_bed_leveling bedlevel; + +#include "../../../MarlinCore.h" +#include "../../../gcode/gcode.h" + +#include "../../../module/settings.h" +#include "../../../module/planner.h" +#include "../../../module/motion.h" +#include "../../../module/probe.h" +#include "../../../module/temperature.h" + +#if ENABLED(EXTENSIBLE_UI) + #include "../../../lcd/extui/ui_api.h" +#endif + +#include "math.h" + +void unified_bed_leveling::echo_name() { SERIAL_ECHOPGM("Unified Bed Leveling"); } + +void unified_bed_leveling::report_current_mesh() { + if (!leveling_is_valid()) return; + SERIAL_ECHO_MSG(" G29 I999"); + GRID_LOOP(x, y) + if (!isnan(z_values[x][y])) { + SERIAL_ECHO_START(); + SERIAL_ECHOPGM(" M421 I", x, " J", y); + SERIAL_ECHOLNPAIR_F_P(SP_Z_STR, z_values[x][y], 4); + serial_delay(75); // Prevent Printrun from exploding + } +} + +void unified_bed_leveling::report_state() { + echo_name(); + SERIAL_ECHO_TERNARY(planner.leveling_active, " System v" UBL_VERSION " ", "", "in", "active\n"); + serial_delay(50); +} + +int8_t unified_bed_leveling::storage_slot; + +float unified_bed_leveling::z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y]; + +#define _GRIDPOS(A,N) (MESH_MIN_##A + N * (MESH_##A##_DIST)) + +const float +unified_bed_leveling::_mesh_index_to_xpos[GRID_MAX_POINTS_X] PROGMEM = ARRAY_N(GRID_MAX_POINTS_X, + _GRIDPOS(X, 0), _GRIDPOS(X, 1), _GRIDPOS(X, 2), _GRIDPOS(X, 3), + _GRIDPOS(X, 4), _GRIDPOS(X, 5), _GRIDPOS(X, 6), _GRIDPOS(X, 7), + _GRIDPOS(X, 8), _GRIDPOS(X, 9), _GRIDPOS(X, 10), _GRIDPOS(X, 11), + _GRIDPOS(X, 12), _GRIDPOS(X, 13), _GRIDPOS(X, 14), _GRIDPOS(X, 15) +), +unified_bed_leveling::_mesh_index_to_ypos[GRID_MAX_POINTS_Y] PROGMEM = ARRAY_N(GRID_MAX_POINTS_Y, + _GRIDPOS(Y, 0), _GRIDPOS(Y, 1), _GRIDPOS(Y, 2), _GRIDPOS(Y, 3), + _GRIDPOS(Y, 4), _GRIDPOS(Y, 5), _GRIDPOS(Y, 6), _GRIDPOS(Y, 7), + _GRIDPOS(Y, 8), _GRIDPOS(Y, 9), _GRIDPOS(Y, 10), _GRIDPOS(Y, 11), + _GRIDPOS(Y, 12), _GRIDPOS(Y, 13), _GRIDPOS(Y, 14), _GRIDPOS(Y, 15) +); + +volatile int16_t unified_bed_leveling::encoder_diff; + +unified_bed_leveling::unified_bed_leveling() { reset(); } + +void unified_bed_leveling::reset() { + const bool was_enabled = planner.leveling_active; + set_bed_leveling_enabled(false); + storage_slot = -1; + ZERO(z_values); + #if ENABLED(EXTENSIBLE_UI) + GRID_LOOP(x, y) ExtUI::onMeshUpdate(x, y, 0); + #endif + if (was_enabled) report_current_position(); +} + +void unified_bed_leveling::invalidate() { + set_bed_leveling_enabled(false); + set_all_mesh_points_to_value(NAN); +} + +void unified_bed_leveling::set_all_mesh_points_to_value(const_float_t value) { + GRID_LOOP(x, y) { + z_values[x][y] = value; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, value)); + } +} + +#if ENABLED(OPTIMIZED_MESH_STORAGE) + + constexpr float mesh_store_scaling = 1000; + constexpr int16_t Z_STEPS_NAN = INT16_MAX; + + void unified_bed_leveling::set_store_from_mesh(const bed_mesh_t &in_values, mesh_store_t &stored_values) { + auto z_to_store = [](const_float_t z) { + if (isnan(z)) return Z_STEPS_NAN; + const int32_t z_scaled = TRUNC(z * mesh_store_scaling); + if (z_scaled == Z_STEPS_NAN || !WITHIN(z_scaled, INT16_MIN, INT16_MAX)) + return Z_STEPS_NAN; // If Z is out of range, return our custom 'NaN' + return int16_t(z_scaled); + }; + GRID_LOOP(x, y) stored_values[x][y] = z_to_store(in_values[x][y]); + } + + void unified_bed_leveling::set_mesh_from_store(const mesh_store_t &stored_values, bed_mesh_t &out_values) { + auto store_to_z = [](const int16_t z_scaled) { + return z_scaled == Z_STEPS_NAN ? NAN : z_scaled / mesh_store_scaling; + }; + GRID_LOOP(x, y) out_values[x][y] = store_to_z(stored_values[x][y]); + } + +#endif // OPTIMIZED_MESH_STORAGE + +static void serial_echo_xy(const uint8_t sp, const int16_t x, const int16_t y) { + SERIAL_ECHO_SP(sp); + SERIAL_CHAR('('); + if (x < 100) { SERIAL_CHAR(' '); if (x < 10) SERIAL_CHAR(' '); } + SERIAL_ECHO(x); + SERIAL_CHAR(','); + if (y < 100) { SERIAL_CHAR(' '); if (y < 10) SERIAL_CHAR(' '); } + SERIAL_ECHO(y); + SERIAL_CHAR(')'); + serial_delay(5); +} + +static void serial_echo_column_labels(const uint8_t sp) { + SERIAL_ECHO_SP(7); + LOOP_L_N(i, GRID_MAX_POINTS_X) { + if (i < 10) SERIAL_CHAR(' '); + SERIAL_ECHO(i); + SERIAL_ECHO_SP(sp); + } + serial_delay(10); +} + +/** + * Produce one of these mesh maps: + * 0: Human-readable + * 1: CSV format for spreadsheet import + * 2: TODO: Display on Graphical LCD + * 4: Compact Human-Readable + */ +void unified_bed_leveling::display_map(const uint8_t map_type) { + const bool was = gcode.set_autoreport_paused(true); + + constexpr uint8_t eachsp = 1 + 6 + 1, // [-3.567] + twixt = eachsp * (GRID_MAX_POINTS_X) - 9 * 2; // Leading 4sp, Coordinates 9sp each + + const bool human = !(map_type & 0x3), csv = map_type == 1, lcd = map_type == 2, comp = map_type & 0x4; + + SERIAL_ECHOPGM("\nBed Topography Report"); + if (human) { + SERIAL_ECHOLNPGM(":\n"); + serial_echo_xy(4, MESH_MIN_X, MESH_MAX_Y); + serial_echo_xy(twixt, MESH_MAX_X, MESH_MAX_Y); + SERIAL_EOL(); + serial_echo_column_labels(eachsp - 2); + } + else + SERIAL_ECHOPGM(" for ", csv ? F("CSV:\n") : F("LCD:\n")); + + // Add XY probe offset from extruder because probe.probe_at_point() subtracts them when + // moving to the XY position to be measured. This ensures better agreement between + // the current Z position after G28 and the mesh values. + const xy_int8_t curr = closest_indexes(xy_pos_t(current_position) + probe.offset_xy); + + if (!lcd) SERIAL_EOL(); + for (int8_t j = (GRID_MAX_POINTS_Y) - 1; j >= 0; j--) { + + // Row Label (J index) + if (human) { + if (j < 10) SERIAL_CHAR(' '); + SERIAL_ECHO(j); + SERIAL_ECHOPGM(" |"); + } + + // Row Values (I indexes) + LOOP_L_N(i, GRID_MAX_POINTS_X) { + + // Opening Brace or Space + const bool is_current = i == curr.x && j == curr.y; + if (human) SERIAL_CHAR(is_current ? '[' : ' '); + + // Z Value at current I, J + const float f = z_values[i][j]; + if (lcd) { + // TODO: Display on Graphical LCD + } + else if (isnan(f)) + SERIAL_ECHOF(human ? F(" . ") : F("NAN")); + else if (human || csv) { + if (human && f >= 0) SERIAL_CHAR(f > 0 ? '+' : ' '); // Display sign also for positive numbers (' ' for 0) + SERIAL_DECIMAL(f); // Positive: 5 digits, Negative: 6 digits + } + if (csv && i < (GRID_MAX_POINTS_X) - 1) SERIAL_CHAR('\t'); + + // Closing Brace or Space + if (human) SERIAL_CHAR(is_current ? ']' : ' '); + + SERIAL_FLUSHTX(); + idle_no_sleep(); + } + if (!lcd) SERIAL_EOL(); + + // A blank line between rows (unless compact) + if (j && human && !comp) SERIAL_ECHOLNPGM(" |"); + } + + if (human) { + serial_echo_column_labels(eachsp - 2); + SERIAL_EOL(); + serial_echo_xy(4, MESH_MIN_X, MESH_MIN_Y); + serial_echo_xy(twixt, MESH_MAX_X, MESH_MIN_Y); + SERIAL_EOL(); + SERIAL_EOL(); + } + + gcode.set_autoreport_paused(was); +} + +bool unified_bed_leveling::sanity_check() { + uint8_t error_flag = 0; + + if (settings.calc_num_meshes() < 1) { + SERIAL_ECHOLNPGM("?Mesh too big for EEPROM."); + error_flag++; + } + + return !!error_flag; +} + +#if ENABLED(UBL_MESH_WIZARD) + + /** + * M1004: UBL Mesh Wizard - One-click mesh creation with or without a probe + */ + void GcodeSuite::M1004() { + + #define ALIGN_GCODE TERN(Z_STEPPER_AUTO_ALIGN, "G34", "") + #define PROBE_GCODE TERN(HAS_BED_PROBE, "G29P1\nG29P3", "G29P4R") + + #if HAS_HOTEND + if (parser.seenval('H')) { // Handle H# parameter to set Hotend temp + const celsius_t hotend_temp = parser.value_int(); // Marlin never sends itself F or K, always C + thermalManager.setTargetHotend(hotend_temp, 0); + thermalManager.wait_for_hotend(false); + } + #endif + + #if HAS_HEATED_BED + if (parser.seenval('B')) { // Handle B# parameter to set Bed temp + const celsius_t bed_temp = parser.value_int(); // Marlin never sends itself F or K, always C + thermalManager.setTargetBed(bed_temp); + thermalManager.wait_for_bed(false); + } + #endif + + process_subcommands_now(FPSTR(G28_STR)); // Home + process_subcommands_now(F(ALIGN_GCODE "\n" // Align multi z axis if available + PROBE_GCODE "\n" // Build mesh with available hardware + "G29P3\nG29P3")); // Ensure mesh is complete by running smart fill twice + + if (parser.seenval('S')) { + char umw_gcode[32]; + sprintf_P(umw_gcode, PSTR("G29S%i"), parser.value_int()); + queue.inject(umw_gcode); + } + + process_subcommands_now(F("G29A\nG29F10\n" // Set UBL Active & Fade 10 + "M140S0\nM104S0\n" // Turn off heaters + "M500")); // Store settings + } + +#endif // UBL_MESH_WIZARD + +#endif // AUTO_BED_LEVELING_UBL diff --git a/src/feature/bedlevel/ubl/ubl.h b/src/feature/bedlevel/ubl/ubl.h new file mode 100644 index 0000000..a7103d6 --- /dev/null +++ b/src/feature/bedlevel/ubl/ubl.h @@ -0,0 +1,316 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +//#define UBL_DEVEL_DEBUGGING + +#include "../../../module/motion.h" + +#define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) +#include "../../../core/debug_out.h" + +#define UBL_VERSION "1.01" +#define UBL_OK false +#define UBL_ERR true + +enum MeshPointType : char { INVALID, REAL, SET_IN_BITMAP, CLOSEST }; + +// External references + +struct mesh_index_pair; + +#define MESH_X_DIST (float(MESH_MAX_X - (MESH_MIN_X)) / (GRID_MAX_CELLS_X)) +#define MESH_Y_DIST (float(MESH_MAX_Y - (MESH_MIN_Y)) / (GRID_MAX_CELLS_Y)) + +#if ENABLED(OPTIMIZED_MESH_STORAGE) + typedef int16_t mesh_store_t[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y]; +#endif + +typedef struct { + bool C_seen; + int8_t KLS_storage_slot; + uint8_t R_repetition, + V_verbosity, + P_phase, + T_map_type; + float B_shim_thickness, + C_constant; + xy_pos_t XY_pos; + xy_bool_t XY_seen; + #if HAS_BED_PROBE + uint8_t J_grid_size; + #endif +} G29_parameters_t; + +class unified_bed_leveling { +private: + + static G29_parameters_t param; + + #if IS_NEWPANEL + static void move_z_with_encoder(const_float_t multiplier); + static float measure_point_with_encoder(); + static float measure_business_card_thickness(); + static void manually_probe_remaining_mesh(const xy_pos_t&, const_float_t , const_float_t , const bool) __O0; + static void fine_tune_mesh(const xy_pos_t &pos, const bool do_ubl_mesh_map) __O0; + #endif + + static bool G29_parse_parameters() __O0; + static void shift_mesh_height(); + static void probe_entire_mesh(const xy_pos_t &near, const bool do_ubl_mesh_map, const bool stow_probe, const bool do_furthest) __O0; + static void tilt_mesh_based_on_3pts(const_float_t z1, const_float_t z2, const_float_t z3); + static void tilt_mesh_based_on_probed_grid(const bool do_ubl_mesh_map); + static bool smart_fill_one(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir); + static bool smart_fill_one(const xy_uint8_t &pos, const xy_uint8_t &dir) { + return smart_fill_one(pos.x, pos.y, dir.x, dir.y); + } + + #if ENABLED(UBL_DEVEL_DEBUGGING) + static void g29_what_command(); + static void g29_eeprom_dump(); + static void g29_compare_current_mesh_to_stored_mesh(); + #endif + +public: + + static void echo_name(); + static void report_current_mesh(); + static void report_state(); + static void save_ubl_active_state_and_disable(); + static void restore_ubl_active_state_and_leave(); + static void display_map(const uint8_t) __O0; + static mesh_index_pair find_closest_mesh_point_of_type(const MeshPointType, const xy_pos_t&, const bool=false, MeshFlags *done_flags=nullptr) __O0; + static mesh_index_pair find_furthest_invalid_mesh_point() __O0; + static void reset(); + static void invalidate(); + static void set_all_mesh_points_to_value(const_float_t value); + static void adjust_mesh_to_mean(const bool cflag, const_float_t value); + static bool sanity_check(); + static void smart_fill_mesh(); + + static void G29() __O0; // O0 for no optimization + static void smart_fill_wlsf(const_float_t ) __O2; // O2 gives smaller code than Os on A2560 + + static int8_t storage_slot; + + static bed_mesh_t z_values; + #if ENABLED(OPTIMIZED_MESH_STORAGE) + static void set_store_from_mesh(const bed_mesh_t &in_values, mesh_store_t &stored_values); + static void set_mesh_from_store(const mesh_store_t &stored_values, bed_mesh_t &out_values); + #endif + static const float _mesh_index_to_xpos[GRID_MAX_POINTS_X], + _mesh_index_to_ypos[GRID_MAX_POINTS_Y]; + + #if HAS_MARLINUI_MENU + static bool lcd_map_control; + static void steppers_were_disabled(); + #else + static void steppers_were_disabled() {} + #endif + + static volatile int16_t encoder_diff; // Volatile because buttons may change it at interrupt time + + unified_bed_leveling(); + + FORCE_INLINE static void set_z(const int8_t px, const int8_t py, const_float_t z) { z_values[px][py] = z; } + + static int8_t cell_index_x_raw(const_float_t x) { + return FLOOR((x - (MESH_MIN_X)) * RECIPROCAL(MESH_X_DIST)); + } + + static int8_t cell_index_y_raw(const_float_t y) { + return FLOOR((y - (MESH_MIN_Y)) * RECIPROCAL(MESH_Y_DIST)); + } + + static int8_t cell_index_x_valid(const_float_t x) { + return WITHIN(cell_index_x_raw(x), 0, GRID_MAX_CELLS_X - 1); + } + + static int8_t cell_index_y_valid(const_float_t y) { + return WITHIN(cell_index_y_raw(y), 0, GRID_MAX_CELLS_Y - 1); + } + + static int8_t cell_index_x(const_float_t x) { + return constrain(cell_index_x_raw(x), 0, GRID_MAX_CELLS_X - 1); + } + + static int8_t cell_index_y(const_float_t y) { + return constrain(cell_index_y_raw(y), 0, GRID_MAX_CELLS_Y - 1); + } + + static xy_int8_t cell_indexes(const_float_t x, const_float_t y) { + return { cell_index_x(x), cell_index_y(y) }; + } + static xy_int8_t cell_indexes(const xy_pos_t &xy) { return cell_indexes(xy.x, xy.y); } + + static int8_t closest_x_index(const_float_t x) { + const int8_t px = (x - (MESH_MIN_X) + (MESH_X_DIST) * 0.5) * RECIPROCAL(MESH_X_DIST); + return WITHIN(px, 0, (GRID_MAX_POINTS_X) - 1) ? px : -1; + } + static int8_t closest_y_index(const_float_t y) { + const int8_t py = (y - (MESH_MIN_Y) + (MESH_Y_DIST) * 0.5) * RECIPROCAL(MESH_Y_DIST); + return WITHIN(py, 0, (GRID_MAX_POINTS_Y) - 1) ? py : -1; + } + static xy_int8_t closest_indexes(const xy_pos_t &xy) { + return { closest_x_index(xy.x), closest_y_index(xy.y) }; + } + + /** + * z2 --| + * z0 | | + * | | + (z2-z1) + * z1 | | | + * ---+-------------+--------+-- --| + * a1 a0 a2 + * |<---delta_a---------->| + * + * calc_z0 is the basis for all the Mesh Based correction. It is used to + * find the expected Z Height at a position between two known Z-Height locations. + * + * It is fairly expensive with its 4 floating point additions and 2 floating point + * multiplications. + */ + FORCE_INLINE static float calc_z0(const_float_t a0, const_float_t a1, const_float_t z1, const_float_t a2, const_float_t z2) { + return z1 + (z2 - z1) * (a0 - a1) / (a2 - a1); + } + + #ifdef UBL_Z_RAISE_WHEN_OFF_MESH + #define _UBL_OUTER_Z_RAISE UBL_Z_RAISE_WHEN_OFF_MESH + #else + #define _UBL_OUTER_Z_RAISE NAN + #endif + + /** + * z_correction_for_x_on_horizontal_mesh_line is an optimization for + * the case where the printer is making a vertical line that only crosses horizontal mesh lines. + */ + static float z_correction_for_x_on_horizontal_mesh_line(const_float_t rx0, const int x1_i, const int yi) { + if (!WITHIN(x1_i, 0, (GRID_MAX_POINTS_X) - 1) || !WITHIN(yi, 0, (GRID_MAX_POINTS_Y) - 1)) { + + if (DEBUGGING(LEVELING)) { + if (WITHIN(x1_i, 0, (GRID_MAX_POINTS_X) - 1)) DEBUG_ECHOPGM("yi"); else DEBUG_ECHOPGM("x1_i"); + DEBUG_ECHOLNPGM(" out of bounds in z_correction_for_x_on_horizontal_mesh_line(rx0=", rx0, ",x1_i=", x1_i, ",yi=", yi, ")"); + } + + // The requested location is off the mesh. Return UBL_Z_RAISE_WHEN_OFF_MESH or NAN. + return _UBL_OUTER_Z_RAISE; + } + + const float xratio = (rx0 - get_mesh_x(x1_i)) * RECIPROCAL(MESH_X_DIST), + z1 = z_values[x1_i][yi]; + + return z1 + xratio * (z_values[_MIN(x1_i, (GRID_MAX_POINTS_X) - 2) + 1][yi] - z1); // Don't allow x1_i+1 to be past the end of the array + // If it is, it is clamped to the last element of the + // z_values[][] array and no correction is applied. + } + + // + // See comments above for z_correction_for_x_on_horizontal_mesh_line + // + static float z_correction_for_y_on_vertical_mesh_line(const_float_t ry0, const int xi, const int y1_i) { + if (!WITHIN(xi, 0, (GRID_MAX_POINTS_X) - 1) || !WITHIN(y1_i, 0, (GRID_MAX_POINTS_Y) - 1)) { + + if (DEBUGGING(LEVELING)) { + if (WITHIN(xi, 0, (GRID_MAX_POINTS_X) - 1)) DEBUG_ECHOPGM("y1_i"); else DEBUG_ECHOPGM("xi"); + DEBUG_ECHOLNPGM(" out of bounds in z_correction_for_y_on_vertical_mesh_line(ry0=", ry0, ", xi=", xi, ", y1_i=", y1_i, ")"); + } + + // The requested location is off the mesh. Return UBL_Z_RAISE_WHEN_OFF_MESH or NAN. + return _UBL_OUTER_Z_RAISE; + } + + const float yratio = (ry0 - get_mesh_y(y1_i)) * RECIPROCAL(MESH_Y_DIST), + z1 = z_values[xi][y1_i]; + + return z1 + yratio * (z_values[xi][_MIN(y1_i, (GRID_MAX_POINTS_Y) - 2) + 1] - z1); // Don't allow y1_i+1 to be past the end of the array + // If it is, it is clamped to the last element of the + // z_values[][] array and no correction is applied. + } + + /** + * This is the generic Z-Correction. It works anywhere within a Mesh Cell. It first + * does a linear interpolation along both of the bounding X-Mesh-Lines to find the + * Z-Height at both ends. Then it does a linear interpolation of these heights based + * on the Y position within the cell. + */ + static float get_z_correction(const_float_t rx0, const_float_t ry0) { + const int8_t cx = cell_index_x(rx0), cy = cell_index_y(ry0); // return values are clamped + + /** + * Check if the requested location is off the mesh. If so, and + * UBL_Z_RAISE_WHEN_OFF_MESH is specified, that value is returned. + */ + #ifdef UBL_Z_RAISE_WHEN_OFF_MESH + if (!WITHIN(rx0, MESH_MIN_X, MESH_MAX_X) || !WITHIN(ry0, MESH_MIN_Y, MESH_MAX_Y)) + return UBL_Z_RAISE_WHEN_OFF_MESH; + #endif + + const uint8_t mx = _MIN(cx, (GRID_MAX_POINTS_X) - 2) + 1, my = _MIN(cy, (GRID_MAX_POINTS_Y) - 2) + 1, + x0 = get_mesh_x(cx), x1 = get_mesh_x(cx + 1); + const float z1 = calc_z0(rx0, x0, z_values[cx][cy], x1, z_values[mx][cy]), + z2 = calc_z0(rx0, x0, z_values[cx][my], x1, z_values[mx][my]); + float z0 = calc_z0(ry0, get_mesh_y(cy), z1, get_mesh_y(cy + 1), z2); + + if (isnan(z0)) { // If part of the Mesh is undefined, it will show up as NAN + z0 = 0.0; // in z_values[][] and propagate through the calculations. + // If our correction is NAN, we throw it out because part of + // the Mesh is undefined and we don't have the information + // needed to complete the height correction. + + if (DEBUGGING(MESH_ADJUST)) DEBUG_ECHOLNPGM("??? Yikes! NAN in "); + } + + if (DEBUGGING(MESH_ADJUST)) { + DEBUG_ECHOPGM("get_z_correction(", rx0, ", ", ry0); + DEBUG_ECHOLNPAIR_F(") => ", z0, 6); + } + + return z0; + } + static float get_z_correction(const xy_pos_t &pos) { return get_z_correction(pos.x, pos.y); } + + static constexpr float get_z_offset() { return 0.0f; } + + static float get_mesh_x(const uint8_t i) { + return i < (GRID_MAX_POINTS_X) ? pgm_read_float(&_mesh_index_to_xpos[i]) : MESH_MIN_X + i * (MESH_X_DIST); + } + static float get_mesh_y(const uint8_t i) { + return i < (GRID_MAX_POINTS_Y) ? pgm_read_float(&_mesh_index_to_ypos[i]) : MESH_MIN_Y + i * (MESH_Y_DIST); + } + + #if UBL_SEGMENTED + static bool line_to_destination_segmented(const_feedRate_t scaled_fr_mm_s); + #else + static void line_to_destination_cartesian(const_feedRate_t scaled_fr_mm_s, const uint8_t e); + #endif + + static bool mesh_is_valid() { + GRID_LOOP(x, y) if (isnan(z_values[x][y])) return false; + return true; + } + +}; // class unified_bed_leveling + +extern unified_bed_leveling bedlevel; + +// Prevent debugging propagating to other files +#include "../../../core/debug_out.h" diff --git a/src/feature/bedlevel/ubl/ubl_G29.cpp b/src/feature/bedlevel/ubl/ubl_G29.cpp new file mode 100644 index 0000000..6b45e48 --- /dev/null +++ b/src/feature/bedlevel/ubl/ubl_G29.cpp @@ -0,0 +1,1851 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../../../inc/MarlinConfig.h" + +#if ENABLED(AUTO_BED_LEVELING_UBL) + +#include "../bedlevel.h" + +#include "../../../MarlinCore.h" +#include "../../../HAL/shared/eeprom_api.h" +#include "../../../libs/hex_print.h" +#include "../../../module/settings.h" +#include "../../../lcd/marlinui.h" +#include "../../../module/planner.h" +#include "../../../module/motion.h" +#include "../../../module/probe.h" +#include "../../../gcode/gcode.h" +#include "../../../libs/least_squares_fit.h" + +#if HAS_MULTI_HOTEND + #include "../../../module/tool_change.h" +#endif + +#define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) +#include "../../../core/debug_out.h" + +#if ENABLED(EXTENSIBLE_UI) + #include "../../../lcd/extui/ui_api.h" +#endif + +#if ENABLED(UBL_HILBERT_CURVE) + #include "../hilbert_curve.h" +#endif + +#include + +#define UBL_G29_P31 + +#if HAS_MARLINUI_MENU + + bool unified_bed_leveling::lcd_map_control = false; + + void unified_bed_leveling::steppers_were_disabled() { + if (lcd_map_control) { + lcd_map_control = false; + ui.defer_status_screen(false); + } + } + + void ubl_map_screen(); + +#endif + +#define SIZE_OF_LITTLE_RAISE 1 +#define BIG_RAISE_NOT_NEEDED 0 + +/** + * G29: Unified Bed Leveling by Roxy + * + * Parameters understood by this leveling system: + * + * A Activate Activate the Unified Bed Leveling system. + * + * B # Business Use the 'Business Card' mode of the Manual Probe subsystem with P2. + * Note: A non-compressible Spark Gap feeler gauge is recommended over a business card. + * In this mode of G29 P2, a business or index card is used as a shim that the nozzle can + * grab onto as it is lowered. In principle, the nozzle-bed distance is the same when the + * same resistance is felt in the shim. You can omit the numerical value on first invocation + * of G29 P2 B to measure shim thickness. Subsequent use of 'B' will apply the previously- + * measured thickness by default. + * + * C Continue G29 P1 C continues the generation of a partially-constructed Mesh without invalidating + * previous measurements. + * + * C G29 P2 C tells the Manual Probe subsystem to not use the current nozzle + * location in its search for the closest unmeasured Mesh Point. Instead, attempt to + * start at one end of the uprobed points and Continue sequentially. + * + * G29 P3 C specifies the Constant for the fill. Otherwise, uses a "reasonable" value. + * + * C Current G29 Z C uses the Current location (instead of bed center or nearest edge). + * + * D Disable Disable the Unified Bed Leveling system. + * + * E Stow_probe Stow the probe after each sampled point. + * + * F # Fade Fade the amount of Mesh Based Compensation over a specified height. At the + * specified height, no correction is applied and natural printer kenimatics take over. If no + * number is specified for the command, 10mm is assumed to be reasonable. + * + * H # Height With P2, 'H' specifies the Height to raise the nozzle after each manual probe of the bed. + * If omitted, the nozzle will raise by Z_CLEARANCE_BETWEEN_PROBES. + * + * H # Offset With P4, 'H' specifies the Offset above the mesh height to place the nozzle. + * If omitted, Z_CLEARANCE_BETWEEN_PROBES will be used. + * + * I # Invalidate Invalidate the specified number of Mesh Points near the given 'X' 'Y'. If X or Y are omitted, + * the nozzle location is used. If no 'I' value is given, only the point nearest to the location + * is invalidated. Use 'T' to produce a map afterward. This command is useful to invalidate a + * portion of the Mesh so it can be adjusted using other UBL tools. When attempting to invalidate + * an isolated bad mesh point, the 'T' option shows the nozzle position in the Mesh with (#). You + * can move the nozzle around and use this feature to select the center of the area (or cell) to + * invalidate. + * + * J # Grid Perform a Grid Based Leveling of the current Mesh using a grid with n points on a side. + * Not specifying a grid size will invoke the 3-Point leveling function. + * + * L Load Load Mesh from the previously activated location in the EEPROM. + * + * L # Load Load Mesh from the specified location in the EEPROM. Set this location as activated + * for subsequent Load and Store operations. + * + * The P or Phase commands are used for the bulk of the work to setup a Mesh. In general, your Mesh will + * start off being initialized with a G29 P0 or a G29 P1. Further refinement of the Mesh happens with + * each additional Phase that processes it. + * + * P0 Phase 0 Zero Mesh Data and turn off the Mesh Compensation System. This reverts the + * 3D Printer to the same state it was in before the Unified Bed Leveling Compensation + * was turned on. Setting the entire Mesh to Zero is a special case that allows + * a subsequent G or T leveling operation for backward compatibility. + * + * P1 Phase 1 Invalidate entire Mesh and continue with automatic generation of the Mesh data using + * the Z-Probe. Usually the probe can't reach all areas that the nozzle can reach. For delta + * printers only the areas where the probe and nozzle can both reach will be automatically probed. + * + * Unreachable points will be handled in Phase 2 and Phase 3. + * + * Use 'C' to leave the previous mesh intact and automatically probe needed points. This allows you + * to invalidate parts of the Mesh but still use Automatic Probing. + * + * The 'X' and 'Y' parameters prioritize where to try and measure points. If omitted, the current + * probe position is used. + * + * Use 'T' (Topology) to generate a report of mesh generation. + * + * P1 will suspend Mesh generation if the controller button is held down. Note that you may need + * to press and hold the switch for several seconds if moves are underway. + * + * P2 Phase 2 Probe unreachable points. + * + * Use 'H' to set the height between Mesh points. If omitted, Z_CLEARANCE_BETWEEN_PROBES is used. + * Smaller values will be quicker. Move the nozzle down till it barely touches the bed. Make sure the + * nozzle is clean and unobstructed. Use caution and move slowly. This can damage your printer! + * (Uses SIZE_OF_LITTLE_RAISE mm if the nozzle is moving less than BIG_RAISE_NOT_NEEDED mm.) + * + * The 'H' value can be negative if the Mesh dips in a large area. Press and hold the + * controller button to terminate the current Phase 2 command. You can then re-issue "G29 P 2" + * with an 'H' parameter more suitable for the area you're manually probing. Note that the command + * tries to start in a corner of the bed where movement will be predictable. Override the distance + * calculation location with the X and Y parameters. You can print a Mesh Map (G29 T) to see where + * the mesh is invalidated and where the nozzle needs to move to complete the command. Use 'C' to + * indicate that the search should be based on the current position. + * + * The 'B' parameter for this command is described above. It places the manual probe subsystem into + * Business Card mode where the thickness of a business card is measured and then used to accurately + * set the nozzle height in all manual probing for the duration of the command. A Business card can + * be used, but you'll get better results with a flexible Shim that doesn't compress. This makes it + * easier to produce similar amounts of force and get more accurate measurements. Google if you're + * not sure how to use a shim. + * + * The 'T' (Map) parameter helps track Mesh building progress. + * + * NOTE: P2 requires an LCD controller! + * + * P3 Phase 3 Fill the unpopulated regions of the Mesh with a fixed value. There are two different paths to + * go down: + * + * - If a 'C' constant is specified, the closest invalid mesh points to the nozzle will be filled, + * and a repeat count can then also be specified with 'R'. + * + * - Leaving out 'C' invokes Smart Fill, which scans the mesh from the edges inward looking for + * invalid mesh points. Adjacent points are used to determine the bed slope. If the bed is sloped + * upward from the invalid point, it takes the value of the nearest point. If sloped downward, it's + * replaced by a value that puts all three points in a line. This version of G29 P3 is a quick, easy + * and (usually) safe way to populate unprobed mesh regions before continuing to G26 Mesh Validation + * Pattern. Note that this populates the mesh with unverified values. Pay attention and use caution. + * + * P4 Phase 4 Fine tune the Mesh. The Delta Mesh Compensation System assumes the existence of + * an LCD Panel. It is possible to fine tune the mesh without an LCD Panel using + * G42 and M421. See the UBL documentation for further details. + * + * Phase 4 is meant to be used with G26 Mesh Validation to fine tune the mesh by direct editing + * of Mesh Points. Raise and lower points to fine tune the mesh until it gives consistently reliable + * adhesion. + * + * P4 moves to the closest Mesh Point (and/or the given X Y), raises the nozzle above the mesh height + * by the given 'H' offset (or default 0), and waits while the controller is used to adjust the nozzle + * height. On click the displayed height is saved in the mesh. + * + * Start Phase 4 at a specific location with X and Y. Adjust a specific number of Mesh Points with + * the 'R' (Repeat) parameter. (If 'R' is left out, the whole matrix is assumed.) This command can be + * terminated early (e.g., after editing the area of interest) by pressing and holding the encoder button. + * + * The general form is G29 P4 [R points] [X position] [Y position] + * + * The H [offset] parameter is useful if a shim is used to fine-tune the mesh. For a 0.4mm shim the + * command would be G29 P4 H0.4. The nozzle is moved to the shim height, you adjust height to the shim, + * and on click the height minus the shim thickness will be saved in the mesh. + * + * !!Use with caution, as a very poor mesh could cause the nozzle to crash into the bed!! + * + * NOTE: P4 is not available unless you have LCD support enabled! + * + * P5 Phase 5 Find Mean Mesh Height and Standard Deviation. Typically, it is easier to use and + * work with the Mesh if it is Mean Adjusted. You can specify a C parameter to + * Correct the Mesh to a 0.00 Mean Height. Adding a C parameter will automatically + * execute a G29 P6 C . + * + * P6 Phase 6 Shift Mesh height. The entire Mesh's height is adjusted by the height specified + * with the C parameter. Being able to adjust the height of a Mesh is useful tool. It + * can be used to compensate for poorly calibrated Z-Probes and other errors. Ideally, + * you should have the Mesh adjusted for a Mean Height of 0.00 and the Z-Probe measuring + * 0.000 at the Z Home location. + * + * Q Test Load specified Test Pattern to assist in checking correct operation of system. This + * command is not anticipated to be of much value to the typical user. It is intended + * for developers to help them verify correct operation of the Unified Bed Leveling System. + * + * R # Repeat Repeat this command the specified number of times. If no number is specified the + * command will be repeated GRID_MAX_POINTS_X * GRID_MAX_POINTS_Y times. + * + * S Store Store the current Mesh in the Activated area of the EEPROM. It will also store the + * current state of the Unified Bed Leveling system in the EEPROM. + * + * S # Store Store the current Mesh at the specified location in EEPROM. Activate this location + * for subsequent Load and Store operations. Valid storage slot numbers begin at 0 and + * extend to a limit related to the available EEPROM storage. + * + * S -1 Store Print the current Mesh as G-code that can be used to restore the mesh anytime. + * + * T Topology Display the Mesh Map Topology. + * 'T' can be used alone (e.g., G29 T) or in combination with most of the other commands. + * This option works with all Phase commands (e.g., G29 P4 R 5 T X 50 Y100 C -.1 O) + * This parameter can also specify a Map Type. T0 (the default) is user-readable. T1 + * is suitable to paste into a spreadsheet for a 3D graph of the mesh. + * + * U Unlevel Perform a probe of the outer perimeter to assist in physically leveling unlevel beds. + * Only used for G29 P1 T U. This speeds up the probing of the edge of the bed. Useful + * when the entire bed doesn't need to be probed because it will be adjusted. + * + * V # Verbosity Set the verbosity level (0-4) for extra details. (Default 0) + * + * X # X Location for this command + * + * Y # Y Location for this command + * + * With UBL_DEVEL_DEBUGGING: + * + * K # Kompare Kompare current Mesh with stored Mesh #, replacing current Mesh with the result. + * This command literally performs a diff between two Meshes. + * + * Q-1 Dump EEPROM Dump the UBL contents stored in EEPROM as HEX format. Useful for developers to help + * verify correct operation of the UBL. + * + * W What? Display valuable UBL data. + * + * + * Release Notes: + * You MUST do M502, M500 to initialize the storage. Failure to do this will cause all + * kinds of problems. Enabling EEPROM Storage is required. + * + * When you do a G28 and G29 P1 to automatically build your first mesh, you are going to notice that + * UBL probes points increasingly further from the starting location. (The starting location defaults + * to the center of the bed.) In contrast, ABL and MBL follow a zigzag pattern. The spiral pattern is + * especially better for Delta printers, since it populates the center of the mesh first, allowing for + * a quicker test print to verify settings. You don't need to populate the entire mesh to use it. + * After all, you don't want to spend a lot of time generating a mesh only to realize the resolution + * or probe offsets are incorrect. Mesh-generation gathers points starting closest to the nozzle unless + * an (X,Y) coordinate pair is given. + * + * Unified Bed Leveling uses a lot of EEPROM storage to hold its data, and it takes some effort to get + * the mesh just right. To prevent this valuable data from being destroyed as the EEPROM structure + * evolves, UBL stores all mesh data at the end of EEPROM. + * + * UBL is founded on Edward Patel's Mesh Bed Leveling code. A big 'Thanks!' to him and the creators of + * 3-Point and Grid Based leveling. Combining their contributions we now have the functionality and + * features of all three systems combined. + */ + +G29_parameters_t unified_bed_leveling::param; + +void unified_bed_leveling::G29() { + + bool probe_deployed = false; + if (G29_parse_parameters()) return; // Abort on parameter error + + const uint8_t p_val = parser.byteval('P'); + const bool may_move = p_val == 1 || p_val == 2 || p_val == 4 || parser.seen_test('J'); + #if HAS_MULTI_HOTEND + const uint8_t old_tool_index = active_extruder; + #endif + + // Check for commands that require the printer to be homed + if (may_move) { + planner.synchronize(); + // Send 'N' to force homing before G29 (internal only) + if (axes_should_home() || parser.seen_test('N')) gcode.home_all_axes(); + TERN_(HAS_MULTI_HOTEND, if (active_extruder != 0) tool_change(0, true)); + } + + // Invalidate one or more nearby mesh points, possibly all. + if (parser.seen('I')) { + uint8_t count = parser.has_value() ? parser.value_byte() : 1; + bool invalidate_all = count >= GRID_MAX_POINTS; + if (!invalidate_all) { + while (count--) { + if ((count & 0x0F) == 0x0F) idle(); + const mesh_index_pair closest = find_closest_mesh_point_of_type(REAL, param.XY_pos); + // No more REAL mesh points to invalidate? Assume the user meant + // to invalidate the ENTIRE mesh, which can't be done with + // find_closest_mesh_point (which only returns REAL points). + if (closest.pos.x < 0) { invalidate_all = true; break; } + z_values[closest.pos.x][closest.pos.y] = NAN; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(closest.pos, 0.0f)); + } + } + if (invalidate_all) { + invalidate(); + SERIAL_ECHOPGM("Entire Mesh"); + } + else + SERIAL_ECHOPGM("Locations"); + SERIAL_ECHOLNPGM(" invalidated.\n"); + } + + if (parser.seen('Q')) { + const int16_t test_pattern = parser.has_value() ? parser.value_int() : -99; + if (!WITHIN(test_pattern, TERN0(UBL_DEVEL_DEBUGGING, -1), 2)) { + SERIAL_ECHOLNPGM("?Invalid (Q) test pattern. (" TERN(UBL_DEVEL_DEBUGGING, "-1", "0") " to 2)\n"); + return; + } + SERIAL_ECHOLNPGM("Applying test pattern.\n"); + switch (test_pattern) { + + default: + case -1: TERN_(UBL_DEVEL_DEBUGGING, g29_eeprom_dump()); break; + + case 0: + GRID_LOOP(x, y) { // Create a bowl shape similar to a poorly-calibrated Delta + const float p1 = 0.5f * (GRID_MAX_POINTS_X) - x, + p2 = 0.5f * (GRID_MAX_POINTS_Y) - y; + z_values[x][y] += 2.0f * HYPOT(p1, p2); + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y])); + } + break; + + case 1: + LOOP_L_N(x, GRID_MAX_POINTS_X) { // Create a diagonal line several Mesh cells thick that is raised + const uint8_t x2 = x + (x < (GRID_MAX_POINTS_Y) - 1 ? 1 : -1); + z_values[x][x] += 9.999f; + z_values[x][x2] += 9.999f; // We want the altered line several mesh points thick + #if ENABLED(EXTENSIBLE_UI) + ExtUI::onMeshUpdate(x, x, z_values[x][x]); + ExtUI::onMeshUpdate(x, (x2), z_values[x][x2]); + #endif + } + break; + + case 2: + // Allow the user to specify the height because 10mm is a little extreme in some cases. + for (uint8_t x = (GRID_MAX_POINTS_X) / 3; x < 2 * (GRID_MAX_POINTS_X) / 3; x++) // Create a rectangular raised area in + for (uint8_t y = (GRID_MAX_POINTS_Y) / 3; y < 2 * (GRID_MAX_POINTS_Y) / 3; y++) { // the center of the bed + z_values[x][y] += parser.seen_test('C') ? param.C_constant : 9.99f; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y])); + } + break; + } + } + + #if HAS_BED_PROBE + + if (parser.seen_test('J')) { + save_ubl_active_state_and_disable(); + tilt_mesh_based_on_probed_grid(param.J_grid_size == 0); // Zero size does 3-Point + restore_ubl_active_state_and_leave(); + #if ENABLED(UBL_G29_J_RECENTER) + do_blocking_move_to_xy(0.5f * ((MESH_MIN_X) + (MESH_MAX_X)), 0.5f * ((MESH_MIN_Y) + (MESH_MAX_Y))); + #endif + report_current_position(); + probe_deployed = true; + } + + #endif // HAS_BED_PROBE + + if (parser.seen_test('P')) { + if (WITHIN(param.P_phase, 0, 1) && storage_slot == -1) { + storage_slot = 0; + SERIAL_ECHOLNPGM("Default storage slot 0 selected."); + } + + switch (param.P_phase) { + case 0: + // + // Zero Mesh Data + // + reset(); + SERIAL_ECHOLNPGM("Mesh zeroed."); + break; + + #if HAS_BED_PROBE + + case 1: { + // + // Invalidate Entire Mesh and Automatically Probe Mesh in areas that can be reached by the probe + // + if (!parser.seen_test('C')) { + invalidate(); + SERIAL_ECHOLNPGM("Mesh invalidated. Probing mesh."); + } + if (param.V_verbosity > 1) { + SERIAL_ECHOPGM("Probing around (", param.XY_pos.x); + SERIAL_CHAR(','); + SERIAL_DECIMAL(param.XY_pos.y); + SERIAL_ECHOLNPGM(").\n"); + } + probe_entire_mesh(param.XY_pos, parser.seen_test('T'), parser.seen_test('E'), parser.seen_test('U')); + + report_current_position(); + probe_deployed = true; + } break; + + #endif // HAS_BED_PROBE + + case 2: { + #if HAS_MARLINUI_MENU + // + // Manually Probe Mesh in areas that can't be reached by the probe + // + SERIAL_ECHOLNPGM("Manually probing unreachable points."); + do_z_clearance(Z_CLEARANCE_BETWEEN_PROBES); + + if (parser.seen_test('C') && !param.XY_seen) { + + /** + * Use a good default location for the path. + * The flipped > and < operators in these comparisons is intentional. + * It should cause the probed points to follow a nice path on Cartesian printers. + * It may make sense to have Delta printers default to the center of the bed. + * Until that is decided, this can be forced with the X and Y parameters. + */ + param.XY_pos.set( + #if IS_KINEMATIC + X_HOME_POS, Y_HOME_POS + #else + probe.offset_xy.x > 0 ? X_BED_SIZE : 0, + probe.offset_xy.y < 0 ? Y_BED_SIZE : 0 + #endif + ); + } + + if (parser.seen('B')) { + param.B_shim_thickness = parser.has_value() ? parser.value_float() : measure_business_card_thickness(); + if (ABS(param.B_shim_thickness) > 1.5f) { + SERIAL_ECHOLNPGM("?Error in Business Card measurement."); + return; + } + probe_deployed = true; + } + + if (!position_is_reachable(param.XY_pos)) { + SERIAL_ECHOLNPGM("XY outside printable radius."); + return; + } + + const float height = parser.floatval('H', Z_CLEARANCE_BETWEEN_PROBES); + manually_probe_remaining_mesh(param.XY_pos, height, param.B_shim_thickness, parser.seen_test('T')); + + SERIAL_ECHOLNPGM("G29 P2 finished."); + + report_current_position(); + + #else + + SERIAL_ECHOLNPGM("?P2 is only available when an LCD is present."); + return; + + #endif + } break; + + case 3: { + /** + * Populate invalid mesh areas. Proceed with caution. + * Two choices are available: + * - Specify a constant with the 'C' parameter. + * - Allow 'G29 P3' to choose a 'reasonable' constant. + */ + + if (param.C_seen) { + if (param.R_repetition >= GRID_MAX_POINTS) { + set_all_mesh_points_to_value(param.C_constant); + } + else { + while (param.R_repetition--) { // this only populates reachable mesh points near + const mesh_index_pair closest = find_closest_mesh_point_of_type(INVALID, param.XY_pos); + const xy_int8_t &cpos = closest.pos; + if (cpos.x < 0) { + // No more REAL INVALID mesh points to populate, so we ASSUME + // user meant to populate ALL INVALID mesh points to value + GRID_LOOP(x, y) if (isnan(z_values[x][y])) z_values[x][y] = param.C_constant; + break; // No more invalid Mesh Points to populate + } + else { + z_values[cpos.x][cpos.y] = param.C_constant; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(cpos, param.C_constant)); + } + } + } + } + else { + const float cvf = parser.value_float(); + switch ((int)TRUNC(cvf * 10.0f) - 30) { // 3.1 -> 1 + #if ENABLED(UBL_G29_P31) + case 1: { + + // P3.1 use least squares fit to fill missing mesh values + // P3.10 zero weighting for distance, all grid points equal, best fit tilted plane + // P3.11 10X weighting for nearest grid points versus farthest grid points + // P3.12 100X distance weighting + // P3.13 1000X distance weighting, approaches simple average of nearest points + + const float weight_power = (cvf - 3.10f) * 100.0f, // 3.12345 -> 2.345 + weight_factor = weight_power ? POW(10.0f, weight_power) : 0; + smart_fill_wlsf(weight_factor); + } + break; + #endif + case 0: // P3 or P3.0 + default: // and anything P3.x that's not P3.1 + smart_fill_mesh(); // Do a 'Smart' fill using nearby known values + break; + } + } + break; + } + + case 4: // Fine Tune (i.e., Edit) the Mesh + #if HAS_MARLINUI_MENU + fine_tune_mesh(param.XY_pos, parser.seen_test('T')); + #else + SERIAL_ECHOLNPGM("?P4 is only available when an LCD is present."); + return; + #endif + break; + + case 5: adjust_mesh_to_mean(param.C_seen, param.C_constant); break; + + case 6: shift_mesh_height(); break; + } + } + + #if ENABLED(UBL_DEVEL_DEBUGGING) + + // + // Much of the 'What?' command can be eliminated. But until we are fully debugged, it is + // good to have the extra information. Soon... we prune this to just a few items + // + if (parser.seen_test('W')) g29_what_command(); + + // + // When we are fully debugged, this may go away. But there are some valid + // use cases for the users. So we can wait and see what to do with it. + // + + if (parser.seen('K')) // Kompare Current Mesh Data to Specified Stored Mesh + g29_compare_current_mesh_to_stored_mesh(); + + #endif // UBL_DEVEL_DEBUGGING + + + // + // Load a Mesh from the EEPROM + // + + if (parser.seen('L')) { // Load Current Mesh Data + param.KLS_storage_slot = parser.has_value() ? (int8_t)parser.value_int() : storage_slot; + + int16_t a = settings.calc_num_meshes(); + + if (!a) { + SERIAL_ECHOLNPGM("?EEPROM storage not available."); + return; + } + + if (!WITHIN(param.KLS_storage_slot, 0, a - 1)) { + SERIAL_ECHOLNPGM("?Invalid storage slot.\n?Use 0 to ", a - 1); + return; + } + + settings.load_mesh(param.KLS_storage_slot); + storage_slot = param.KLS_storage_slot; + + SERIAL_ECHOLNPGM(STR_DONE); + } + + // + // Store a Mesh in the EEPROM + // + + if (parser.seen('S')) { // Store (or Save) Current Mesh Data + param.KLS_storage_slot = parser.has_value() ? (int8_t)parser.value_int() : storage_slot; + + if (param.KLS_storage_slot == -1) // Special case: 'Export' the mesh to the + return report_current_mesh(); // host so it can be saved in a file. + + int16_t a = settings.calc_num_meshes(); + + if (!a) { + SERIAL_ECHOLNPGM("?EEPROM storage not available."); + goto LEAVE; + } + + if (!WITHIN(param.KLS_storage_slot, 0, a - 1)) { + SERIAL_ECHOLNPGM("?Invalid storage slot.\n?Use 0 to ", a - 1); + goto LEAVE; + } + + settings.store_mesh(param.KLS_storage_slot); + storage_slot = param.KLS_storage_slot; + + SERIAL_ECHOLNPGM(STR_DONE); + } + + if (parser.seen_test('T')) + display_map(param.T_map_type); + + LEAVE: + + #if HAS_MARLINUI_MENU + ui.reset_alert_level(); + ui.quick_feedback(); + ui.reset_status(); + ui.release(); + #endif + + #ifdef Z_PROBE_END_SCRIPT + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Z Probe End Script: ", Z_PROBE_END_SCRIPT); + if (probe_deployed) { + planner.synchronize(); + gcode.process_subcommands_now(F(Z_PROBE_END_SCRIPT)); + } + #else + UNUSED(probe_deployed); + #endif + + TERN_(HAS_MULTI_HOTEND, if (old_tool_index != 0) tool_change(old_tool_index)); + return; +} + +/** + * M420 C + * G29 P5 C : Adjust Mesh To Mean (and subtract the given offset). + * Find the mean average and shift the mesh to center on that value. + */ +void unified_bed_leveling::adjust_mesh_to_mean(const bool cflag, const_float_t offset) { + float sum = 0; + uint8_t n = 0; + GRID_LOOP(x, y) + if (!isnan(z_values[x][y])) { + sum += z_values[x][y]; + n++; + } + + const float mean = sum / n; + + // + // Sum the squares of difference from mean + // + float sum_of_diff_squared = 0; + GRID_LOOP(x, y) + if (!isnan(z_values[x][y])) + sum_of_diff_squared += sq(z_values[x][y] - mean); + + SERIAL_ECHOLNPGM("# of samples: ", n); + SERIAL_ECHOLNPAIR_F("Mean Mesh Height: ", mean, 6); + + const float sigma = SQRT(sum_of_diff_squared / (n + 1)); + SERIAL_ECHOLNPAIR_F("Standard Deviation: ", sigma, 6); + + if (cflag) + GRID_LOOP(x, y) + if (!isnan(z_values[x][y])) { + z_values[x][y] -= mean + offset; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y])); + } +} + +/** + * G29 P6 C : Shift Mesh Height by a uniform constant. + */ +void unified_bed_leveling::shift_mesh_height() { + GRID_LOOP(x, y) + if (!isnan(z_values[x][y])) { + z_values[x][y] += param.C_constant; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y])); + } +} + +#if HAS_BED_PROBE + /** + * G29 P1 T V : Probe Entire Mesh + * Probe all invalidated locations of the mesh that can be reached by the probe. + * This attempts to fill in locations closest to the nozzle's start location first. + */ + void unified_bed_leveling::probe_entire_mesh(const xy_pos_t &nearby, const bool do_ubl_mesh_map, const bool stow_probe, const bool do_furthest) { + probe.deploy(); // Deploy before ui.capture() to allow for PAUSE_BEFORE_DEPLOY_STOW + + TERN_(HAS_MARLINUI_MENU, ui.capture()); + TERN_(EXTENSIBLE_UI, ExtUI::onLevelingStart()); + TERN_(DWIN_LCD_PROUI, DWIN_LevelingStart()); + + save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained + uint8_t count = GRID_MAX_POINTS; + + mesh_index_pair best; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(best.pos, ExtUI::G29_START)); + do { + if (do_ubl_mesh_map) display_map(param.T_map_type); + + const uint8_t point_num = (GRID_MAX_POINTS - count) + 1; + SERIAL_ECHOLNPGM("Probing mesh point ", point_num, "/", GRID_MAX_POINTS, "."); + TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " %i/%i"), GET_TEXT(MSG_PROBING_POINT), point_num, int(GRID_MAX_POINTS))); + + #if HAS_MARLINUI_MENU + if (ui.button_pressed()) { + ui.quick_feedback(false); // Preserve button state for click-and-hold + SERIAL_ECHOLNPGM("\nMesh only partially populated.\n"); + ui.wait_for_release(); + ui.quick_feedback(); + ui.release(); + probe.stow(); // Release UI before stow to allow for PAUSE_BEFORE_DEPLOY_STOW + TERN_(EXTENSIBLE_UI, ExtUI::onLevelingDone()); + return restore_ubl_active_state_and_leave(); + } + #endif + + best = do_furthest + ? find_furthest_invalid_mesh_point() + : find_closest_mesh_point_of_type(INVALID, nearby, true); + + if (best.pos.x >= 0) { // mesh point found and is reachable by probe + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(best.pos, ExtUI::G29_POINT_START)); + const float measured_z = probe.probe_at_point( + best.meshpos(), + stow_probe ? PROBE_PT_STOW : PROBE_PT_RAISE, param.V_verbosity + ); + z_values[best.pos.x][best.pos.y] = measured_z; + #if ENABLED(EXTENSIBLE_UI) + ExtUI::onMeshUpdate(best.pos, ExtUI::G29_POINT_FINISH); + ExtUI::onMeshUpdate(best.pos, measured_z); + #endif + } + SERIAL_FLUSH(); // Prevent host M105 buffer overrun. + + } while (best.pos.x >= 0 && --count); + + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(best.pos, ExtUI::G29_FINISH)); + + // Release UI during stow to allow for PAUSE_BEFORE_DEPLOY_STOW + TERN_(HAS_MARLINUI_MENU, ui.release()); + probe.stow(); + TERN_(HAS_MARLINUI_MENU, ui.capture()); + + probe.move_z_after_probing(); + + restore_ubl_active_state_and_leave(); + + do_blocking_move_to_xy( + constrain(nearby.x - probe.offset_xy.x, MESH_MIN_X, MESH_MAX_X), + constrain(nearby.y - probe.offset_xy.y, MESH_MIN_Y, MESH_MAX_Y) + ); + + TERN_(EXTENSIBLE_UI, ExtUI::onLevelingDone()); + TERN_(DWIN_LCD_PROUI, DWIN_LevelingDone()); + } + +#endif // HAS_BED_PROBE + +void set_message_with_feedback(FSTR_P const fstr) { + #if HAS_MARLINUI_MENU + ui.set_status(fstr); + ui.quick_feedback(); + #else + UNUSED(fstr); + #endif +} + +#if HAS_MARLINUI_MENU + + typedef void (*clickFunc_t)(); + + bool _click_and_hold(const clickFunc_t func=nullptr) { + if (ui.button_pressed()) { + ui.quick_feedback(false); // Preserve button state for click-and-hold + const millis_t nxt = millis() + 1500UL; + while (ui.button_pressed()) { // Loop while the encoder is pressed. Uses hardware flag! + idle(); // idle, of course + if (ELAPSED(millis(), nxt)) { // After 1.5 seconds + ui.quick_feedback(); + if (func) (*func)(); + ui.wait_for_release(); + return true; + } + } + } + serial_delay(15); + return false; + } + + void unified_bed_leveling::move_z_with_encoder(const_float_t multiplier) { + ui.wait_for_release(); + while (!ui.button_pressed()) { + idle(); + gcode.reset_stepper_timeout(); // Keep steppers powered + if (encoder_diff) { + do_blocking_move_to_z(current_position.z + float(encoder_diff) * multiplier); + encoder_diff = 0; + } + } + } + + float unified_bed_leveling::measure_point_with_encoder() { + KEEPALIVE_STATE(PAUSED_FOR_USER); + const float z_step = 0.01f; + move_z_with_encoder(z_step); + return current_position.z; + } + + static void echo_and_take_a_measurement() { SERIAL_ECHOLNPGM(" and take a measurement."); } + + float unified_bed_leveling::measure_business_card_thickness() { + ui.capture(); + save_ubl_active_state_and_disable(); // Disable bed level correction for probing + + do_blocking_move_to(0.5f * (MESH_MAX_X - (MESH_MIN_X)), 0.5f * (MESH_MAX_Y - (MESH_MIN_Y)), MANUAL_PROBE_START_Z); + //, _MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS]) * 0.5f); + planner.synchronize(); + + SERIAL_ECHOPGM("Place shim under nozzle"); + LCD_MESSAGE(MSG_UBL_BC_INSERT); + ui.return_to_status(); + echo_and_take_a_measurement(); + + const float z1 = measure_point_with_encoder(); + do_blocking_move_to_z(current_position.z + SIZE_OF_LITTLE_RAISE); + planner.synchronize(); + + SERIAL_ECHOPGM("Remove shim"); + LCD_MESSAGE(MSG_UBL_BC_REMOVE); + echo_and_take_a_measurement(); + + const float z2 = measure_point_with_encoder(); + do_blocking_move_to_z(current_position.z + Z_CLEARANCE_BETWEEN_PROBES); + + const float thickness = ABS(z1 - z2); + + if (param.V_verbosity > 1) { + SERIAL_ECHOPAIR_F("Business Card is ", thickness, 4); + SERIAL_ECHOLNPGM("mm thick."); + } + + restore_ubl_active_state_and_leave(); + + return thickness; + } + + /** + * G29 P2 : Manually Probe Remaining Mesh Points. + * Move to INVALID points and + * NOTE: Blocks the G-code queue and captures Marlin UI during use. + */ + void unified_bed_leveling::manually_probe_remaining_mesh(const xy_pos_t &pos, const_float_t z_clearance, const_float_t thick, const bool do_ubl_mesh_map) { + ui.capture(); + TERN_(EXTENSIBLE_UI, ExtUI::onLevelingStart()); + + save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained + do_blocking_move_to_xy_z(current_position, z_clearance); + + ui.return_to_status(); + + mesh_index_pair location; + const xy_int8_t &lpos = location.pos; + do { + location = find_closest_mesh_point_of_type(INVALID, pos); + // It doesn't matter if the probe can't reach the NAN location. This is a manual probe. + if (!location.valid()) continue; + + const xyz_pos_t ppos = { get_mesh_x(lpos.x), get_mesh_y(lpos.y), z_clearance }; + + if (!position_is_reachable(ppos)) break; // SHOULD NOT OCCUR (find_closest_mesh_point only returns reachable points) + + LCD_MESSAGE(MSG_UBL_MOVING_TO_NEXT); + + do_blocking_move_to(ppos); + do_z_clearance(z_clearance); + + KEEPALIVE_STATE(PAUSED_FOR_USER); + ui.capture(); + + if (do_ubl_mesh_map) display_map(param.T_map_type); // Show user where we're probing + + if (parser.seen_test('B')) { + SERIAL_ECHOPGM("Place Shim & Measure"); + LCD_MESSAGE(MSG_UBL_BC_INSERT); + } + else { + SERIAL_ECHOPGM("Measure"); + LCD_MESSAGE(MSG_UBL_BC_INSERT2); + } + + const float z_step = 0.01f; // 0.01mm per encoder tick, occasionally step + move_z_with_encoder(z_step); + + if (_click_and_hold([]{ + SERIAL_ECHOLNPGM("\nMesh only partially populated."); + do_z_clearance(Z_CLEARANCE_DEPLOY_PROBE); + })) return restore_ubl_active_state_and_leave(); + + // Store the Z position minus the shim height + z_values[lpos.x][lpos.y] = current_position.z - thick; + + // Tell the external UI to update + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location, z_values[lpos.x][lpos.y])); + + if (param.V_verbosity > 2) + SERIAL_ECHOLNPAIR_F("Mesh Point Measured at: ", z_values[lpos.x][lpos.y], 6); + SERIAL_FLUSH(); // Prevent host M105 buffer overrun. + } while (location.valid()); + + if (do_ubl_mesh_map) display_map(param.T_map_type); // show user where we're probing + + restore_ubl_active_state_and_leave(); + do_blocking_move_to_xy_z(pos, Z_CLEARANCE_DEPLOY_PROBE); + + TERN_(EXTENSIBLE_UI, ExtUI::onLevelingDone()); + } + + /** + * G29 P4 : Mesh Fine-Tuning. Go to point(s) and adjust values with the LCD. + * NOTE: Blocks the G-code queue and captures Marlin UI during use. + */ + void unified_bed_leveling::fine_tune_mesh(const xy_pos_t &pos, const bool do_ubl_mesh_map) { + if (!parser.seen_test('R')) // fine_tune_mesh() is special. If no repetition count flag is specified + param.R_repetition = 1; // do exactly one mesh location. Otherwise use what the parser decided. + + #if ENABLED(UBL_MESH_EDIT_MOVES_Z) + const float h_offset = parser.seenval('H') ? parser.value_linear_units() : MANUAL_PROBE_START_Z; + if (!WITHIN(h_offset, 0, 10)) { + SERIAL_ECHOLNPGM("Offset out of bounds. (0 to 10mm)\n"); + return; + } + #endif + + mesh_index_pair location; + + if (!position_is_reachable(pos)) { + SERIAL_ECHOLNPGM("(X,Y) outside printable radius."); + return; + } + + save_ubl_active_state_and_disable(); + + LCD_MESSAGE(MSG_UBL_FINE_TUNE_MESH); + ui.capture(); // Take over control of the LCD encoder + + do_blocking_move_to_xy_z(pos, Z_CLEARANCE_BETWEEN_PROBES); // Move to the given XY with probe clearance + + MeshFlags done_flags{0}; + const xy_int8_t &lpos = location.pos; + + #if IS_TFTGLCD_PANEL + ui.ubl_mesh_edit_start(0); // Change current screen before calling ui.ubl_plot + safe_delay(50); + #endif + + do { + location = find_closest_mesh_point_of_type(SET_IN_BITMAP, pos, false, &done_flags); + + if (lpos.x < 0) break; // Stop when there are no more reachable points + + done_flags.mark(lpos); // Mark this location as 'adjusted' so a new + // location is used on the next loop + const xyz_pos_t raw = { get_mesh_x(lpos.x), get_mesh_y(lpos.y), Z_CLEARANCE_BETWEEN_PROBES }; + + if (!position_is_reachable(raw)) break; // SHOULD NOT OCCUR (find_closest_mesh_point_of_type only returns reachable) + + do_blocking_move_to(raw); // Move the nozzle to the edit point with probe clearance + + TERN_(UBL_MESH_EDIT_MOVES_Z, do_blocking_move_to_z(h_offset)); // Move Z to the given 'H' offset before editing + + KEEPALIVE_STATE(PAUSED_FOR_USER); + + if (do_ubl_mesh_map) display_map(param.T_map_type); // Display the current point + + #if IS_TFTGLCD_PANEL + ui.ubl_plot(lpos.x, lpos.y); // update plot screen + #endif + + ui.refresh(); + + float new_z = z_values[lpos.x][lpos.y]; + if (isnan(new_z)) new_z = 0; // Invalid points begin at 0 + new_z = FLOOR(new_z * 1000) * 0.001f; // Chop off digits after the 1000ths place + + ui.ubl_mesh_edit_start(new_z); + + SET_SOFT_ENDSTOP_LOOSE(true); + + do { + idle_no_sleep(); + new_z = ui.ubl_mesh_value(); + TERN_(UBL_MESH_EDIT_MOVES_Z, do_blocking_move_to_z(h_offset + new_z)); // Move the nozzle as the point is edited + SERIAL_FLUSH(); // Prevent host M105 buffer overrun. + } while (!ui.button_pressed()); + + SET_SOFT_ENDSTOP_LOOSE(false); + + if (!lcd_map_control) ui.return_to_status(); // Just editing a single point? Return to status + + // Button held down? Abort editing + if (_click_and_hold([]{ + ui.return_to_status(); + do_z_clearance(Z_CLEARANCE_BETWEEN_PROBES); + set_message_with_feedback(GET_TEXT_F(MSG_EDITING_STOPPED)); + })) break; + + // TODO: Disable leveling here so the Z value becomes the 'native' Z value. + + z_values[lpos.x][lpos.y] = new_z; // Save the updated Z value + + // TODO: Re-enable leveling here so Z is correctly based on the updated mesh. + + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location, new_z)); + + serial_delay(20); // No switch noise + ui.refresh(); + + } while (lpos.x >= 0 && --param.R_repetition > 0); + + if (do_ubl_mesh_map) display_map(param.T_map_type); + restore_ubl_active_state_and_leave(); + + do_blocking_move_to_xy_z(pos, Z_CLEARANCE_BETWEEN_PROBES); + + LCD_MESSAGE(MSG_UBL_DONE_EDITING_MESH); + SERIAL_ECHOLNPGM("Done Editing Mesh"); + + if (lcd_map_control) + ui.goto_screen(ubl_map_screen); + else + ui.return_to_status(); + } + +#endif // HAS_MARLINUI_MENU + +/** + * Parse and validate most G29 parameters, store for use by G29 functions. + */ +bool unified_bed_leveling::G29_parse_parameters() { + bool err_flag = false; + + set_message_with_feedback(GET_TEXT_F(MSG_UBL_DOING_G29)); + + param.C_constant = 0; + param.R_repetition = 0; + + if (parser.seen('R')) { + param.R_repetition = parser.has_value() ? parser.value_byte() : GRID_MAX_POINTS; + NOMORE(param.R_repetition, GRID_MAX_POINTS); + if (param.R_repetition < 1) { + SERIAL_ECHOLNPGM("?(R)epetition count invalid (1+).\n"); + return UBL_ERR; + } + } + + param.V_verbosity = parser.byteval('V'); + if (!WITHIN(param.V_verbosity, 0, 4)) { + SERIAL_ECHOLNPGM("?(V)erbose level implausible (0-4).\n"); + err_flag = true; + } + + if (parser.seen('P')) { + const uint8_t pv = parser.value_byte(); + #if !HAS_BED_PROBE + if (pv == 1) { + SERIAL_ECHOLNPGM("G29 P1 requires a probe.\n"); + err_flag = true; + } + else + #endif + { + param.P_phase = pv; + if (!WITHIN(param.P_phase, 0, 6)) { + SERIAL_ECHOLNPGM("?(P)hase value invalid (0-6).\n"); + err_flag = true; + } + } + } + + if (parser.seen('J')) { + #if HAS_BED_PROBE + param.J_grid_size = parser.value_byte(); + if (param.J_grid_size && !WITHIN(param.J_grid_size, 2, 9)) { + SERIAL_ECHOLNPGM("?Invalid grid size (J) specified (2-9).\n"); + err_flag = true; + } + #else + SERIAL_ECHOLNPGM("G29 J action requires a probe.\n"); + err_flag = true; + #endif + } + + param.XY_seen.x = parser.seenval('X'); + float sx = param.XY_seen.x ? parser.value_float() : current_position.x; + param.XY_seen.y = parser.seenval('Y'); + float sy = param.XY_seen.y ? parser.value_float() : current_position.y; + + if (param.XY_seen.x != param.XY_seen.y) { + SERIAL_ECHOLNPGM("Both X & Y locations must be specified.\n"); + err_flag = true; + } + + // If X or Y are not valid, use center of the bed values + // (for UBL_HILBERT_CURVE default to lower-left corner instead) + if (!COORDINATE_OKAY(sx, X_MIN_BED, X_MAX_BED)) sx = TERN(UBL_HILBERT_CURVE, 0, X_CENTER); + if (!COORDINATE_OKAY(sy, Y_MIN_BED, Y_MAX_BED)) sy = TERN(UBL_HILBERT_CURVE, 0, Y_CENTER); + + if (err_flag) return UBL_ERR; + + param.XY_pos.set(sx, sy); + + /** + * Activate or deactivate UBL + * Note: UBL's G29 restores the state set here when done. + * Leveling is being enabled here with old data, possibly + * none. Error handling should disable for safety... + */ + if (parser.seen_test('A')) { + if (parser.seen_test('D')) { + SERIAL_ECHOLNPGM("?Can't activate and deactivate at the same time.\n"); + return UBL_ERR; + } + set_bed_leveling_enabled(true); + report_state(); + } + else if (parser.seen_test('D')) { + set_bed_leveling_enabled(false); + report_state(); + } + + // Set global 'C' flag and its value + if ((param.C_seen = parser.seen('C'))) + param.C_constant = parser.value_float(); + + #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) + if (parser.seenval('F')) { + const float fh = parser.value_float(); + if (!WITHIN(fh, 0, 100)) { + SERIAL_ECHOLNPGM("?(F)ade height for Bed Level Correction not plausible.\n"); + return UBL_ERR; + } + set_z_fade_height(fh); + } + #endif + + param.T_map_type = parser.byteval('T'); + if (!WITHIN(param.T_map_type, 0, 2)) { + SERIAL_ECHOLNPGM("Invalid map type.\n"); + return UBL_ERR; + } + return UBL_OK; +} + +static uint8_t ubl_state_at_invocation = 0; + +#if ENABLED(UBL_DEVEL_DEBUGGING) + static uint8_t ubl_state_recursion_chk = 0; +#endif + +void unified_bed_leveling::save_ubl_active_state_and_disable() { + #if ENABLED(UBL_DEVEL_DEBUGGING) + ubl_state_recursion_chk++; + if (ubl_state_recursion_chk != 1) { + SERIAL_ECHOLNPGM("save_ubl_active_state_and_disabled() called multiple times in a row."); + set_message_with_feedback(GET_TEXT_F(MSG_UBL_SAVE_ERROR)); + return; + } + #endif + ubl_state_at_invocation = planner.leveling_active; + set_bed_leveling_enabled(false); +} + +void unified_bed_leveling::restore_ubl_active_state_and_leave() { + TERN_(HAS_MARLINUI_MENU, ui.release()); + #if ENABLED(UBL_DEVEL_DEBUGGING) + if (--ubl_state_recursion_chk) { + SERIAL_ECHOLNPGM("restore_ubl_active_state_and_leave() called too many times."); + set_message_with_feedback(GET_TEXT_F(MSG_UBL_RESTORE_ERROR)); + return; + } + #endif + set_bed_leveling_enabled(ubl_state_at_invocation); + TERN_(EXTENSIBLE_UI, ExtUI::onLevelingDone()); +} + +mesh_index_pair unified_bed_leveling::find_furthest_invalid_mesh_point() { + + bool found_a_NAN = false, found_a_real = false; + + mesh_index_pair farthest { -1, -1, -99999.99 }; + + GRID_LOOP(i, j) { + if (!isnan(z_values[i][j])) continue; // Skip valid mesh points + + // Skip unreachable points + if (!probe.can_reach(get_mesh_x(i), get_mesh_y(j))) + continue; + + found_a_NAN = true; + + xy_int8_t nearby { -1, -1 }; + float d1, d2 = 99999.9f; + GRID_LOOP(k, l) { + if (isnan(z_values[k][l])) continue; + + found_a_real = true; + + // Add in a random weighting factor that scrambles the probing of the + // last half of the mesh (when every unprobed mesh point is one index + // from a probed location). + + d1 = HYPOT(i - k, j - l) + (1.0f / ((millis() % 47) + 13)); + + if (d1 < d2) { // Invalid mesh point (i,j) is closer to the defined point (k,l) + d2 = d1; + nearby.set(i, j); + } + } + + // + // At this point d2 should have the near defined mesh point to invalid mesh point (i,j) + // + + if (found_a_real && nearby.x >= 0 && d2 > farthest.distance) { + farthest.pos = nearby; // Found an invalid location farther from the defined mesh point + farthest.distance = d2; + } + } // GRID_LOOP + + if (!found_a_real && found_a_NAN) { // if the mesh is totally unpopulated, start the probing + farthest.pos.set((GRID_MAX_POINTS_X) / 2, (GRID_MAX_POINTS_Y) / 2); + farthest.distance = 1; + } + return farthest; +} + +#if ENABLED(UBL_HILBERT_CURVE) + + typedef struct { + MeshPointType type; + MeshFlags *done_flags; + bool probe_relative; + mesh_index_pair closest; + } find_closest_t; + + static bool test_func(uint8_t i, uint8_t j, void *data) { + find_closest_t *d = (find_closest_t*)data; + if ( d->type == CLOSEST || d->type == (isnan(bedlevel.z_values[i][j]) ? INVALID : REAL) + || (d->type == SET_IN_BITMAP && !d->done_flags->marked(i, j)) + ) { + // Found a Mesh Point of the specified type! + const xy_pos_t mpos = { bedlevel.get_mesh_x(i), bedlevel.get_mesh_y(j) }; + + // If using the probe as the reference there are some unreachable locations. + // Also for round beds, there are grid points outside the bed the nozzle can't reach. + // Prune them from the list and ignore them till the next Phase (manual nozzle probing). + + if (!(d->probe_relative ? probe.can_reach(mpos) : position_is_reachable(mpos))) + return false; + d->closest.pos.set(i, j); + return true; + } + return false; + } + +#endif + +mesh_index_pair unified_bed_leveling::find_closest_mesh_point_of_type(const MeshPointType type, const xy_pos_t &pos, const bool probe_relative/*=false*/, MeshFlags *done_flags/*=nullptr*/) { + + #if ENABLED(UBL_HILBERT_CURVE) + + find_closest_t d; + d.type = type; + d.done_flags = done_flags; + d.probe_relative = probe_relative; + d.closest.invalidate(); + hilbert_curve::search_from_closest(pos, test_func, &d); + return d.closest; + + #else + + mesh_index_pair closest; + closest.invalidate(); + closest.distance = -99999.9f; + + // Get the reference position, either nozzle or probe + const xy_pos_t ref = probe_relative ? pos + probe.offset_xy : pos; + + float best_so_far = 99999.99f; + + GRID_LOOP(i, j) { + if ( type == CLOSEST || type == (isnan(z_values[i][j]) ? INVALID : REAL) + || (type == SET_IN_BITMAP && !done_flags->marked(i, j)) + ) { + // Found a Mesh Point of the specified type! + const xy_pos_t mpos = { get_mesh_x(i), get_mesh_y(j) }; + + // If using the probe as the reference there are some unreachable locations. + // Also for round beds, there are grid points outside the bed the nozzle can't reach. + // Prune them from the list and ignore them till the next Phase (manual nozzle probing). + + if (!(probe_relative ? probe.can_reach(mpos) : position_is_reachable(mpos))) + continue; + + // Reachable. Check if it's the best_so_far location to the nozzle. + + const xy_pos_t diff = current_position - mpos; + const float distance = (ref - mpos).magnitude() + diff.magnitude() * 0.1f; + + // factor in the distance from the current location for the normal case + // so the nozzle isn't running all over the bed. + if (distance < best_so_far) { + best_so_far = distance; // Found a closer location with the desired value type. + closest.pos.set(i, j); + closest.distance = best_so_far; + } + } + } // GRID_LOOP + + return closest; + + #endif +} + +/** + * 'Smart Fill': Scan from the outward edges of the mesh towards the center. + * If an invalid location is found, use the next two points (if valid) to + * calculate a 'reasonable' value for the unprobed mesh point. + */ + +bool unified_bed_leveling::smart_fill_one(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) { + const float v = z_values[x][y]; + if (isnan(v)) { // A NAN... + const int8_t dx = x + xdir, dy = y + ydir; + const float v1 = z_values[dx][dy]; + if (!isnan(v1)) { // ...next to a pair of real values? + const float v2 = z_values[dx + xdir][dy + ydir]; + if (!isnan(v2)) { + z_values[x][y] = v1 < v2 ? v1 : v1 + v1 - v2; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y])); + return true; + } + } + } + return false; +} + +typedef struct { uint8_t sx, ex, sy, ey; bool yfirst; } smart_fill_info; + +void unified_bed_leveling::smart_fill_mesh() { + static const smart_fill_info + info0 PROGMEM = { 0, GRID_MAX_POINTS_X, 0, (GRID_MAX_POINTS_Y) - 2, false }, // Bottom of the mesh looking up + info1 PROGMEM = { 0, GRID_MAX_POINTS_X, (GRID_MAX_POINTS_Y) - 1, 0, false }, // Top of the mesh looking down + info2 PROGMEM = { 0, (GRID_MAX_POINTS_X) - 2, 0, GRID_MAX_POINTS_Y, true }, // Left side of the mesh looking right + info3 PROGMEM = { (GRID_MAX_POINTS_X) - 1, 0, 0, GRID_MAX_POINTS_Y, true }; // Right side of the mesh looking left + static const smart_fill_info * const info[] PROGMEM = { &info0, &info1, &info2, &info3 }; + + LOOP_L_N(i, COUNT(info)) { + const smart_fill_info *f = (smart_fill_info*)pgm_read_ptr(&info[i]); + const int8_t sx = pgm_read_byte(&f->sx), sy = pgm_read_byte(&f->sy), + ex = pgm_read_byte(&f->ex), ey = pgm_read_byte(&f->ey); + if (pgm_read_byte(&f->yfirst)) { + const int8_t dir = ex > sx ? 1 : -1; + for (uint8_t y = sy; y != ey; ++y) + for (uint8_t x = sx; x != ex; x += dir) + if (smart_fill_one(x, y, dir, 0)) break; + } + else { + const int8_t dir = ey > sy ? 1 : -1; + for (uint8_t x = sx; x != ex; ++x) + for (uint8_t y = sy; y != ey; y += dir) + if (smart_fill_one(x, y, 0, dir)) break; + } + } +} + +#if HAS_BED_PROBE + + //#define VALIDATE_MESH_TILT + + #include "../../../libs/vector_3.h" + + void unified_bed_leveling::tilt_mesh_based_on_probed_grid(const bool do_3_pt_leveling) { + const float x_min = probe.min_x(), x_max = probe.max_x(), + y_min = probe.min_y(), y_max = probe.max_y(), + dx = (x_max - x_min) / (param.J_grid_size - 1), + dy = (y_max - y_min) / (param.J_grid_size - 1); + + xy_float_t points[3]; + probe.get_three_points(points); + + float measured_z; + bool abort_flag = false; + + #ifdef VALIDATE_MESH_TILT + float z1, z2, z3; // Needed for algorithm validation below + #endif + + struct linear_fit_data lsf_results; + incremental_LSF_reset(&lsf_results); + + if (do_3_pt_leveling) { + SERIAL_ECHOLNPGM("Tilting mesh (1/3)"); + TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " 1/3"), GET_TEXT(MSG_LCD_TILTING_MESH))); + + measured_z = probe.probe_at_point(points[0], PROBE_PT_RAISE, param.V_verbosity); + if (isnan(measured_z)) + abort_flag = true; + else { + measured_z -= get_z_correction(points[0]); + #ifdef VALIDATE_MESH_TILT + z1 = measured_z; + #endif + if (param.V_verbosity > 3) { + serial_spaces(16); + SERIAL_ECHOLNPGM("Corrected_Z=", measured_z); + } + incremental_LSF(&lsf_results, points[0], measured_z); + } + + if (!abort_flag) { + SERIAL_ECHOLNPGM("Tilting mesh (2/3)"); + TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " 2/3"), GET_TEXT(MSG_LCD_TILTING_MESH))); + + measured_z = probe.probe_at_point(points[1], PROBE_PT_RAISE, param.V_verbosity); + #ifdef VALIDATE_MESH_TILT + z2 = measured_z; + #endif + if (isnan(measured_z)) + abort_flag = true; + else { + measured_z -= get_z_correction(points[1]); + if (param.V_verbosity > 3) { + serial_spaces(16); + SERIAL_ECHOLNPGM("Corrected_Z=", measured_z); + } + incremental_LSF(&lsf_results, points[1], measured_z); + } + } + + if (!abort_flag) { + SERIAL_ECHOLNPGM("Tilting mesh (3/3)"); + TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " 3/3"), GET_TEXT(MSG_LCD_TILTING_MESH))); + + measured_z = probe.probe_at_point(points[2], PROBE_PT_LAST_STOW, param.V_verbosity); + #ifdef VALIDATE_MESH_TILT + z3 = measured_z; + #endif + if (isnan(measured_z)) + abort_flag = true; + else { + measured_z -= get_z_correction(points[2]); + if (param.V_verbosity > 3) { + serial_spaces(16); + SERIAL_ECHOLNPGM("Corrected_Z=", measured_z); + } + incremental_LSF(&lsf_results, points[2], measured_z); + } + } + + probe.stow(); + probe.move_z_after_probing(); + + if (abort_flag) { + SERIAL_ECHOLNPGM("?Error probing point. Aborting operation."); + return; + } + } + else { // !do_3_pt_leveling + + bool zig_zag = false; + + const uint16_t total_points = sq(param.J_grid_size); + uint16_t point_num = 1; + + xy_pos_t rpos; + LOOP_L_N(ix, param.J_grid_size) { + rpos.x = x_min + ix * dx; + LOOP_L_N(iy, param.J_grid_size) { + rpos.y = y_min + dy * (zig_zag ? param.J_grid_size - 1 - iy : iy); + + if (!abort_flag) { + SERIAL_ECHOLNPGM("Tilting mesh point ", point_num, "/", total_points, "\n"); + TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " %i/%i"), GET_TEXT(MSG_LCD_TILTING_MESH), point_num, total_points)); + + measured_z = probe.probe_at_point(rpos, parser.seen_test('E') ? PROBE_PT_STOW : PROBE_PT_RAISE, param.V_verbosity); // TODO: Needs error handling + + abort_flag = isnan(measured_z); + + #if ENABLED(DEBUG_LEVELING_FEATURE) + if (DEBUGGING(LEVELING)) { + const xy_pos_t lpos = rpos.asLogical(); + DEBUG_CHAR('('); + DEBUG_ECHO_F(rpos.x, 7); + DEBUG_CHAR(','); + DEBUG_ECHO_F(rpos.y, 7); + DEBUG_ECHOPAIR_F(") logical: (", lpos.x, 7); + DEBUG_CHAR(','); + DEBUG_ECHO_F(lpos.y, 7); + DEBUG_ECHOPAIR_F(") measured: ", measured_z, 7); + DEBUG_ECHOPAIR_F(" correction: ", get_z_correction(rpos), 7); + } + #endif + + measured_z -= get_z_correction(rpos) /* + probe.offset.z */ ; + + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPAIR_F(" final >>>---> ", measured_z, 7); + + if (param.V_verbosity > 3) { + serial_spaces(16); + SERIAL_ECHOLNPGM("Corrected_Z=", measured_z); + } + incremental_LSF(&lsf_results, rpos, measured_z); + } + + point_num++; + } + + zig_zag ^= true; + } + } + probe.stow(); + probe.move_z_after_probing(); + + if (abort_flag || finish_incremental_LSF(&lsf_results)) { + SERIAL_ECHOPGM("Could not complete LSF!"); + return; + } + + vector_3 normal = vector_3(lsf_results.A, lsf_results.B, 1).get_normal(); + + if (param.V_verbosity > 2) { + SERIAL_ECHOPAIR_F("bed plane normal = [", normal.x, 7); + SERIAL_CHAR(','); + SERIAL_ECHO_F(normal.y, 7); + SERIAL_CHAR(','); + SERIAL_ECHO_F(normal.z, 7); + SERIAL_ECHOLNPGM("]"); + } + + matrix_3x3 rotation = matrix_3x3::create_look_at(vector_3(lsf_results.A, lsf_results.B, 1)); + + GRID_LOOP(i, j) { + float mx = get_mesh_x(i), my = get_mesh_y(j), mz = z_values[i][j]; + + if (DEBUGGING(LEVELING)) { + DEBUG_ECHOPAIR_F("before rotation = [", mx, 7); + DEBUG_CHAR(','); + DEBUG_ECHO_F(my, 7); + DEBUG_CHAR(','); + DEBUG_ECHO_F(mz, 7); + DEBUG_ECHOPGM("] ---> "); + DEBUG_DELAY(20); + } + + rotation.apply_rotation_xyz(mx, my, mz); + + if (DEBUGGING(LEVELING)) { + DEBUG_ECHOPAIR_F("after rotation = [", mx, 7); + DEBUG_CHAR(','); + DEBUG_ECHO_F(my, 7); + DEBUG_CHAR(','); + DEBUG_ECHO_F(mz, 7); + DEBUG_ECHOLNPGM("]"); + DEBUG_DELAY(20); + } + + z_values[i][j] = mz - lsf_results.D; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(i, j, z_values[i][j])); + } + + if (DEBUGGING(LEVELING)) { + rotation.debug(F("rotation matrix:\n")); + DEBUG_ECHOPAIR_F("LSF Results A=", lsf_results.A, 7); + DEBUG_ECHOPAIR_F(" B=", lsf_results.B, 7); + DEBUG_ECHOLNPAIR_F(" D=", lsf_results.D, 7); + DEBUG_DELAY(55); + + DEBUG_ECHOPAIR_F("bed plane normal = [", normal.x, 7); + DEBUG_CHAR(','); + DEBUG_ECHO_F(normal.y, 7); + DEBUG_CHAR(','); + DEBUG_ECHO_F(normal.z, 7); + DEBUG_ECHOLNPGM("]"); + DEBUG_EOL(); + + /** + * Use the code below to check the validity of the mesh tilting algorithm. + * 3-Point Mesh Tilt uses the same algorithm as grid-based tilting, but only + * three points are used in the calculation. This guarantees that each probed point + * has an exact match when get_z_correction() for that location is calculated. + * The Z error between the probed point locations and the get_z_correction() + * numbers for those locations should be 0. + */ + #ifdef VALIDATE_MESH_TILT + auto d_from = []{ DEBUG_ECHOPGM("D from "); }; + auto normed = [&](const xy_pos_t &pos, const_float_t zadd) { + return normal.x * pos.x + normal.y * pos.y + zadd; + }; + auto debug_pt = [](FSTR_P const pre, const xy_pos_t &pos, const_float_t zadd) { + d_from(); SERIAL_ECHOF(pre); + DEBUG_ECHO_F(normed(pos, zadd), 6); + DEBUG_ECHOLNPAIR_F(" Z error = ", zadd - get_z_correction(pos), 6); + }; + debug_pt(F("1st point: "), probe_pt[0], normal.z * z1); + debug_pt(F("2nd point: "), probe_pt[1], normal.z * z2); + debug_pt(F("3rd point: "), probe_pt[2], normal.z * z3); + d_from(); DEBUG_ECHOPGM("safe home with Z="); + DEBUG_ECHOLNPAIR_F("0 : ", normed(safe_homing_xy, 0), 6); + d_from(); DEBUG_ECHOPGM("safe home with Z="); + DEBUG_ECHOLNPAIR_F("mesh value ", normed(safe_homing_xy, get_z_correction(safe_homing_xy)), 6); + DEBUG_ECHOPGM(" Z error = (", Z_SAFE_HOMING_X_POINT, ",", Z_SAFE_HOMING_Y_POINT); + DEBUG_ECHOLNPAIR_F(") = ", get_z_correction(safe_homing_xy), 6); + #endif + } // DEBUGGING(LEVELING) + + } + +#endif // HAS_BED_PROBE + +#if ENABLED(UBL_G29_P31) + void unified_bed_leveling::smart_fill_wlsf(const_float_t weight_factor) { + + // For each undefined mesh point, compute a distance-weighted least squares fit + // from all the originally populated mesh points, weighted toward the point + // being extrapolated so that nearby points will have greater influence on + // the point being extrapolated. Then extrapolate the mesh point from WLSF. + + static_assert((GRID_MAX_POINTS_Y) <= 16, "GRID_MAX_POINTS_Y too big"); + uint16_t bitmap[GRID_MAX_POINTS_X] = { 0 }; + struct linear_fit_data lsf_results; + + SERIAL_ECHOPGM("Extrapolating mesh..."); + + const float weight_scaled = weight_factor * _MAX(MESH_X_DIST, MESH_Y_DIST); + + GRID_LOOP(jx, jy) if (!isnan(z_values[jx][jy])) SBI(bitmap[jx], jy); + + xy_pos_t ppos; + LOOP_L_N(ix, GRID_MAX_POINTS_X) { + ppos.x = get_mesh_x(ix); + LOOP_L_N(iy, GRID_MAX_POINTS_Y) { + ppos.y = get_mesh_y(iy); + if (isnan(z_values[ix][iy])) { + // undefined mesh point at (ppos.x,ppos.y), compute weighted LSF from original valid mesh points. + incremental_LSF_reset(&lsf_results); + xy_pos_t rpos; + LOOP_L_N(jx, GRID_MAX_POINTS_X) { + rpos.x = get_mesh_x(jx); + LOOP_L_N(jy, GRID_MAX_POINTS_Y) { + if (TEST(bitmap[jx], jy)) { + rpos.y = get_mesh_y(jy); + const float rz = z_values[jx][jy], + w = 1.0f + weight_scaled / (rpos - ppos).magnitude(); + incremental_WLSF(&lsf_results, rpos, rz, w); + } + } + } + if (finish_incremental_LSF(&lsf_results)) { + SERIAL_ECHOLNPGM("Insufficient data"); + return; + } + const float ez = -lsf_results.D - lsf_results.A * ppos.x - lsf_results.B * ppos.y; + z_values[ix][iy] = ez; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(ix, iy, z_values[ix][iy])); + idle(); // housekeeping + } + } + } + + SERIAL_ECHOLNPGM("done"); + } +#endif // UBL_G29_P31 + +#if ENABLED(UBL_DEVEL_DEBUGGING) + /** + * Much of the 'What?' command can be eliminated. But until we are fully debugged, it is + * good to have the extra information. Soon... we prune this to just a few items + */ + void unified_bed_leveling::g29_what_command() { + report_state(); + + if (storage_slot == -1) + SERIAL_ECHOPGM("No Mesh Loaded."); + else + SERIAL_ECHOPGM("Mesh ", storage_slot, " Loaded."); + SERIAL_EOL(); + serial_delay(50); + + #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) + SERIAL_ECHOLNPAIR_F("Fade Height M420 Z", planner.z_fade_height, 4); + #endif + + adjust_mesh_to_mean(param.C_seen, param.C_constant); + + #if HAS_BED_PROBE + SERIAL_ECHOLNPAIR_F("Probe Offset M851 Z", probe.offset.z, 7); + #endif + + SERIAL_ECHOLNPGM("MESH_MIN_X " STRINGIFY(MESH_MIN_X) "=", MESH_MIN_X); serial_delay(50); + SERIAL_ECHOLNPGM("MESH_MIN_Y " STRINGIFY(MESH_MIN_Y) "=", MESH_MIN_Y); serial_delay(50); + SERIAL_ECHOLNPGM("MESH_MAX_X " STRINGIFY(MESH_MAX_X) "=", MESH_MAX_X); serial_delay(50); + SERIAL_ECHOLNPGM("MESH_MAX_Y " STRINGIFY(MESH_MAX_Y) "=", MESH_MAX_Y); serial_delay(50); + SERIAL_ECHOLNPGM("GRID_MAX_POINTS_X ", GRID_MAX_POINTS_X); serial_delay(50); + SERIAL_ECHOLNPGM("GRID_MAX_POINTS_Y ", GRID_MAX_POINTS_Y); serial_delay(50); + SERIAL_ECHOLNPGM("MESH_X_DIST ", MESH_X_DIST); + SERIAL_ECHOLNPGM("MESH_Y_DIST ", MESH_Y_DIST); serial_delay(50); + + SERIAL_ECHOPGM("X-Axis Mesh Points at: "); + LOOP_L_N(i, GRID_MAX_POINTS_X) { + SERIAL_ECHO_F(LOGICAL_X_POSITION(get_mesh_x(i)), 3); + SERIAL_ECHOPGM(" "); + serial_delay(25); + } + SERIAL_EOL(); + + SERIAL_ECHOPGM("Y-Axis Mesh Points at: "); + LOOP_L_N(i, GRID_MAX_POINTS_Y) { + SERIAL_ECHO_F(LOGICAL_Y_POSITION(get_mesh_y(i)), 3); + SERIAL_ECHOPGM(" "); + serial_delay(25); + } + SERIAL_EOL(); + + #if HAS_KILL + SERIAL_ECHOLNPGM("Kill pin on :", KILL_PIN, " state:", kill_state()); + #endif + + SERIAL_EOL(); + serial_delay(50); + + #if ENABLED(UBL_DEVEL_DEBUGGING) + SERIAL_ECHOLNPGM("ubl_state_at_invocation :", ubl_state_at_invocation, "\nubl_state_recursion_chk :", ubl_state_recursion_chk); + serial_delay(50); + + SERIAL_ECHOLNPGM("Meshes go from ", hex_address((void*)settings.meshes_start_index()), " to ", hex_address((void*)settings.meshes_end_index())); + serial_delay(50); + + SERIAL_ECHOLNPGM("sizeof(ubl) : ", sizeof(ubl)); SERIAL_EOL(); + SERIAL_ECHOLNPGM("z_value[][] size: ", sizeof(z_values)); SERIAL_EOL(); + serial_delay(25); + + SERIAL_ECHOLNPGM("EEPROM free for UBL: ", hex_address((void*)(settings.meshes_end_index() - settings.meshes_start_index()))); + serial_delay(50); + + SERIAL_ECHOLNPGM("EEPROM can hold ", settings.calc_num_meshes(), " meshes.\n"); + serial_delay(25); + #endif // UBL_DEVEL_DEBUGGING + + if (!sanity_check()) { + echo_name(); + SERIAL_ECHOLNPGM(" sanity checks passed."); + } + } + + /** + * When we are fully debugged, the EEPROM dump command will get deleted also. But + * right now, it is good to have the extra information. Soon... we prune this. + */ + void unified_bed_leveling::g29_eeprom_dump() { + uint8_t cccc; + + SERIAL_ECHO_MSG("EEPROM Dump:"); + persistentStore.access_start(); + for (uint16_t i = 0; i < persistentStore.capacity(); i += 16) { + if (!(i & 0x3)) idle(); + print_hex_word(i); + SERIAL_ECHOPGM(": "); + for (uint16_t j = 0; j < 16; j++) { + persistentStore.read_data(i + j, &cccc, sizeof(uint8_t)); + print_hex_byte(cccc); + SERIAL_CHAR(' '); + } + SERIAL_EOL(); + } + SERIAL_EOL(); + persistentStore.access_finish(); + } + + /** + * When we are fully debugged, this may go away. But there are some valid + * use cases for the users. So we can wait and see what to do with it. + */ + void unified_bed_leveling::g29_compare_current_mesh_to_stored_mesh() { + const int16_t a = settings.calc_num_meshes(); + + if (!a) { + SERIAL_ECHOLNPGM("?EEPROM storage not available."); + return; + } + + if (!parser.has_value() || !WITHIN(parser.value_int(), 0, a - 1)) { + SERIAL_ECHOLNPGM("?Invalid storage slot.\n?Use 0 to ", a - 1); + return; + } + + param.KLS_storage_slot = (int8_t)parser.value_int(); + + float tmp_z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y]; + settings.load_mesh(param.KLS_storage_slot, &tmp_z_values); + + SERIAL_ECHOLNPGM("Subtracting mesh in slot ", param.KLS_storage_slot, " from current mesh."); + + GRID_LOOP(x, y) { + z_values[x][y] -= tmp_z_values[x][y]; + TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y])); + } + } + +#endif // UBL_DEVEL_DEBUGGING + +#endif // AUTO_BED_LEVELING_UBL diff --git a/src/feature/bedlevel/ubl/ubl_motion.cpp b/src/feature/bedlevel/ubl/ubl_motion.cpp new file mode 100644 index 0000000..18110c6 --- /dev/null +++ b/src/feature/bedlevel/ubl/ubl_motion.cpp @@ -0,0 +1,492 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../../../inc/MarlinConfig.h" + +#if ENABLED(AUTO_BED_LEVELING_UBL) + +#include "../bedlevel.h" +#include "../../../module/planner.h" +#include "../../../module/motion.h" + +#if ENABLED(DELTA) + #include "../../../module/delta.h" +#endif + +#include "../../../MarlinCore.h" +#include + +//#define DEBUG_UBL_MOTION +#define DEBUG_OUT ENABLED(DEBUG_UBL_MOTION) +#include "../../../core/debug_out.h" + +#if !UBL_SEGMENTED + + // TODO: The first and last parts of a move might result in very short segment(s) + // after getting split on the cell boundary, so moves like that should not + // get split. This will be most common for moves that start/end near the + // corners of cells. To fix the issue, simply check if the start/end of the line + // is very close to a cell boundary in advance and don't split the line there. + + void unified_bed_leveling::line_to_destination_cartesian(const_feedRate_t scaled_fr_mm_s, const uint8_t extruder) { + /** + * Much of the nozzle movement will be within the same cell. So we will do as little computation + * as possible to determine if this is the case. If this move is within the same cell, we will + * just do the required Z-Height correction, call the Planner's buffer_line() routine, and leave + */ + #if HAS_POSITION_MODIFIERS + xyze_pos_t start = current_position, end = destination; + planner.apply_modifiers(start); + planner.apply_modifiers(end); + #else + const xyze_pos_t &start = current_position, &end = destination; + #endif + + const xy_int8_t istart = cell_indexes(start), iend = cell_indexes(end); + + // A move within the same cell needs no splitting + if (istart == iend) { + + FINAL_MOVE: + + // When UBL_Z_RAISE_WHEN_OFF_MESH is disabled Z correction is extrapolated from the edge of the mesh + #ifdef UBL_Z_RAISE_WHEN_OFF_MESH + // For a move off the UBL mesh, use a constant Z raise + if (!cell_index_x_valid(end.x) || !cell_index_y_valid(end.y)) { + + // Note: There is no Z Correction in this case. We are off the mesh and don't know what + // a reasonable correction would be, UBL_Z_RAISE_WHEN_OFF_MESH will be used instead of + // a calculated (Bi-Linear interpolation) correction. + + end.z += UBL_Z_RAISE_WHEN_OFF_MESH; + planner.buffer_segment(end, scaled_fr_mm_s, extruder); + current_position = destination; + return; + } + #endif + + // The distance is always MESH_X_DIST so multiply by the constant reciprocal. + const float xratio = (end.x - get_mesh_x(iend.x)) * RECIPROCAL(MESH_X_DIST), + yratio = (end.y - get_mesh_y(iend.y)) * RECIPROCAL(MESH_Y_DIST), + z1 = z_values[iend.x][iend.y ] + xratio * (z_values[iend.x + 1][iend.y ] - z_values[iend.x][iend.y ]), + z2 = z_values[iend.x][iend.y + 1] + xratio * (z_values[iend.x + 1][iend.y + 1] - z_values[iend.x][iend.y + 1]); + + // X cell-fraction done. Interpolate the two Z offsets with the Y fraction for the final Z offset. + const float z0 = (z1 + (z2 - z1) * yratio) * planner.fade_scaling_factor_for_z(end.z); + + // Undefined parts of the Mesh in z_values[][] are NAN. + // Replace NAN corrections with 0.0 to prevent NAN propagation. + if (!isnan(z0)) end.z += z0; + planner.buffer_segment(end, scaled_fr_mm_s, extruder); + current_position = destination; + return; + } + + /** + * Past this point the move is known to cross one or more mesh lines. Check for the most common + * case - crossing only one X or Y line - after details are worked out to reduce computation. + */ + + const xy_float_t dist = end - start; + const xy_bool_t neg { dist.x < 0, dist.y < 0 }; + const xy_int8_t ineg { int8_t(neg.x), int8_t(neg.y) }; + const xy_float_t sign { neg.x ? -1.0f : 1.0f, neg.y ? -1.0f : 1.0f }; + const xy_int8_t iadd { int8_t(iend.x == istart.x ? 0 : sign.x), int8_t(iend.y == istart.y ? 0 : sign.y) }; + + /** + * Compute the extruder scaling factor for each partial move, checking for + * zero-length moves that would result in an infinite scaling factor. + * A float divide is required for this, but then it just multiplies. + * Also select a scaling factor based on the larger of the X and Y + * components. The larger of the two is used to preserve precision. + */ + + const xy_float_t ad = sign * dist; + const bool use_x_dist = ad.x > ad.y; + + float on_axis_distance = use_x_dist ? dist.x : dist.y; + + const float z_normalized_dist = (end.z - start.z) / on_axis_distance; // Allow divide by zero + #if HAS_EXTRUDERS + const float e_normalized_dist = (end.e - start.e) / on_axis_distance; + const bool inf_normalized_flag = isinf(e_normalized_dist); + #endif + + xy_int8_t icell = istart; + + const float ratio = dist.y / dist.x, // Allow divide by zero + c = start.y - ratio * start.x; + + const bool inf_ratio_flag = isinf(ratio); + + xyze_pos_t dest; // Stores XYZE for segmented moves + + /** + * Handle vertical lines that stay within one column. + * These need not be perfectly vertical. + */ + if (iadd.x == 0) { // Vertical line? + icell.y += ineg.y; // Line going down? Just go to the bottom. + while (icell.y != iend.y + ineg.y) { + icell.y += iadd.y; + const float next_mesh_line_y = get_mesh_y(icell.y); + + /** + * Skip the calculations for an infinite slope. + * For others the next X is the same so this can continue. + * Calculate X at the next Y mesh line. + */ + dest.x = inf_ratio_flag ? start.x : (next_mesh_line_y - c) / ratio; + + float z0 = z_correction_for_x_on_horizontal_mesh_line(dest.x, icell.x, icell.y) + * planner.fade_scaling_factor_for_z(end.z); + + // Undefined parts of the Mesh in z_values[][] are NAN. + // Replace NAN corrections with 0.0 to prevent NAN propagation. + if (isnan(z0)) z0 = 0.0; + + dest.y = get_mesh_y(icell.y); + + /** + * Without this check, it's possible to generate a zero length move, as in the case where + * the line is heading down, starting exactly on a mesh line boundary. Since this is rare + * it might be fine to remove this check and let planner.buffer_segment() filter it out. + */ + if (dest.y != start.y) { + if (!inf_normalized_flag) { // fall-through faster than branch + on_axis_distance = use_x_dist ? dest.x - start.x : dest.y - start.y; + TERN_(HAS_EXTRUDERS, dest.e = start.e + on_axis_distance * e_normalized_dist); + dest.z = start.z + on_axis_distance * z_normalized_dist; + } + else { + TERN_(HAS_EXTRUDERS, dest.e = end.e); + dest.z = end.z; + } + + dest.z += z0; + planner.buffer_segment(dest, scaled_fr_mm_s, extruder); + + } + else + DEBUG_ECHOLNPGM("[ubl] skip Y segment"); + } + + // At the final destination? Usually not, but when on a Y Mesh Line it's completed. + if (xy_pos_t(current_position) != xy_pos_t(end)) + goto FINAL_MOVE; + + current_position = destination; + return; + } + + /** + * Handle horizontal lines that stay within one row. + * These need not be perfectly horizontal. + */ + if (iadd.y == 0) { // Horizontal line? + icell.x += ineg.x; // Heading left? Just go to the left edge of the cell for the first move. + + while (icell.x != iend.x + ineg.x) { + icell.x += iadd.x; + dest.x = get_mesh_x(icell.x); + dest.y = ratio * dest.x + c; // Calculate Y at the next X mesh line + + float z0 = z_correction_for_y_on_vertical_mesh_line(dest.y, icell.x, icell.y) + * planner.fade_scaling_factor_for_z(end.z); + + // Undefined parts of the Mesh in z_values[][] are NAN. + // Replace NAN corrections with 0.0 to prevent NAN propagation. + if (isnan(z0)) z0 = 0.0; + + /** + * Without this check, it's possible to generate a zero length move, as in the case where + * the line is heading left, starting exactly on a mesh line boundary. Since this is rare + * it might be fine to remove this check and let planner.buffer_segment() filter it out. + */ + if (dest.x != start.x) { + if (!inf_normalized_flag) { + on_axis_distance = use_x_dist ? dest.x - start.x : dest.y - start.y; + TERN_(HAS_EXTRUDERS, dest.e = start.e + on_axis_distance * e_normalized_dist); // Based on X or Y because the move is horizontal + dest.z = start.z + on_axis_distance * z_normalized_dist; + } + else { + TERN_(HAS_EXTRUDERS, dest.e = end.e); + dest.z = end.z; + } + + dest.z += z0; + if (!planner.buffer_segment(dest, scaled_fr_mm_s, extruder)) break; + + } + else + DEBUG_ECHOLNPGM("[ubl] skip Y segment"); + } + + if (xy_pos_t(current_position) != xy_pos_t(end)) + goto FINAL_MOVE; + + current_position = destination; + return; + } + + /** + * Generic case of a line crossing both X and Y Mesh lines. + */ + + xy_int8_t cnt = (istart - iend).ABS(); + + icell += ineg; + + while (cnt) { + + const float next_mesh_line_x = get_mesh_x(icell.x + iadd.x), + next_mesh_line_y = get_mesh_y(icell.y + iadd.y); + + dest.y = ratio * next_mesh_line_x + c; // Calculate Y at the next X mesh line + dest.x = (next_mesh_line_y - c) / ratio; // Calculate X at the next Y mesh line + // (No need to worry about ratio == 0. + // In that case, it was already detected + // as a vertical line move above.) + + if (neg.x == (dest.x > next_mesh_line_x)) { // Check if we hit the Y line first + // Yes! Crossing a Y Mesh Line next + float z0 = z_correction_for_x_on_horizontal_mesh_line(dest.x, icell.x - ineg.x, icell.y + iadd.y) + * planner.fade_scaling_factor_for_z(end.z); + + // Undefined parts of the Mesh in z_values[][] are NAN. + // Replace NAN corrections with 0.0 to prevent NAN propagation. + if (isnan(z0)) z0 = 0.0; + + dest.y = next_mesh_line_y; + + if (!inf_normalized_flag) { + on_axis_distance = use_x_dist ? dest.x - start.x : dest.y - start.y; + TERN_(HAS_EXTRUDERS, dest.e = start.e + on_axis_distance * e_normalized_dist); + dest.z = start.z + on_axis_distance * z_normalized_dist; + } + else { + TERN_(HAS_EXTRUDERS, dest.e = end.e); + dest.z = end.z; + } + + dest.z += z0; + if (!planner.buffer_segment(dest, scaled_fr_mm_s, extruder)) break; + + icell.y += iadd.y; + cnt.y--; + } + else { + // Yes! Crossing a X Mesh Line next + float z0 = z_correction_for_y_on_vertical_mesh_line(dest.y, icell.x + iadd.x, icell.y - ineg.y) + * planner.fade_scaling_factor_for_z(end.z); + + // Undefined parts of the Mesh in z_values[][] are NAN. + // Replace NAN corrections with 0.0 to prevent NAN propagation. + if (isnan(z0)) z0 = 0.0; + + dest.x = next_mesh_line_x; + + if (!inf_normalized_flag) { + on_axis_distance = use_x_dist ? dest.x - start.x : dest.y - start.y; + TERN_(HAS_EXTRUDERS, dest.e = start.e + on_axis_distance * e_normalized_dist); + dest.z = start.z + on_axis_distance * z_normalized_dist; + } + else { + TERN_(HAS_EXTRUDERS, dest.e = end.e); + dest.z = end.z; + } + + dest.z += z0; + if (!planner.buffer_segment(dest, scaled_fr_mm_s, extruder)) break; + + icell.x += iadd.x; + cnt.x--; + } + + if (cnt.x < 0 || cnt.y < 0) break; // Too far! Exit the loop and go to FINAL_MOVE + } + + if (xy_pos_t(current_position) != xy_pos_t(end)) + goto FINAL_MOVE; + + current_position = destination; + } + +#else // UBL_SEGMENTED + + #if IS_SCARA + #define DELTA_SEGMENT_MIN_LENGTH 0.25 // SCARA minimum segment size is 0.25mm + #elif ENABLED(DELTA) + #define DELTA_SEGMENT_MIN_LENGTH 0.10 // mm (still subject to DELTA_SEGMENTS_PER_SECOND) + #elif ENABLED(POLARGRAPH) + #define DELTA_SEGMENT_MIN_LENGTH 0.10 // mm (still subject to DELTA_SEGMENTS_PER_SECOND) + #else // CARTESIAN + #ifdef LEVELED_SEGMENT_LENGTH + #define DELTA_SEGMENT_MIN_LENGTH LEVELED_SEGMENT_LENGTH + #else + #define DELTA_SEGMENT_MIN_LENGTH 1.00 // mm (similar to G2/G3 arc segmentation) + #endif + #endif + + /** + * Prepare a segmented linear move for DELTA/SCARA/CARTESIAN with UBL and FADE semantics. + * This calls planner.buffer_segment multiple times for small incremental moves. + * Returns true if did NOT move, false if moved (requires current_position update). + */ + + bool __O2 unified_bed_leveling::line_to_destination_segmented(const_feedRate_t scaled_fr_mm_s) { + + if (!position_is_reachable(destination)) // fail if moving outside reachable boundary + return true; // did not move, so current_position still accurate + + const xyze_pos_t total = destination - current_position; + + const float cart_xy_mm_2 = HYPOT2(total.x, total.y), + cart_xy_mm = SQRT(cart_xy_mm_2); // Total XY distance + + #if IS_KINEMATIC + const float seconds = cart_xy_mm / scaled_fr_mm_s; // Duration of XY move at requested rate + uint16_t segments = LROUND(segments_per_second * seconds), // Preferred number of segments for distance @ feedrate + seglimit = LROUND(cart_xy_mm * RECIPROCAL(DELTA_SEGMENT_MIN_LENGTH)); // Number of segments at minimum segment length + NOMORE(segments, seglimit); // Limit to minimum segment length (fewer segments) + #else + uint16_t segments = LROUND(cart_xy_mm * RECIPROCAL(DELTA_SEGMENT_MIN_LENGTH)); // Cartesian fixed segment length + #endif + + NOLESS(segments, 1U); // Must have at least one segment + const float inv_segments = 1.0f / segments; // Reciprocal to save calculation + + // Add hints to help optimize the move + PlannerHints hints(SQRT(cart_xy_mm_2 + sq(total.z)) * inv_segments); // Length of each segment + #if ENABLED(SCARA_FEEDRATE_SCALING) + hints.inv_duration = scaled_fr_mm_s / hints.millimeters; + #endif + + xyze_float_t diff = total * inv_segments; + + // Note that E segment distance could vary slightly as z mesh height + // changes for each segment, but small enough to ignore. + + xyze_pos_t raw = current_position; + + // Just do plain segmentation if UBL is inactive or the target is above the fade height + if (!planner.leveling_active || !planner.leveling_active_at_z(destination.z)) { + while (--segments) { + raw += diff; + planner.buffer_line(raw, scaled_fr_mm_s, active_extruder, hints); + } + planner.buffer_line(destination, scaled_fr_mm_s, active_extruder, hints); + return false; // Did not set current from destination + } + + // Otherwise perform per-segment leveling + + #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) + const float fade_scaling_factor = planner.fade_scaling_factor_for_z(destination.z); + #endif + + // Move to first segment destination + raw += diff; + + for (;;) { // for each mesh cell encountered during the move + + // Compute mesh cell invariants that remain constant for all segments within cell. + // Note for cell index, if point is outside the mesh grid (in MESH_INSET perimeter) + // the bilinear interpolation from the adjacent cell within the mesh will still work. + // Inner loop will exit each time (because out of cell bounds) but will come back + // in top of loop and again re-find same adjacent cell and use it, just less efficient + // for mesh inset area. + + xy_int8_t icell = { + int8_t((raw.x - (MESH_MIN_X)) * RECIPROCAL(MESH_X_DIST)), + int8_t((raw.y - (MESH_MIN_Y)) * RECIPROCAL(MESH_Y_DIST)) + }; + LIMIT(icell.x, 0, GRID_MAX_CELLS_X); + LIMIT(icell.y, 0, GRID_MAX_CELLS_Y); + + float z_x0y0 = z_values[icell.x ][icell.y ], // z at lower left corner + z_x1y0 = z_values[icell.x+1][icell.y ], // z at upper left corner + z_x0y1 = z_values[icell.x ][icell.y+1], // z at lower right corner + z_x1y1 = z_values[icell.x+1][icell.y+1]; // z at upper right corner + + if (isnan(z_x0y0)) z_x0y0 = 0; // ideally activating planner.leveling_active (G29 A) + if (isnan(z_x1y0)) z_x1y0 = 0; // should refuse if any invalid mesh points + if (isnan(z_x0y1)) z_x0y1 = 0; // in order to avoid isnan tests per cell, + if (isnan(z_x1y1)) z_x1y1 = 0; // thus guessing zero for undefined points + + const xy_pos_t pos = { get_mesh_x(icell.x), get_mesh_y(icell.y) }; + xy_pos_t cell = raw - pos; + + const float z_xmy0 = (z_x1y0 - z_x0y0) * RECIPROCAL(MESH_X_DIST), // z slope per x along y0 (lower left to lower right) + z_xmy1 = (z_x1y1 - z_x0y1) * RECIPROCAL(MESH_X_DIST); // z slope per x along y1 (upper left to upper right) + + float z_cxy0 = z_x0y0 + z_xmy0 * cell.x; // z height along y0 at cell.x (changes for each cell.x in cell) + + const float z_cxy1 = z_x0y1 + z_xmy1 * cell.x, // z height along y1 at cell.x + z_cxyd = z_cxy1 - z_cxy0; // z height difference along cell.x from y0 to y1 + + float z_cxym = z_cxyd * RECIPROCAL(MESH_Y_DIST); // z slope per y along cell.x from pos.y to y1 (changes for each cell.x in cell) + + // float z_cxcy = z_cxy0 + z_cxym * cell.y; // interpolated mesh z height along cell.x at cell.y (do inside the segment loop) + + // As subsequent segments step through this cell, the z_cxy0 intercept will change + // and the z_cxym slope will change, both as a function of cell.x within the cell, and + // each change by a constant for fixed segment lengths. + + const float z_sxy0 = z_xmy0 * diff.x, // per-segment adjustment to z_cxy0 + z_sxym = (z_xmy1 - z_xmy0) * RECIPROCAL(MESH_Y_DIST) * diff.x; // per-segment adjustment to z_cxym + + for (;;) { // for all segments within this mesh cell + + if (--segments == 0) raw = destination; // if this is last segment, use destination for exact + + const float z_cxcy = (z_cxy0 + z_cxym * cell.y) // interpolated mesh z height along cell.x at cell.y + TERN_(ENABLE_LEVELING_FADE_HEIGHT, * fade_scaling_factor); // apply fade factor to interpolated height + + const float oldz = raw.z; raw.z += z_cxcy; + planner.buffer_line(raw, scaled_fr_mm_s, active_extruder, hints); + raw.z = oldz; + + if (segments == 0) // done with last segment + return false; // didn't set current from destination + + raw += diff; + cell += diff; + + if (!WITHIN(cell.x, 0, MESH_X_DIST) || !WITHIN(cell.y, 0, MESH_Y_DIST)) // done within this cell, break to next + break; + + // Next segment still within same mesh cell, adjust the per-segment + // slope and intercept to compute next z height. + + z_cxy0 += z_sxy0; // adjust z_cxy0 by per-segment z_sxy0 + z_cxym += z_sxym; // adjust z_cxym by per-segment z_sxym + + } // segment loop + } // cell loop + + return false; // caller will update current_position + } + +#endif // UBL_SEGMENTED + +#endif // AUTO_BED_LEVELING_UBL diff --git a/src/feature/binary_stream.cpp b/src/feature/binary_stream.cpp new file mode 100644 index 0000000..81e1103 --- /dev/null +++ b/src/feature/binary_stream.cpp @@ -0,0 +1,36 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(BINARY_FILE_TRANSFER) + +#include "../sd/cardreader.h" +#include "binary_stream.h" + +char* SDFileTransferProtocol::Packet::Open::data = nullptr; +size_t SDFileTransferProtocol::data_waiting, SDFileTransferProtocol::transfer_timeout, SDFileTransferProtocol::idle_timeout; +bool SDFileTransferProtocol::transfer_active, SDFileTransferProtocol::dummy_transfer, SDFileTransferProtocol::compression; + +BinaryStream binaryStream[NUM_SERIAL]; + +#endif diff --git a/src/feature/binary_stream.h b/src/feature/binary_stream.h new file mode 100644 index 0000000..417e39c --- /dev/null +++ b/src/feature/binary_stream.h @@ -0,0 +1,456 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" + +#define BINARY_STREAM_COMPRESSION +#if ENABLED(BINARY_STREAM_COMPRESSION) + #include "../libs/heatshrink/heatshrink_decoder.h" + // STM32 (and others?) require a word-aligned buffer for SD card transfers via DMA + static __attribute__((aligned(sizeof(size_t)))) uint8_t decode_buffer[512] = {}; + static heatshrink_decoder hsd; +#endif + +inline bool bs_serial_data_available(const serial_index_t index) { + return SERIAL_IMPL.available(index); +} + +inline int bs_read_serial(const serial_index_t index) { + return SERIAL_IMPL.read(index); +} + +class SDFileTransferProtocol { +private: + struct Packet { + struct [[gnu::packed]] Open { + static bool validate(char *buffer, size_t length) { + return (length > sizeof(Open) && buffer[length - 1] == '\0'); + } + static Open& decode(char *buffer) { + data = &buffer[2]; + return *reinterpret_cast(buffer); + } + bool compression_enabled() { return compression & 0x1; } + bool dummy_transfer() { return dummy & 0x1; } + static char* filename() { return data; } + private: + uint8_t dummy, compression; + static char* data; // variable length strings complicate things + }; + }; + + static bool file_open(char *filename) { + if (!dummy_transfer) { + card.mount(); + card.openFileWrite(filename); + if (!card.isFileOpen()) return false; + } + transfer_active = true; + data_waiting = 0; + TERN_(BINARY_STREAM_COMPRESSION, heatshrink_decoder_reset(&hsd)); + return true; + } + + static bool file_write(char *buffer, const size_t length) { + #if ENABLED(BINARY_STREAM_COMPRESSION) + if (compression) { + size_t total_processed = 0, processed_count = 0; + HSD_poll_res presult; + + while (total_processed < length) { + heatshrink_decoder_sink(&hsd, reinterpret_cast(&buffer[total_processed]), length - total_processed, &processed_count); + total_processed += processed_count; + do { + presult = heatshrink_decoder_poll(&hsd, &decode_buffer[data_waiting], sizeof(decode_buffer) - data_waiting, &processed_count); + data_waiting += processed_count; + if (data_waiting == sizeof(decode_buffer)) { + if (!dummy_transfer) + if (card.write(decode_buffer, data_waiting) < 0) { + return false; + } + data_waiting = 0; + } + } while (presult == HSDR_POLL_MORE); + } + return true; + } + #endif + return (dummy_transfer || card.write(buffer, length) >= 0); + } + + static bool file_close() { + if (!dummy_transfer) { + #if ENABLED(BINARY_STREAM_COMPRESSION) + // flush any buffered data + if (data_waiting) { + if (card.write(decode_buffer, data_waiting) < 0) return false; + data_waiting = 0; + } + #endif + card.closefile(); + card.release(); + } + TERN_(BINARY_STREAM_COMPRESSION, heatshrink_decoder_finish(&hsd)); + transfer_active = false; + return true; + } + + static void transfer_abort() { + if (!dummy_transfer) { + card.closefile(); + card.removeFile(card.filename); + card.release(); + TERN_(BINARY_STREAM_COMPRESSION, heatshrink_decoder_finish(&hsd)); + } + transfer_active = false; + return; + } + + enum class FileTransfer : uint8_t { QUERY, OPEN, CLOSE, WRITE, ABORT }; + + static size_t data_waiting, transfer_timeout, idle_timeout; + static bool transfer_active, dummy_transfer, compression; + +public: + + static void idle() { + // If a transfer is interrupted and a file is left open, abort it after TIMEOUT ms + const millis_t ms = millis(); + if (transfer_active && ELAPSED(ms, idle_timeout)) { + idle_timeout = ms + IDLE_PERIOD; + if (ELAPSED(ms, transfer_timeout)) transfer_abort(); + } + } + + static void process(uint8_t packet_type, char *buffer, const uint16_t length) { + transfer_timeout = millis() + TIMEOUT; + switch (static_cast(packet_type)) { + case FileTransfer::QUERY: + SERIAL_ECHOPGM("PFT:version:", VERSION_MAJOR, ".", VERSION_MINOR, ".", VERSION_PATCH); + #if ENABLED(BINARY_STREAM_COMPRESSION) + SERIAL_ECHOLNPGM(":compression:heatshrink,", HEATSHRINK_STATIC_WINDOW_BITS, ",", HEATSHRINK_STATIC_LOOKAHEAD_BITS); + #else + SERIAL_ECHOLNPGM(":compression:none"); + #endif + break; + case FileTransfer::OPEN: + if (transfer_active) + SERIAL_ECHOLNPGM("PFT:busy"); + else { + if (Packet::Open::validate(buffer, length)) { + auto packet = Packet::Open::decode(buffer); + compression = packet.compression_enabled(); + dummy_transfer = packet.dummy_transfer(); + if (file_open(packet.filename())) { + SERIAL_ECHOLNPGM("PFT:success"); + break; + } + } + SERIAL_ECHOLNPGM("PFT:fail"); + } + break; + case FileTransfer::CLOSE: + if (transfer_active) { + if (file_close()) + SERIAL_ECHOLNPGM("PFT:success"); + else + SERIAL_ECHOLNPGM("PFT:ioerror"); + } + else SERIAL_ECHOLNPGM("PFT:invalid"); + break; + case FileTransfer::WRITE: + if (!transfer_active) + SERIAL_ECHOLNPGM("PFT:invalid"); + else if (!file_write(buffer, length)) + SERIAL_ECHOLNPGM("PFT:ioerror"); + break; + case FileTransfer::ABORT: + transfer_abort(); + SERIAL_ECHOLNPGM("PFT:success"); + break; + default: + SERIAL_ECHOLNPGM("PTF:invalid"); + break; + } + } + + static const uint16_t VERSION_MAJOR = 0, VERSION_MINOR = 1, VERSION_PATCH = 0, TIMEOUT = 10000, IDLE_PERIOD = 1000; +}; + +class BinaryStream { +public: + enum class Protocol : uint8_t { CONTROL, FILE_TRANSFER }; + + enum class ProtocolControl : uint8_t { SYNC = 1, CLOSE }; + + enum class StreamState : uint8_t { PACKET_RESET, PACKET_WAIT, PACKET_HEADER, PACKET_DATA, PACKET_FOOTER, + PACKET_PROCESS, PACKET_RESEND, PACKET_TIMEOUT, PACKET_ERROR }; + + struct Packet { // 10 byte protocol overhead, ascii with checksum and line number has a minimum of 7 increasing with line + + union Header { + static constexpr uint16_t HEADER_TOKEN = 0xB5AD; + struct [[gnu::packed]] { + uint16_t token; // packet start token + uint8_t sync; // stream sync, resend id and packet loss detection + uint8_t meta; // 4 bit protocol, + // 4 bit packet type + uint16_t size; // data length + uint16_t checksum; // header checksum + }; + uint8_t protocol() { return (meta >> 4) & 0xF; } + uint8_t type() { return meta & 0xF; } + void reset() { token = 0; sync = 0; meta = 0; size = 0; checksum = 0; } + uint8_t data[2]; + }; + + union Footer { + struct [[gnu::packed]] { + uint16_t checksum; // full packet checksum + }; + void reset() { checksum = 0; } + uint8_t data[1]; + }; + + Header header; + Footer footer; + uint32_t bytes_received; + uint16_t checksum, header_checksum; + millis_t timeout; + char* buffer; + + void reset() { + header.reset(); + footer.reset(); + bytes_received = 0; + checksum = 0; + header_checksum = 0; + timeout = millis() + PACKET_MAX_WAIT; + buffer = nullptr; + } + } packet{}; + + void reset() { + sync = 0; + packet_retries = 0; + buffer_next_index = 0; + } + + // fletchers 16 checksum + uint32_t checksum(uint32_t cs, uint8_t value) { + uint16_t cs_low = (((cs & 0xFF) + value) % 255); + return ((((cs >> 8) + cs_low) % 255) << 8) | cs_low; + } + + // read the next byte from the data stream keeping track of + // whether the stream times out from data starvation + // takes the data variable by reference in order to return status + bool stream_read(uint8_t& data) { + if (stream_state != StreamState::PACKET_WAIT && ELAPSED(millis(), packet.timeout)) { + stream_state = StreamState::PACKET_TIMEOUT; + return false; + } + if (!bs_serial_data_available(card.transfer_port_index)) return false; + data = bs_read_serial(card.transfer_port_index); + packet.timeout = millis() + PACKET_MAX_WAIT; + return true; + } + + template + void receive(char (&buffer)[buffer_size]) { + uint8_t data = 0; + millis_t transfer_window = millis() + RX_TIMESLICE; + + #if ENABLED(SDSUPPORT) + PORT_REDIRECT(SERIAL_PORTMASK(card.transfer_port_index)); + #endif + + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Warray-bounds" + + while (PENDING(millis(), transfer_window)) { + switch (stream_state) { + /** + * Data stream packet handling + */ + case StreamState::PACKET_RESET: + packet.reset(); + stream_state = StreamState::PACKET_WAIT; + case StreamState::PACKET_WAIT: + if (!stream_read(data)) { idle(); return; } // no active packet so don't wait + packet.header.data[1] = data; + if (packet.header.token == packet.header.HEADER_TOKEN) { + packet.bytes_received = 2; + stream_state = StreamState::PACKET_HEADER; + } + else { + // stream corruption drop data + packet.header.data[0] = data; + } + break; + case StreamState::PACKET_HEADER: + if (!stream_read(data)) break; + + packet.header.data[packet.bytes_received++] = data; + packet.checksum = checksum(packet.checksum, data); + + // header checksum calculation can't contain the checksum + if (packet.bytes_received == sizeof(Packet::header) - 2) + packet.header_checksum = packet.checksum; + + if (packet.bytes_received == sizeof(Packet::header)) { + if (packet.header.checksum == packet.header_checksum) { + // The SYNC control packet is a special case in that it doesn't require the stream sync to be correct + if (static_cast(packet.header.protocol()) == Protocol::CONTROL && static_cast(packet.header.type()) == ProtocolControl::SYNC) { + SERIAL_ECHOLNPGM("ss", sync, ",", buffer_size, ",", VERSION_MAJOR, ".", VERSION_MINOR, ".", VERSION_PATCH); + stream_state = StreamState::PACKET_RESET; + break; + } + if (packet.header.sync == sync) { + buffer_next_index = 0; + packet.bytes_received = 0; + if (packet.header.size) { + stream_state = StreamState::PACKET_DATA; + packet.buffer = static_cast(&buffer[0]); // multipacket buffering not implemented, always allocate whole buffer to packet + } + else + stream_state = StreamState::PACKET_PROCESS; + } + else if (packet.header.sync == sync - 1) { // ok response must have been lost + SERIAL_ECHOLNPGM("ok", packet.header.sync); // transmit valid packet received and drop the payload + stream_state = StreamState::PACKET_RESET; + } + else if (packet_retries) { + stream_state = StreamState::PACKET_RESET; // could be packets already buffered on flow controlled connections, drop them without ack + } + else { + SERIAL_ECHO_MSG("Datastream packet out of order"); + stream_state = StreamState::PACKET_RESEND; + } + } + else { + SERIAL_ECHO_MSG("Packet header(", packet.header.sync, "?) corrupt"); + stream_state = StreamState::PACKET_RESEND; + } + } + break; + case StreamState::PACKET_DATA: + if (!stream_read(data)) break; + + if (buffer_next_index < buffer_size) + packet.buffer[buffer_next_index] = data; + else { + SERIAL_ECHO_MSG("Datastream packet data buffer overrun"); + stream_state = StreamState::PACKET_ERROR; + break; + } + + packet.checksum = checksum(packet.checksum, data); + packet.bytes_received++; + buffer_next_index++; + + if (packet.bytes_received == packet.header.size) { + stream_state = StreamState::PACKET_FOOTER; + packet.bytes_received = 0; + } + break; + case StreamState::PACKET_FOOTER: + if (!stream_read(data)) break; + + packet.footer.data[packet.bytes_received++] = data; + if (packet.bytes_received == sizeof(Packet::footer)) { + if (packet.footer.checksum == packet.checksum) { + stream_state = StreamState::PACKET_PROCESS; + } + else { + SERIAL_ECHO_MSG("Packet(", packet.header.sync, ") payload corrupt"); + stream_state = StreamState::PACKET_RESEND; + } + } + break; + case StreamState::PACKET_PROCESS: + sync++; + packet_retries = 0; + bytes_received += packet.header.size; + + SERIAL_ECHOLNPGM("ok", packet.header.sync); // transmit valid packet received + dispatch(); + stream_state = StreamState::PACKET_RESET; + break; + case StreamState::PACKET_RESEND: + if (packet_retries < MAX_RETRIES || MAX_RETRIES == 0) { + packet_retries++; + stream_state = StreamState::PACKET_RESET; + SERIAL_ECHO_MSG("Resend request ", packet_retries); + SERIAL_ECHOLNPGM("rs", sync); + } + else + stream_state = StreamState::PACKET_ERROR; + break; + case StreamState::PACKET_TIMEOUT: + SERIAL_ECHO_MSG("Datastream timeout"); + stream_state = StreamState::PACKET_RESEND; + break; + case StreamState::PACKET_ERROR: + SERIAL_ECHOLNPGM("fe", packet.header.sync); + reset(); // reset everything, resync required + stream_state = StreamState::PACKET_RESET; + break; + } + } + + #pragma GCC diagnostic pop + } + + void dispatch() { + switch (static_cast(packet.header.protocol())) { + case Protocol::CONTROL: + switch (static_cast(packet.header.type())) { + case ProtocolControl::CLOSE: // revert back to ASCII mode + card.flag.binary_mode = false; + break; + default: + SERIAL_ECHO_MSG("Unknown BinaryProtocolControl Packet"); + } + break; + case Protocol::FILE_TRANSFER: + SDFileTransferProtocol::process(packet.header.type(), packet.buffer, packet.header.size); // send user data to be processed + break; + default: + SERIAL_ECHO_MSG("Unsupported Binary Protocol"); + } + } + + void idle() { + // Some Protocols may need periodic updates without new data + SDFileTransferProtocol::idle(); + } + + static const uint16_t PACKET_MAX_WAIT = 500, RX_TIMESLICE = 20, MAX_RETRIES = 0, VERSION_MAJOR = 0, VERSION_MINOR = 1, VERSION_PATCH = 0; + uint8_t packet_retries, sync; + uint16_t buffer_next_index; + uint32_t bytes_received; + StreamState stream_state = StreamState::PACKET_RESET; +}; + +extern BinaryStream binaryStream[NUM_SERIAL]; diff --git a/src/feature/bltouch.cpp b/src/feature/bltouch.cpp new file mode 100644 index 0000000..10d3131 --- /dev/null +++ b/src/feature/bltouch.cpp @@ -0,0 +1,196 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(BLTOUCH) + +#include "bltouch.h" + +BLTouch bltouch; + +bool BLTouch::od_5v_mode; // Initialized by settings.load, 0 = Open Drain; 1 = 5V Drain +#ifdef BLTOUCH_HS_MODE + bool BLTouch::high_speed_mode; // Initialized by settings.load, 0 = Low Speed; 1 = High Speed +#else + constexpr bool BLTouch::high_speed_mode; +#endif + +#include "../module/servo.h" +#include "../module/probe.h" + +void stop(); + +#define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) +#include "../core/debug_out.h" + +bool BLTouch::command(const BLTCommand cmd, const millis_t &ms) { + if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("BLTouch Command :", cmd); + servo[Z_PROBE_SERVO_NR].move(cmd); + safe_delay(_MAX(ms, (uint32_t)BLTOUCH_DELAY)); // BLTOUCH_DELAY is also the *minimum* delay + return triggered(); +} + +// Init the class and device. Call from setup(). +void BLTouch::init(const bool set_voltage/*=false*/) { + // Voltage Setting (if enabled). At every Marlin initialization: + // BLTOUCH < V3.0 and clones: This will be ignored by the probe + // BLTOUCH V3.0: SET_5V_MODE or SET_OD_MODE (if enabled). + // OD_MODE is the default on power on, but setting it does not hurt + // This mode will stay active until manual SET_OD_MODE or power cycle + // BLTOUCH V3.1: SET_5V_MODE or SET_OD_MODE (if enabled). + // At power on, the probe will default to the eeprom settings configured by the user + _reset(); + _stow(); + + #if ENABLED(BLTOUCH_FORCE_MODE_SET) + + constexpr bool should_set = true; + + #else + + #ifdef DEBUG_OUT + if (DEBUGGING(LEVELING)) { + PGMSTR(mode0, "OD"); + PGMSTR(mode1, "5V"); + DEBUG_ECHOPGM("BLTouch Mode: "); + DEBUG_ECHOPGM_P(bltouch.od_5v_mode ? mode1 : mode0); + DEBUG_ECHOLNPGM(" (Default " TERN(BLTOUCH_SET_5V_MODE, "5V", "OD") ")"); + } + #endif + + const bool should_set = od_5v_mode != ENABLED(BLTOUCH_SET_5V_MODE); + + #endif + + if (should_set && set_voltage) + mode_conv_proc(ENABLED(BLTOUCH_SET_5V_MODE)); +} + +void BLTouch::clear() { + _reset(); // RESET or RESET_SW will clear an alarm condition but... + // ...it will not clear a triggered condition in SW mode when the pin is currently up + // ANTClabs <-- CODE ERROR + _stow(); // STOW will pull up the pin and clear any triggered condition unless it fails, don't care + _deploy(); // DEPLOY to test the probe. Could fail, don't care + _stow(); // STOW to be ready for meaningful work. Could fail, don't care +} + +bool BLTouch::triggered() { return PROBE_TRIGGERED(); } + +bool BLTouch::deploy_proc() { + // Do a DEPLOY + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("BLTouch DEPLOY requested"); + + // Attempt to DEPLOY, wait for DEPLOY_DELAY or ALARM + if (_deploy_query_alarm()) { + // The deploy might have failed or the probe is already triggered (nozzle too low?) + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("BLTouch ALARM or TRIGGER after DEPLOY, recovering"); + + clear(); // Get the probe into start condition + + // Last attempt to DEPLOY + if (_deploy_query_alarm()) { + // The deploy might have failed or the probe is actually triggered (nozzle too low?) again + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("BLTouch Deploy Failed"); + probe.probe_error_stop(); // Something is wrong, needs action, but not too bad, allow restart + return true; // Tell our caller we goofed in case he cares to know + } + } + + // One of the recommended ANTClabs ways to probe, using SW MODE + TERN_(BLTOUCH_FORCE_SW_MODE, _set_SW_mode()); + + // Now the probe is ready to issue a 10ms pulse when the pin goes up. + // The trigger STOW (see motion.cpp for example) will pull up the probes pin as soon as the pulse + // is registered. + + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("bltouch.deploy_proc() end"); + + return false; // report success to caller +} + +bool BLTouch::stow_proc() { + // Do a STOW + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("BLTouch STOW requested"); + + // A STOW will clear a triggered condition in the probe (10ms pulse). + // At the moment that we come in here, we might (pulse) or will (SW mode) see the trigger on the pin. + // So even though we know a STOW will be ignored if an ALARM condition is active, we will STOW. + // Note: If the probe is deployed AND in an ALARM condition, this STOW will not pull up the pin + // and the ALARM condition will still be there. --> ANTClabs should change this behavior maybe + + // Attempt to STOW, wait for STOW_DELAY or ALARM + if (_stow_query_alarm()) { + // The stow might have failed + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("BLTouch ALARM or TRIGGER after STOW, recovering"); + + _reset(); // This RESET will then also pull up the pin. If it doesn't + // work and the pin is still down, there will no longer be + // an ALARM condition though. + // But one more STOW will catch that + // Last attempt to STOW + if (_stow_query_alarm()) { // so if there is now STILL an ALARM condition: + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("BLTouch Stow Failed"); + probe.probe_error_stop(); // Something is wrong, needs action, but not too bad, allow restart + return true; // Tell our caller we goofed in case he cares to know + } + } + + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("bltouch.stow_proc() end"); + + return false; // report success to caller +} + +bool BLTouch::status_proc() { + /** + * Return a TRUE for "YES, it is DEPLOYED" + * This function will ensure switch state is reset after execution + */ + + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("BLTouch STATUS requested"); + + _set_SW_mode(); // Incidentally, _set_SW_mode() will also RESET any active alarm + const bool tr = triggered(); // If triggered in SW mode, the pin is up, it is STOWED + + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("BLTouch is ", tr); + + if (tr) _stow(); else _deploy(); // Turn off SW mode, reset any trigger, honor pin state + return !tr; +} + +void BLTouch::mode_conv_proc(const bool M5V) { + /** + * BLTOUCH pre V3.0 and clones: No reaction at all to this sequence apart from a DEPLOY -> STOW + * BLTOUCH V3.0: This will set the mode (twice) and sadly, a STOW is needed at the end, because of the deploy + * BLTOUCH V3.1: This will set the mode and store it in the eeprom. The STOW is not needed but does not hurt + */ + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("BLTouch Set Mode - ", M5V); + _deploy(); + if (M5V) _set_5V_mode(); else _set_OD_mode(); + _mode_store(); + if (M5V) _set_5V_mode(); else _set_OD_mode(); + _stow(); + od_5v_mode = M5V; +} + +#endif // BLTOUCH diff --git a/src/feature/bltouch.h b/src/feature/bltouch.h new file mode 100644 index 0000000..fa857bb --- /dev/null +++ b/src/feature/bltouch.h @@ -0,0 +1,118 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfigPre.h" + +// BLTouch commands are sent as servo angles +typedef unsigned char BLTCommand; + +#define STOW_ALARM true +#define BLTOUCH_DEPLOY 10 +#define BLTOUCH_STOW 90 +#define BLTOUCH_SW_MODE 60 +#define BLTOUCH_SELFTEST 120 +#define BLTOUCH_MODE_STORE 130 +#define BLTOUCH_5V_MODE 140 +#define BLTOUCH_OD_MODE 150 +#define BLTOUCH_RESET 160 + +/** + * The following commands require different minimum delays. + * + * 500ms required for a reliable Reset. + * + * 750ms required for Deploy/Stow, otherwise the alarm state + * will not be seen until the following move command. + */ + +#ifndef BLTOUCH_SET5V_DELAY + #define BLTOUCH_SET5V_DELAY 150 +#endif +#ifndef BLTOUCH_SETOD_DELAY + #define BLTOUCH_SETOD_DELAY 150 +#endif +#ifndef BLTOUCH_MODE_STORE_DELAY + #define BLTOUCH_MODE_STORE_DELAY 150 +#endif +#ifndef BLTOUCH_DEPLOY_DELAY + #define BLTOUCH_DEPLOY_DELAY 750 +#endif +#ifndef BLTOUCH_STOW_DELAY + #define BLTOUCH_STOW_DELAY 750 +#endif +#ifndef BLTOUCH_RESET_DELAY + #define BLTOUCH_RESET_DELAY 500 +#endif + +class BLTouch { +public: + + static void init(const bool set_voltage=false); + static bool od_5v_mode; // Initialized by settings.load, 0 = Open Drain; 1 = 5V Drain + + #ifdef BLTOUCH_HS_MODE + static bool high_speed_mode; // Initialized by settings.load, 0 = Low Speed; 1 = High Speed + #else + static constexpr bool high_speed_mode = false; + #endif + + static float z_extra_clearance() { return high_speed_mode ? 7 : 0; } + + // DEPLOY and STOW are wrapped for error handling - these are used by homing and by probing + static bool deploy() { return deploy_proc(); } + static bool stow() { return stow_proc(); } + static bool status() { return status_proc(); } + + // Native BLTouch commands ("Underscore"...), used in lcd menus and internally + static void _reset() { command(BLTOUCH_RESET, BLTOUCH_RESET_DELAY); } + + static void _selftest() { command(BLTOUCH_SELFTEST, BLTOUCH_DELAY); } + + static void _set_SW_mode() { command(BLTOUCH_SW_MODE, BLTOUCH_DELAY); } + static void _reset_SW_mode() { if (triggered()) _stow(); else _deploy(); } + + static void _set_5V_mode() { command(BLTOUCH_5V_MODE, BLTOUCH_SET5V_DELAY); } + static void _set_OD_mode() { command(BLTOUCH_OD_MODE, BLTOUCH_SETOD_DELAY); } + static void _mode_store() { command(BLTOUCH_MODE_STORE, BLTOUCH_MODE_STORE_DELAY); } + + static void _deploy() { command(BLTOUCH_DEPLOY, BLTOUCH_DEPLOY_DELAY); } + static void _stow() { command(BLTOUCH_STOW, BLTOUCH_STOW_DELAY); } + + static void mode_conv_5V() { mode_conv_proc(true); } + static void mode_conv_OD() { mode_conv_proc(false); } + + static bool triggered(); + +private: + static bool _deploy_query_alarm() { return command(BLTOUCH_DEPLOY, BLTOUCH_DEPLOY_DELAY); } + static bool _stow_query_alarm() { return command(BLTOUCH_STOW, BLTOUCH_STOW_DELAY) == STOW_ALARM; } + + static void clear(); + static bool command(const BLTCommand cmd, const millis_t &ms); + static bool deploy_proc(); + static bool stow_proc(); + static bool status_proc(); + static void mode_conv_proc(const bool M5V); +}; + +extern BLTouch bltouch; diff --git a/src/feature/cancel_object.cpp b/src/feature/cancel_object.cpp new file mode 100644 index 0000000..bffd2bb --- /dev/null +++ b/src/feature/cancel_object.cpp @@ -0,0 +1,82 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(CANCEL_OBJECTS) + +#include "cancel_object.h" +#include "../gcode/gcode.h" +#include "../lcd/marlinui.h" + +CancelObject cancelable; + +int8_t CancelObject::object_count, // = 0 + CancelObject::active_object = -1; +uint32_t CancelObject::canceled; // = 0x0000 +bool CancelObject::skipping; // = false + +void CancelObject::set_active_object(const int8_t obj) { + active_object = obj; + if (WITHIN(obj, 0, 31)) { + if (obj >= object_count) object_count = obj + 1; + skipping = TEST(canceled, obj); + } + else + skipping = false; + + #if BOTH(HAS_STATUS_MESSAGE, CANCEL_OBJECTS_REPORTING) + if (active_object >= 0) + ui.status_printf(0, F(S_FMT " %i"), GET_TEXT(MSG_PRINTING_OBJECT), int(active_object)); + else + ui.reset_status(); + #endif +} + +void CancelObject::cancel_object(const int8_t obj) { + if (WITHIN(obj, 0, 31)) { + SBI(canceled, obj); + if (obj == active_object) skipping = true; + } +} + +void CancelObject::uncancel_object(const int8_t obj) { + if (WITHIN(obj, 0, 31)) { + CBI(canceled, obj); + if (obj == active_object) skipping = false; + } +} + +void CancelObject::report() { + if (active_object >= 0) + SERIAL_ECHO_MSG("Active Object: ", active_object); + + if (canceled) { + SERIAL_ECHO_START(); + SERIAL_ECHOPGM("Canceled:"); + for (int i = 0; i < object_count; i++) + if (TEST(canceled, i)) { SERIAL_CHAR(' '); SERIAL_ECHO(i); } + SERIAL_EOL(); + } +} + +#endif // CANCEL_OBJECTS diff --git a/src/feature/cancel_object.h b/src/feature/cancel_object.h new file mode 100644 index 0000000..62548a3 --- /dev/null +++ b/src/feature/cancel_object.h @@ -0,0 +1,41 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include + +class CancelObject { +public: + static bool skipping; + static int8_t object_count, active_object; + static uint32_t canceled; + static void set_active_object(const int8_t obj); + static void cancel_object(const int8_t obj); + static void uncancel_object(const int8_t obj); + static void report(); + static bool is_canceled(const int8_t obj) { return TEST(canceled, obj); } + static void clear_active_object() { set_active_object(-1); } + static void cancel_active_object() { cancel_object(active_object); } + static void reset() { canceled = 0x0000; object_count = 0; clear_active_object(); } +}; + +extern CancelObject cancelable; diff --git a/src/feature/caselight.cpp b/src/feature/caselight.cpp new file mode 100644 index 0000000..eb580a6 --- /dev/null +++ b/src/feature/caselight.cpp @@ -0,0 +1,103 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(CASE_LIGHT_ENABLE) + +#include "caselight.h" + +CaseLight caselight; + +#if CASELIGHT_USES_BRIGHTNESS && !defined(CASE_LIGHT_DEFAULT_BRIGHTNESS) + #define CASE_LIGHT_DEFAULT_BRIGHTNESS 0 // For use on PWM pin as non-PWM just sets a default +#endif + +#if CASELIGHT_USES_BRIGHTNESS + uint8_t CaseLight::brightness = CASE_LIGHT_DEFAULT_BRIGHTNESS; +#endif + +bool CaseLight::on = CASE_LIGHT_DEFAULT_ON; + +#if CASE_LIGHT_IS_COLOR_LED + constexpr uint8_t init_case_light[] = CASE_LIGHT_DEFAULT_COLOR; + LEDColor CaseLight::color = { init_case_light[0], init_case_light[1], init_case_light[2] OPTARG(HAS_WHITE_LED, init_case_light[3]) }; +#endif + +void CaseLight::update(const bool sflag) { + #if CASELIGHT_USES_BRIGHTNESS + /** + * The brightness_sav (and sflag) is needed because ARM chips ignore + * a "WRITE(CASE_LIGHT_PIN,x)" command to the pins that are directly + * controlled by the PWM module. In order to turn them off the brightness + * level needs to be set to OFF. Since we can't use the PWM register to + * save the last brightness level we need a variable to save it. + */ + static uint8_t brightness_sav; // Save brightness info for restore on "M355 S1" + + if (on || !sflag) + brightness_sav = brightness; // Save brightness except for M355 S0 + if (sflag && on) + brightness = brightness_sav; // Restore last brightness for M355 S1 + + const uint8_t i = on ? brightness : 0, n10ct = ENABLED(INVERT_CASE_LIGHT) ? 255 - i : i; + UNUSED(n10ct); + #endif + + #if CASE_LIGHT_IS_COLOR_LED + #if ENABLED(CASE_LIGHT_USE_NEOPIXEL) + if (on) + // Use current color of (NeoPixel) leds and new brightness level + leds.set_color(LEDColor(leds.color.r, leds.color.g, leds.color.b OPTARG(HAS_WHITE_LED, leds.color.w) OPTARG(NEOPIXEL_LED, n10ct))); + else + // Switch off leds + leds.set_off(); + #else + // Use CaseLight color (CASE_LIGHT_DEFAULT_COLOR) and new brightness level + leds.set_color(LEDColor(color.r, color.g, color.b OPTARG(HAS_WHITE_LED, color.w) OPTARG(NEOPIXEL_LED, n10ct))); + #endif + #else // !CASE_LIGHT_IS_COLOR_LED + + #if CASELIGHT_USES_BRIGHTNESS + if (pin_is_pwm()) + hal.set_pwm_duty(pin_t(CASE_LIGHT_PIN), ( + #if CASE_LIGHT_MAX_PWM == 255 + n10ct + #else + map(n10ct, 0, 255, 0, CASE_LIGHT_MAX_PWM) + #endif + )); + else + #endif + { + const bool s = on ? TERN(INVERT_CASE_LIGHT, LOW, HIGH) : TERN(INVERT_CASE_LIGHT, HIGH, LOW); + WRITE(CASE_LIGHT_PIN, s ? HIGH : LOW); + } + + #endif // !CASE_LIGHT_IS_COLOR_LED + + #if ENABLED(CASE_LIGHT_USE_RGB_LED) + if (leds.lights_on) leds.update(); else leds.set_off(); + #endif +} + +#endif // CASE_LIGHT_ENABLE diff --git a/src/feature/caselight.h b/src/feature/caselight.h new file mode 100644 index 0000000..17e1222 --- /dev/null +++ b/src/feature/caselight.h @@ -0,0 +1,57 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" + +#if CASE_LIGHT_IS_COLOR_LED + #include "leds/leds.h" // for LEDColor +#endif + +class CaseLight { +public: + static bool on; + #if ENABLED(CASELIGHT_USES_BRIGHTNESS) + static uint8_t brightness; + #endif + + static bool pin_is_pwm() { return TERN0(NEED_CASE_LIGHT_PIN, PWM_PIN(CASE_LIGHT_PIN)); } + static bool has_brightness() { return TERN0(CASELIGHT_USES_BRIGHTNESS, TERN(CASE_LIGHT_USE_NEOPIXEL, true, pin_is_pwm())); } + + static void init() { + #if NEED_CASE_LIGHT_PIN + if (pin_is_pwm()) SET_PWM(CASE_LIGHT_PIN); else SET_OUTPUT(CASE_LIGHT_PIN); + #endif + update_brightness(); + } + + static void update(const bool sflag); + static void update_brightness() { update(false); } + static void update_enabled() { update(true); } + + #if ENABLED(CASE_LIGHT_IS_COLOR_LED) + private: + static LEDColor color; + #endif +}; + +extern CaseLight caselight; diff --git a/src/feature/closedloop.cpp b/src/feature/closedloop.cpp new file mode 100644 index 0000000..1b9f711 --- /dev/null +++ b/src/feature/closedloop.cpp @@ -0,0 +1,44 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER) + +#if !PIN_EXISTS(CLOSED_LOOP_ENABLE) || !PIN_EXISTS(CLOSED_LOOP_MOVE_COMPLETE) + #error "CLOSED_LOOP_ENABLE_PIN and CLOSED_LOOP_MOVE_COMPLETE_PIN are required for EXTERNAL_CLOSED_LOOP_CONTROLLER." +#endif + +#include "closedloop.h" + +ClosedLoop closedloop; + +void ClosedLoop::init() { + OUT_WRITE(CLOSED_LOOP_ENABLE_PIN, LOW); + SET_INPUT_PULLUP(CLOSED_LOOP_MOVE_COMPLETE_PIN); +} + +void ClosedLoop::set(const byte val) { + OUT_WRITE(CLOSED_LOOP_ENABLE_PIN, val); +} + +#endif // EXTERNAL_CLOSED_LOOP_CONTROLLER diff --git a/src/feature/closedloop.h b/src/feature/closedloop.h new file mode 100644 index 0000000..e03400c --- /dev/null +++ b/src/feature/closedloop.h @@ -0,0 +1,32 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +class ClosedLoop { +public: + static void init(); + static void set(const byte val); +}; + +extern ClosedLoop closedloop; + +#define CLOSED_LOOP_WAITING() (READ(CLOSED_LOOP_ENABLE_PIN) && !READ(CLOSED_LOOP_MOVE_COMPLETE_PIN)) diff --git a/src/feature/controllerfan.cpp b/src/feature/controllerfan.cpp new file mode 100644 index 0000000..f42bf52 --- /dev/null +++ b/src/feature/controllerfan.cpp @@ -0,0 +1,86 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(USE_CONTROLLER_FAN) + +#include "controllerfan.h" +#include "../module/stepper.h" +#include "../module/temperature.h" + +ControllerFan controllerFan; + +uint8_t ControllerFan::speed; + +#if ENABLED(CONTROLLER_FAN_EDITABLE) + controllerFan_settings_t ControllerFan::settings; // {0} + #else + const controllerFan_settings_t &ControllerFan::settings = controllerFan_defaults; +#endif + +void ControllerFan::setup() { + SET_OUTPUT(CONTROLLER_FAN_PIN); + init(); +} + +void ControllerFan::set_fan_speed(const uint8_t s) { + speed = s < (CONTROLLERFAN_SPEED_MIN) ? 0 : s; // Fan OFF below minimum +} + +void ControllerFan::update() { + static millis_t lastMotorOn = 0, // Last time a motor was turned on + nextMotorCheck = 0; // Last time the state was checked + const millis_t ms = millis(); + if (ELAPSED(ms, nextMotorCheck)) { + nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s + + // If any triggers for the controller fan are true... + // - At least one stepper driver is enabled + // - The heated bed is enabled + // - TEMP_SENSOR_BOARD is reporting >= CONTROLLER_FAN_MIN_BOARD_TEMP + const ena_mask_t axis_mask = TERN(CONTROLLER_FAN_USE_Z_ONLY, _BV(Z_AXIS), (ena_mask_t)~TERN0(CONTROLLER_FAN_IGNORE_Z, _BV(Z_AXIS))); + if ( (stepper.axis_enabled.bits & axis_mask) + || TERN0(HAS_HEATED_BED, thermalManager.temp_bed.soft_pwm_amount > 0) + || TERN0(HAS_CONTROLLER_FAN_MIN_BOARD_TEMP, thermalManager.wholeDegBoard() >= CONTROLLER_FAN_MIN_BOARD_TEMP) + ) lastMotorOn = ms; //... set time to NOW so the fan will turn on + + // Fan Settings. Set fan > 0: + // - If AutoMode is on and steppers have been enabled for CONTROLLERFAN_IDLE_TIME seconds. + // - If System is on idle and idle fan speed settings is activated. + set_fan_speed( + settings.auto_mode && lastMotorOn && PENDING(ms, lastMotorOn + SEC_TO_MS(settings.duration)) + ? settings.active_speed : settings.idle_speed + ); + + #if ENABLED(FAN_SOFT_PWM) + thermalManager.soft_pwm_controller_speed = speed; + #else + if (PWM_PIN(CONTROLLER_FAN_PIN)) + hal.set_pwm_duty(pin_t(CONTROLLER_FAN_PIN), speed); + else + WRITE(CONTROLLER_FAN_PIN, speed > 0); + #endif + } +} + +#endif // USE_CONTROLLER_FAN diff --git a/src/feature/controllerfan.h b/src/feature/controllerfan.h new file mode 100644 index 0000000..55eb235 --- /dev/null +++ b/src/feature/controllerfan.h @@ -0,0 +1,72 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfigPre.h" + +typedef struct { + uint8_t active_speed, // 0-255 (fullspeed); Speed with enabled stepper motors + idle_speed; // 0-255 (fullspeed); Speed after idle period with all motors are disabled + uint16_t duration; // Duration in seconds for the fan to run after all motors are disabled + bool auto_mode; // Default true +} controllerFan_settings_t; + +#ifndef CONTROLLERFAN_SPEED_ACTIVE + #define CONTROLLERFAN_SPEED_ACTIVE 255 +#endif +#ifndef CONTROLLERFAN_SPEED_IDLE + #define CONTROLLERFAN_SPEED_IDLE 0 +#endif +#ifndef CONTROLLERFAN_IDLE_TIME + #define CONTROLLERFAN_IDLE_TIME 60 +#endif + +static constexpr controllerFan_settings_t controllerFan_defaults = { + CONTROLLERFAN_SPEED_ACTIVE, + CONTROLLERFAN_SPEED_IDLE, + CONTROLLERFAN_IDLE_TIME, + true +}; + +#if ENABLED(USE_CONTROLLER_FAN) + +class ControllerFan { + private: + static uint8_t speed; + static void set_fan_speed(const uint8_t s); + + public: + #if ENABLED(CONTROLLER_FAN_EDITABLE) + static controllerFan_settings_t settings; + #else + static const controllerFan_settings_t &settings; + #endif + static bool state() { return speed > 0; } + static void init() { reset(); } + static void reset() { TERN_(CONTROLLER_FAN_EDITABLE, settings = controllerFan_defaults); } + static void setup(); + static void update(); +}; + +extern ControllerFan controllerFan; + +#endif diff --git a/src/feature/cooler.cpp b/src/feature/cooler.cpp new file mode 100644 index 0000000..e0f9977 --- /dev/null +++ b/src/feature/cooler.cpp @@ -0,0 +1,48 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if EITHER(HAS_COOLER, LASER_COOLANT_FLOW_METER) + +#include "cooler.h" +Cooler cooler; + +#if HAS_COOLER + uint8_t Cooler::mode = 0; + uint16_t Cooler::capacity; + uint16_t Cooler::load; + bool Cooler::enabled = false; +#endif + +#if ENABLED(LASER_COOLANT_FLOW_METER) + bool Cooler::flowmeter = false; + millis_t Cooler::flowmeter_next_ms; // = 0 + volatile uint16_t Cooler::flowpulses; + float Cooler::flowrate; + #if ENABLED(FLOWMETER_SAFETY) + bool Cooler::flowsafety_enabled = true; + bool Cooler::flowfault = false; + #endif +#endif + +#endif // HAS_COOLER || LASER_COOLANT_FLOW_METER diff --git a/src/feature/cooler.h b/src/feature/cooler.h new file mode 100644 index 0000000..9891514 --- /dev/null +++ b/src/feature/cooler.h @@ -0,0 +1,109 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfigPre.h" + +#ifndef FLOWMETER_PPL + #define FLOWMETER_PPL 5880 // Pulses per liter +#endif +#ifndef FLOWMETER_INTERVAL + #define FLOWMETER_INTERVAL 1000 // milliseconds +#endif + +// Cooling device + +class Cooler { +public: + static uint16_t capacity; // Cooling capacity in watts + static uint16_t load; // Cooling load in watts + + static bool enabled; + static void enable() { enabled = true; } + static void disable() { enabled = false; } + static void toggle() { enabled = !enabled; } + + static uint8_t mode; // 0 = CO2 Liquid cooling, 1 = Laser Diode TEC Heatsink Cooling + static void set_mode(const uint8_t m) { mode = m; } + + #if ENABLED(LASER_COOLANT_FLOW_METER) + static float flowrate; // Flow meter reading in liters-per-minute. + static bool flowmeter; // Flag to monitor the flow + static volatile uint16_t flowpulses; // Flowmeter IRQ pulse count + static millis_t flowmeter_next_ms; // Next time at which to calculate flow + + static void set_flowmeter(const bool sflag) { + if (flowmeter != sflag) { + flowmeter = sflag; + if (sflag) { + flowpulses = 0; + flowmeter_next_ms = millis() + FLOWMETER_INTERVAL; + } + } + } + + // To calculate flow we only need to count pulses + static void flowmeter_ISR() { flowpulses++; } + + // Enable / Disable the flow meter interrupt + static void flowmeter_interrupt_enable() { + attachInterrupt(digitalPinToInterrupt(FLOWMETER_PIN), flowmeter_ISR, RISING); + } + static void flowmeter_interrupt_disable() { + detachInterrupt(digitalPinToInterrupt(FLOWMETER_PIN)); + } + + // Enable / Disable the flow meter interrupt + static void flowmeter_enable() { set_flowmeter(true); flowpulses = 0; flowmeter_interrupt_enable(); } + static void flowmeter_disable() { set_flowmeter(false); flowmeter_interrupt_disable(); flowpulses = 0; } + + // Get the total flow (in liters per minute) since the last reading + static void calc_flowrate() { + // flowrate = (litres) * (seconds) = litres per minute + flowrate = (flowpulses / (float)FLOWMETER_PPL) * ((1000.0f / (float)FLOWMETER_INTERVAL) * 60.0f); + flowpulses = 0; + } + + // Userland task to update the flow meter + static void flowmeter_task(const millis_t ms=millis()) { + if (!flowmeter) // !! The flow meter must always be on !! + flowmeter_enable(); // Init and prime + if (ELAPSED(ms, flowmeter_next_ms)) { + calc_flowrate(); + flowmeter_next_ms = ms + FLOWMETER_INTERVAL; + } + } + + #if ENABLED(FLOWMETER_SAFETY) + static bool flowfault; // Flag that the cooler is in a fault state + static bool flowsafety_enabled; // Flag to disable the cutter if flow rate is too low + static void flowsafety_toggle() { flowsafety_enabled = !flowsafety_enabled; } + static bool check_flow_too_low() { + const bool too_low = flowsafety_enabled && flowrate < (FLOWMETER_MIN_LITERS_PER_MINUTE); + flowfault = too_low; + return too_low; + } + #endif + #endif +}; + +extern Cooler cooler; diff --git a/src/feature/dac/dac_dac084s085.cpp b/src/feature/dac/dac_dac084s085.cpp new file mode 100644 index 0000000..772bb68 --- /dev/null +++ b/src/feature/dac/dac_dac084s085.cpp @@ -0,0 +1,97 @@ +/*************************************************************** + * + * External DAC for Alligator Board + * + ****************************************************************/ + +#include "../../inc/MarlinConfig.h" + +#if MB(ALLIGATOR) + +#include "dac_dac084s085.h" + +#include "../../MarlinCore.h" +#include "../../HAL/shared/Delay.h" + +dac084s085::dac084s085() { } + +void dac084s085::begin() { + uint8_t externalDac_buf[] = { 0x20, 0x00 }; // all off + + // All SPI chip-select HIGH + SET_OUTPUT(DAC0_SYNC_PIN); + #if HAS_MULTI_EXTRUDER + SET_OUTPUT(DAC1_SYNC_PIN); + #endif + cshigh(); + spiBegin(); + + //init onboard DAC + DELAY_US(2); + WRITE(DAC0_SYNC_PIN, LOW); + DELAY_US(2); + WRITE(DAC0_SYNC_PIN, HIGH); + DELAY_US(2); + WRITE(DAC0_SYNC_PIN, LOW); + + spiSend(SPI_CHAN_DAC, externalDac_buf, COUNT(externalDac_buf)); + WRITE(DAC0_SYNC_PIN, HIGH); + + #if HAS_MULTI_EXTRUDER + //init Piggy DAC + DELAY_US(2); + WRITE(DAC1_SYNC_PIN, LOW); + DELAY_US(2); + WRITE(DAC1_SYNC_PIN, HIGH); + DELAY_US(2); + WRITE(DAC1_SYNC_PIN, LOW); + + spiSend(SPI_CHAN_DAC, externalDac_buf, COUNT(externalDac_buf)); + WRITE(DAC1_SYNC_PIN, HIGH); + #endif + + return; +} + +void dac084s085::setValue(const uint8_t channel, const uint8_t value) { + if (channel >= 7) return; // max channel (X,Y,Z,E0,E1,E2,E3) + + const uint8_t externalDac_buf[] = { + 0x10 | ((channel > 3 ? 7 : 3) - channel << 6) | (value >> 4), + 0x00 | (value << 4) + }; + + // All SPI chip-select HIGH + cshigh(); + + if (channel > 3) { // DAC Piggy E1,E2,E3 + WRITE(DAC1_SYNC_PIN, LOW); + DELAY_US(2); + WRITE(DAC1_SYNC_PIN, HIGH); + DELAY_US(2); + WRITE(DAC1_SYNC_PIN, LOW); + } + else { // DAC onboard X,Y,Z,E0 + WRITE(DAC0_SYNC_PIN, LOW); + DELAY_US(2); + WRITE(DAC0_SYNC_PIN, HIGH); + DELAY_US(2); + WRITE(DAC0_SYNC_PIN, LOW); + } + + DELAY_US(2); + spiSend(SPI_CHAN_DAC, externalDac_buf, COUNT(externalDac_buf)); +} + +void dac084s085::cshigh() { + WRITE(DAC0_SYNC_PIN, HIGH); + #if HAS_MULTI_EXTRUDER + WRITE(DAC1_SYNC_PIN, HIGH); + #endif + WRITE(SPI_EEPROM1_CS_PIN, HIGH); + WRITE(SPI_EEPROM2_CS_PIN, HIGH); + WRITE(SPI_FLASH_CS_PIN, HIGH); + WRITE(SD_SS_PIN, HIGH); +} + +#endif // MB(ALLIGATOR) diff --git a/src/feature/dac/dac_dac084s085.h b/src/feature/dac/dac_dac084s085.h new file mode 100644 index 0000000..5be0129 --- /dev/null +++ b/src/feature/dac/dac_dac084s085.h @@ -0,0 +1,31 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +class dac084s085 { + public: + dac084s085(); + static void begin(); + static void setValue(const uint8_t channel, const uint8_t value); + private: + static void cshigh(); +}; diff --git a/src/feature/dac/dac_mcp4728.cpp b/src/feature/dac/dac_mcp4728.cpp new file mode 100644 index 0000000..6f5a9ee --- /dev/null +++ b/src/feature/dac/dac_mcp4728.cpp @@ -0,0 +1,154 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * mcp4728.cpp - Arduino library for MicroChip MCP4728 I2C D/A converter + * + * For implementation details, please take a look at the datasheet: + * https://ww1.microchip.com/downloads/en/DeviceDoc/22187a.pdf + * + * For discussion and feedback, please go to: + * https://forum.arduino.cc/index.php/topic,51842.0.html + */ + +#include "../../inc/MarlinConfig.h" + +#if HAS_MOTOR_CURRENT_DAC + +#include "dac_mcp4728.h" + +MCP4728 mcp4728; + +xyze_uint_t dac_values; + +/** + * Begin I2C, get current values (input register and eeprom) of mcp4728 + */ +void MCP4728::init() { + Wire.begin(); + Wire.requestFrom(I2C_ADDRESS(DAC_DEV_ADDRESS), uint8_t(24)); + while (Wire.available()) { + char deviceID = Wire.read(), + hiByte = Wire.read(), + loByte = Wire.read(); + + if (!(deviceID & 0x08)) + dac_values[(deviceID & 0x30) >> 4] = word((hiByte & 0x0F), loByte); + } +} + +/** + * Write input resister value to specified channel using fastwrite method. + * Channel : 0-3, Values : 0-4095 + */ +uint8_t MCP4728::analogWrite(const uint8_t channel, const uint16_t value) { + dac_values[channel] = value; + return fastWrite(); +} + +/** + * Write all input resistor values to EEPROM using SequentialWrite method. + * This will update both input register and EEPROM value + * This will also write current Vref, PowerDown, Gain settings to EEPROM + */ +uint8_t MCP4728::eepromWrite() { + Wire.beginTransmission(I2C_ADDRESS(DAC_DEV_ADDRESS)); + Wire.write(SEQWRITE); + LOOP_LOGICAL_AXES(i) { + Wire.write(DAC_STEPPER_VREF << 7 | DAC_STEPPER_GAIN << 4 | highByte(dac_values[i])); + Wire.write(lowByte(dac_values[i])); + } + return Wire.endTransmission(); +} + +/** + * Write Voltage reference setting to all input registers + */ +uint8_t MCP4728::setVref_all(const uint8_t value) { + Wire.beginTransmission(I2C_ADDRESS(DAC_DEV_ADDRESS)); + Wire.write(VREFWRITE | (value ? 0x0F : 0x00)); + return Wire.endTransmission(); +} +/** + * Write Gain setting to all input registers + */ +uint8_t MCP4728::setGain_all(const uint8_t value) { + Wire.beginTransmission(I2C_ADDRESS(DAC_DEV_ADDRESS)); + Wire.write(GAINWRITE | (value ? 0x0F : 0x00)); + return Wire.endTransmission(); +} + +/** + * Return Input Register value + */ +uint16_t MCP4728::getValue(const uint8_t channel) { return dac_values[channel]; } + +#if 0 +/** + * Steph: Might be useful in the future + * Return Vout + */ +uint16_t MCP4728::getVout(const uint8_t channel) { + const uint32_t vref = 2048, + vOut = (vref * dac_values[channel] * (_DAC_STEPPER_GAIN + 1)) / 4096; + return _MIN(vOut, defaultVDD); +} +#endif + +/** + * Returns DAC values as a 0-100 percentage of drive strength + */ +uint8_t MCP4728::getDrvPct(const uint8_t channel) { return uint8_t(100.0 * dac_values[channel] / (DAC_STEPPER_MAX) + 0.5); } + +/** + * Receives all Drive strengths as 0-100 percent values, updates + * DAC Values array and calls fastwrite to update the DAC. + */ +void MCP4728::setDrvPct(xyze_uint_t &pct) { + dac_values = pct * (DAC_STEPPER_MAX) * 0.01f; + fastWrite(); +} + +/** + * FastWrite input register values - All DAC output update. refer to DATASHEET 5.6.1 + * DAC Input and PowerDown bits update. + * No EEPROM update + */ +uint8_t MCP4728::fastWrite() { + Wire.beginTransmission(I2C_ADDRESS(DAC_DEV_ADDRESS)); + LOOP_LOGICAL_AXES(i) { + Wire.write(highByte(dac_values[i])); + Wire.write(lowByte(dac_values[i])); + } + return Wire.endTransmission(); +} + +/** + * Common function for simple general commands + */ +uint8_t MCP4728::simpleCommand(const byte simpleCommand) { + Wire.beginTransmission(I2C_ADDRESS(GENERALCALL)); + Wire.write(simpleCommand); + return Wire.endTransmission(); +} + +#endif // HAS_MOTOR_CURRENT_DAC diff --git a/src/feature/dac/dac_mcp4728.h b/src/feature/dac/dac_mcp4728.h new file mode 100644 index 0000000..3a7d5f1 --- /dev/null +++ b/src/feature/dac/dac_mcp4728.h @@ -0,0 +1,82 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * Arduino library for MicroChip MCP4728 I2C D/A converter. + */ + +#include "../../core/types.h" + +#include + +/** + * The following three macros are only used in this piece of code related to mcp4728. + * They are defined in the standard Arduino framework but could be undefined in 32 bits Arduino frameworks. + * (For instance not defined in Arduino lpc176x framework) + * So we have to define them if needed. + */ +#ifndef word + #define word(h, l) ((uint8_t) ((h << 8) | l)) +#endif + +#ifndef lowByte + #define lowByte(w) ((uint8_t) ((w) & 0xFF)) +#endif + +#ifndef highByte + #define highByte(w) ((uint8_t) ((w) >> 8)) +#endif + +#define defaultVDD DAC_STEPPER_MAX //was 5000 but differs with internal Vref +#define BASE_ADDR 0x60 +#define RESET 0b00000110 +#define WAKE 0b00001001 +#define UPDATE 0b00001000 +#define MULTIWRITE 0b01000000 +#define SINGLEWRITE 0b01011000 +#define SEQWRITE 0b01010000 +#define VREFWRITE 0b10000000 +#define GAINWRITE 0b11000000 +#define POWERDOWNWRITE 0b10100000 +#define GENERALCALL 0b00000000 +#define GAINWRITE 0b11000000 + +// This is taken from the original lib, makes it easy to edit if needed +// DAC_OR_ADDRESS defined in pins_BOARD.h file +#define DAC_DEV_ADDRESS (BASE_ADDR | DAC_OR_ADDRESS) + +class MCP4728 { +public: + static void init(); + static uint8_t analogWrite(const uint8_t channel, const uint16_t value); + static uint8_t eepromWrite(); + static uint8_t setVref_all(const uint8_t value); + static uint8_t setGain_all(const uint8_t value); + static uint16_t getValue(const uint8_t channel); + static uint8_t fastWrite(); + static uint8_t simpleCommand(const byte simpleCommand); + static uint8_t getDrvPct(const uint8_t channel); + static void setDrvPct(xyze_uint_t &pct); +}; + +extern MCP4728 mcp4728; diff --git a/src/feature/dac/stepper_dac.cpp b/src/feature/dac/stepper_dac.cpp new file mode 100644 index 0000000..f5664bc --- /dev/null +++ b/src/feature/dac/stepper_dac.cpp @@ -0,0 +1,102 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * stepper_dac.cpp - To set stepper current via DAC + */ + +#include "../../inc/MarlinConfig.h" + +#if HAS_MOTOR_CURRENT_DAC + +#include "stepper_dac.h" + +bool dac_present = false; +constexpr xyze_uint8_t dac_order = DAC_STEPPER_ORDER; +xyze_uint_t dac_channel_pct = DAC_MOTOR_CURRENT_DEFAULT; + +StepperDAC stepper_dac; + +int StepperDAC::init() { + #if PIN_EXISTS(DAC_DISABLE) + OUT_WRITE(DAC_DISABLE_PIN, LOW); // set pin low to enable DAC + #endif + + mcp4728.init(); + + if (mcp4728.simpleCommand(RESET)) return -1; + + dac_present = true; + + mcp4728.setVref_all(DAC_STEPPER_VREF); + mcp4728.setGain_all(DAC_STEPPER_GAIN); + + if (mcp4728.getDrvPct(0) < 1 || mcp4728.getDrvPct(1) < 1 || mcp4728.getDrvPct(2) < 1 || mcp4728.getDrvPct(3) < 1) { + mcp4728.setDrvPct(dac_channel_pct); + mcp4728.eepromWrite(); + } + + return 0; +} + +void StepperDAC::set_current_value(const uint8_t channel, uint16_t val) { + if (!(dac_present && channel < LOGICAL_AXES)) return; + + NOMORE(val, uint16_t(DAC_STEPPER_MAX)); + + mcp4728.analogWrite(dac_order[channel], val); + mcp4728.simpleCommand(UPDATE); +} + +void StepperDAC::set_current_percent(const uint8_t channel, float val) { + set_current_value(channel, _MIN(val, 100.0f) * (DAC_STEPPER_MAX) / 100.0f); +} + +static float dac_perc(int8_t n) { return mcp4728.getDrvPct(dac_order[n]); } +static float dac_amps(int8_t n) { return mcp4728.getValue(dac_order[n]) * 0.125 * RECIPROCAL(DAC_STEPPER_SENSE * 1000); } + +uint8_t StepperDAC::get_current_percent(const AxisEnum axis) { return mcp4728.getDrvPct(dac_order[axis]); } +void StepperDAC::set_current_percents(xyze_uint8_t &pct) { + LOOP_LOGICAL_AXES(i) dac_channel_pct[i] = pct[dac_order[i]]; + mcp4728.setDrvPct(dac_channel_pct); +} + +void StepperDAC::print_values() { + if (!dac_present) return; + SERIAL_ECHO_MSG("Stepper current values in % (Amps):"); + SERIAL_ECHO_START(); + LOOP_LOGICAL_AXES(a) { + SERIAL_CHAR(' ', IAXIS_CHAR(a), ':'); + SERIAL_ECHO(dac_perc(a)); + SERIAL_ECHOPGM_P(PSTR(" ("), dac_amps(AxisEnum(a)), PSTR(")")); + } + #if HAS_EXTRUDERS + SERIAL_ECHOLNPGM_P(SP_E_LBL, dac_perc(E_AXIS), PSTR(" ("), dac_amps(E_AXIS), PSTR(")")); + #endif +} + +void StepperDAC::commit_eeprom() { + if (!dac_present) return; + mcp4728.eepromWrite(); +} + +#endif // HAS_MOTOR_CURRENT_DAC diff --git a/src/feature/dac/stepper_dac.h b/src/feature/dac/stepper_dac.h new file mode 100644 index 0000000..26a0f2f --- /dev/null +++ b/src/feature/dac/stepper_dac.h @@ -0,0 +1,41 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * stepper_dac.h - To set stepper current via DAC + */ + +#include "dac_mcp4728.h" + +class StepperDAC { +public: + static int init(); + static void set_current_percent(const uint8_t channel, float val); + static void set_current_value(const uint8_t channel, uint16_t val); + static void print_values(); + static void commit_eeprom(); + static uint8_t get_current_percent(const AxisEnum axis); + static void set_current_percents(xyze_uint8_t &pct); +}; + +extern StepperDAC stepper_dac; diff --git a/src/feature/digipot/digipot.h b/src/feature/digipot/digipot.h new file mode 100644 index 0000000..3fbd1f3 --- /dev/null +++ b/src/feature/digipot/digipot.h @@ -0,0 +1,33 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +// +// Header for MCP4018 and MCP4451 current control i2c devices +// +class DigipotI2C { +public: + static void init(); + static void set_current(const uint8_t channel, const float current); +}; + +extern DigipotI2C digipot_i2c; diff --git a/src/feature/digipot/digipot_mcp4018.cpp b/src/feature/digipot/digipot_mcp4018.cpp new file mode 100644 index 0000000..3f2ecbf --- /dev/null +++ b/src/feature/digipot/digipot_mcp4018.cpp @@ -0,0 +1,108 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../../inc/MarlinConfig.h" + +#if ENABLED(DIGIPOT_MCP4018) + +#include "digipot.h" + +#include +#include // https://github.com/felias-fogg/SlowSoftI2CMaster + +// Settings for the I2C based DIGIPOT (MCP4018) based on WT150 + +#ifndef DIGIPOT_A4988_Rsx + #define DIGIPOT_A4988_Rsx 0.250 +#endif +#ifndef DIGIPOT_A4988_Vrefmax + #define DIGIPOT_A4988_Vrefmax 1.666 +#endif +#define DIGIPOT_MCP4018_MAX_VALUE 127 + +#define DIGIPOT_A4988_Itripmax(Vref) ((Vref) / (8.0 * DIGIPOT_A4988_Rsx)) + +#define DIGIPOT_A4988_FACTOR ((DIGIPOT_MCP4018_MAX_VALUE) / DIGIPOT_A4988_Itripmax(DIGIPOT_A4988_Vrefmax)) +#define DIGIPOT_A4988_MAX_CURRENT 2.0 + +static byte current_to_wiper(const float current) { + const int16_t value = TERN(DIGIPOT_USE_RAW_VALUES, current, CEIL(current * DIGIPOT_A4988_FACTOR)); + return byte(constrain(value, 0, DIGIPOT_MCP4018_MAX_VALUE)); +} + +static SlowSoftI2CMaster pots[DIGIPOT_I2C_NUM_CHANNELS] = { + SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_X, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) + #if DIGIPOT_I2C_NUM_CHANNELS > 1 + , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_Y, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) + #if DIGIPOT_I2C_NUM_CHANNELS > 2 + , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_Z, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) + #if DIGIPOT_I2C_NUM_CHANNELS > 3 + , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_E0, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) + #if DIGIPOT_I2C_NUM_CHANNELS > 4 + , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_E1, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) + #if DIGIPOT_I2C_NUM_CHANNELS > 5 + , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_E2, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) + #if DIGIPOT_I2C_NUM_CHANNELS > 6 + , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_E3, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) + #if DIGIPOT_I2C_NUM_CHANNELS > 7 + , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_E4, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) + #endif + #endif + #endif + #endif + #endif + #endif + #endif +}; + +static void digipot_i2c_send(const uint8_t channel, const byte v) { + if (WITHIN(channel, 0, DIGIPOT_I2C_NUM_CHANNELS - 1)) { + pots[channel].i2c_start(((DIGIPOT_I2C_ADDRESS_A) << 1) | I2C_WRITE); + pots[channel].i2c_write(v); + pots[channel].i2c_stop(); + } +} + +// This is for the MCP4018 I2C based digipot +void DigipotI2C::set_current(const uint8_t channel, const float current) { + const float ival = _MIN(_MAX(current, 0), float(DIGIPOT_MCP4018_MAX_VALUE)); + digipot_i2c_send(channel, current_to_wiper(ival)); +} + +void DigipotI2C::init() { + LOOP_L_N(i, DIGIPOT_I2C_NUM_CHANNELS) pots[i].i2c_init(); + + // Init currents according to Configuration_adv.h + static const float digipot_motor_current[] PROGMEM = + #if ENABLED(DIGIPOT_USE_RAW_VALUES) + DIGIPOT_MOTOR_CURRENT + #else + DIGIPOT_I2C_MOTOR_CURRENTS + #endif + ; + LOOP_L_N(i, COUNT(digipot_motor_current)) + set_current(i, pgm_read_float(&digipot_motor_current[i])); +} + +DigipotI2C digipot_i2c; + +#endif // DIGIPOT_MCP4018 diff --git a/src/feature/digipot/digipot_mcp4451.cpp b/src/feature/digipot/digipot_mcp4451.cpp new file mode 100644 index 0000000..ba5ecda --- /dev/null +++ b/src/feature/digipot/digipot_mcp4451.cpp @@ -0,0 +1,103 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../../inc/MarlinConfig.h" + +#if ENABLED(DIGIPOT_MCP4451) + +#include "digipot.h" + +#include +#include + +#if MB(MKS_SBASE) + #include "digipot_mcp4451_I2C_routines.h" +#endif + +// Settings for the I2C based DIGIPOT (MCP4451) on Azteeg X3 Pro +#if MB(5DPRINT) + #define DIGIPOT_I2C_FACTOR 117.96f + #define DIGIPOT_I2C_MAX_CURRENT 1.736f +#elif MB(AZTEEG_X5_MINI, AZTEEG_X5_MINI_WIFI) + #define DIGIPOT_I2C_FACTOR 113.5f + #define DIGIPOT_I2C_MAX_CURRENT 2.0f +#elif MB(AZTEEG_X5_GT) + #define DIGIPOT_I2C_FACTOR 51.0f + #define DIGIPOT_I2C_MAX_CURRENT 3.0f +#else + #define DIGIPOT_I2C_FACTOR 106.7f + #define DIGIPOT_I2C_MAX_CURRENT 2.5f +#endif + +static byte current_to_wiper(const float current) { + return byte(TERN(DIGIPOT_USE_RAW_VALUES, current, CEIL(DIGIPOT_I2C_FACTOR * current))); +} + +static void digipot_i2c_send(const byte addr, const byte a, const byte b) { + #if MB(MKS_SBASE) + digipot_mcp4451_start(addr); + digipot_mcp4451_send_byte(a); + digipot_mcp4451_send_byte(b); + #else + Wire.beginTransmission(I2C_ADDRESS(addr)); + Wire.write(a); + Wire.write(b); + Wire.endTransmission(); + #endif +} + +// This is for the MCP4451 I2C based digipot +void DigipotI2C::set_current(const uint8_t channel, const float current) { + // These addresses are specific to Azteeg X3 Pro, can be set to others. + // In this case first digipot is at address A0=0, A1=0, second one is at A0=0, A1=1 + const byte addr = channel < 4 ? DIGIPOT_I2C_ADDRESS_A : DIGIPOT_I2C_ADDRESS_B; // channel 0-3 vs 4-7 + + // Initial setup + digipot_i2c_send(addr, 0x40, 0xFF); + digipot_i2c_send(addr, 0xA0, 0xFF); + + // Set actual wiper value + byte addresses[4] = { 0x00, 0x10, 0x60, 0x70 }; + digipot_i2c_send(addr, addresses[channel & 0x3], current_to_wiper(_MIN(float(_MAX(current, 0)), DIGIPOT_I2C_MAX_CURRENT))); +} + +void DigipotI2C::init() { + #if MB(MKS_SBASE) + configure_i2c(16); // Set clock_option to 16 ensure I2C is initialized at 400kHz + #else + Wire.begin(); + #endif + // Set up initial currents as defined in Configuration_adv.h + static const float digipot_motor_current[] PROGMEM = + #if ENABLED(DIGIPOT_USE_RAW_VALUES) + DIGIPOT_MOTOR_CURRENT + #else + DIGIPOT_I2C_MOTOR_CURRENTS + #endif + ; + LOOP_L_N(i, COUNT(digipot_motor_current)) + set_current(i, pgm_read_float(&digipot_motor_current[i])); +} + +DigipotI2C digipot_i2c; + +#endif // DIGIPOT_MCP4451 diff --git a/src/feature/direct_stepping.cpp b/src/feature/direct_stepping.cpp new file mode 100644 index 0000000..13cf71e --- /dev/null +++ b/src/feature/direct_stepping.cpp @@ -0,0 +1,264 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(DIRECT_STEPPING) + +#include "direct_stepping.h" + +#include "../MarlinCore.h" + +#define CHECK_PAGE(I, R) do{ \ + if (I >= sizeof(page_states) / sizeof(page_states[0])) { \ + fatal_error = true; \ + return R; \ + } \ +}while(0) + +#define CHECK_PAGE_STATE(I, R, S) do { \ + CHECK_PAGE(I, R); \ + if (page_states[I] != S) { \ + fatal_error = true; \ + return R; \ + } \ +}while(0) + +namespace DirectStepping { + + template + State SerialPageManager::state; + + template + volatile bool SerialPageManager::fatal_error; + + template + volatile PageState SerialPageManager::page_states[Cfg::PAGE_COUNT]; + + template + volatile bool SerialPageManager::page_states_dirty; + + template + uint8_t SerialPageManager::pages[Cfg::PAGE_COUNT][Cfg::PAGE_SIZE]; + + template + uint8_t SerialPageManager::checksum; + + template + typename Cfg::write_byte_idx_t SerialPageManager::write_byte_idx; + + template + typename Cfg::page_idx_t SerialPageManager::write_page_idx; + + template + typename Cfg::write_byte_idx_t SerialPageManager::write_page_size; + + template + void SerialPageManager::init() { + for (int i = 0 ; i < Cfg::PAGE_COUNT ; i++) + page_states[i] = PageState::FREE; + + fatal_error = false; + state = State::NEWLINE; + + page_states_dirty = false; + + SERIAL_ECHOLNPGM("pages_ready"); + } + + template + FORCE_INLINE bool SerialPageManager::maybe_store_rxd_char(uint8_t c) { + switch (state) { + default: + case State::MONITOR: + switch (c) { + case '\n': + case '\r': + state = State::NEWLINE; + default: + return false; + } + case State::NEWLINE: + switch (c) { + case Cfg::CONTROL_CHAR: + state = State::ADDRESS; + return true; + case '\n': + case '\r': + state = State::NEWLINE; + return false; + default: + state = State::MONITOR; + return false; + } + case State::ADDRESS: + //TODO: 16 bit address, State::ADDRESS2 + write_page_idx = c; + write_byte_idx = 0; + checksum = 0; + + CHECK_PAGE(write_page_idx, true); + + if (page_states[write_page_idx] == PageState::FAIL) { + // Special case for fail + state = State::UNFAIL; + return true; + } + + set_page_state(write_page_idx, PageState::WRITING); + + state = Cfg::DIRECTIONAL ? State::COLLECT : State::SIZE; + + return true; + case State::SIZE: + // Zero means full page size + write_page_size = c; + state = State::COLLECT; + return true; + case State::COLLECT: + pages[write_page_idx][write_byte_idx++] = c; + checksum ^= c; + + // check if still collecting + if (Cfg::PAGE_SIZE == 256) { + // special case for 8-bit, check if rolled back to 0 + if (Cfg::DIRECTIONAL || !write_page_size) { // full 256 bytes + if (write_byte_idx) return true; + } + else if (write_byte_idx < write_page_size) + return true; + } + else if (Cfg::DIRECTIONAL) { + if (write_byte_idx != Cfg::PAGE_SIZE) + return true; + } + else if (write_byte_idx < write_page_size) + return true; + + state = State::CHECKSUM; + return true; + case State::CHECKSUM: { + const PageState page_state = (checksum == c) ? PageState::OK : PageState::FAIL; + set_page_state(write_page_idx, page_state); + state = State::MONITOR; + return true; + } + case State::UNFAIL: + if (c == 0) + set_page_state(write_page_idx, PageState::FREE); + else + fatal_error = true; + state = State::MONITOR; + return true; + } + } + + template + void SerialPageManager::write_responses() { + if (fatal_error) { + kill(GET_TEXT_F(MSG_BAD_PAGE)); + return; + } + + if (!page_states_dirty) return; + page_states_dirty = false; + + SERIAL_CHAR(Cfg::CONTROL_CHAR); + constexpr int state_bits = 2; + constexpr int n_bytes = Cfg::PAGE_COUNT >> state_bits; + volatile uint8_t bits_b[n_bytes] = { 0 }; + + for (page_idx_t i = 0 ; i < Cfg::PAGE_COUNT ; i++) { + bits_b[i >> state_bits] |= page_states[i] << ((i * state_bits) & 0x7); + } + + uint8_t crc = 0; + for (uint8_t i = 0 ; i < n_bytes ; i++) { + crc ^= bits_b[i]; + SERIAL_CHAR(bits_b[i]); + } + + SERIAL_CHAR(crc); + SERIAL_EOL(); + } + + template + FORCE_INLINE void SerialPageManager::set_page_state(const page_idx_t page_idx, const PageState page_state) { + CHECK_PAGE(page_idx,); + + page_states[page_idx] = page_state; + page_states_dirty = true; + } + + template <> + FORCE_INLINE uint8_t *PageManager::get_page(const page_idx_t page_idx) { + CHECK_PAGE(page_idx, nullptr); + + return pages[page_idx]; + } + + template <> + FORCE_INLINE void PageManager::free_page(const page_idx_t page_idx) { + set_page_state(page_idx, PageState::FREE); + } + +}; + +DirectStepping::PageManager page_manager; + +const uint8_t segment_table[DirectStepping::Config::NUM_SEGMENTS][DirectStepping::Config::SEGMENT_STEPS] PROGMEM = { + + #if STEPPER_PAGE_FORMAT == SP_4x4D_128 + + { 1, 1, 1, 1, 1, 1, 1 }, // 0 = -7 + { 1, 1, 1, 0, 1, 1, 1 }, // 1 = -6 + { 1, 1, 1, 0, 1, 0, 1 }, // 2 = -5 + { 1, 1, 0, 1, 0, 1, 0 }, // 3 = -4 + { 1, 1, 0, 0, 1, 0, 0 }, // 4 = -3 + { 0, 0, 1, 0, 0, 0, 1 }, // 5 = -2 + { 0, 0, 0, 1, 0, 0, 0 }, // 6 = -1 + { 0, 0, 0, 0, 0, 0, 0 }, // 7 = 0 + { 0, 0, 0, 1, 0, 0, 0 }, // 8 = 1 + { 0, 0, 1, 0, 0, 0, 1 }, // 9 = 2 + { 1, 1, 0, 0, 1, 0, 0 }, // 10 = 3 + { 1, 1, 0, 1, 0, 1, 0 }, // 11 = 4 + { 1, 1, 1, 0, 1, 0, 1 }, // 12 = 5 + { 1, 1, 1, 0, 1, 1, 1 }, // 13 = 6 + { 1, 1, 1, 1, 1, 1, 1 }, // 14 = 7 + { 0 } + + #elif STEPPER_PAGE_FORMAT == SP_4x2_256 + + { 0, 0, 0 }, // 0 + { 0, 1, 0 }, // 1 + { 1, 0, 1 }, // 2 + { 1, 1, 1 }, // 3 + + #elif STEPPER_PAGE_FORMAT == SP_4x1_512 + + {0} // Uncompressed format, table not used + + #endif + +}; + +#endif // DIRECT_STEPPING diff --git a/src/feature/direct_stepping.h b/src/feature/direct_stepping.h new file mode 100644 index 0000000..9623102 --- /dev/null +++ b/src/feature/direct_stepping.h @@ -0,0 +1,133 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" + +namespace DirectStepping { + + enum State : char { + MONITOR, NEWLINE, ADDRESS, SIZE, COLLECT, CHECKSUM, UNFAIL + }; + + enum PageState : uint8_t { + FREE, WRITING, OK, FAIL + }; + + // Static state used for stepping through direct stepping pages + struct page_step_state_t { + // Current page + uint8_t *page; + // Current segment + uint16_t segment_idx; + // Current steps within segment + uint8_t segment_steps; + // Segment delta + xyze_uint8_t sd; + // Block delta + xyze_int_t bd; + }; + + template + class SerialPageManager { + public: + + typedef typename Cfg::page_idx_t page_idx_t; + + static bool maybe_store_rxd_char(uint8_t c); + static void write_responses(); + + // common methods for page managers + static void init(); + static uint8_t *get_page(const page_idx_t page_idx); + static void free_page(const page_idx_t page_idx); + + protected: + + typedef typename Cfg::write_byte_idx_t write_byte_idx_t; + + static State state; + static volatile bool fatal_error; + + static volatile PageState page_states[Cfg::PAGE_COUNT]; + static volatile bool page_states_dirty; + + static uint8_t pages[Cfg::PAGE_COUNT][Cfg::PAGE_SIZE]; + static uint8_t checksum; + static write_byte_idx_t write_byte_idx; + static page_idx_t write_page_idx; + static write_byte_idx_t write_page_size; + + static void set_page_state(const page_idx_t page_idx, const PageState page_state); + }; + + template struct TypeSelector { typedef T type;} ; + template struct TypeSelector { typedef F type; }; + + template + struct config_t { + static constexpr char CONTROL_CHAR = '!'; + + static constexpr int PAGE_COUNT = num_pages; + static constexpr int AXIS_COUNT = num_axes; + static constexpr int BITS_SEGMENT = bits_segment; + static constexpr int DIRECTIONAL = dir ? 1 : 0; + static constexpr int SEGMENTS = segments; + + static constexpr int NUM_SEGMENTS = _BV(BITS_SEGMENT); + static constexpr int SEGMENT_STEPS = _BV(BITS_SEGMENT - DIRECTIONAL) - 1; + static constexpr int TOTAL_STEPS = SEGMENT_STEPS * SEGMENTS; + static constexpr int PAGE_SIZE = (AXIS_COUNT * BITS_SEGMENT * SEGMENTS) / 8; + + typedef typename TypeSelector<(PAGE_SIZE>256), uint16_t, uint8_t>::type write_byte_idx_t; + typedef typename TypeSelector<(PAGE_COUNT>256), uint16_t, uint8_t>::type page_idx_t; + }; + + template + using SP_4x4D_128 = config_t; + + template + using SP_4x2_256 = config_t; + + template + using SP_4x1_512 = config_t; + + // configured types + typedef STEPPER_PAGE_FORMAT Config; + + template class PAGE_MANAGER; + typedef PAGE_MANAGER PageManager; +}; + +#define SP_4x4D_128 1 +//#define SP_4x4_128 2 +//#define SP_4x2D_256 3 +#define SP_4x2_256 4 +#define SP_4x1_512 5 + +typedef typename DirectStepping::Config::page_idx_t page_idx_t; + +// TODO: use config +typedef DirectStepping::page_step_state_t page_step_state_t; + +extern const uint8_t segment_table[DirectStepping::Config::NUM_SEGMENTS][DirectStepping::Config::SEGMENT_STEPS]; +extern DirectStepping::PageManager page_manager; diff --git a/src/feature/e_parser.cpp b/src/feature/e_parser.cpp new file mode 100644 index 0000000..d98afcf --- /dev/null +++ b/src/feature/e_parser.cpp @@ -0,0 +1,45 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * e_parser.cpp - Intercept special commands directly in the serial stream + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(EMERGENCY_PARSER) + +#include "e_parser.h" + +// Static data members +bool EmergencyParser::killed_by_M112, // = false + EmergencyParser::quickstop_by_M410, + EmergencyParser::enabled; + +#if ENABLED(HOST_PROMPT_SUPPORT) + uint8_t EmergencyParser::M876_reason; // = 0 +#endif + +// Global instance +EmergencyParser emergency_parser; + +#endif // EMERGENCY_PARSER diff --git a/src/feature/e_parser.h b/src/feature/e_parser.h new file mode 100644 index 0000000..fda1ba1 --- /dev/null +++ b/src/feature/e_parser.h @@ -0,0 +1,225 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * e_parser.h - Intercept special commands directly in the serial stream + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(HOST_PROMPT_SUPPORT) + #include "host_actions.h" +#endif + +// External references +extern bool wait_for_user, wait_for_heatup; + +#if ENABLED(REALTIME_REPORTING_COMMANDS) + // From motion.h, which cannot be included here + void report_current_position_moving(); + void quickpause_stepper(); + void quickresume_stepper(); +#endif + +#if ENABLED(SOFT_RESET_VIA_SERIAL) + void HAL_reboot(); +#endif + +class EmergencyParser { + +public: + + // Currently looking for: M108, M112, M410, M876 S[0-9], S000, P000, R000 + enum State : uint8_t { + EP_RESET, + EP_N, + EP_M, + EP_M1, + EP_M10, EP_M108, + EP_M11, EP_M112, + EP_M4, EP_M41, EP_M410, + #if ENABLED(HOST_PROMPT_SUPPORT) + EP_M8, EP_M87, EP_M876, EP_M876S, EP_M876SN, + #endif + #if ENABLED(REALTIME_REPORTING_COMMANDS) + EP_S, EP_S0, EP_S00, EP_GRBL_STATUS, + EP_R, EP_R0, EP_R00, EP_GRBL_RESUME, + EP_P, EP_P0, EP_P00, EP_GRBL_PAUSE, + #endif + #if ENABLED(SOFT_RESET_VIA_SERIAL) + EP_ctrl, + EP_K, EP_KI, EP_KIL, EP_KILL, + #endif + EP_IGNORE // to '\n' + }; + + static bool killed_by_M112; + static bool quickstop_by_M410; + + #if ENABLED(HOST_PROMPT_SUPPORT) + static uint8_t M876_reason; + #endif + + EmergencyParser() { enable(); } + + FORCE_INLINE static void enable() { enabled = true; } + FORCE_INLINE static void disable() { enabled = false; } + + FORCE_INLINE static void update(State &state, const uint8_t c) { + switch (state) { + case EP_RESET: + switch (c) { + case ' ': case '\n': case '\r': break; + case 'N': state = EP_N; break; + case 'M': state = EP_M; break; + #if ENABLED(REALTIME_REPORTING_COMMANDS) + case 'S': state = EP_S; break; + case 'P': state = EP_P; break; + case 'R': state = EP_R; break; + #endif + #if ENABLED(SOFT_RESET_VIA_SERIAL) + case '^': state = EP_ctrl; break; + case 'K': state = EP_K; break; + #endif + default: state = EP_IGNORE; + } + break; + + case EP_N: + switch (c) { + case '0' ... '9': + case '-': case ' ': break; + case 'M': state = EP_M; break; + #if ENABLED(REALTIME_REPORTING_COMMANDS) + case 'S': state = EP_S; break; + case 'P': state = EP_P; break; + case 'R': state = EP_R; break; + #endif + default: state = EP_IGNORE; + } + break; + + #if ENABLED(REALTIME_REPORTING_COMMANDS) + case EP_S: state = (c == '0') ? EP_S0 : EP_IGNORE; break; + case EP_S0: state = (c == '0') ? EP_S00 : EP_IGNORE; break; + case EP_S00: state = (c == '0') ? EP_GRBL_STATUS : EP_IGNORE; break; + + case EP_R: state = (c == '0') ? EP_R0 : EP_IGNORE; break; + case EP_R0: state = (c == '0') ? EP_R00 : EP_IGNORE; break; + case EP_R00: state = (c == '0') ? EP_GRBL_RESUME : EP_IGNORE; break; + + case EP_P: state = (c == '0') ? EP_P0 : EP_IGNORE; break; + case EP_P0: state = (c == '0') ? EP_P00 : EP_IGNORE; break; + case EP_P00: state = (c == '0') ? EP_GRBL_PAUSE : EP_IGNORE; break; + #endif + + #if ENABLED(SOFT_RESET_VIA_SERIAL) + case EP_ctrl: state = (c == 'X') ? EP_KILL : EP_IGNORE; break; + case EP_K: state = (c == 'I') ? EP_KI : EP_IGNORE; break; + case EP_KI: state = (c == 'L') ? EP_KIL : EP_IGNORE; break; + case EP_KIL: state = (c == 'L') ? EP_KILL : EP_IGNORE; break; + #endif + + case EP_M: + switch (c) { + case ' ': break; + case '1': state = EP_M1; break; + case '4': state = EP_M4; break; + #if ENABLED(HOST_PROMPT_SUPPORT) + case '8': state = EP_M8; break; + #endif + default: state = EP_IGNORE; + } + break; + + case EP_M1: + switch (c) { + case '0': state = EP_M10; break; + case '1': state = EP_M11; break; + default: state = EP_IGNORE; + } + break; + + case EP_M10: state = (c == '8') ? EP_M108 : EP_IGNORE; break; + case EP_M11: state = (c == '2') ? EP_M112 : EP_IGNORE; break; + case EP_M4: state = (c == '1') ? EP_M41 : EP_IGNORE; break; + case EP_M41: state = (c == '0') ? EP_M410 : EP_IGNORE; break; + + #if ENABLED(HOST_PROMPT_SUPPORT) + + case EP_M8: state = (c == '7') ? EP_M87 : EP_IGNORE; break; + case EP_M87: state = (c == '6') ? EP_M876 : EP_IGNORE; break; + + case EP_M876: + switch (c) { + case ' ': break; + case 'S': state = EP_M876S; break; + default: state = EP_IGNORE; break; + } + break; + + case EP_M876S: + switch (c) { + case ' ': break; + case '0' ... '9': + state = EP_M876SN; + M876_reason = uint8_t(c - '0'); + break; + } + break; + + #endif + + case EP_IGNORE: + if (ISEOL(c)) state = EP_RESET; + break; + + default: + if (ISEOL(c)) { + if (enabled) switch (state) { + case EP_M108: wait_for_user = wait_for_heatup = false; break; + case EP_M112: killed_by_M112 = true; break; + case EP_M410: quickstop_by_M410 = true; break; + #if ENABLED(HOST_PROMPT_SUPPORT) + case EP_M876SN: hostui.handle_response(M876_reason); break; + #endif + #if ENABLED(REALTIME_REPORTING_COMMANDS) + case EP_GRBL_STATUS: report_current_position_moving(); break; + case EP_GRBL_PAUSE: quickpause_stepper(); break; + case EP_GRBL_RESUME: quickresume_stepper(); break; + #endif + #if ENABLED(SOFT_RESET_VIA_SERIAL) + case EP_KILL: HAL_reboot(); break; + #endif + default: break; + } + state = EP_RESET; + } + } + } + +private: + static bool enabled; +}; + +extern EmergencyParser emergency_parser; diff --git a/src/feature/easythreed_ui.cpp b/src/feature/easythreed_ui.cpp new file mode 100644 index 0000000..b15daff --- /dev/null +++ b/src/feature/easythreed_ui.cpp @@ -0,0 +1,236 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(EASYTHREED_UI) + +#include "easythreed_ui.h" +#include "pause.h" +#include "../module/temperature.h" +#include "../module/printcounter.h" +#include "../sd/cardreader.h" +#include "../gcode/queue.h" +#include "../module/motion.h" +#include "../module/planner.h" +#include "../MarlinCore.h" + +EasythreedUI easythreed_ui; + +#define BTN_DEBOUNCE_MS 20 + +void EasythreedUI::init() { + SET_INPUT_PULLUP(BTN_HOME); SET_OUTPUT(BTN_HOME_GND); + SET_INPUT_PULLUP(BTN_FEED); SET_OUTPUT(BTN_FEED_GND); + SET_INPUT_PULLUP(BTN_RETRACT); SET_OUTPUT(BTN_RETRACT_GND); + SET_INPUT_PULLUP(BTN_PRINT); + SET_OUTPUT(EASYTHREED_LED_PIN); +} + +void EasythreedUI::run() { + blinkLED(); + loadButton(); + printButton(); +} + +enum LEDInterval : uint16_t { + LED_OFF = 0, + LED_ON = 4000, + LED_BLINK_0 = 2500, + LED_BLINK_1 = 1500, + LED_BLINK_2 = 1000, + LED_BLINK_3 = 800, + LED_BLINK_4 = 500, + LED_BLINK_5 = 300, + LED_BLINK_6 = 150, + LED_BLINK_7 = 50 +}; + +uint16_t blink_interval_ms = LED_ON; // Status LED on Start button + +void EasythreedUI::blinkLED() { + static millis_t prev_blink_interval_ms = 0, blink_start_ms = 0; + + if (blink_interval_ms == LED_OFF) { WRITE(EASYTHREED_LED_PIN, HIGH); return; } // OFF + if (blink_interval_ms >= LED_ON) { WRITE(EASYTHREED_LED_PIN, LOW); return; } // ON + + const millis_t ms = millis(); + if (prev_blink_interval_ms != blink_interval_ms) { + prev_blink_interval_ms = blink_interval_ms; + blink_start_ms = ms; + } + if (PENDING(ms, blink_start_ms + blink_interval_ms)) + WRITE(EASYTHREED_LED_PIN, LOW); + else if (PENDING(ms, blink_start_ms + 2 * blink_interval_ms)) + WRITE(EASYTHREED_LED_PIN, HIGH); + else + blink_start_ms = ms; +} + +// +// Filament Load/Unload Button +// Load/Unload buttons are a 3 position switch with a common center ground. +// +void EasythreedUI::loadButton() { + if (printingIsActive()) return; + + enum FilamentStatus : uint8_t { FS_IDLE, FS_PRESS, FS_CHECK, FS_PROCEED }; + static uint8_t filament_status = FS_IDLE; + static millis_t filament_time = 0; + + switch (filament_status) { + + case FS_IDLE: + if (!READ(BTN_RETRACT) || !READ(BTN_FEED)) { // If feed/retract switch is toggled... + filament_status++; // ...proceed to next test. + filament_time = millis(); + } + break; + + case FS_PRESS: + if (ELAPSED(millis(), filament_time + BTN_DEBOUNCE_MS)) { // After a short debounce delay... + if (!READ(BTN_RETRACT) || !READ(BTN_FEED)) { // ...if switch still toggled... + thermalManager.setTargetHotend(EXTRUDE_MINTEMP + 10, 0); // Start heating up + blink_interval_ms = LED_BLINK_7; // Set the LED to blink fast + filament_status++; + } + else + filament_status = FS_IDLE; // Switch not toggled long enough + } + break; + + case FS_CHECK: + if (READ(BTN_RETRACT) && READ(BTN_FEED)) { // Switch in center position (stop) + blink_interval_ms = LED_ON; // LED on steady + filament_status = FS_IDLE; + thermalManager.disable_all_heaters(); + } + else if (thermalManager.hotEnoughToExtrude(0)) { // Is the hotend hot enough to move material? + filament_status++; // Proceed to feed / retract. + blink_interval_ms = LED_BLINK_5; // Blink ~3 times per second + } + break; + + case FS_PROCEED: { + // Feed or Retract just once. Hard abort all moves and return to idle on swicth release. + static bool flag = false; + if (READ(BTN_RETRACT) && READ(BTN_FEED)) { // Switch in center position (stop) + flag = false; // Restore flag to false + filament_status = FS_IDLE; // Go back to idle state + quickstop_stepper(); // Hard-stop all the steppers ... now! + thermalManager.disable_all_heaters(); // And disable all the heaters + blink_interval_ms = LED_ON; + } + else if (!flag) { + flag = true; + queue.inject(!READ(BTN_RETRACT) ? F("G91\nG0 E10 F180\nG0 E-120 F180\nM104 S0") : F("G91\nG0 E100 F120\nM104 S0")); + } + } break; + } + +} + +#if HAS_STEPPER_RESET + void disableStepperDrivers(); +#endif + +// +// Print Start/Pause/Resume Button +// +void EasythreedUI::printButton() { + enum KeyStatus : uint8_t { KS_IDLE, KS_PRESS, KS_PROCEED }; + static uint8_t key_status = KS_IDLE; + static millis_t key_time = 0; + + enum PrintFlag : uint8_t { PF_START, PF_PAUSE, PF_RESUME }; + static PrintFlag print_key_flag = PF_START; + + const millis_t ms = millis(); + + switch (key_status) { + case KS_IDLE: + if (!READ(BTN_PRINT)) { // Print/Pause/Resume button pressed? + key_time = ms; // Save start time + key_status++; // Go to debounce test + } + break; + + case KS_PRESS: + if (ELAPSED(ms, key_time + BTN_DEBOUNCE_MS)) // Wait for debounce interval to expire + key_status = READ(BTN_PRINT) ? KS_IDLE : KS_PROCEED; // Proceed if still pressed + break; + + case KS_PROCEED: + if (!READ(BTN_PRINT)) break; // Wait for the button to be released + key_status = KS_IDLE; // Ready for the next press + if (PENDING(ms, key_time + 1200 - BTN_DEBOUNCE_MS)) { // Register a press < 1.2 seconds + switch (print_key_flag) { + case PF_START: { // The "Print" button starts an SD card print + if (printingIsActive()) break; // Already printing? (find another line that checks for 'is planner doing anything else right now?') + blink_interval_ms = LED_BLINK_2; // Blink the indicator LED at 1 second intervals + print_key_flag = PF_PAUSE; // The "Print" button now pauses the print + card.mount(); // Force SD card to mount - now! + if (!card.isMounted) { // Failed to mount? + blink_interval_ms = LED_OFF; // Turn off LED + print_key_flag = PF_START; + return; // Bail out + } + card.ls(); // List all files to serial output + const uint16_t filecnt = card.countFilesInWorkDir(); // Count printable files in cwd + if (filecnt == 0) return; // None are printable? + card.selectFileByIndex(filecnt); // Select the last file according to current sort options + card.openAndPrintFile(card.filename); // Start printing it + break; + } + case PF_PAUSE: { // Pause printing (not currently firing) + if (!printingIsActive()) break; + blink_interval_ms = LED_ON; // Set indicator to steady ON + queue.inject(F("M25")); // Queue Pause + print_key_flag = PF_RESUME; // The "Print" button now resumes the print + break; + } + case PF_RESUME: { // Resume printing + if (printingIsActive()) break; + blink_interval_ms = LED_BLINK_2; // Blink the indicator LED at 1 second intervals + queue.inject(F("M24")); // Queue resume + print_key_flag = PF_PAUSE; // The "Print" button now pauses the print + break; + } + } + } + else { // Register a longer press + if (print_key_flag == PF_START && !printingIsActive()) { // While not printing, this moves Z up 10mm + blink_interval_ms = LED_ON; + queue.inject(F("G91\nG0 Z10 F600\nG90")); // Raise Z soon after returning to main loop + } + else { // While printing, cancel print + card.abortFilePrintSoon(); // There is a delay while the current steps play out + blink_interval_ms = LED_OFF; // Turn off LED + } + planner.synchronize(); // Wait for commands already in the planner to finish + TERN_(HAS_STEPPER_RESET, disableStepperDrivers()); // Disable all steppers - now! + print_key_flag = PF_START; // The "Print" button now starts a new print + } + break; + } +} +#endif // EASYTHREED_UI diff --git a/src/feature/easythreed_ui.h b/src/feature/easythreed_ui.h new file mode 100644 index 0000000..af9ad2d --- /dev/null +++ b/src/feature/easythreed_ui.h @@ -0,0 +1,35 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +class EasythreedUI { + public: + static void init(); + static void run(); + + private: + static void blinkLED(); + static void loadButton(); + static void printButton(); +}; + +extern EasythreedUI easythreed_ui; diff --git a/src/feature/encoder_i2c.cpp b/src/feature/encoder_i2c.cpp new file mode 100644 index 0000000..092ce0f --- /dev/null +++ b/src/feature/encoder_i2c.cpp @@ -0,0 +1,1128 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +//todo: add support for multiple encoders on a single axis +//todo: add z axis auto-leveling +//todo: consolidate some of the related M codes? +//todo: add endstop-replacement mode? +//todo: try faster I2C speed; tweak TWI_FREQ (400000L, or faster?); or just TWBR = ((CPU_FREQ / 400000L) - 16) / 2; +//todo: consider Marlin-optimized Wire library; i.e. MarlinWire, like MarlinSerial + + +#include "../inc/MarlinConfig.h" + +#if ENABLED(I2C_POSITION_ENCODERS) + +#include "encoder_i2c.h" + +#include "../module/stepper.h" +#include "../gcode/parser.h" + +#include "../feature/babystep.h" + +#include + +I2CPositionEncodersMgr I2CPEM; + +void I2CPositionEncoder::init(const uint8_t address, const AxisEnum axis) { + encoderAxis = axis; + i2cAddress = address; + + initialized = true; + + SERIAL_ECHOLNPGM("Setting up encoder on ", AS_CHAR(AXIS_CHAR(encoderAxis)), " axis, addr = ", address); + + position = get_position(); +} + +void I2CPositionEncoder::update() { + if (!initialized || !homed || !active) return; //check encoder is set up and active + + position = get_position(); + + //we don't want to stop things just because the encoder missed a message, + //so we only care about responses that indicate bad magnetic strength + + if (!passes_test(false)) { //check encoder data is good + lastErrorTime = millis(); + /* + if (trusted) { //commented out as part of the note below + trusted = false; + SERIAL_ECHOLNPGM("Fault detected on ", AS_CHAR(AXIS_CHAR(encoderAxis)), " axis encoder. Disengaging error correction until module is trusted again."); + } + */ + return; + } + + if (!trusted) { + /** + * This is commented out because it introduces error and can cause bad print quality. + * + * This code is intended to manage situations where the encoder has reported bad magnetic strength. + * This indicates that the magnetic strip was too far away from the sensor to reliably track position. + * When this happens, this code resets the offset based on where the printer thinks it is. This has been + * shown to introduce errors in actual position which result in drifting prints and poor print quality. + * Perhaps a better method would be to disable correction on the axis with a problem, report it to the + * user via the status leds on the encoder module and prompt the user to re-home the axis at which point + * the encoder would be re-enabled. + */ + + #if 0 + // If the magnetic strength has been good for a certain time, start trusting the module again + + if (millis() - lastErrorTime > I2CPE_TIME_TRUSTED) { + trusted = true; + + SERIAL_ECHOLNPGM("Untrusted encoder module on ", AS_CHAR(AXIS_CHAR(encoderAxis)), " axis has been fault-free for set duration, reinstating error correction."); + + //the encoder likely lost its place when the error occurred, so we'll reset and use the printer's + //idea of where it the axis is to re-initialize + const float pos = planner.get_axis_position_mm(encoderAxis); + int32_t positionInTicks = pos * get_ticks_unit(); + + //shift position from previous to current position + zeroOffset -= (positionInTicks - get_position()); + + #ifdef I2CPE_DEBUG + SERIAL_ECHOLNPGM("Current position is ", pos); + SERIAL_ECHOLNPGM("Position in encoder ticks is ", positionInTicks); + SERIAL_ECHOLNPGM("New zero-offset of ", zeroOffset); + SERIAL_ECHOPGM("New position reads as ", get_position()); + SERIAL_CHAR('('); + SERIAL_DECIMAL(mm_from_count(get_position())); + SERIAL_ECHOLNPGM(")"); + #endif + } + #endif + return; + } + + lastPosition = position; + const millis_t positionTime = millis(); + + //only do error correction if setup and enabled + if (ec && ecMethod != I2CPE_ECM_NONE) { + + #ifdef I2CPE_EC_THRESH_PROPORTIONAL + const millis_t deltaTime = positionTime - lastPositionTime; + const uint32_t distance = ABS(position - lastPosition), + speed = distance / deltaTime; + const float threshold = constrain((speed / 50), 1, 50) * ecThreshold; + #else + const float threshold = get_error_correct_threshold(); + #endif + + //check error + #if ENABLED(I2CPE_ERR_ROLLING_AVERAGE) + float sum = 0, diffSum = 0; + + errIdx = (errIdx >= I2CPE_ERR_ARRAY_SIZE - 1) ? 0 : errIdx + 1; + err[errIdx] = get_axis_error_steps(false); + + LOOP_L_N(i, I2CPE_ERR_ARRAY_SIZE) { + sum += err[i]; + if (i) diffSum += ABS(err[i-1] - err[i]); + } + + const int32_t error = int32_t(sum / (I2CPE_ERR_ARRAY_SIZE + 1)); //calculate average for error + + #else + const int32_t error = get_axis_error_steps(false); + #endif + + //SERIAL_ECHOLNPGM("Axis error steps: ", error); + + #ifdef I2CPE_ERR_THRESH_ABORT + if (ABS(error) > I2CPE_ERR_THRESH_ABORT * planner.settings.axis_steps_per_mm[encoderAxis]) { + //kill(F("Significant Error")); + SERIAL_ECHOLNPGM("Axis error over threshold, aborting!", error); + safe_delay(5000); + } + #endif + + #if ENABLED(I2CPE_ERR_ROLLING_AVERAGE) + if (errIdx == 0) { + // In order to correct for "error" but avoid correcting for noise and non-skips + // it must be > threshold and have a difference average of < 10 and be < 2000 steps + if (ABS(error) > threshold * planner.settings.axis_steps_per_mm[encoderAxis] + && diffSum < 10 * (I2CPE_ERR_ARRAY_SIZE - 1) + && ABS(error) < 2000 + ) { // Check for persistent error (skip) + errPrst[errPrstIdx++] = error; // Error must persist for I2CPE_ERR_PRST_ARRAY_SIZE error cycles. This also serves to improve the average accuracy + if (errPrstIdx >= I2CPE_ERR_PRST_ARRAY_SIZE) { + float sumP = 0; + LOOP_L_N(i, I2CPE_ERR_PRST_ARRAY_SIZE) sumP += errPrst[i]; + const int32_t errorP = int32_t(sumP * RECIPROCAL(I2CPE_ERR_PRST_ARRAY_SIZE)); + SERIAL_CHAR(AXIS_CHAR(encoderAxis)); + SERIAL_ECHOLNPGM(" : CORRECT ERR ", errorP * planner.mm_per_step[encoderAxis], "mm"); + babystep.add_steps(encoderAxis, -LROUND(errorP)); + errPrstIdx = 0; + } + } + else + errPrstIdx = 0; + } + #else + if (ABS(error) > threshold * planner.settings.axis_steps_per_mm[encoderAxis]) { + //SERIAL_ECHOLN(error); + //SERIAL_ECHOLN(position); + babystep.add_steps(encoderAxis, -LROUND(error / 2)); + } + #endif + + if (ABS(error) > I2CPE_ERR_CNT_THRESH * planner.settings.axis_steps_per_mm[encoderAxis]) { + const millis_t ms = millis(); + if (ELAPSED(ms, nextErrorCountTime)) { + SERIAL_CHAR(AXIS_CHAR(encoderAxis)); + SERIAL_ECHOLNPGM(" : LARGE ERR ", error, "; diffSum=", diffSum); + errorCount++; + nextErrorCountTime = ms + I2CPE_ERR_CNT_DEBOUNCE_MS; + } + } + } + + lastPositionTime = positionTime; +} + +void I2CPositionEncoder::set_homed() { + if (active) { + reset(); // Reset module's offset to zero (so current position is homed / zero) + delay(10); + + zeroOffset = get_raw_count(); + homed = trusted = true; + + #ifdef I2CPE_DEBUG + SERIAL_CHAR(AXIS_CHAR(encoderAxis)); + SERIAL_ECHOLNPGM(" axis encoder homed, offset of ", zeroOffset, " ticks."); + #endif + } +} + +void I2CPositionEncoder::set_unhomed() { + zeroOffset = 0; + homed = trusted = false; + + #ifdef I2CPE_DEBUG + SERIAL_CHAR(AXIS_CHAR(encoderAxis)); + SERIAL_ECHOLNPGM(" axis encoder unhomed."); + #endif +} + +bool I2CPositionEncoder::passes_test(const bool report) { + if (report) { + if (H != I2CPE_MAG_SIG_GOOD) SERIAL_ECHOPGM("Warning. "); + SERIAL_CHAR(AXIS_CHAR(encoderAxis)); + serial_ternary(H == I2CPE_MAG_SIG_BAD, F(" axis "), F("magnetic strip "), F("encoder ")); + switch (H) { + case I2CPE_MAG_SIG_GOOD: + case I2CPE_MAG_SIG_MID: + SERIAL_ECHO_TERNARY(H == I2CPE_MAG_SIG_GOOD, "passes test; field strength ", "good", "fair", ".\n"); + break; + default: + SERIAL_ECHOLNPGM("not detected!"); + } + } + return (H == I2CPE_MAG_SIG_GOOD || H == I2CPE_MAG_SIG_MID); +} + +float I2CPositionEncoder::get_axis_error_mm(const bool report) { + const float target = planner.get_axis_position_mm(encoderAxis), + actual = mm_from_count(position), + diff = actual - target, + error = ABS(diff) > 10000 ? 0 : diff; // Huge error is a bad reading + + if (report) { + SERIAL_CHAR(AXIS_CHAR(encoderAxis)); + SERIAL_ECHOLNPGM(" axis target=", target, "mm; actual=", actual, "mm; err=", error, "mm"); + } + + return error; +} + +int32_t I2CPositionEncoder::get_axis_error_steps(const bool report) { + if (!active) { + if (report) { + SERIAL_CHAR(AXIS_CHAR(encoderAxis)); + SERIAL_ECHOLNPGM(" axis encoder not active!"); + } + return 0; + } + + float stepperTicksPerUnit; + int32_t encoderTicks = position, encoderCountInStepperTicksScaled; + //int32_t stepperTicks = stepper.position(encoderAxis); + + // With a rotary encoder we're concerned with ticks/rev; whereas with a linear we're concerned with ticks/mm + stepperTicksPerUnit = (type == I2CPE_ENC_TYPE_ROTARY) ? stepperTicks : planner.settings.axis_steps_per_mm[encoderAxis]; + + //convert both 'ticks' into same units / base + encoderCountInStepperTicksScaled = LROUND((stepperTicksPerUnit * encoderTicks) / encoderTicksPerUnit); + + const int32_t target = stepper.position(encoderAxis); + int32_t error = encoderCountInStepperTicksScaled - target; + + //suppress discontinuities (might be caused by bad I2C readings...?) + const bool suppressOutput = (ABS(error - errorPrev) > 100); + + errorPrev = error; + + if (report) { + SERIAL_CHAR(AXIS_CHAR(encoderAxis)); + SERIAL_ECHOLNPGM(" axis target=", target, "; actual=", encoderCountInStepperTicksScaled, "; err=", error); + } + + if (suppressOutput) { + if (report) SERIAL_ECHOLNPGM("!Discontinuity. Suppressing error."); + error = 0; + } + + return error; +} + +int32_t I2CPositionEncoder::get_raw_count() { + uint8_t index = 0; + i2cLong encoderCount; + + encoderCount.val = 0x00; + + if (Wire.requestFrom(I2C_ADDRESS(i2cAddress), uint8_t(3)) != 3) { + //houston, we have a problem... + H = I2CPE_MAG_SIG_NF; + return 0; + } + + while (Wire.available()) + encoderCount.bval[index++] = (uint8_t)Wire.read(); + + //extract the magnetic strength + H = (B00000011 & (encoderCount.bval[2] >> 6)); + + //extract sign bit; sign = (encoderCount.bval[2] & B00100000); + //set all upper bits to the sign value to overwrite H + encoderCount.val = (encoderCount.bval[2] & B00100000) ? (encoderCount.val | 0xFFC00000) : (encoderCount.val & 0x003FFFFF); + + if (invert) encoderCount.val *= -1; + + return encoderCount.val; +} + +bool I2CPositionEncoder::test_axis() { + // Only works on XYZ Cartesian machines for the time being + if (!(encoderAxis == X_AXIS || encoderAxis == Y_AXIS || encoderAxis == Z_AXIS)) return false; + + const float startPosition = soft_endstop.min[encoderAxis] + 10, + endPosition = soft_endstop.max[encoderAxis] - 10; + const feedRate_t fr_mm_s = FLOOR(homing_feedrate(encoderAxis)); + + ec = false; + + xyze_pos_t startCoord, endCoord; + LOOP_NUM_AXES(a) { + startCoord[a] = planner.get_axis_position_mm((AxisEnum)a); + endCoord[a] = planner.get_axis_position_mm((AxisEnum)a); + } + startCoord[encoderAxis] = startPosition; + endCoord[encoderAxis] = endPosition; + + planner.synchronize(); + + #if HAS_EXTRUDERS + startCoord.e = planner.get_axis_position_mm(E_AXIS); + planner.buffer_line(startCoord, fr_mm_s, 0); + planner.synchronize(); + #endif + + // if the module isn't currently trusted, wait until it is (or until it should be if things are working) + if (!trusted) { + int32_t startWaitingTime = millis(); + while (!trusted && millis() - startWaitingTime < I2CPE_TIME_TRUSTED) + safe_delay(500); + } + + if (trusted) { // if trusted, commence test + TERN_(HAS_EXTRUDERS, endCoord.e = planner.get_axis_position_mm(E_AXIS)); + planner.buffer_line(endCoord, fr_mm_s, 0); + planner.synchronize(); + } + + return trusted; +} + +void I2CPositionEncoder::calibrate_steps_mm(const uint8_t iter) { + if (type != I2CPE_ENC_TYPE_LINEAR) { + SERIAL_ECHOLNPGM("Steps/mm calibration requires linear encoder."); + return; + } + + if (!(encoderAxis == X_AXIS || encoderAxis == Y_AXIS || encoderAxis == Z_AXIS)) { + SERIAL_ECHOLNPGM("Steps/mm calibration not supported for this axis."); + return; + } + + float old_steps_mm, new_steps_mm, + startDistance, endDistance, + travelDistance, travelledDistance, total = 0; + + int32_t startCount, stopCount; + + const feedRate_t fr_mm_s = homing_feedrate(encoderAxis); + + bool oldec = ec; + ec = false; + + startDistance = 20; + endDistance = soft_endstop.max[encoderAxis] - 20; + travelDistance = endDistance - startDistance; + + xyze_pos_t startCoord, endCoord; + LOOP_NUM_AXES(a) { + startCoord[a] = planner.get_axis_position_mm((AxisEnum)a); + endCoord[a] = planner.get_axis_position_mm((AxisEnum)a); + } + startCoord[encoderAxis] = startDistance; + endCoord[encoderAxis] = endDistance; + + planner.synchronize(); + + LOOP_L_N(i, iter) { + TERN_(HAS_EXTRUDERS, startCoord.e = planner.get_axis_position_mm(E_AXIS)); + planner.buffer_line(startCoord, fr_mm_s, 0); + planner.synchronize(); + + delay(250); + startCount = get_position(); + + //do_blocking_move_to(endCoord); + + TERN_(HAS_EXTRUDERS, endCoord.e = planner.get_axis_position_mm(E_AXIS)); + planner.buffer_line(endCoord, fr_mm_s, 0); + planner.synchronize(); + + //Read encoder distance + delay(250); + stopCount = get_position(); + + travelledDistance = mm_from_count(ABS(stopCount - startCount)); + + SERIAL_ECHOLNPGM("Attempted travel: ", travelDistance, "mm"); + SERIAL_ECHOLNPGM(" Actual travel: ", travelledDistance, "mm"); + + //Calculate new axis steps per unit + old_steps_mm = planner.settings.axis_steps_per_mm[encoderAxis]; + new_steps_mm = (old_steps_mm * travelDistance) / travelledDistance; + + SERIAL_ECHOLNPGM("Old steps/mm: ", old_steps_mm); + SERIAL_ECHOLNPGM("New steps/mm: ", new_steps_mm); + + //Save new value + planner.settings.axis_steps_per_mm[encoderAxis] = new_steps_mm; + + if (iter > 1) { + total += new_steps_mm; + + // swap start and end points so next loop runs from current position + const float tempCoord = startCoord[encoderAxis]; + startCoord[encoderAxis] = endCoord[encoderAxis]; + endCoord[encoderAxis] = tempCoord; + } + } + + if (iter > 1) { + total /= (float)iter; + SERIAL_ECHOLNPGM("Average steps/mm: ", total); + } + + ec = oldec; + + SERIAL_ECHOLNPGM("Calculated steps/mm set. Use M500 to save to EEPROM."); +} + +void I2CPositionEncoder::reset() { + Wire.beginTransmission(I2C_ADDRESS(i2cAddress)); + Wire.write(I2CPE_RESET_COUNT); + Wire.endTransmission(); + + TERN_(I2CPE_ERR_ROLLING_AVERAGE, ZERO(err)); +} + + +bool I2CPositionEncodersMgr::I2CPE_anyaxis; +uint8_t I2CPositionEncodersMgr::I2CPE_addr, + I2CPositionEncodersMgr::I2CPE_idx; +I2CPositionEncoder I2CPositionEncodersMgr::encoders[I2CPE_ENCODER_CNT]; + +void I2CPositionEncodersMgr::init() { + Wire.begin(); + + #if I2CPE_ENCODER_CNT > 0 + uint8_t i = 0; + + encoders[i].init(I2CPE_ENC_1_ADDR, I2CPE_ENC_1_AXIS); + + #ifdef I2CPE_ENC_1_TYPE + encoders[i].set_type(I2CPE_ENC_1_TYPE); + #endif + #ifdef I2CPE_ENC_1_TICKS_UNIT + encoders[i].set_ticks_unit(I2CPE_ENC_1_TICKS_UNIT); + #endif + #ifdef I2CPE_ENC_1_TICKS_REV + encoders[i].set_stepper_ticks(I2CPE_ENC_1_TICKS_REV); + #endif + #ifdef I2CPE_ENC_1_INVERT + encoders[i].set_inverted(ENABLED(I2CPE_ENC_1_INVERT)); + #endif + #ifdef I2CPE_ENC_1_EC_METHOD + encoders[i].set_ec_method(I2CPE_ENC_1_EC_METHOD); + #endif + #ifdef I2CPE_ENC_1_EC_THRESH + encoders[i].set_ec_threshold(I2CPE_ENC_1_EC_THRESH); + #endif + + encoders[i].set_active(encoders[i].passes_test(true)); + + TERN_(HAS_EXTRUDERS, if (I2CPE_ENC_1_AXIS == E_AXIS) encoders[i].set_homed()); + #endif + + #if I2CPE_ENCODER_CNT > 1 + i++; + + encoders[i].init(I2CPE_ENC_2_ADDR, I2CPE_ENC_2_AXIS); + + #ifdef I2CPE_ENC_2_TYPE + encoders[i].set_type(I2CPE_ENC_2_TYPE); + #endif + #ifdef I2CPE_ENC_2_TICKS_UNIT + encoders[i].set_ticks_unit(I2CPE_ENC_2_TICKS_UNIT); + #endif + #ifdef I2CPE_ENC_2_TICKS_REV + encoders[i].set_stepper_ticks(I2CPE_ENC_2_TICKS_REV); + #endif + #ifdef I2CPE_ENC_2_INVERT + encoders[i].set_inverted(ENABLED(I2CPE_ENC_2_INVERT)); + #endif + #ifdef I2CPE_ENC_2_EC_METHOD + encoders[i].set_ec_method(I2CPE_ENC_2_EC_METHOD); + #endif + #ifdef I2CPE_ENC_2_EC_THRESH + encoders[i].set_ec_threshold(I2CPE_ENC_2_EC_THRESH); + #endif + + encoders[i].set_active(encoders[i].passes_test(true)); + + TERN_(HAS_EXTRUDERS, if (I2CPE_ENC_2_AXIS == E_AXIS) encoders[i].set_homed()); + #endif + + #if I2CPE_ENCODER_CNT > 2 + i++; + + encoders[i].init(I2CPE_ENC_3_ADDR, I2CPE_ENC_3_AXIS); + + #ifdef I2CPE_ENC_3_TYPE + encoders[i].set_type(I2CPE_ENC_3_TYPE); + #endif + #ifdef I2CPE_ENC_3_TICKS_UNIT + encoders[i].set_ticks_unit(I2CPE_ENC_3_TICKS_UNIT); + #endif + #ifdef I2CPE_ENC_3_TICKS_REV + encoders[i].set_stepper_ticks(I2CPE_ENC_3_TICKS_REV); + #endif + #ifdef I2CPE_ENC_3_INVERT + encoders[i].set_inverted(ENABLED(I2CPE_ENC_3_INVERT)); + #endif + #ifdef I2CPE_ENC_3_EC_METHOD + encoders[i].set_ec_method(I2CPE_ENC_3_EC_METHOD); + #endif + #ifdef I2CPE_ENC_3_EC_THRESH + encoders[i].set_ec_threshold(I2CPE_ENC_3_EC_THRESH); + #endif + + encoders[i].set_active(encoders[i].passes_test(true)); + + TERN_(HAS_EXTRUDERS, if (I2CPE_ENC_3_AXIS == E_AXIS) encoders[i].set_homed()); + #endif + + #if I2CPE_ENCODER_CNT > 3 + i++; + + encoders[i].init(I2CPE_ENC_4_ADDR, I2CPE_ENC_4_AXIS); + + #ifdef I2CPE_ENC_4_TYPE + encoders[i].set_type(I2CPE_ENC_4_TYPE); + #endif + #ifdef I2CPE_ENC_4_TICKS_UNIT + encoders[i].set_ticks_unit(I2CPE_ENC_4_TICKS_UNIT); + #endif + #ifdef I2CPE_ENC_4_TICKS_REV + encoders[i].set_stepper_ticks(I2CPE_ENC_4_TICKS_REV); + #endif + #ifdef I2CPE_ENC_4_INVERT + encoders[i].set_inverted(ENABLED(I2CPE_ENC_4_INVERT)); + #endif + #ifdef I2CPE_ENC_4_EC_METHOD + encoders[i].set_ec_method(I2CPE_ENC_4_EC_METHOD); + #endif + #ifdef I2CPE_ENC_4_EC_THRESH + encoders[i].set_ec_threshold(I2CPE_ENC_4_EC_THRESH); + #endif + + encoders[i].set_active(encoders[i].passes_test(true)); + + TERN_(HAS_EXTRUDERS, if (I2CPE_ENC_4_AXIS == E_AXIS) encoders[i].set_homed()); + #endif + + #if I2CPE_ENCODER_CNT > 4 + i++; + + encoders[i].init(I2CPE_ENC_5_ADDR, I2CPE_ENC_5_AXIS); + + #ifdef I2CPE_ENC_5_TYPE + encoders[i].set_type(I2CPE_ENC_5_TYPE); + #endif + #ifdef I2CPE_ENC_5_TICKS_UNIT + encoders[i].set_ticks_unit(I2CPE_ENC_5_TICKS_UNIT); + #endif + #ifdef I2CPE_ENC_5_TICKS_REV + encoders[i].set_stepper_ticks(I2CPE_ENC_5_TICKS_REV); + #endif + #ifdef I2CPE_ENC_5_INVERT + encoders[i].set_inverted(ENABLED(I2CPE_ENC_5_INVERT)); + #endif + #ifdef I2CPE_ENC_5_EC_METHOD + encoders[i].set_ec_method(I2CPE_ENC_5_EC_METHOD); + #endif + #ifdef I2CPE_ENC_5_EC_THRESH + encoders[i].set_ec_threshold(I2CPE_ENC_5_EC_THRESH); + #endif + + encoders[i].set_active(encoders[i].passes_test(true)); + + TERN_(HAS_EXTRUDERS, if (I2CPE_ENC_5_AXIS == E_AXIS) encoders[i].set_homed()); + #endif + + #if I2CPE_ENCODER_CNT > 5 + i++; + + encoders[i].init(I2CPE_ENC_6_ADDR, I2CPE_ENC_6_AXIS); + + #ifdef I2CPE_ENC_6_TYPE + encoders[i].set_type(I2CPE_ENC_6_TYPE); + #endif + #ifdef I2CPE_ENC_6_TICKS_UNIT + encoders[i].set_ticks_unit(I2CPE_ENC_6_TICKS_UNIT); + #endif + #ifdef I2CPE_ENC_6_TICKS_REV + encoders[i].set_stepper_ticks(I2CPE_ENC_6_TICKS_REV); + #endif + #ifdef I2CPE_ENC_6_INVERT + encoders[i].set_inverted(ENABLED(I2CPE_ENC_6_INVERT)); + #endif + #ifdef I2CPE_ENC_6_EC_METHOD + encoders[i].set_ec_method(I2CPE_ENC_6_EC_METHOD); + #endif + #ifdef I2CPE_ENC_6_EC_THRESH + encoders[i].set_ec_threshold(I2CPE_ENC_6_EC_THRESH); + #endif + + encoders[i].set_active(encoders[i].passes_test(true)); + + TERN_(HAS_EXTRUDERS, if (I2CPE_ENC_6_AXIS == E_AXIS) encoders[i].set_homed()); + #endif +} + +void I2CPositionEncodersMgr::report_position(const int8_t idx, const bool units, const bool noOffset) { + CHECK_IDX(); + + if (units) + SERIAL_ECHOLN(noOffset ? encoders[idx].mm_from_count(encoders[idx].get_raw_count()) : encoders[idx].get_position_mm()); + else { + if (noOffset) { + const int32_t raw_count = encoders[idx].get_raw_count(); + SERIAL_CHAR(AXIS_CHAR(encoders[idx).get_axis()], ' '); + + for (uint8_t j = 31; j > 0; j--) + SERIAL_ECHO((bool)(0x00000001 & (raw_count >> j))); + + SERIAL_ECHO((bool)(0x00000001 & raw_count)); + SERIAL_CHAR(' '); + SERIAL_ECHOLN(raw_count); + } + else + SERIAL_ECHOLN(encoders[idx].get_position()); + } +} + +void I2CPositionEncodersMgr::change_module_address(const uint8_t oldaddr, const uint8_t newaddr) { + // First check 'new' address is not in use + Wire.beginTransmission(I2C_ADDRESS(newaddr)); + if (!Wire.endTransmission()) { + SERIAL_ECHOLNPGM("?There is already a device with that address on the I2C bus! (", newaddr, ")"); + return; + } + + // Now check that we can find the module on the oldaddr address + Wire.beginTransmission(I2C_ADDRESS(oldaddr)); + if (Wire.endTransmission()) { + SERIAL_ECHOLNPGM("?No module detected at this address! (", oldaddr, ")"); + return; + } + + SERIAL_ECHOLNPGM("Module found at ", oldaddr, ", changing address to ", newaddr); + + // Change the modules address + Wire.beginTransmission(I2C_ADDRESS(oldaddr)); + Wire.write(I2CPE_SET_ADDR); + Wire.write(newaddr); + Wire.endTransmission(); + + SERIAL_ECHOLNPGM("Address changed, resetting and waiting for confirmation.."); + + // Wait for the module to reset (can probably be improved by polling address with a timeout). + safe_delay(I2CPE_REBOOT_TIME); + + // Look for the module at the new address. + Wire.beginTransmission(I2C_ADDRESS(newaddr)); + if (Wire.endTransmission()) { + SERIAL_ECHOLNPGM("Address change failed! Check encoder module."); + return; + } + + SERIAL_ECHOLNPGM("Address change successful!"); + + // Now, if this module is configured, find which encoder instance it's supposed to correspond to + // and enable it (it will likely have failed initialization on power-up, before the address change). + const int8_t idx = idx_from_addr(newaddr); + if (idx >= 0 && !encoders[idx].get_active()) { + SERIAL_CHAR(AXIS_CHAR(encoders[idx).get_axis()]); + SERIAL_ECHOLNPGM(" axis encoder was not detected on printer startup. Trying again."); + encoders[idx].set_active(encoders[idx].passes_test(true)); + } +} + +void I2CPositionEncodersMgr::report_module_firmware(const uint8_t address) { + // First check there is a module + Wire.beginTransmission(I2C_ADDRESS(address)); + if (Wire.endTransmission()) { + SERIAL_ECHOLNPGM("?No module detected at this address! (", address, ")"); + return; + } + + SERIAL_ECHOLNPGM("Requesting version info from module at address ", address, ":"); + + Wire.beginTransmission(I2C_ADDRESS(address)); + Wire.write(I2CPE_SET_REPORT_MODE); + Wire.write(I2CPE_REPORT_VERSION); + Wire.endTransmission(); + + // Read value + if (Wire.requestFrom(I2C_ADDRESS(address), uint8_t(32))) { + char c; + while (Wire.available() > 0 && (c = (char)Wire.read()) > 0) + SERIAL_CHAR(c); + SERIAL_EOL(); + } + + // Set module back to normal (distance) mode + Wire.beginTransmission(I2C_ADDRESS(address)); + Wire.write(I2CPE_SET_REPORT_MODE); + Wire.write(I2CPE_REPORT_DISTANCE); + Wire.endTransmission(); +} + +int8_t I2CPositionEncodersMgr::parse() { + I2CPE_addr = 0; + + if (parser.seen('A')) { + + if (!parser.has_value()) { + SERIAL_ECHOLNPGM("?A seen, but no address specified! [30-200]"); + return I2CPE_PARSE_ERR; + } + + I2CPE_addr = parser.value_byte(); + if (!WITHIN(I2CPE_addr, 30, 200)) { // reserve the first 30 and last 55 + SERIAL_ECHOLNPGM("?Address out of range. [30-200]"); + return I2CPE_PARSE_ERR; + } + + I2CPE_idx = idx_from_addr(I2CPE_addr); + if (I2CPE_idx >= I2CPE_ENCODER_CNT) { + SERIAL_ECHOLNPGM("?No device with this address!"); + return I2CPE_PARSE_ERR; + } + } + else if (parser.seenval('I')) { + + if (!parser.has_value()) { + SERIAL_ECHOLNPGM("?I seen, but no index specified! [0-", I2CPE_ENCODER_CNT - 1, "]"); + return I2CPE_PARSE_ERR; + } + + I2CPE_idx = parser.value_byte(); + if (I2CPE_idx >= I2CPE_ENCODER_CNT) { + SERIAL_ECHOLNPGM("?Index out of range. [0-", I2CPE_ENCODER_CNT - 1, "]"); + return I2CPE_PARSE_ERR; + } + + I2CPE_addr = encoders[I2CPE_idx].get_address(); + } + else + I2CPE_idx = 0xFF; + + I2CPE_anyaxis = parser.seen_axis(); + + return I2CPE_PARSE_OK; +} + +/** + * M860: Report the position(s) of position encoder module(s). + * + * A Module I2C address. [30, 200]. + * I Module index. [0, I2CPE_ENCODER_CNT - 1] + * O Include homed zero-offset in returned position. + * U Units in mm or raw step count. + * + * If A or I not specified: + * X Report on X axis encoder, if present. + * Y Report on Y axis encoder, if present. + * Z Report on Z axis encoder, if present. + * E Report on E axis encoder, if present. + */ +void I2CPositionEncodersMgr::M860() { + if (parse()) return; + + const bool hasU = parser.seen_test('U'), hasO = parser.seen_test('O'); + + if (I2CPE_idx == 0xFF) { + LOOP_LOGICAL_AXES(i) { + if (!I2CPE_anyaxis || parser.seen_test(AXIS_CHAR(i))) { + const uint8_t idx = idx_from_axis(AxisEnum(i)); + if ((int8_t)idx >= 0) report_position(idx, hasU, hasO); + } + } + } + else + report_position(I2CPE_idx, hasU, hasO); +} + +/** + * M861: Report the status of position encoder modules. + * + * A Module I2C address. [30, 200]. + * I Module index. [0, I2CPE_ENCODER_CNT - 1] + * + * If A or I not specified: + * X Report on X axis encoder, if present. + * Y Report on Y axis encoder, if present. + * Z Report on Z axis encoder, if present. + * E Report on E axis encoder, if present. + */ +void I2CPositionEncodersMgr::M861() { + if (parse()) return; + + if (I2CPE_idx == 0xFF) { + LOOP_LOGICAL_AXES(i) { + if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { + const uint8_t idx = idx_from_axis(AxisEnum(i)); + if ((int8_t)idx >= 0) report_status(idx); + } + } + } + else + report_status(I2CPE_idx); +} + +/** + * M862: Perform an axis continuity test for position encoder + * modules. + * + * A Module I2C address. [30, 200]. + * I Module index. [0, I2CPE_ENCODER_CNT - 1] + * + * If A or I not specified: + * X Report on X axis encoder, if present. + * Y Report on Y axis encoder, if present. + * Z Report on Z axis encoder, if present. + * E Report on E axis encoder, if present. + */ +void I2CPositionEncodersMgr::M862() { + if (parse()) return; + + if (I2CPE_idx == 0xFF) { + LOOP_LOGICAL_AXES(i) { + if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { + const uint8_t idx = idx_from_axis(AxisEnum(i)); + if ((int8_t)idx >= 0) test_axis(idx); + } + } + } + else + test_axis(I2CPE_idx); +} + +/** + * M863: Perform steps-per-mm calibration for + * position encoder modules. + * + * A Module I2C address. [30, 200]. + * I Module index. [0, I2CPE_ENCODER_CNT - 1] + * P Number of rePeats/iterations. + * + * If A or I not specified: + * X Report on X axis encoder, if present. + * Y Report on Y axis encoder, if present. + * Z Report on Z axis encoder, if present. + * E Report on E axis encoder, if present. + */ +void I2CPositionEncodersMgr::M863() { + if (parse()) return; + + const uint8_t iterations = constrain(parser.byteval('P', 1), 1, 10); + + if (I2CPE_idx == 0xFF) { + LOOP_LOGICAL_AXES(i) { + if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { + const uint8_t idx = idx_from_axis(AxisEnum(i)); + if ((int8_t)idx >= 0) calibrate_steps_mm(idx, iterations); + } + } + } + else + calibrate_steps_mm(I2CPE_idx, iterations); +} + +/** + * M864: Change position encoder module I2C address. + * + * A Module current/old I2C address. If not present, + * assumes default address (030). [30, 200]. + * S Module new I2C address. [30, 200]. + * + * If S is not specified: + * X Use I2CPE_PRESET_ADDR_X (030). + * Y Use I2CPE_PRESET_ADDR_Y (031). + * Z Use I2CPE_PRESET_ADDR_Z (032). + * E Use I2CPE_PRESET_ADDR_E (033). + */ +void I2CPositionEncodersMgr::M864() { + uint8_t newAddress; + + if (parse()) return; + + if (!I2CPE_addr) I2CPE_addr = I2CPE_PRESET_ADDR_X; + + if (parser.seen('S')) { + if (!parser.has_value()) { + SERIAL_ECHOLNPGM("?S seen, but no address specified! [30-200]"); + return; + } + + newAddress = parser.value_byte(); + if (!WITHIN(newAddress, 30, 200)) { + SERIAL_ECHOLNPGM("?New address out of range. [30-200]"); + return; + } + } + else if (!I2CPE_anyaxis) { + SERIAL_ECHOLNPGM("?You must specify S or [XYZE]."); + return; + } + else { + if (parser.seen_test('X')) newAddress = I2CPE_PRESET_ADDR_X; + else if (parser.seen_test('Y')) newAddress = I2CPE_PRESET_ADDR_Y; + else if (parser.seen_test('Z')) newAddress = I2CPE_PRESET_ADDR_Z; + else if (parser.seen_test('E')) newAddress = I2CPE_PRESET_ADDR_E; + else return; + } + + SERIAL_ECHOLNPGM("Changing module at address ", I2CPE_addr, " to address ", newAddress); + + change_module_address(I2CPE_addr, newAddress); +} + +/** + * M865: Check position encoder module firmware version. + * + * A Module I2C address. [30, 200]. + * I Module index. [0, I2CPE_ENCODER_CNT - 1]. + * + * If A or I not specified: + * X Check X axis encoder, if present. + * Y Check Y axis encoder, if present. + * Z Check Z axis encoder, if present. + * E Check E axis encoder, if present. + */ +void I2CPositionEncodersMgr::M865() { + if (parse()) return; + + if (!I2CPE_addr) { + LOOP_LOGICAL_AXES(i) { + if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { + const uint8_t idx = idx_from_axis(AxisEnum(i)); + if ((int8_t)idx >= 0) report_module_firmware(encoders[idx].get_address()); + } + } + } + else + report_module_firmware(I2CPE_addr); +} + +/** + * M866: Report or reset position encoder module error + * count. + * + * A Module I2C address. [30, 200]. + * I Module index. [0, I2CPE_ENCODER_CNT - 1]. + * R Reset error counter. + * + * If A or I not specified: + * X Act on X axis encoder, if present. + * Y Act on Y axis encoder, if present. + * Z Act on Z axis encoder, if present. + * E Act on E axis encoder, if present. + */ +void I2CPositionEncodersMgr::M866() { + if (parse()) return; + + const bool hasR = parser.seen_test('R'); + + if (I2CPE_idx == 0xFF) { + LOOP_LOGICAL_AXES(i) { + if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { + const uint8_t idx = idx_from_axis(AxisEnum(i)); + if ((int8_t)idx >= 0) { + if (hasR) + reset_error_count(idx, AxisEnum(i)); + else + report_error_count(idx, AxisEnum(i)); + } + } + } + } + else if (hasR) + reset_error_count(I2CPE_idx, encoders[I2CPE_idx].get_axis()); + else + report_error_count(I2CPE_idx, encoders[I2CPE_idx].get_axis()); +} + +/** + * M867: Enable/disable or toggle error correction for position encoder modules. + * + * A Module I2C address. [30, 200]. + * I Module index. [0, I2CPE_ENCODER_CNT - 1]. + * S<1|0> Enable/disable error correction. 1 enables, 0 disables. If not + * supplied, toggle. + * + * If A or I not specified: + * X Act on X axis encoder, if present. + * Y Act on Y axis encoder, if present. + * Z Act on Z axis encoder, if present. + * E Act on E axis encoder, if present. + */ +void I2CPositionEncodersMgr::M867() { + if (parse()) return; + + const int8_t onoff = parser.seenval('S') ? parser.value_int() : -1; + + if (I2CPE_idx == 0xFF) { + LOOP_LOGICAL_AXES(i) { + if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { + const uint8_t idx = idx_from_axis(AxisEnum(i)); + if ((int8_t)idx >= 0) { + const bool ena = onoff == -1 ? !encoders[I2CPE_idx].get_ec_enabled() : !!onoff; + enable_ec(idx, ena, AxisEnum(i)); + } + } + } + } + else { + const bool ena = onoff == -1 ? !encoders[I2CPE_idx].get_ec_enabled() : !!onoff; + enable_ec(I2CPE_idx, ena, encoders[I2CPE_idx].get_axis()); + } +} + +/** + * M868: Report or set position encoder module error correction + * threshold. + * + * A Module I2C address. [30, 200]. + * I Module index. [0, I2CPE_ENCODER_CNT - 1]. + * T New error correction threshold. + * + * If A not specified: + * X Act on X axis encoder, if present. + * Y Act on Y axis encoder, if present. + * Z Act on Z axis encoder, if present. + * E Act on E axis encoder, if present. + */ +void I2CPositionEncodersMgr::M868() { + if (parse()) return; + + const float newThreshold = parser.seenval('T') ? parser.value_float() : -9999; + + if (I2CPE_idx == 0xFF) { + LOOP_LOGICAL_AXES(i) { + if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { + const uint8_t idx = idx_from_axis(AxisEnum(i)); + if ((int8_t)idx >= 0) { + if (newThreshold != -9999) + set_ec_threshold(idx, newThreshold, encoders[idx].get_axis()); + else + get_ec_threshold(idx, encoders[idx].get_axis()); + } + } + } + } + else if (newThreshold != -9999) + set_ec_threshold(I2CPE_idx, newThreshold, encoders[I2CPE_idx].get_axis()); + else + get_ec_threshold(I2CPE_idx, encoders[I2CPE_idx].get_axis()); +} + +/** + * M869: Report position encoder module error. + * + * A Module I2C address. [30, 200]. + * I Module index. [0, I2CPE_ENCODER_CNT - 1]. + * + * If A not specified: + * X Act on X axis encoder, if present. + * Y Act on Y axis encoder, if present. + * Z Act on Z axis encoder, if present. + * E Act on E axis encoder, if present. + */ +void I2CPositionEncodersMgr::M869() { + if (parse()) return; + + if (I2CPE_idx == 0xFF) { + LOOP_LOGICAL_AXES(i) { + if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { + const uint8_t idx = idx_from_axis(AxisEnum(i)); + if ((int8_t)idx >= 0) report_error(idx); + } + } + } + else + report_error(I2CPE_idx); +} + +#endif // I2C_POSITION_ENCODERS diff --git a/src/feature/encoder_i2c.h b/src/feature/encoder_i2c.h new file mode 100644 index 0000000..f25fe2e --- /dev/null +++ b/src/feature/encoder_i2c.h @@ -0,0 +1,320 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" + +#include "../module/planner.h" + +#include + +//=========== Advanced / Less-Common Encoder Configuration Settings ========== + +#define I2CPE_EC_THRESH_PROPORTIONAL // if enabled adjusts the error correction threshold + // proportional to the current speed of the axis allows + // for very small error margin at low speeds without + // stuttering due to reading latency at high speeds + +#define I2CPE_DEBUG // enable encoder-related debug serial echos + +#define I2CPE_REBOOT_TIME 5000 // time we wait for an encoder module to reboot + // after changing address. + +#define I2CPE_MAG_SIG_GOOD 0 +#define I2CPE_MAG_SIG_MID 1 +#define I2CPE_MAG_SIG_BAD 2 +#define I2CPE_MAG_SIG_NF 255 + +#define I2CPE_REQ_REPORT 0 +#define I2CPE_RESET_COUNT 1 +#define I2CPE_SET_ADDR 2 +#define I2CPE_SET_REPORT_MODE 3 +#define I2CPE_CLEAR_EEPROM 4 + +#define I2CPE_LED_PAR_MODE 10 +#define I2CPE_LED_PAR_BRT 11 +#define I2CPE_LED_PAR_RATE 14 + +#define I2CPE_REPORT_DISTANCE 0 +#define I2CPE_REPORT_STRENGTH 1 +#define I2CPE_REPORT_VERSION 2 + +// Default I2C addresses +#define I2CPE_PRESET_ADDR_X 30 +#define I2CPE_PRESET_ADDR_Y 31 +#define I2CPE_PRESET_ADDR_Z 32 +#define I2CPE_PRESET_ADDR_E 33 + +#define I2CPE_DEF_AXIS X_AXIS +#define I2CPE_DEF_ADDR I2CPE_PRESET_ADDR_X + +// Error event counter; tracks how many times there is an error exceeding a certain threshold +#define I2CPE_ERR_CNT_THRESH 3.00 +#define I2CPE_ERR_CNT_DEBOUNCE_MS 2000 + +#if ENABLED(I2CPE_ERR_ROLLING_AVERAGE) + #define I2CPE_ERR_ARRAY_SIZE 32 + #define I2CPE_ERR_PRST_ARRAY_SIZE 10 +#endif + +// Error Correction Methods +#define I2CPE_ECM_NONE 0 +#define I2CPE_ECM_MICROSTEP 1 +#define I2CPE_ECM_PLANNER 2 +#define I2CPE_ECM_STALLDETECT 3 + +// Encoder types +#define I2CPE_ENC_TYPE_ROTARY 0 +#define I2CPE_ENC_TYPE_LINEAR 1 + +// Parser +#define I2CPE_PARSE_ERR 1 +#define I2CPE_PARSE_OK 0 + +#define LOOP_PE(VAR) LOOP_L_N(VAR, I2CPE_ENCODER_CNT) +#define CHECK_IDX() do{ if (!WITHIN(idx, 0, I2CPE_ENCODER_CNT - 1)) return; }while(0) + +typedef union { + volatile int32_t val = 0; + uint8_t bval[4]; +} i2cLong; + +class I2CPositionEncoder { + private: + AxisEnum encoderAxis = I2CPE_DEF_AXIS; + + uint8_t i2cAddress = I2CPE_DEF_ADDR, + ecMethod = I2CPE_DEF_EC_METHOD, + type = I2CPE_DEF_TYPE, + H = I2CPE_MAG_SIG_NF; // Magnetic field strength + + int encoderTicksPerUnit = I2CPE_DEF_ENC_TICKS_UNIT, + stepperTicks = I2CPE_DEF_TICKS_REV, + errorCount = 0, + errorPrev = 0; + + float ecThreshold = I2CPE_DEF_EC_THRESH; + + bool homed = false, + trusted = false, + initialized = false, + active = false, + invert = false, + ec = true; + + int32_t zeroOffset = 0, + lastPosition = 0, + position; + + millis_t lastPositionTime = 0, + nextErrorCountTime = 0, + lastErrorTime; + + #if ENABLED(I2CPE_ERR_ROLLING_AVERAGE) + uint8_t errIdx = 0, errPrstIdx = 0; + int err[I2CPE_ERR_ARRAY_SIZE] = { 0 }, + errPrst[I2CPE_ERR_PRST_ARRAY_SIZE] = { 0 }; + #endif + + public: + void init(const uint8_t address, const AxisEnum axis); + void reset(); + + void update(); + + void set_homed(); + void set_unhomed(); + + int32_t get_raw_count(); + + FORCE_INLINE float mm_from_count(const int32_t count) { + switch (type) { + default: return -1; + case I2CPE_ENC_TYPE_LINEAR: + return count / encoderTicksPerUnit; + case I2CPE_ENC_TYPE_ROTARY: + return (count * stepperTicks) / (encoderTicksPerUnit * planner.settings.axis_steps_per_mm[encoderAxis]); + } + } + + FORCE_INLINE float get_position_mm() { return mm_from_count(get_position()); } + FORCE_INLINE int32_t get_position() { return get_raw_count() - zeroOffset; } + + int32_t get_axis_error_steps(const bool report); + float get_axis_error_mm(const bool report); + + void calibrate_steps_mm(const uint8_t iter); + + bool passes_test(const bool report); + + bool test_axis(); + + FORCE_INLINE int get_error_count() { return errorCount; } + FORCE_INLINE void set_error_count(const int newCount) { errorCount = newCount; } + + FORCE_INLINE uint8_t get_address() { return i2cAddress; } + FORCE_INLINE void set_address(const uint8_t addr) { i2cAddress = addr; } + + FORCE_INLINE bool get_active() { return active; } + FORCE_INLINE void set_active(const bool a) { active = a; } + + FORCE_INLINE void set_inverted(const bool i) { invert = i; } + + FORCE_INLINE AxisEnum get_axis() { return encoderAxis; } + + FORCE_INLINE bool get_ec_enabled() { return ec; } + FORCE_INLINE void set_ec_enabled(const bool enabled) { ec = enabled; } + + FORCE_INLINE uint8_t get_ec_method() { return ecMethod; } + FORCE_INLINE void set_ec_method(const byte method) { ecMethod = method; } + + FORCE_INLINE float get_ec_threshold() { return ecThreshold; } + FORCE_INLINE void set_ec_threshold(const_float_t newThreshold) { ecThreshold = newThreshold; } + + FORCE_INLINE int get_encoder_ticks_mm() { + switch (type) { + default: return 0; + case I2CPE_ENC_TYPE_LINEAR: + return encoderTicksPerUnit; + case I2CPE_ENC_TYPE_ROTARY: + return (int)((encoderTicksPerUnit / stepperTicks) * planner.settings.axis_steps_per_mm[encoderAxis]); + } + } + + FORCE_INLINE int get_ticks_unit() { return encoderTicksPerUnit; } + FORCE_INLINE void set_ticks_unit(const int ticks) { encoderTicksPerUnit = ticks; } + + FORCE_INLINE uint8_t get_type() { return type; } + FORCE_INLINE void set_type(const byte newType) { type = newType; } + + FORCE_INLINE int get_stepper_ticks() { return stepperTicks; } + FORCE_INLINE void set_stepper_ticks(const int ticks) { stepperTicks = ticks; } +}; + +class I2CPositionEncodersMgr { + private: + static bool I2CPE_anyaxis; + static uint8_t I2CPE_addr, I2CPE_idx; + + public: + + static void init(); + + // consider only updating one endoder per call / tick if encoders become too time intensive + static void update() { LOOP_PE(i) encoders[i].update(); } + + static void homed(const AxisEnum axis) { + LOOP_PE(i) + if (encoders[i].get_axis() == axis) encoders[i].set_homed(); + } + + static void unhomed(const AxisEnum axis) { + LOOP_PE(i) + if (encoders[i].get_axis() == axis) encoders[i].set_unhomed(); + } + + static void report_position(const int8_t idx, const bool units, const bool noOffset); + + static void report_status(const int8_t idx) { + CHECK_IDX(); + SERIAL_ECHOLNPGM("Encoder ", idx, ": "); + encoders[idx].get_raw_count(); + encoders[idx].passes_test(true); + } + + static void report_error(const int8_t idx) { + CHECK_IDX(); + encoders[idx].get_axis_error_steps(true); + } + + static void test_axis(const int8_t idx) { + CHECK_IDX(); + encoders[idx].test_axis(); + } + + static void calibrate_steps_mm(const int8_t idx, const int iterations) { + CHECK_IDX(); + encoders[idx].calibrate_steps_mm(iterations); + } + + static void change_module_address(const uint8_t oldaddr, const uint8_t newaddr); + static void report_module_firmware(const uint8_t address); + + static void report_error_count(const int8_t idx, const AxisEnum axis) { + CHECK_IDX(); + SERIAL_ECHOLNPGM("Error count on ", AS_CHAR(AXIS_CHAR(axis)), " axis is ", encoders[idx].get_error_count()); + } + + static void reset_error_count(const int8_t idx, const AxisEnum axis) { + CHECK_IDX(); + encoders[idx].set_error_count(0); + SERIAL_ECHOLNPGM("Error count on ", AS_CHAR(AXIS_CHAR(axis)), " axis has been reset."); + } + + static void enable_ec(const int8_t idx, const bool enabled, const AxisEnum axis) { + CHECK_IDX(); + encoders[idx].set_ec_enabled(enabled); + SERIAL_ECHOPGM("Error correction on ", AS_CHAR(AXIS_CHAR(axis))); + SERIAL_ECHO_TERNARY(encoders[idx].get_ec_enabled(), " axis is ", "en", "dis", "abled.\n"); + } + + static void set_ec_threshold(const int8_t idx, const float newThreshold, const AxisEnum axis) { + CHECK_IDX(); + encoders[idx].set_ec_threshold(newThreshold); + SERIAL_ECHOLNPGM("Error correct threshold for ", AS_CHAR(AXIS_CHAR(axis)), " axis set to ", newThreshold, "mm."); + } + + static void get_ec_threshold(const int8_t idx, const AxisEnum axis) { + CHECK_IDX(); + const float threshold = encoders[idx].get_ec_threshold(); + SERIAL_ECHOLNPGM("Error correct threshold for ", AS_CHAR(AXIS_CHAR(axis)), " axis is ", threshold, "mm."); + } + + static int8_t idx_from_axis(const AxisEnum axis) { + LOOP_PE(i) + if (encoders[i].get_axis() == axis) return i; + return -1; + } + + static int8_t idx_from_addr(const uint8_t addr) { + LOOP_PE(i) + if (encoders[i].get_address() == addr) return i; + return -1; + } + + static int8_t parse(); + + static void M860(); + static void M861(); + static void M862(); + static void M863(); + static void M864(); + static void M865(); + static void M866(); + static void M867(); + static void M868(); + static void M869(); + + static I2CPositionEncoder encoders[I2CPE_ENCODER_CNT]; +}; + +extern I2CPositionEncodersMgr I2CPEM; diff --git a/src/feature/ethernet.cpp b/src/feature/ethernet.cpp new file mode 100644 index 0000000..c5bfa93 --- /dev/null +++ b/src/feature/ethernet.cpp @@ -0,0 +1,175 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfigPre.h" + +#if HAS_ETHERNET + +#include "ethernet.h" +#include "../core/serial.h" + +#define DEBUG_OUT ENABLED(DEBUG_ETHERNET) +#include "../core/debug_out.h" + +bool MarlinEthernet::hardware_enabled, // = false + MarlinEthernet::have_telnet_client; // = false + +IPAddress MarlinEthernet::ip, + MarlinEthernet::myDns, + MarlinEthernet::gateway, + MarlinEthernet::subnet; + +EthernetClient MarlinEthernet::telnetClient; // connected client + +MarlinEthernet ethernet; + +EthernetServer server(23); // telnet server + +enum linkStates { UNLINKED, LINKING, LINKED, CONNECTING, CONNECTED, NO_HARDWARE } linkState; + +#ifdef __IMXRT1062__ + + static void teensyMAC(uint8_t * const mac) { + const uint32_t m1 = HW_OCOTP_MAC1, m2 = HW_OCOTP_MAC0; + mac[0] = m1 >> 8; + mac[1] = m1 >> 0; + mac[2] = m2 >> 24; + mac[3] = m2 >> 16; + mac[4] = m2 >> 8; + mac[5] = m2 >> 0; + } + +#else + + byte mac[] = MAC_ADDRESS; + +#endif + +void ethernet_cable_error() { SERIAL_ERROR_MSG("Ethernet cable is not connected."); } + +void MarlinEthernet::init() { + if (!hardware_enabled) return; + + SERIAL_ECHO_MSG("Starting network..."); + + // Init the Ethernet device + #ifdef __IMXRT1062__ + uint8_t mac[6]; + teensyMAC(mac); + #endif + + if (!ip) { + Ethernet.begin(mac); // use DHCP + } + else { + if (!gateway) { + gateway = ip; + gateway[3] = 1; + myDns = gateway; + subnet = IPAddress(255,255,255,0); + } + if (!myDns) myDns = gateway; + if (!subnet) subnet = IPAddress(255,255,255,0); + Ethernet.begin(mac, ip, myDns, gateway, subnet); + } + + // Check for Ethernet hardware present + if (Ethernet.hardwareStatus() == EthernetNoHardware) { + SERIAL_ERROR_MSG("No Ethernet hardware found."); + linkState = NO_HARDWARE; + return; + } + + linkState = UNLINKED; + + if (Ethernet.linkStatus() == LinkOFF) + ethernet_cable_error(); +} + +void MarlinEthernet::check() { + if (!hardware_enabled) return; + + switch (linkState) { + case NO_HARDWARE: + break; + + case UNLINKED: + if (Ethernet.linkStatus() == LinkOFF) break; + + SERIAL_ECHOLNPGM("Ethernet cable connected"); + server.begin(); + linkState = LINKING; + break; + + case LINKING: + if (!Ethernet.localIP()) break; + + SERIAL_ECHOPGM("Successfully started telnet server with IP "); + MYSERIAL1.println(Ethernet.localIP()); + + linkState = LINKED; + break; + + case LINKED: + if (Ethernet.linkStatus() == LinkOFF) { + ethernet_cable_error(); + linkState = UNLINKED; + break; + } + telnetClient = server.accept(); + if (telnetClient) linkState = CONNECTING; + break; + + case CONNECTING: + telnetClient.println("Marlin " SHORT_BUILD_VERSION); + #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR) + telnetClient.println( + " Last Updated: " STRING_DISTRIBUTION_DATE + " | Author: " STRING_CONFIG_H_AUTHOR + ); + #endif + telnetClient.println(" Compiled: " __DATE__); + + SERIAL_ECHOLNPGM("Client connected"); + have_telnet_client = true; + linkState = CONNECTED; + break; + + case CONNECTED: + if (telnetClient && !telnetClient.connected()) { + SERIAL_ECHOLNPGM("Client disconnected"); + telnetClient.stop(); + have_telnet_client = false; + linkState = LINKED; + } + if (Ethernet.linkStatus() == LinkOFF) { + ethernet_cable_error(); + if (telnetClient) telnetClient.stop(); + linkState = UNLINKED; + } + break; + + default: break; + } +} + +#endif // HAS_ETHERNET diff --git a/src/feature/ethernet.h b/src/feature/ethernet.h new file mode 100644 index 0000000..70a58ef --- /dev/null +++ b/src/feature/ethernet.h @@ -0,0 +1,39 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#ifdef __IMXRT1062__ + #include +#endif + +// Teensy 4.1 uses internal MAC Address + +class MarlinEthernet { + public: + static bool hardware_enabled, have_telnet_client; + static IPAddress ip, myDns, gateway, subnet; + static EthernetClient telnetClient; + static void init(); + static void check(); +}; + +extern MarlinEthernet ethernet; diff --git a/src/feature/fancheck.cpp b/src/feature/fancheck.cpp new file mode 100644 index 0000000..126b79b --- /dev/null +++ b/src/feature/fancheck.cpp @@ -0,0 +1,207 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * fancheck.cpp - fan tachometer check + */ + +#include "../inc/MarlinConfig.h" + +#if HAS_FANCHECK + +#include "fancheck.h" +#include "../module/temperature.h" + +#if HAS_AUTO_FAN && EXTRUDER_AUTO_FAN_SPEED != 255 && DISABLED(FOURWIRES_FANS) + bool FanCheck::measuring = false; +#endif +Flags FanCheck::tacho_state; +uint16_t FanCheck::edge_counter[TACHO_COUNT]; +uint8_t FanCheck::rps[TACHO_COUNT]; +FanCheck::TachoError FanCheck::error = FanCheck::TachoError::NONE; +bool FanCheck::enabled; + +void FanCheck::init() { + #define _TACHINIT(N) TERN(E##N##_FAN_TACHO_PULLUP, SET_INPUT_PULLUP, TERN(E##N##_FAN_TACHO_PULLDOWN, SET_INPUT_PULLDOWN, SET_INPUT))(E##N##_FAN_TACHO_PIN) + #if HAS_E0_FAN_TACHO + _TACHINIT(0); + #endif + #if HAS_E1_FAN_TACHO + _TACHINIT(1); + #endif + #if HAS_E2_FAN_TACHO + _TACHINIT(2); + #endif + #if HAS_E3_FAN_TACHO + _TACHINIT(3); + #endif + #if HAS_E4_FAN_TACHO + _TACHINIT(4); + #endif + #if HAS_E5_FAN_TACHO + _TACHINIT(5); + #endif + #if HAS_E6_FAN_TACHO + _TACHINIT(6); + #endif + #if HAS_E7_FAN_TACHO + _TACHINIT(7); + #endif +} + +void FanCheck::update_tachometers() { + bool status; + + #define _TACHO_CASE(N) case N: status = READ(E##N##_FAN_TACHO_PIN); break; + LOOP_L_N(f, TACHO_COUNT) { + switch (f) { + #if HAS_E0_FAN_TACHO + _TACHO_CASE(0) + #endif + #if HAS_E1_FAN_TACHO + _TACHO_CASE(1) + #endif + #if HAS_E2_FAN_TACHO + _TACHO_CASE(2) + #endif + #if HAS_E3_FAN_TACHO + _TACHO_CASE(3) + #endif + #if HAS_E4_FAN_TACHO + _TACHO_CASE(4) + #endif + #if HAS_E5_FAN_TACHO + _TACHO_CASE(5) + #endif + #if HAS_E6_FAN_TACHO + _TACHO_CASE(6) + #endif + #if HAS_E7_FAN_TACHO + _TACHO_CASE(7) + #endif + default: continue; + } + + if (status != tacho_state[f]) { + if (measuring) ++edge_counter[f]; + tacho_state.set(f, status); + } + } +} + +void FanCheck::compute_speed(uint16_t elapsedTime) { + static uint8_t errors_count[TACHO_COUNT]; + static uint8_t fan_reported_errors_msk = 0; + + uint8_t fan_error_msk = 0; + LOOP_L_N(f, TACHO_COUNT) { + switch (f) { + TERN_(HAS_E0_FAN_TACHO, case 0:) + TERN_(HAS_E1_FAN_TACHO, case 1:) + TERN_(HAS_E2_FAN_TACHO, case 2:) + TERN_(HAS_E3_FAN_TACHO, case 3:) + TERN_(HAS_E4_FAN_TACHO, case 4:) + TERN_(HAS_E5_FAN_TACHO, case 5:) + TERN_(HAS_E6_FAN_TACHO, case 6:) + TERN_(HAS_E7_FAN_TACHO, case 7:) + // Compute fan speed + rps[f] = edge_counter[f] * float(250) / elapsedTime; + edge_counter[f] = 0; + + // Check fan speed + constexpr int8_t max_extruder_fan_errors = TERN(HAS_PWMFANCHECK, 10000, 5000) / Temperature::fan_update_interval_ms; + + if (rps[f] >= 20 || TERN0(HAS_AUTO_FAN, thermalManager.autofan_speed[f] == 0)) + errors_count[f] = 0; + else if (errors_count[f] < max_extruder_fan_errors) + ++errors_count[f]; + else if (enabled) + SBI(fan_error_msk, f); + break; + } + } + + // Drop the error when all fans are ok + if (!fan_error_msk && error == TachoError::REPORTED) error = TachoError::FIXED; + + if (error == TachoError::FIXED && !printJobOngoing() && !printingIsPaused()) { + error = TachoError::NONE; // if the issue has been fixed while the printer is idle, reenable immediately + ui.reset_alert_level(); + } + + if (fan_error_msk & ~fan_reported_errors_msk) { + // Handle new faults only + LOOP_L_N(f, TACHO_COUNT) if (TEST(fan_error_msk, f)) report_speed_error(f); + } + fan_reported_errors_msk = fan_error_msk; +} + +void FanCheck::report_speed_error(uint8_t fan) { + if (printJobOngoing()) { + if (error == TachoError::NONE) { + if (thermalManager.degTargetHotend(fan) != 0) { + kill(GET_TEXT_F(MSG_FAN_SPEED_FAULT)); + error = TachoError::REPORTED; + } + else + error = TachoError::DETECTED; // Plans error for next processed command + } + } + else if (!printingIsPaused()) { + thermalManager.setTargetHotend(0, fan); // Always disable heating + if (error == TachoError::NONE) error = TachoError::REPORTED; + } + + SERIAL_ERROR_MSG(STR_ERR_FANSPEED, fan); + LCD_ALERTMESSAGE(MSG_FAN_SPEED_FAULT); +} + +void FanCheck::print_fan_states() { + LOOP_L_N(s, 2) { + LOOP_L_N(f, TACHO_COUNT) { + switch (f) { + TERN_(HAS_E0_FAN_TACHO, case 0:) + TERN_(HAS_E1_FAN_TACHO, case 1:) + TERN_(HAS_E2_FAN_TACHO, case 2:) + TERN_(HAS_E3_FAN_TACHO, case 3:) + TERN_(HAS_E4_FAN_TACHO, case 4:) + TERN_(HAS_E5_FAN_TACHO, case 5:) + TERN_(HAS_E6_FAN_TACHO, case 6:) + TERN_(HAS_E7_FAN_TACHO, case 7:) + SERIAL_ECHOPGM("E", f); + if (s == 0) + SERIAL_ECHOPGM(":", 60 * rps[f], " RPM "); + else + SERIAL_ECHOPGM("@:", TERN(HAS_AUTO_FAN, thermalManager.autofan_speed[f], 255), " "); + break; + } + } + } + SERIAL_EOL(); +} + +#if ENABLED(AUTO_REPORT_FANS) + AutoReporter FanCheck::auto_reporter; + void FanCheck::AutoReportFan::report() { print_fan_states(); } +#endif + +#endif // HAS_FANCHECK diff --git a/src/feature/fancheck.h b/src/feature/fancheck.h new file mode 100644 index 0000000..b13a34f --- /dev/null +++ b/src/feature/fancheck.h @@ -0,0 +1,89 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" + +#if HAS_FANCHECK + +#include "../MarlinCore.h" +#include "../lcd/marlinui.h" + +#if ENABLED(AUTO_REPORT_FANS) + #include "../libs/autoreport.h" +#endif + +#if ENABLED(PARK_HEAD_ON_PAUSE) + #include "../gcode/queue.h" +#endif + +/** + * fancheck.h + */ +#define TACHO_COUNT TERN(HAS_E7_FAN_TACHO, 8, TERN(HAS_E6_FAN_TACHO, 7, TERN(HAS_E5_FAN_TACHO, 6, TERN(HAS_E4_FAN_TACHO, 5, TERN(HAS_E3_FAN_TACHO, 4, TERN(HAS_E2_FAN_TACHO, 3, TERN(HAS_E1_FAN_TACHO, 2, 1))))))) + +class FanCheck { + private: + + enum class TachoError : uint8_t { NONE, DETECTED, REPORTED, FIXED }; + + #if HAS_PWMFANCHECK + static bool measuring; // For future use (3 wires PWM controlled fans) + #else + static constexpr bool measuring = true; + #endif + static Flags tacho_state; + static uint16_t edge_counter[TACHO_COUNT]; + static uint8_t rps[TACHO_COUNT]; + static TachoError error; + + static void report_speed_error(uint8_t fan); + + public: + + static bool enabled; + + static void init(); + static void update_tachometers(); + static void compute_speed(uint16_t elapsedTime); + static void print_fan_states(); + #if HAS_PWMFANCHECK + static void toggle_measuring() { measuring = !measuring; } + static bool is_measuring() { return measuring; } + #endif + + static void check_deferred_error() { + if (error == TachoError::DETECTED) { + error = TachoError::REPORTED; + TERN(PARK_HEAD_ON_PAUSE, queue.inject(F("M125")), kill(GET_TEXT_F(MSG_FAN_SPEED_FAULT))); + } + } + + #if ENABLED(AUTO_REPORT_FANS) + struct AutoReportFan { static void report(); }; + static AutoReporter auto_reporter; + #endif +}; + +extern FanCheck fan_check; + +#endif // HAS_FANCHECK diff --git a/src/feature/fanmux.cpp b/src/feature/fanmux.cpp new file mode 100644 index 0000000..43952ca --- /dev/null +++ b/src/feature/fanmux.cpp @@ -0,0 +1,55 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * feature/pause.cpp - Pause feature support functions + * This may be combined with related G-codes if features are consolidated. + */ + +#include "../inc/MarlinConfig.h" + +#if HAS_FANMUX + +#include "fanmux.h" + +void fanmux_switch(const uint8_t e) { + WRITE(FANMUX0_PIN, TEST(e, 0) ? HIGH : LOW); + #if PIN_EXISTS(FANMUX1) + WRITE(FANMUX1_PIN, TEST(e, 1) ? HIGH : LOW); + #if PIN_EXISTS(FANMUX2) + WRITE(FANMUX2_PIN, TEST(e, 2) ? HIGH : LOW); + #endif + #endif +} + +void fanmux_init() { + SET_OUTPUT(FANMUX0_PIN); + #if PIN_EXISTS(FANMUX1) + SET_OUTPUT(FANMUX1_PIN); + #if PIN_EXISTS(FANMUX2) + SET_OUTPUT(FANMUX2_PIN); + #endif + #endif + fanmux_switch(0); +} + +#endif // HAS_FANMUX diff --git a/src/feature/fanmux.h b/src/feature/fanmux.h new file mode 100644 index 0000000..efb92cf --- /dev/null +++ b/src/feature/fanmux.h @@ -0,0 +1,29 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * feature/fanmux.h - Cooling Fan Multiplexer support functions + */ + +void fanmux_switch(const uint8_t e); +void fanmux_init(); diff --git a/src/feature/filwidth.cpp b/src/feature/filwidth.cpp new file mode 100644 index 0000000..2bd9c78 --- /dev/null +++ b/src/feature/filwidth.cpp @@ -0,0 +1,49 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(FILAMENT_WIDTH_SENSOR) + +#include "filwidth.h" + +FilamentWidthSensor filwidth; + +bool FilamentWidthSensor::enabled; // = false; // (M405-M406) Filament Width Sensor ON/OFF. +uint32_t FilamentWidthSensor::accum; // = 0 // ADC accumulator +uint16_t FilamentWidthSensor::raw; // = 0 // Measured filament diameter - one extruder only +float FilamentWidthSensor::nominal_mm = DEFAULT_NOMINAL_FILAMENT_DIA, // (M104) Nominal filament width + FilamentWidthSensor::measured_mm = DEFAULT_MEASURED_FILAMENT_DIA, // Measured filament diameter + FilamentWidthSensor::e_count = 0, + FilamentWidthSensor::delay_dist = 0; +uint8_t FilamentWidthSensor::meas_delay_cm = MEASUREMENT_DELAY_CM; // Distance delay setting +int8_t FilamentWidthSensor::ratios[MAX_MEASUREMENT_DELAY + 1], // Ring buffer to delay measurement. (Extruder factor minus 100) + FilamentWidthSensor::index_r, // Indexes into ring buffer + FilamentWidthSensor::index_w; + +void FilamentWidthSensor::init() { + const int8_t ratio = sample_to_size_ratio(); + LOOP_L_N(i, COUNT(ratios)) ratios[i] = ratio; + index_r = index_w = 0; +} + +#endif // FILAMENT_WIDTH_SENSOR diff --git a/src/feature/filwidth.h b/src/feature/filwidth.h new file mode 100644 index 0000000..9eb1e77 --- /dev/null +++ b/src/feature/filwidth.h @@ -0,0 +1,120 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" +#include "../module/planner.h" +#include "../module/thermistor/thermistors.h" + +class FilamentWidthSensor { +public: + static constexpr int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10; + static bool enabled; // (M405-M406) Filament Width Sensor ON/OFF. + static uint32_t accum; // ADC accumulator + static uint16_t raw; // Measured filament diameter - one extruder only + static float nominal_mm, // (M104) Nominal filament width + measured_mm, // Measured filament diameter + e_count, delay_dist; + static uint8_t meas_delay_cm; // Distance delay setting + static int8_t ratios[MMD_CM], // Ring buffer to delay measurement. (Extruder factor minus 100) + index_r, index_w; // Indexes into ring buffer + + FilamentWidthSensor() { init(); } + static void init(); + + static void enable(const bool ena) { enabled = ena; } + + static void set_delay_cm(const uint8_t cm) { + meas_delay_cm = _MIN(cm, MAX_MEASUREMENT_DELAY); + } + + /** + * Convert Filament Width (mm) to an extrusion ratio + * and reduce to an 8 bit value. + * + * A nominal width of 1.75 and measured width of 1.73 + * gives (100 * 1.75 / 1.73) for a ratio of 101 and + * a return value of 1. + */ + static int8_t sample_to_size_ratio() { + return ABS(nominal_mm - measured_mm) <= FILWIDTH_ERROR_MARGIN + ? int(100.0f * nominal_mm / measured_mm) - 100 : 0; + } + + // Apply a single ADC reading to the raw value + static void accumulate(const uint16_t adc) { + if (adc > 102) // Ignore ADC under 0.5 volts + accum += (uint32_t(adc) << 7) - (accum >> 7); + } + + // Convert raw measurement to mm + static float raw_to_mm(const uint16_t v) { return v * float(ADC_VREF) * RECIPROCAL(float(MAX_RAW_THERMISTOR_VALUE)); } + static float raw_to_mm() { return raw_to_mm(raw); } + + // A scaled reading is ready + // Divide to get to 0-16384 range since we used 1/128 IIR filter approach + static void reading_ready() { raw = accum >> 10; } + + // Update mm from the raw measurement + static void update_measured_mm() { measured_mm = raw_to_mm(); } + + // Update ring buffer used to delay filament measurements + static void advance_e(const_float_t e_move) { + + // Increment counters with the E distance + e_count += e_move; + delay_dist += e_move; + + // Only get new measurements on forward E movement + if (!UNEAR_ZERO(e_count)) { + + // Loop the delay distance counter (modulus by the mm length) + while (delay_dist >= MMD_MM) delay_dist -= MMD_MM; + + // Convert into an index (cm) into the measurement array + index_r = int8_t(delay_dist * 0.1f); + + // If the ring buffer is not full... + if (index_r != index_w) { + e_count = 0; // Reset the E movement counter + const int8_t meas_sample = sample_to_size_ratio(); + do { + if (++index_w >= MMD_CM) index_w = 0; // The next unused slot + ratios[index_w] = meas_sample; // Store the measurement + } while (index_r != index_w); // More slots to fill? + } + } + } + + // Dynamically set the volumetric multiplier based on the delayed width measurement. + static void update_volumetric() { + if (enabled) { + int8_t read_index = index_r - meas_delay_cm; + if (read_index < 0) read_index += MMD_CM; // Loop around buffer if needed + LIMIT(read_index, 0, MAX_MEASUREMENT_DELAY); + planner.apply_filament_width_sensor(ratios[read_index]); + } + } + +}; + +extern FilamentWidthSensor filwidth; diff --git a/src/feature/fwretract.cpp b/src/feature/fwretract.cpp new file mode 100644 index 0000000..2835564 --- /dev/null +++ b/src/feature/fwretract.cpp @@ -0,0 +1,269 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * fwretract.cpp - Implement firmware-based retraction + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(FWRETRACT) + +#include "fwretract.h" + +FWRetract fwretract; // Single instance - this calls the constructor + +#include "../module/motion.h" +#include "../module/planner.h" + +#include "../gcode/gcode.h" + +#if ENABLED(RETRACT_SYNC_MIXING) + #include "mixing.h" +#endif + +// private: + +#if HAS_MULTI_EXTRUDER + Flags FWRetract::retracted_swap; // Which extruders are swap-retracted +#endif + +// public: + +fwretract_settings_t FWRetract::settings; // M207 S F Z W, M208 S F W R + +#if ENABLED(FWRETRACT_AUTORETRACT) + bool FWRetract::autoretract_enabled; // M209 S - Autoretract switch +#endif + +Flags FWRetract::retracted; // Which extruders are currently retracted + +float FWRetract::current_retract[EXTRUDERS], // Retract value used by planner + FWRetract::current_hop; + +void FWRetract::reset() { + TERN_(FWRETRACT_AUTORETRACT, autoretract_enabled = false); + settings.retract_length = RETRACT_LENGTH; + settings.retract_feedrate_mm_s = RETRACT_FEEDRATE; + settings.retract_zraise = RETRACT_ZRAISE; + settings.retract_recover_extra = RETRACT_RECOVER_LENGTH; + settings.retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE; + settings.swap_retract_length = RETRACT_LENGTH_SWAP; + settings.swap_retract_recover_extra = RETRACT_RECOVER_LENGTH_SWAP; + settings.swap_retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE_SWAP; + current_hop = 0.0; + + retracted.reset(); + EXTRUDER_LOOP() { + E_TERN_(retracted_swap.clear(e)); + current_retract[e] = 0.0; + } +} + +/** + * Retract or recover according to firmware settings + * + * This function handles retract/recover moves for G10 and G11, + * plus auto-retract moves sent from G0/G1 when E-only moves are done. + * + * To simplify the logic, doubled retract/recover moves are ignored. + * + * Note: Auto-retract will apply the set Z hop in addition to any Z hop + * included in the G-code. Use M207 Z0 to to prevent double hop. + */ +void FWRetract::retract(const bool retracting E_OPTARG(bool swapping/*=false*/)) { + // Prevent two retracts or recovers in a row + if (retracted[active_extruder] == retracting) return; + + // Prevent two swap-retract or recovers in a row + #if HAS_MULTI_EXTRUDER + // Allow G10 S1 only after G11 + if (swapping && retracted_swap[active_extruder] == retracting) return; + // G11 priority to recover the long retract if activated + if (!retracting) swapping = retracted_swap[active_extruder]; + #else + constexpr bool swapping = false; + #endif + + /* // debugging + SERIAL_ECHOLNPGM( + "retracting ", AS_DIGIT(retracting), + " swapping ", swapping, + " active extruder ", active_extruder + ); + EXTRUDER_LOOP() { + SERIAL_ECHOLNPGM("retracted[", e, "] ", AS_DIGIT(retracted[e])); + #if HAS_MULTI_EXTRUDER + SERIAL_ECHOLNPGM("retracted_swap[", e, "] ", AS_DIGIT(retracted_swap[e])); + #endif + } + SERIAL_ECHOLNPGM("current_position.z ", current_position.z); + SERIAL_ECHOLNPGM("current_position.e ", current_position.e); + SERIAL_ECHOLNPGM("current_hop ", current_hop); + //*/ + + const float base_retract = TERN1(RETRACT_SYNC_MIXING, (MIXING_STEPPERS)) + * (swapping ? settings.swap_retract_length : settings.retract_length); + + // The current position will be the destination for E and Z moves + destination = current_position; + + #if ENABLED(RETRACT_SYNC_MIXING) + const uint8_t old_mixing_tool = mixer.get_current_vtool(); + mixer.T(MIXER_AUTORETRACT_TOOL); + #endif + + const feedRate_t fr_max_z = planner.settings.max_feedrate_mm_s[Z_AXIS]; + if (retracting) { + // Retract by moving from a faux E position back to the current E position + current_retract[active_extruder] = base_retract; + prepare_internal_move_to_destination( // set current from destination + settings.retract_feedrate_mm_s * TERN1(RETRACT_SYNC_MIXING, (MIXING_STEPPERS)) + ); + + // Is a Z hop set, and has the hop not yet been done? + if (!current_hop && settings.retract_zraise > 0.01f) { // Apply hop only once + current_hop += settings.retract_zraise; // Add to the hop total (again, only once) + // Raise up, set_current_to_destination. Maximum Z feedrate + prepare_internal_move_to_destination(fr_max_z); + } + } + else { + // If a hop was done and Z hasn't changed, undo the Z hop + if (current_hop) { + current_hop = 0; + // Lower Z, set_current_to_destination. Maximum Z feedrate + prepare_internal_move_to_destination(fr_max_z); + } + + const float extra_recover = swapping ? settings.swap_retract_recover_extra : settings.retract_recover_extra; + if (extra_recover) { + current_position.e -= extra_recover; // Adjust the current E position by the extra amount to recover + sync_plan_position_e(); // Sync the planner position so the extra amount is recovered + } + + current_retract[active_extruder] = 0; + + // Recover E, set_current_to_destination + prepare_internal_move_to_destination( + (swapping ? settings.swap_retract_recover_feedrate_mm_s : settings.retract_recover_feedrate_mm_s) + * TERN1(RETRACT_SYNC_MIXING, (MIXING_STEPPERS)) + ); + } + + TERN_(RETRACT_SYNC_MIXING, mixer.T(old_mixing_tool)); // Restore original mixing tool + + retracted.set(active_extruder, retracting); // Active extruder now retracted / recovered + + // If swap retract/recover update the retracted_swap flag too + #if HAS_MULTI_EXTRUDER + if (swapping) retracted_swap.set(active_extruder, retracting); + #endif + + /* // debugging + SERIAL_ECHOLNPGM("retracting ", AS_DIGIT(retracting)); + SERIAL_ECHOLNPGM("swapping ", AS_DIGIT(swapping)); + SERIAL_ECHOLNPGM("active_extruder ", active_extruder); + EXTRUDER_LOOP() { + SERIAL_ECHOLNPGM("retracted[", e, "] ", AS_DIGIT(retracted[e])); + #if HAS_MULTI_EXTRUDER + SERIAL_ECHOLNPGM("retracted_swap[", e, "] ", AS_DIGIT(retracted_swap[e])); + #endif + } + SERIAL_ECHOLNPGM("current_position.z ", current_position.z); + SERIAL_ECHOLNPGM("current_position.e ", current_position.e); + SERIAL_ECHOLNPGM("current_hop ", current_hop); + //*/ +} + +//extern const char SP_Z_STR[]; + +/** + * M207: Set firmware retraction values + * + * S[+units] retract_length + * W[+units] swap_retract_length (multi-extruder) + * F[units/min] retract_feedrate_mm_s + * Z[units] retract_zraise + */ +void FWRetract::M207() { + if (!parser.seen("FSWZ")) return M207_report(); + if (parser.seenval('S')) settings.retract_length = parser.value_axis_units(E_AXIS); + if (parser.seenval('F')) settings.retract_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS)); + if (parser.seenval('Z')) settings.retract_zraise = parser.value_linear_units(); + if (parser.seenval('W')) settings.swap_retract_length = parser.value_axis_units(E_AXIS); +} + +void FWRetract::M207_report() { + SERIAL_ECHOLNPGM_P( + PSTR(" M207 S"), LINEAR_UNIT(settings.retract_length) + , PSTR(" W"), LINEAR_UNIT(settings.swap_retract_length) + , PSTR(" F"), LINEAR_UNIT(MMS_TO_MMM(settings.retract_feedrate_mm_s)) + , SP_Z_STR, LINEAR_UNIT(settings.retract_zraise) + ); +} + +/** + * M208: Set firmware un-retraction values + * + * S[+units] retract_recover_extra (in addition to M207 S*) + * W[+units] swap_retract_recover_extra (multi-extruder) + * F[units/min] retract_recover_feedrate_mm_s + * R[units/min] swap_retract_recover_feedrate_mm_s + */ +void FWRetract::M208() { + if (!parser.seen("FSRW")) return M208_report(); + if (parser.seen('S')) settings.retract_recover_extra = parser.value_axis_units(E_AXIS); + if (parser.seen('F')) settings.retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS)); + if (parser.seen('R')) settings.swap_retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS)); + if (parser.seen('W')) settings.swap_retract_recover_extra = parser.value_axis_units(E_AXIS); +} + +void FWRetract::M208_report() { + SERIAL_ECHOLNPGM( + " M208 S", LINEAR_UNIT(settings.retract_recover_extra) + , " W", LINEAR_UNIT(settings.swap_retract_recover_extra) + , " F", LINEAR_UNIT(MMS_TO_MMM(settings.retract_recover_feedrate_mm_s)) + ); +} + +#if ENABLED(FWRETRACT_AUTORETRACT) + + /** + * M209: Enable automatic retract (M209 S1) + * For slicers that don't support G10/11, reversed extrude-only + * moves will be classified as retraction. + */ + void FWRetract::M209() { + if (!parser.seen('S')) return M209_report(); + if (MIN_AUTORETRACT <= MAX_AUTORETRACT) + enable_autoretract(parser.value_bool()); + } + + void FWRetract::M209_report() { + SERIAL_ECHOLNPGM(" M209 S", AS_DIGIT(autoretract_enabled)); + } + +#endif // FWRETRACT_AUTORETRACT + + +#endif // FWRETRACT diff --git a/src/feature/fwretract.h b/src/feature/fwretract.h new file mode 100644 index 0000000..db2a62c --- /dev/null +++ b/src/feature/fwretract.h @@ -0,0 +1,89 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * fwretract.h - Define firmware-based retraction interface + */ + +#include "../inc/MarlinConfigPre.h" + +typedef struct { + float retract_length; // M207 S - G10 Retract length + feedRate_t retract_feedrate_mm_s; // M207 F - G10 Retract feedrate + float retract_zraise, // M207 Z - G10 Retract hop size + retract_recover_extra; // M208 S - G11 Recover length + feedRate_t retract_recover_feedrate_mm_s; // M208 F - G11 Recover feedrate + float swap_retract_length, // M207 W - G10 Swap Retract length + swap_retract_recover_extra; // M208 W - G11 Swap Recover length + feedRate_t swap_retract_recover_feedrate_mm_s; // M208 R - G11 Swap Recover feedrate +} fwretract_settings_t; + +#if ENABLED(FWRETRACT) + +class FWRetract { +private: + #if HAS_MULTI_EXTRUDER + static Flags retracted_swap; // Which extruders are swap-retracted + #endif + +public: + static fwretract_settings_t settings; + + #if ENABLED(FWRETRACT_AUTORETRACT) + static bool autoretract_enabled; // M209 S - Autoretract switch + #else + static constexpr bool autoretract_enabled = false; + #endif + + static Flags retracted; // Which extruders are currently retracted + static float current_retract[EXTRUDERS], // Retract value used by planner + current_hop; // Hop value used by planner + + FWRetract() { reset(); } + + static void reset(); + + static void refresh_autoretract() { retracted.reset(); } + + static void enable_autoretract(const bool enable) { + #if ENABLED(FWRETRACT_AUTORETRACT) + autoretract_enabled = enable; + refresh_autoretract(); + #endif + } + + static void retract(const bool retracting E_OPTARG(bool swapping=false)); + + static void M207_report(); + static void M207(); + static void M208_report(); + static void M208(); + #if ENABLED(FWRETRACT_AUTORETRACT) + static void M209_report(); + static void M209(); + #endif +}; + +extern FWRetract fwretract; + +#endif // FWRETRACT diff --git a/src/feature/host_actions.cpp b/src/feature/host_actions.cpp new file mode 100644 index 0000000..c03a6bc --- /dev/null +++ b/src/feature/host_actions.cpp @@ -0,0 +1,204 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(HOST_ACTION_COMMANDS) + +//#define DEBUG_HOST_ACTIONS + +#include "host_actions.h" + +#if ENABLED(ADVANCED_PAUSE_FEATURE) + #include "pause.h" + #include "../gcode/queue.h" +#endif + +#if HAS_FILAMENT_SENSOR + #include "runout.h" +#endif + +HostUI hostui; + +void HostUI::action(FSTR_P const fstr, const bool eol) { + PORT_REDIRECT(SerialMask::All); + SERIAL_ECHOPGM("//action:"); + SERIAL_ECHOF(fstr); + if (eol) SERIAL_EOL(); +} + +#ifdef ACTION_ON_KILL + void HostUI::kill() { action(F(ACTION_ON_KILL)); } +#endif +#ifdef ACTION_ON_PAUSE + void HostUI::pause(const bool eol/*=true*/) { action(F(ACTION_ON_PAUSE), eol); } +#endif +#ifdef ACTION_ON_PAUSED + void HostUI::paused(const bool eol/*=true*/) { action(F(ACTION_ON_PAUSED), eol); } +#endif +#ifdef ACTION_ON_RESUME + void HostUI::resume() { action(F(ACTION_ON_RESUME)); } +#endif +#ifdef ACTION_ON_RESUMED + void HostUI::resumed() { action(F(ACTION_ON_RESUMED)); } +#endif +#ifdef ACTION_ON_CANCEL + void HostUI::cancel() { action(F(ACTION_ON_CANCEL)); } +#endif +#ifdef ACTION_ON_START + void HostUI::start() { action(F(ACTION_ON_START)); } +#endif + +#if ENABLED(G29_RETRY_AND_RECOVER) + #ifdef ACTION_ON_G29_RECOVER + void HostUI::g29_recover() { action(F(ACTION_ON_G29_RECOVER)); } + #endif + #ifdef ACTION_ON_G29_FAILURE + void HostUI::g29_failure() { action(F(ACTION_ON_G29_FAILURE)); } + #endif +#endif + +#ifdef SHUTDOWN_ACTION + void HostUI::shutdown() { action(F(SHUTDOWN_ACTION)); } +#endif + +#if ENABLED(HOST_PROMPT_SUPPORT) + + PromptReason HostUI::host_prompt_reason = PROMPT_NOT_DEFINED; + + PGMSTR(CONTINUE_STR, "Continue"); + PGMSTR(DISMISS_STR, "Dismiss"); + + #if HAS_RESUME_CONTINUE + extern bool wait_for_user; + #endif + + void HostUI::notify(const char * const cstr) { + PORT_REDIRECT(SerialMask::All); + action(F("notification "), false); + SERIAL_ECHOLN(cstr); + } + + void HostUI::notify_P(PGM_P const pstr) { + PORT_REDIRECT(SerialMask::All); + action(F("notification "), false); + SERIAL_ECHOLNPGM_P(pstr); + } + + void HostUI::prompt(FSTR_P const ptype, const bool eol/*=true*/) { + PORT_REDIRECT(SerialMask::All); + action(F("prompt_"), false); + SERIAL_ECHOF(ptype); + if (eol) SERIAL_EOL(); + } + + void HostUI::prompt_plus(FSTR_P const ptype, FSTR_P const fstr, const char extra_char/*='\0'*/) { + prompt(ptype, false); + PORT_REDIRECT(SerialMask::All); + SERIAL_CHAR(' '); + SERIAL_ECHOF(fstr); + if (extra_char != '\0') SERIAL_CHAR(extra_char); + SERIAL_EOL(); + } + void HostUI::prompt_begin(const PromptReason reason, FSTR_P const fstr, const char extra_char/*='\0'*/) { + prompt_end(); + host_prompt_reason = reason; + prompt_plus(F("begin"), fstr, extra_char); + } + void HostUI::prompt_button(FSTR_P const fstr) { prompt_plus(F("button"), fstr); } + void HostUI::prompt_end() { prompt(F("end")); } + void HostUI::prompt_show() { prompt(F("show")); } + + void HostUI::_prompt_show(FSTR_P const btn1, FSTR_P const btn2) { + if (btn1) prompt_button(btn1); + if (btn2) prompt_button(btn2); + prompt_show(); + } + void HostUI::prompt_do(const PromptReason reason, FSTR_P const fstr, FSTR_P const btn1/*=nullptr*/, FSTR_P const btn2/*=nullptr*/) { + prompt_begin(reason, fstr); + _prompt_show(btn1, btn2); + } + void HostUI::prompt_do(const PromptReason reason, FSTR_P const fstr, const char extra_char, FSTR_P const btn1/*=nullptr*/, FSTR_P const btn2/*=nullptr*/) { + prompt_begin(reason, fstr, extra_char); + _prompt_show(btn1, btn2); + } + + #if ENABLED(ADVANCED_PAUSE_FEATURE) + void HostUI::filament_load_prompt() { + const bool disable_to_continue = TERN0(HAS_FILAMENT_SENSOR, runout.filament_ran_out); + prompt_do(PROMPT_FILAMENT_RUNOUT, F("Paused"), F("PurgeMore"), + disable_to_continue ? F("DisableRunout") : FPSTR(CONTINUE_STR) + ); + } + #endif + + // + // Handle responses from the host, such as: + // - Filament runout responses: Purge More, Continue + // - General "Continue" response + // - Resume Print response + // - Dismissal of info + // + void HostUI::handle_response(const uint8_t response) { + const PromptReason hpr = host_prompt_reason; + host_prompt_reason = PROMPT_NOT_DEFINED; // Reset now ahead of logic + switch (hpr) { + case PROMPT_FILAMENT_RUNOUT: + switch (response) { + + case 0: // "Purge More" button + #if BOTH(M600_PURGE_MORE_RESUMABLE, ADVANCED_PAUSE_FEATURE) + pause_menu_response = PAUSE_RESPONSE_EXTRUDE_MORE; // Simulate menu selection (menu exits, doesn't extrude more) + #endif + break; + + case 1: // "Continue" / "Disable Runout" button + #if BOTH(M600_PURGE_MORE_RESUMABLE, ADVANCED_PAUSE_FEATURE) + pause_menu_response = PAUSE_RESPONSE_RESUME_PRINT; // Simulate menu selection + #endif + #if HAS_FILAMENT_SENSOR + if (runout.filament_ran_out) { // Disable a triggered sensor + runout.enabled = false; + runout.reset(); + } + #endif + break; + } + break; + case PROMPT_USER_CONTINUE: + TERN_(HAS_RESUME_CONTINUE, wait_for_user = false); + break; + case PROMPT_PAUSE_RESUME: + #if BOTH(ADVANCED_PAUSE_FEATURE, SDSUPPORT) + extern const char M24_STR[]; + queue.inject_P(M24_STR); + #endif + break; + case PROMPT_INFO: + break; + default: break; + } + } + +#endif // HOST_PROMPT_SUPPORT + +#endif // HOST_ACTION_COMMANDS diff --git a/src/feature/host_actions.h b/src/feature/host_actions.h new file mode 100644 index 0000000..41d66b8 --- /dev/null +++ b/src/feature/host_actions.h @@ -0,0 +1,114 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfigPre.h" +#include "../HAL/shared/Marduino.h" + +#if ENABLED(HOST_PROMPT_SUPPORT) + + enum PromptReason : uint8_t { + PROMPT_NOT_DEFINED, + PROMPT_FILAMENT_RUNOUT, + PROMPT_USER_CONTINUE, + PROMPT_FILAMENT_RUNOUT_REHEAT, + PROMPT_PAUSE_RESUME, + PROMPT_INFO + }; + +#endif + +class HostUI { + public: + + static void action(FSTR_P const fstr, const bool eol=true); + + #ifdef ACTION_ON_KILL + static void kill(); + #endif + #ifdef ACTION_ON_PAUSE + static void pause(const bool eol=true); + #endif + #ifdef ACTION_ON_PAUSED + static void paused(const bool eol=true); + #endif + #ifdef ACTION_ON_RESUME + static void resume(); + #endif + #ifdef ACTION_ON_RESUMED + static void resumed(); + #endif + #ifdef ACTION_ON_CANCEL + static void cancel(); + #endif + #ifdef ACTION_ON_START + static void start(); + #endif + #ifdef SHUTDOWN_ACTION + static void shutdown(); + #endif + + #if ENABLED(G29_RETRY_AND_RECOVER) + #ifdef ACTION_ON_G29_RECOVER + static void g29_recover(); + #endif + #ifdef ACTION_ON_G29_FAILURE + static void g29_failure(); + #endif + #endif + + #if ENABLED(HOST_PROMPT_SUPPORT) + private: + static void prompt(FSTR_P const ptype, const bool eol=true); + static void prompt_plus(FSTR_P const ptype, FSTR_P const fstr, const char extra_char='\0'); + static void prompt_show(); + static void _prompt_show(FSTR_P const btn1, FSTR_P const btn2); + + public: + static PromptReason host_prompt_reason; + + static void handle_response(const uint8_t response); + + static void notify_P(PGM_P const message); + static void notify(FSTR_P const fmsg) { notify_P(FTOP(fmsg)); } + static void notify(const char * const message); + + static void prompt_begin(const PromptReason reason, FSTR_P const fstr, const char extra_char='\0'); + static void prompt_button(FSTR_P const fstr); + static void prompt_end(); + static void prompt_do(const PromptReason reason, FSTR_P const pstr, FSTR_P const btn1=nullptr, FSTR_P const btn2=nullptr); + static void prompt_do(const PromptReason reason, FSTR_P const pstr, const char extra_char, FSTR_P const btn1=nullptr, FSTR_P const btn2=nullptr); + static void prompt_open(const PromptReason reason, FSTR_P const pstr, FSTR_P const btn1=nullptr, FSTR_P const btn2=nullptr) { + if (host_prompt_reason == PROMPT_NOT_DEFINED) prompt_do(reason, pstr, btn1, btn2); + } + + #if ENABLED(ADVANCED_PAUSE_FEATURE) + static void filament_load_prompt(); + #endif + + #endif + +}; + +extern HostUI hostui; + +extern const char CONTINUE_STR[], DISMISS_STR[]; diff --git a/src/feature/hotend_idle.cpp b/src/feature/hotend_idle.cpp new file mode 100644 index 0000000..4b137f4 --- /dev/null +++ b/src/feature/hotend_idle.cpp @@ -0,0 +1,91 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * Hotend Idle Timeout + * Prevent filament in the nozzle from charring and causing a critical jam. + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(HOTEND_IDLE_TIMEOUT) + +#include "hotend_idle.h" +#include "../gcode/gcode.h" + +#include "../module/temperature.h" +#include "../module/motion.h" +#include "../module/planner.h" +#include "../lcd/marlinui.h" + +extern HotendIdleProtection hotend_idle; + +millis_t HotendIdleProtection::next_protect_ms = 0; + +void HotendIdleProtection::check_hotends(const millis_t &ms) { + bool do_prot = false; + HOTEND_LOOP() { + const bool busy = (TERN0(HAS_RESUME_CONTINUE, wait_for_user) || planner.has_blocks_queued()); + if (thermalManager.degHotend(e) >= (HOTEND_IDLE_MIN_TRIGGER) && !busy) { + do_prot = true; break; + } + } + if (bool(next_protect_ms) != do_prot) + next_protect_ms = do_prot ? ms + hp_interval : 0; +} + +void HotendIdleProtection::check_e_motion(const millis_t &ms) { + static float old_e_position = 0; + if (old_e_position != current_position.e) { + old_e_position = current_position.e; // Track filament motion + if (next_protect_ms) // If some heater is on then... + next_protect_ms = ms + hp_interval; // ...delay the timeout till later + } +} + +void HotendIdleProtection::check() { + const millis_t ms = millis(); // Shared millis + + check_hotends(ms); // Any hotends need protection? + check_e_motion(ms); // Motion will protect them + + // Hot and not moving for too long... + if (next_protect_ms && ELAPSED(ms, next_protect_ms)) + timed_out(); +} + +// Lower (but don't raise) hotend / bed temperatures +void HotendIdleProtection::timed_out() { + next_protect_ms = 0; + SERIAL_ECHOLNPGM("Hotend Idle Timeout"); + LCD_MESSAGE(MSG_HOTEND_IDLE_TIMEOUT); + HOTEND_LOOP() { + if ((HOTEND_IDLE_NOZZLE_TARGET) < thermalManager.degTargetHotend(e)) + thermalManager.setTargetHotend(HOTEND_IDLE_NOZZLE_TARGET, e); + } + #if HAS_HEATED_BED + if ((HOTEND_IDLE_BED_TARGET) < thermalManager.degTargetBed()) + thermalManager.setTargetBed(HOTEND_IDLE_BED_TARGET); + #endif +} + +#endif // HOTEND_IDLE_TIMEOUT diff --git a/src/feature/hotend_idle.h b/src/feature/hotend_idle.h new file mode 100644 index 0000000..40f557d --- /dev/null +++ b/src/feature/hotend_idle.h @@ -0,0 +1,37 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../core/millis_t.h" + +class HotendIdleProtection { +public: + static void check(); +private: + static constexpr millis_t hp_interval = SEC_TO_MS(HOTEND_IDLE_TIMEOUT_SEC); + static millis_t next_protect_ms; + static void check_hotends(const millis_t &ms); + static void check_e_motion(const millis_t &ms); + static void timed_out(); +}; + +extern HotendIdleProtection hotend_idle; diff --git a/src/feature/joystick.cpp b/src/feature/joystick.cpp new file mode 100644 index 0000000..acab5d7 --- /dev/null +++ b/src/feature/joystick.cpp @@ -0,0 +1,184 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * joystick.cpp - joystick input / jogging + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(JOYSTICK) + +#include "joystick.h" + +#include "../inc/MarlinConfig.h" // for pins +#include "../module/planner.h" + +Joystick joystick; + +#if ENABLED(EXTENSIBLE_UI) + #include "../lcd/extui/ui_api.h" +#endif + +#if HAS_JOY_ADC_X + temp_info_t Joystick::x; // = { 0 } + #if ENABLED(INVERT_JOY_X) + #define JOY_X(N) (16383 - (N)) + #else + #define JOY_X(N) (N) + #endif +#endif +#if HAS_JOY_ADC_Y + temp_info_t Joystick::y; // = { 0 } + #if ENABLED(INVERT_JOY_Y) + #define JOY_Y(N) (16383 - (N)) + #else + #define JOY_Y(N) (N) + #endif +#endif +#if HAS_JOY_ADC_Z + temp_info_t Joystick::z; // = { 0 } + #if ENABLED(INVERT_JOY_Z) + #define JOY_Z(N) (16383 - (N)) + #else + #define JOY_Z(N) (N) + #endif +#endif + +#if ENABLED(JOYSTICK_DEBUG) + void Joystick::report() { + SERIAL_ECHOPGM("Joystick"); + #if HAS_JOY_ADC_X + SERIAL_ECHOPGM_P(SP_X_STR, JOY_X(x.getraw())); + #endif + #if HAS_JOY_ADC_Y + SERIAL_ECHOPGM_P(SP_Y_STR, JOY_Y(y.getraw())); + #endif + #if HAS_JOY_ADC_Z + SERIAL_ECHOPGM_P(SP_Z_STR, JOY_Z(z.getraw())); + #endif + #if HAS_JOY_ADC_EN + SERIAL_ECHO_TERNARY(READ(JOY_EN_PIN), " EN=", "HIGH (dis", "LOW (en", "abled)"); + #endif + SERIAL_EOL(); + } +#endif + +#if HAS_JOY_ADC_X || HAS_JOY_ADC_Y || HAS_JOY_ADC_Z + + void Joystick::calculate(xyz_float_t &norm_jog) { + // Do nothing if enable pin (active-low) is not LOW + #if HAS_JOY_ADC_EN + if (READ(JOY_EN_PIN)) return; + #endif + + auto _normalize_joy = [](float &axis_jog, const raw_adc_t raw, const raw_adc_t (&joy_limits)[4]) { + if (WITHIN(raw, joy_limits[0], joy_limits[3])) { + // within limits, check deadzone + if (raw > joy_limits[2]) + axis_jog = (raw - joy_limits[2]) / float(joy_limits[3] - joy_limits[2]); + else if (raw < joy_limits[1]) + axis_jog = int16_t(raw - joy_limits[1]) / float(joy_limits[1] - joy_limits[0]); // negative value + // Map normal to jog value via quadratic relationship + axis_jog = SIGN(axis_jog) * sq(axis_jog); + } + }; + + #if HAS_JOY_ADC_X + static constexpr raw_adc_t joy_x_limits[4] = JOY_X_LIMITS; + _normalize_joy(norm_jog.x, JOY_X(x.getraw()), joy_x_limits); + #endif + #if HAS_JOY_ADC_Y + static constexpr raw_adc_t joy_y_limits[4] = JOY_Y_LIMITS; + _normalize_joy(norm_jog.y, JOY_Y(y.getraw()), joy_y_limits); + #endif + #if HAS_JOY_ADC_Z + static constexpr raw_adc_t joy_z_limits[4] = JOY_Z_LIMITS; + _normalize_joy(norm_jog.z, JOY_Z(z.getraw()), joy_z_limits); + #endif + } + +#endif + +#if ENABLED(POLL_JOG) + + void Joystick::inject_jog_moves() { + // Recursion barrier + static bool injecting_now; // = false; + if (injecting_now) return; + + #if ENABLED(NO_MOTION_BEFORE_HOMING) + if (TERN0(HAS_JOY_ADC_X, axis_should_home(X_AXIS)) || TERN0(HAS_JOY_ADC_Y, axis_should_home(Y_AXIS)) || TERN0(HAS_JOY_ADC_Z, axis_should_home(Z_AXIS))) + return; + #endif + + static constexpr int QUEUE_DEPTH = 5; // Insert up to this many movements + static constexpr float target_lag = 0.25f, // Aim for 1/4 second lag + seg_time = target_lag / QUEUE_DEPTH; // 0.05 seconds, short segments inserted every 1/20th of a second + static constexpr millis_t timer_limit_ms = millis_t(seg_time * 500); // 25 ms minimum delay between insertions + + // The planner can merge/collapse small moves, so the movement queue is unreliable to control the lag + static millis_t next_run = 0; + if (PENDING(millis(), next_run)) return; + next_run = millis() + timer_limit_ms; + + // Only inject a command if the planner has fewer than 5 moves and there are no unparsed commands + if (planner.movesplanned() >= QUEUE_DEPTH || queue.has_commands_queued()) + return; + + // Normalized jog values are 0 for no movement and -1 or +1 for as max feedrate (nonlinear relationship) + // Jog are initialized to zero and handling input can update values but doesn't have to + // You could use a two-axis joystick and a one-axis keypad and they might work together + xyz_float_t norm_jog{0}; + + // Use ADC values and defined limits. The active zone is normalized: -1..0 (dead) 0..1 + #if HAS_JOY_ADC_X || HAS_JOY_ADC_Y || HAS_JOY_ADC_Z + joystick.calculate(norm_jog); + #endif + + // Other non-joystick poll-based jogging could be implemented here + // with "jogging" encapsulated as a more general class. + + TERN_(EXTENSIBLE_UI, ExtUI::_joystick_update(norm_jog)); + + // norm_jog values of [-1 .. 1] maps linearly to [-feedrate .. feedrate] + xyz_float_t move_dist{0}; + float hypot2 = 0; + LOOP_NUM_AXES(i) if (norm_jog[i]) { + move_dist[i] = seg_time * norm_jog[i] * TERN(EXTENSIBLE_UI, manual_feedrate_mm_s, planner.settings.max_feedrate_mm_s)[i]; + hypot2 += sq(move_dist[i]); + } + + if (!UNEAR_ZERO(hypot2)) { + current_position += move_dist; + apply_motion_limits(current_position); + const float length = sqrt(hypot2); + PlannerHints hints(length); + injecting_now = true; + planner.buffer_line(current_position, length / seg_time, active_extruder, hints); + injecting_now = false; + } + } + +#endif // POLL_JOG + +#endif // JOYSTICK diff --git a/src/feature/joystick.h b/src/feature/joystick.h new file mode 100644 index 0000000..91bf6bd --- /dev/null +++ b/src/feature/joystick.h @@ -0,0 +1,52 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * joystick.h - joystick input / jogging + */ + +#include "../inc/MarlinConfigPre.h" +#include "../core/types.h" +#include "../module/temperature.h" + +class Joystick { + friend class Temperature; + private: + #if HAS_JOY_ADC_X + static temp_info_t x; + #endif + #if HAS_JOY_ADC_Y + static temp_info_t y; + #endif + #if HAS_JOY_ADC_Z + static temp_info_t z; + #endif + public: + #if ENABLED(JOYSTICK_DEBUG) + static void report(); + #endif + static void calculate(xyz_float_t &norm_jog); + static void inject_jog_moves(); +}; + +extern Joystick joystick; diff --git a/src/feature/leds/blinkm.cpp b/src/feature/leds/blinkm.cpp new file mode 100644 index 0000000..868eb4b --- /dev/null +++ b/src/feature/leds/blinkm.cpp @@ -0,0 +1,46 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * blinkm.cpp - Control a BlinkM over i2c + */ + +#include "../../inc/MarlinConfig.h" + +#if ENABLED(BLINKM) + +#include "blinkm.h" +#include "leds.h" +#include + +void blinkm_set_led_color(const LEDColor &color) { + Wire.begin(); + Wire.beginTransmission(I2C_ADDRESS(0x09)); + Wire.write('o'); //to disable ongoing script, only needs to be used once + Wire.write('n'); + Wire.write(color.r); + Wire.write(color.g); + Wire.write(color.b); + Wire.endTransmission(); +} + +#endif // BLINKM diff --git a/src/feature/leds/blinkm.h b/src/feature/leds/blinkm.h new file mode 100644 index 0000000..29a9e78 --- /dev/null +++ b/src/feature/leds/blinkm.h @@ -0,0 +1,31 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * blinkm.h - Control a BlinkM over i2c + */ + +struct LEDColor; +typedef LEDColor LEDColor; + +void blinkm_set_led_color(const LEDColor &color); diff --git a/src/feature/leds/leds.cpp b/src/feature/leds/leds.cpp new file mode 100644 index 0000000..2a53a7c --- /dev/null +++ b/src/feature/leds/leds.cpp @@ -0,0 +1,219 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * leds.cpp - Marlin RGB LED general support + */ + +#include "../../inc/MarlinConfig.h" + +#if HAS_COLOR_LEDS + +#include "leds.h" + +#if ENABLED(BLINKM) + #include "blinkm.h" +#endif + +#if ENABLED(PCA9632) + #include "pca9632.h" +#endif + +#if ENABLED(PCA9533) + #include "pca9533.h" +#endif + +#if EITHER(CASE_LIGHT_USE_RGB_LED, CASE_LIGHT_USE_NEOPIXEL) + #include "../../feature/caselight.h" +#endif + +#if ENABLED(LED_COLOR_PRESETS) + const LEDColor LEDLights::defaultLEDColor = LEDColor( + LED_USER_PRESET_RED, LED_USER_PRESET_GREEN, LED_USER_PRESET_BLUE + OPTARG(HAS_WHITE_LED, LED_USER_PRESET_WHITE) + OPTARG(NEOPIXEL_LED, LED_USER_PRESET_BRIGHTNESS) + ); +#endif + +#if ANY(LED_CONTROL_MENU, PRINTER_EVENT_LEDS, CASE_LIGHT_IS_COLOR_LED) + LEDColor LEDLights::color; + bool LEDLights::lights_on; +#endif + +LEDLights leds; + +void LEDLights::setup() { + #if EITHER(RGB_LED, RGBW_LED) + if (PWM_PIN(RGB_LED_R_PIN)) SET_PWM(RGB_LED_R_PIN); else SET_OUTPUT(RGB_LED_R_PIN); + if (PWM_PIN(RGB_LED_G_PIN)) SET_PWM(RGB_LED_G_PIN); else SET_OUTPUT(RGB_LED_G_PIN); + if (PWM_PIN(RGB_LED_B_PIN)) SET_PWM(RGB_LED_B_PIN); else SET_OUTPUT(RGB_LED_B_PIN); + #if ENABLED(RGBW_LED) + if (PWM_PIN(RGB_LED_W_PIN)) SET_PWM(RGB_LED_W_PIN); else SET_OUTPUT(RGB_LED_W_PIN); + #endif + #endif + TERN_(NEOPIXEL_LED, neo.init()); + TERN_(PCA9533, PCA9533_init()); + TERN_(LED_USER_PRESET_STARTUP, set_default()); +} + +void LEDLights::set_color(const LEDColor &incol + OPTARG(NEOPIXEL_IS_SEQUENTIAL, bool isSequence/*=false*/) +) { + + #if ENABLED(NEOPIXEL_LED) + + const uint32_t neocolor = LEDColorWhite() == incol + ? neo.Color(NEO_WHITE) + : neo.Color(incol.r, incol.g, incol.b OPTARG(HAS_WHITE_LED, incol.w)); + + #if ENABLED(NEOPIXEL_IS_SEQUENTIAL) + static uint16_t nextLed = 0; + #ifdef NEOPIXEL_BKGD_INDEX_FIRST + while (WITHIN(nextLed, NEOPIXEL_BKGD_INDEX_FIRST, NEOPIXEL_BKGD_INDEX_LAST)) { + neo.reset_background_color(); + if (++nextLed >= neo.pixels()) { nextLed = 0; return; } + } + #endif + #endif + + #if BOTH(CASE_LIGHT_MENU, CASE_LIGHT_USE_NEOPIXEL) + // Update brightness only if caselight is ON or switching leds off + if (caselight.on || incol.is_off()) + #endif + neo.set_brightness(incol.i); + + #if ENABLED(NEOPIXEL_IS_SEQUENTIAL) + if (isSequence) { + neo.set_pixel_color(nextLed, neocolor); + neo.show(); + if (++nextLed >= neo.pixels()) nextLed = 0; + return; + } + #endif + + #if BOTH(CASE_LIGHT_MENU, CASE_LIGHT_USE_NEOPIXEL) + // Update color only if caselight is ON or switching leds off + if (caselight.on || incol.is_off()) + #endif + neo.set_color(neocolor); + + #endif + + #if ENABLED(BLINKM) + + // This variant uses i2c to send the RGB components to the device. + blinkm_set_led_color(incol); + + #endif + + #if EITHER(RGB_LED, RGBW_LED) + + // This variant uses 3-4 separate pins for the RGB(W) components. + // If the pins can do PWM then their intensity will be set. + #define _UPDATE_RGBW(C,c) do { \ + if (PWM_PIN(RGB_LED_##C##_PIN)) \ + hal.set_pwm_duty(pin_t(RGB_LED_##C##_PIN), c); \ + else \ + WRITE(RGB_LED_##C##_PIN, c ? HIGH : LOW); \ + }while(0) + #define UPDATE_RGBW(C,c) _UPDATE_RGBW(C, TERN1(CASE_LIGHT_USE_RGB_LED, caselight.on) ? incol.c : 0) + UPDATE_RGBW(R,r); UPDATE_RGBW(G,g); UPDATE_RGBW(B,b); + #if ENABLED(RGBW_LED) + UPDATE_RGBW(W,w); + #endif + + #endif + + // Update I2C LED driver + TERN_(PCA9632, PCA9632_set_led_color(incol)); + TERN_(PCA9533, PCA9533_set_rgb(incol.r, incol.g, incol.b)); + + #if EITHER(LED_CONTROL_MENU, PRINTER_EVENT_LEDS) + // Don't update the color when OFF + lights_on = !incol.is_off(); + if (lights_on) color = incol; + #endif +} + +#if ENABLED(LED_CONTROL_MENU) + void LEDLights::toggle() { if (lights_on) set_off(); else update(); } +#endif + +#if LED_POWEROFF_TIMEOUT > 0 + + millis_t LEDLights::led_off_time; // = 0 + + void LEDLights::update_timeout(const bool power_on) { + if (lights_on) { + const millis_t ms = millis(); + if (power_on) + reset_timeout(ms); + else if (ELAPSED(ms, led_off_time)) + set_off(); + } + } + +#endif + +#if ENABLED(NEOPIXEL2_SEPARATE) + + #if ENABLED(NEO2_COLOR_PRESETS) + const LEDColor LEDLights2::defaultLEDColor = LEDColor( + NEO2_USER_PRESET_RED, NEO2_USER_PRESET_GREEN, NEO2_USER_PRESET_BLUE + OPTARG(HAS_WHITE_LED2, NEO2_USER_PRESET_WHITE) + OPTARG(NEOPIXEL_LED, NEO2_USER_PRESET_BRIGHTNESS) + ); + #endif + + #if ENABLED(LED_CONTROL_MENU) + LEDColor LEDLights2::color; + bool LEDLights2::lights_on; + #endif + + LEDLights2 leds2; + + void LEDLights2::setup() { + neo2.init(); + TERN_(NEO2_USER_PRESET_STARTUP, set_default()); + } + + void LEDLights2::set_color(const LEDColor &incol) { + const uint32_t neocolor = LEDColorWhite() == incol + ? neo2.Color(NEO2_WHITE) + : neo2.Color(incol.r, incol.g, incol.b OPTARG(HAS_WHITE_LED2, incol.w)); + neo2.set_brightness(incol.i); + neo2.set_color(neocolor); + + #if ENABLED(LED_CONTROL_MENU) + // Don't update the color when OFF + lights_on = !incol.is_off(); + if (lights_on) color = incol; + #endif + } + + #if ENABLED(LED_CONTROL_MENU) + void LEDLights2::toggle() { if (lights_on) set_off(); else update(); } + #endif + +#endif // NEOPIXEL2_SEPARATE + +#endif // HAS_COLOR_LEDS diff --git a/src/feature/leds/leds.h b/src/feature/leds/leds.h new file mode 100644 index 0000000..8649dd0 --- /dev/null +++ b/src/feature/leds/leds.h @@ -0,0 +1,216 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * leds.h - Marlin general RGB LED support + */ + +#include "../../inc/MarlinConfigPre.h" + +#include + +// A white component can be passed +#if EITHER(RGBW_LED, PCA9632_RGBW) + #define HAS_WHITE_LED 1 +#endif + +#if ENABLED(NEOPIXEL_LED) + #define _NEOPIXEL_INCLUDE_ + #include "neopixel.h" + #undef _NEOPIXEL_INCLUDE_ +#endif + +/** + * LEDcolor type for use with leds.set_color + */ +typedef struct LEDColor { + uint8_t r, g, b + OPTARG(HAS_WHITE_LED, w) + OPTARG(NEOPIXEL_LED, i) + ; + + LEDColor() : r(255), g(255), b(255) + OPTARG(HAS_WHITE_LED, w(255)) + OPTARG(NEOPIXEL_LED, i(NEOPIXEL_BRIGHTNESS)) + {} + + LEDColor(const LEDColor&) = default; + + LEDColor(uint8_t r, uint8_t g, uint8_t b OPTARG(HAS_WHITE_LED, uint8_t w=0) OPTARG(NEOPIXEL_LED, uint8_t i=NEOPIXEL_BRIGHTNESS)) + : r(r), g(g), b(b) OPTARG(HAS_WHITE_LED, w(w)) OPTARG(NEOPIXEL_LED, i(i)) {} + + LEDColor(const uint8_t (&rgbw)[4]) : r(rgbw[0]), g(rgbw[1]), b(rgbw[2]) + OPTARG(HAS_WHITE_LED, w(rgbw[3])) + OPTARG(NEOPIXEL_LED, i(NEOPIXEL_BRIGHTNESS)) + {} + + LEDColor& operator=(const uint8_t (&rgbw)[4]) { + r = rgbw[0]; g = rgbw[1]; b = rgbw[2]; + TERN_(HAS_WHITE_LED, w = rgbw[3]); + return *this; + } + + bool operator==(const LEDColor &right) { + if (this == &right) return true; + return 0 == memcmp(this, &right, sizeof(LEDColor)); + } + + bool operator!=(const LEDColor &right) { return !operator==(right); } + + bool is_off() const { + return 3 > r + g + b + TERN0(HAS_WHITE_LED, w); + } +} LEDColor; + +/** + * Color presets + */ + +#define LEDColorOff() LEDColor( 0, 0, 0) +#define LEDColorRed() LEDColor(255, 0, 0) +#if ENABLED(LED_COLORS_REDUCE_GREEN) + #define LEDColorOrange() LEDColor(255, 25, 0) + #define LEDColorYellow() LEDColor(255, 75, 0) +#else + #define LEDColorOrange() LEDColor(255, 80, 0) + #define LEDColorYellow() LEDColor(255, 255, 0) +#endif +#define LEDColorGreen() LEDColor( 0, 255, 0) +#define LEDColorBlue() LEDColor( 0, 0, 255) +#define LEDColorIndigo() LEDColor( 0, 255, 255) +#define LEDColorViolet() LEDColor(255, 0, 255) +#if HAS_WHITE_LED && DISABLED(RGB_LED) + #define LEDColorWhite() LEDColor( 0, 0, 0, 255) +#else + #define LEDColorWhite() LEDColor(255, 255, 255) +#endif + +class LEDLights { +public: + LEDLights() {} // ctor + + static void setup(); // init() + + static void set_color(const LEDColor &color + OPTARG(NEOPIXEL_IS_SEQUENTIAL, bool isSequence=false) + ); + + static void set_color(uint8_t r, uint8_t g, uint8_t b + OPTARG(HAS_WHITE_LED, uint8_t w=0) + OPTARG(NEOPIXEL_LED, uint8_t i=NEOPIXEL_BRIGHTNESS) + OPTARG(NEOPIXEL_IS_SEQUENTIAL, bool isSequence=false) + ) { + set_color(LEDColor(r, g, b OPTARG(HAS_WHITE_LED, w) OPTARG(NEOPIXEL_LED, i)) OPTARG(NEOPIXEL_IS_SEQUENTIAL, isSequence)); + } + + static void set_off() { set_color(LEDColorOff()); } + static void set_green() { set_color(LEDColorGreen()); } + static void set_white() { set_color(LEDColorWhite()); } + + #if ENABLED(LED_COLOR_PRESETS) + static const LEDColor defaultLEDColor; + static void set_default() { set_color(defaultLEDColor); } + static void set_red() { set_color(LEDColorRed()); } + static void set_orange() { set_color(LEDColorOrange()); } + static void set_yellow() { set_color(LEDColorYellow()); } + static void set_blue() { set_color(LEDColorBlue()); } + static void set_indigo() { set_color(LEDColorIndigo()); } + static void set_violet() { set_color(LEDColorViolet()); } + #endif + + #if ENABLED(PRINTER_EVENT_LEDS) + static LEDColor get_color() { return lights_on ? color : LEDColorOff(); } + #endif + + #if ANY(LED_CONTROL_MENU, PRINTER_EVENT_LEDS, CASE_LIGHT_IS_COLOR_LED) + static LEDColor color; // last non-off color + static bool lights_on; // the last set color was "on" + #endif + + #if ENABLED(LED_CONTROL_MENU) + static void toggle(); // swap "off" with color + #endif + #if EITHER(LED_CONTROL_MENU, CASE_LIGHT_USE_RGB_LED) + static void update() { set_color(color); } + #endif + + #if LED_POWEROFF_TIMEOUT > 0 + private: + static millis_t led_off_time; + public: + static void reset_timeout(const millis_t &ms) { + led_off_time = ms + LED_POWEROFF_TIMEOUT; + if (!lights_on) update(); + } + static void update_timeout(const bool power_on); + #endif +}; + +extern LEDLights leds; + +#if ENABLED(NEOPIXEL2_SEPARATE) + + class LEDLights2 { + public: + LEDLights2() {} + + static void setup(); // init() + + static void set_color(const LEDColor &color); + + static void set_color(uint8_t r, uint8_t g, uint8_t b + OPTARG(HAS_WHITE_LED, uint8_t w=0) + OPTARG(NEOPIXEL_LED, uint8_t i=NEOPIXEL_BRIGHTNESS) + ) { + set_color(LEDColor(r, g, b + OPTARG(HAS_WHITE_LED, w) + OPTARG(NEOPIXEL_LED, i) + )); + } + + static void set_off() { set_color(LEDColorOff()); } + static void set_green() { set_color(LEDColorGreen()); } + static void set_white() { set_color(LEDColorWhite()); } + + #if ENABLED(NEO2_COLOR_PRESETS) + static const LEDColor defaultLEDColor; + static void set_default() { set_color(defaultLEDColor); } + static void set_red() { set_color(LEDColorRed()); } + static void set_orange() { set_color(LEDColorOrange()); } + static void set_yellow() { set_color(LEDColorYellow()); } + static void set_blue() { set_color(LEDColorBlue()); } + static void set_indigo() { set_color(LEDColorIndigo()); } + static void set_violet() { set_color(LEDColorViolet()); } + #endif + + #if ENABLED(NEOPIXEL2_SEPARATE) + static LEDColor color; // last non-off color + static bool lights_on; // the last set color was "on" + static void toggle(); // swap "off" with color + static void update() { set_color(color); } + #endif + }; + + extern LEDLights2 leds2; + +#endif // NEOPIXEL2_SEPARATE diff --git a/src/feature/leds/neopixel.cpp b/src/feature/leds/neopixel.cpp new file mode 100644 index 0000000..4f10423 --- /dev/null +++ b/src/feature/leds/neopixel.cpp @@ -0,0 +1,168 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * Marlin RGB LED general support + */ + +#include "../../inc/MarlinConfig.h" + +#if ENABLED(NEOPIXEL_LED) + +#include "leds.h" + +#if EITHER(NEOPIXEL_STARTUP_TEST, NEOPIXEL2_STARTUP_TEST) + #include "../../core/utility.h" +#endif + +Marlin_NeoPixel neo; +pixel_index_t Marlin_NeoPixel::neoindex; + +Adafruit_NeoPixel Marlin_NeoPixel::adaneo1(NEOPIXEL_PIXELS, NEOPIXEL_PIN, NEOPIXEL_TYPE + NEO_KHZ800); +#if CONJOINED_NEOPIXEL + Adafruit_NeoPixel Marlin_NeoPixel::adaneo2(NEOPIXEL_PIXELS, NEOPIXEL2_PIN, NEOPIXEL2_TYPE + NEO_KHZ800); +#endif + +#ifdef NEOPIXEL_BKGD_INDEX_FIRST + + void Marlin_NeoPixel::set_background_color(const uint8_t r, const uint8_t g, const uint8_t b, const uint8_t w) { + for (int background_led = NEOPIXEL_BKGD_INDEX_FIRST; background_led <= NEOPIXEL_BKGD_INDEX_LAST; background_led++) + set_pixel_color(background_led, adaneo1.Color(r, g, b, w)); + } + + void Marlin_NeoPixel::reset_background_color() { + constexpr uint8_t background_color[4] = NEOPIXEL_BKGD_COLOR; + set_background_color(background_color); + } + +#endif + +void Marlin_NeoPixel::set_color(const uint32_t color) { + if (neoindex >= 0) { + set_pixel_color(neoindex, color); + neoindex = -1; + } + else { + for (uint16_t i = 0; i < pixels(); ++i) { + #ifdef NEOPIXEL_BKGD_INDEX_FIRST + if (i == NEOPIXEL_BKGD_INDEX_FIRST && TERN(NEOPIXEL_BKGD_ALWAYS_ON, true, color != 0x000000)) { + reset_background_color(); + i += NEOPIXEL_BKGD_INDEX_LAST - (NEOPIXEL_BKGD_INDEX_FIRST); + continue; + } + #endif + set_pixel_color(i, color); + } + } + show(); +} + +void Marlin_NeoPixel::set_color_startup(const uint32_t color) { + for (uint16_t i = 0; i < pixels(); ++i) + set_pixel_color(i, color); + show(); +} + +void Marlin_NeoPixel::init() { + neoindex = -1; // -1 .. NEOPIXEL_PIXELS-1 range + set_brightness(NEOPIXEL_BRIGHTNESS); // 0 .. 255 range + begin(); + show(); // initialize to all off + + #if ENABLED(NEOPIXEL_STARTUP_TEST) + set_color_startup(adaneo1.Color(255, 0, 0, 0)); // red + safe_delay(500); + set_color_startup(adaneo1.Color(0, 255, 0, 0)); // green + safe_delay(500); + set_color_startup(adaneo1.Color(0, 0, 255, 0)); // blue + safe_delay(500); + #if HAS_WHITE_LED + set_color_startup(adaneo1.Color(0, 0, 0, 255)); // white + safe_delay(500); + #endif + #endif + + #ifdef NEOPIXEL_BKGD_INDEX_FIRST + reset_background_color(); + #endif + + set_color(adaneo1.Color + TERN(LED_USER_PRESET_STARTUP, + (LED_USER_PRESET_RED, LED_USER_PRESET_GREEN, LED_USER_PRESET_BLUE, LED_USER_PRESET_WHITE), + (255, 255, 255, 255)) + ); +} + +#if ENABLED(NEOPIXEL2_SEPARATE) + + Marlin_NeoPixel2 neo2; + + pixel_index_t Marlin_NeoPixel2::neoindex; + Adafruit_NeoPixel Marlin_NeoPixel2::adaneo(NEOPIXEL2_PIXELS, NEOPIXEL2_PIN, NEOPIXEL2_TYPE); + + void Marlin_NeoPixel2::set_color(const uint32_t color) { + if (neoindex >= 0) { + set_pixel_color(neoindex, color); + neoindex = -1; + } + else { + for (uint16_t i = 0; i < pixels(); ++i) + set_pixel_color(i, color); + } + show(); + } + + void Marlin_NeoPixel2::set_color_startup(const uint32_t color) { + for (uint16_t i = 0; i < pixels(); ++i) + set_pixel_color(i, color); + show(); + } + + void Marlin_NeoPixel2::init() { + neoindex = -1; // -1 .. NEOPIXEL2_PIXELS-1 range + set_brightness(NEOPIXEL2_BRIGHTNESS); // 0 .. 255 range + begin(); + show(); // initialize to all off + + #if ENABLED(NEOPIXEL2_STARTUP_TEST) + set_color_startup(adaneo.Color(255, 0, 0, 0)); // red + safe_delay(500); + set_color_startup(adaneo.Color(0, 255, 0, 0)); // green + safe_delay(500); + set_color_startup(adaneo.Color(0, 0, 255, 0)); // blue + safe_delay(500); + #if HAS_WHITE_LED2 + set_color_startup(adaneo.Color(0, 0, 0, 255)); // white + safe_delay(500); + #endif + #endif + + set_color(adaneo.Color + TERN(NEO2_USER_PRESET_STARTUP, + (NEO2_USER_PRESET_RED, NEO2_USER_PRESET_GREEN, NEO2_USER_PRESET_BLUE, NEO2_USER_PRESET_WHITE), + (0, 0, 0, 0)) + ); + } + +#endif // NEOPIXEL2_SEPARATE + +#endif // NEOPIXEL_LED diff --git a/src/feature/leds/neopixel.h b/src/feature/leds/neopixel.h new file mode 100644 index 0000000..d71aa25 --- /dev/null +++ b/src/feature/leds/neopixel.h @@ -0,0 +1,187 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * NeoPixel support + */ + +#ifndef _NEOPIXEL_INCLUDE_ + #error "Always include 'leds.h' and not 'neopixel.h' directly." +#endif + +// ------------------------ +// Includes +// ------------------------ + +#include "../../inc/MarlinConfig.h" + +#include +#include + +// ------------------------ +// Defines +// ------------------------ + +#define _NEO_IS_RGB(N) (N == NEO_RGB || N == NEO_RBG || N == NEO_GRB || N == NEO_GBR || N == NEO_BRG || N == NEO_BGR) + +#if !_NEO_IS_RGB(NEOPIXEL_TYPE) + #define HAS_WHITE_LED 1 +#endif + +#if HAS_WHITE_LED + #define NEO_WHITE 0, 0, 0, 255 +#else + #define NEO_WHITE 255, 255, 255 +#endif + +#if defined(NEOPIXEL2_TYPE) && NEOPIXEL2_TYPE != NEOPIXEL_TYPE && DISABLED(NEOPIXEL2_SEPARATE) + #define MULTIPLE_NEOPIXEL_TYPES 1 +#endif + +#if EITHER(MULTIPLE_NEOPIXEL_TYPES, NEOPIXEL2_INSERIES) + #define CONJOINED_NEOPIXEL 1 +#endif + +// ------------------------ +// Types +// ------------------------ + +typedef IF<(TERN0(NEOPIXEL_LED, NEOPIXEL_PIXELS > 127)), int16_t, int8_t>::type pixel_index_t; + +// ------------------------ +// Classes +// ------------------------ + +class Marlin_NeoPixel { +private: + static Adafruit_NeoPixel adaneo1; + #if CONJOINED_NEOPIXEL + static Adafruit_NeoPixel adaneo2; + #endif + +public: + static pixel_index_t neoindex; + + static void init(); + static void set_color_startup(const uint32_t c); + + static void set_color(const uint32_t c); + + #ifdef NEOPIXEL_BKGD_INDEX_FIRST + static void set_background_color(const uint8_t r, const uint8_t g, const uint8_t b, const uint8_t w); + static void set_background_color(const uint8_t (&rgbw)[4]) { set_background_color(rgbw[0], rgbw[1], rgbw[2], rgbw[3]); } + static void reset_background_color(); + #endif + + static void begin() { + adaneo1.begin(); + TERN_(CONJOINED_NEOPIXEL, adaneo2.begin()); + } + + static void set_pixel_color(const uint16_t n, const uint32_t c) { + #if ENABLED(NEOPIXEL2_INSERIES) + if (n >= NEOPIXEL_PIXELS) adaneo2.setPixelColor(n - (NEOPIXEL_PIXELS), c); + else adaneo1.setPixelColor(n, c); + #else + adaneo1.setPixelColor(n, c); + TERN_(MULTIPLE_NEOPIXEL_TYPES, adaneo2.setPixelColor(n, c)); + #endif + } + + static void set_brightness(const uint8_t b) { + adaneo1.setBrightness(b); + TERN_(CONJOINED_NEOPIXEL, adaneo2.setBrightness(b)); + } + + static void show() { + // Some platforms cannot maintain PWM output when NeoPixel disables interrupts for long durations. + TERN_(HAS_PAUSE_SERVO_OUTPUT, PAUSE_SERVO_OUTPUT()); + adaneo1.show(); + #if PIN_EXISTS(NEOPIXEL2) + #if CONJOINED_NEOPIXEL + adaneo2.show(); + #else + adaneo1.show(); + adaneo1.setPin(NEOPIXEL_PIN); + #endif + #endif + TERN_(HAS_PAUSE_SERVO_OUTPUT, RESUME_SERVO_OUTPUT()); + } + + // Accessors + static uint16_t pixels() { return adaneo1.numPixels() * TERN1(NEOPIXEL2_INSERIES, 2); } + + static uint8_t brightness() { return adaneo1.getBrightness(); } + + static uint32_t Color(uint8_t r, uint8_t g, uint8_t b OPTARG(HAS_WHITE_LED, uint8_t w)) { + return adaneo1.Color(r, g, b OPTARG(HAS_WHITE_LED, w)); + } +}; + +extern Marlin_NeoPixel neo; + +// Neo pixel channel 2 +#if ENABLED(NEOPIXEL2_SEPARATE) + + #if _NEO_IS_RGB(NEOPIXEL2_TYPE) + #define NEOPIXEL2_IS_RGB 1 + #define NEO2_WHITE 255, 255, 255 + #else + #define NEOPIXEL2_IS_RGBW 1 + #define HAS_WHITE_LED2 1 // A white component can be passed for NEOPIXEL2 + #define NEO2_WHITE 0, 0, 0, 255 + #endif + + class Marlin_NeoPixel2 { + private: + static Adafruit_NeoPixel adaneo; + + public: + static pixel_index_t neoindex; + + static void init(); + static void set_color_startup(const uint32_t c); + + static void set_color(const uint32_t c); + + static void begin() { adaneo.begin(); } + static void set_pixel_color(const uint16_t n, const uint32_t c) { adaneo.setPixelColor(n, c); } + static void set_brightness(const uint8_t b) { adaneo.setBrightness(b); } + static void show() { + adaneo.show(); + adaneo.setPin(NEOPIXEL2_PIN); + } + + // Accessors + static uint16_t pixels() { return adaneo.numPixels();} + static uint8_t brightness() { return adaneo.getBrightness(); } + static uint32_t Color(uint8_t r, uint8_t g, uint8_t b OPTARG(HAS_WHITE_LED2, uint8_t w)) { + return adaneo.Color(r, g, b OPTARG(HAS_WHITE_LED2, w)); + } + }; + + extern Marlin_NeoPixel2 neo2; + +#endif // NEOPIXEL2_SEPARATE + +#undef _NEO_IS_RGB diff --git a/src/feature/leds/pca9533.cpp b/src/feature/leds/pca9533.cpp new file mode 100644 index 0000000..914db21 --- /dev/null +++ b/src/feature/leds/pca9533.cpp @@ -0,0 +1,127 @@ +/* + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * PCA9533 LED controller driver (MightyBoard, FlashForge Creator Pro, etc.) + * by @grauerfuchs - 1 Apr 2020 + */ +#include "../../inc/MarlinConfig.h" + +#if ENABLED(PCA9533) + +#include "pca9533.h" +#include + +void PCA9533_init() { + Wire.begin(); + PCA9533_reset(); +} + +static void PCA9533_writeAllRegisters(uint8_t psc0, uint8_t pwm0, uint8_t psc1, uint8_t pwm1, uint8_t ls0) { + uint8_t data[6] = { PCA9533_REG_PSC0 | PCA9533_REGM_AI, psc0, pwm0, psc1, pwm1, ls0 }; + Wire.beginTransmission(PCA9533_Addr >> 1); + Wire.write(data, 6); + Wire.endTransmission(); + delayMicroseconds(1); +} + +static void PCA9533_writeRegister(uint8_t reg, uint8_t val) { + uint8_t data[2] = { reg, val }; + Wire.beginTransmission(PCA9533_Addr >> 1); + Wire.write(data, 2); + Wire.endTransmission(); + delayMicroseconds(1); +} + +// Reset (clear) all registers +void PCA9533_reset() { + PCA9533_writeAllRegisters(0, 0, 0, 0, 0); +} + +// Turn all LEDs off +void PCA9533_setOff() { + PCA9533_writeRegister(PCA9533_REG_SEL, 0); +} + +void PCA9533_set_rgb(uint8_t red, uint8_t green, uint8_t blue) { + uint8_t r_pwm0 = 0; // Register data - PWM value + uint8_t r_pwm1 = 0; // Register data - PWM value + + uint8_t op_g = 0, op_r = 0, op_b = 0; // Opcodes - Green, Red, Blue + + // Light theory! GREEN takes priority because + // it's the most visible to the human eye. + if (green == 0) op_g = PCA9533_LED_OP_OFF; + else if (green == 255) op_g = PCA9533_LED_OP_ON; + else { r_pwm0 = green; op_g = PCA9533_LED_OP_PWM0; } + + // RED + if (red == 0) op_r = PCA9533_LED_OP_OFF; + else if (red == 255) op_r = PCA9533_LED_OP_ON; + else if (r_pwm0 == 0 || r_pwm0 == red) { + r_pwm0 = red; op_r = PCA9533_LED_OP_PWM0; + } + else { + r_pwm1 = red; op_r = PCA9533_LED_OP_PWM1; + } + + // BLUE + if (blue == 0) op_b = PCA9533_LED_OP_OFF; + else if (blue == 255) op_b = PCA9533_LED_OP_ON; + else if (r_pwm0 == 0 || r_pwm0 == blue) { + r_pwm0 = blue; op_b = PCA9533_LED_OP_PWM0; + } + else if (r_pwm1 == 0 || r_pwm1 == blue) { + r_pwm1 = blue; op_b = PCA9533_LED_OP_PWM1; + } + else { + /** + * Conflict. 3 values are requested but only 2 channels exist. + * G is on channel 0 and R is on channel 1, so work from there. + * Find the closest match, average the values, then use the free channel. + */ + uint8_t dgb = ABS(green - blue), + dgr = ABS(green - red), + dbr = ABS(blue - red); + if (dgb < dgr && dgb < dbr) { // Mix with G on channel 0. + op_b = PCA9533_LED_OP_PWM0; + r_pwm0 = uint8_t(((uint16_t)green + (uint16_t)blue) / 2); + } + else if (dbr <= dgr && dbr <= dgb) { // Mix with R on channel 1. + op_b = PCA9533_LED_OP_PWM1; + r_pwm1 = uint8_t(((uint16_t)red + (uint16_t)blue) / 2); + } + else { // Mix R+G on 0 and put B on 1. + op_r = PCA9533_LED_OP_PWM0; + r_pwm0 = uint8_t(((uint16_t)green + (uint16_t)red) / 2); + op_b = PCA9533_LED_OP_PWM1; + r_pwm1 = blue; + } + } + + // Write the changes to the hardware + PCA9533_writeAllRegisters(0, r_pwm0, 0, r_pwm1, + (op_g << PCA9533_LED_OFS_GRN) | (op_r << PCA9533_LED_OFS_RED) | (op_b << PCA9533_LED_OFS_BLU) + ); +} + +#endif // PCA9533 diff --git a/src/feature/leds/pca9533.h b/src/feature/leds/pca9533.h new file mode 100644 index 0000000..431058c --- /dev/null +++ b/src/feature/leds/pca9533.h @@ -0,0 +1,59 @@ +/* + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/* + * Driver for the PCA9533 LED controller found on the MightyBoard + * used by FlashForge Creator Pro, MakerBot, etc. + * Written 2020 APR 01 by grauerfuchs + */ +#include + +#define ENABLE_I2C_PULLUPS + +// Chip address (for Wire) +#define PCA9533_Addr 0xC4 + +// Control registers +#define PCA9533_REG_READ 0x00 +#define PCA9533_REG_PSC0 0x01 +#define PCA9533_REG_PWM0 0x02 +#define PCA9533_REG_PSC1 0x03 +#define PCA9533_REG_PWM1 0x04 +#define PCA9533_REG_SEL 0x05 +#define PCA9533_REGM_AI 0x10 + +// LED selector operation +#define PCA9533_LED_OP_OFF 0B00 +#define PCA9533_LED_OP_ON 0B01 +#define PCA9533_LED_OP_PWM0 0B10 +#define PCA9533_LED_OP_PWM1 0B11 + +// Select register bit offsets for LED colors +#define PCA9533_LED_OFS_RED 0 +#define PCA9533_LED_OFS_GRN 2 +#define PCA9533_LED_OFS_BLU 4 + +void PCA9533_init(); +void PCA9533_reset(); +void PCA9533_set_rgb(uint8_t red, uint8_t green, uint8_t blue); +void PCA9533_setOff(); diff --git a/src/feature/leds/pca9632.cpp b/src/feature/leds/pca9632.cpp new file mode 100644 index 0000000..abea988 --- /dev/null +++ b/src/feature/leds/pca9632.cpp @@ -0,0 +1,160 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * Driver for the Philips PCA9632 LED driver. + * Written by Robert Mendon Feb 2017. + */ + +#include "../../inc/MarlinConfig.h" + +#if ENABLED(PCA9632) + +#include "pca9632.h" +#include "leds.h" +#include + +#define PCA9632_MODE1_VALUE 0b00000001 //(ALLCALL) +#define PCA9632_MODE2_VALUE 0b00010101 //(DIMMING, INVERT, CHANGE ON STOP,TOTEM) +#define PCA9632_LEDOUT_VALUE 0b00101010 + +/* Register addresses */ +#define PCA9632_MODE1 0x00 +#define PCA9632_MODE2 0x01 +#define PCA9632_PWM0 0x02 +#define PCA9632_PWM1 0x03 +#define PCA9632_PWM2 0x04 +#define PCA9632_PWM3 0x05 +#define PCA9632_GRPPWM 0x06 +#define PCA9632_GRPFREQ 0x07 +#define PCA9632_LEDOUT 0x08 +#define PCA9632_SUBADR1 0x09 +#define PCA9632_SUBADR2 0x0A +#define PCA9632_SUBADR3 0x0B +#define PCA9632_ALLCALLADDR 0x0C + +#define PCA9632_NO_AUTOINC 0x00 +#define PCA9632_AUTO_ALL 0x80 +#define PCA9632_AUTO_IND 0xA0 +#define PCA9632_AUTOGLO 0xC0 +#define PCA9632_AUTOGI 0xE0 + +// Red=LED0 Green=LED1 Blue=LED2 White=LED3 +#ifndef PCA9632_RED + #define PCA9632_RED 0x00 +#endif +#ifndef PCA9632_GRN + #define PCA9632_GRN 0x02 +#endif +#ifndef PCA9632_BLU + #define PCA9632_BLU 0x04 +#endif +#if HAS_WHITE_LED && !defined(PCA9632_WHT) + #define PCA9632_WHT 0x06 +#endif + +// If any of the color indexes are greater than 0x04 they can't use auto increment +#if !defined(PCA9632_NO_AUTO_INC) && (PCA9632_RED > 0x04 || PCA9632_GRN > 0x04 || PCA9632_BLU > 0x04 || PCA9632_WHT > 0x04) + #define PCA9632_NO_AUTO_INC +#endif + +#define LED_OFF 0x00 +#define LED_ON 0x01 +#define LED_PWM 0x02 + +#define PCA9632_ADDRESS 0b01100000 + +byte PCA_init = 0; + +static void PCA9632_WriteRegister(const byte addr, const byte regadd, const byte value) { + Wire.beginTransmission(I2C_ADDRESS(addr)); + Wire.write(regadd); + Wire.write(value); + Wire.endTransmission(); +} + +static void PCA9632_WriteAllRegisters(const byte addr, const byte regadd, const byte vr, const byte vg, const byte vb + OPTARG(PCA9632_RGBW, const byte vw) +) { + #if DISABLED(PCA9632_NO_AUTO_INC) + uint8_t data[4]; + data[0] = PCA9632_AUTO_IND | regadd; + data[1 + (PCA9632_RED >> 1)] = vr; + data[1 + (PCA9632_GRN >> 1)] = vg; + data[1 + (PCA9632_BLU >> 1)] = vb; + Wire.beginTransmission(I2C_ADDRESS(addr)); + Wire.write(data, sizeof(data)); + Wire.endTransmission(); + #else + PCA9632_WriteRegister(addr, regadd + (PCA9632_RED >> 1), vr); + PCA9632_WriteRegister(addr, regadd + (PCA9632_GRN >> 1), vg); + PCA9632_WriteRegister(addr, regadd + (PCA9632_BLU >> 1), vb); + #if ENABLED(PCA9632_RGBW) + PCA9632_WriteRegister(addr, regadd + (PCA9632_WHT >> 1), vw); + #endif + #endif +} + +#if 0 + static byte PCA9632_ReadRegister(const byte addr, const byte regadd) { + Wire.beginTransmission(I2C_ADDRESS(addr)); + Wire.write(regadd); + const byte value = Wire.read(); + Wire.endTransmission(); + return value; + } +#endif + +void PCA9632_set_led_color(const LEDColor &color) { + Wire.begin(); + if (!PCA_init) { + PCA_init = 1; + PCA9632_WriteRegister(PCA9632_ADDRESS,PCA9632_MODE1, PCA9632_MODE1_VALUE); + PCA9632_WriteRegister(PCA9632_ADDRESS,PCA9632_MODE2, PCA9632_MODE2_VALUE); + } + + const byte LEDOUT = (color.r ? LED_PWM << PCA9632_RED : 0) + | (color.g ? LED_PWM << PCA9632_GRN : 0) + | (color.b ? LED_PWM << PCA9632_BLU : 0) + #if ENABLED(PCA9632_RGBW) + | (color.w ? LED_PWM << PCA9632_WHT : 0) + #endif + ; + + PCA9632_WriteAllRegisters(PCA9632_ADDRESS,PCA9632_PWM0, color.r, color.g, color.b + OPTARG(PCA9632_RGBW, color.w) + ); + PCA9632_WriteRegister(PCA9632_ADDRESS,PCA9632_LEDOUT, LEDOUT); +} + +#if ENABLED(PCA9632_BUZZER) + + void PCA9632_buzz(const long, const uint16_t) { + uint8_t data[] = PCA9632_BUZZER_DATA; + Wire.beginTransmission(I2C_ADDRESS(PCA9632_ADDRESS)); + Wire.write(data, sizeof(data)); + Wire.endTransmission(); + } + +#endif // PCA9632_BUZZER + +#endif // PCA9632 diff --git a/src/feature/leds/pca9632.h b/src/feature/leds/pca9632.h new file mode 100644 index 0000000..fb59a8c --- /dev/null +++ b/src/feature/leds/pca9632.h @@ -0,0 +1,37 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * Driver for the Philips PCA9632 LED driver. + * Written by Robert Mendon Feb 2017. + */ + +struct LEDColor; +typedef LEDColor LEDColor; + +void PCA9632_set_led_color(const LEDColor &color); + +#if ENABLED(PCA9632_BUZZER) + #include + void PCA9632_buzz(const long, const uint16_t); +#endif diff --git a/src/feature/leds/printer_event_leds.cpp b/src/feature/leds/printer_event_leds.cpp new file mode 100644 index 0000000..e6407a6 --- /dev/null +++ b/src/feature/leds/printer_event_leds.cpp @@ -0,0 +1,93 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * feature/leds/printer_event_leds.cpp - LED color changing based on printer status + */ + +#include "../../inc/MarlinConfigPre.h" + +#if ENABLED(PRINTER_EVENT_LEDS) + +#include "printer_event_leds.h" + +PrinterEventLEDs printerEventLEDs; + +#if HAS_LEDS_OFF_FLAG + bool PrinterEventLEDs::leds_off_after_print; // = false +#endif + +#if HAS_TEMP_HOTEND || HAS_HEATED_BED + + uint8_t PrinterEventLEDs::old_intensity = 0; + + inline uint8_t pel_intensity(const celsius_t start, const celsius_t current, const celsius_t target) { + if (start == target) return 255; + return (uint8_t)map(constrain(current, start, target), start, target, 0, 255); + } + + inline void pel_set_rgb(const uint8_t r, const uint8_t g, const uint8_t b OPTARG(HAS_WHITE_LED, const uint8_t w=0)) { + leds.set_color( + LEDColor(r, g, b OPTARG(HAS_WHITE_LED, w) OPTARG(NEOPIXEL_LED, neo.brightness())) + OPTARG(NEOPIXEL_IS_SEQUENTIAL, true) + ); + } + +#endif + +#if HAS_TEMP_HOTEND + + void PrinterEventLEDs::onHotendHeating(const celsius_t start, const celsius_t current, const celsius_t target) { + const uint8_t blue = pel_intensity(start, current, target); + if (blue != old_intensity) { + old_intensity = blue; + pel_set_rgb(255, 0, 255 - blue); + } + } + +#endif + +#if HAS_HEATED_BED + + void PrinterEventLEDs::onBedHeating(const celsius_t start, const celsius_t current, const celsius_t target) { + const uint8_t red = pel_intensity(start, current, target); + if (red != old_intensity) { + old_intensity = red; + pel_set_rgb(red, 0, 255); + } + } + +#endif + +#if HAS_HEATED_CHAMBER + + void PrinterEventLEDs::onChamberHeating(const celsius_t start, const celsius_t current, const celsius_t target) { + const uint8_t green = pel_intensity(start, current, target); + if (green != old_intensity) { + old_intensity = green; + pel_set_rgb(255, green, 255); + } + } + +#endif + +#endif // PRINTER_EVENT_LEDS diff --git a/src/feature/leds/printer_event_leds.h b/src/feature/leds/printer_event_leds.h new file mode 100644 index 0000000..2a4342e --- /dev/null +++ b/src/feature/leds/printer_event_leds.h @@ -0,0 +1,86 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * feature/leds/printer_event_leds.h - LED color changing based on printer status + */ + +#include "leds.h" +#include "../../inc/MarlinConfig.h" + +class PrinterEventLEDs { +private: + static uint8_t old_intensity; + + #if HAS_LEDS_OFF_FLAG + static bool leds_off_after_print; + #endif + + static void set_done() { TERN(LED_COLOR_PRESETS, leds.set_default(), leds.set_off()); } + +public: + #if HAS_TEMP_HOTEND + static LEDColor onHotendHeatingStart() { old_intensity = 0; return leds.get_color(); } + static void onHotendHeating(const celsius_t start, const celsius_t current, const celsius_t target); + #endif + + #if HAS_HEATED_BED + static LEDColor onBedHeatingStart() { old_intensity = 127; return leds.get_color(); } + static void onBedHeating(const celsius_t start, const celsius_t current, const celsius_t target); + #endif + + #if HAS_HEATED_CHAMBER + static LEDColor onChamberHeatingStart() { old_intensity = 127; return leds.get_color(); } + static void onChamberHeating(const celsius_t start, const celsius_t current, const celsius_t target); + #endif + + #if HAS_TEMP_HOTEND || HAS_HEATED_BED || HAS_HEATED_CHAMBER + static void onHeatingDone() { leds.set_white(); } + static void onPidTuningDone(LEDColor c) { leds.set_color(c); } + #endif + + #if ENABLED(SDSUPPORT) + + static void onPrintCompleted() { + leds.set_green(); + #if HAS_LEDS_OFF_FLAG + leds_off_after_print = true; + #else + safe_delay(2000); + set_done(); + #endif + } + + static void onResumeAfterWait() { + #if HAS_LEDS_OFF_FLAG + if (leds_off_after_print) { + set_done(); + leds_off_after_print = false; + } + #endif + } + + #endif // SDSUPPORT +}; + +extern PrinterEventLEDs printerEventLEDs; diff --git a/src/feature/leds/tempstat.cpp b/src/feature/leds/tempstat.cpp new file mode 100644 index 0000000..967b9f4 --- /dev/null +++ b/src/feature/leds/tempstat.cpp @@ -0,0 +1,55 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * Marlin RGB LED general support + */ + +#include "../../inc/MarlinConfig.h" + +#if ENABLED(TEMP_STAT_LEDS) + +#include "tempstat.h" +#include "../../module/temperature.h" + +void handle_status_leds() { + static int8_t old_red = -1; // Invalid value to force LED initialization + static millis_t next_status_led_update_ms = 0; + if (ELAPSED(millis(), next_status_led_update_ms)) { + next_status_led_update_ms += 500; // Update every 0.5s + celsius_t max_temp = TERN0(HAS_HEATED_BED, _MAX(thermalManager.degTargetBed(), thermalManager.wholeDegBed())); + HOTEND_LOOP() + max_temp = _MAX(max_temp, thermalManager.wholeDegHotend(e), thermalManager.degTargetHotend(e)); + const int8_t new_red = (max_temp > 55) ? HIGH : (max_temp < 54 || old_red < 0) ? LOW : old_red; + if (new_red != old_red) { + old_red = new_red; + #if PIN_EXISTS(STAT_LED_RED) + WRITE(STAT_LED_RED_PIN, new_red); + #endif + #if PIN_EXISTS(STAT_LED_BLUE) + WRITE(STAT_LED_BLUE_PIN, !new_red); + #endif + } + } +} + +#endif // TEMP_STAT_LEDS diff --git a/src/feature/leds/tempstat.h b/src/feature/leds/tempstat.h new file mode 100644 index 0000000..a8b919b --- /dev/null +++ b/src/feature/leds/tempstat.h @@ -0,0 +1,28 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * Marlin general RGB LED support + */ + +void handle_status_leds(); diff --git a/src/feature/max7219.cpp b/src/feature/max7219.cpp new file mode 100644 index 0000000..ef698f8 --- /dev/null +++ b/src/feature/max7219.cpp @@ -0,0 +1,698 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * This module is off by default, but can be enabled to facilitate the display of + * extra debug information during code development. + * + * Just connect up 5V and GND to give it power, then connect up the pins assigned + * in Configuration_adv.h. For example, on the Re-ARM you could use: + * + * #define MAX7219_CLK_PIN 77 + * #define MAX7219_DIN_PIN 78 + * #define MAX7219_LOAD_PIN 79 + * + * send() is called automatically at startup, and then there are a number of + * support functions available to control the LEDs in the 8x8 grid. + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(MAX7219_DEBUG) + +#define MAX7219_ERRORS // Disable to save 406 bytes of Program Memory + +#include "max7219.h" + +#include "../module/planner.h" +#include "../MarlinCore.h" +#include "../HAL/shared/Delay.h" + +#if ENABLED(MAX7219_SIDE_BY_SIDE) && MAX7219_NUMBER_UNITS > 1 + #define HAS_SIDE_BY_SIDE 1 +#endif + +#if _ROT == 0 || _ROT == 180 + #define MAX7219_X_LEDS TERN(HAS_SIDE_BY_SIDE, 8, MAX7219_LINES) + #define MAX7219_Y_LEDS TERN(HAS_SIDE_BY_SIDE, MAX7219_LINES, 8) +#elif _ROT == 90 || _ROT == 270 + #define MAX7219_X_LEDS TERN(HAS_SIDE_BY_SIDE, MAX7219_LINES, 8) + #define MAX7219_Y_LEDS TERN(HAS_SIDE_BY_SIDE, 8, MAX7219_LINES) +#else + #error "MAX7219_ROTATE must be a multiple of +/- 90°." +#endif + +Max7219 max7219; + +uint8_t Max7219::led_line[MAX7219_LINES]; // = { 0 }; +uint8_t Max7219::suspended; // = 0; + +#define LINE_REG(Q) (max7219_reg_digit0 + ((Q) & 0x7)) + +#if _ROT == 0 || _ROT == 270 + #define _LED_BIT(Q) (7 - ((Q) & 0x7)) +#else + #define _LED_BIT(Q) ((Q) & 0x7) +#endif +#if _ROT == 0 || _ROT == 180 + #define LED_BIT(X,Y) _LED_BIT(X) +#else + #define LED_BIT(X,Y) _LED_BIT(Y) +#endif +#if _ROT == 0 || _ROT == 90 + #define _LED_IND(P,Q) (_LED_TOP(P) + ((Q) & 0x7)) +#else + #define _LED_IND(P,Q) (_LED_TOP(P) + (7 - ((Q) & 0x7))) +#endif + +#if HAS_SIDE_BY_SIDE + #if (_ROT == 0 || _ROT == 90) == DISABLED(MAX7219_REVERSE_ORDER) + #define _LED_TOP(Q) ((MAX7219_NUMBER_UNITS - 1 - ((Q) >> 3)) << 3) + #else + #define _LED_TOP(Q) ((Q) & ~0x7) + #endif + #if _ROT == 0 || _ROT == 180 + #define LED_IND(X,Y) _LED_IND(Y,Y) + #elif _ROT == 90 || _ROT == 270 + #define LED_IND(X,Y) _LED_IND(X,X) + #endif +#else + #if (_ROT == 0 || _ROT == 270) == DISABLED(MAX7219_REVERSE_ORDER) + #define _LED_TOP(Q) ((Q) & ~0x7) + #else + #define _LED_TOP(Q) ((MAX7219_NUMBER_UNITS - 1 - ((Q) >> 3)) << 3) + #endif + #if _ROT == 0 || _ROT == 180 + #define LED_IND(X,Y) _LED_IND(X,Y) + #elif _ROT == 90 || _ROT == 270 + #define LED_IND(X,Y) _LED_IND(Y,X) + #endif +#endif + +#define XOR_7219(X,Y) do{ led_line[LED_IND(X,Y)] ^= _BV(LED_BIT(X,Y)); }while(0) +#define SET_7219(X,Y) do{ led_line[LED_IND(X,Y)] |= _BV(LED_BIT(X,Y)); }while(0) +#define CLR_7219(X,Y) do{ led_line[LED_IND(X,Y)] &= ~_BV(LED_BIT(X,Y)); }while(0) +#define BIT_7219(X,Y) TEST(led_line[LED_IND(X,Y)], LED_BIT(X,Y)) + +#ifdef CPU_32_BIT + #define SIG_DELAY() DELAY_US(1) // Approximate a 1µs delay on 32-bit ARM + #undef CRITICAL_SECTION_START + #undef CRITICAL_SECTION_END + #define CRITICAL_SECTION_START() NOOP + #define CRITICAL_SECTION_END() NOOP +#else + #define SIG_DELAY() DELAY_NS(250) +#endif + +void Max7219::error(FSTR_P const func, const int32_t v1, const int32_t v2/*=-1*/) { + #if ENABLED(MAX7219_ERRORS) + SERIAL_ECHOPGM("??? Max7219::"); + SERIAL_ECHOF(func, AS_CHAR('(')); + SERIAL_ECHO(v1); + if (v2 > 0) SERIAL_ECHOPGM(", ", v2); + SERIAL_CHAR(')'); + SERIAL_EOL(); + #else + UNUSED(func); UNUSED(v1); UNUSED(v2); + #endif +} + +/** + * Flip the lowest n_bytes of the supplied bits: + * flipped(x, 1) flips the low 8 bits of x. + * flipped(x, 2) flips the low 16 bits of x. + * flipped(x, 3) flips the low 24 bits of x. + * flipped(x, 4) flips the low 32 bits of x. + */ +inline uint32_t flipped(const uint32_t bits, const uint8_t n_bytes) { + uint32_t mask = 1, outbits = 0; + LOOP_L_N(b, n_bytes * 8) { + outbits <<= 1; + if (bits & mask) outbits |= 1; + mask <<= 1; + } + return outbits; +} + +void Max7219::noop() { + CRITICAL_SECTION_START(); + SIG_DELAY(); + WRITE(MAX7219_DIN_PIN, LOW); + for (uint8_t i = 16; i--;) { + SIG_DELAY(); + WRITE(MAX7219_CLK_PIN, LOW); + SIG_DELAY(); + SIG_DELAY(); + WRITE(MAX7219_CLK_PIN, HIGH); + SIG_DELAY(); + } + CRITICAL_SECTION_END(); +} + +void Max7219::putbyte(uint8_t data) { + CRITICAL_SECTION_START(); + for (uint8_t i = 8; i--;) { + SIG_DELAY(); + WRITE(MAX7219_CLK_PIN, LOW); // tick + SIG_DELAY(); + WRITE(MAX7219_DIN_PIN, (data & 0x80) ? HIGH : LOW); // send 1 or 0 based on data bit + SIG_DELAY(); + WRITE(MAX7219_CLK_PIN, HIGH); // tock + SIG_DELAY(); + data <<= 1; + } + CRITICAL_SECTION_END(); +} + +void Max7219::pulse_load() { + SIG_DELAY(); + WRITE(MAX7219_LOAD_PIN, LOW); // tell the chip to load the data + SIG_DELAY(); + WRITE(MAX7219_LOAD_PIN, HIGH); + SIG_DELAY(); +} + +void Max7219::send(const uint8_t reg, const uint8_t data) { + SIG_DELAY(); + CRITICAL_SECTION_START(); + SIG_DELAY(); + putbyte(reg); // specify register + SIG_DELAY(); + putbyte(data); // put data + CRITICAL_SECTION_END(); +} + +// Send out a single native row of bits to just one unit +void Max7219::refresh_unit_line(const uint8_t line) { + if (suspended) return; + #if MAX7219_NUMBER_UNITS == 1 + send(LINE_REG(line), led_line[line]); + #else + for (uint8_t u = MAX7219_NUMBER_UNITS; u--;) + if (u == (line >> 3)) send(LINE_REG(line), led_line[line]); else noop(); + #endif + pulse_load(); +} + +// Send out a single native row of bits to all units +void Max7219::refresh_line(const uint8_t line) { + if (suspended) return; + #if MAX7219_NUMBER_UNITS == 1 + refresh_unit_line(line); + #else + for (uint8_t u = MAX7219_NUMBER_UNITS; u--;) + send(LINE_REG(line), led_line[(u << 3) | (line & 0x7)]); + #endif + pulse_load(); +} + +void Max7219::set(const uint8_t line, const uint8_t bits) { + led_line[line] = bits; + refresh_unit_line(line); +} + +#if ENABLED(MAX7219_NUMERIC) + + // Draw an integer with optional leading zeros and optional decimal point + void Max7219::print(const uint8_t start, int16_t value, uint8_t size, const bool leadzero=false, bool dec=false) { + if (suspended) return; + constexpr uint8_t led_numeral[10] = { 0x7E, 0x60, 0x6D, 0x79, 0x63, 0x5B, 0x5F, 0x70, 0x7F, 0x7A }, + led_decimal = 0x80, led_minus = 0x01; + bool blank = false, neg = value < 0; + if (neg) value *= -1; + while (size--) { + const bool minus = neg && blank; + if (minus) neg = false; + send( + max7219_reg_digit0 + start + size, + minus ? led_minus : blank ? 0x00 : led_numeral[value % 10] | (dec ? led_decimal : 0x00) + ); + pulse_load(); // tell the chips to load the clocked out data + value /= 10; + if (!value && !leadzero) blank = true; + dec = false; + } + } + + // Draw a float with a decimal point and optional digits + void Max7219::print(const uint8_t start, const_float_t value, const uint8_t pre_size, const uint8_t post_size, const bool leadzero=false) { + if (pre_size) print(start, value, pre_size, leadzero, !!post_size); + if (post_size) { + const int16_t after = ABS(value) * (10 ^ post_size); + print(start + pre_size, after, post_size, true); + } + } + +#endif // MAX7219_NUMERIC + +// Modify a single LED bit and send the changed line +void Max7219::led_set(const uint8_t x, const uint8_t y, const bool on) { + if (x >= MAX7219_X_LEDS || y >= MAX7219_Y_LEDS) return error(F("led_set"), x, y); + if (BIT_7219(x, y) == on) return; + XOR_7219(x, y); + refresh_unit_line(LED_IND(x, y)); +} + +void Max7219::led_on(const uint8_t x, const uint8_t y) { + if (x >= MAX7219_X_LEDS || y >= MAX7219_Y_LEDS) return error(F("led_on"), x, y); + led_set(x, y, true); +} + +void Max7219::led_off(const uint8_t x, const uint8_t y) { + if (x >= MAX7219_X_LEDS || y >= MAX7219_Y_LEDS) return error(F("led_off"), x, y); + led_set(x, y, false); +} + +void Max7219::led_toggle(const uint8_t x, const uint8_t y) { + if (x >= MAX7219_X_LEDS || y >= MAX7219_Y_LEDS) return error(F("led_toggle"), x, y); + led_set(x, y, !BIT_7219(x, y)); +} + +void Max7219::send_row(const uint8_t row) { + if (suspended) return; + #if _ROT == 0 || _ROT == 180 // Native Lines are horizontal too + #if MAX7219_X_LEDS <= 8 + refresh_unit_line(LED_IND(0, row)); // A single unit line + #else + refresh_line(LED_IND(0, row)); // Same line, all units + #endif + #else // Native lines are vertical + UNUSED(row); + refresh(); // Actually a column + #endif +} + +void Max7219::send_column(const uint8_t col) { + if (suspended) return; + #if _ROT == 90 || _ROT == 270 // Native Lines are vertical too + #if MAX7219_Y_LEDS <= 8 + refresh_unit_line(LED_IND(col, 0)); // A single unit line + #else + refresh_line(LED_IND(col, 0)); // Same line, all units + #endif + #else // Native lines are horizontal + UNUSED(col); + refresh(); // Actually a row + #endif +} + +void Max7219::clear() { + ZERO(led_line); + refresh(); +} + +void Max7219::fill() { + memset(led_line, 0xFF, sizeof(led_line)); + refresh(); +} + +void Max7219::clear_row(const uint8_t row) { + if (row >= MAX7219_Y_LEDS) return error(F("clear_row"), row); + LOOP_L_N(x, MAX7219_X_LEDS) CLR_7219(x, row); + send_row(row); +} + +void Max7219::clear_column(const uint8_t col) { + if (col >= MAX7219_X_LEDS) return error(F("set_column"), col); + LOOP_L_N(y, MAX7219_Y_LEDS) CLR_7219(col, y); + send_column(col); +} + +/** + * Plot the low order bits of val to the specified row of the matrix. + * With 4 Max7219 units in the chain, it's possible to set 32 bits at + * once with a single call to the function (if rotated 90° or 270°). + */ +void Max7219::set_row(const uint8_t row, const uint32_t val) { + if (row >= MAX7219_Y_LEDS) return error(F("set_row"), row); + uint32_t mask = _BV32(MAX7219_X_LEDS - 1); + LOOP_L_N(x, MAX7219_X_LEDS) { + if (val & mask) SET_7219(x, row); else CLR_7219(x, row); + mask >>= 1; + } + send_row(row); +} + +/** + * Plot the low order bits of val to the specified column of the matrix. + * With 4 Max7219 units in the chain, it's possible to set 32 bits at + * once with a single call to the function (if rotated 0° or 180°). + */ +void Max7219::set_column(const uint8_t col, const uint32_t val) { + if (col >= MAX7219_X_LEDS) return error(F("set_column"), col); + uint32_t mask = _BV32(MAX7219_Y_LEDS - 1); + LOOP_L_N(y, MAX7219_Y_LEDS) { + if (val & mask) SET_7219(col, y); else CLR_7219(col, y); + mask >>= 1; + } + send_column(col); +} + +void Max7219::set_rows_16bits(const uint8_t y, uint32_t val) { + #if MAX7219_X_LEDS == 8 + if (y > MAX7219_Y_LEDS - 2) return error(F("set_rows_16bits"), y, val); + set_row(y + 1, val); val >>= 8; + set_row(y + 0, val); + #else // at least 16 bits on each row + if (y > MAX7219_Y_LEDS - 1) return error(F("set_rows_16bits"), y, val); + set_row(y, val); + #endif +} + +void Max7219::set_rows_32bits(const uint8_t y, uint32_t val) { + #if MAX7219_X_LEDS == 8 + if (y > MAX7219_Y_LEDS - 4) return error(F("set_rows_32bits"), y, val); + set_row(y + 3, val); val >>= 8; + set_row(y + 2, val); val >>= 8; + set_row(y + 1, val); val >>= 8; + set_row(y + 0, val); + #elif MAX7219_X_LEDS == 16 + if (y > MAX7219_Y_LEDS - 2) return error(F("set_rows_32bits"), y, val); + set_row(y + 1, val); val >>= 16; + set_row(y + 0, val); + #else // at least 24 bits on each row. In the 3 matrix case, just display the low 24 bits + if (y > MAX7219_Y_LEDS - 1) return error(F("set_rows_32bits"), y, val); + set_row(y, val); + #endif +} + +void Max7219::set_columns_16bits(const uint8_t x, uint32_t val) { + #if MAX7219_Y_LEDS == 8 + if (x > MAX7219_X_LEDS - 2) return error(F("set_columns_16bits"), x, val); + set_column(x + 0, val); val >>= 8; + set_column(x + 1, val); + #else // at least 16 bits in each column + if (x > MAX7219_X_LEDS - 1) return error(F("set_columns_16bits"), x, val); + set_column(x, val); + #endif +} + +void Max7219::set_columns_32bits(const uint8_t x, uint32_t val) { + #if MAX7219_Y_LEDS == 8 + if (x > MAX7219_X_LEDS - 4) return error(F("set_rows_32bits"), x, val); + set_column(x + 3, val); val >>= 8; + set_column(x + 2, val); val >>= 8; + set_column(x + 1, val); val >>= 8; + set_column(x + 0, val); + #elif MAX7219_Y_LEDS == 16 + if (x > MAX7219_X_LEDS - 2) return error(F("set_rows_32bits"), x, val); + set_column(x + 1, val); val >>= 16; + set_column(x + 0, val); + #else // at least 24 bits on each row. In the 3 matrix case, just display the low 24 bits + if (x > MAX7219_X_LEDS - 1) return error(F("set_rows_32bits"), x, val); + set_column(x, val); + #endif +} + +// Initialize the Max7219 +void Max7219::register_setup() { + LOOP_L_N(i, MAX7219_NUMBER_UNITS) + send(max7219_reg_scanLimit, 0x07); + pulse_load(); // Tell the chips to load the clocked out data + + LOOP_L_N(i, MAX7219_NUMBER_UNITS) + send(max7219_reg_decodeMode, 0x00); // Using an led matrix (not digits) + pulse_load(); // Tell the chips to load the clocked out data + + LOOP_L_N(i, MAX7219_NUMBER_UNITS) + send(max7219_reg_shutdown, 0x01); // Not in shutdown mode + pulse_load(); // Tell the chips to load the clocked out data + + LOOP_L_N(i, MAX7219_NUMBER_UNITS) + send(max7219_reg_displayTest, 0x00); // No display test + pulse_load(); // Tell the chips to load the clocked out data + + LOOP_L_N(i, MAX7219_NUMBER_UNITS) + send(max7219_reg_intensity, 0x01 & 0x0F); // The first 0x0F is the value you can set + // Range: 0x00 to 0x0F + pulse_load(); // Tell the chips to load the clocked out data +} + +#ifdef MAX7219_INIT_TEST + + uint8_t test_mode = 0; + millis_t next_patt_ms; + bool patt_on; + + #if MAX7219_INIT_TEST == 2 + + #define MAX7219_LEDS (MAX7219_X_LEDS * MAX7219_Y_LEDS) + + constexpr millis_t pattern_delay = 4; + + int8_t spiralx, spiraly, spiral_dir; + IF<(MAX7219_LEDS > 255), uint16_t, uint8_t>::type spiral_count; + + void Max7219::test_pattern() { + constexpr int8_t way[][2] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; + led_set(spiralx, spiraly, patt_on); + const int8_t x = spiralx + way[spiral_dir][0], y = spiraly + way[spiral_dir][1]; + if (!WITHIN(x, 0, MAX7219_X_LEDS - 1) || !WITHIN(y, 0, MAX7219_Y_LEDS - 1) || BIT_7219(x, y) == patt_on) + spiral_dir = (spiral_dir + 1) & 0x3; + spiralx += way[spiral_dir][0]; + spiraly += way[spiral_dir][1]; + if (!spiral_count--) { + if (!patt_on) + test_mode = 0; + else { + spiral_count = MAX7219_LEDS; + spiralx = spiraly = spiral_dir = 0; + patt_on = false; + } + } + } + + #else + + constexpr millis_t pattern_delay = 20; + int8_t sweep_count, sweepx, sweep_dir; + + void Max7219::test_pattern() { + set_column(sweepx, patt_on ? 0xFFFFFFFF : 0x00000000); + sweepx += sweep_dir; + if (!WITHIN(sweepx, 0, MAX7219_X_LEDS - 1)) { + if (!patt_on) { + sweep_dir *= -1; + sweepx += sweep_dir; + } + else + sweepx -= MAX7219_X_LEDS * sweep_dir; + patt_on ^= true; + next_patt_ms += 100; + if (++test_mode > 4) test_mode = 0; + } + } + + #endif + + void Max7219::run_test_pattern() { + const millis_t ms = millis(); + if (PENDING(ms, next_patt_ms)) return; + next_patt_ms = ms + pattern_delay; + test_pattern(); + } + + void Max7219::start_test_pattern() { + clear(); + test_mode = 1; + patt_on = true; + #if MAX7219_INIT_TEST == 2 + spiralx = spiraly = spiral_dir = 0; + spiral_count = MAX7219_LEDS; + #else + sweep_dir = 1; + sweepx = 0; + sweep_count = MAX7219_X_LEDS; + #endif + } + +#endif // MAX7219_INIT_TEST + +void Max7219::init() { + SET_OUTPUT(MAX7219_DIN_PIN); + SET_OUTPUT(MAX7219_CLK_PIN); + OUT_WRITE(MAX7219_LOAD_PIN, HIGH); + delay(1); + + register_setup(); + + LOOP_LE_N(i, 7) { // Empty registers to turn all LEDs off + led_line[i] = 0x00; + send(max7219_reg_digit0 + i, 0); + pulse_load(); // Tell the chips to load the clocked out data + } + + #ifdef MAX7219_INIT_TEST + start_test_pattern(); + #endif +} + +/** + * This code demonstrates some simple debugging using a single 8x8 LED Matrix. If your feature could + * benefit from matrix display, add its code here. Very little processing is required, so the 7219 is + * ideal for debugging when realtime feedback is important but serial output can't be used. + */ + +// Apply changes to update a marker +void Max7219::mark16(const uint8_t pos, const uint8_t v1, const uint8_t v2) { + #if MAX7219_X_LEDS > 8 // At least 16 LEDs on the X-Axis. Use single line. + led_off(v1 & 0xF, pos); + led_on(v2 & 0xF, pos); + #elif MAX7219_Y_LEDS > 8 // At least 16 LEDs on the Y-Axis. Use a single column. + led_off(pos, v1 & 0xF); + led_on(pos, v2 & 0xF); + #else // Single 8x8 LED matrix. Use two lines to get 16 LEDs. + led_off(v1 & 0x7, pos + (v1 >= 8)); + led_on(v2 & 0x7, pos + (v2 >= 8)); + #endif +} + +// Apply changes to update a tail-to-head range +void Max7219::range16(const uint8_t y, const uint8_t ot, const uint8_t nt, const uint8_t oh, const uint8_t nh) { + #if MAX7219_X_LEDS > 8 // At least 16 LEDs on the X-Axis. Use single line. + if (ot != nt) for (uint8_t n = ot & 0xF; n != (nt & 0xF) && n != (nh & 0xF); n = (n + 1) & 0xF) + led_off(n & 0xF, y); + if (oh != nh) for (uint8_t n = (oh + 1) & 0xF; n != ((nh + 1) & 0xF); n = (n + 1) & 0xF) + led_on(n & 0xF, y); + #elif MAX7219_Y_LEDS > 8 // At least 16 LEDs on the Y-Axis. Use a single column. + if (ot != nt) for (uint8_t n = ot & 0xF; n != (nt & 0xF) && n != (nh & 0xF); n = (n + 1) & 0xF) + led_off(y, n & 0xF); + if (oh != nh) for (uint8_t n = (oh + 1) & 0xF; n != ((nh + 1) & 0xF); n = (n + 1) & 0xF) + led_on(y, n & 0xF); + #else // Single 8x8 LED matrix. Use two lines to get 16 LEDs. + if (ot != nt) for (uint8_t n = ot & 0xF; n != (nt & 0xF) && n != (nh & 0xF); n = (n + 1) & 0xF) + led_off(n & 0x7, y + (n >= 8)); + if (oh != nh) for (uint8_t n = (oh + 1) & 0xF; n != ((nh + 1) & 0xF); n = (n + 1) & 0xF) + led_on(n & 0x7, y + (n >= 8)); + #endif +} + +// Apply changes to update a quantity +void Max7219::quantity16(const uint8_t pos, const uint8_t ov, const uint8_t nv) { + for (uint8_t i = _MIN(nv, ov); i < _MAX(nv, ov); i++) + led_set( + #if MAX7219_X_LEDS > 8 // At least 16 LEDs on the X-Axis. Use single line. + i, pos + #elif MAX7219_Y_LEDS > 8 // At least 16 LEDs on the Y-Axis. Use a single column. + pos, i + #else // Single 8x8 LED matrix. Use two lines to get 16 LEDs. + i >> 1, pos + (i & 1) + #endif + , nv >= ov + ); +} + +void Max7219::idle_tasks() { + #define MAX7219_USE_HEAD (defined(MAX7219_DEBUG_PLANNER_HEAD) || defined(MAX7219_DEBUG_PLANNER_QUEUE)) + #define MAX7219_USE_TAIL (defined(MAX7219_DEBUG_PLANNER_TAIL) || defined(MAX7219_DEBUG_PLANNER_QUEUE)) + #if MAX7219_USE_HEAD || MAX7219_USE_TAIL + CRITICAL_SECTION_START(); + #if MAX7219_USE_HEAD + const uint8_t head = planner.block_buffer_head; + #endif + #if MAX7219_USE_TAIL + const uint8_t tail = planner.block_buffer_tail; + #endif + CRITICAL_SECTION_END(); + #endif + + #if ENABLED(MAX7219_DEBUG_PRINTER_ALIVE) + static uint8_t refresh_cnt; // = 0 + constexpr uint16_t refresh_limit = 5; + static millis_t next_blink = 0; + const millis_t ms = millis(); + const bool do_blink = ELAPSED(ms, next_blink); + #else + static uint16_t refresh_cnt; // = 0 + constexpr bool do_blink = true; + constexpr uint16_t refresh_limit = 50000; + #endif + + // Some Max7219 units are vulnerable to electrical noise, especially + // with long wires next to high current wires. If the display becomes + // corrupted, this will fix it within a couple seconds. + if (do_blink && ++refresh_cnt >= refresh_limit) { + refresh_cnt = 0; + register_setup(); + } + + #ifdef MAX7219_INIT_TEST + if (test_mode) { + run_test_pattern(); + return; + } + #endif + + #if ENABLED(MAX7219_DEBUG_PRINTER_ALIVE) + if (do_blink) { + led_toggle(MAX7219_X_LEDS - 1, MAX7219_Y_LEDS - 1); + next_blink = ms + 1000; + } + #endif + + #if defined(MAX7219_DEBUG_PLANNER_HEAD) && defined(MAX7219_DEBUG_PLANNER_TAIL) && MAX7219_DEBUG_PLANNER_HEAD == MAX7219_DEBUG_PLANNER_TAIL + + static int16_t last_head_cnt = 0xF, last_tail_cnt = 0xF; + + if (last_head_cnt != head || last_tail_cnt != tail) { + range16(MAX7219_DEBUG_PLANNER_HEAD, last_tail_cnt, tail, last_head_cnt, head); + last_head_cnt = head; + last_tail_cnt = tail; + } + + #else + + #ifdef MAX7219_DEBUG_PLANNER_HEAD + static int16_t last_head_cnt = 0x1; + if (last_head_cnt != head) { + mark16(MAX7219_DEBUG_PLANNER_HEAD, last_head_cnt, head); + last_head_cnt = head; + } + #endif + + #ifdef MAX7219_DEBUG_PLANNER_TAIL + static int16_t last_tail_cnt = 0x1; + if (last_tail_cnt != tail) { + mark16(MAX7219_DEBUG_PLANNER_TAIL, last_tail_cnt, tail); + last_tail_cnt = tail; + } + #endif + + #endif + + #ifdef MAX7219_DEBUG_PLANNER_QUEUE + static int16_t last_depth = 0; + const int16_t current_depth = (head - tail + BLOCK_BUFFER_SIZE) & (BLOCK_BUFFER_SIZE - 1) & 0xF; + if (current_depth != last_depth) { + quantity16(MAX7219_DEBUG_PLANNER_QUEUE, last_depth, current_depth); + last_depth = current_depth; + } + #endif + + // After resume() automatically do a refresh() + if (suspended == 0x80) { + suspended = 0; + refresh(); + } +} + +#endif // MAX7219_DEBUG diff --git a/src/feature/max7219.h b/src/feature/max7219.h new file mode 100644 index 0000000..809bda6 --- /dev/null +++ b/src/feature/max7219.h @@ -0,0 +1,161 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * This module is off by default, but can be enabled to facilitate the display of + * extra debug information during code development. + * + * Just connect up 5V and GND to give it power, then connect up the pins assigned + * in Configuration_adv.h. For example, on the Re-ARM you could use: + * + * #define MAX7219_CLK_PIN 77 + * #define MAX7219_DIN_PIN 78 + * #define MAX7219_LOAD_PIN 79 + * + * max7219.init() is called automatically at startup, and then there are a number of + * support functions available to control the LEDs in the 8x8 grid. + * + * If you are using the Max7219 matrix for firmware debug purposes in time sensitive + * areas of the code, please be aware that the orientation (rotation) of the display can + * affect the speed. The Max7219 can update a single column fairly fast. It is much + * faster to do a Max7219_Set_Column() with a rotation of 90 or 270 degrees than to do + * a Max7219_Set_Row(). The opposite is true for rotations of 0 or 180 degrees. + */ + +#include "../inc/MarlinConfig.h" + +#ifndef MAX7219_ROTATE + #define MAX7219_ROTATE 0 +#endif +#define _ROT ((MAX7219_ROTATE + 360) % 360) + +#ifndef MAX7219_NUMBER_UNITS + #define MAX7219_NUMBER_UNITS 1 +#endif +#define MAX7219_LINES (8 * (MAX7219_NUMBER_UNITS)) + +// +// MAX7219 registers +// +#define max7219_reg_noop 0x00 +#define max7219_reg_digit0 0x01 +#define max7219_reg_digit1 0x02 +#define max7219_reg_digit2 0x03 +#define max7219_reg_digit3 0x04 +#define max7219_reg_digit4 0x05 +#define max7219_reg_digit5 0x06 +#define max7219_reg_digit6 0x07 +#define max7219_reg_digit7 0x08 + +#define max7219_reg_decodeMode 0x09 +#define max7219_reg_intensity 0x0A +#define max7219_reg_scanLimit 0x0B +#define max7219_reg_shutdown 0x0C +#define max7219_reg_displayTest 0x0F + +class Max7219 { +public: + static uint8_t led_line[MAX7219_LINES]; + + Max7219() {} + + static void init(); + static void register_setup(); + static void putbyte(uint8_t data); + static void pulse_load(); + + // Set a single register (e.g., a whole native row) + static void send(const uint8_t reg, const uint8_t data); + + // Refresh all units + static void refresh() { for (uint8_t i = 0; i < 8; i++) refresh_line(i); } + + // Suspend / resume updates to the LED unit + // Use these methods to speed up multiple changes + // or to apply updates from interrupt context. + static void suspend() { suspended++; } + static void resume() { suspended--; suspended |= 0x80; } + + // Update a single native line on all units + static void refresh_line(const uint8_t line); + + // Update a single native line on just one unit + static void refresh_unit_line(const uint8_t line); + + #if ENABLED(MAX7219_NUMERIC) + // Draw an integer with optional leading zeros and optional decimal point + void print(const uint8_t start, int16_t value, uint8_t size, const bool leadzero=false, bool dec=false); + // Draw a float with a decimal point and optional digits + void print(const uint8_t start, const_float_t value, const uint8_t pre_size, const uint8_t post_size, const bool leadzero=false); + #endif + + // Set a single LED by XY coordinate + static void led_set(const uint8_t x, const uint8_t y, const bool on); + static void led_on(const uint8_t x, const uint8_t y); + static void led_off(const uint8_t x, const uint8_t y); + static void led_toggle(const uint8_t x, const uint8_t y); + + // Set all LEDs in a single column + static void set_column(const uint8_t col, const uint32_t val); + static void clear_column(const uint8_t col); + + // Set all LEDs in a single row + static void set_row(const uint8_t row, const uint32_t val); + static void clear_row(const uint8_t row); + + // 16 and 32 bit versions of Row and Column functions + // Multiple rows and columns will be used to display the value if + // the array of matrix LED's is too narrow to accomplish the goal + static void set_rows_16bits(const uint8_t y, uint32_t val); + static void set_rows_32bits(const uint8_t y, uint32_t val); + static void set_columns_16bits(const uint8_t x, uint32_t val); + static void set_columns_32bits(const uint8_t x, uint32_t val); + + // Quickly clear the whole matrix + static void clear(); + + // Quickly fill the whole matrix + static void fill(); + + // Apply custom code to update the matrix + static void idle_tasks(); + +private: + static uint8_t suspended; + static void error(FSTR_P const func, const int32_t v1, const int32_t v2=-1); + static void noop(); + static void set(const uint8_t line, const uint8_t bits); + static void send_row(const uint8_t row); + static void send_column(const uint8_t col); + static void mark16(const uint8_t y, const uint8_t v1, const uint8_t v2); + static void range16(const uint8_t y, const uint8_t ot, const uint8_t nt, const uint8_t oh, const uint8_t nh); + static void quantity16(const uint8_t y, const uint8_t ov, const uint8_t nv); + + #ifdef MAX7219_INIT_TEST + static void test_pattern(); + static void run_test_pattern(); + static void start_test_pattern(); + #endif +}; + +extern Max7219 max7219; diff --git a/src/feature/meatpack.cpp b/src/feature/meatpack.cpp new file mode 100644 index 0000000..07ff41e --- /dev/null +++ b/src/feature/meatpack.cpp @@ -0,0 +1,218 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * MeatPack G-code Compression + * + * Algorithm & Implementation: Scott Mudge - mail@scottmudge.com + * Date: Dec. 2020 + * + * Character Frequencies from ~30 MB of comment-stripped G-code: + * '1' -> 4451136 '4' -> 1353273 '\n' -> 1087683 '-' -> 90242 + * '0' -> 4253577 '9' -> 1352147 'G' -> 1075806 'Z' -> 34109 + * ' ' -> 3053297 '3' -> 1262929 'X' -> 975742 'M' -> 11879 + * '.' -> 3035310 '5' -> 1189871 'E' -> 965275 'S' -> 9910 + * '2' -> 1523296 '6' -> 1127900 'Y' -> 965274 + * '8' -> 1366812 '7' -> 1112908 'F' -> 99416 + * + * When space is omitted the letter 'E' is used in its place + */ + +#include "../inc/MarlinConfig.h" + +#if HAS_MEATPACK + +#include "meatpack.h" + +#define MeatPack_ProtocolVersion "PV01" +//#define MP_DEBUG + +#define DEBUG_OUT ENABLED(MP_DEBUG) +#include "../core/debug_out.h" + +// The 15 most-common characters used in G-code, ~90-95% of all G-code uses these characters +// Stored in SRAM for performance. +uint8_t meatPackLookupTable[16] = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + '.', ' ', '\n', 'G', 'X', + '\0' // Unused. 0b1111 indicates a literal character +}; + +#if ENABLED(MP_DEBUG) + uint8_t chars_decoded = 0; // Log the first 64 bytes after each reset +#endif + +void MeatPack::reset_state() { + state = 0; + cmd_is_next = false; + second_char = 0; + cmd_count = full_char_count = char_out_count = 0; + TERN_(MP_DEBUG, chars_decoded = 0); +} + +/** + * Unpack one or two characters from a packed byte into a buffer. + * Return flags indicating whether any literal bytes follow. + */ +uint8_t MeatPack::unpack_chars(const uint8_t pk, uint8_t* __restrict const chars_out) { + uint8_t out = 0; + + // If lower nybble is 1111, the higher nybble is unused, and next char is full. + if ((pk & kFirstNotPacked) == kFirstNotPacked) + out = kFirstCharIsLiteral; + else { + const uint8_t chr = pk & 0x0F; + chars_out[0] = meatPackLookupTable[chr]; // Set the first char + } + + // Check if upper nybble is 1111... if so, we don't need the second char. + if ((pk & kSecondNotPacked) == kSecondNotPacked) + out |= kSecondCharIsLiteral; + else { + const uint8_t chr = (pk >> 4) & 0x0F; + chars_out[1] = meatPackLookupTable[chr]; // Set the second char + } + + return out; +} + +/** + * Interpret a single (non-command) character + * according to the current MeatPack state. + */ +void MeatPack::handle_rx_char_inner(const uint8_t c) { + if (TEST(state, MPConfig_Bit_Active)) { // Is MeatPack active? + if (!full_char_count) { // No literal characters to fetch? + uint8_t buf[2] = { 0, 0 }; + const uint8_t res = unpack_chars(c, buf); // Decode the byte into one or two characters. + if (res & kFirstCharIsLiteral) { // The 1st character couldn't be packed. + ++full_char_count; // So the next stream byte is a full character. + if (res & kSecondCharIsLiteral) ++full_char_count; // The 2nd character couldn't be packed. Another stream byte is a full character. + else second_char = buf[1]; // Retain the unpacked second character. + } + else { + handle_output_char(buf[0]); // Send the unpacked first character out. + if (buf[0] != '\n') { // After a newline the next char won't be set + if (res & kSecondCharIsLiteral) ++full_char_count; // The 2nd character couldn't be packed. The next stream byte is a full character. + else handle_output_char(buf[1]); // Send the unpacked second character out. + } + } + } + else { + handle_output_char(c); // Pass through the character that couldn't be packed... + if (second_char) { + handle_output_char(second_char); // ...and send an unpacked 2nd character, if set. + second_char = 0; + } + --full_char_count; // One literal character was consumed + } + } + else // Packing not enabled, just copy character to output + handle_output_char(c); +} + +/** + * Buffer a single output character which will be picked up in + * GCodeQueue::get_serial_commands via calls to get_result_char + */ +void MeatPack::handle_output_char(const uint8_t c) { + char_out_buf[char_out_count++] = c; + + #if ENABLED(MP_DEBUG) + if (chars_decoded < 1024) { + ++chars_decoded; + DEBUG_ECHOLNPGM("RB: ", AS_CHAR(c)); + } + #endif +} + +/** + * Process a MeatPack command byte to update the state. + * Report the new state to serial. + */ +void MeatPack::handle_command(const MeatPack_Command c) { + switch (c) { + case MPCommand_QueryConfig: break; + case MPCommand_EnablePacking: SBI(state, MPConfig_Bit_Active); DEBUG_ECHOLNPGM("[MPDBG] ENA REC"); break; + case MPCommand_DisablePacking: CBI(state, MPConfig_Bit_Active); DEBUG_ECHOLNPGM("[MPDBG] DIS REC"); break; + case MPCommand_ResetAll: reset_state(); DEBUG_ECHOLNPGM("[MPDBG] RESET REC"); break; + case MPCommand_EnableNoSpaces: + SBI(state, MPConfig_Bit_NoSpaces); + meatPackLookupTable[kSpaceCharIdx] = kSpaceCharReplace; DEBUG_ECHOLNPGM("[MPDBG] ENA NSP"); break; + case MPCommand_DisableNoSpaces: + CBI(state, MPConfig_Bit_NoSpaces); + meatPackLookupTable[kSpaceCharIdx] = ' '; DEBUG_ECHOLNPGM("[MPDBG] DIS NSP"); break; + default: DEBUG_ECHOLNPGM("[MPDBG] UNK CMD REC"); + } + report_state(); +} + +void MeatPack::report_state() { + // NOTE: if any configuration vars are added below, the outgoing sync text for host plugin + // should not contain the "PV' substring, as this is used to indicate protocol version + SERIAL_ECHOPGM("[MP] " MeatPack_ProtocolVersion " "); + serialprint_onoff(TEST(state, MPConfig_Bit_Active)); + SERIAL_ECHOF(TEST(state, MPConfig_Bit_NoSpaces) ? F(" NSP\n") : F(" ESP\n")); +} + +/** + * Interpret a single character received from serial + * according to the current meatpack state. + */ +void MeatPack::handle_rx_char(const uint8_t c, const serial_index_t serial_ind) { + if (c == kCommandByte) { // A command (0xFF) byte? + if (cmd_count) { // In fact, two in a row? + cmd_is_next = true; // Then a MeatPack command follows + cmd_count = 0; + } + else + ++cmd_count; // cmd_count = 1 // One command byte received so far... + return; + } + + if (cmd_is_next) { // Were two command bytes received? + PORT_REDIRECT(SERIAL_PORTMASK(serial_ind)); + handle_command((MeatPack_Command)c); // Then the byte is a MeatPack command + cmd_is_next = false; + return; + } + + if (cmd_count) { // Only a single 0xFF was received + handle_rx_char_inner(kCommandByte); // A single 0xFF is passed on literally so it can be interpreted as kFirstNotPacked|kSecondNotPacked + cmd_count = 0; + } + + handle_rx_char_inner(c); // Other characters are passed on for MeatPack decoding +} + +uint8_t MeatPack::get_result_char(char * const __restrict out) { + uint8_t res = 0; + if (char_out_count) { + res = char_out_count; + char_out_count = 0; + for (uint8_t i = 0; i < res; ++i) + out[i] = (char)char_out_buf[i]; + } + return res; +} + +#endif // HAS_MEATPACK diff --git a/src/feature/meatpack.h b/src/feature/meatpack.h new file mode 100644 index 0000000..98a535e --- /dev/null +++ b/src/feature/meatpack.h @@ -0,0 +1,175 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/* + * MeatPack G-code Compression + * + * Algorithm & Implementation: Scott Mudge - mail@scottmudge.com + * Date: Dec. 2020 + * + * Specifically optimized for 3D printing G-Code, this is a zero-cost data compression method + * which packs ~180-190% more data into the same amount of bytes going to the CNC controller. + * As a majority of G-Code can be represented by a restricted alphabet, I performed histogram + * analysis on a wide variety of 3D printing G-code samples, and found ~93% of all G-code could + * be represented by the same 15-character alphabet. + * + * This allowed me to design a system of packing 2 8-bit characters into a single byte, assuming + * they fall within this limited 15-character alphabet. Using a 4-bit lookup table, these 8-bit + * characters can be represented by a 4-bit index. + * + * Combined with some logic to allow commingling of full-width characters outside of this 15- + * character alphabet (at the cost of an extra 8-bits per full-width character), and by stripping + * out unnecessary comments, the end result is G-code which is roughly half the original size. + * + * Why did I do this? I noticed micro-stuttering and other data-bottleneck issues while printing + * objects with high curvature, especially at high speeds. There is also the issue of the limited + * baud rate provided by Prusa's Atmega2560-based boards, over the USB serial connection. So soft- + * ware like OctoPrint would also suffer this same micro-stuttering and poor print quality issue. + * + */ +#pragma once + +#include +#include "../core/serial_hook.h" + +/** + * Commands sent to MeatPack to control its behavior. + * They are sent by first sending 2x MeatPack_CommandByte (0xFF) in sequence, + * followed by one of the command bytes below. + * Provided that 0xFF is an exceedingly rare character that is virtually never + * present in G-code naturally, it is safe to assume 2 in sequence should never + * happen naturally, and so it is used as a signal here. + * + * 0xFF *IS* used in "packed" G-code (used to denote that the next 2 characters are + * full-width), however 2 in a row will never occur, as the next 2 bytes will always + * some non-0xFF character. + */ +enum MeatPack_Command : uint8_t { + MPCommand_None = 0, + MPCommand_EnablePacking = 0xFB, + MPCommand_DisablePacking = 0xFA, + MPCommand_ResetAll = 0xF9, + MPCommand_QueryConfig = 0xF8, + MPCommand_EnableNoSpaces = 0xF7, + MPCommand_DisableNoSpaces = 0xF6 +}; + +enum MeatPack_ConfigStateBits : uint8_t { + MPConfig_Bit_Active = 0, + MPConfig_Bit_NoSpaces = 1 +}; + +class MeatPack { + + // Utility definitions + static const uint8_t kCommandByte = 0b11111111, + kFirstNotPacked = 0b00001111, + kSecondNotPacked = 0b11110000, + kFirstCharIsLiteral = 0b00000001, + kSecondCharIsLiteral = 0b00000010; + + static const uint8_t kSpaceCharIdx = 11; + static const char kSpaceCharReplace = 'E'; + + bool cmd_is_next; // A command is pending + uint8_t state; // Configuration state + uint8_t second_char; // Buffers a character if dealing with out-of-sequence pairs + uint8_t cmd_count, // Counter of command bytes received (need 2) + full_char_count, // Counter for full-width characters to be received + char_out_count; // Stores number of characters to be read out. + uint8_t char_out_buf[2]; // Output buffer for caching up to 2 characters + +public: + // Pass in a character rx'd by SD card or serial. Automatically parses command/ctrl sequences, + // and will control state internally. + void handle_rx_char(const uint8_t c, const serial_index_t serial_ind); + + /** + * After passing in rx'd char using above method, call this to get characters out. + * Can return from 0 to 2 characters at once. + * @param out [in] Output pointer for unpacked/processed data. + * @return Number of characters returned. Range from 0 to 2. + */ + uint8_t get_result_char(char * const __restrict out); + + void reset_state(); + void report_state(); + uint8_t unpack_chars(const uint8_t pk, uint8_t* __restrict const chars_out); + void handle_command(const MeatPack_Command c); + void handle_output_char(const uint8_t c); + void handle_rx_char_inner(const uint8_t c); + + MeatPack() : cmd_is_next(false), state(0), second_char(0), cmd_count(0), full_char_count(0), char_out_count(0) {} +}; + +// Implement the MeatPack serial class so it's transparent to rest of the code +template +struct MeatpackSerial : public SerialBase > { + typedef SerialBase< MeatpackSerial > BaseClassT; + + SerialT & out; + MeatPack meatpack; + + char serialBuffer[2]; + uint8_t charCount; + uint8_t readIndex; + + NO_INLINE void write(uint8_t c) { out.write(c); } + void flush() { out.flush(); } + void begin(long br) { out.begin(br); readIndex = 0; } + void end() { out.end(); } + + void msgDone() { out.msgDone(); } + // Existing instances implement Arduino's operator bool, so use that if it's available + bool connected() { return Private::HasMember_connected::value ? CALL_IF_EXISTS(bool, &out, connected) : (bool)out; } + void flushTX() { CALL_IF_EXISTS(void, &out, flushTX); } + SerialFeature features(serial_index_t index) const { return SerialFeature::MeatPack | CALL_IF_EXISTS(SerialFeature, &out, features, index); } + + + int available(serial_index_t index) { + if (charCount) return charCount; // The buffer still has data + if (out.available(index) <= 0) return 0; // No data to read + + // Don't read in read method, instead do it here, so we can make progress in the read method + const int r = out.read(index); + if (r == -1) return 0; // This is an error from the underlying serial code + meatpack.handle_rx_char((uint8_t)r, index); + charCount = meatpack.get_result_char(serialBuffer); + readIndex = 0; + + return charCount; + } + + int readImpl(const serial_index_t index) { + // Not enough char to make progress? + if (charCount == 0 && available(index) == 0) return -1; + + charCount--; + return serialBuffer[readIndex++]; + } + + int read(serial_index_t index) { return readImpl(index); } + int available() { return available(0); } + int read() { return readImpl(0); } + + MeatpackSerial(const bool e, SerialT & out) : BaseClassT(e), out(out) {} +}; diff --git a/src/feature/mixing.cpp b/src/feature/mixing.cpp new file mode 100644 index 0000000..b1a069e --- /dev/null +++ b/src/feature/mixing.cpp @@ -0,0 +1,210 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(MIXING_EXTRUDER) + +//#define MIXER_NORMALIZER_DEBUG + +#include "mixing.h" + +Mixer mixer; + +#ifdef MIXER_NORMALIZER_DEBUG + #include "../core/serial.h" +#endif + +// Used up to Planner level +uint_fast8_t Mixer::selected_vtool = 0; +float Mixer::collector[MIXING_STEPPERS]; // mix proportion. 0.0 = off, otherwise <= COLOR_A_MASK. +mixer_comp_t Mixer::color[NR_MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS]; + +// Used in Stepper +int_fast8_t Mixer::runner = 0; +mixer_comp_t Mixer::s_color[MIXING_STEPPERS]; +mixer_accu_t Mixer::accu[MIXING_STEPPERS] = { 0 }; + +#if EITHER(HAS_DUAL_MIXING, GRADIENT_MIX) + mixer_perc_t Mixer::mix[MIXING_STEPPERS]; +#endif + +void Mixer::normalize(const uint8_t tool_index) { + float cmax = 0; + #ifdef MIXER_NORMALIZER_DEBUG + float csum = 0; + #endif + MIXER_STEPPER_LOOP(i) { + const float v = collector[i]; + NOLESS(cmax, v); + #ifdef MIXER_NORMALIZER_DEBUG + csum += v; + #endif + } + #ifdef MIXER_NORMALIZER_DEBUG + SERIAL_ECHOPGM("Mixer: Old relation : [ "); + MIXER_STEPPER_LOOP(i) { + SERIAL_DECIMAL(collector[i] / csum); + SERIAL_CHAR(' '); + } + SERIAL_ECHOLNPGM("]"); + #endif + + // Scale all values so their maximum is COLOR_A_MASK + const float scale = float(COLOR_A_MASK) / cmax; + MIXER_STEPPER_LOOP(i) color[tool_index][i] = collector[i] * scale; + + #ifdef MIXER_NORMALIZER_DEBUG + csum = 0; + SERIAL_ECHOPGM("Mixer: Normalize to : [ "); + MIXER_STEPPER_LOOP(i) { + SERIAL_ECHO(uint16_t(color[tool_index][i])); + SERIAL_CHAR(' '); + csum += color[tool_index][i]; + } + SERIAL_ECHOLNPGM("]"); + SERIAL_ECHOPGM("Mixer: New relation : [ "); + MIXER_STEPPER_LOOP(i) { + SERIAL_ECHO_F(uint16_t(color[tool_index][i]) / csum, 3); + SERIAL_CHAR(' '); + } + SERIAL_ECHOLNPGM("]"); + #endif + + TERN_(GRADIENT_MIX, refresh_gradient()); +} + +void Mixer::reset_vtools() { + // Virtual Tools 0, 1, 2, 3 = Filament 1, 2, 3, 4, etc. + // Every virtual tool gets a pure filament + LOOP_L_N(t, _MIN(MIXING_VIRTUAL_TOOLS, MIXING_STEPPERS)) + MIXER_STEPPER_LOOP(i) + color[t][i] = (t == i) ? COLOR_A_MASK : 0; + + // Remaining virtual tools are 100% filament 1 + #if MIXING_VIRTUAL_TOOLS > MIXING_STEPPERS + LOOP_S_L_N(t, MIXING_STEPPERS, MIXING_VIRTUAL_TOOLS) + MIXER_STEPPER_LOOP(i) + color[t][i] = (i == 0) ? COLOR_A_MASK : 0; + #endif + + // MIXING_PRESETS: Set a variety of obvious mixes as presets + #if ENABLED(MIXING_PRESETS) && WITHIN(MIXING_STEPPERS, 2, 3) + #if MIXING_STEPPERS == 2 + if (MIXING_VIRTUAL_TOOLS > 2) { collector[0] = 1; collector[1] = 1; mixer.normalize(2); } // 1:1 + if (MIXING_VIRTUAL_TOOLS > 3) { collector[0] = 3; mixer.normalize(3); } // 3:1 + if (MIXING_VIRTUAL_TOOLS > 4) { collector[0] = 1; collector[1] = 3; mixer.normalize(4); } // 1:3 + if (MIXING_VIRTUAL_TOOLS > 5) { collector[1] = 2; mixer.normalize(5); } // 1:2 + if (MIXING_VIRTUAL_TOOLS > 6) { collector[0] = 2; collector[1] = 1; mixer.normalize(6); } // 2:1 + if (MIXING_VIRTUAL_TOOLS > 7) { collector[0] = 3; collector[1] = 2; mixer.normalize(7); } // 3:2 + #else + if (MIXING_VIRTUAL_TOOLS > 3) { collector[0] = 1; collector[1] = 1; collector[2] = 1; mixer.normalize(3); } // 1:1:1 + if (MIXING_VIRTUAL_TOOLS > 4) { collector[1] = 3; collector[2] = 0; mixer.normalize(4); } // 1:3:0 + if (MIXING_VIRTUAL_TOOLS > 5) { collector[0] = 0; collector[2] = 1; mixer.normalize(5); } // 0:3:1 + if (MIXING_VIRTUAL_TOOLS > 6) { collector[1] = 1; mixer.normalize(6); } // 0:1:1 + if (MIXING_VIRTUAL_TOOLS > 7) { collector[0] = 1; collector[2] = 0; mixer.normalize(7); } // 1:1:0 + #endif + ZERO(collector); + #endif +} + +// called at boot +void Mixer::init() { + + ZERO(collector); + + reset_vtools(); + + #if HAS_MIXER_SYNC_CHANNEL + // AUTORETRACT_TOOL gets the same amount of all filaments + MIXER_STEPPER_LOOP(i) + color[MIXER_AUTORETRACT_TOOL][i] = COLOR_A_MASK; + #endif + + #if EITHER(HAS_DUAL_MIXING, GRADIENT_MIX) + update_mix_from_vtool(); + #endif + + TERN_(GRADIENT_MIX, update_gradient_for_planner_z()); +} + +void Mixer::refresh_collector(const float proportion/*=1.0*/, const uint8_t t/*=selected_vtool*/, float (&c)[MIXING_STEPPERS]/*=collector*/) { + float csum = 0, cmax = 0; + MIXER_STEPPER_LOOP(i) { + const float v = color[t][i]; + cmax = _MAX(cmax, v); + csum += v; + } + //SERIAL_ECHOPGM("Mixer::refresh_collector(", proportion, ", ", t, ") cmax=", cmax, " csum=", csum, " color"); + const float inv_prop = proportion / csum; + MIXER_STEPPER_LOOP(i) { + c[i] = color[t][i] * inv_prop; + //SERIAL_ECHOPGM(" [", t, "][", i, "] = ", color[t][i], " (", c[i], ") "); + } + //SERIAL_EOL(); +} + +#if ENABLED(GRADIENT_MIX) + + #include "../module/motion.h" + #include "../module/planner.h" + + gradient_t Mixer::gradient = { + false, // enabled + {0}, // color (array) + 0, 0, // start_z, end_z + 0, 1, // start_vtool, end_vtool + {0}, {0} // start_mix[], end_mix[] + OPTARG(GRADIENT_VTOOL, -1) // vtool_index + }; + + float Mixer::prev_z; // = 0 + + void Mixer::update_gradient_for_z(const_float_t z) { + if (z == prev_z) return; + prev_z = z; + + const float slice = gradient.end_z - gradient.start_z; + + float pct = (z - gradient.start_z) / slice; + NOLESS(pct, 0.0f); NOMORE(pct, 1.0f); + + MIXER_STEPPER_LOOP(i) { + const mixer_perc_t sm = gradient.start_mix[i]; + mix[i] = sm + (gradient.end_mix[i] - sm) * pct; + } + + copy_mix_to_color(gradient.color); + } + + void Mixer::update_gradient_for_planner_z() { + #if ENABLED(DELTA) + get_cartesian_from_steppers(); + update_gradient_for_z(cartes.z); + #else + update_gradient_for_z(planner.get_axis_position_mm(Z_AXIS)); + #endif + } + +#endif // GRADIENT_MIX + +#endif // MIXING_EXTRUDER diff --git a/src/feature/mixing.h b/src/feature/mixing.h new file mode 100644 index 0000000..85d52d6 --- /dev/null +++ b/src/feature/mixing.h @@ -0,0 +1,262 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" + +//#define MIXER_NORMALIZER_DEBUG + +#ifndef __AVR__ // || HAS_DUAL_MIXING + // Use 16-bit (or fastest) data for the integer mix factors + typedef uint_fast16_t mixer_comp_t; + typedef uint_fast16_t mixer_accu_t; + #define COLOR_A_MASK 0x8000 + #define COLOR_MASK 0x7FFF +#else + // Use 8-bit data for the integer mix factors + // Exactness is sacrificed for speed + #define MIXER_ACCU_SIGNED + typedef uint8_t mixer_comp_t; + typedef int8_t mixer_accu_t; + #define COLOR_A_MASK 0x80 + #define COLOR_MASK 0x7F +#endif + +typedef int8_t mixer_perc_t; + +#ifndef MIXING_VIRTUAL_TOOLS + #define MIXING_VIRTUAL_TOOLS 1 +#endif + +enum MixTool { + FIRST_USER_VIRTUAL_TOOL = 0 + , LAST_USER_VIRTUAL_TOOL = MIXING_VIRTUAL_TOOLS - 1 + , NR_USER_VIRTUAL_TOOLS + , MIXER_DIRECT_SET_TOOL = NR_USER_VIRTUAL_TOOLS + #if HAS_MIXER_SYNC_CHANNEL + , MIXER_AUTORETRACT_TOOL + #endif + , NR_MIXING_VIRTUAL_TOOLS +}; + +#define MAX_VTOOLS TERN(HAS_MIXER_SYNC_CHANNEL, 254, 255) +static_assert(NR_MIXING_VIRTUAL_TOOLS <= MAX_VTOOLS, "MIXING_VIRTUAL_TOOLS must be <= " STRINGIFY(MAX_VTOOLS) "!"); + +#define MIXER_STEPPER_LOOP(VAR) for (uint_fast8_t VAR = 0; VAR < MIXING_STEPPERS; VAR++) + +#if ENABLED(GRADIENT_MIX) + + typedef struct { + bool enabled; // This gradient is enabled + mixer_comp_t color[MIXING_STEPPERS]; // The current gradient color + float start_z, end_z; // Region for gradient + int8_t start_vtool, end_vtool; // Start and end virtual tools + mixer_perc_t start_mix[MIXING_STEPPERS], // Start and end mixes from those tools + end_mix[MIXING_STEPPERS]; + #if ENABLED(GRADIENT_VTOOL) + int8_t vtool_index; // Use this virtual tool number as index + #endif + } gradient_t; + +#endif + +/** + * @brief Mixer class + * @details Contains data and behaviors for a Mixing Extruder + */ +class Mixer { + public: + + static float collector[MIXING_STEPPERS]; // M163 components, also editable from LCD + + static void init(); // Populate colors at boot time + + static void reset_vtools(); + static void refresh_collector(const float proportion=1.0, const uint8_t t=selected_vtool, float (&c)[MIXING_STEPPERS]=collector); + + // Used up to Planner level + FORCE_INLINE static void set_collector(const uint8_t c, const float f) { collector[c] = _MAX(f, 0.0f); } + + static void normalize(const uint8_t tool_index); + FORCE_INLINE static void normalize() { normalize(selected_vtool); } + + FORCE_INLINE static uint8_t get_current_vtool() { return selected_vtool; } + + FORCE_INLINE static void T(const uint_fast8_t c) { + selected_vtool = c; + TERN_(GRADIENT_VTOOL, refresh_gradient()); + TERN_(HAS_DUAL_MIXING, update_mix_from_vtool()); + } + + // Used when dealing with blocks + FORCE_INLINE static void populate_block(mixer_comp_t b_color[MIXING_STEPPERS]) { + #if ENABLED(GRADIENT_MIX) + if (gradient.enabled) { + MIXER_STEPPER_LOOP(i) b_color[i] = gradient.color[i]; + return; + } + #endif + MIXER_STEPPER_LOOP(i) b_color[i] = color[selected_vtool][i]; + } + + FORCE_INLINE static void stepper_setup(mixer_comp_t b_color[MIXING_STEPPERS]) { + MIXER_STEPPER_LOOP(i) s_color[i] = b_color[i]; + } + + #if EITHER(HAS_DUAL_MIXING, GRADIENT_MIX) + + static mixer_perc_t mix[MIXING_STEPPERS]; // Scratch array for the Mix in proportion to 100 + + static void copy_mix_to_color(mixer_comp_t (&tcolor)[MIXING_STEPPERS]) { + // Scale each component to the largest one in terms of COLOR_A_MASK + // So the largest component will be COLOR_A_MASK and the other will be in proportion to it + const float scale = (COLOR_A_MASK) * RECIPROCAL(_MAX( + LIST_N(MIXING_STEPPERS, mix[0], mix[1], mix[2], mix[3], mix[4], mix[5]) + )); + + // Scale all values so their maximum is COLOR_A_MASK + MIXER_STEPPER_LOOP(i) tcolor[i] = mix[i] * scale; + + #ifdef MIXER_NORMALIZER_DEBUG + SERIAL_ECHOPGM("Mix [ "); + SERIAL_ECHOLIST_N(MIXING_STEPPERS, mix[0], mix[1], mix[2], mix[3], mix[4], mix[5]); + SERIAL_ECHOPGM(" ] to Color [ "); + SERIAL_ECHOLIST_N(MIXING_STEPPERS, tcolor[0], tcolor[1], tcolor[2], tcolor[3], tcolor[4], tcolor[5]); + SERIAL_ECHOLNPGM(" ]"); + #endif + } + + static void update_mix_from_vtool(const uint8_t j=selected_vtool) { + float ctot = 0; + MIXER_STEPPER_LOOP(i) ctot += color[j][i]; + //MIXER_STEPPER_LOOP(i) mix[i] = 100.0f * color[j][i] / ctot; + MIXER_STEPPER_LOOP(i) mix[i] = mixer_perc_t(100.0f * color[j][i] / ctot); + + #ifdef MIXER_NORMALIZER_DEBUG + SERIAL_ECHOPGM("V-tool ", j, " [ "); + SERIAL_ECHOLIST_N(MIXING_STEPPERS, color[j][0], color[j][1], color[j][2], color[j][3], color[j][4], color[j][5]); + SERIAL_ECHOPGM(" ] to Mix [ "); + SERIAL_ECHOLIST_N(MIXING_STEPPERS, mix[0], mix[1], mix[2], mix[3], mix[4], mix[5]); + SERIAL_ECHOLNPGM(" ]"); + #endif + } + + #endif // HAS_DUAL_MIXING || GRADIENT_MIX + + #if HAS_DUAL_MIXING + + // Update the virtual tool from an edited mix + static void update_vtool_from_mix() { + copy_mix_to_color(color[selected_vtool]); + TERN_(GRADIENT_MIX, refresh_gradient()); + // MIXER_STEPPER_LOOP(i) collector[i] = mix[i]; + // normalize(); + } + + #endif // HAS_DUAL_MIXING + + #if ENABLED(GRADIENT_MIX) + + static gradient_t gradient; + static float prev_z; + + // Update the current mix from the gradient for a given Z + static void update_gradient_for_z(const_float_t z); + static void update_gradient_for_planner_z(); + static void gradient_control(const_float_t z) { + if (gradient.enabled) { + if (z >= gradient.end_z) + T(gradient.end_vtool); + else + update_gradient_for_z(z); + } + } + + static void update_mix_from_gradient() { + float ctot = 0; + MIXER_STEPPER_LOOP(i) ctot += gradient.color[i]; + MIXER_STEPPER_LOOP(i) mix[i] = (mixer_perc_t)CEIL(100.0f * gradient.color[i] / ctot); + + #ifdef MIXER_NORMALIZER_DEBUG + SERIAL_ECHOPGM("Gradient [ "); + SERIAL_ECHOLIST_N(MIXING_STEPPERS, gradient.color[0], gradient.color[1], gradient.color[2], gradient.color[3], gradient.color[4], gradient.color[5]); + SERIAL_ECHOPGM(" ] to Mix [ "); + SERIAL_ECHOLIST_N(MIXING_STEPPERS, mix[0], mix[1], mix[2], mix[3], mix[4], mix[5]); + SERIAL_ECHOLNPGM(" ]"); + #endif + } + + // Refresh the gradient after a change + static void refresh_gradient() { + #if ENABLED(GRADIENT_VTOOL) + const bool is_grd = (gradient.vtool_index == -1 || selected_vtool == (uint8_t)gradient.vtool_index); + #else + constexpr bool is_grd = true; + #endif + gradient.enabled = is_grd && gradient.start_vtool != gradient.end_vtool && gradient.start_z < gradient.end_z; + if (gradient.enabled) { + mixer_perc_t mix_bak[MIXING_STEPPERS]; + COPY(mix_bak, mix); + update_mix_from_vtool(gradient.start_vtool); + COPY(gradient.start_mix, mix); + update_mix_from_vtool(gradient.end_vtool); + COPY(gradient.end_mix, mix); + update_gradient_for_planner_z(); + COPY(mix, mix_bak); + prev_z = -1; + } + } + + #endif // GRADIENT_MIX + + // Used in Stepper + FORCE_INLINE static uint8_t get_stepper() { return runner; } + FORCE_INLINE static uint8_t get_next_stepper() { + for (;;) { + if (--runner < 0) runner = MIXING_STEPPERS - 1; + accu[runner] += s_color[runner]; + if ( + #ifdef MIXER_ACCU_SIGNED + accu[runner] < 0 + #else + accu[runner] & COLOR_A_MASK + #endif + ) { + accu[runner] &= COLOR_MASK; + return runner; + } + } + } + + private: + + // Used up to Planner level + static uint_fast8_t selected_vtool; + static mixer_comp_t color[NR_MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS]; + + // Used in Stepper + static int_fast8_t runner; + static mixer_comp_t s_color[MIXING_STEPPERS]; + static mixer_accu_t accu[MIXING_STEPPERS]; +}; + +extern Mixer mixer; diff --git a/src/feature/mmu/mmu.cpp b/src/feature/mmu/mmu.cpp new file mode 100644 index 0000000..58c49ed --- /dev/null +++ b/src/feature/mmu/mmu.cpp @@ -0,0 +1,46 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../../inc/MarlinConfig.h" + +#if HAS_PRUSA_MMU1 + +#include "../../MarlinCore.h" +#include "../../module/planner.h" +#include "../../module/stepper.h" + +void mmu_init() { + SET_OUTPUT(E_MUX0_PIN); + SET_OUTPUT(E_MUX1_PIN); + SET_OUTPUT(E_MUX2_PIN); +} + +void select_multiplexed_stepper(const uint8_t e) { + planner.synchronize(); + stepper.disable_e_steppers(); + WRITE(E_MUX0_PIN, TEST(e, 0) ? HIGH : LOW); + WRITE(E_MUX1_PIN, TEST(e, 1) ? HIGH : LOW); + WRITE(E_MUX2_PIN, TEST(e, 2) ? HIGH : LOW); + safe_delay(100); +} + +#endif // HAS_PRUSA_MMU1 diff --git a/src/feature/mmu/mmu.h b/src/feature/mmu/mmu.h new file mode 100644 index 0000000..23742d0 --- /dev/null +++ b/src/feature/mmu/mmu.h @@ -0,0 +1,25 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +void mmu_init(); +void select_multiplexed_stepper(const uint8_t e); diff --git a/src/feature/mmu/mmu2-serial-protocol.md b/src/feature/mmu/mmu2-serial-protocol.md new file mode 100644 index 0000000..d8939ae --- /dev/null +++ b/src/feature/mmu/mmu2-serial-protocol.md @@ -0,0 +1,94 @@ +Startup sequence +================ + +When initialized, MMU sends + +- MMU => 'start\n' + +We follow with + +- MMU <= 'S1\n' +- MMU => 'ok*Firmware version*\n' +- MMU <= 'S2\n' +- MMU => 'ok*Build number*\n' + +#if (12V_mode) + +- MMU <= 'M1\n' +- MMU => 'ok\n' + +#endif + +- MMU <= 'P0\n' +- MMU => '*FINDA status*\n' + +Now we are sure MMU is available and ready. If there was a timeout or other communication problem somewhere, printer will be killed. + +- *Firmware version* is an integer value, but we don't care about it +- *Build number* is an integer value and has to be >=126, or =>132 if 12V mode is enabled +- *FINDA status* is 1 if the filament is loaded to the extruder, 0 otherwise + + +*Build number* is checked against the required value, if it does not match, printer is halted. + + + +Toolchange +========== + +- MMU <= 'T*Filament index*\n' + +MMU sends + +- MMU => 'ok\n' + +as soon as the filament is fed down to the extruder. We follow with + +- MMU <= 'C0\n' + +MMU will feed a few more millimeters of filament for the extruder gears to grab. +When done, the MMU sends + +- MMU => 'ok\n' + +We don't wait for a response here but immediately continue with the next G-code which should +be one or more extruder moves to feed the filament into the hotend. + + +FINDA status +============ + +- MMU <= 'P0\n' +- MMU => '*FINDA status*\n' + +*FINDA status* is 1 if the is filament loaded to the extruder, 0 otherwise. This could be used as filament runout sensor if probed regularly. + + + +Load filament +============= + +- MMU <= 'L*Filament index*\n' + +MMU will feed filament down to the extruder, when done + +- MMU => 'ok\n' + + +Unload filament +============= + +- MMU <= 'U0\n' + +MMU will retract current filament from the extruder, when done + +- MMU => 'ok\n' + + + +Eject filament +============== + +- MMU <= 'E*Filament index*\n' +- MMU => 'ok\n' + diff --git a/src/feature/mmu/mmu2.cpp b/src/feature/mmu/mmu2.cpp new file mode 100644 index 0000000..a4718b5 --- /dev/null +++ b/src/feature/mmu/mmu2.cpp @@ -0,0 +1,1046 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../../inc/MarlinConfig.h" + +#if HAS_PRUSA_MMU2 + +#include "mmu2.h" +#include "../../lcd/menu/menu_mmu2.h" + +MMU2 mmu2; + +#include "../../gcode/gcode.h" +#include "../../lcd/marlinui.h" +#include "../../libs/buzzer.h" +#include "../../libs/nozzle.h" +#include "../../module/temperature.h" +#include "../../module/planner.h" +#include "../../module/stepper.h" +#include "../../MarlinCore.h" + +#if ENABLED(HOST_PROMPT_SUPPORT) + #include "../../feature/host_actions.h" +#endif + +#if ENABLED(EXTENSIBLE_UI) + #include "../../lcd/extui/ui_api.h" +#endif + +#define DEBUG_OUT ENABLED(MMU2_DEBUG) +#include "../../core/debug_out.h" + +#define MMU_TODELAY 100 +#define MMU_TIMEOUT 10 +#define MMU_CMD_TIMEOUT 45000UL // 45s timeout for mmu commands (except P0) +#define MMU_P0_TIMEOUT 3000UL // Timeout for P0 command: 3seconds + +#define MMU2_COMMAND(S) tx_str(F(S "\n")) + +#if ENABLED(MMU_EXTRUDER_SENSOR) + uint8_t mmu_idl_sens = 0; + static bool mmu_loading_flag = false; +#endif + +#define MMU_CMD_NONE 0 +#define MMU_CMD_T0 0x10 // up to supported filaments +#define MMU_CMD_L0 0x20 // up to supported filaments +#define MMU_CMD_C0 0x30 +#define MMU_CMD_U0 0x40 +#define MMU_CMD_E0 0x50 // up to supported filaments +#define MMU_CMD_R0 0x60 +#define MMU_CMD_F0 0x70 // up to supported filaments + +#define MMU_REQUIRED_FW_BUILDNR TERN(MMU2_MODE_12V, 132, 126) + +#define MMU2_NO_TOOL 99 +#define MMU_BAUD 115200 + +bool MMU2::_enabled, MMU2::ready, MMU2::mmu_print_saved; +#if HAS_PRUSA_MMU2S + bool MMU2::mmu2s_triggered; +#endif +uint8_t MMU2::cmd, MMU2::cmd_arg, MMU2::last_cmd, MMU2::extruder; +int8_t MMU2::state = 0; +volatile int8_t MMU2::finda = 1; +volatile bool MMU2::finda_runout_valid; +int16_t MMU2::version = -1, MMU2::buildnr = -1; +millis_t MMU2::prev_request, MMU2::prev_P0_request; +char MMU2::rx_buffer[MMU_RX_SIZE], MMU2::tx_buffer[MMU_TX_SIZE]; + +struct E_Step { + float extrude; //!< extrude distance in mm + feedRate_t feedRate; //!< feed rate in mm/s +}; + +static constexpr E_Step + ramming_sequence[] PROGMEM = { MMU2_RAMMING_SEQUENCE } + , load_to_nozzle_sequence[] PROGMEM = { MMU2_LOAD_TO_NOZZLE_SEQUENCE } + #if HAS_PRUSA_MMU2S + , can_load_sequence[] PROGMEM = { MMU2_CAN_LOAD_SEQUENCE } + , can_load_increment_sequence[] PROGMEM = { MMU2_CAN_LOAD_INCREMENT_SEQUENCE } + #endif +; + +MMU2::MMU2() { + rx_buffer[0] = '\0'; +} + +void MMU2::init() { + + set_runout_valid(false); + + #if PIN_EXISTS(MMU2_RST) + WRITE(MMU2_RST_PIN, HIGH); + SET_OUTPUT(MMU2_RST_PIN); + #endif + + MMU2_SERIAL.begin(MMU_BAUD); + extruder = MMU2_NO_TOOL; + + safe_delay(10); + reset(); + rx_buffer[0] = '\0'; + state = -1; +} + +void MMU2::reset() { + DEBUG_ECHOLNPGM("MMU <= reset"); + + #if PIN_EXISTS(MMU2_RST) + WRITE(MMU2_RST_PIN, LOW); + safe_delay(20); + WRITE(MMU2_RST_PIN, HIGH); + #else + MMU2_COMMAND("X0"); // Send soft reset + #endif +} + +uint8_t MMU2::get_current_tool() { + return extruder == MMU2_NO_TOOL ? -1 : extruder; +} + +#if EITHER(HAS_PRUSA_MMU2S, MMU_EXTRUDER_SENSOR) + #define FILAMENT_PRESENT() (READ(FIL_RUNOUT1_PIN) != FIL_RUNOUT1_STATE) +#endif + +void mmu2_attn_buzz(const bool two=false) { + BUZZ(200, 404); + if (two) { BUZZ(10, 0); BUZZ(200, 404); } +} + +void MMU2::mmu_loop() { + + switch (state) { + + case 0: break; + + case -1: + if (rx_start()) { + prev_P0_request = millis(); // Initialize finda sensor timeout + + DEBUG_ECHOLNPGM("MMU => 'start'"); + DEBUG_ECHOLNPGM("MMU <= 'S1'"); + + MMU2_COMMAND("S1"); // Read Version + state = -2; + } + else if (millis() > 30000) { // 30sec after reset disable MMU + SERIAL_ECHOLNPGM("MMU not responding - DISABLED"); + state = 0; + } + break; + + case -2: + if (rx_ok()) { + sscanf(rx_buffer, "%huok\n", &version); + + DEBUG_ECHOLNPGM("MMU => ", version, "\nMMU <= 'S2'"); + + MMU2_COMMAND("S2"); // Read Build Number + state = -3; + } + break; + + case -3: + if (rx_ok()) { + sscanf(rx_buffer, "%huok\n", &buildnr); + + DEBUG_ECHOLNPGM("MMU => ", buildnr); + + check_version(); + + #if ENABLED(MMU2_MODE_12V) + DEBUG_ECHOLNPGM("MMU <= 'M1'"); + + MMU2_COMMAND("M1"); // Stealth Mode + state = -5; + + #else + DEBUG_ECHOLNPGM("MMU <= 'P0'"); + + MMU2_COMMAND("P0"); // Read FINDA + state = -4; + #endif + } + break; + + #if ENABLED(MMU2_MODE_12V) + case -5: + // response to M1 + if (rx_ok()) { + DEBUG_ECHOLNPGM("MMU => ok"); + + DEBUG_ECHOLNPGM("MMU <= 'P0'"); + + MMU2_COMMAND("P0"); // Read FINDA + state = -4; + } + break; + #endif + + case -4: + if (rx_ok()) { + sscanf(rx_buffer, "%hhuok\n", &finda); + + DEBUG_ECHOLNPGM("MMU => ", finda, "\nMMU - ENABLED"); + + _enabled = true; + state = 1; + TERN_(HAS_PRUSA_MMU2S, mmu2s_triggered = false); + } + break; + + case 1: + if (cmd) { + if (WITHIN(cmd, MMU_CMD_T0, MMU_CMD_T0 + EXTRUDERS - 1)) { + // tool change + const int filament = cmd - MMU_CMD_T0; + DEBUG_ECHOLNPGM("MMU <= T", filament); + tx_printf(F("T%d\n"), filament); + TERN_(MMU_EXTRUDER_SENSOR, mmu_idl_sens = 1); // enable idler sensor, if any + state = 3; // wait for response + } + else if (WITHIN(cmd, MMU_CMD_L0, MMU_CMD_L0 + EXTRUDERS - 1)) { + // load + const int filament = cmd - MMU_CMD_L0; + DEBUG_ECHOLNPGM("MMU <= L", filament); + tx_printf(F("L%d\n"), filament); + state = 3; // wait for response + } + else if (cmd == MMU_CMD_C0) { + // continue loading + DEBUG_ECHOLNPGM("MMU <= 'C0'"); + MMU2_COMMAND("C0"); + state = 3; // wait for response + } + else if (cmd == MMU_CMD_U0) { + // unload current + DEBUG_ECHOLNPGM("MMU <= 'U0'"); + + MMU2_COMMAND("U0"); + state = 3; // wait for response + } + else if (WITHIN(cmd, MMU_CMD_E0, MMU_CMD_E0 + EXTRUDERS - 1)) { + // eject filament + const int filament = cmd - MMU_CMD_E0; + DEBUG_ECHOLNPGM("MMU <= E", filament); + tx_printf(F("E%d\n"), filament); + state = 3; // wait for response + } + else if (cmd == MMU_CMD_R0) { + // recover after eject + DEBUG_ECHOLNPGM("MMU <= 'R0'"); + MMU2_COMMAND("R0"); + state = 3; // wait for response + } + else if (WITHIN(cmd, MMU_CMD_F0, MMU_CMD_F0 + EXTRUDERS - 1)) { + // filament type + const int filament = cmd - MMU_CMD_F0; + DEBUG_ECHOLNPGM("MMU <= F", filament, " ", cmd_arg); + tx_printf(F("F%d %d\n"), filament, cmd_arg); + state = 3; // wait for response + } + + last_cmd = cmd; + cmd = MMU_CMD_NONE; + } + else if (ELAPSED(millis(), prev_P0_request + 300)) { + MMU2_COMMAND("P0"); // Read FINDA + state = 2; // wait for response + } + + TERN_(HAS_PRUSA_MMU2S, check_filament()); + break; + + case 2: // response to command P0 + if (rx_ok()) { + sscanf(rx_buffer, "%hhuok\n", &finda); + + // This is super annoying. Only activate if necessary + // if (finda_runout_valid) DEBUG_ECHOLNPAIR_F("MMU <= 'P0'\nMMU => ", finda, 6); + + if (!finda && finda_runout_valid) filament_runout(); + if (cmd == MMU_CMD_NONE) ready = true; + state = 1; + } + else if (ELAPSED(millis(), prev_request + MMU_P0_TIMEOUT)) // Resend request after timeout (3s) + state = 1; + + TERN_(HAS_PRUSA_MMU2S, check_filament()); + break; + + case 3: // response to mmu commands + #if ENABLED(MMU_EXTRUDER_SENSOR) + if (mmu_idl_sens) { + if (FILAMENT_PRESENT() && mmu_loading_flag) { + DEBUG_ECHOLNPGM("MMU <= 'A'"); + MMU2_COMMAND("A"); // send 'abort' request + mmu_idl_sens = 0; + DEBUG_ECHOLNPGM("MMU IDLER_SENSOR = 0 - ABORT"); + } + } + #endif + + if (rx_ok()) { + #if HAS_PRUSA_MMU2S + // Respond to C0 MMU command in MMU2S model + const bool keep_trying = !mmu2s_triggered && last_cmd == MMU_CMD_C0; + if (keep_trying) { + // MMU ok received but filament sensor not triggered, retrying... + DEBUG_ECHOLNPGM("MMU => 'ok' (filament not present in gears)"); + DEBUG_ECHOLNPGM("MMU <= 'C0' (keep trying)"); + MMU2_COMMAND("C0"); + } + #else + constexpr bool keep_trying = false; + #endif + + if (!keep_trying) { + DEBUG_ECHOLNPGM("MMU => 'ok'"); + ready = true; + state = 1; + last_cmd = MMU_CMD_NONE; + } + } + else if (ELAPSED(millis(), prev_request + MMU_CMD_TIMEOUT)) { + // resend request after timeout + if (last_cmd) { + DEBUG_ECHOLNPGM("MMU retry"); + cmd = last_cmd; + last_cmd = MMU_CMD_NONE; + } + state = 1; + } + TERN_(HAS_PRUSA_MMU2S, check_filament()); + break; + } +} + +/** + * Check if MMU was started + */ +bool MMU2::rx_start() { + // check for start message + return rx_str(F("start\n")); +} + +/** + * Check if the data received ends with the given string. + */ +bool MMU2::rx_str(FSTR_P fstr) { + PGM_P pstr = FTOP(fstr); + + uint8_t i = strlen(rx_buffer); + + while (MMU2_SERIAL.available()) { + rx_buffer[i++] = MMU2_SERIAL.read(); + + if (i == sizeof(rx_buffer) - 1) { + DEBUG_ECHOLNPGM("rx buffer overrun"); + break; + } + } + rx_buffer[i] = '\0'; + + uint8_t len = strlen_P(pstr); + + if (i < len) return false; + + pstr += len; + + while (len--) { + char c0 = pgm_read_byte(pstr--), c1 = rx_buffer[i--]; + if (c0 == c1) continue; + if (c0 == '\r' && c1 == '\n') continue; // match cr as lf + if (c0 == '\n' && c1 == '\r') continue; // match lf as cr + return false; + } + return true; +} + +/** + * Transfer data to MMU, no argument + */ +void MMU2::tx_str(FSTR_P fstr) { + clear_rx_buffer(); + PGM_P pstr = FTOP(fstr); + while (const char c = pgm_read_byte(pstr)) { MMU2_SERIAL.write(c); pstr++; } + prev_request = millis(); +} + +/** + * Transfer data to MMU, single argument + */ +void MMU2::tx_printf(FSTR_P format, int argument = -1) { + clear_rx_buffer(); + const uint8_t len = sprintf_P(tx_buffer, FTOP(format), argument); + LOOP_L_N(i, len) MMU2_SERIAL.write(tx_buffer[i]); + prev_request = millis(); +} + +/** + * Transfer data to MMU, two arguments + */ +void MMU2::tx_printf(FSTR_P format, int argument1, int argument2) { + clear_rx_buffer(); + const uint8_t len = sprintf_P(tx_buffer, FTOP(format), argument1, argument2); + LOOP_L_N(i, len) MMU2_SERIAL.write(tx_buffer[i]); + prev_request = millis(); +} + +/** + * Empty the rx buffer + */ +void MMU2::clear_rx_buffer() { + while (MMU2_SERIAL.available()) MMU2_SERIAL.read(); + rx_buffer[0] = '\0'; +} + +/** + * Check if we received 'ok' from MMU + */ +bool MMU2::rx_ok() { + if (rx_str(F("ok\n"))) { + prev_P0_request = millis(); + return true; + } + return false; +} + +/** + * Check if MMU has compatible firmware + */ +void MMU2::check_version() { + if (buildnr < MMU_REQUIRED_FW_BUILDNR) { + SERIAL_ERROR_MSG("Invalid MMU2 firmware. Version >= " STRINGIFY(MMU_REQUIRED_FW_BUILDNR) " required."); + kill(GET_TEXT_F(MSG_KILL_MMU2_FIRMWARE)); + } +} + +static void mmu2_not_responding() { + LCD_MESSAGE(MSG_MMU2_NOT_RESPONDING); + BUZZ(100, 659); + BUZZ(200, 698); + BUZZ(100, 659); + BUZZ(300, 440); + BUZZ(100, 659); +} + +#if HAS_PRUSA_MMU2S + + bool MMU2::load_to_gears() { + command(MMU_CMD_C0); + manage_response(true, true); + LOOP_L_N(i, MMU2_C0_RETRY) { // Keep loading until filament reaches gears + if (mmu2s_triggered) break; + command(MMU_CMD_C0); + manage_response(true, true); + check_filament(); + } + const bool success = mmu2s_triggered && can_load(); + if (!success) mmu2_not_responding(); + return success; + } + + /** + * Handle tool change + */ + void MMU2::tool_change(const uint8_t index) { + + if (!_enabled) return; + + set_runout_valid(false); + + if (index != extruder) { + + stepper.disable_extruder(); + ui.status_printf(0, GET_TEXT_F(MSG_MMU2_LOADING_FILAMENT), int(index + 1)); + + command(MMU_CMD_T0 + index); + manage_response(true, true); + + if (load_to_gears()) { + extruder = index; // filament change is finished + active_extruder = 0; + stepper.enable_extruder(); + SERIAL_ECHO_MSG(STR_ACTIVE_EXTRUDER, extruder); + } + ui.reset_status(); + } + + set_runout_valid(true); + } + + /** + * Handle special T?/Tx/Tc commands + * + * T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically + * Tx Same as T?, except nozzle doesn't have to be preheated. Tc must be placed after extruder nozzle is preheated to finish filament load. + * Tc Load to nozzle after filament was prepared by Tx and extruder nozzle is already heated. + */ + void MMU2::tool_change(const char *special) { + if (!_enabled) return; + + set_runout_valid(false); + + switch (*special) { + case '?': { + #if ENABLED(MMU2_MENUS) + const uint8_t index = mmu2_choose_filament(); + while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(100); + load_filament_to_nozzle(index); + #else + ERR_BUZZ(); + #endif + } break; + + case 'x': { + #if ENABLED(MMU2_MENUS) + planner.synchronize(); + const uint8_t index = mmu2_choose_filament(); + stepper.disable_extruder(); + command(MMU_CMD_T0 + index); + manage_response(true, true); + + if (load_to_gears()) { + mmu_loop(); + stepper.enable_extruder(); + extruder = index; + active_extruder = 0; + } + #else + ERR_BUZZ(); + #endif + } break; + + case 'c': { + while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(100); + load_to_nozzle(); + } break; + } + + set_runout_valid(true); + } + +#elif ENABLED(MMU_EXTRUDER_SENSOR) + + /** + * Handle tool change + */ + void MMU2::tool_change(const uint8_t index) { + if (!_enabled) return; + + set_runout_valid(false); + + if (index != extruder) { + stepper.disable_extruder(); + if (FILAMENT_PRESENT()) { + DEBUG_ECHOLNPGM("Unloading\n"); + mmu_loading_flag = false; + command(MMU_CMD_U0); + manage_response(true, true); + } + ui.status_printf(0, GET_TEXT_F(MSG_MMU2_LOADING_FILAMENT), int(index + 1)); + mmu_loading_flag = true; + command(MMU_CMD_T0 + index); + manage_response(true, true); + mmu_continue_loading(); + command(MMU_CMD_C0); + extruder = index; + active_extruder = 0; + + stepper.enable_extruder(); + SERIAL_ECHO_MSG(STR_ACTIVE_EXTRUDER, extruder); + + ui.reset_status(); + } + + set_runout_valid(true); + } + + /** + * Handle special T?/Tx/Tc commands + * + * T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically + * Tx Same as T?, except nozzle doesn't have to be preheated. Tc must be placed after extruder nozzle is preheated to finish filament load. + * Tc Load to nozzle after filament was prepared by Tx and extruder nozzle is already heated. + */ + void MMU2::tool_change(const char *special) { + if (!_enabled) return; + + set_runout_valid(false); + + switch (*special) { + case '?': { + DEBUG_ECHOLNPGM("case ?\n"); + #if ENABLED(MMU2_MENUS) + uint8_t index = mmu2_choose_filament(); + while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(100); + load_filament_to_nozzle(index); + #else + ERR_BUZZ(); + #endif + } break; + + case 'x': { + DEBUG_ECHOLNPGM("case x\n"); + #if ENABLED(MMU2_MENUS) + planner.synchronize(); + uint8_t index = mmu2_choose_filament(); + stepper.disable_extruder(); + command(MMU_CMD_T0 + index); + manage_response(true, true); + mmu_continue_loading(); + command(MMU_CMD_C0); + mmu_loop(); + + stepper.enable_extruder(); + extruder = index; + active_extruder = 0; + #else + ERR_BUZZ(); + #endif + } break; + + case 'c': { + DEBUG_ECHOLNPGM("case c\n"); + while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(100); + execute_extruder_sequence((const E_Step *)load_to_nozzle_sequence, COUNT(load_to_nozzle_sequence)); + } break; + } + + set_runout_valid(true); + } + + void MMU2::mmu_continue_loading() { + for (uint8_t i = 0; i < MMU_LOADING_ATTEMPTS_NR; i++) { + DEBUG_ECHOLNPGM("Additional load attempt #", i); + if (FILAMENT_PRESENT()) break; + command(MMU_CMD_C0); + manage_response(true, true); + } + if (!FILAMENT_PRESENT()) { + DEBUG_ECHOLNPGM("Filament never reached sensor, runout"); + filament_runout(); + } + mmu_idl_sens = 0; + } + +#else // !HAS_PRUSA_MMU2S && !MMU_EXTRUDER_SENSOR + + /** + * Handle tool change + */ + void MMU2::tool_change(const uint8_t index) { + if (!_enabled) return; + + set_runout_valid(false); + + if (index != extruder) { + stepper.disable_extruder(); + ui.status_printf(0, GET_TEXT_F(MSG_MMU2_LOADING_FILAMENT), int(index + 1)); + command(MMU_CMD_T0 + index); + manage_response(true, true); + command(MMU_CMD_C0); + extruder = index; //filament change is finished + active_extruder = 0; + stepper.enable_extruder(); + SERIAL_ECHO_MSG(STR_ACTIVE_EXTRUDER, extruder); + ui.reset_status(); + } + + set_runout_valid(true); + } + + /** + * Handle special T?/Tx/Tc commands + * + * T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically + * Tx Same as T?, except nozzle doesn't have to be preheated. Tc must be placed after extruder nozzle is preheated to finish filament load. + * Tc Load to nozzle after filament was prepared by Tx and extruder nozzle is already heated. + */ + void MMU2::tool_change(const char *special) { + if (!_enabled) return; + + set_runout_valid(false); + + switch (*special) { + case '?': { + DEBUG_ECHOLNPGM("case ?\n"); + #if ENABLED(MMU2_MENUS) + uint8_t index = mmu2_choose_filament(); + while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(100); + load_filament_to_nozzle(index); + #else + ERR_BUZZ(); + #endif + } break; + + case 'x': { + DEBUG_ECHOLNPGM("case x\n"); + #if ENABLED(MMU2_MENUS) + planner.synchronize(); + uint8_t index = mmu2_choose_filament(); + stepper.disable_extruder(); + command(MMU_CMD_T0 + index); + manage_response(true, true); + command(MMU_CMD_C0); + mmu_loop(); + + stepper.enable_extruder(); + extruder = index; + active_extruder = 0; + #else + ERR_BUZZ(); + #endif + } break; + + case 'c': { + DEBUG_ECHOLNPGM("case c\n"); + while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(100); + execute_extruder_sequence((const E_Step *)load_to_nozzle_sequence, COUNT(load_to_nozzle_sequence)); + } break; + } + + set_runout_valid(true); + } + +#endif // HAS_PRUSA_MMU2S + +/** + * Set next command + */ +void MMU2::command(const uint8_t mmu_cmd) { + if (!_enabled) return; + cmd = mmu_cmd; + ready = false; +} + +/** + * Wait for response from MMU + */ +bool MMU2::get_response() { + while (cmd != MMU_CMD_NONE) idle(); + + while (!ready) { + idle(); + if (state != 3) break; + } + + const bool ret = ready; + ready = false; + + return ret; +} + +/** + * Wait for response and deal with timeout if necessary + */ +void MMU2::manage_response(const bool move_axes, const bool turn_off_nozzle) { + + constexpr xyz_pos_t park_point = NOZZLE_PARK_POINT; + bool response = false; + mmu_print_saved = false; + xyz_pos_t resume_position; + celsius_t resume_hotend_temp = thermalManager.degTargetHotend(active_extruder); + + KEEPALIVE_STATE(PAUSED_FOR_USER); + + while (!response) { + + response = get_response(); // wait for "ok" from mmu + + if (!response) { // No "ok" was received in reserved time frame, user will fix the issue on mmu unit + if (!mmu_print_saved) { // First occurrence. Save current position, park print head, disable nozzle heater. + + planner.synchronize(); + + mmu_print_saved = true; + + SERIAL_ECHOLNPGM("MMU not responding"); + + resume_hotend_temp = thermalManager.degTargetHotend(active_extruder); + resume_position = current_position; + + if (move_axes && all_axes_homed()) + nozzle.park(0, park_point /*= NOZZLE_PARK_POINT*/); + + if (turn_off_nozzle) thermalManager.setTargetHotend(0, active_extruder); + + mmu2_not_responding(); + } + } + else if (mmu_print_saved) { + SERIAL_ECHOLNPGM("MMU starts responding\n"); + + if (turn_off_nozzle && resume_hotend_temp) { + thermalManager.setTargetHotend(resume_hotend_temp, active_extruder); + LCD_MESSAGE(MSG_HEATING); + ERR_BUZZ(); + + while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(1000); + } + + LCD_MESSAGE(MSG_MMU2_RESUMING); + mmu2_attn_buzz(true); + + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" + + if (move_axes && all_axes_homed()) { + // Move XY to starting position, then Z + do_blocking_move_to_xy(resume_position, feedRate_t(NOZZLE_PARK_XY_FEEDRATE)); + + // Move Z_AXIS to saved position + do_blocking_move_to_z(resume_position.z, feedRate_t(NOZZLE_PARK_Z_FEEDRATE)); + } + + #pragma GCC diagnostic pop + } + } +} + +void MMU2::set_filament_type(const uint8_t index, const uint8_t filamentType) { + if (!_enabled) return; + + cmd_arg = filamentType; + command(MMU_CMD_F0 + index); + + manage_response(true, true); +} + +void MMU2::filament_runout() { + queue.inject(F(MMU2_FILAMENT_RUNOUT_SCRIPT)); + planner.synchronize(); +} + +#if HAS_PRUSA_MMU2S + + void MMU2::check_filament() { + const bool present = FILAMENT_PRESENT(); + if (cmd == MMU_CMD_NONE && last_cmd == MMU_CMD_C0) { + if (present && !mmu2s_triggered) { + DEBUG_ECHOLNPGM("MMU <= 'A'"); + tx_str(F("A\n")); + } + // Slowly spin the extruder during C0 + else { + while (planner.movesplanned() < 3) { + current_position.e += 0.25; + line_to_current_position(MMM_TO_MMS(120)); + } + } + } + mmu2s_triggered = present; + } + + bool MMU2::can_load() { + execute_extruder_sequence((const E_Step *)can_load_sequence, COUNT(can_load_sequence)); + + int filament_detected_count = 0; + const int steps = (MMU2_CAN_LOAD_RETRACT) / (MMU2_CAN_LOAD_INCREMENT); + DEBUG_ECHOLNPGM("MMU can_load:"); + LOOP_L_N(i, steps) { + execute_extruder_sequence((const E_Step *)can_load_increment_sequence, COUNT(can_load_increment_sequence)); + check_filament(); // Don't trust the idle function + DEBUG_CHAR(mmu2s_triggered ? 'O' : 'o'); + if (mmu2s_triggered) ++filament_detected_count; + } + + if (filament_detected_count <= steps - (MMU2_CAN_LOAD_DEVIATION) / (MMU2_CAN_LOAD_INCREMENT)) { + DEBUG_ECHOLNPGM(" failed."); + return false; + } + + DEBUG_ECHOLNPGM(" succeeded."); + return true; + } + +#endif + +// Load filament into MMU2 +void MMU2::load_filament(const uint8_t index) { + if (!_enabled) return; + + command(MMU_CMD_L0 + index); + manage_response(false, false); + mmu2_attn_buzz(); +} + +/** + * Switch material and load to nozzle + */ +bool MMU2::load_filament_to_nozzle(const uint8_t index) { + + if (!_enabled) return false; + + if (thermalManager.tooColdToExtrude(active_extruder)) { + mmu2_attn_buzz(); + LCD_ALERTMESSAGE(MSG_HOTEND_TOO_COLD); + return false; + } + + stepper.disable_extruder(); + command(MMU_CMD_T0 + index); + manage_response(true, true); + + const bool success = load_to_gears(); + if (success) { + mmu_loop(); + extruder = index; + active_extruder = 0; + load_to_nozzle(); + mmu2_attn_buzz(); + } + return success; +} + +/** + * Load filament to nozzle of multimaterial printer + * + * This function is used only after T? (user select filament) and M600 (change filament). + * It is not used after T0 .. T4 command (select filament), in such case, G-code is responsible for loading + * filament to nozzle. + */ +void MMU2::load_to_nozzle() { + execute_extruder_sequence((const E_Step *)load_to_nozzle_sequence, COUNT(load_to_nozzle_sequence)); +} + +bool MMU2::eject_filament(const uint8_t index, const bool recover) { + + if (!_enabled) return false; + + if (thermalManager.tooColdToExtrude(active_extruder)) { + mmu2_attn_buzz(); + LCD_ALERTMESSAGE(MSG_HOTEND_TOO_COLD); + return false; + } + + LCD_MESSAGE(MSG_MMU2_EJECTING_FILAMENT); + + stepper.enable_extruder(); + current_position.e -= MMU2_FILAMENTCHANGE_EJECT_FEED; + line_to_current_position(MMM_TO_MMS(2500)); + planner.synchronize(); + command(MMU_CMD_E0 + index); + manage_response(false, false); + + if (recover) { + LCD_MESSAGE(MSG_MMU2_EJECT_RECOVER); + mmu2_attn_buzz(); + TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_do(PROMPT_USER_CONTINUE, F("MMU2 Eject Recover"), FPSTR(CONTINUE_STR))); + TERN_(EXTENSIBLE_UI, ExtUI::onUserConfirmRequired(F("MMU2 Eject Recover"))); + TERN_(HAS_RESUME_CONTINUE, wait_for_user_response()); + mmu2_attn_buzz(true); + + command(MMU_CMD_R0); + manage_response(false, false); + } + + ui.reset_status(); + + // no active tool + extruder = MMU2_NO_TOOL; + + set_runout_valid(false); + + mmu2_attn_buzz(); + + stepper.disable_extruder(); + + return true; +} + +/** + * Unload from hotend and retract to MMU + */ +bool MMU2::unload() { + + if (!_enabled) return false; + + if (thermalManager.tooColdToExtrude(active_extruder)) { + mmu2_attn_buzz(); + LCD_ALERTMESSAGE(MSG_HOTEND_TOO_COLD); + return false; + } + + // Unload sequence to optimize shape of the tip of the unloaded filament + execute_extruder_sequence((const E_Step *)ramming_sequence, sizeof(ramming_sequence) / sizeof(E_Step)); + + command(MMU_CMD_U0); + manage_response(false, true); + + mmu2_attn_buzz(); + + // no active tool + extruder = MMU2_NO_TOOL; + + set_runout_valid(false); + + return true; +} + +void MMU2::execute_extruder_sequence(const E_Step * sequence, int steps) { + + planner.synchronize(); + stepper.enable_extruder(); + + const E_Step* step = sequence; + + LOOP_L_N(i, steps) { + const float es = pgm_read_float(&(step->extrude)); + const feedRate_t fr_mm_m = pgm_read_float(&(step->feedRate)); + + DEBUG_ECHO_MSG("E step ", es, "/", fr_mm_m); + + current_position.e += es; + line_to_current_position(MMM_TO_MMS(fr_mm_m)); + planner.synchronize(); + + step++; + } + + stepper.disable_extruder(); +} + +#endif // HAS_PRUSA_MMU2 diff --git a/src/feature/mmu/mmu2.h b/src/feature/mmu/mmu2.h new file mode 100644 index 0000000..7d3d9ec --- /dev/null +++ b/src/feature/mmu/mmu2.h @@ -0,0 +1,111 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../../inc/MarlinConfig.h" + +#if HAS_FILAMENT_SENSOR + #include "../runout.h" +#endif + +#if SERIAL_USB + #define MMU_RX_SIZE 256 + #define MMU_TX_SIZE 256 +#else + #define MMU_RX_SIZE 16 + #define MMU_TX_SIZE 16 +#endif + +struct E_Step; + +class MMU2 { +public: + MMU2(); + + static void init(); + static void reset(); + static bool enabled() { return _enabled; } + static void mmu_loop(); + static void tool_change(const uint8_t index); + static void tool_change(const char *special); + static uint8_t get_current_tool(); + static void set_filament_type(const uint8_t index, const uint8_t type); + + static bool unload(); + static void load_filament(uint8_t); + static void load_all(); + static bool load_filament_to_nozzle(const uint8_t index); + static bool eject_filament(const uint8_t index, const bool recover); + +private: + static bool rx_str(FSTR_P fstr); + static void tx_str(FSTR_P fstr); + static void tx_printf(FSTR_P ffmt, const int argument); + static void tx_printf(FSTR_P ffmt, const int argument1, const int argument2); + static void clear_rx_buffer(); + + static bool rx_ok(); + static bool rx_start(); + static void check_version(); + + static void command(const uint8_t cmd); + static bool get_response(); + static void manage_response(const bool move_axes, const bool turn_off_nozzle); + + static void load_to_nozzle(); + static void execute_extruder_sequence(const E_Step * sequence, int steps); + + static void filament_runout(); + + #if HAS_PRUSA_MMU2S + static bool mmu2s_triggered; + static void check_filament(); + static bool can_load(); + static bool load_to_gears(); + #else + FORCE_INLINE static bool load_to_gears() { return true; } + #endif + + #if ENABLED(MMU_EXTRUDER_SENSOR) + static void mmu_continue_loading(); + #endif + + static bool _enabled, ready, mmu_print_saved; + + static uint8_t cmd, cmd_arg, last_cmd, extruder; + static int8_t state; + static volatile int8_t finda; + static volatile bool finda_runout_valid; + static int16_t version, buildnr; + static millis_t prev_request, prev_P0_request; + static char rx_buffer[MMU_RX_SIZE], tx_buffer[MMU_TX_SIZE]; + + static void set_runout_valid(const bool valid) { + finda_runout_valid = valid; + #if HAS_FILAMENT_SENSOR + if (valid) runout.reset(); + #endif + } + +}; + +extern MMU2 mmu2; diff --git a/src/feature/password/password.cpp b/src/feature/password/password.cpp new file mode 100644 index 0000000..1d376cc --- /dev/null +++ b/src/feature/password/password.cpp @@ -0,0 +1,61 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../../inc/MarlinConfigPre.h" + +#if ENABLED(PASSWORD_FEATURE) + +#include "password.h" +#include "../../gcode/gcode.h" +#include "../../core/serial.h" + +Password password; + +// public: +bool Password::is_set, Password::is_locked, Password::did_first_run; // = false +uint32_t Password::value, Password::value_entry; + +// +// Authenticate user with password. +// Called from Setup, after SD Prinitng Stops/Aborts, and M510 +// +void Password::lock_machine() { + is_locked = true; + TERN_(HAS_MARLINUI_MENU, authenticate_user(ui.status_screen, screen_password_entry)); +} + +// +// Authentication check +// +void Password::authentication_check() { + if (value_entry == value) { + is_locked = false; + did_first_run = true; + } + else { + is_locked = true; + SERIAL_ECHOLNPGM(STR_WRONG_PASSWORD); + } + TERN_(HAS_MARLINUI_MENU, authentication_done()); +} + +#endif // PASSWORD_FEATURE diff --git a/src/feature/password/password.h b/src/feature/password/password.h new file mode 100644 index 0000000..208765b --- /dev/null +++ b/src/feature/password/password.h @@ -0,0 +1,57 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../../lcd/marlinui.h" + +class Password { +public: + static bool is_set, is_locked, did_first_run; + static uint32_t value, value_entry; + + Password() {} + + static void lock_machine(); + static void authentication_check(); + + #if HAS_MARLINUI_MENU + static void access_menu_password(); + static void authentication_done(); + static void media_gatekeeper(); + + private: + static void authenticate_user(const screenFunc_t, const screenFunc_t); + static void menu_password(); + static void menu_password_entry(); + static void screen_password_entry(); + static void screen_set_password(); + static void start_over(); + + static void digit_entered(); + static void set_password_done(const bool with_set=true); + static void menu_password_report(); + + static void remove_password(); + #endif +}; + +extern Password password; diff --git a/src/feature/pause.cpp b/src/feature/pause.cpp new file mode 100644 index 0000000..1c2ea59 --- /dev/null +++ b/src/feature/pause.cpp @@ -0,0 +1,726 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * feature/pause.cpp - Pause feature support functions + * This may be combined with related G-codes if features are consolidated. + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(ADVANCED_PAUSE_FEATURE) + +//#define DEBUG_PAUSE_RESUME + +#include "../MarlinCore.h" +#include "../gcode/gcode.h" +#include "../module/motion.h" +#include "../module/planner.h" +#include "../module/printcounter.h" +#include "../module/temperature.h" + +#if HAS_EXTRUDERS + #include "../module/stepper.h" +#endif + +#if ENABLED(AUTO_BED_LEVELING_UBL) + #include "bedlevel/bedlevel.h" +#endif + +#if ENABLED(FWRETRACT) + #include "fwretract.h" +#endif + +#if HAS_FILAMENT_SENSOR + #include "runout.h" +#endif + +#if ENABLED(HOST_ACTION_COMMANDS) + #include "host_actions.h" +#endif + +#if ENABLED(EXTENSIBLE_UI) + #include "../lcd/extui/ui_api.h" +#elif ENABLED(DWIN_LCD_PROUI) + #include "../lcd/e3v2/proui/dwin.h" +#endif + +#include "../lcd/marlinui.h" + +#if HAS_SOUND + #include "../libs/buzzer.h" +#endif + +#if ENABLED(POWER_LOSS_RECOVERY) + #include "powerloss.h" +#endif + +#include "../libs/nozzle.h" +#include "pause.h" + +#define DEBUG_OUT ENABLED(DEBUG_PAUSE_RESUME) +#include "../core/debug_out.h" + +// private: + +static xyze_pos_t resume_position; + +#if M600_PURGE_MORE_RESUMABLE + PauseMenuResponse pause_menu_response; + PauseMode pause_mode = PAUSE_MODE_PAUSE_PRINT; +#endif + +fil_change_settings_t fc_settings[EXTRUDERS]; + +#if ENABLED(SDSUPPORT) + #include "../sd/cardreader.h" +#endif + +#if ENABLED(EMERGENCY_PARSER) + #define _PMSG(L) L##_M108 +#else + #define _PMSG(L) L##_LCD +#endif + +#if HAS_SOUND + static void impatient_beep(const int8_t max_beep_count, const bool restart=false) { + + if (TERN0(HAS_MARLINUI_MENU, pause_mode == PAUSE_MODE_PAUSE_PRINT)) return; + + static millis_t next_buzz = 0; + static int8_t runout_beep = 0; + + if (restart) next_buzz = runout_beep = 0; + + const bool always = max_beep_count < 0; + + const millis_t ms = millis(); + if (ELAPSED(ms, next_buzz)) { + if (always || runout_beep < max_beep_count + 5) { // Only beep as long as we're supposed to + next_buzz = ms + ((always || runout_beep < max_beep_count) ? 1000 : 500); + BUZZ(50, 880 - (runout_beep & 1) * 220); + runout_beep++; + } + } + } + inline void first_impatient_beep(const int8_t max_beep_count) { impatient_beep(max_beep_count, true); } +#else + inline void impatient_beep(const int8_t, const bool=false) {} + inline void first_impatient_beep(const int8_t) {} +#endif + +/** + * Ensure a safe temperature for extrusion + * + * - Fail if the TARGET temperature is too low + * - Display LCD placard with temperature status + * - Return when heating is done or aborted + * + * Returns 'true' if heating was completed, 'false' for abort + */ +static bool ensure_safe_temperature(const bool wait=true, const PauseMode mode=PAUSE_MODE_SAME) { + DEBUG_SECTION(est, "ensure_safe_temperature", true); + DEBUG_ECHOLNPGM("... wait:", wait, " mode:", mode); + + #if ENABLED(PREVENT_COLD_EXTRUSION) + if (!DEBUGGING(DRYRUN) && thermalManager.targetTooColdToExtrude(active_extruder)) + thermalManager.setTargetHotend(thermalManager.extrude_min_temp, active_extruder); + #endif + + ui.pause_show_message(PAUSE_MESSAGE_HEATING, mode); UNUSED(mode); + + if (wait) return thermalManager.wait_for_hotend(active_extruder); + + // Allow interruption by Emergency Parser M108 + wait_for_heatup = TERN1(PREVENT_COLD_EXTRUSION, !thermalManager.allow_cold_extrude); + while (wait_for_heatup && ABS(thermalManager.wholeDegHotend(active_extruder) - thermalManager.degTargetHotend(active_extruder)) > (TEMP_WINDOW)) + idle(); + wait_for_heatup = false; + + #if ENABLED(PREVENT_COLD_EXTRUSION) + // A user can cancel wait-for-heating with M108 + if (!DEBUGGING(DRYRUN) && thermalManager.targetTooColdToExtrude(active_extruder)) { + SERIAL_ECHO_MSG(STR_ERR_HOTEND_TOO_COLD); + return false; + } + #endif + + return true; +} + +/** + * Load filament into the hotend + * + * - Fail if the a safe temperature was not reached + * - If pausing for confirmation, wait for a click or M108 + * - Show "wait for load" placard + * - Load and purge filament + * - Show "Purge more" / "Continue" menu + * - Return when "Continue" is selected + * + * Returns 'true' if load was completed, 'false' for abort + */ +bool load_filament(const_float_t slow_load_length/*=0*/, const_float_t fast_load_length/*=0*/, const_float_t purge_length/*=0*/, const int8_t max_beep_count/*=0*/, + const bool show_lcd/*=false*/, const bool pause_for_user/*=false*/, + const PauseMode mode/*=PAUSE_MODE_PAUSE_PRINT*/ + DXC_ARGS +) { + DEBUG_SECTION(lf, "load_filament", true); + DEBUG_ECHOLNPGM("... slowlen:", slow_load_length, " fastlen:", fast_load_length, " purgelen:", purge_length, " maxbeep:", max_beep_count, " showlcd:", show_lcd, " pauseforuser:", pause_for_user, " pausemode:", mode DXC_SAY); + + if (!ensure_safe_temperature(false, mode)) { + if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_STATUS, mode); + return false; + } + + if (pause_for_user) { + if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_INSERT, mode); + SERIAL_ECHO_MSG(_PMSG(STR_FILAMENT_CHANGE_INSERT)); + + first_impatient_beep(max_beep_count); + + KEEPALIVE_STATE(PAUSED_FOR_USER); + wait_for_user = true; // LCD click or M108 will clear this + + TERN_(EXTENSIBLE_UI, ExtUI::onUserConfirmRequired(F("Load Filament"))); + + #if ENABLED(HOST_PROMPT_SUPPORT) + const char tool = '0' + TERN0(MULTI_FILAMENT_SENSOR, active_extruder); + hostui.prompt_do(PROMPT_USER_CONTINUE, F("Load Filament T"), tool, FPSTR(CONTINUE_STR)); + #endif + + while (wait_for_user) { + impatient_beep(max_beep_count); + #if BOTH(FILAMENT_CHANGE_RESUME_ON_INSERT, FILAMENT_RUNOUT_SENSOR) + #if ENABLED(MULTI_FILAMENT_SENSOR) + #define _CASE_INSERTED(N) case N-1: if (READ(FIL_RUNOUT##N##_PIN) != FIL_RUNOUT##N##_STATE) wait_for_user = false; break; + switch (active_extruder) { + REPEAT_1(NUM_RUNOUT_SENSORS, _CASE_INSERTED) + } + #else + if (READ(FIL_RUNOUT_PIN) != FIL_RUNOUT_STATE) wait_for_user = false; + #endif + #endif + idle_no_sleep(); + } + } + + if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_LOAD, mode); + + #if ENABLED(DUAL_X_CARRIAGE) + const int8_t saved_ext = active_extruder; + const bool saved_ext_dup_mode = extruder_duplication_enabled; + set_duplication_enabled(false, DXC_ext); + #endif + + TERN_(BELTPRINTER, do_blocking_move_to_xy(0.00, 50.00)); + + // Slow Load filament + if (slow_load_length) unscaled_e_move(slow_load_length, FILAMENT_CHANGE_SLOW_LOAD_FEEDRATE); + + // Fast Load Filament + if (fast_load_length) { + #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0 + const float saved_acceleration = planner.settings.retract_acceleration; + planner.settings.retract_acceleration = FILAMENT_CHANGE_FAST_LOAD_ACCEL; + #endif + + unscaled_e_move(fast_load_length, FILAMENT_CHANGE_FAST_LOAD_FEEDRATE); + + #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0 + planner.settings.retract_acceleration = saved_acceleration; + #endif + } + + #if ENABLED(DUAL_X_CARRIAGE) // Tie the two extruders movement back together. + set_duplication_enabled(saved_ext_dup_mode, saved_ext); + #endif + + #if ENABLED(ADVANCED_PAUSE_CONTINUOUS_PURGE) + + if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_PURGE); + + TERN_(EXTENSIBLE_UI, ExtUI::onUserConfirmRequired(GET_TEXT_F(MSG_FILAMENT_CHANGE_PURGE))); + TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_do(PROMPT_USER_CONTINUE, GET_TEXT_F(MSG_FILAMENT_CHANGE_PURGE), FPSTR(CONTINUE_STR))); + wait_for_user = true; // A click or M108 breaks the purge_length loop + for (float purge_count = purge_length; purge_count > 0 && wait_for_user; --purge_count) + unscaled_e_move(1, ADVANCED_PAUSE_PURGE_FEEDRATE); + wait_for_user = false; + + #else + + do { + if (purge_length > 0) { + // "Wait for filament purge" + if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_PURGE); + + // Extrude filament to get into hotend + unscaled_e_move(purge_length, ADVANCED_PAUSE_PURGE_FEEDRATE); + } + + TERN_(HOST_PROMPT_SUPPORT, hostui.filament_load_prompt()); // Initiate another host prompt. + + #if M600_PURGE_MORE_RESUMABLE + if (show_lcd) { + // Show "Purge More" / "Resume" menu and wait for reply + KEEPALIVE_STATE(PAUSED_FOR_USER); + wait_for_user = false; + #if EITHER(HAS_MARLINUI_MENU, DWIN_LCD_PROUI) + ui.pause_show_message(PAUSE_MESSAGE_OPTION); // Also sets PAUSE_RESPONSE_WAIT_FOR + #else + pause_menu_response = PAUSE_RESPONSE_WAIT_FOR; + #endif + while (pause_menu_response == PAUSE_RESPONSE_WAIT_FOR) idle_no_sleep(); + } + #endif + + // Keep looping if "Purge More" was selected + } while (TERN0(M600_PURGE_MORE_RESUMABLE, pause_menu_response == PAUSE_RESPONSE_EXTRUDE_MORE)); + + #endif + TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_end()); + + return true; +} + +/** + * Disabling E steppers for manual filament change should be fine + * as long as users don't spin the E motor ridiculously fast and + * send current back to their board, potentially frying it. + */ +inline void disable_active_extruder() { + #if HAS_EXTRUDERS + stepper.DISABLE_EXTRUDER(active_extruder); + safe_delay(100); + #endif +} + +/** + * Unload filament from the hotend + * + * - Fail if the a safe temperature was not reached + * - Show "wait for unload" placard + * - Retract, pause, then unload filament + * - Disable E stepper (on most machines) + * + * Returns 'true' if unload was completed, 'false' for abort + */ +bool unload_filament(const_float_t unload_length, const bool show_lcd/*=false*/, + const PauseMode mode/*=PAUSE_MODE_PAUSE_PRINT*/ + #if BOTH(FILAMENT_UNLOAD_ALL_EXTRUDERS, MIXING_EXTRUDER) + , const_float_t mix_multiplier/*=1.0*/ + #endif +) { + DEBUG_SECTION(uf, "unload_filament", true); + DEBUG_ECHOLNPGM("... unloadlen:", unload_length, " showlcd:", show_lcd, " mode:", mode + #if BOTH(FILAMENT_UNLOAD_ALL_EXTRUDERS, MIXING_EXTRUDER) + , " mixmult:", mix_multiplier + #endif + ); + + #if !BOTH(FILAMENT_UNLOAD_ALL_EXTRUDERS, MIXING_EXTRUDER) + constexpr float mix_multiplier = 1.0f; + #endif + + if (!ensure_safe_temperature(false, mode)) { + if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_STATUS); + return false; + } + + if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_UNLOAD, mode); + + // Retract filament + unscaled_e_move(-(FILAMENT_UNLOAD_PURGE_RETRACT) * mix_multiplier, (PAUSE_PARK_RETRACT_FEEDRATE) * mix_multiplier); + + // Wait for filament to cool + safe_delay(FILAMENT_UNLOAD_PURGE_DELAY); + + // Quickly purge + unscaled_e_move((FILAMENT_UNLOAD_PURGE_RETRACT + FILAMENT_UNLOAD_PURGE_LENGTH) * mix_multiplier, + (FILAMENT_UNLOAD_PURGE_FEEDRATE) * mix_multiplier); + + // Unload filament + #if FILAMENT_CHANGE_UNLOAD_ACCEL > 0 + const float saved_acceleration = planner.settings.retract_acceleration; + planner.settings.retract_acceleration = FILAMENT_CHANGE_UNLOAD_ACCEL; + #endif + + unscaled_e_move(unload_length * mix_multiplier, (FILAMENT_CHANGE_UNLOAD_FEEDRATE) * mix_multiplier); + + #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0 + planner.settings.retract_acceleration = saved_acceleration; + #endif + + // Disable the Extruder for manual change + disable_active_extruder(); + + return true; +} + +// public: + +/** + * Pause procedure + * + * - Abort if already paused + * - Send host action for pause, if configured + * - Abort if TARGET temperature is too low + * - Display "wait for start of filament change" (if a length was specified) + * - Initial retract, if current temperature is hot enough + * - Park the nozzle at the given position + * - Call unload_filament (if a length was specified) + * + * Return 'true' if pause was completed, 'false' for abort + */ +uint8_t did_pause_print = 0; + +bool pause_print(const_float_t retract, const xyz_pos_t &park_point, const bool show_lcd/*=false*/, const_float_t unload_length/*=0*/ DXC_ARGS) { + DEBUG_SECTION(pp, "pause_print", true); + DEBUG_ECHOLNPGM("... park.x:", park_point.x, " y:", park_point.y, " z:", park_point.z, " unloadlen:", unload_length, " showlcd:", show_lcd DXC_SAY); + + UNUSED(show_lcd); + + if (did_pause_print) return false; // already paused + + #if ENABLED(HOST_ACTION_COMMANDS) + #ifdef ACTION_ON_PAUSED + hostui.paused(); + #elif defined(ACTION_ON_PAUSE) + hostui.pause(); + #endif + #endif + + TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_open(PROMPT_INFO, F("Pause"), FPSTR(DISMISS_STR))); + TERN_(DWIN_LCD_PROUI, DWIN_Print_Pause()); + + // Indicate that the printer is paused + ++did_pause_print; + + // Pause the print job and timer + #if ENABLED(SDSUPPORT) + const bool was_sd_printing = IS_SD_PRINTING(); + if (was_sd_printing) { + card.pauseSDPrint(); + ++did_pause_print; // Indicate SD pause also + } + #endif + + print_job_timer.pause(); + + // Save current position + resume_position = current_position; + + // Will the nozzle be parking? + const bool do_park = !axes_should_home(); + + #if ENABLED(POWER_LOSS_RECOVERY) + // Save PLR info in case the power goes out while parked + const float park_raise = do_park ? nozzle.park_mode_0_height(park_point.z) - current_position.z : POWER_LOSS_ZRAISE; + if (was_sd_printing && recovery.enabled) recovery.save(true, park_raise, do_park); + #endif + + // Wait for buffered blocks to complete + planner.synchronize(); + + #if ENABLED(ADVANCED_PAUSE_FANS_PAUSE) && HAS_FAN + thermalManager.set_fans_paused(true); + #endif + + // Initial retract before move to filament change position + if (retract && thermalManager.hotEnoughToExtrude(active_extruder)) { + DEBUG_ECHOLNPGM("... retract:", retract); + + #if ENABLED(AUTO_BED_LEVELING_UBL) + const bool leveling_was_enabled = planner.leveling_active; // save leveling state + set_bed_leveling_enabled(false); // turn off leveling + #endif + + unscaled_e_move(retract, PAUSE_PARK_RETRACT_FEEDRATE); + + TERN_(AUTO_BED_LEVELING_UBL, set_bed_leveling_enabled(leveling_was_enabled)); // restore leveling + } + + // If axes don't need to home then the nozzle can park + if (do_park) nozzle.park(0, park_point); // Park the nozzle by doing a Minimum Z Raise followed by an XY Move + + #if ENABLED(DUAL_X_CARRIAGE) + const int8_t saved_ext = active_extruder; + const bool saved_ext_dup_mode = extruder_duplication_enabled; + set_duplication_enabled(false, DXC_ext); + #endif + + // Unload the filament, if specified + if (unload_length) + unload_filament(unload_length, show_lcd, PAUSE_MODE_CHANGE_FILAMENT); + + #if ENABLED(DUAL_X_CARRIAGE) + set_duplication_enabled(saved_ext_dup_mode, saved_ext); + #endif + + // Disable the Extruder for manual change + disable_active_extruder(); + + return true; +} + +/** + * For Paused Print: + * - Show "Press button (or M108) to resume" + * + * For Filament Change: + * - Show "Insert filament and press button to continue" + * + * - Wait for a click before returning + * - Heaters can time out and must reheat before continuing + * + * Used by M125 and M600 + */ + +void show_continue_prompt(const bool is_reload) { + DEBUG_SECTION(scp, "pause_print", true); + DEBUG_ECHOLNPGM("... is_reload:", is_reload); + + ui.pause_show_message(is_reload ? PAUSE_MESSAGE_INSERT : PAUSE_MESSAGE_WAITING); + SERIAL_ECHO_START(); + SERIAL_ECHOF(is_reload ? F(_PMSG(STR_FILAMENT_CHANGE_INSERT) "\n") : F(_PMSG(STR_FILAMENT_CHANGE_WAIT) "\n")); +} + +void wait_for_confirmation(const bool is_reload/*=false*/, const int8_t max_beep_count/*=0*/ DXC_ARGS) { + DEBUG_SECTION(wfc, "wait_for_confirmation", true); + DEBUG_ECHOLNPGM("... is_reload:", is_reload, " maxbeep:", max_beep_count DXC_SAY); + + bool nozzle_timed_out = false; + + show_continue_prompt(is_reload); + + first_impatient_beep(max_beep_count); + + // Start the heater idle timers + const millis_t nozzle_timeout = SEC_TO_MS(PAUSE_PARK_NOZZLE_TIMEOUT); + + HOTEND_LOOP() thermalManager.heater_idle[e].start(nozzle_timeout); + + #if ENABLED(DUAL_X_CARRIAGE) + const int8_t saved_ext = active_extruder; + const bool saved_ext_dup_mode = extruder_duplication_enabled; + set_duplication_enabled(false, DXC_ext); + #endif + + // Wait for filament insert by user and press button + KEEPALIVE_STATE(PAUSED_FOR_USER); + TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_do(PROMPT_USER_CONTINUE, GET_TEXT_F(MSG_NOZZLE_PARKED), FPSTR(CONTINUE_STR))); + TERN_(EXTENSIBLE_UI, ExtUI::onUserConfirmRequired(GET_TEXT_F(MSG_NOZZLE_PARKED))); + wait_for_user = true; // LCD click or M108 will clear this + while (wait_for_user) { + impatient_beep(max_beep_count); + + // If the nozzle has timed out... + if (!nozzle_timed_out) + HOTEND_LOOP() nozzle_timed_out |= thermalManager.heater_idle[e].timed_out; + + // Wait for the user to press the button to re-heat the nozzle, then + // re-heat the nozzle, re-show the continue prompt, restart idle timers, start over + if (nozzle_timed_out) { + ui.pause_show_message(PAUSE_MESSAGE_HEAT); + SERIAL_ECHO_MSG(_PMSG(STR_FILAMENT_CHANGE_HEAT)); + + TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_do(PROMPT_USER_CONTINUE, GET_TEXT_F(MSG_HEATER_TIMEOUT), GET_TEXT_F(MSG_REHEAT))); + + TERN_(EXTENSIBLE_UI, ExtUI::onUserConfirmRequired(GET_TEXT_F(MSG_HEATER_TIMEOUT))); + + TERN_(HAS_RESUME_CONTINUE, wait_for_user_response(0, true)); // Wait for LCD click or M108 + + TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_do(PROMPT_INFO, GET_TEXT_F(MSG_REHEATING))); + + TERN_(EXTENSIBLE_UI, ExtUI::onStatusChanged(GET_TEXT_F(MSG_REHEATING))); + + TERN_(DWIN_LCD_PROUI, LCD_MESSAGE(MSG_REHEATING)); + + // Re-enable the heaters if they timed out + HOTEND_LOOP() thermalManager.reset_hotend_idle_timer(e); + + // Wait for the heaters to reach the target temperatures + ensure_safe_temperature(false); + + // Show the prompt to continue + show_continue_prompt(is_reload); + + // Start the heater idle timers + const millis_t nozzle_timeout = SEC_TO_MS(PAUSE_PARK_NOZZLE_TIMEOUT); + + HOTEND_LOOP() thermalManager.heater_idle[e].start(nozzle_timeout); + + TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_do(PROMPT_USER_CONTINUE, GET_TEXT_F(MSG_REHEATDONE), FPSTR(CONTINUE_STR))); + TERN_(EXTENSIBLE_UI, ExtUI::onUserConfirmRequired(GET_TEXT_F(MSG_REHEATDONE))); + TERN_(DWIN_LCD_PROUI, LCD_MESSAGE(MSG_REHEATDONE)); + + IF_DISABLED(PAUSE_REHEAT_FAST_RESUME, wait_for_user = true); + + nozzle_timed_out = false; + first_impatient_beep(max_beep_count); + } + idle_no_sleep(); + } + #if ENABLED(DUAL_X_CARRIAGE) + set_duplication_enabled(saved_ext_dup_mode, saved_ext); + #endif +} + +/** + * Resume or Start print procedure + * + * - If not paused, do nothing and return + * - Reset heater idle timers + * - Load filament if specified, but only if: + * - a nozzle timed out, or + * - the nozzle is already heated. + * - Display "wait for print to resume" + * - Retract to prevent oozing + * - Move the nozzle back to resume_position + * - Unretract + * - Re-prime the nozzle... + * - FWRETRACT: Recover/prime from the prior G10. + * - !FWRETRACT: Retract by resume_position.e, if negative. + * Not sure how this logic comes into use. + * - Sync the planner E to resume_position.e + * - Send host action for resume, if configured + * - Resume the current SD print job, if any + */ +void resume_print(const_float_t slow_load_length/*=0*/, const_float_t fast_load_length/*=0*/, const_float_t purge_length/*=ADVANCED_PAUSE_PURGE_LENGTH*/, const int8_t max_beep_count/*=0*/, const celsius_t targetTemp/*=0*/ DXC_ARGS) { + DEBUG_SECTION(rp, "resume_print", true); + DEBUG_ECHOLNPGM("... slowlen:", slow_load_length, " fastlen:", fast_load_length, " purgelen:", purge_length, " maxbeep:", max_beep_count, " targetTemp:", targetTemp DXC_SAY); + + /* + SERIAL_ECHOLNPGM( + "start of resume_print()\ndual_x_carriage_mode:", dual_x_carriage_mode, + "\nextruder_duplication_enabled:", extruder_duplication_enabled, + "\nactive_extruder:", active_extruder, + "\n" + ); + //*/ + + if (!did_pause_print) return; + + // Re-enable the heaters if they timed out + bool nozzle_timed_out = false; + HOTEND_LOOP() { + nozzle_timed_out |= thermalManager.heater_idle[e].timed_out; + thermalManager.reset_hotend_idle_timer(e); + } + + if (targetTemp > thermalManager.degTargetHotend(active_extruder)) + thermalManager.setTargetHotend(targetTemp, active_extruder); + + // Load the new filament + load_filament(slow_load_length, fast_load_length, purge_length, max_beep_count, true, nozzle_timed_out, PAUSE_MODE_SAME DXC_PASS); + + if (targetTemp > 0) { + thermalManager.setTargetHotend(targetTemp, active_extruder); + thermalManager.wait_for_hotend(active_extruder, false); + } + + ui.pause_show_message(PAUSE_MESSAGE_RESUME); + + // Check Temperature before moving hotend + ensure_safe_temperature(DISABLED(BELTPRINTER)); + + // Retract to prevent oozing + unscaled_e_move(-(PAUSE_PARK_RETRACT_LENGTH), feedRate_t(PAUSE_PARK_RETRACT_FEEDRATE)); + + if (!axes_should_home()) { + // Move XY back to saved position + destination.set(resume_position.x, resume_position.y, current_position.z, current_position.e); + prepare_internal_move_to_destination(NOZZLE_PARK_XY_FEEDRATE); + + // Move Z back to saved position + destination.z = resume_position.z; + prepare_internal_move_to_destination(NOZZLE_PARK_Z_FEEDRATE); + } + + #if ENABLED(AUTO_BED_LEVELING_UBL) + const bool leveling_was_enabled = planner.leveling_active; // save leveling state + set_bed_leveling_enabled(false); // turn off leveling + #endif + + // Unretract + unscaled_e_move(PAUSE_PARK_RETRACT_LENGTH, feedRate_t(PAUSE_PARK_RETRACT_FEEDRATE)); + + TERN_(AUTO_BED_LEVELING_UBL, set_bed_leveling_enabled(leveling_was_enabled)); // restore leveling + + // Intelligent resuming + #if ENABLED(FWRETRACT) + // If retracted before goto pause + if (fwretract.retracted[active_extruder]) + unscaled_e_move(-fwretract.settings.retract_length, fwretract.settings.retract_feedrate_mm_s); + #endif + + // If resume_position is negative + if (resume_position.e < 0) unscaled_e_move(resume_position.e, feedRate_t(PAUSE_PARK_RETRACT_FEEDRATE)); + #ifdef ADVANCED_PAUSE_RESUME_PRIME + if (ADVANCED_PAUSE_RESUME_PRIME != 0) + unscaled_e_move(ADVANCED_PAUSE_RESUME_PRIME, feedRate_t(ADVANCED_PAUSE_PURGE_FEEDRATE)); + #endif + + // Now all extrusion positions are resumed and ready to be confirmed + // Set extruder to saved position + planner.set_e_position_mm((destination.e = current_position.e = resume_position.e)); + + ui.pause_show_message(PAUSE_MESSAGE_STATUS); + + #ifdef ACTION_ON_RESUMED + hostui.resumed(); + #elif defined(ACTION_ON_RESUME) + hostui.resume(); + #endif + + --did_pause_print; + + TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_open(PROMPT_INFO, F("Resuming"), FPSTR(DISMISS_STR))); + + // Resume the print job timer if it was running + if (print_job_timer.isPaused()) print_job_timer.start(); + + #if ENABLED(SDSUPPORT) + if (did_pause_print) { + --did_pause_print; + card.startOrResumeFilePrinting(); + // Write PLR now to update the z axis value + TERN_(POWER_LOSS_RECOVERY, if (recovery.enabled) recovery.save(true)); + } + #endif + + #if ENABLED(ADVANCED_PAUSE_FANS_PAUSE) && HAS_FAN + thermalManager.set_fans_paused(false); + #endif + + TERN_(HAS_FILAMENT_SENSOR, runout.reset()); + + #if ENABLED(DWIN_LCD_PROUI) + DWIN_Print_Resume(); + HMI_ReturnScreen(); + #else + ui.reset_status(); + ui.return_to_status(); + #endif +} + +#endif // ADVANCED_PAUSE_FEATURE diff --git a/src/feature/pause.h b/src/feature/pause.h new file mode 100644 index 0000000..134b1d1 --- /dev/null +++ b/src/feature/pause.h @@ -0,0 +1,129 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * feature/pause.h - Pause feature support functions + * This may be combined with related G-codes if features are consolidated. + */ + +typedef struct { + float unload_length, load_length; +} fil_change_settings_t; + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(ADVANCED_PAUSE_FEATURE) + +#include "../libs/nozzle.h" + +enum PauseMode : char { + PAUSE_MODE_SAME, + PAUSE_MODE_PAUSE_PRINT, + PAUSE_MODE_CHANGE_FILAMENT, + PAUSE_MODE_LOAD_FILAMENT, + PAUSE_MODE_UNLOAD_FILAMENT +}; + +enum PauseMessage : char { + PAUSE_MESSAGE_PARKING, + PAUSE_MESSAGE_CHANGING, + PAUSE_MESSAGE_WAITING, + PAUSE_MESSAGE_UNLOAD, + PAUSE_MESSAGE_INSERT, + PAUSE_MESSAGE_LOAD, + PAUSE_MESSAGE_PURGE, + PAUSE_MESSAGE_OPTION, + PAUSE_MESSAGE_RESUME, + PAUSE_MESSAGE_STATUS, + PAUSE_MESSAGE_HEAT, + PAUSE_MESSAGE_HEATING +}; + +#if M600_PURGE_MORE_RESUMABLE + enum PauseMenuResponse : char { + PAUSE_RESPONSE_WAIT_FOR, + PAUSE_RESPONSE_EXTRUDE_MORE, + PAUSE_RESPONSE_RESUME_PRINT + }; + extern PauseMenuResponse pause_menu_response; + extern PauseMode pause_mode; +#endif + +extern fil_change_settings_t fc_settings[EXTRUDERS]; + +extern uint8_t did_pause_print; + +#define DXC_PARAMS OPTARG(DUAL_X_CARRIAGE, const int8_t DXC_ext=-1) +#define DXC_ARGS OPTARG(DUAL_X_CARRIAGE, const int8_t DXC_ext) +#define DXC_PASS OPTARG(DUAL_X_CARRIAGE, DXC_ext) +#define DXC_SAY OPTARG(DUAL_X_CARRIAGE, " dxc:", int(DXC_ext)) + +// Pause the print. If unload_length is set, do a Filament Unload +bool pause_print( + const_float_t retract, // (mm) Retraction length + const xyz_pos_t &park_point, // Parking XY Position and Z Raise + const bool show_lcd=false, // Set LCD status messages? + const_float_t unload_length=0 // (mm) Filament Change Unload Length - 0 to skip + DXC_PARAMS // Dual-X-Carriage extruder index +); + +void wait_for_confirmation( + const bool is_reload=false, // Reload Filament? (otherwise Resume Print) + const int8_t max_beep_count=0 // Beep alert for attention + DXC_PARAMS // Dual-X-Carriage extruder index +); + +void resume_print( + const_float_t slow_load_length=0, // (mm) Slow Load Length for finishing move + const_float_t fast_load_length=0, // (mm) Fast Load Length for initial move + const_float_t extrude_length=ADVANCED_PAUSE_PURGE_LENGTH, // (mm) Purge length + const int8_t max_beep_count=0, // Beep alert for attention + const celsius_t targetTemp=0 // (°C) A target temperature for the hotend + DXC_PARAMS // Dual-X-Carriage extruder index +); + +bool load_filament( + const_float_t slow_load_length=0, // (mm) Slow Load Length for finishing move + const_float_t fast_load_length=0, // (mm) Fast Load Length for initial move + const_float_t extrude_length=0, // (mm) Purge length + const int8_t max_beep_count=0, // Beep alert for attention + const bool show_lcd=false, // Set LCD status messages? + const bool pause_for_user=false, // Pause for user before returning? + const PauseMode mode=PAUSE_MODE_PAUSE_PRINT // Pause Mode to apply + DXC_PARAMS // Dual-X-Carriage extruder index +); + +bool unload_filament( + const_float_t unload_length, // (mm) Filament Unload Length - 0 to skip + const bool show_lcd=false, // Set LCD status messages? + const PauseMode mode=PAUSE_MODE_PAUSE_PRINT // Pause Mode to apply + #if BOTH(FILAMENT_UNLOAD_ALL_EXTRUDERS, MIXING_EXTRUDER) + , const_float_t mix_multiplier=1.0f // Extrusion multiplier (for a Mixing Extruder) + #endif +); + +#else // !ADVANCED_PAUSE_FEATURE + + constexpr uint8_t did_pause_print = 0; + +#endif // !ADVANCED_PAUSE_FEATURE diff --git a/src/feature/power.cpp b/src/feature/power.cpp new file mode 100644 index 0000000..8a16628 --- /dev/null +++ b/src/feature/power.cpp @@ -0,0 +1,252 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * power.cpp - power control + */ + +#include "../inc/MarlinConfigPre.h" + +#if EITHER(PSU_CONTROL, AUTO_POWER_CONTROL) + +#include "power.h" +#include "../module/planner.h" +#include "../module/stepper/indirection.h" // for restore_stepper_drivers +#include "../module/temperature.h" +#include "../MarlinCore.h" + +#if ENABLED(PS_OFF_SOUND) + #include "../libs/buzzer.h" +#endif + +#if defined(PSU_POWERUP_GCODE) || defined(PSU_POWEROFF_GCODE) + #include "../gcode/gcode.h" +#endif + +Power powerManager; +bool Power::psu_on; + +#if ENABLED(AUTO_POWER_CONTROL) + #include "../module/stepper.h" + #include "../module/temperature.h" + + #if BOTH(USE_CONTROLLER_FAN, AUTO_POWER_CONTROLLERFAN) + #include "controllerfan.h" + #endif + + millis_t Power::lastPowerOn; +#endif + +/** + * Initialize pins & state for the power manager. + * + */ +void Power::init() { + psu_on = ENABLED(PSU_DEFAULT_OFF); // Set opposite state to get full power_off/on + TERN(PSU_DEFAULT_OFF, power_off(), power_on()); +} + +/** + * Power on if the power is currently off. + * Restores stepper drivers and processes any PSU_POWERUP_GCODE. + * + */ +void Power::power_on() { + #if ENABLED(AUTO_POWER_CONTROL) + const millis_t now = millis(); + lastPowerOn = now + !now; + #endif + + if (psu_on) return; + + #if EITHER(POWER_OFF_TIMER, POWER_OFF_WAIT_FOR_COOLDOWN) + cancelAutoPowerOff(); + #endif + + OUT_WRITE(PS_ON_PIN, PSU_ACTIVE_STATE); + psu_on = true; + safe_delay(PSU_POWERUP_DELAY); + restore_stepper_drivers(); + TERN_(HAS_TRINAMIC_CONFIG, safe_delay(PSU_POWERUP_DELAY)); + + #ifdef PSU_POWERUP_GCODE + gcode.process_subcommands_now(F(PSU_POWERUP_GCODE)); + #endif +} + +/** + * Power off if the power is currently on. + * Processes any PSU_POWEROFF_GCODE and makes a PS_OFF_SOUND if enabled. + */ +void Power::power_off() { + SERIAL_ECHOLNPGM(STR_POWEROFF); + + TERN_(HAS_SUICIDE, suicide()); + + if (!psu_on) return; + + #ifdef PSU_POWEROFF_GCODE + gcode.process_subcommands_now(F(PSU_POWEROFF_GCODE)); + #endif + + #if ENABLED(PS_OFF_SOUND) + BUZZ(1000, 659); + #endif + + OUT_WRITE(PS_ON_PIN, !PSU_ACTIVE_STATE); + psu_on = false; + + #if EITHER(POWER_OFF_TIMER, POWER_OFF_WAIT_FOR_COOLDOWN) + cancelAutoPowerOff(); + #endif +} + +#if EITHER(AUTO_POWER_CONTROL, POWER_OFF_WAIT_FOR_COOLDOWN) + + bool Power::is_cooling_needed() { + #if HAS_HOTEND && AUTO_POWER_E_TEMP + HOTEND_LOOP() if (thermalManager.degHotend(e) >= (AUTO_POWER_E_TEMP)) return true; + #endif + + #if HAS_HEATED_CHAMBER && AUTO_POWER_CHAMBER_TEMP + if (thermalManager.degChamber() >= (AUTO_POWER_CHAMBER_TEMP)) return true; + #endif + + #if HAS_COOLER && AUTO_POWER_COOLER_TEMP + if (thermalManager.degCooler() >= (AUTO_POWER_COOLER_TEMP)) return true; + #endif + + return false; + } + +#endif + +#if EITHER(POWER_OFF_TIMER, POWER_OFF_WAIT_FOR_COOLDOWN) + + #if ENABLED(POWER_OFF_TIMER) + millis_t Power::power_off_time = 0; + void Power::setPowerOffTimer(const millis_t delay_ms) { power_off_time = millis() + delay_ms; } + #endif + + #if ENABLED(POWER_OFF_WAIT_FOR_COOLDOWN) + bool Power::power_off_on_cooldown = false; + void Power::setPowerOffOnCooldown(const bool ena) { power_off_on_cooldown = ena; } + #endif + + void Power::cancelAutoPowerOff() { + TERN_(POWER_OFF_TIMER, power_off_time = 0); + TERN_(POWER_OFF_WAIT_FOR_COOLDOWN, power_off_on_cooldown = false); + } + + void Power::checkAutoPowerOff() { + if (TERN1(POWER_OFF_TIMER, !power_off_time) && TERN1(POWER_OFF_WAIT_FOR_COOLDOWN, !power_off_on_cooldown)) return; + if (TERN0(POWER_OFF_WAIT_FOR_COOLDOWN, power_off_on_cooldown && is_cooling_needed())) return; + if (TERN0(POWER_OFF_TIMER, power_off_time && PENDING(millis(), power_off_time))) return; + power_off(); + } + +#endif // POWER_OFF_TIMER || POWER_OFF_WAIT_FOR_COOLDOWN + +#if ENABLED(AUTO_POWER_CONTROL) + + #ifndef POWER_TIMEOUT + #define POWER_TIMEOUT 0 + #endif + + /** + * Check all conditions that would signal power needing to be on. + * + * @returns bool if power is needed + */ + bool Power::is_power_needed() { + + // If any of the stepper drivers are enabled... + if (stepper.axis_enabled.bits) return true; + + if (printJobOngoing() || printingIsPaused()) return true; + + #if ENABLED(AUTO_POWER_FANS) + FANS_LOOP(i) if (thermalManager.fan_speed[i]) return true; + #endif + + #if ENABLED(AUTO_POWER_E_FANS) + HOTEND_LOOP() if (thermalManager.autofan_speed[e]) return true; + #endif + + #if BOTH(USE_CONTROLLER_FAN, AUTO_POWER_CONTROLLERFAN) + if (controllerFan.state()) return true; + #endif + + if (TERN0(AUTO_POWER_CHAMBER_FAN, thermalManager.chamberfan_speed)) + return true; + + if (TERN0(AUTO_POWER_COOLER_FAN, thermalManager.coolerfan_speed)) + return true; + + #if HAS_HOTEND + HOTEND_LOOP() if (thermalManager.degTargetHotend(e) > 0 || thermalManager.temp_hotend[e].soft_pwm_amount > 0) return true; + #endif + + if (TERN0(HAS_HEATED_BED, thermalManager.degTargetBed() > 0 || thermalManager.temp_bed.soft_pwm_amount > 0)) return true; + + return is_cooling_needed(); + } + + /** + * Check if we should power off automatically (POWER_TIMEOUT elapsed, !is_power_needed). + * + * @param pause pause the 'timer' + */ + void Power::check(const bool pause) { + static millis_t nextPowerCheck = 0; + const millis_t now = millis(); + #if POWER_TIMEOUT > 0 + static bool _pause = false; + if (pause != _pause) { + lastPowerOn = now + !now; + _pause = pause; + } + if (pause) return; + #endif + if (ELAPSED(now, nextPowerCheck)) { + nextPowerCheck = now + 2500UL; + if (is_power_needed()) + power_on(); + else if (!lastPowerOn || (POWER_TIMEOUT > 0 && ELAPSED(now, lastPowerOn + SEC_TO_MS(POWER_TIMEOUT)))) + power_off(); + } + } + + #if POWER_OFF_DELAY > 0 + + /** + * Power off with a delay. Power off is triggered by check() after the delay. + */ + void Power::power_off_soon() { + lastPowerOn = millis() - SEC_TO_MS(POWER_TIMEOUT) + SEC_TO_MS(POWER_OFF_DELAY); + } + + #endif + +#endif // AUTO_POWER_CONTROL + +#endif // PSU_CONTROL || AUTO_POWER_CONTROL diff --git a/src/feature/power.h b/src/feature/power.h new file mode 100644 index 0000000..839366c --- /dev/null +++ b/src/feature/power.h @@ -0,0 +1,72 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * power.h - power control + */ + +#if EITHER(AUTO_POWER_CONTROL, POWER_OFF_TIMER) + #include "../core/millis_t.h" +#endif + +class Power { + public: + static bool psu_on; + + static void init(); + static void power_on(); + static void power_off(); + + #if EITHER(POWER_OFF_TIMER, POWER_OFF_WAIT_FOR_COOLDOWN) + #if ENABLED(POWER_OFF_TIMER) + static millis_t power_off_time; + static void setPowerOffTimer(const millis_t delay_ms); + #endif + #if ENABLED(POWER_OFF_WAIT_FOR_COOLDOWN) + static bool power_off_on_cooldown; + static void setPowerOffOnCooldown(const bool ena); + #endif + static void cancelAutoPowerOff(); + static void checkAutoPowerOff(); + #endif + + #if ENABLED(AUTO_POWER_CONTROL) && POWER_OFF_DELAY > 0 + static void power_off_soon(); + #else + static void power_off_soon() { power_off(); } + #endif + + #if ENABLED(AUTO_POWER_CONTROL) + static void check(const bool pause); + + private: + static millis_t lastPowerOn; + static bool is_power_needed(); + static bool is_cooling_needed(); + #elif ENABLED(POWER_OFF_WAIT_FOR_COOLDOWN) + private: + static bool is_cooling_needed(); + #endif +}; + +extern Power powerManager; diff --git a/src/feature/power_monitor.cpp b/src/feature/power_monitor.cpp new file mode 100644 index 0000000..5a9db1e --- /dev/null +++ b/src/feature/power_monitor.cpp @@ -0,0 +1,78 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfigPre.h" + +#if HAS_POWER_MONITOR + +#include "power_monitor.h" + +#if HAS_MARLINUI_MENU + #include "../lcd/marlinui.h" + #include "../lcd/lcdprint.h" +#endif + +#include "../libs/numtostr.h" + +uint8_t PowerMonitor::flags; // = 0 + +#if ENABLED(POWER_MONITOR_CURRENT) + pm_lpf_t PowerMonitor::amps; +#endif +#if ENABLED(POWER_MONITOR_VOLTAGE) + pm_lpf_t PowerMonitor::volts; +#endif + +millis_t PowerMonitor::display_item_ms; +uint8_t PowerMonitor::display_item; + +PowerMonitor power_monitor; // Single instance - this calls the constructor + +#if HAS_MARLINUI_U8GLIB + + #if ENABLED(POWER_MONITOR_CURRENT) + void PowerMonitor::draw_current() { + const float amps = getAmps(); + lcd_put_u8str(amps < 100 ? ftostr31ns(amps) : ui16tostr4rj((uint16_t)amps)); + lcd_put_lchar('A'); + } + #endif + + #if ENABLED(POWER_MONITOR_VOLTAGE) + void PowerMonitor::draw_voltage() { + const float volts = getVolts(); + lcd_put_u8str(volts < 100 ? ftostr31ns(volts) : ui16tostr4rj((uint16_t)volts)); + lcd_put_lchar('V'); + } + #endif + + #if HAS_POWER_MONITOR_WATTS + void PowerMonitor::draw_power() { + const float power = getPower(); + lcd_put_u8str(power < 100 ? ftostr31ns(power) : ui16tostr4rj((uint16_t)power)); + lcd_put_lchar('W'); + } + #endif + +#endif // HAS_MARLINUI_U8GLIB + +#endif // HAS_POWER_MONITOR diff --git a/src/feature/power_monitor.h b/src/feature/power_monitor.h new file mode 100644 index 0000000..fa06909 --- /dev/null +++ b/src/feature/power_monitor.h @@ -0,0 +1,138 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" + +#define PM_SAMPLE_RANGE HAL_ADC_RANGE +#define PM_K_VALUE 6 +#define PM_K_SCALE 6 + +template +struct pm_lpf_t { + uint32_t filter_buf; + float value; + void add_sample(const uint16_t sample) { + filter_buf += (uint32_t(sample) << K_SCALE) - (filter_buf >> K_VALUE); + } + void capture() { + value = filter_buf * (SCALE * (1.0f / (1UL << (PM_K_VALUE + PM_K_SCALE)))); + } + void reset(uint16_t reset_value = 0) { + filter_buf = uint32_t(reset_value) << (K_VALUE + K_SCALE); + capture(); + } +}; + +class PowerMonitor { +private: + #if ENABLED(POWER_MONITOR_CURRENT) + static constexpr float amps_adc_scale = float(ADC_VREF) / (POWER_MONITOR_VOLTS_PER_AMP * PM_SAMPLE_RANGE); + static pm_lpf_t amps; + #endif + #if ENABLED(POWER_MONITOR_VOLTAGE) + static constexpr float volts_adc_scale = float(ADC_VREF) / (POWER_MONITOR_VOLTS_PER_VOLT * PM_SAMPLE_RANGE); + static pm_lpf_t volts; + #endif + +public: + static uint8_t flags; // M430 flags to display current + + static millis_t display_item_ms; + static uint8_t display_item; + + PowerMonitor() { reset(); } + + enum PM_Display_Bit : uint8_t { + PM_DISP_BIT_I, // Current display enable bit + PM_DISP_BIT_V, // Voltage display enable bit + PM_DISP_BIT_P // Power display enable bit + }; + + #if ENABLED(POWER_MONITOR_CURRENT) + FORCE_INLINE static float getAmps() { return amps.value + (POWER_MONITOR_CURRENT_OFFSET); } + void add_current_sample(const uint16_t value) { amps.add_sample(value); } + #endif + + #if ENABLED(POWER_MONITOR_VOLTAGE) + FORCE_INLINE static float getVolts() { return volts.value + (POWER_MONITOR_VOLTAGE_OFFSET); } + void add_voltage_sample(const uint16_t value) { volts.add_sample(value); } + #else + FORCE_INLINE static float getVolts() { return POWER_MONITOR_FIXED_VOLTAGE; } + #endif + + #if HAS_POWER_MONITOR_WATTS + FORCE_INLINE static float getPower() { return getAmps() * getVolts(); } + #endif + + #if HAS_WIRED_LCD + #if HAS_MARLINUI_U8GLIB && DISABLED(LIGHTWEIGHT_UI) + FORCE_INLINE static bool display_enabled() { return flags != 0x00; } + #endif + #if ENABLED(POWER_MONITOR_CURRENT) + static void draw_current(); + FORCE_INLINE static bool current_display_enabled() { return TEST(flags, PM_DISP_BIT_I); } + FORCE_INLINE static void set_current_display(const bool b) { SET_BIT_TO(flags, PM_DISP_BIT_I, b); } + FORCE_INLINE static void toggle_current_display() { TBI(flags, PM_DISP_BIT_I); } + #endif + #if ENABLED(POWER_MONITOR_VOLTAGE) + static void draw_voltage(); + FORCE_INLINE static bool voltage_display_enabled() { return TEST(flags, PM_DISP_BIT_V); } + FORCE_INLINE static void set_voltage_display(const bool b) { SET_BIT_TO(flags, PM_DISP_BIT_V, b); } + FORCE_INLINE static void toggle_voltage_display() { TBI(flags, PM_DISP_BIT_V); } + #endif + #if HAS_POWER_MONITOR_WATTS + static void draw_power(); + FORCE_INLINE static bool power_display_enabled() { return TEST(flags, PM_DISP_BIT_P); } + FORCE_INLINE static void set_power_display(const bool b) { SET_BIT_TO(flags, PM_DISP_BIT_P, b); } + FORCE_INLINE static void toggle_power_display() { TBI(flags, PM_DISP_BIT_P); } + #endif + #endif + + static void reset() { + flags = 0x00; + + #if ENABLED(POWER_MONITOR_CURRENT) + amps.reset(); + #endif + + #if ENABLED(POWER_MONITOR_VOLTAGE) + volts.reset(); + #endif + + #if ENABLED(SDSUPPORT) + display_item_ms = 0; + display_item = 0; + #endif + } + + static void capture_values() { + #if ENABLED(POWER_MONITOR_CURRENT) + amps.capture(); + #endif + #if ENABLED(POWER_MONITOR_VOLTAGE) + volts.capture(); + #endif + } +}; + +extern PowerMonitor power_monitor; diff --git a/src/feature/powerloss.cpp b/src/feature/powerloss.cpp new file mode 100644 index 0000000..d4450ad --- /dev/null +++ b/src/feature/powerloss.cpp @@ -0,0 +1,712 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * feature/powerloss.cpp - Resume an SD print after power-loss + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(POWER_LOSS_RECOVERY) + +#include "powerloss.h" +#include "../core/macros.h" + +bool PrintJobRecovery::enabled; // Initialized by settings.load() + +SdFile PrintJobRecovery::file; +job_recovery_info_t PrintJobRecovery::info; +const char PrintJobRecovery::filename[5] = "/PLR"; +uint8_t PrintJobRecovery::queue_index_r; +uint32_t PrintJobRecovery::cmd_sdpos, // = 0 + PrintJobRecovery::sdpos[BUFSIZE]; + +#if HAS_DWIN_E3V2_BASIC + bool PrintJobRecovery::dwin_flag; // = false +#endif + +#include "../sd/cardreader.h" +#include "../lcd/marlinui.h" +#include "../gcode/queue.h" +#include "../gcode/gcode.h" +#include "../module/motion.h" +#include "../module/planner.h" +#include "../module/printcounter.h" +#include "../module/temperature.h" +#include "../core/serial.h" + +#if HOMING_Z_WITH_PROBE + #include "../module/probe.h" +#endif + +#if ENABLED(FWRETRACT) + #include "fwretract.h" +#endif + +#define DEBUG_OUT ENABLED(DEBUG_POWER_LOSS_RECOVERY) +#include "../core/debug_out.h" + +PrintJobRecovery recovery; + +#ifndef POWER_LOSS_PURGE_LEN + #define POWER_LOSS_PURGE_LEN 0 +#endif + +#if DISABLED(BACKUP_POWER_SUPPLY) + #undef POWER_LOSS_RETRACT_LEN // No retract at outage without backup power +#endif +#ifndef POWER_LOSS_RETRACT_LEN + #define POWER_LOSS_RETRACT_LEN 0 +#endif + +/** + * Clear the recovery info + */ +void PrintJobRecovery::init() { memset(&info, 0, sizeof(info)); } + +/** + * Enable or disable then call changed() + */ +void PrintJobRecovery::enable(const bool onoff) { + enabled = onoff; + changed(); +} + +/** + * The enabled state was changed: + * - Enabled: Purge the job recovery file + * - Disabled: Write the job recovery file + */ +void PrintJobRecovery::changed() { + if (!enabled) + purge(); + else if (IS_SD_PRINTING()) + save(true); +} + +/** + * Check for Print Job Recovery during setup() + * + * If a saved state exists send 'M1000 S' to initiate job recovery. + */ +bool PrintJobRecovery::check() { + //if (!card.isMounted()) card.mount(); + bool success = false; + if (card.isMounted()) { + load(); + success = valid(); + if (!success) + cancel(); + else + queue.inject(F("M1000S")); + } + return success; +} + +/** + * Delete the recovery file and clear the recovery data + */ +void PrintJobRecovery::purge() { + init(); + card.removeJobRecoveryFile(); +} + +/** + * Load the recovery data, if it exists + */ +void PrintJobRecovery::load() { + if (exists()) { + open(true); + (void)file.read(&info, sizeof(info)); + close(); + } + debug(F("Load")); +} + +/** + * Set info fields that won't change + */ +void PrintJobRecovery::prepare() { + card.getAbsFilenameInCWD(info.sd_filename); // SD filename + cmd_sdpos = 0; +} + +/** + * Save the current machine state to the power-loss recovery file + */ +void PrintJobRecovery::save(const bool force/*=false*/, const float zraise/*=POWER_LOSS_ZRAISE*/, const bool raised/*=false*/) { + + // We don't check IS_SD_PRINTING here so a save may occur during a pause + + #if SAVE_INFO_INTERVAL_MS > 0 + static millis_t next_save_ms; // = 0 + millis_t ms = millis(); + #endif + + #ifndef POWER_LOSS_MIN_Z_CHANGE + #define POWER_LOSS_MIN_Z_CHANGE 0.05 // Vase-mode-friendly out of the box + #endif + + // Did Z change since the last call? + if (force + #if DISABLED(SAVE_EACH_CMD_MODE) // Always save state when enabled + #if SAVE_INFO_INTERVAL_MS > 0 // Save if interval is elapsed + || ELAPSED(ms, next_save_ms) + #endif + // Save if Z is above the last-saved position by some minimum height + || current_position.z > info.current_position.z + POWER_LOSS_MIN_Z_CHANGE + #endif + ) { + + #if SAVE_INFO_INTERVAL_MS > 0 + next_save_ms = ms + SAVE_INFO_INTERVAL_MS; + #endif + + // Set Head and Foot to matching non-zero values + if (!++info.valid_head) ++info.valid_head; // non-zero in sequence + //if (!IS_SD_PRINTING()) info.valid_head = 0; + info.valid_foot = info.valid_head; + + // Machine state + // info.sdpos and info.current_position are pre-filled from the Stepper ISR + + info.feedrate = uint16_t(MMS_TO_MMM(feedrate_mm_s)); + info.zraise = zraise; + info.flag.raised = raised; // Was Z raised before power-off? + + TERN_(GCODE_REPEAT_MARKERS, info.stored_repeat = repeat); + TERN_(HAS_HOME_OFFSET, info.home_offset = home_offset); + TERN_(HAS_POSITION_SHIFT, info.position_shift = position_shift); + E_TERN_(info.active_extruder = active_extruder); + + #if DISABLED(NO_VOLUMETRICS) + info.flag.volumetric_enabled = parser.volumetric_enabled; + #if HAS_MULTI_EXTRUDER + EXTRUDER_LOOP() info.filament_size[e] = planner.filament_size[e]; + #else + if (parser.volumetric_enabled) info.filament_size[0] = planner.filament_size[active_extruder]; + #endif + #endif + + #if HAS_EXTRUDERS + HOTEND_LOOP() info.target_temperature[e] = thermalManager.degTargetHotend(e); + #endif + + TERN_(HAS_HEATED_BED, info.target_temperature_bed = thermalManager.degTargetBed()); + + #if HAS_FAN + COPY(info.fan_speed, thermalManager.fan_speed); + #endif + + #if HAS_LEVELING + info.flag.leveling = planner.leveling_active; + info.fade = TERN0(ENABLE_LEVELING_FADE_HEIGHT, planner.z_fade_height); + #endif + + TERN_(GRADIENT_MIX, memcpy(&info.gradient, &mixer.gradient, sizeof(info.gradient))); + + #if ENABLED(FWRETRACT) + COPY(info.retract, fwretract.current_retract); + info.retract_hop = fwretract.current_hop; + #endif + + // Elapsed print job time + info.print_job_elapsed = print_job_timer.duration(); + + // Relative axis modes + info.axis_relative = gcode.axis_relative; + + // Misc. Marlin flags + info.flag.dryrun = !!(marlin_debug_flags & MARLIN_DEBUG_DRYRUN); + info.flag.allow_cold_extrusion = TERN0(PREVENT_COLD_EXTRUSION, thermalManager.allow_cold_extrude); + + write(); + } +} + +#if PIN_EXISTS(POWER_LOSS) + + #if ENABLED(BACKUP_POWER_SUPPLY) + + void PrintJobRecovery::retract_and_lift(const_float_t zraise) { + #if POWER_LOSS_RETRACT_LEN || POWER_LOSS_ZRAISE + + gcode.set_relative_mode(true); // Use relative coordinates + + #if POWER_LOSS_RETRACT_LEN + // Retract filament now + gcode.process_subcommands_now(F("G1 F3000 E-" STRINGIFY(POWER_LOSS_RETRACT_LEN))); + #endif + + #if POWER_LOSS_ZRAISE + // Raise the Z axis now + if (zraise) { + char cmd[20], str_1[16]; + sprintf_P(cmd, PSTR("G0Z%s"), dtostrf(zraise, 1, 3, str_1)); + gcode.process_subcommands_now(cmd); + } + #else + UNUSED(zraise); + #endif + + //gcode.axis_relative = info.axis_relative; + planner.synchronize(); + #endif + } + + #endif + +#endif // POWER_LOSS_PIN + +#if PIN_EXISTS(POWER_LOSS) || ENABLED(DEBUG_POWER_LOSS_RECOVERY) + + /** + * An outage was detected by a sensor pin. + * - If not SD printing, let the machine turn off on its own with no "KILL" screen + * - Disable all heaters first to save energy + * - Save the recovery data for the current instant + * - If backup power is available Retract E and Raise Z + * - Go to the KILL screen + */ + void PrintJobRecovery::_outage(TERN_(DEBUG_POWER_LOSS_RECOVERY, const bool simulated/*=false*/)) { + #if ENABLED(BACKUP_POWER_SUPPLY) + static bool lock = false; + if (lock) return; // No re-entrance from idle() during retract_and_lift() + lock = true; + #endif + + #if POWER_LOSS_ZRAISE + // Get the limited Z-raise to do now or on resume + const float zraise = _MAX(0, _MIN(current_position.z + POWER_LOSS_ZRAISE, Z_MAX_POS - 1) - current_position.z); + #else + constexpr float zraise = 0; + #endif + + // Save the current position, distance that Z was (or should be) raised, + // and a flag whether the raise was already done here. + if (IS_SD_PRINTING()) save(true, zraise, ENABLED(BACKUP_POWER_SUPPLY)); + + // Disable all heaters to reduce power loss + thermalManager.disable_all_heaters(); + + #if ENABLED(BACKUP_POWER_SUPPLY) + // Do a hard-stop of the steppers (with possibly a loud thud) + quickstop_stepper(); + // With backup power a retract and raise can be done now + retract_and_lift(zraise); + #endif + + if (TERN0(DEBUG_POWER_LOSS_RECOVERY, simulated)) { + card.fileHasFinished(); + current_position.reset(); + sync_plan_position(); + } + else + kill(GET_TEXT_F(MSG_OUTAGE_RECOVERY)); + } + +#endif // POWER_LOSS_PIN || DEBUG_POWER_LOSS_RECOVERY + +/** + * Save the recovery info the recovery file + */ +void PrintJobRecovery::write() { + + debug(F("Write")); + + open(false); + file.seekSet(0); + const int16_t ret = file.write(&info, sizeof(info)); + if (ret == -1) DEBUG_ECHOLNPGM("Power-loss file write failed."); + if (!file.close()) DEBUG_ECHOLNPGM("Power-loss file close failed."); +} + +/** + * Resume the saved print job + */ +void PrintJobRecovery::resume() { + + char cmd[MAX_CMD_SIZE+16], str_1[16], str_2[16]; + + const uint32_t resume_sdpos = info.sdpos; // Get here before the stepper ISR overwrites it + + // Apply the dry-run flag if enabled + if (info.flag.dryrun) marlin_debug_flags |= MARLIN_DEBUG_DRYRUN; + + // Restore cold extrusion permission + TERN_(PREVENT_COLD_EXTRUSION, thermalManager.allow_cold_extrude = info.flag.allow_cold_extrusion); + + #if HAS_LEVELING + // Make sure leveling is off before any G92 and G28 + gcode.process_subcommands_now(F("M420 S0 Z0")); + #endif + + #if HAS_HEATED_BED + const celsius_t bt = info.target_temperature_bed; + if (bt) { + // Restore the bed temperature + sprintf_P(cmd, PSTR("M190S%i"), bt); + gcode.process_subcommands_now(cmd); + } + #endif + + // Heat hotend enough to soften material + #if HAS_HOTEND + HOTEND_LOOP() { + const celsius_t et = _MAX(info.target_temperature[e], 180); + if (et) { + #if HAS_MULTI_HOTEND + sprintf_P(cmd, PSTR("T%iS"), e); + gcode.process_subcommands_now(cmd); + #endif + sprintf_P(cmd, PSTR("M109S%i"), et); + gcode.process_subcommands_now(cmd); + } + } + #endif + + // Interpret the saved Z according to flags + const float z_print = info.current_position.z, + z_raised = z_print + info.zraise; + + // + // Home the axes that can safely be homed, and + // establish the current position as best we can. + // + + gcode.process_subcommands_now(F("G92.9E0")); // Reset E to 0 + + #if Z_HOME_TO_MAX + + float z_now = z_raised; + + // If Z homing goes to max then just move back to the "raised" position + sprintf_P(cmd, PSTR( + "G28R0\n" // Home all axes (no raise) + "G1Z%sF1200" // Move Z down to (raised) height + ), dtostrf(z_now, 1, 3, str_1)); + gcode.process_subcommands_now(cmd); + + #elif DISABLED(BELTPRINTER) + + #if ENABLED(POWER_LOSS_RECOVER_ZHOME) && defined(POWER_LOSS_ZHOME_POS) + #define HOMING_Z_DOWN 1 + #endif + + float z_now = info.flag.raised ? z_raised : z_print; + + #if !HOMING_Z_DOWN + // Set Z to the real position + sprintf_P(cmd, PSTR("G92.9Z%s"), dtostrf(z_now, 1, 3, str_1)); + gcode.process_subcommands_now(cmd); + #endif + + // Does Z need to be raised now? It should be raised before homing XY. + if (z_raised > z_now) { + z_now = z_raised; + sprintf_P(cmd, PSTR("G1Z%sF600"), dtostrf(z_now, 1, 3, str_1)); + gcode.process_subcommands_now(cmd); + } + + // Home XY with no Z raise + gcode.process_subcommands_now(F("G28R0XY")); // No raise during G28 + + #endif + + #if HOMING_Z_DOWN + // Move to a safe XY position and home Z while avoiding the print. + const xy_pos_t p = xy_pos_t(POWER_LOSS_ZHOME_POS) TERN_(HOMING_Z_WITH_PROBE, - probe.offset_xy); + sprintf_P(cmd, PSTR("G1X%sY%sF1000\nG28HZ"), dtostrf(p.x, 1, 3, str_1), dtostrf(p.y, 1, 3, str_2)); + gcode.process_subcommands_now(cmd); + #endif + + // Mark all axes as having been homed (no effect on current_position) + set_all_homed(); + + #if HAS_LEVELING + // Restore Z fade and possibly re-enable bed leveling compensation. + // Leveling may already be enabled due to the ENABLE_LEVELING_AFTER_G28 option. + // TODO: Add a G28 parameter to leave leveling disabled. + sprintf_P(cmd, PSTR("M420S%cZ%s"), '0' + (char)info.flag.leveling, dtostrf(info.fade, 1, 1, str_1)); + gcode.process_subcommands_now(cmd); + + #if !HOMING_Z_DOWN + // The physical Z was adjusted at power-off so undo the M420S1 correction to Z with G92.9. + sprintf_P(cmd, PSTR("G92.9Z%s"), dtostrf(z_now, 1, 1, str_1)); + gcode.process_subcommands_now(cmd); + #endif + #endif + + #if ENABLED(POWER_LOSS_RECOVER_ZHOME) + // Z was homed down to the bed, so move up to the raised height. + z_now = z_raised; + sprintf_P(cmd, PSTR("G1Z%sF600"), dtostrf(z_now, 1, 3, str_1)); + gcode.process_subcommands_now(cmd); + #endif + + // Recover volumetric extrusion state + #if DISABLED(NO_VOLUMETRICS) + #if HAS_MULTI_EXTRUDER + EXTRUDER_LOOP() { + sprintf_P(cmd, PSTR("M200T%iD%s"), e, dtostrf(info.filament_size[e], 1, 3, str_1)); + gcode.process_subcommands_now(cmd); + } + if (!info.flag.volumetric_enabled) { + sprintf_P(cmd, PSTR("M200T%iD0"), info.active_extruder); + gcode.process_subcommands_now(cmd); + } + #else + if (info.flag.volumetric_enabled) { + sprintf_P(cmd, PSTR("M200D%s"), dtostrf(info.filament_size[0], 1, 3, str_1)); + gcode.process_subcommands_now(cmd); + } + #endif + #endif + + // Restore all hotend temperatures + #if HAS_HOTEND + HOTEND_LOOP() { + const celsius_t et = info.target_temperature[e]; + if (et) { + #if HAS_MULTI_HOTEND + sprintf_P(cmd, PSTR("T%iS"), e); + gcode.process_subcommands_now(cmd); + #endif + sprintf_P(cmd, PSTR("M109S%i"), et); + gcode.process_subcommands_now(cmd); + } + } + #endif + + // Restore the previously active tool (with no_move) + #if HAS_MULTI_EXTRUDER || HAS_MULTI_HOTEND + sprintf_P(cmd, PSTR("T%i S"), info.active_extruder); + gcode.process_subcommands_now(cmd); + #endif + + // Restore print cooling fan speeds + #if HAS_FAN + FANS_LOOP(i) { + const int f = info.fan_speed[i]; + if (f) { + sprintf_P(cmd, PSTR("M106P%iS%i"), i, f); + gcode.process_subcommands_now(cmd); + } + } + #endif + + // Restore retract and hop state from an active `G10` command + #if ENABLED(FWRETRACT) + EXTRUDER_LOOP() { + if (info.retract[e] != 0.0) { + fwretract.current_retract[e] = info.retract[e]; + fwretract.retracted.set(e); + } + } + fwretract.current_hop = info.retract_hop; + #endif + + #if ENABLED(GRADIENT_MIX) + memcpy(&mixer.gradient, &info.gradient, sizeof(info.gradient)); + #endif + + // Un-retract if there was a retract at outage + #if ENABLED(BACKUP_POWER_SUPPLY) && POWER_LOSS_RETRACT_LEN > 0 + gcode.process_subcommands_now(F("G1F3000E" STRINGIFY(POWER_LOSS_RETRACT_LEN))); + #endif + + // Additional purge on resume if configured + #if POWER_LOSS_PURGE_LEN + sprintf_P(cmd, PSTR("G1F3000E%d"), (POWER_LOSS_PURGE_LEN) + (POWER_LOSS_RETRACT_LEN)); + gcode.process_subcommands_now(cmd); + #endif + + #if ENABLED(NOZZLE_CLEAN_FEATURE) + gcode.process_subcommands_now(F("G12")); + #endif + + // Move back over to the saved XY + sprintf_P(cmd, PSTR("G1X%sY%sF3000"), + dtostrf(info.current_position.x, 1, 3, str_1), + dtostrf(info.current_position.y, 1, 3, str_2) + ); + gcode.process_subcommands_now(cmd); + + // Move back down to the saved Z for printing + sprintf_P(cmd, PSTR("G1Z%sF600"), dtostrf(z_print, 1, 3, str_1)); + gcode.process_subcommands_now(cmd); + + // Restore the feedrate + sprintf_P(cmd, PSTR("G1F%d"), info.feedrate); + gcode.process_subcommands_now(cmd); + + // Restore E position with G92.9 + sprintf_P(cmd, PSTR("G92.9E%s"), dtostrf(info.current_position.e, 1, 3, str_1)); + gcode.process_subcommands_now(cmd); + + TERN_(GCODE_REPEAT_MARKERS, repeat = info.stored_repeat); + TERN_(HAS_HOME_OFFSET, home_offset = info.home_offset); + TERN_(HAS_POSITION_SHIFT, position_shift = info.position_shift); + #if HAS_HOME_OFFSET || HAS_POSITION_SHIFT + LOOP_NUM_AXES(i) update_workspace_offset((AxisEnum)i); + #endif + + // Relative axis modes + gcode.axis_relative = info.axis_relative; + + #if ENABLED(DEBUG_POWER_LOSS_RECOVERY) + const uint8_t old_flags = marlin_debug_flags; + marlin_debug_flags |= MARLIN_DEBUG_ECHO; + #endif + + // Continue to apply PLR when a file is resumed! + enable(true); + + // Resume the SD file from the last position + char *fn = info.sd_filename; + sprintf_P(cmd, M23_STR, fn); + gcode.process_subcommands_now(cmd); + sprintf_P(cmd, PSTR("M24S%ldT%ld"), resume_sdpos, info.print_job_elapsed); + gcode.process_subcommands_now(cmd); + + TERN_(DEBUG_POWER_LOSS_RECOVERY, marlin_debug_flags = old_flags); +} + +#if ENABLED(DEBUG_POWER_LOSS_RECOVERY) + + void PrintJobRecovery::debug(FSTR_P const prefix) { + DEBUG_ECHOF(prefix); + DEBUG_ECHOLNPGM(" Job Recovery Info...\nvalid_head:", info.valid_head, " valid_foot:", info.valid_foot); + if (info.valid_head) { + if (info.valid_head == info.valid_foot) { + DEBUG_ECHOPGM("current_position: "); + LOOP_LOGICAL_AXES(i) { + if (i) DEBUG_CHAR(','); + DEBUG_DECIMAL(info.current_position[i]); + } + DEBUG_EOL(); + + DEBUG_ECHOLNPGM("feedrate: ", info.feedrate); + + DEBUG_ECHOLNPGM("zraise: ", info.zraise, " ", info.flag.raised ? "(before)" : ""); + + #if ENABLED(GCODE_REPEAT_MARKERS) + DEBUG_ECHOLNPGM("repeat index: ", info.stored_repeat.index); + LOOP_L_N(i, info.stored_repeat.index) + DEBUG_ECHOLNPGM("..... sdpos: ", info.stored_repeat.marker.sdpos, " count: ", info.stored_repeat.marker.counter); + #endif + + #if HAS_HOME_OFFSET + DEBUG_ECHOPGM("home_offset: "); + LOOP_NUM_AXES(i) { + if (i) DEBUG_CHAR(','); + DEBUG_DECIMAL(info.home_offset[i]); + } + DEBUG_EOL(); + #endif + + #if HAS_POSITION_SHIFT + DEBUG_ECHOPGM("position_shift: "); + LOOP_NUM_AXES(i) { + if (i) DEBUG_CHAR(','); + DEBUG_DECIMAL(info.position_shift[i]); + } + DEBUG_EOL(); + #endif + + #if HAS_MULTI_EXTRUDER + DEBUG_ECHOLNPGM("active_extruder: ", info.active_extruder); + #endif + + #if DISABLED(NO_VOLUMETRICS) + DEBUG_ECHOPGM("filament_size:"); + EXTRUDER_LOOP() DEBUG_ECHOLNPGM(" ", info.filament_size[e]); + DEBUG_EOL(); + #endif + + #if HAS_HOTEND + DEBUG_ECHOPGM("target_temperature: "); + HOTEND_LOOP() { + DEBUG_ECHO(info.target_temperature[e]); + if (e < HOTENDS - 1) DEBUG_CHAR(','); + } + DEBUG_EOL(); + #endif + + #if HAS_HEATED_BED + DEBUG_ECHOLNPGM("target_temperature_bed: ", info.target_temperature_bed); + #endif + + #if HAS_FAN + DEBUG_ECHOPGM("fan_speed: "); + FANS_LOOP(i) { + DEBUG_ECHO(info.fan_speed[i]); + if (i < FAN_COUNT - 1) DEBUG_CHAR(','); + } + DEBUG_EOL(); + #endif + + #if HAS_LEVELING + DEBUG_ECHOLNPGM("leveling: ", info.flag.leveling ? "ON" : "OFF", " fade: ", info.fade); + #endif + + #if ENABLED(FWRETRACT) + DEBUG_ECHOPGM("retract: "); + EXTRUDER_LOOP() { + DEBUG_ECHO(info.retract[e]); + if (e < EXTRUDERS - 1) DEBUG_CHAR(','); + } + DEBUG_EOL(); + DEBUG_ECHOLNPGM("retract_hop: ", info.retract_hop); + #endif + + // Mixing extruder and gradient + #if BOTH(MIXING_EXTRUDER, GRADIENT_MIX) + DEBUG_ECHOLNPGM("gradient: ", info.gradient.enabled ? "ON" : "OFF"); + #endif + + DEBUG_ECHOLNPGM("sd_filename: ", info.sd_filename); + DEBUG_ECHOLNPGM("sdpos: ", info.sdpos); + DEBUG_ECHOLNPGM("print_job_elapsed: ", info.print_job_elapsed); + + DEBUG_ECHOPGM("axis_relative:"); + if (TEST(info.axis_relative, REL_X)) DEBUG_ECHOPGM(" REL_X"); + if (TEST(info.axis_relative, REL_Y)) DEBUG_ECHOPGM(" REL_Y"); + if (TEST(info.axis_relative, REL_Z)) DEBUG_ECHOPGM(" REL_Z"); + if (TEST(info.axis_relative, REL_E)) DEBUG_ECHOPGM(" REL_E"); + if (TEST(info.axis_relative, E_MODE_ABS)) DEBUG_ECHOPGM(" E_MODE_ABS"); + if (TEST(info.axis_relative, E_MODE_REL)) DEBUG_ECHOPGM(" E_MODE_REL"); + DEBUG_EOL(); + + DEBUG_ECHOLNPGM("flag.dryrun: ", AS_DIGIT(info.flag.dryrun)); + DEBUG_ECHOLNPGM("flag.allow_cold_extrusion: ", AS_DIGIT(info.flag.allow_cold_extrusion)); + DEBUG_ECHOLNPGM("flag.volumetric_enabled: ", AS_DIGIT(info.flag.volumetric_enabled)); + } + else + DEBUG_ECHOLNPGM("INVALID DATA"); + } + DEBUG_ECHOLNPGM("---"); + } + +#endif // DEBUG_POWER_LOSS_RECOVERY + +#endif // POWER_LOSS_RECOVERY diff --git a/src/feature/powerloss.h b/src/feature/powerloss.h new file mode 100644 index 0000000..33d9dc0 --- /dev/null +++ b/src/feature/powerloss.h @@ -0,0 +1,225 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * feature/powerloss.h - Resume an SD print after power-loss + */ + +#include "../sd/cardreader.h" +#include "../gcode/gcode.h" + +#include "../inc/MarlinConfig.h" + +#if ENABLED(GCODE_REPEAT_MARKERS) + #include "../feature/repeat.h" +#endif + +#if ENABLED(MIXING_EXTRUDER) + #include "../feature/mixing.h" +#endif + +#if !defined(POWER_LOSS_STATE) && PIN_EXISTS(POWER_LOSS) + #define POWER_LOSS_STATE HIGH +#endif + +#ifndef POWER_LOSS_ZRAISE + #define POWER_LOSS_ZRAISE 2 +#endif + +//#define DEBUG_POWER_LOSS_RECOVERY +//#define SAVE_EACH_CMD_MODE +//#define SAVE_INFO_INTERVAL_MS 0 + +typedef struct { + uint8_t valid_head; + + // Machine state + xyze_pos_t current_position; + uint16_t feedrate; + + float zraise; + + // Repeat information + #if ENABLED(GCODE_REPEAT_MARKERS) + Repeat stored_repeat; + #endif + + #if HAS_HOME_OFFSET + xyz_pos_t home_offset; + #endif + #if HAS_POSITION_SHIFT + xyz_pos_t position_shift; + #endif + #if HAS_MULTI_EXTRUDER + uint8_t active_extruder; + #endif + + #if DISABLED(NO_VOLUMETRICS) + float filament_size[EXTRUDERS]; + #endif + + #if HAS_HOTEND + celsius_t target_temperature[HOTENDS]; + #endif + #if HAS_HEATED_BED + celsius_t target_temperature_bed; + #endif + #if HAS_FAN + uint8_t fan_speed[FAN_COUNT]; + #endif + + #if HAS_LEVELING + float fade; + #endif + + #if ENABLED(FWRETRACT) + float retract[EXTRUDERS], retract_hop; + #endif + + // Mixing extruder and gradient + #if ENABLED(MIXING_EXTRUDER) + //uint_fast8_t selected_vtool; + //mixer_comp_t color[NR_MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS]; + #if ENABLED(GRADIENT_MIX) + gradient_t gradient; + #endif + #endif + + // SD Filename and position + char sd_filename[MAXPATHNAMELENGTH]; + volatile uint32_t sdpos; + + // Job elapsed time + millis_t print_job_elapsed; + + // Relative axis modes + uint8_t axis_relative; + + // Misc. Marlin flags + struct { + bool raised:1; // Raised before saved + bool dryrun:1; // M111 S8 + bool allow_cold_extrusion:1; // M302 P1 + #if HAS_LEVELING + bool leveling:1; // M420 S + #endif + #if DISABLED(NO_VOLUMETRICS) + bool volumetric_enabled:1; // M200 S D + #endif + } flag; + + uint8_t valid_foot; + + bool valid() { return valid_head && valid_head == valid_foot; } + +} job_recovery_info_t; + +class PrintJobRecovery { + public: + static const char filename[5]; + + static SdFile file; + static job_recovery_info_t info; + + static uint8_t queue_index_r; //!< Queue index of the active command + static uint32_t cmd_sdpos, //!< SD position of the next command + sdpos[BUFSIZE]; //!< SD positions of queued commands + + #if HAS_DWIN_E3V2_BASIC + static bool dwin_flag; + #endif + + static void init(); + static void prepare(); + + static void setup() { + #if PIN_EXISTS(POWER_LOSS) + #if ENABLED(POWER_LOSS_PULLUP) + SET_INPUT_PULLUP(POWER_LOSS_PIN); + #elif ENABLED(POWER_LOSS_PULLDOWN) + SET_INPUT_PULLDOWN(POWER_LOSS_PIN); + #else + SET_INPUT(POWER_LOSS_PIN); + #endif + #endif + } + + // Track each command's file offsets + static uint32_t command_sdpos() { return sdpos[queue_index_r]; } + static void commit_sdpos(const uint8_t index_w) { sdpos[index_w] = cmd_sdpos; } + + static bool enabled; + static void enable(const bool onoff); + static void changed(); + + static bool exists() { return card.jobRecoverFileExists(); } + static void open(const bool read) { card.openJobRecoveryFile(read); } + static void close() { file.close(); } + + static bool check(); + static void resume(); + static void purge(); + + static void cancel() { purge(); } + + static void load(); + static void save(const bool force=ENABLED(SAVE_EACH_CMD_MODE), const float zraise=POWER_LOSS_ZRAISE, const bool raised=false); + + #if PIN_EXISTS(POWER_LOSS) + static void outage() { + static constexpr uint8_t OUTAGE_THRESHOLD = 3; + static uint8_t outage_counter = 0; + if (enabled && READ(POWER_LOSS_PIN) == POWER_LOSS_STATE) { + outage_counter++; + if (outage_counter >= OUTAGE_THRESHOLD) _outage(); + } + else + outage_counter = 0; + } + #endif + + // The referenced file exists + static bool interrupted_file_exists() { return card.fileExists(info.sd_filename); } + + static bool valid() { return info.valid() && interrupted_file_exists(); } + + #if ENABLED(DEBUG_POWER_LOSS_RECOVERY) + static void debug(FSTR_P const prefix); + #else + static void debug(FSTR_P const) {} + #endif + + private: + static void write(); + + #if ENABLED(BACKUP_POWER_SUPPLY) + static void retract_and_lift(const_float_t zraise); + #endif + + #if PIN_EXISTS(POWER_LOSS) || ENABLED(DEBUG_POWER_LOSS_RECOVERY) + friend class GcodeSuite; + static void _outage(TERN_(DEBUG_POWER_LOSS_RECOVERY, const bool simulated=false)); + #endif +}; + +extern PrintJobRecovery recovery; diff --git a/src/feature/probe_temp_comp.cpp b/src/feature/probe_temp_comp.cpp new file mode 100644 index 0000000..b5f636e --- /dev/null +++ b/src/feature/probe_temp_comp.cpp @@ -0,0 +1,257 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfigPre.h" + +#if HAS_PTC + +//#define DEBUG_PTC // Print extra debug output with 'M871' + +#include "probe_temp_comp.h" +#include +#include "../module/temperature.h" + +ProbeTempComp ptc; + +#if ENABLED(PTC_PROBE) + constexpr int16_t z_offsets_probe_default[PTC_PROBE_COUNT] = PTC_PROBE_ZOFFS; + int16_t ProbeTempComp::z_offsets_probe[PTC_PROBE_COUNT] = PTC_PROBE_ZOFFS; +#endif + +#if ENABLED(PTC_BED) + constexpr int16_t z_offsets_bed_default[PTC_BED_COUNT] = PTC_BED_ZOFFS; + int16_t ProbeTempComp::z_offsets_bed[PTC_BED_COUNT] = PTC_BED_ZOFFS; +#endif + +#if ENABLED(PTC_HOTEND) + constexpr int16_t z_offsets_hotend_default[PTC_HOTEND_COUNT] = PTC_HOTEND_ZOFFS; + int16_t ProbeTempComp::z_offsets_hotend[PTC_HOTEND_COUNT] = PTC_HOTEND_ZOFFS; +#endif + +int16_t *ProbeTempComp::sensor_z_offsets[TSI_COUNT] = { + #if ENABLED(PTC_PROBE) + ProbeTempComp::z_offsets_probe, + #endif + #if ENABLED(PTC_BED) + ProbeTempComp::z_offsets_bed, + #endif + #if ENABLED(PTC_HOTEND) + ProbeTempComp::z_offsets_hotend, + #endif +}; + +constexpr temp_calib_t ProbeTempComp::cali_info[TSI_COUNT]; + +uint8_t ProbeTempComp::calib_idx; // = 0 +float ProbeTempComp::init_measurement; // = 0.0 +bool ProbeTempComp::enabled = true; + +void ProbeTempComp::reset() { + TERN_(PTC_PROBE, LOOP_L_N(i, PTC_PROBE_COUNT) z_offsets_probe[i] = z_offsets_probe_default[i]); + TERN_(PTC_BED, LOOP_L_N(i, PTC_BED_COUNT) z_offsets_bed[i] = z_offsets_bed_default[i]); + TERN_(PTC_HOTEND, LOOP_L_N(i, PTC_HOTEND_COUNT) z_offsets_hotend[i] = z_offsets_hotend_default[i]); +} + +void ProbeTempComp::clear_offsets(const TempSensorID tsi) { + LOOP_L_N(i, cali_info[tsi].measurements) + sensor_z_offsets[tsi][i] = 0; + calib_idx = 0; +} + +bool ProbeTempComp::set_offset(const TempSensorID tsi, const uint8_t idx, const int16_t offset) { + if (idx >= cali_info[tsi].measurements) return false; + sensor_z_offsets[tsi][idx] = offset; + return true; +} + +void ProbeTempComp::print_offsets() { + LOOP_L_N(s, TSI_COUNT) { + celsius_t temp = cali_info[s].start_temp; + for (int16_t i = -1; i < cali_info[s].measurements; ++i) { + SERIAL_ECHOF( + TERN_(PTC_BED, s == TSI_BED ? F("Bed") :) + TERN_(PTC_HOTEND, s == TSI_EXT ? F("Extruder") :) + F("Probe") + ); + SERIAL_ECHOLNPGM( + " temp: ", temp, + "C; Offset: ", i < 0 ? 0.0f : sensor_z_offsets[s][i], " um" + ); + temp += cali_info[s].temp_resolution; + } + } + #if ENABLED(DEBUG_PTC) + float meas[4] = { 0, 0, 0, 0 }; + compensate_measurement(TSI_PROBE, 27.5, meas[0]); + compensate_measurement(TSI_PROBE, 32.5, meas[1]); + compensate_measurement(TSI_PROBE, 77.5, meas[2]); + compensate_measurement(TSI_PROBE, 82.5, meas[3]); + SERIAL_ECHOLNPGM("DEBUG_PTC 27.5:", meas[0], " 32.5:", meas[1], " 77.5:", meas[2], " 82.5:", meas[3]); + #endif +} + +void ProbeTempComp::prepare_new_calibration(const_float_t init_meas_z) { + calib_idx = 0; + init_measurement = init_meas_z; +} + +void ProbeTempComp::push_back_new_measurement(const TempSensorID tsi, const_float_t meas_z) { + if (calib_idx >= cali_info[tsi].measurements) return; + sensor_z_offsets[tsi][calib_idx++] = static_cast((meas_z - init_measurement) * 1000.0f); +} + +bool ProbeTempComp::finish_calibration(const TempSensorID tsi) { + if (!calib_idx) { + SERIAL_ECHOLNPGM("!No measurements."); + clear_offsets(tsi); + return false; + } + + const uint8_t measurements = cali_info[tsi].measurements; + const celsius_t start_temp = cali_info[tsi].start_temp, + res_temp = cali_info[tsi].temp_resolution; + int16_t * const data = sensor_z_offsets[tsi]; + + // Extrapolate + float k, d; + if (calib_idx < measurements) { + SERIAL_ECHOLNPGM("Got ", calib_idx, " measurements. "); + if (linear_regression(tsi, k, d)) { + SERIAL_ECHOPGM("Applying linear extrapolation"); + for (; calib_idx < measurements; ++calib_idx) { + const celsius_float_t temp = start_temp + float(calib_idx + 1) * res_temp; + data[calib_idx] = static_cast(k * temp + d); + } + } + else { + // Simply use the last measured value for higher temperatures + SERIAL_ECHOPGM("Failed to extrapolate"); + const int16_t last_val = data[calib_idx-1]; + for (; calib_idx < measurements; ++calib_idx) + data[calib_idx] = last_val; + } + SERIAL_ECHOLNPGM(" for higher temperatures."); + } + + // Sanity check + for (calib_idx = 0; calib_idx < measurements; ++calib_idx) { + // Restrict the max. offset + if (ABS(data[calib_idx]) > 2000) { + SERIAL_ECHOLNPGM("!Invalid Z-offset detected (0-2)."); + clear_offsets(tsi); + return false; + } + // Restrict the max. offset difference between two probings + if (calib_idx > 0 && ABS(data[calib_idx - 1] - data[calib_idx]) > 800) { + SERIAL_ECHOLNPGM("!Invalid Z-offset between two probings detected (0-0.8)."); + clear_offsets(tsi); + return false; + } + } + + return true; +} + +void ProbeTempComp::apply_compensation(float &meas_z) { + if (!enabled) return; + TERN_(PTC_BED, compensate_measurement(TSI_BED, thermalManager.degBed(), meas_z)); + TERN_(PTC_PROBE, compensate_measurement(TSI_PROBE, thermalManager.degProbe(), meas_z)); + TERN_(PTC_HOTEND, compensate_measurement(TSI_EXT, thermalManager.degHotend(0), meas_z)); +} + +void ProbeTempComp::compensate_measurement(const TempSensorID tsi, const celsius_t temp, float &meas_z) { + const uint8_t measurements = cali_info[tsi].measurements; + const celsius_t start_temp = cali_info[tsi].start_temp, + res_temp = cali_info[tsi].temp_resolution, + end_temp = start_temp + measurements * res_temp; + const int16_t * const data = sensor_z_offsets[tsi]; + + // Given a data index, return { celsius, zoffset } in the form { x, y } + auto tpoint = [&](uint8_t i) -> xy_float_t { + return xy_float_t({ static_cast(start_temp) + i * res_temp, i ? static_cast(data[i - 1]) : 0.0f }); + }; + + // Interpolate Z based on a temperature being within a given range + auto linear_interp = [](const_float_t x, xy_float_t p1, xy_float_t p2) { + // zoffs1 + zoffset_per_toffset * toffset + return p1.y + (p2.y - p1.y) / (p2.x - p1.x) * (x - p1.x); + }; + + // offset in µm + float offset = 0.0f; + + #if PTC_LINEAR_EXTRAPOLATION + if (temp < start_temp) + offset = linear_interp(temp, tpoint(0), tpoint(PTC_LINEAR_EXTRAPOLATION)); + else if (temp >= end_temp) + offset = linear_interp(temp, tpoint(measurements - PTC_LINEAR_EXTRAPOLATION), tpoint(measurements)); + #else + if (temp < start_temp) + offset = 0.0f; + else if (temp >= end_temp) + offset = static_cast(data[measurements - 1]); + #endif + else { + // Linear interpolation + const int8_t idx = static_cast((temp - start_temp) / res_temp); + offset = linear_interp(temp, tpoint(idx), tpoint(idx + 1)); + } + + // convert offset to mm and apply it + meas_z -= offset / 1000.0f; +} + +bool ProbeTempComp::linear_regression(const TempSensorID tsi, float &k, float &d) { + if (!WITHIN(calib_idx, 1, cali_info[tsi].measurements)) return false; + + const celsius_t start_temp = cali_info[tsi].start_temp, + res_temp = cali_info[tsi].temp_resolution; + const int16_t * const data = sensor_z_offsets[tsi]; + + float sum_x = start_temp, + sum_x2 = sq(start_temp), + sum_xy = 0, sum_y = 0; + + float xi = static_cast(start_temp); + LOOP_L_N(i, calib_idx) { + const float yi = static_cast(data[i]); + xi += res_temp; + sum_x += xi; + sum_x2 += sq(xi); + sum_xy += xi * yi; + sum_y += yi; + } + + const float denom = static_cast(calib_idx + 1) * sum_x2 - sq(sum_x); + if (fabs(denom) <= 10e-5) { + // Singularity - unable to solve + k = d = 0.0; + return false; + } + + k = (static_cast(calib_idx + 1) * sum_xy - sum_x * sum_y) / denom; + d = (sum_y - k * sum_x) / static_cast(calib_idx + 1); + + return true; +} + +#endif // HAS_PTC diff --git a/src/feature/probe_temp_comp.h b/src/feature/probe_temp_comp.h new file mode 100644 index 0000000..42348db --- /dev/null +++ b/src/feature/probe_temp_comp.h @@ -0,0 +1,116 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" + +enum TempSensorID : uint8_t { + #if ENABLED(PTC_PROBE) + TSI_PROBE, + #endif + #if ENABLED(PTC_BED) + TSI_BED, + #endif + #if ENABLED(PTC_HOTEND) + TSI_EXT, + #endif + TSI_COUNT +}; + +typedef struct { + uint8_t measurements; // Max. number of measurements to be stored (35 - 80°C) + celsius_t temp_resolution, // Resolution in °C between measurements + start_temp; // Base measurement; z-offset == 0 +} temp_calib_t; + +/** + * Probe temperature compensation implementation. + * Z-probes like the P.I.N.D.A V2 allow for compensation of + * measurement errors/shifts due to changed temperature. + */ + +class ProbeTempComp { + public: + + static constexpr temp_calib_t cali_info[TSI_COUNT] = { + #if ENABLED(PTC_PROBE) + { PTC_PROBE_COUNT, PTC_PROBE_RES, PTC_PROBE_START }, // Probe + #endif + #if ENABLED(PTC_BED) + { PTC_BED_COUNT, PTC_BED_RES, PTC_BED_START }, // Bed + #endif + #if ENABLED(PTC_HOTEND) + { PTC_HOTEND_COUNT, PTC_HOTEND_RES, PTC_HOTEND_START }, // Extruder + #endif + }; + + static int16_t *sensor_z_offsets[TSI_COUNT]; + #if ENABLED(PTC_PROBE) + static int16_t z_offsets_probe[PTC_PROBE_COUNT]; // (µm) + #endif + #if ENABLED(PTC_BED) + static int16_t z_offsets_bed[PTC_BED_COUNT]; // (µm) + #endif + #if ENABLED(PTC_HOTEND) + static int16_t z_offsets_hotend[PTC_HOTEND_COUNT]; // (µm) + #endif + + static void reset_index() { calib_idx = 0; }; + static uint8_t get_index() { return calib_idx; } + static void reset(); + static void clear_all_offsets() { + TERN_(PTC_PROBE, clear_offsets(TSI_PROBE)); + TERN_(PTC_BED, clear_offsets(TSI_BED)); + TERN_(PTC_HOTEND, clear_offsets(TSI_EXT)); + } + static bool set_offset(const TempSensorID tsi, const uint8_t idx, const int16_t offset); + static void print_offsets(); + static void prepare_new_calibration(const_float_t init_meas_z); + static void push_back_new_measurement(const TempSensorID tsi, const_float_t meas_z); + static bool finish_calibration(const TempSensorID tsi); + static void set_enabled(const bool ena) { enabled = ena; } + + // Apply all temperature compensation adjustments + static void apply_compensation(float &meas_z); + + private: + static uint8_t calib_idx; + static bool enabled; + + static void clear_offsets(const TempSensorID tsi); + + /** + * Base value. Temperature compensation values will be deltas + * to this value, set at first probe. + */ + static float init_measurement; + + /** + * Fit a linear function in measured temperature offsets + * to allow generating values of higher temperatures. + */ + static bool linear_regression(const TempSensorID tsi, float &k, float &d); + + static void compensate_measurement(const TempSensorID tsi, const celsius_t temp, float &meas_z); +}; + +extern ProbeTempComp ptc; diff --git a/src/feature/repeat.cpp b/src/feature/repeat.cpp new file mode 100644 index 0000000..165f71f --- /dev/null +++ b/src/feature/repeat.cpp @@ -0,0 +1,82 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(GCODE_REPEAT_MARKERS) + +//#define DEBUG_GCODE_REPEAT_MARKERS + +#include "repeat.h" + +#include "../gcode/gcode.h" +#include "../sd/cardreader.h" + +#define DEBUG_OUT ENABLED(DEBUG_GCODE_REPEAT_MARKERS) +#include "../core/debug_out.h" + +repeat_marker_t Repeat::marker[MAX_REPEAT_NESTING]; +uint8_t Repeat::index; + +void Repeat::add_marker(const uint32_t sdpos, const uint16_t count) { + if (index >= MAX_REPEAT_NESTING) + SERIAL_ECHO_MSG("!Too many markers."); + else { + marker[index].sdpos = sdpos; + marker[index].counter = count ?: -1; + index++; + DEBUG_ECHOLNPGM("Add Marker ", index, " at ", sdpos, " (", count, ")"); + } +} + +void Repeat::loop() { + if (!index) // No marker? + SERIAL_ECHO_MSG("!No marker set."); // Inform the user. + else { + const uint8_t ind = index - 1; // Active marker's index + if (!marker[ind].counter) { // Did its counter run out? + DEBUG_ECHOLNPGM("Pass Marker ", index); + index--; // Carry on. Previous marker on the next 'M808'. + } + else { + card.setIndex(marker[ind].sdpos); // Loop back to the marker. + if (marker[ind].counter > 0) // Ignore a negative (or zero) counter. + --marker[ind].counter; // Decrement the counter. If zero this 'M808' will be skipped next time. + DEBUG_ECHOLNPGM("Goto Marker ", index, " at ", marker[ind].sdpos, " (", marker[ind].counter, ")"); + } + } +} + +void Repeat::cancel() { LOOP_L_N(i, index) marker[i].counter = 0; } + +void Repeat::early_parse_M808(char * const cmd) { + if (is_command_M808(cmd)) { + DEBUG_ECHOLNPGM("Parsing \"", cmd, "\""); + parser.parse(cmd); + if (parser.seen('L')) + add_marker(card.getIndex(), parser.value_ushort()); + else + Repeat::loop(); + } +} + +#endif // GCODE_REPEAT_MARKERS diff --git a/src/feature/repeat.h b/src/feature/repeat.h new file mode 100644 index 0000000..fc11e4a --- /dev/null +++ b/src/feature/repeat.h @@ -0,0 +1,53 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfigPre.h" +#include "../gcode/parser.h" + +#include + +#define MAX_REPEAT_NESTING 10 + +typedef struct { + uint32_t sdpos; // The repeat file position + int16_t counter; // The counter for looping +} repeat_marker_t; + +class Repeat { +private: + static repeat_marker_t marker[MAX_REPEAT_NESTING]; + static uint8_t index; +public: + static void reset() { index = 0; } + static bool is_active() { + LOOP_L_N(i, index) if (marker[i].counter) return true; + return false; + } + static bool is_command_M808(char * const cmd) { return cmd[0] == 'M' && cmd[1] == '8' && cmd[2] == '0' && cmd[3] == '8' && !NUMERIC(cmd[4]); } + static void early_parse_M808(char * const cmd); + static void add_marker(const uint32_t sdpos, const uint16_t count); + static void loop(); + static void cancel(); +}; + +extern Repeat repeat; diff --git a/src/feature/runout.cpp b/src/feature/runout.cpp new file mode 100644 index 0000000..98b6bd0 --- /dev/null +++ b/src/feature/runout.cpp @@ -0,0 +1,147 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * feature/runout.cpp - Runout sensor support + */ + +#include "../inc/MarlinConfigPre.h" + +#if HAS_FILAMENT_SENSOR + +#include "runout.h" + +FilamentMonitor runout; + +bool FilamentMonitorBase::enabled = true, + FilamentMonitorBase::filament_ran_out; // = false + +#if ENABLED(HOST_ACTION_COMMANDS) + bool FilamentMonitorBase::host_handling; // = false +#endif + +#if ENABLED(TOOLCHANGE_MIGRATION_FEATURE) + #include "../module/tool_change.h" + #define DEBUG_OUT ENABLED(DEBUG_TOOLCHANGE_MIGRATION_FEATURE) + #include "../core/debug_out.h" +#endif + +#if HAS_FILAMENT_RUNOUT_DISTANCE + float RunoutResponseDelayed::runout_distance_mm = FILAMENT_RUNOUT_DISTANCE_MM; + volatile float RunoutResponseDelayed::runout_mm_countdown[NUM_RUNOUT_SENSORS]; + #if ENABLED(FILAMENT_MOTION_SENSOR) + uint8_t FilamentSensorEncoder::motion_detected; + #endif +#else + int8_t RunoutResponseDebounced::runout_count[NUM_RUNOUT_SENSORS]; // = 0 +#endif + +// +// Filament Runout event handler +// +#include "../MarlinCore.h" +#include "../feature/pause.h" +#include "../gcode/queue.h" + +#if ENABLED(HOST_ACTION_COMMANDS) + #include "host_actions.h" +#endif + +#if ENABLED(EXTENSIBLE_UI) + #include "../lcd/extui/ui_api.h" +#elif ENABLED(DWIN_LCD_PROUI) + #include "../lcd/e3v2/proui/dwin.h" +#endif + +void event_filament_runout(const uint8_t extruder) { + + if (did_pause_print) return; // Action already in progress. Purge triggered repeated runout. + + #if ENABLED(TOOLCHANGE_MIGRATION_FEATURE) + if (migration.in_progress) { + DEBUG_ECHOLNPGM("Migration Already In Progress"); + return; // Action already in progress. Purge triggered repeated runout. + } + if (migration.automode) { + DEBUG_ECHOLNPGM("Migration Starting"); + if (extruder_migration()) return; + } + #endif + + TERN_(EXTENSIBLE_UI, ExtUI::onFilamentRunout(ExtUI::getTool(extruder))); + TERN_(DWIN_LCD_PROUI, DWIN_FilamentRunout(extruder)); + + #if ANY(HOST_PROMPT_SUPPORT, HOST_ACTION_COMMANDS, MULTI_FILAMENT_SENSOR) + const char tool = '0' + TERN0(MULTI_FILAMENT_SENSOR, extruder); + #endif + + //action:out_of_filament + #if ENABLED(HOST_PROMPT_SUPPORT) + hostui.prompt_do(PROMPT_FILAMENT_RUNOUT, F("FilamentRunout T"), tool); //action:out_of_filament + #endif + + const bool run_runout_script = !runout.host_handling; + + #if ENABLED(HOST_ACTION_COMMANDS) + if (run_runout_script + && ( strstr(FILAMENT_RUNOUT_SCRIPT, "M600") + || strstr(FILAMENT_RUNOUT_SCRIPT, "M125") + || TERN0(ADVANCED_PAUSE_FEATURE, strstr(FILAMENT_RUNOUT_SCRIPT, "M25")) + ) + ) { + hostui.paused(false); + } + else { + // Legacy Repetier command for use until newer version supports standard dialog + // To be removed later when pause command also triggers dialog + #ifdef ACTION_ON_FILAMENT_RUNOUT + hostui.action(F(ACTION_ON_FILAMENT_RUNOUT " T"), false); + SERIAL_CHAR(tool); + SERIAL_EOL(); + #endif + + hostui.pause(false); + } + SERIAL_ECHOPGM(" " ACTION_REASON_ON_FILAMENT_RUNOUT " "); + SERIAL_CHAR(tool); + SERIAL_EOL(); + #endif // HOST_ACTION_COMMANDS + + if (run_runout_script) { + #if MULTI_FILAMENT_SENSOR + char script[strlen(FILAMENT_RUNOUT_SCRIPT) + 1]; + sprintf_P(script, PSTR(FILAMENT_RUNOUT_SCRIPT), tool); + #if ENABLED(FILAMENT_RUNOUT_SENSOR_DEBUG) + SERIAL_ECHOLNPGM("Runout Command: ", script); + #endif + queue.inject(script); + #else + #if ENABLED(FILAMENT_RUNOUT_SENSOR_DEBUG) + SERIAL_ECHOPGM("Runout Command: "); + SERIAL_ECHOLNPGM(FILAMENT_RUNOUT_SCRIPT); + #endif + queue.inject(F(FILAMENT_RUNOUT_SCRIPT)); + #endif + } +} + +#endif // HAS_FILAMENT_SENSOR diff --git a/src/feature/runout.h b/src/feature/runout.h new file mode 100644 index 0000000..e74d857 --- /dev/null +++ b/src/feature/runout.h @@ -0,0 +1,413 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * feature/runout.h - Runout sensor support + */ + +#include "../sd/cardreader.h" +#include "../module/printcounter.h" +#include "../module/planner.h" +#include "../module/stepper.h" // for block_t +#include "../gcode/queue.h" +#include "../feature/pause.h" + +#include "../inc/MarlinConfig.h" + +#if ENABLED(EXTENSIBLE_UI) + #include "../lcd/extui/ui_api.h" +#endif + +//#define FILAMENT_RUNOUT_SENSOR_DEBUG +#ifndef FILAMENT_RUNOUT_THRESHOLD + #define FILAMENT_RUNOUT_THRESHOLD 5 +#endif + +void event_filament_runout(const uint8_t extruder); + +template +class TFilamentMonitor; +class FilamentSensorEncoder; +class FilamentSensorSwitch; +class RunoutResponseDelayed; +class RunoutResponseDebounced; + +/********************************* TEMPLATE SPECIALIZATION *********************************/ + +typedef TFilamentMonitor< + TERN(HAS_FILAMENT_RUNOUT_DISTANCE, RunoutResponseDelayed, RunoutResponseDebounced), + TERN(FILAMENT_MOTION_SENSOR, FilamentSensorEncoder, FilamentSensorSwitch) + > FilamentMonitor; + +extern FilamentMonitor runout; + +/*******************************************************************************************/ + +class FilamentMonitorBase { + public: + static bool enabled, filament_ran_out; + + #if ENABLED(HOST_ACTION_COMMANDS) + static bool host_handling; + #else + static constexpr bool host_handling = false; + #endif +}; + +template +class TFilamentMonitor : public FilamentMonitorBase { + private: + typedef RESPONSE_T response_t; + typedef SENSOR_T sensor_t; + static response_t response; + static sensor_t sensor; + + public: + static void setup() { + sensor.setup(); + reset(); + } + + static void reset() { + filament_ran_out = false; + response.reset(); + } + + // Call this method when filament is present, + // so the response can reset its counter. + static void filament_present(const uint8_t extruder) { + response.filament_present(extruder); + } + + #if HAS_FILAMENT_RUNOUT_DISTANCE + static float& runout_distance() { return response.runout_distance_mm; } + static void set_runout_distance(const_float_t mm) { response.runout_distance_mm = mm; } + #endif + + // Handle a block completion. RunoutResponseDelayed uses this to + // add up the length of filament moved while the filament is out. + static void block_completed(const block_t * const b) { + if (enabled) { + response.block_completed(b); + sensor.block_completed(b); + } + } + + // Give the response a chance to update its counter. + static void run() { + if (enabled && !filament_ran_out && (printingIsActive() || did_pause_print)) { + TERN_(HAS_FILAMENT_RUNOUT_DISTANCE, cli()); // Prevent RunoutResponseDelayed::block_completed from accumulating here + response.run(); + sensor.run(); + const uint8_t runout_flags = response.has_run_out(); + TERN_(HAS_FILAMENT_RUNOUT_DISTANCE, sei()); + #if MULTI_FILAMENT_SENSOR + #if ENABLED(WATCH_ALL_RUNOUT_SENSORS) + const bool ran_out = !!runout_flags; // any sensor triggers + uint8_t extruder = 0; + if (ran_out) { + uint8_t bitmask = runout_flags; + while (!(bitmask & 1)) { + bitmask >>= 1; + extruder++; + } + } + #else + const bool ran_out = TEST(runout_flags, active_extruder); // suppress non active extruders + uint8_t extruder = active_extruder; + #endif + #else + const bool ran_out = !!runout_flags; + uint8_t extruder = active_extruder; + #endif + + #if ENABLED(FILAMENT_RUNOUT_SENSOR_DEBUG) + if (runout_flags) { + SERIAL_ECHOPGM("Runout Sensors: "); + LOOP_L_N(i, 8) SERIAL_ECHO('0' + TEST(runout_flags, i)); + SERIAL_ECHOPGM(" -> ", extruder); + if (ran_out) SERIAL_ECHOPGM(" RUN OUT"); + SERIAL_EOL(); + } + #endif + + if (ran_out) { + filament_ran_out = true; + event_filament_runout(extruder); + planner.synchronize(); + } + } + } +}; + +/*************************** FILAMENT PRESENCE SENSORS ***************************/ + +class FilamentSensorBase { + protected: + /** + * Called by FilamentSensorSwitch::run when filament is detected. + * Called by FilamentSensorEncoder::block_completed when motion is detected. + */ + static void filament_present(const uint8_t extruder) { + runout.filament_present(extruder); // ...which calls response.filament_present(extruder) + } + + public: + static void setup() { + #define _INIT_RUNOUT_PIN(P,S,U,D) do{ if (ENABLED(U)) SET_INPUT_PULLUP(P); else if (ENABLED(D)) SET_INPUT_PULLDOWN(P); else SET_INPUT(P); }while(0) + #define INIT_RUNOUT_PIN(N) _INIT_RUNOUT_PIN(FIL_RUNOUT##N##_PIN, FIL_RUNOUT##N##_STATE, FIL_RUNOUT##N##_PULLUP, FIL_RUNOUT##N##_PULLDOWN) + #if NUM_RUNOUT_SENSORS >= 1 + INIT_RUNOUT_PIN(1); + #endif + #if NUM_RUNOUT_SENSORS >= 2 + INIT_RUNOUT_PIN(2); + #endif + #if NUM_RUNOUT_SENSORS >= 3 + INIT_RUNOUT_PIN(3); + #endif + #if NUM_RUNOUT_SENSORS >= 4 + INIT_RUNOUT_PIN(4); + #endif + #if NUM_RUNOUT_SENSORS >= 5 + INIT_RUNOUT_PIN(5); + #endif + #if NUM_RUNOUT_SENSORS >= 6 + INIT_RUNOUT_PIN(6); + #endif + #if NUM_RUNOUT_SENSORS >= 7 + INIT_RUNOUT_PIN(7); + #endif + #if NUM_RUNOUT_SENSORS >= 8 + INIT_RUNOUT_PIN(8); + #endif + #undef _INIT_RUNOUT_PIN + #undef INIT_RUNOUT_PIN + } + + // Return a bitmask of runout pin states + static uint8_t poll_runout_pins() { + #define _OR_RUNOUT(N) | (READ(FIL_RUNOUT##N##_PIN) ? _BV((N) - 1) : 0) + return (0 REPEAT_1(NUM_RUNOUT_SENSORS, _OR_RUNOUT)); + #undef _OR_RUNOUT + } + + // Return a bitmask of runout flag states (1 bits always indicates runout) + static uint8_t poll_runout_states() { + return poll_runout_pins() ^ uint8_t(0 + #if NUM_RUNOUT_SENSORS >= 1 + | (FIL_RUNOUT1_STATE ? 0 : _BV(1 - 1)) + #endif + #if NUM_RUNOUT_SENSORS >= 2 + | (FIL_RUNOUT2_STATE ? 0 : _BV(2 - 1)) + #endif + #if NUM_RUNOUT_SENSORS >= 3 + | (FIL_RUNOUT3_STATE ? 0 : _BV(3 - 1)) + #endif + #if NUM_RUNOUT_SENSORS >= 4 + | (FIL_RUNOUT4_STATE ? 0 : _BV(4 - 1)) + #endif + #if NUM_RUNOUT_SENSORS >= 5 + | (FIL_RUNOUT5_STATE ? 0 : _BV(5 - 1)) + #endif + #if NUM_RUNOUT_SENSORS >= 6 + | (FIL_RUNOUT6_STATE ? 0 : _BV(6 - 1)) + #endif + #if NUM_RUNOUT_SENSORS >= 7 + | (FIL_RUNOUT7_STATE ? 0 : _BV(7 - 1)) + #endif + #if NUM_RUNOUT_SENSORS >= 8 + | (FIL_RUNOUT8_STATE ? 0 : _BV(8 - 1)) + #endif + ); + } +}; + +#if ENABLED(FILAMENT_MOTION_SENSOR) + + /** + * This sensor uses a magnetic encoder disc and a Hall effect + * sensor (or a slotted disc and optical sensor). The state + * will toggle between 0 and 1 on filament movement. It can detect + * filament runout and stripouts or jams. + */ + class FilamentSensorEncoder : public FilamentSensorBase { + private: + static uint8_t motion_detected; + + static void poll_motion_sensor() { + static uint8_t old_state; + const uint8_t new_state = poll_runout_pins(), + change = old_state ^ new_state; + old_state = new_state; + + #if ENABLED(FILAMENT_RUNOUT_SENSOR_DEBUG) + if (change) { + SERIAL_ECHOPGM("Motion detected:"); + LOOP_L_N(e, NUM_RUNOUT_SENSORS) + if (TEST(change, e)) SERIAL_CHAR(' ', '0' + e); + SERIAL_EOL(); + } + #endif + + motion_detected |= change; + } + + public: + static void block_completed(const block_t * const b) { + // If the sensor wheel has moved since the last call to + // this method reset the runout counter for the extruder. + if (TEST(motion_detected, b->extruder)) + filament_present(b->extruder); + + // Clear motion triggers for next block + motion_detected = 0; + } + + static void run() { poll_motion_sensor(); } + }; + +#else + + /** + * This is a simple endstop switch in the path of the filament. + * It can detect filament runout, but not stripouts or jams. + */ + class FilamentSensorSwitch : public FilamentSensorBase { + private: + static bool poll_runout_state(const uint8_t extruder) { + const uint8_t runout_states = poll_runout_states(); + #if MULTI_FILAMENT_SENSOR + if ( !TERN0(DUAL_X_CARRIAGE, idex_is_duplicating()) + && !TERN0(MULTI_NOZZLE_DUPLICATION, extruder_duplication_enabled) + ) return TEST(runout_states, extruder); // A specific extruder ran out + #else + UNUSED(extruder); + #endif + return !!runout_states; // Any extruder ran out + } + + public: + static void block_completed(const block_t * const) {} + + static void run() { + LOOP_L_N(s, NUM_RUNOUT_SENSORS) { + const bool out = poll_runout_state(s); + if (!out) filament_present(s); + #if ENABLED(FILAMENT_RUNOUT_SENSOR_DEBUG) + static uint8_t was_out; // = 0 + if (out != TEST(was_out, s)) { + TBI(was_out, s); + SERIAL_ECHOLNF(F("Filament Sensor "), AS_DIGIT(s), out ? F(" OUT") : F(" IN")); + } + #endif + } + } + }; + + +#endif // !FILAMENT_MOTION_SENSOR + +/********************************* RESPONSE TYPE *********************************/ + +#if HAS_FILAMENT_RUNOUT_DISTANCE + + // RunoutResponseDelayed triggers a runout event only if the length + // of filament specified by FILAMENT_RUNOUT_DISTANCE_MM has been fed + // during a runout condition. + class RunoutResponseDelayed { + private: + static volatile float runout_mm_countdown[NUM_RUNOUT_SENSORS]; + + public: + static float runout_distance_mm; + + static void reset() { + LOOP_L_N(i, NUM_RUNOUT_SENSORS) filament_present(i); + } + + static void run() { + #if ENABLED(FILAMENT_RUNOUT_SENSOR_DEBUG) + static millis_t t = 0; + const millis_t ms = millis(); + if (ELAPSED(ms, t)) { + t = millis() + 1000UL; + LOOP_L_N(i, NUM_RUNOUT_SENSORS) + SERIAL_ECHOF(i ? F(", ") : F("Remaining mm: "), runout_mm_countdown[i]); + SERIAL_EOL(); + } + #endif + } + + static uint8_t has_run_out() { + uint8_t runout_flags = 0; + LOOP_L_N(i, NUM_RUNOUT_SENSORS) if (runout_mm_countdown[i] < 0) SBI(runout_flags, i); + return runout_flags; + } + + static void filament_present(const uint8_t extruder) { + runout_mm_countdown[extruder] = runout_distance_mm; + } + + static void block_completed(const block_t * const b) { + if (b->steps.x || b->steps.y || b->steps.z || did_pause_print) { // Allow pause purge move to re-trigger runout state + // Only trigger on extrusion with XYZ movement to allow filament change and retract/recover. + const uint8_t e = b->extruder; + const int32_t steps = b->steps.e; + runout_mm_countdown[e] -= (TEST(b->direction_bits, E_AXIS) ? -steps : steps) * planner.mm_per_step[E_AXIS_N(e)]; + } + } + }; + +#else // !HAS_FILAMENT_RUNOUT_DISTANCE + + // RunoutResponseDebounced triggers a runout event after a runout + // condition has been detected runout_threshold times in a row. + + class RunoutResponseDebounced { + private: + static constexpr int8_t runout_threshold = FILAMENT_RUNOUT_THRESHOLD; + static int8_t runout_count[NUM_RUNOUT_SENSORS]; + + public: + static void reset() { + LOOP_L_N(i, NUM_RUNOUT_SENSORS) filament_present(i); + } + + static void run() { + LOOP_L_N(i, NUM_RUNOUT_SENSORS) if (runout_count[i] >= 0) runout_count[i]--; + } + + static uint8_t has_run_out() { + uint8_t runout_flags = 0; + LOOP_L_N(i, NUM_RUNOUT_SENSORS) if (runout_count[i] < 0) SBI(runout_flags, i); + return runout_flags; + } + + static void block_completed(const block_t * const) { } + + static void filament_present(const uint8_t extruder) { + runout_count[extruder] = runout_threshold; + } + }; + +#endif // !HAS_FILAMENT_RUNOUT_DISTANCE diff --git a/src/feature/solenoid.cpp b/src/feature/solenoid.cpp new file mode 100644 index 0000000..861e44e --- /dev/null +++ b/src/feature/solenoid.cpp @@ -0,0 +1,55 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if EITHER(EXT_SOLENOID, MANUAL_SOLENOID_CONTROL) + +#include "solenoid.h" + +#include "../module/motion.h" // for active_extruder +#include "../module/tool_change.h" + +// Used primarily with MANUAL_SOLENOID_CONTROL +static void set_solenoid(const uint8_t num, const uint8_t state) { + #define _SOL_CASE(N) case N: TERN_(HAS_SOLENOID_##N, OUT_WRITE(SOL##N##_PIN, state)); break; + switch (num) { + REPEAT(8, _SOL_CASE) + default: SERIAL_ECHO_MSG(STR_INVALID_SOLENOID); break; + } + + #if ENABLED(PARKING_EXTRUDER) + if (state == LOW && active_extruder == num) // If active extruder's solenoid is disabled, carriage is considered parked + parking_extruder_set_parked(true); + #endif +} + +// PARKING_EXTRUDER options alter the default behavior of solenoids to ensure compliance of M380-381 +void enable_solenoid(const uint8_t num) { set_solenoid(num, TERN1(PARKING_EXTRUDER, PE_MAGNET_ON_STATE)); } +void disable_solenoid(const uint8_t num) { set_solenoid(num, TERN0(PARKING_EXTRUDER, !PE_MAGNET_ON_STATE)); } + +void disable_all_solenoids() { + #define _SOL_DISABLE(N) TERN_(HAS_SOLENOID_##N, disable_solenoid(N)); + REPEAT(8, _SOL_DISABLE) +} + +#endif // EXT_SOLENOID || MANUAL_SOLENOID_CONTROL diff --git a/src/feature/solenoid.h b/src/feature/solenoid.h new file mode 100644 index 0000000..3131aeb --- /dev/null +++ b/src/feature/solenoid.h @@ -0,0 +1,26 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +void disable_all_solenoids(); +void enable_solenoid(const uint8_t num); +void disable_solenoid(const uint8_t num); diff --git a/src/feature/spindle_laser.cpp b/src/feature/spindle_laser.cpp new file mode 100644 index 0000000..da38646 --- /dev/null +++ b/src/feature/spindle_laser.cpp @@ -0,0 +1,181 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * feature/spindle_laser.cpp + */ + +#include "../inc/MarlinConfig.h" + +#if HAS_CUTTER + +#include "spindle_laser.h" + +#if ENABLED(SPINDLE_SERVO) + #include "../module/servo.h" +#endif + +#if ENABLED(I2C_AMMETER) + #include "../feature/ammeter.h" +#endif + +SpindleLaser cutter; +bool SpindleLaser::enable_state; // Virtual enable state, controls enable pin if present and or apply power if > 0 +uint8_t SpindleLaser::power, // Actual power output 0-255 ocr or "0 = off" > 0 = "on" + SpindleLaser::last_power_applied; // = 0 // Basic power state tracking + +#if ENABLED(LASER_FEATURE) + cutter_test_pulse_t SpindleLaser::testPulse = 50; // (ms) Test fire pulse default duration + uint8_t SpindleLaser::last_block_power; // = 0 // Track power changes for dynamic inline power + feedRate_t SpindleLaser::feedrate_mm_m = 1500, + SpindleLaser::last_feedrate_mm_m; // = 0 // (mm/min) Track feedrate changes for dynamic power +#endif + +bool SpindleLaser::isReadyForUI = false; // Ready to apply power setting from the UI to OCR +CutterMode SpindleLaser::cutter_mode = CUTTER_MODE_STANDARD; // Default is standard mode + +constexpr cutter_cpower_t SpindleLaser::power_floor; +cutter_power_t SpindleLaser::menuPower = 0, // Power value via LCD menu in PWM, PERCENT, or RPM based on configured format set by CUTTER_POWER_UNIT. + SpindleLaser::unitPower = 0; // Unit power is in PWM, PERCENT, or RPM based on CUTTER_POWER_UNIT. + +cutter_frequency_t SpindleLaser::frequency; // PWM frequency setting; range: 2K - 50K + +#define SPINDLE_LASER_PWM_OFF TERN(SPINDLE_LASER_PWM_INVERT, 255, 0) + +/** + * Init the cutter to a safe OFF state + */ +void SpindleLaser::init() { + #if ENABLED(SPINDLE_SERVO) + servo[SPINDLE_SERVO_NR].move(SPINDLE_SERVO_MIN); + #else + OUT_WRITE(SPINDLE_LASER_ENA_PIN, !SPINDLE_LASER_ACTIVE_STATE); // Init spindle to off + #endif + #if ENABLED(SPINDLE_CHANGE_DIR) + OUT_WRITE(SPINDLE_DIR_PIN, SPINDLE_INVERT_DIR); // Init rotation to clockwise (M3) + #endif + #if ENABLED(HAL_CAN_SET_PWM_FREQ) && SPINDLE_LASER_FREQUENCY + frequency = SPINDLE_LASER_FREQUENCY; + hal.set_pwm_frequency(pin_t(SPINDLE_LASER_PWM_PIN), SPINDLE_LASER_FREQUENCY); + #endif + #if ENABLED(SPINDLE_LASER_USE_PWM) + SET_PWM(SPINDLE_LASER_PWM_PIN); + hal.set_pwm_duty(pin_t(SPINDLE_LASER_PWM_PIN), SPINDLE_LASER_PWM_OFF); // Set to lowest speed + #endif + #if ENABLED(AIR_EVACUATION) + OUT_WRITE(AIR_EVACUATION_PIN, !AIR_EVACUATION_ACTIVE); // Init Vacuum/Blower OFF + #endif + #if ENABLED(AIR_ASSIST) + OUT_WRITE(AIR_ASSIST_PIN, !AIR_ASSIST_ACTIVE); // Init Air Assist OFF + #endif + TERN_(I2C_AMMETER, ammeter.init()); // Init I2C Ammeter +} + +#if ENABLED(SPINDLE_LASER_USE_PWM) + /** + * Set the cutter PWM directly to the given ocr value + * + * @param ocr Power value + */ + void SpindleLaser::_set_ocr(const uint8_t ocr) { + #if ENABLED(HAL_CAN_SET_PWM_FREQ) && SPINDLE_LASER_FREQUENCY + hal.set_pwm_frequency(pin_t(SPINDLE_LASER_PWM_PIN), frequency); + #endif + hal.set_pwm_duty(pin_t(SPINDLE_LASER_PWM_PIN), ocr ^ SPINDLE_LASER_PWM_OFF); + } + + void SpindleLaser::set_ocr(const uint8_t ocr) { + WRITE(SPINDLE_LASER_ENA_PIN, SPINDLE_LASER_ACTIVE_STATE); // Cutter ON + _set_ocr(ocr); + } + + void SpindleLaser::ocr_off() { + WRITE(SPINDLE_LASER_ENA_PIN, !SPINDLE_LASER_ACTIVE_STATE); // Cutter OFF + _set_ocr(0); + } +#endif // SPINDLE_LASER_USE_PWM + +/** + * Apply power for Laser or Spindle + * + * Apply cutter power value for PWM, Servo, and on/off pin. + * + * @param opwr Power value. Range 0 to MAX. + */ +void SpindleLaser::apply_power(const uint8_t opwr) { + if (enabled() || opwr == 0) { // 0 check allows us to disable where no ENA pin exists + // Test and set the last power used to improve performance + if (opwr == last_power_applied) return; + last_power_applied = opwr; + // Handle PWM driven or just simple on/off + #if ENABLED(SPINDLE_LASER_USE_PWM) + if (CUTTER_UNIT_IS(RPM) && unitPower == 0) + ocr_off(); + else if (ENABLED(CUTTER_POWER_RELATIVE) || enabled() || opwr == 0) { + set_ocr(opwr); + isReadyForUI = true; + } + else + ocr_off(); + #elif ENABLED(SPINDLE_SERVO) + MOVE_SERVO(SPINDLE_SERVO_NR, power); + #else + WRITE(SPINDLE_LASER_ENA_PIN, enabled() ? SPINDLE_LASER_ACTIVE_STATE : !SPINDLE_LASER_ACTIVE_STATE); + isReadyForUI = true; + #endif + } + else { + #if PIN_EXISTS(SPINDLE_LASER_ENA) + WRITE(SPINDLE_LASER_ENA_PIN, !SPINDLE_LASER_ACTIVE_STATE); + #endif + isReadyForUI = false; // Only used for UI display updates. + TERN_(SPINDLE_LASER_USE_PWM, ocr_off()); + } +} + +#if ENABLED(SPINDLE_CHANGE_DIR) + /** + * Set the spindle direction and apply immediately + * Stop on direction change if SPINDLE_STOP_ON_DIR_CHANGE is enabled + */ + void SpindleLaser::set_reverse(const bool reverse) { + const bool dir_state = (reverse == SPINDLE_INVERT_DIR); // Forward (M3) HIGH when not inverted + if (TERN0(SPINDLE_STOP_ON_DIR_CHANGE, enabled()) && READ(SPINDLE_DIR_PIN) != dir_state) disable(); + WRITE(SPINDLE_DIR_PIN, dir_state); + } +#endif + +#if ENABLED(AIR_EVACUATION) + // Enable / disable Cutter Vacuum or Laser Blower motor + void SpindleLaser::air_evac_enable() { WRITE(AIR_EVACUATION_PIN, AIR_EVACUATION_ACTIVE); } // Turn ON + void SpindleLaser::air_evac_disable() { WRITE(AIR_EVACUATION_PIN, !AIR_EVACUATION_ACTIVE); } // Turn OFF + void SpindleLaser::air_evac_toggle() { TOGGLE(AIR_EVACUATION_PIN); } // Toggle state +#endif + +#if ENABLED(AIR_ASSIST) + // Enable / disable air assist + void SpindleLaser::air_assist_enable() { WRITE(AIR_ASSIST_PIN, AIR_ASSIST_ACTIVE); } // Turn ON + void SpindleLaser::air_assist_disable() { WRITE(AIR_ASSIST_PIN, !AIR_ASSIST_ACTIVE); } // Turn OFF + void SpindleLaser::air_assist_toggle() { TOGGLE(AIR_ASSIST_PIN); } // Toggle state +#endif + +#endif // HAS_CUTTER diff --git a/src/feature/spindle_laser.h b/src/feature/spindle_laser.h new file mode 100644 index 0000000..c4923a0 --- /dev/null +++ b/src/feature/spindle_laser.h @@ -0,0 +1,329 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * feature/spindle_laser.h + * Support for Laser Power or Spindle Power & Direction + */ + +#include "../inc/MarlinConfig.h" + +#include "spindle_laser_types.h" + +#if HAS_BEEPER + #include "../libs/buzzer.h" +#endif + +// Inline laser power +#include "../module/planner.h" + +#define PCT_TO_PWM(X) ((X) * 255 / 100) +#define PCT_TO_SERVO(X) ((X) * 180 / 100) + +// Laser/Cutter operation mode +enum CutterMode : int8_t { + CUTTER_MODE_ERROR = -1, + CUTTER_MODE_STANDARD, // M3 power is applied directly and waits for planner moves to sync. + CUTTER_MODE_CONTINUOUS, // M3 or G1/2/3 move power is controlled within planner blocks, set with 'M3 I', cleared with 'M5 I'. + CUTTER_MODE_DYNAMIC // M4 laser power is proportional to the feed rate, set with 'M4 I', cleared with 'M5 I'. +}; + +class SpindleLaser { +public: + static CutterMode cutter_mode; + + static constexpr uint8_t pct_to_ocr(const_float_t pct) { return uint8_t(PCT_TO_PWM(pct)); } + + // cpower = configured values (e.g., SPEED_POWER_MAX) + // Convert configured power range to a percentage + static constexpr cutter_cpower_t power_floor = TERN(CUTTER_POWER_RELATIVE, SPEED_POWER_MIN, 0); + static constexpr uint8_t cpwr_to_pct(const cutter_cpower_t cpwr) { + return cpwr ? round(100.0f * (cpwr - power_floor) / (SPEED_POWER_MAX - power_floor)) : 0; + } + + // Convert config defines from RPM to %, angle or PWM when in Spindle mode + // and convert from PERCENT to PWM when in Laser mode + static constexpr cutter_power_t cpwr_to_upwr(const cutter_cpower_t cpwr) { // STARTUP power to Unit power + return ( + #if ENABLED(SPINDLE_FEATURE) + // Spindle configured define values are in RPM + #if CUTTER_UNIT_IS(RPM) + cpwr // to same + #elif CUTTER_UNIT_IS(PERCENT) + cpwr_to_pct(cpwr) // to Percent + #elif CUTTER_UNIT_IS(SERVO) + PCT_TO_SERVO(cpwr_to_pct(cpwr)) // to SERVO angle + #else + PCT_TO_PWM(cpwr_to_pct(cpwr)) // to PWM + #endif + #else + // Laser configured define values are in Percent + #if CUTTER_UNIT_IS(PWM255) + PCT_TO_PWM(cpwr) // to PWM + #else + cpwr // to same + #endif + #endif + ); + } + + static constexpr cutter_power_t mpower_min() { return cpwr_to_upwr(SPEED_POWER_MIN); } + static constexpr cutter_power_t mpower_max() { return cpwr_to_upwr(SPEED_POWER_MAX); } + + #if ENABLED(LASER_FEATURE) + static cutter_test_pulse_t testPulse; // (ms) Test fire pulse duration + static uint8_t last_block_power; // Track power changes for dynamic power + + static feedRate_t feedrate_mm_m, last_feedrate_mm_m; // (mm/min) Track feedrate changes for dynamic power + static bool laser_feedrate_changed() { + const bool changed = last_feedrate_mm_m != feedrate_mm_m; + if (changed) last_feedrate_mm_m = feedrate_mm_m; + return changed; + } + #endif + + static bool isReadyForUI; // Ready to apply power setting from the UI to OCR + static bool enable_state; + static uint8_t power, + last_power_applied; // Basic power state tracking + + static cutter_frequency_t frequency; // Set PWM frequency; range: 2K-50K + + static cutter_power_t menuPower, // Power as set via LCD menu in PWM, Percentage or RPM + unitPower; // Power as displayed status in PWM, Percentage or RPM + + static void init(); + + #if ENABLED(HAL_CAN_SET_PWM_FREQ) && SPINDLE_LASER_FREQUENCY + static void refresh_frequency() { hal.set_pwm_frequency(pin_t(SPINDLE_LASER_PWM_PIN), frequency); } + #endif + + // Modifying this function should update everywhere + static bool enabled(const cutter_power_t opwr) { return opwr > 0; } + static bool enabled() { return enable_state; } + + static void apply_power(const uint8_t inpow); + + FORCE_INLINE static void refresh() { apply_power(power); } + + #if ENABLED(SPINDLE_LASER_USE_PWM) + + private: + + static void _set_ocr(const uint8_t ocr); + + public: + + static void set_ocr(const uint8_t ocr); + static void ocr_off(); + + /** + * Update output for power->OCR translation + */ + static uint8_t upower_to_ocr(const cutter_power_t upwr) { + return uint8_t( + #if CUTTER_UNIT_IS(PWM255) + upwr + #elif CUTTER_UNIT_IS(PERCENT) + pct_to_ocr(upwr) + #else + pct_to_ocr(cpwr_to_pct(upwr)) + #endif + ); + } + + #endif // SPINDLE_LASER_USE_PWM + + /** + * Correct power to configured range + */ + static cutter_power_t power_to_range(const cutter_power_t pwr, const uint8_t pwrUnit=_CUTTER_POWER(CUTTER_POWER_UNIT)) { + static constexpr float + min_pct = TERN(CUTTER_POWER_RELATIVE, 0, TERN(SPINDLE_FEATURE, round(100.0f * (SPEED_POWER_MIN) / (SPEED_POWER_MAX)), SPEED_POWER_MIN)), + max_pct = TERN(SPINDLE_FEATURE, 100, SPEED_POWER_MAX); + if (pwr <= 0) return 0; + cutter_power_t upwr; + switch (pwrUnit) { + case _CUTTER_POWER_PWM255: { // PWM + const uint8_t pmin = pct_to_ocr(min_pct), pmax = pct_to_ocr(max_pct); + upwr = cutter_power_t(constrain(pwr, pmin, pmax)); + } break; + case _CUTTER_POWER_PERCENT: // Percent + upwr = cutter_power_t(constrain(pwr, min_pct, max_pct)); + break; + case _CUTTER_POWER_RPM: // Calculate OCR value + upwr = cutter_power_t(constrain(pwr, SPEED_POWER_MIN, SPEED_POWER_MAX)); + break; + default: break; + } + return upwr; + } + + /** + * Enable Laser or Spindle output. + * It's important to prevent changing the power output value during inline cutter operation. + * Inline power is adjusted in the planner to support LASER_TRAP_POWER and CUTTER_MODE_DYNAMIC mode. + * + * This method accepts one of the following control states: + * + * - For CUTTER_MODE_STANDARD the cutter power is either full on/off or ocr-based and it will apply + * SPEED_POWER_STARTUP if no value is assigned. + * + * - For CUTTER_MODE_CONTINUOUS inline and power remains where last set and the cutter output enable flag is set. + * + * - CUTTER_MODE_DYNAMIC is also inline-based and it just sets the enable output flag. + * + * - For CUTTER_MODE_ERROR set the output enable_state flag directly and set power to 0 for any mode. + * This mode allows a global power shutdown action to occur. + */ + static void set_enabled(const bool enable) { + switch (cutter_mode) { + case CUTTER_MODE_STANDARD: + apply_power(enable ? TERN(SPINDLE_LASER_USE_PWM, (power ?: (unitPower ? upower_to_ocr(cpwr_to_upwr(SPEED_POWER_STARTUP)) : 0)), 255) : 0); + break; + case CUTTER_MODE_CONTINUOUS: + TERN_(LASER_FEATURE, set_inline_enabled(enable)); + break; + case CUTTER_MODE_DYNAMIC: + TERN_(LASER_FEATURE, set_inline_enabled(enable)); + break; + case CUTTER_MODE_ERROR: // Error mode, no enable and kill power. + enable_state = false; + apply_power(0); + } + #if SPINDLE_LASER_ENA_PIN + WRITE(SPINDLE_LASER_ENA_PIN, enable ? SPINDLE_LASER_ACTIVE_STATE : !SPINDLE_LASER_ACTIVE_STATE); + #endif + enable_state = enable; + } + + static void disable() { isReadyForUI = false; set_enabled(false); } + + // Wait for spindle/laser to startup or shutdown + static void power_delay(const bool on) { + safe_delay(on ? SPINDLE_LASER_POWERUP_DELAY : SPINDLE_LASER_POWERDOWN_DELAY); + } + + #if ENABLED(SPINDLE_CHANGE_DIR) + static void set_reverse(const bool reverse); + static bool is_reverse() { return READ(SPINDLE_DIR_PIN) == SPINDLE_INVERT_DIR; } + #else + static void set_reverse(const bool) {} + static bool is_reverse() { return false; } + #endif + + #if ENABLED(AIR_EVACUATION) + static void air_evac_enable(); // Turn On Cutter Vacuum or Laser Blower motor + static void air_evac_disable(); // Turn Off Cutter Vacuum or Laser Blower motor + static void air_evac_toggle(); // Toggle Cutter Vacuum or Laser Blower motor + static bool air_evac_state() { // Get current state + return (READ(AIR_EVACUATION_PIN) == AIR_EVACUATION_ACTIVE); + } + #endif + + #if ENABLED(AIR_ASSIST) + static void air_assist_enable(); // Turn on air assist + static void air_assist_disable(); // Turn off air assist + static void air_assist_toggle(); // Toggle air assist + static bool air_assist_state() { // Get current state + return (READ(AIR_ASSIST_PIN) == AIR_ASSIST_ACTIVE); + } + #endif + + #if HAS_MARLINUI_MENU + + #if ENABLED(SPINDLE_FEATURE) + static void enable_with_dir(const bool reverse) { + isReadyForUI = true; + const uint8_t ocr = TERN(SPINDLE_LASER_USE_PWM, upower_to_ocr(menuPower), 255); + if (menuPower) + power = ocr; + else + menuPower = cpwr_to_upwr(SPEED_POWER_STARTUP); + unitPower = menuPower; + set_reverse(reverse); + set_enabled(true); + } + FORCE_INLINE static void enable_forward() { enable_with_dir(false); } + FORCE_INLINE static void enable_reverse() { enable_with_dir(true); } + FORCE_INLINE static void enable_same_dir() { enable_with_dir(is_reverse()); } + #endif // SPINDLE_FEATURE + + #if ENABLED(SPINDLE_LASER_USE_PWM) + static void update_from_mpower() { + if (isReadyForUI) power = upower_to_ocr(menuPower); + unitPower = menuPower; + } + #endif + + #if ENABLED(LASER_FEATURE) + // Toggle the laser on/off with menuPower. Apply SPEED_POWER_STARTUP if it was 0 on entry. + static void laser_menu_toggle(const bool state) { + set_enabled(state); + if (state) { + if (!menuPower) menuPower = cpwr_to_upwr(SPEED_POWER_STARTUP); + power = upower_to_ocr(menuPower); + apply_power(power); + } + } + + /** + * Test fire the laser using the testPulse ms duration + * Also fires with any PWM power that was previous set + * If not set defaults to 80% power + */ + static void test_fire_pulse() { + BUZZ(30, 3000); + cutter_mode = CUTTER_MODE_STANDARD;// Menu needs standard mode. + laser_menu_toggle(true); // Laser On + delay(testPulse); // Delay for time set by user in pulse ms menu screen. + laser_menu_toggle(false); // Laser Off + } + #endif // LASER_FEATURE + + #endif // HAS_MARLINUI_MENU + + #if ENABLED(LASER_FEATURE) + + // Dynamic mode rate calculation + static uint8_t calc_dynamic_power() { + if (feedrate_mm_m > 65535) return 255; // Too fast, go always on + uint16_t rate = uint16_t(feedrate_mm_m); // 16 bits from the G-code parser float input + rate >>= 8; // Take the G-code input e.g. F40000 and shift off the lower bits to get an OCR value from 1-255 + return uint8_t(rate); + } + + // Inline modes of all other functions; all enable planner inline power control + static void set_inline_enabled(const bool enable) { planner.laser_inline.status.isEnabled = enable;} + + // Set the power for subsequent movement blocks + static void inline_power(const cutter_power_t cpwr) { + TERN(SPINDLE_LASER_USE_PWM, power = planner.laser_inline.power = cpwr, planner.laser_inline.power = cpwr > 0 ? 255 : 0); + } + + #endif // LASER_FEATURE + + static void kill() { disable(); } +}; + +extern SpindleLaser cutter; diff --git a/src/feature/spindle_laser_types.h b/src/feature/spindle_laser_types.h new file mode 100644 index 0000000..2f36a68 --- /dev/null +++ b/src/feature/spindle_laser_types.h @@ -0,0 +1,83 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * feature/spindle_laser_types.h + * Support for Laser Power or Spindle Power & Direction + */ + +#include "../inc/MarlinConfigPre.h" + +#define MSG_CUTTER(M) _MSG_CUTTER(M) + +#ifndef SPEED_POWER_INTERCEPT + #define SPEED_POWER_INTERCEPT 0 +#endif +#if ENABLED(SPINDLE_FEATURE) + #define _MSG_CUTTER(M) MSG_SPINDLE_##M + #ifndef SPEED_POWER_MIN + #define SPEED_POWER_MIN 5000 + #endif + #ifndef SPEED_POWER_MAX + #define SPEED_POWER_MAX 30000 + #endif + #ifndef SPEED_POWER_STARTUP + #define SPEED_POWER_STARTUP 25000 + #endif +#else + #define _MSG_CUTTER(M) MSG_LASER_##M + #ifndef SPEED_POWER_MIN + #define SPEED_POWER_MIN 0 + #endif + #ifndef SPEED_POWER_MAX + #define SPEED_POWER_MAX 255 + #endif + #ifndef SPEED_POWER_STARTUP + #define SPEED_POWER_STARTUP 255 + #endif +#endif + +typedef IF<(SPEED_POWER_MAX > 255), uint16_t, uint8_t>::type cutter_cpower_t; + +#if CUTTER_UNIT_IS(RPM) && SPEED_POWER_MAX > 255 + typedef uint16_t cutter_power_t; + #define CUTTER_MENU_POWER_TYPE uint16_5 + #define cutter_power2str ui16tostr5rj +#else + typedef uint8_t cutter_power_t; + #if CUTTER_UNIT_IS(PERCENT) + #define CUTTER_MENU_POWER_TYPE percent_3 + #define cutter_power2str pcttostrpctrj + #else + #define CUTTER_MENU_POWER_TYPE uint8 + #define cutter_power2str ui8tostr3rj + #endif +#endif + +typedef uint16_t cutter_frequency_t; + +#if ENABLED(LASER_FEATURE) + typedef uint16_t cutter_test_pulse_t; + #define CUTTER_MENU_PULSE_TYPE uint16_3 + #define CUTTER_MENU_FREQUENCY_TYPE uint16_5 +#endif diff --git a/src/feature/stepper_driver_safety.cpp b/src/feature/stepper_driver_safety.cpp new file mode 100644 index 0000000..11b9095 --- /dev/null +++ b/src/feature/stepper_driver_safety.cpp @@ -0,0 +1,117 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "../inc/MarlinConfig.h" +#include "../lcd/marlinui.h" + +#if HAS_DRIVER_SAFE_POWER_PROTECT + +#include "stepper_driver_safety.h" + +static uint32_t axis_plug_backward = 0; + +void stepper_driver_backward_error(FSTR_P const fstr) { + SERIAL_ERROR_START(); + SERIAL_ECHOF(fstr); + SERIAL_ECHOLNPGM(" driver is backward!"); + ui.status_printf(2, F(S_FMT S_FMT), FTOP(fstr), GET_TEXT(MSG_DRIVER_BACKWARD)); +} + +void stepper_driver_backward_check() { + + OUT_WRITE(SAFE_POWER_PIN, LOW); + + #define _TEST_BACKWARD(AXIS, BIT) do { \ + SET_INPUT(AXIS##_ENABLE_PIN); \ + OUT_WRITE(AXIS##_STEP_PIN, false); \ + delay(20); \ + if (READ(AXIS##_ENABLE_PIN) == false) { \ + SBI(axis_plug_backward, BIT); \ + stepper_driver_backward_error(F(STRINGIFY(AXIS))); \ + } \ + }while(0) + + #define TEST_BACKWARD(AXIS, BIT) TERN_(HAS_##AXIS##_ENABLE, _TEST_BACKWARD(AXIS, BIT)) + + TEST_BACKWARD(X, 0); + TEST_BACKWARD(X2, 1); + + TEST_BACKWARD(Y, 2); + TEST_BACKWARD(Y2, 3); + + TEST_BACKWARD(Z, 4); + TEST_BACKWARD(Z2, 5); + TEST_BACKWARD(Z3, 6); + TEST_BACKWARD(Z4, 7); + + TEST_BACKWARD(I, 8); + TEST_BACKWARD(J, 9); + TEST_BACKWARD(K, 10); + + TEST_BACKWARD(E0, 11); + TEST_BACKWARD(E1, 12); + TEST_BACKWARD(E2, 13); + TEST_BACKWARD(E3, 14); + TEST_BACKWARD(E4, 15); + TEST_BACKWARD(E5, 16); + TEST_BACKWARD(E6, 17); + TEST_BACKWARD(E7, 18); + + if (!axis_plug_backward) + WRITE(SAFE_POWER_PIN, HIGH); +} + +void stepper_driver_backward_report() { + if (!axis_plug_backward) return; + + auto _report_if_backward = [](FSTR_P const axis, uint8_t bit) { + if (TEST(axis_plug_backward, bit)) + stepper_driver_backward_error(axis); + }; + + #define REPORT_BACKWARD(axis, bit) TERN_(HAS_##axis##_ENABLE, _report_if_backward(F(STRINGIFY(axis)), bit)) + + REPORT_BACKWARD(X, 0); + REPORT_BACKWARD(X2, 1); + + REPORT_BACKWARD(Y, 2); + REPORT_BACKWARD(Y2, 3); + + REPORT_BACKWARD(Z, 4); + REPORT_BACKWARD(Z2, 5); + REPORT_BACKWARD(Z3, 6); + REPORT_BACKWARD(Z4, 7); + + REPORT_BACKWARD(I, 8); + REPORT_BACKWARD(J, 9); + REPORT_BACKWARD(K, 10); + + REPORT_BACKWARD(E0, 11); + REPORT_BACKWARD(E1, 12); + REPORT_BACKWARD(E2, 13); + REPORT_BACKWARD(E3, 14); + REPORT_BACKWARD(E4, 15); + REPORT_BACKWARD(E5, 16); + REPORT_BACKWARD(E6, 17); + REPORT_BACKWARD(E7, 18); +} + +#endif // HAS_DRIVER_SAFE_POWER_PROTECT diff --git a/src/feature/stepper_driver_safety.h b/src/feature/stepper_driver_safety.h new file mode 100644 index 0000000..46edf33 --- /dev/null +++ b/src/feature/stepper_driver_safety.h @@ -0,0 +1,28 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + + +#include "../inc/MarlinConfigPre.h" + +void stepper_driver_backward_check(); +void stepper_driver_backward_report(); diff --git a/src/feature/tmc_util.cpp b/src/feature/tmc_util.cpp new file mode 100644 index 0000000..ef3fb3a --- /dev/null +++ b/src/feature/tmc_util.cpp @@ -0,0 +1,1336 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if HAS_TRINAMIC_CONFIG + +#include "tmc_util.h" +#include "../MarlinCore.h" + +#include "../module/stepper/indirection.h" +#include "../module/printcounter.h" +#include "../libs/duration_t.h" +#include "../gcode/gcode.h" + +#if ENABLED(TMC_DEBUG) + #include "../libs/hex_print.h" + #if ENABLED(MONITOR_DRIVER_STATUS) + static uint16_t report_tmc_status_interval; // = 0 + #endif +#endif + +/** + * Check for over temperature or short to ground error flags. + * Report and log warning of overtemperature condition. + * Reduce driver current in a persistent otpw condition. + * Keep track of otpw counter so we don't reduce current on a single instance, + * and so we don't repeatedly report warning before the condition is cleared. + */ +#if ENABLED(MONITOR_DRIVER_STATUS) + + struct TMC_driver_data { + uint32_t drv_status; + bool is_otpw:1, + is_ot:1, + is_s2g:1, + is_error:1 + #if ENABLED(TMC_DEBUG) + , is_stall:1 + , is_stealth:1 + , is_standstill:1 + #if HAS_STALLGUARD + , sg_result_reasonable:1 + #endif + #endif + ; + #if ENABLED(TMC_DEBUG) + #if HAS_TMCX1X0 || HAS_TMC220x + uint8_t cs_actual; + #endif + #if HAS_STALLGUARD + uint16_t sg_result; + #endif + #endif + }; + + #if HAS_TMCX1X0 + + #if ENABLED(TMC_DEBUG) + static uint32_t get_pwm_scale(TMC2130Stepper &st) { return st.PWM_SCALE(); } + #endif + + static TMC_driver_data get_driver_data(TMC2130Stepper &st) { + constexpr uint8_t OT_bp = 25, OTPW_bp = 26; + constexpr uint32_t S2G_bm = 0x18000000; + #if ENABLED(TMC_DEBUG) + constexpr uint16_t SG_RESULT_bm = 0x3FF; // 0:9 + constexpr uint8_t STEALTH_bp = 14; + constexpr uint32_t CS_ACTUAL_bm = 0x1F0000; // 16:20 + constexpr uint8_t STALL_GUARD_bp = 24; + constexpr uint8_t STST_bp = 31; + #endif + TMC_driver_data data; + const auto ds = data.drv_status = st.DRV_STATUS(); + #ifdef __AVR__ + + // 8-bit optimization saves up to 70 bytes of PROGMEM per axis + uint8_t spart; + #if ENABLED(TMC_DEBUG) + data.sg_result = ds & SG_RESULT_bm; + spart = ds >> 8; + data.is_stealth = TEST(spart, STEALTH_bp - 8); + spart = ds >> 16; + data.cs_actual = spart & (CS_ACTUAL_bm >> 16); + #endif + spart = ds >> 24; + data.is_ot = TEST(spart, OT_bp - 24); + data.is_otpw = TEST(spart, OTPW_bp - 24); + data.is_s2g = !!(spart & (S2G_bm >> 24)); + #if ENABLED(TMC_DEBUG) + data.is_stall = TEST(spart, STALL_GUARD_bp - 24); + data.is_standstill = TEST(spart, STST_bp - 24); + data.sg_result_reasonable = !data.is_standstill; // sg_result has no reasonable meaning while standstill + #endif + + #else // !__AVR__ + + data.is_ot = TEST(ds, OT_bp); + data.is_otpw = TEST(ds, OTPW_bp); + data.is_s2g = !!(ds & S2G_bm); + #if ENABLED(TMC_DEBUG) + constexpr uint8_t CS_ACTUAL_sb = 16; + data.sg_result = ds & SG_RESULT_bm; + data.is_stealth = TEST(ds, STEALTH_bp); + data.cs_actual = (ds & CS_ACTUAL_bm) >> CS_ACTUAL_sb; + data.is_stall = TEST(ds, STALL_GUARD_bp); + data.is_standstill = TEST(ds, STST_bp); + data.sg_result_reasonable = !data.is_standstill; // sg_result has no reasonable meaning while standstill + #endif + + #endif // !__AVR__ + + return data; + } + + #endif // HAS_TMCX1X0 + + #if HAS_TMC220x + + #if ENABLED(TMC_DEBUG) + static uint32_t get_pwm_scale(TMC2208Stepper &st) { return st.pwm_scale_sum(); } + #endif + + static TMC_driver_data get_driver_data(TMC2208Stepper &st) { + constexpr uint8_t OTPW_bp = 0, OT_bp = 1; + constexpr uint8_t S2G_bm = 0b111100; // 2..5 + TMC_driver_data data; + const auto ds = data.drv_status = st.DRV_STATUS(); + data.is_otpw = TEST(ds, OTPW_bp); + data.is_ot = TEST(ds, OT_bp); + data.is_s2g = !!(ds & S2G_bm); + #if ENABLED(TMC_DEBUG) + constexpr uint32_t CS_ACTUAL_bm = 0x1F0000; // 16:20 + constexpr uint8_t STEALTH_bp = 30, STST_bp = 31; + #ifdef __AVR__ + // 8-bit optimization saves up to 12 bytes of PROGMEM per axis + uint8_t spart = ds >> 16; + data.cs_actual = spart & (CS_ACTUAL_bm >> 16); + spart = ds >> 24; + data.is_stealth = TEST(spart, STEALTH_bp - 24); + data.is_standstill = TEST(spart, STST_bp - 24); + #else + constexpr uint8_t CS_ACTUAL_sb = 16; + data.cs_actual = (ds & CS_ACTUAL_bm) >> CS_ACTUAL_sb; + data.is_stealth = TEST(ds, STEALTH_bp); + data.is_standstill = TEST(ds, STST_bp); + #endif + TERN_(HAS_STALLGUARD, data.sg_result_reasonable = false); + #endif + return data; + } + + #endif // TMC2208 || TMC2209 + + #if HAS_DRIVER(TMC2660) + + #if ENABLED(TMC_DEBUG) + static uint32_t get_pwm_scale(TMC2660Stepper) { return 0; } + #endif + + static TMC_driver_data get_driver_data(TMC2660Stepper &st) { + constexpr uint8_t OT_bp = 1, OTPW_bp = 2; + constexpr uint8_t S2G_bm = 0b11000; + TMC_driver_data data; + const auto ds = data.drv_status = st.DRVSTATUS(); + uint8_t spart = ds & 0xFF; + data.is_otpw = TEST(spart, OTPW_bp); + data.is_ot = TEST(spart, OT_bp); + data.is_s2g = !!(ds & S2G_bm); + #if ENABLED(TMC_DEBUG) + constexpr uint8_t STALL_GUARD_bp = 0; + constexpr uint8_t STST_bp = 7, SG_RESULT_sp = 10; + constexpr uint32_t SG_RESULT_bm = 0xFFC00; // 10:19 + data.is_stall = TEST(spart, STALL_GUARD_bp); + data.is_standstill = TEST(spart, STST_bp); + data.sg_result = (ds & SG_RESULT_bm) >> SG_RESULT_sp; + data.sg_result_reasonable = true; + #endif + return data; + } + + #endif // TMC2660 + + #if ENABLED(STOP_ON_ERROR) + void report_driver_error(const TMC_driver_data &data) { + SERIAL_ECHOPGM(" driver error detected: 0x"); + SERIAL_PRINTLN(data.drv_status, PrintBase::Hex); + if (data.is_ot) SERIAL_ECHOLNPGM("overtemperature"); + if (data.is_s2g) SERIAL_ECHOLNPGM("coil short circuit"); + TERN_(TMC_DEBUG, tmc_report_all()); + kill(F("Driver error")); + } + #endif + + template + void report_driver_otpw(TMC &st) { + char timestamp[14]; + duration_t elapsed = print_job_timer.duration(); + const bool has_days = (elapsed.value > 60*60*24L); + (void)elapsed.toDigital(timestamp, has_days); + SERIAL_EOL(); + SERIAL_ECHO(timestamp); + SERIAL_ECHOPGM(": "); + st.printLabel(); + SERIAL_ECHOLNPGM(" driver overtemperature warning! (", st.getMilliamps(), "mA)"); + } + + template + void report_polled_driver_data(TMC &st, const TMC_driver_data &data) { + const uint32_t pwm_scale = get_pwm_scale(st); + st.printLabel(); + SERIAL_CHAR(':'); SERIAL_ECHO(pwm_scale); + #if ENABLED(TMC_DEBUG) + #if HAS_TMCX1X0 || HAS_TMC220x + SERIAL_CHAR('/'); SERIAL_ECHO(data.cs_actual); + #endif + #if HAS_STALLGUARD + SERIAL_CHAR('/'); + if (data.sg_result_reasonable) + SERIAL_ECHO(data.sg_result); + else + SERIAL_CHAR('-'); + #endif + #endif + SERIAL_CHAR('|'); + if (st.error_count) SERIAL_CHAR('E'); // Error + if (data.is_ot) SERIAL_CHAR('O'); // Over-temperature + if (data.is_otpw) SERIAL_CHAR('W'); // over-temperature pre-Warning + #if ENABLED(TMC_DEBUG) + if (data.is_stall) SERIAL_CHAR('G'); // stallGuard + if (data.is_stealth) SERIAL_CHAR('T'); // stealthChop + if (data.is_standstill) SERIAL_CHAR('I'); // standstIll + #endif + if (st.flag_otpw) SERIAL_CHAR('F'); // otpw Flag + SERIAL_CHAR('|'); + if (st.otpw_count > 0) SERIAL_ECHO(st.otpw_count); + SERIAL_CHAR('\t'); + } + + #if CURRENT_STEP_DOWN > 0 + + template + void step_current_down(TMC &st) { + if (st.isEnabled()) { + const uint16_t I_rms = st.getMilliamps() - (CURRENT_STEP_DOWN); + if (I_rms > 50) { + st.rms_current(I_rms); + #if ENABLED(REPORT_CURRENT_CHANGE) + st.printLabel(); + SERIAL_ECHOLNPGM(" current decreased to ", I_rms); + #endif + } + } + } + + #else + + #define step_current_down(...) + + #endif + + template + bool monitor_tmc_driver(TMC &st, const bool need_update_error_counters, const bool need_debug_reporting) { + TMC_driver_data data = get_driver_data(st); + if (data.drv_status == 0xFFFFFFFF || data.drv_status == 0x0) return false; + + bool should_step_down = false; + + if (need_update_error_counters) { + if (data.is_ot | data.is_s2g) st.error_count++; + else if (st.error_count > 0) st.error_count--; + + #if ENABLED(STOP_ON_ERROR) + if (st.error_count >= 10) { + SERIAL_EOL(); + st.printLabel(); + report_driver_error(data); + } + #endif + + // Report if a warning was triggered + if (data.is_otpw && st.otpw_count == 0) + report_driver_otpw(st); + + #if CURRENT_STEP_DOWN > 0 + // Decrease current if is_otpw is true and driver is enabled and there's been more than 4 warnings + if (data.is_otpw && st.otpw_count > 4 && st.isEnabled()) + should_step_down = true; + #endif + + if (data.is_otpw) { + st.otpw_count++; + st.flag_otpw = true; + } + else if (st.otpw_count > 0) st.otpw_count = 0; + } + + #if ENABLED(TMC_DEBUG) + if (need_debug_reporting) report_polled_driver_data(st, data); + #endif + + return should_step_down; + } + + void monitor_tmc_drivers() { + const millis_t ms = millis(); + + // Poll TMC drivers at the configured interval + static millis_t next_poll = 0; + const bool need_update_error_counters = ELAPSED(ms, next_poll); + if (need_update_error_counters) next_poll = ms + MONITOR_DRIVER_STATUS_INTERVAL_MS; + + // Also poll at intervals for debugging + #if ENABLED(TMC_DEBUG) + static millis_t next_debug_reporting = 0; + const bool need_debug_reporting = report_tmc_status_interval && ELAPSED(ms, next_debug_reporting); + if (need_debug_reporting) next_debug_reporting = ms + report_tmc_status_interval; + #else + constexpr bool need_debug_reporting = false; + #endif + + if (need_update_error_counters || need_debug_reporting) { + + #if AXIS_IS_TMC(X) || AXIS_IS_TMC(X2) + { + bool result = false; + #if AXIS_IS_TMC(X) + if (monitor_tmc_driver(stepperX, need_update_error_counters, need_debug_reporting)) result = true; + #endif + #if AXIS_IS_TMC(X2) + if (monitor_tmc_driver(stepperX2, need_update_error_counters, need_debug_reporting)) result = true; + #endif + if (result) { + #if AXIS_IS_TMC(X) + step_current_down(stepperX); + #endif + #if AXIS_IS_TMC(X2) + step_current_down(stepperX2); + #endif + } + } + #endif + + #if AXIS_IS_TMC(Y) || AXIS_IS_TMC(Y2) + { + bool result = false; + #if AXIS_IS_TMC(Y) + if (monitor_tmc_driver(stepperY, need_update_error_counters, need_debug_reporting)) result = true; + #endif + #if AXIS_IS_TMC(Y2) + if (monitor_tmc_driver(stepperY2, need_update_error_counters, need_debug_reporting)) result = true; + #endif + if (result) { + #if AXIS_IS_TMC(Y) + step_current_down(stepperY); + #endif + #if AXIS_IS_TMC(Y2) + step_current_down(stepperY2); + #endif + } + } + #endif + + #if AXIS_IS_TMC(Z) || AXIS_IS_TMC(Z2) || AXIS_IS_TMC(Z3) || AXIS_IS_TMC(Z4) + { + bool result = false; + #if AXIS_IS_TMC(Z) + if (monitor_tmc_driver(stepperZ, need_update_error_counters, need_debug_reporting)) result = true; + #endif + #if AXIS_IS_TMC(Z2) + if (monitor_tmc_driver(stepperZ2, need_update_error_counters, need_debug_reporting)) result = true; + #endif + #if AXIS_IS_TMC(Z3) + if (monitor_tmc_driver(stepperZ3, need_update_error_counters, need_debug_reporting)) result = true; + #endif + #if AXIS_IS_TMC(Z4) + if (monitor_tmc_driver(stepperZ4, need_update_error_counters, need_debug_reporting)) result = true; + #endif + if (result) { + #if AXIS_IS_TMC(Z) + step_current_down(stepperZ); + #endif + #if AXIS_IS_TMC(Z2) + step_current_down(stepperZ2); + #endif + #if AXIS_IS_TMC(Z3) + step_current_down(stepperZ3); + #endif + #if AXIS_IS_TMC(Z4) + step_current_down(stepperZ4); + #endif + } + } + #endif + + #if AXIS_IS_TMC(I) + if (monitor_tmc_driver(stepperI, need_update_error_counters, need_debug_reporting)) + step_current_down(stepperI); + #endif + #if AXIS_IS_TMC(J) + if (monitor_tmc_driver(stepperJ, need_update_error_counters, need_debug_reporting)) + step_current_down(stepperJ); + #endif + #if AXIS_IS_TMC(K) + if (monitor_tmc_driver(stepperK, need_update_error_counters, need_debug_reporting)) + step_current_down(stepperK); + #endif + + #if AXIS_IS_TMC(E0) + (void)monitor_tmc_driver(stepperE0, need_update_error_counters, need_debug_reporting); + #endif + #if AXIS_IS_TMC(E1) + (void)monitor_tmc_driver(stepperE1, need_update_error_counters, need_debug_reporting); + #endif + #if AXIS_IS_TMC(E2) + (void)monitor_tmc_driver(stepperE2, need_update_error_counters, need_debug_reporting); + #endif + #if AXIS_IS_TMC(E3) + (void)monitor_tmc_driver(stepperE3, need_update_error_counters, need_debug_reporting); + #endif + #if AXIS_IS_TMC(E4) + (void)monitor_tmc_driver(stepperE4, need_update_error_counters, need_debug_reporting); + #endif + #if AXIS_IS_TMC(E5) + (void)monitor_tmc_driver(stepperE5, need_update_error_counters, need_debug_reporting); + #endif + #if AXIS_IS_TMC(E6) + (void)monitor_tmc_driver(stepperE6, need_update_error_counters, need_debug_reporting); + #endif + #if AXIS_IS_TMC(E7) + (void)monitor_tmc_driver(stepperE7, need_update_error_counters, need_debug_reporting); + #endif + + if (TERN0(TMC_DEBUG, need_debug_reporting)) SERIAL_EOL(); + } + } + +#endif // MONITOR_DRIVER_STATUS + +#if ENABLED(TMC_DEBUG) + + /** + * M122 [S<0|1>] [Pnnn] Enable periodic status reports + */ + #if ENABLED(MONITOR_DRIVER_STATUS) + void tmc_set_report_interval(const uint16_t update_interval) { + if ((report_tmc_status_interval = update_interval)) + SERIAL_ECHOLNPGM("axis:pwm_scale" + TERN_(HAS_STEALTHCHOP, "/curr_scale") + TERN_(HAS_STALLGUARD, "/mech_load") + "|flags|warncount" + ); + } + #endif + + enum TMC_debug_enum : char { + TMC_CODES, + TMC_UART_ADDR, + TMC_ENABLED, + TMC_CURRENT, + TMC_RMS_CURRENT, + TMC_MAX_CURRENT, + TMC_IRUN, + TMC_IHOLD, + TMC_GLOBAL_SCALER, + TMC_CS_ACTUAL, + TMC_PWM_SCALE, + TMC_PWM_SCALE_SUM, + TMC_PWM_SCALE_AUTO, + TMC_PWM_OFS_AUTO, + TMC_PWM_GRAD_AUTO, + TMC_VSENSE, + TMC_STEALTHCHOP, + TMC_MICROSTEPS, + TMC_TSTEP, + TMC_TPWMTHRS, + TMC_TPWMTHRS_MMS, + TMC_OTPW, + TMC_OTPW_TRIGGERED, + TMC_TOFF, + TMC_TBL, + TMC_HEND, + TMC_HSTRT, + TMC_SGT, + TMC_MSCNT, + TMC_INTERPOLATE + }; + enum TMC_drv_status_enum : char { + TMC_DRV_CODES, + TMC_STST, + TMC_OLB, + TMC_OLA, + TMC_S2GB, + TMC_S2GA, + TMC_DRV_OTPW, + TMC_OT, + TMC_STALLGUARD, + TMC_DRV_CS_ACTUAL, + TMC_FSACTIVE, + TMC_SG_RESULT, + TMC_DRV_STATUS_HEX, + TMC_T157, + TMC_T150, + TMC_T143, + TMC_T120, + TMC_STEALTH, + TMC_S2VSB, + TMC_S2VSA + }; + enum TMC_get_registers_enum : char { + TMC_AXIS_CODES, + TMC_GET_GCONF, + TMC_GET_IHOLD_IRUN, + TMC_GET_GSTAT, + TMC_GET_IOIN, + TMC_GET_TPOWERDOWN, + TMC_GET_TSTEP, + TMC_GET_TPWMTHRS, + TMC_GET_TCOOLTHRS, + TMC_GET_THIGH, + TMC_GET_CHOPCONF, + TMC_GET_COOLCONF, + TMC_GET_PWMCONF, + TMC_GET_PWM_SCALE, + TMC_GET_DRV_STATUS, + TMC_GET_DRVCONF, + TMC_GET_DRVCTRL, + TMC_GET_DRVSTATUS, + TMC_GET_SGCSCONF, + TMC_GET_SMARTEN + }; + + template + static void print_vsense(TMC &st) { SERIAL_ECHOF(st.vsense() ? F("1=.18") : F("0=.325")); } + + #if HAS_DRIVER(TMC2130) || HAS_DRIVER(TMC5130) + static void _tmc_status(TMC2130Stepper &st, const TMC_debug_enum i) { + switch (i) { + case TMC_PWM_SCALE: SERIAL_ECHO(st.PWM_SCALE()); break; + case TMC_SGT: SERIAL_ECHO(st.sgt()); break; + case TMC_STEALTHCHOP: serialprint_truefalse(st.en_pwm_mode()); break; + case TMC_INTERPOLATE: serialprint_truefalse(st.intpol()); break; + default: break; + } + } + #endif + #if HAS_TMCX1X0 + static void _tmc_parse_drv_status(TMC2130Stepper &st, const TMC_drv_status_enum i) { + switch (i) { + case TMC_STALLGUARD: if (st.stallguard()) SERIAL_CHAR('*'); break; + case TMC_SG_RESULT: SERIAL_ECHO(st.sg_result()); break; + case TMC_FSACTIVE: if (st.fsactive()) SERIAL_CHAR('*'); break; + case TMC_DRV_CS_ACTUAL: SERIAL_ECHO(st.cs_actual()); break; + default: break; + } + } + #endif + + #if HAS_DRIVER(TMC2160) || HAS_DRIVER(TMC5160) + template + void print_vsense(TMCMarlin &) { } + + template + void print_vsense(TMCMarlin &) { } + + static void _tmc_status(TMC2160Stepper &st, const TMC_debug_enum i) { + switch (i) { + case TMC_PWM_SCALE: SERIAL_ECHO(st.PWM_SCALE()); break; + case TMC_SGT: SERIAL_ECHO(st.sgt()); break; + case TMC_STEALTHCHOP: serialprint_truefalse(st.en_pwm_mode()); break; + case TMC_GLOBAL_SCALER: + { + uint16_t value = st.GLOBAL_SCALER(); + SERIAL_ECHO(value ? value : 256); + SERIAL_ECHOPGM("/256"); + } + break; + case TMC_INTERPOLATE: serialprint_truefalse(st.intpol()); break; + default: break; + } + } + #endif + + #if HAS_TMC220x + static void _tmc_status(TMC2208Stepper &st, const TMC_debug_enum i) { + switch (i) { + case TMC_PWM_SCALE_SUM: SERIAL_ECHO(st.pwm_scale_sum()); break; + case TMC_PWM_SCALE_AUTO: SERIAL_ECHO(st.pwm_scale_auto()); break; + case TMC_PWM_OFS_AUTO: SERIAL_ECHO(st.pwm_ofs_auto()); break; + case TMC_PWM_GRAD_AUTO: SERIAL_ECHO(st.pwm_grad_auto()); break; + case TMC_STEALTHCHOP: serialprint_truefalse(st.stealth()); break; + case TMC_INTERPOLATE: serialprint_truefalse(st.intpol()); break; + default: break; + } + } + + #if HAS_DRIVER(TMC2209) + template + static void _tmc_status(TMCMarlin &st, const TMC_debug_enum i) { + switch (i) { + case TMC_SGT: SERIAL_ECHO(st.SGTHRS()); break; + case TMC_UART_ADDR: SERIAL_ECHO(st.get_address()); break; + default: + TMC2208Stepper *parent = &st; + _tmc_status(*parent, i); + break; + } + } + #endif + + static void _tmc_parse_drv_status(TMC2208Stepper &st, const TMC_drv_status_enum i) { + switch (i) { + case TMC_T157: if (st.t157()) SERIAL_CHAR('*'); break; + case TMC_T150: if (st.t150()) SERIAL_CHAR('*'); break; + case TMC_T143: if (st.t143()) SERIAL_CHAR('*'); break; + case TMC_T120: if (st.t120()) SERIAL_CHAR('*'); break; + case TMC_S2VSA: if (st.s2vsa()) SERIAL_CHAR('*'); break; + case TMC_S2VSB: if (st.s2vsb()) SERIAL_CHAR('*'); break; + case TMC_DRV_CS_ACTUAL: SERIAL_ECHO(st.cs_actual()); break; + default: break; + } + } + + #if HAS_DRIVER(TMC2209) + static void _tmc_parse_drv_status(TMC2209Stepper &st, const TMC_drv_status_enum i) { + switch (i) { + case TMC_SG_RESULT: SERIAL_ECHO(st.SG_RESULT()); break; + default: _tmc_parse_drv_status(static_cast(st), i); break; + } + } + #endif + #endif + + #if HAS_DRIVER(TMC2660) + static void _tmc_parse_drv_status(TMC2660Stepper, const TMC_drv_status_enum) { } + static void _tmc_status(TMC2660Stepper &st, const TMC_debug_enum i) { + switch (i) { + case TMC_INTERPOLATE: serialprint_truefalse(st.intpol()); break; + default: break; + } + } + #endif + + template + static void tmc_status(TMC &st, const TMC_debug_enum i) { + SERIAL_CHAR('\t'); + switch (i) { + case TMC_CODES: st.printLabel(); break; + case TMC_ENABLED: serialprint_truefalse(st.isEnabled()); break; + case TMC_CURRENT: SERIAL_ECHO(st.getMilliamps()); break; + case TMC_RMS_CURRENT: SERIAL_ECHO(st.rms_current()); break; + case TMC_MAX_CURRENT: SERIAL_PRINT((float)st.rms_current() * 1.41, 0); break; + case TMC_IRUN: + SERIAL_ECHO(st.irun()); + SERIAL_ECHOPGM("/31"); + break; + case TMC_IHOLD: + SERIAL_ECHO(st.ihold()); + SERIAL_ECHOPGM("/31"); + break; + case TMC_CS_ACTUAL: + SERIAL_ECHO(st.cs_actual()); + SERIAL_ECHOPGM("/31"); + break; + case TMC_VSENSE: print_vsense(st); break; + case TMC_MICROSTEPS: SERIAL_ECHO(st.microsteps()); break; + case TMC_TSTEP: { + const uint32_t tstep_value = st.TSTEP(); + if (tstep_value != 0xFFFFF) SERIAL_ECHO(tstep_value); else SERIAL_ECHOPGM("max"); + } break; + #if ENABLED(HYBRID_THRESHOLD) + case TMC_TPWMTHRS: SERIAL_ECHO(uint32_t(st.TPWMTHRS())); break; + case TMC_TPWMTHRS_MMS: { + const uint32_t tpwmthrs_val = st.get_pwm_thrs(); + if (tpwmthrs_val) SERIAL_ECHO(tpwmthrs_val); else SERIAL_CHAR('-'); + } break; + #endif + case TMC_OTPW: serialprint_truefalse(st.otpw()); break; + #if ENABLED(MONITOR_DRIVER_STATUS) + case TMC_OTPW_TRIGGERED: serialprint_truefalse(st.getOTPW()); break; + #endif + case TMC_TOFF: SERIAL_ECHO(st.toff()); break; + case TMC_TBL: SERIAL_ECHO(st.blank_time()); break; + case TMC_HEND: SERIAL_ECHO(st.hysteresis_end()); break; + case TMC_HSTRT: SERIAL_ECHO(st.hysteresis_start()); break; + case TMC_MSCNT: SERIAL_ECHO(st.get_microstep_counter()); break; + default: _tmc_status(st, i); break; + } + } + + #if HAS_DRIVER(TMC2660) + template + void tmc_status(TMCMarlin &st, const TMC_debug_enum i) { + SERIAL_CHAR('\t'); + switch (i) { + case TMC_CODES: st.printLabel(); break; + case TMC_ENABLED: serialprint_truefalse(st.isEnabled()); break; + case TMC_CURRENT: SERIAL_ECHO(st.getMilliamps()); break; + case TMC_RMS_CURRENT: SERIAL_ECHO(st.rms_current()); break; + case TMC_MAX_CURRENT: SERIAL_PRINT((float)st.rms_current() * 1.41, 0); break; + case TMC_IRUN: + SERIAL_ECHO(st.cs()); + SERIAL_ECHOPGM("/31"); + break; + case TMC_VSENSE: SERIAL_ECHOF(st.vsense() ? F("1=.165") : F("0=.310")); break; + case TMC_MICROSTEPS: SERIAL_ECHO(st.microsteps()); break; + //case TMC_OTPW: serialprint_truefalse(st.otpw()); break; + //case TMC_OTPW_TRIGGERED: serialprint_truefalse(st.getOTPW()); break; + case TMC_SGT: SERIAL_ECHO(st.sgt()); break; + case TMC_TOFF: SERIAL_ECHO(st.toff()); break; + case TMC_TBL: SERIAL_ECHO(st.blank_time()); break; + case TMC_HEND: SERIAL_ECHO(st.hysteresis_end()); break; + case TMC_HSTRT: SERIAL_ECHO(st.hysteresis_start()); break; + default: break; + } + } + #endif + + template + static void tmc_parse_drv_status(TMC &st, const TMC_drv_status_enum i) { + SERIAL_CHAR('\t'); + switch (i) { + case TMC_DRV_CODES: st.printLabel(); break; + case TMC_STST: if (!st.stst()) SERIAL_CHAR('*'); break; + case TMC_OLB: if (st.olb()) SERIAL_CHAR('*'); break; + case TMC_OLA: if (st.ola()) SERIAL_CHAR('*'); break; + case TMC_S2GB: if (st.s2gb()) SERIAL_CHAR('*'); break; + case TMC_S2GA: if (st.s2ga()) SERIAL_CHAR('*'); break; + case TMC_DRV_OTPW: if (st.otpw()) SERIAL_CHAR('*'); break; + case TMC_OT: if (st.ot()) SERIAL_CHAR('*'); break; + case TMC_DRV_STATUS_HEX: { + const uint32_t drv_status = st.DRV_STATUS(); + SERIAL_CHAR('\t'); + st.printLabel(); + SERIAL_CHAR('\t'); + print_hex_long(drv_status, ':'); + if (drv_status == 0xFFFFFFFF || drv_status == 0) SERIAL_ECHOPGM("\t Bad response!"); + SERIAL_EOL(); + break; + } + default: _tmc_parse_drv_status(st, i); break; + } + } + + static void tmc_debug_loop(const TMC_debug_enum n, LOGICAL_AXIS_ARGS(const bool)) { + if (x) { + #if AXIS_IS_TMC(X) + tmc_status(stepperX, n); + #endif + #if AXIS_IS_TMC(X2) + tmc_status(stepperX2, n); + #endif + } + + if (TERN0(HAS_Y_AXIS, y)) { + #if AXIS_IS_TMC(Y) + tmc_status(stepperY, n); + #endif + #if AXIS_IS_TMC(Y2) + tmc_status(stepperY2, n); + #endif + } + + if (TERN0(HAS_Z_AXIS, z)) { + #if AXIS_IS_TMC(Z) + tmc_status(stepperZ, n); + #endif + #if AXIS_IS_TMC(Z2) + tmc_status(stepperZ2, n); + #endif + #if AXIS_IS_TMC(Z3) + tmc_status(stepperZ3, n); + #endif + #if AXIS_IS_TMC(Z4) + tmc_status(stepperZ4, n); + #endif + } + + #if AXIS_IS_TMC(I) + if (i) tmc_status(stepperI, n); + #endif + #if AXIS_IS_TMC(J) + if (j) tmc_status(stepperJ, n); + #endif + #if AXIS_IS_TMC(K) + if (k) tmc_status(stepperK, n); + #endif + + if (TERN0(HAS_EXTRUDERS, e)) { + #if AXIS_IS_TMC(E0) + tmc_status(stepperE0, n); + #endif + #if AXIS_IS_TMC(E1) + tmc_status(stepperE1, n); + #endif + #if AXIS_IS_TMC(E2) + tmc_status(stepperE2, n); + #endif + #if AXIS_IS_TMC(E3) + tmc_status(stepperE3, n); + #endif + #if AXIS_IS_TMC(E4) + tmc_status(stepperE4, n); + #endif + #if AXIS_IS_TMC(E5) + tmc_status(stepperE5, n); + #endif + #if AXIS_IS_TMC(E6) + tmc_status(stepperE6, n); + #endif + #if AXIS_IS_TMC(E7) + tmc_status(stepperE7, n); + #endif + } + + SERIAL_EOL(); + } + + static void drv_status_loop(const TMC_drv_status_enum n, LOGICAL_AXIS_ARGS(const bool)) { + if (x) { + #if AXIS_IS_TMC(X) + tmc_parse_drv_status(stepperX, n); + #endif + #if AXIS_IS_TMC(X2) + tmc_parse_drv_status(stepperX2, n); + #endif + } + + if (TERN0(HAS_Y_AXIS, y)) { + #if AXIS_IS_TMC(Y) + tmc_parse_drv_status(stepperY, n); + #endif + #if AXIS_IS_TMC(Y2) + tmc_parse_drv_status(stepperY2, n); + #endif + } + + if (TERN0(HAS_Z_AXIS, z)) { + #if AXIS_IS_TMC(Z) + tmc_parse_drv_status(stepperZ, n); + #endif + #if AXIS_IS_TMC(Z2) + tmc_parse_drv_status(stepperZ2, n); + #endif + #if AXIS_IS_TMC(Z3) + tmc_parse_drv_status(stepperZ3, n); + #endif + #if AXIS_IS_TMC(Z4) + tmc_parse_drv_status(stepperZ4, n); + #endif + } + + #if AXIS_IS_TMC(I) + if (i) tmc_parse_drv_status(stepperI, n); + #endif + #if AXIS_IS_TMC(J) + if (j) tmc_parse_drv_status(stepperJ, n); + #endif + #if AXIS_IS_TMC(K) + if (k) tmc_parse_drv_status(stepperK, n); + #endif + + if (TERN0(HAS_EXTRUDERS, e)) { + #if AXIS_IS_TMC(E0) + tmc_parse_drv_status(stepperE0, n); + #endif + #if AXIS_IS_TMC(E1) + tmc_parse_drv_status(stepperE1, n); + #endif + #if AXIS_IS_TMC(E2) + tmc_parse_drv_status(stepperE2, n); + #endif + #if AXIS_IS_TMC(E3) + tmc_parse_drv_status(stepperE3, n); + #endif + #if AXIS_IS_TMC(E4) + tmc_parse_drv_status(stepperE4, n); + #endif + #if AXIS_IS_TMC(E5) + tmc_parse_drv_status(stepperE5, n); + #endif + #if AXIS_IS_TMC(E6) + tmc_parse_drv_status(stepperE6, n); + #endif + #if AXIS_IS_TMC(E7) + tmc_parse_drv_status(stepperE7, n); + #endif + } + + SERIAL_EOL(); + } + + /** + * M122 report functions + */ + + void tmc_report_all(LOGICAL_AXIS_ARGS(const bool)) { + #define TMC_REPORT(LABEL, ITEM) do{ SERIAL_ECHOPGM(LABEL); tmc_debug_loop(ITEM, LOGICAL_AXIS_ARGS()); }while(0) + #define DRV_REPORT(LABEL, ITEM) do{ SERIAL_ECHOPGM(LABEL); drv_status_loop(ITEM, LOGICAL_AXIS_ARGS()); }while(0) + + TMC_REPORT("\t", TMC_CODES); + #if HAS_DRIVER(TMC2209) + TMC_REPORT("Address\t", TMC_UART_ADDR); + #endif + TMC_REPORT("Enabled\t", TMC_ENABLED); + TMC_REPORT("Set current", TMC_CURRENT); + TMC_REPORT("RMS current", TMC_RMS_CURRENT); + TMC_REPORT("MAX current", TMC_MAX_CURRENT); + TMC_REPORT("Run current", TMC_IRUN); + TMC_REPORT("Hold current", TMC_IHOLD); + #if HAS_DRIVER(TMC2160) || HAS_DRIVER(TMC5160) + TMC_REPORT("Global scaler", TMC_GLOBAL_SCALER); + #endif + TMC_REPORT("CS actual", TMC_CS_ACTUAL); + TMC_REPORT("PWM scale", TMC_PWM_SCALE); + #if HAS_DRIVER(TMC2130) || HAS_DRIVER(TMC2224) || HAS_DRIVER(TMC2660) || HAS_TMC220x + TMC_REPORT("vsense\t", TMC_VSENSE); + #endif + TMC_REPORT("stealthChop", TMC_STEALTHCHOP); + TMC_REPORT("msteps\t", TMC_MICROSTEPS); + TMC_REPORT("interp\t", TMC_INTERPOLATE); + TMC_REPORT("tstep\t", TMC_TSTEP); + TMC_REPORT("PWM thresh.", TMC_TPWMTHRS); + TMC_REPORT("[mm/s]\t", TMC_TPWMTHRS_MMS); + TMC_REPORT("OT prewarn", TMC_OTPW); + #if ENABLED(MONITOR_DRIVER_STATUS) + TMC_REPORT("triggered\n OTP\t", TMC_OTPW_TRIGGERED); + #endif + + #if HAS_TMC220x + TMC_REPORT("pwm scale sum", TMC_PWM_SCALE_SUM); + TMC_REPORT("pwm scale auto", TMC_PWM_SCALE_AUTO); + TMC_REPORT("pwm offset auto", TMC_PWM_OFS_AUTO); + TMC_REPORT("pwm grad auto", TMC_PWM_GRAD_AUTO); + #endif + + TMC_REPORT("off time", TMC_TOFF); + TMC_REPORT("blank time", TMC_TBL); + TMC_REPORT("hysteresis\n -end\t", TMC_HEND); + TMC_REPORT(" -start\t", TMC_HSTRT); + TMC_REPORT("Stallguard thrs", TMC_SGT); + TMC_REPORT("uStep count", TMC_MSCNT); + DRV_REPORT("DRVSTATUS", TMC_DRV_CODES); + #if HAS_TMCX1X0 || HAS_TMC220x + DRV_REPORT("sg_result", TMC_SG_RESULT); + #endif + #if HAS_TMCX1X0 + DRV_REPORT("stallguard", TMC_STALLGUARD); + DRV_REPORT("fsactive", TMC_FSACTIVE); + #endif + DRV_REPORT("stst\t", TMC_STST); + DRV_REPORT("olb\t", TMC_OLB); + DRV_REPORT("ola\t", TMC_OLA); + DRV_REPORT("s2gb\t", TMC_S2GB); + DRV_REPORT("s2ga\t", TMC_S2GA); + DRV_REPORT("otpw\t", TMC_DRV_OTPW); + DRV_REPORT("ot\t", TMC_OT); + #if HAS_TMC220x + DRV_REPORT("157C\t", TMC_T157); + DRV_REPORT("150C\t", TMC_T150); + DRV_REPORT("143C\t", TMC_T143); + DRV_REPORT("120C\t", TMC_T120); + DRV_REPORT("s2vsa\t", TMC_S2VSA); + DRV_REPORT("s2vsb\t", TMC_S2VSB); + #endif + DRV_REPORT("Driver registers:\n",TMC_DRV_STATUS_HEX); + SERIAL_EOL(); + } + + #define PRINT_TMC_REGISTER(REG_CASE) case TMC_GET_##REG_CASE: print_hex_long(st.REG_CASE(), ':'); break + + #if HAS_TMCX1X0 + static void tmc_get_ic_registers(TMC2130Stepper &st, const TMC_get_registers_enum i) { + switch (i) { + PRINT_TMC_REGISTER(TCOOLTHRS); + PRINT_TMC_REGISTER(THIGH); + PRINT_TMC_REGISTER(COOLCONF); + default: SERIAL_CHAR('\t'); break; + } + } + #endif + #if HAS_TMC220x + static void tmc_get_ic_registers(TMC2208Stepper, const TMC_get_registers_enum) { SERIAL_CHAR('\t'); } + #endif + + #if HAS_TRINAMIC_CONFIG + template + static void tmc_get_registers(TMC &st, const TMC_get_registers_enum i) { + switch (i) { + case TMC_AXIS_CODES: SERIAL_CHAR('\t'); st.printLabel(); break; + PRINT_TMC_REGISTER(GCONF); + PRINT_TMC_REGISTER(IHOLD_IRUN); + PRINT_TMC_REGISTER(GSTAT); + PRINT_TMC_REGISTER(IOIN); + PRINT_TMC_REGISTER(TPOWERDOWN); + PRINT_TMC_REGISTER(TSTEP); + PRINT_TMC_REGISTER(TPWMTHRS); + PRINT_TMC_REGISTER(CHOPCONF); + PRINT_TMC_REGISTER(PWMCONF); + PRINT_TMC_REGISTER(PWM_SCALE); + PRINT_TMC_REGISTER(DRV_STATUS); + default: tmc_get_ic_registers(st, i); break; + } + SERIAL_CHAR('\t'); + } + #endif + #if HAS_DRIVER(TMC2660) + template + static void tmc_get_registers(TMCMarlin &st, const TMC_get_registers_enum i) { + switch (i) { + case TMC_AXIS_CODES: SERIAL_CHAR('\t'); st.printLabel(); break; + PRINT_TMC_REGISTER(DRVCONF); + PRINT_TMC_REGISTER(DRVCTRL); + PRINT_TMC_REGISTER(CHOPCONF); + PRINT_TMC_REGISTER(DRVSTATUS); + PRINT_TMC_REGISTER(SGCSCONF); + PRINT_TMC_REGISTER(SMARTEN); + default: SERIAL_CHAR('\t'); break; + } + SERIAL_CHAR('\t'); + } + #endif + + static void tmc_get_registers(TMC_get_registers_enum n, LOGICAL_AXIS_ARGS(const bool)) { + if (x) { + #if AXIS_IS_TMC(X) + tmc_get_registers(stepperX, n); + #endif + #if AXIS_IS_TMC(X2) + tmc_get_registers(stepperX2, n); + #endif + } + + if (TERN0(HAS_Y_AXIS, y)) { + #if AXIS_IS_TMC(Y) + tmc_get_registers(stepperY, n); + #endif + #if AXIS_IS_TMC(Y2) + tmc_get_registers(stepperY2, n); + #endif + } + + if (TERN0(HAS_Z_AXIS, z)) { + #if AXIS_IS_TMC(Z) + tmc_get_registers(stepperZ, n); + #endif + #if AXIS_IS_TMC(Z2) + tmc_get_registers(stepperZ2, n); + #endif + #if AXIS_IS_TMC(Z3) + tmc_get_registers(stepperZ3, n); + #endif + #if AXIS_IS_TMC(Z4) + tmc_get_registers(stepperZ4, n); + #endif + } + + #if AXIS_IS_TMC(I) + if (i) tmc_get_registers(stepperI, n); + #endif + #if AXIS_IS_TMC(J) + if (j) tmc_get_registers(stepperJ, n); + #endif + #if AXIS_IS_TMC(K) + if (k) tmc_get_registers(stepperK, n); + #endif + + if (TERN0(HAS_EXTRUDERS, e)) { + #if AXIS_IS_TMC(E0) + tmc_get_registers(stepperE0, n); + #endif + #if AXIS_IS_TMC(E1) + tmc_get_registers(stepperE1, n); + #endif + #if AXIS_IS_TMC(E2) + tmc_get_registers(stepperE2, n); + #endif + #if AXIS_IS_TMC(E3) + tmc_get_registers(stepperE3, n); + #endif + #if AXIS_IS_TMC(E4) + tmc_get_registers(stepperE4, n); + #endif + #if AXIS_IS_TMC(E5) + tmc_get_registers(stepperE5, n); + #endif + #if AXIS_IS_TMC(E6) + tmc_get_registers(stepperE6, n); + #endif + #if AXIS_IS_TMC(E7) + tmc_get_registers(stepperE7, n); + #endif + } + + SERIAL_EOL(); + } + + void tmc_get_registers(LOGICAL_AXIS_ARGS(bool)) { + #define _TMC_GET_REG(LABEL, ITEM) do{ SERIAL_ECHOPGM(LABEL); tmc_get_registers(ITEM, LOGICAL_AXIS_ARGS()); }while(0) + #define TMC_GET_REG(NAME, TABS) _TMC_GET_REG(STRINGIFY(NAME) TABS, TMC_GET_##NAME) + _TMC_GET_REG("\t", TMC_AXIS_CODES); + TMC_GET_REG(GCONF, "\t\t"); + TMC_GET_REG(IHOLD_IRUN, "\t"); + TMC_GET_REG(GSTAT, "\t\t"); + TMC_GET_REG(IOIN, "\t\t"); + TMC_GET_REG(TPOWERDOWN, "\t"); + TMC_GET_REG(TSTEP, "\t\t"); + TMC_GET_REG(TPWMTHRS, "\t"); + TMC_GET_REG(TCOOLTHRS, "\t"); + TMC_GET_REG(THIGH, "\t\t"); + TMC_GET_REG(CHOPCONF, "\t"); + TMC_GET_REG(COOLCONF, "\t"); + TMC_GET_REG(PWMCONF, "\t"); + TMC_GET_REG(PWM_SCALE, "\t"); + TMC_GET_REG(DRV_STATUS, "\t"); + } + +#endif // TMC_DEBUG + +#if USE_SENSORLESS + + bool tmc_enable_stallguard(TMC2130Stepper &st) { + const bool stealthchop_was_enabled = st.en_pwm_mode(); + + st.TCOOLTHRS(0xFFFFF); + st.en_pwm_mode(false); + st.diag1_stall(true); + + return stealthchop_was_enabled; + } + void tmc_disable_stallguard(TMC2130Stepper &st, const bool restore_stealth) { + st.TCOOLTHRS(0); + st.en_pwm_mode(restore_stealth); + st.diag1_stall(false); + } + + bool tmc_enable_stallguard(TMC2209Stepper &st) { + const bool stealthchop_was_enabled = !st.en_spreadCycle(); + + st.TCOOLTHRS(0xFFFFF); + st.en_spreadCycle(false); + return stealthchop_was_enabled; + } + void tmc_disable_stallguard(TMC2209Stepper &st, const bool restore_stealth) { + st.en_spreadCycle(!restore_stealth); + st.TCOOLTHRS(0); + } + + bool tmc_enable_stallguard(TMC2660Stepper) { + // TODO + return false; + } + void tmc_disable_stallguard(TMC2660Stepper, const bool) {}; + +#endif // USE_SENSORLESS + +template +static bool test_connection(TMC &st) { + SERIAL_ECHOPGM("Testing "); + st.printLabel(); + SERIAL_ECHOPGM(" connection... "); + const uint8_t test_result = st.test_connection(); + + if (test_result > 0) SERIAL_ECHOPGM("Error: All "); + + FSTR_P stat; + switch (test_result) { + default: + case 0: stat = F("OK"); break; + case 1: stat = F("HIGH"); break; + case 2: stat = F("LOW"); break; + } + SERIAL_ECHOLNF(stat); + + return test_result; +} + +void test_tmc_connection(LOGICAL_AXIS_ARGS(const bool)) { + uint8_t axis_connection = 0; + + if (x) { + #if AXIS_IS_TMC(X) + axis_connection += test_connection(stepperX); + #endif + #if AXIS_IS_TMC(X2) + axis_connection += test_connection(stepperX2); + #endif + } + + if (TERN0(HAS_Y_AXIS, y)) { + #if AXIS_IS_TMC(Y) + axis_connection += test_connection(stepperY); + #endif + #if AXIS_IS_TMC(Y2) + axis_connection += test_connection(stepperY2); + #endif + } + + if (TERN0(HAS_Z_AXIS, z)) { + #if AXIS_IS_TMC(Z) + axis_connection += test_connection(stepperZ); + #endif + #if AXIS_IS_TMC(Z2) + axis_connection += test_connection(stepperZ2); + #endif + #if AXIS_IS_TMC(Z3) + axis_connection += test_connection(stepperZ3); + #endif + #if AXIS_IS_TMC(Z4) + axis_connection += test_connection(stepperZ4); + #endif + } + + #if AXIS_IS_TMC(I) + if (i) axis_connection += test_connection(stepperI); + #endif + #if AXIS_IS_TMC(J) + if (j) axis_connection += test_connection(stepperJ); + #endif + #if AXIS_IS_TMC(K) + if (k) axis_connection += test_connection(stepperK); + #endif + + if (TERN0(HAS_EXTRUDERS, e)) { + #if AXIS_IS_TMC(E0) + axis_connection += test_connection(stepperE0); + #endif + #if AXIS_IS_TMC(E1) + axis_connection += test_connection(stepperE1); + #endif + #if AXIS_IS_TMC(E2) + axis_connection += test_connection(stepperE2); + #endif + #if AXIS_IS_TMC(E3) + axis_connection += test_connection(stepperE3); + #endif + #if AXIS_IS_TMC(E4) + axis_connection += test_connection(stepperE4); + #endif + #if AXIS_IS_TMC(E5) + axis_connection += test_connection(stepperE5); + #endif + #if AXIS_IS_TMC(E6) + axis_connection += test_connection(stepperE6); + #endif + #if AXIS_IS_TMC(E7) + axis_connection += test_connection(stepperE7); + #endif + } + + if (axis_connection) LCD_MESSAGE(MSG_ERROR_TMC); +} + +#endif // HAS_TRINAMIC_CONFIG + +#if HAS_TMC_SPI + #define SET_CS_PIN(st) OUT_WRITE(st##_CS_PIN, HIGH) + void tmc_init_cs_pins() { + #if AXIS_HAS_SPI(X) + SET_CS_PIN(X); + #endif + #if AXIS_HAS_SPI(Y) + SET_CS_PIN(Y); + #endif + #if AXIS_HAS_SPI(Z) + SET_CS_PIN(Z); + #endif + #if AXIS_HAS_SPI(X2) + SET_CS_PIN(X2); + #endif + #if AXIS_HAS_SPI(Y2) + SET_CS_PIN(Y2); + #endif + #if AXIS_HAS_SPI(Z2) + SET_CS_PIN(Z2); + #endif + #if AXIS_HAS_SPI(Z3) + SET_CS_PIN(Z3); + #endif + #if AXIS_HAS_SPI(Z4) + SET_CS_PIN(Z4); + #endif + #if AXIS_HAS_SPI(I) + SET_CS_PIN(I); + #endif + #if AXIS_HAS_SPI(J) + SET_CS_PIN(J); + #endif + #if AXIS_HAS_SPI(K) + SET_CS_PIN(K); + #endif + #if AXIS_HAS_SPI(E0) + SET_CS_PIN(E0); + #endif + #if AXIS_HAS_SPI(E1) + SET_CS_PIN(E1); + #endif + #if AXIS_HAS_SPI(E2) + SET_CS_PIN(E2); + #endif + #if AXIS_HAS_SPI(E3) + SET_CS_PIN(E3); + #endif + #if AXIS_HAS_SPI(E4) + SET_CS_PIN(E4); + #endif + #if AXIS_HAS_SPI(E5) + SET_CS_PIN(E5); + #endif + #if AXIS_HAS_SPI(E6) + SET_CS_PIN(E6); + #endif + #if AXIS_HAS_SPI(E7) + SET_CS_PIN(E7); + #endif + } +#endif // HAS_TMC_SPI diff --git a/src/feature/tmc_util.h b/src/feature/tmc_util.h new file mode 100644 index 0000000..c10bab6 --- /dev/null +++ b/src/feature/tmc_util.h @@ -0,0 +1,389 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" +#include "../lcd/marlinui.h" + +#if HAS_TRINAMIC_CONFIG + +#include +#include "../module/planner.h" + +#define CHOPPER_DEFAULT_12V { 3, -1, 1 } +#define CHOPPER_DEFAULT_19V { 4, 1, 1 } +#define CHOPPER_DEFAULT_24V { 4, 2, 1 } +#define CHOPPER_DEFAULT_36V { 5, 2, 4 } +#define CHOPPER_PRUSAMK3_24V { 3, -2, 6 } +#define CHOPPER_MARLIN_119 { 5, 2, 3 } +#define CHOPPER_09STEP_24V { 3, -1, 5 } + +#if ENABLED(MONITOR_DRIVER_STATUS) && !defined(MONITOR_DRIVER_STATUS_INTERVAL_MS) + #define MONITOR_DRIVER_STATUS_INTERVAL_MS 500U +#endif + +constexpr uint16_t _tmc_thrs(const uint16_t msteps, const uint32_t thrs, const uint32_t spmm) { + return 12650000UL * msteps / (256 * thrs * spmm); +} + +typedef struct { + uint8_t toff; + int8_t hend; + uint8_t hstrt; +} chopper_timing_t; + +template +class TMCStorage { + protected: + // Only a child class has access to constructor => Don't create on its own! "Poor man's abstract class" + TMCStorage() {} + + public: + uint16_t val_mA = 0; + + #if ENABLED(MONITOR_DRIVER_STATUS) + uint8_t otpw_count = 0, + error_count = 0; + bool flag_otpw = false; + bool getOTPW() { return flag_otpw; } + void clear_otpw() { flag_otpw = 0; } + #endif + + uint16_t getMilliamps() { return val_mA; } + + void printLabel() { + SERIAL_CHAR(AXIS_LETTER); + if (DRIVER_ID > '0') SERIAL_CHAR(DRIVER_ID); + } + + struct { + OPTCODE(HAS_STEALTHCHOP, bool stealthChop_enabled = false) + OPTCODE(HYBRID_THRESHOLD, uint8_t hybrid_thrs = 0) + OPTCODE(USE_SENSORLESS, int16_t homing_thrs = 0) + } stored; +}; + +template +class TMCMarlin : public TMC, public TMCStorage { + public: + TMCMarlin(const uint16_t cs_pin, const float RS) : + TMC(cs_pin, RS) + {} + TMCMarlin(const uint16_t cs_pin, const float RS, const uint8_t axis_chain_index) : + TMC(cs_pin, RS, axis_chain_index) + {} + TMCMarlin(const uint16_t CS, const float RS, const uint16_t pinMOSI, const uint16_t pinMISO, const uint16_t pinSCK) : + TMC(CS, RS, pinMOSI, pinMISO, pinSCK) + {} + TMCMarlin(const uint16_t CS, const float RS, const uint16_t pinMOSI, const uint16_t pinMISO, const uint16_t pinSCK, const uint8_t axis_chain_index) : + TMC(CS, RS, pinMOSI, pinMISO, pinSCK, axis_chain_index) + {} + uint16_t rms_current() { return TMC::rms_current(); } + void rms_current(uint16_t mA) { + this->val_mA = mA; + TMC::rms_current(mA); + } + void rms_current(const uint16_t mA, const float mult) { + this->val_mA = mA; + TMC::rms_current(mA, mult); + } + uint16_t get_microstep_counter() { return TMC::MSCNT(); } + + #if HAS_STEALTHCHOP + bool get_stealthChop() { return this->en_pwm_mode(); } + bool get_stored_stealthChop() { return this->stored.stealthChop_enabled; } + void refresh_stepping_mode() { this->en_pwm_mode(this->stored.stealthChop_enabled); } + void set_stealthChop(const bool stch) { this->stored.stealthChop_enabled = stch; refresh_stepping_mode(); } + bool toggle_stepping_mode() { set_stealthChop(!this->stored.stealthChop_enabled); return get_stealthChop(); } + #endif + + void set_chopper_times(const chopper_timing_t &ct) { + TMC::toff(ct.toff); + TMC::hysteresis_end(ct.hend); + TMC::hysteresis_start(ct.hstrt); + } + + #if ENABLED(HYBRID_THRESHOLD) + uint32_t get_pwm_thrs() { + return _tmc_thrs(this->microsteps(), this->TPWMTHRS(), planner.settings.axis_steps_per_mm[AXIS_ID]); + } + void set_pwm_thrs(const uint32_t thrs) { + TMC::TPWMTHRS(_tmc_thrs(this->microsteps(), thrs, planner.settings.axis_steps_per_mm[AXIS_ID])); + TERN_(HAS_MARLINUI_MENU, this->stored.hybrid_thrs = thrs); + } + #endif + + #if USE_SENSORLESS + int16_t homing_threshold() { return TMC::sgt(); } + void homing_threshold(int16_t sgt_val) { + sgt_val = (int16_t)constrain(sgt_val, sgt_min, sgt_max); + TMC::sgt(sgt_val); + TERN_(HAS_MARLINUI_MENU, this->stored.homing_thrs = sgt_val); + } + #if ENABLED(SPI_ENDSTOPS) + bool test_stall_status(); + #endif + #endif + + #if HAS_MARLINUI_MENU + void refresh_stepper_current() { rms_current(this->val_mA); } + + #if ENABLED(HYBRID_THRESHOLD) + void refresh_hybrid_thrs() { set_pwm_thrs(this->stored.hybrid_thrs); } + #endif + #if USE_SENSORLESS + void refresh_homing_thrs() { homing_threshold(this->stored.homing_thrs); } + #endif + #endif + + static constexpr int8_t sgt_min = -64, + sgt_max = 63; +}; + +template +class TMCMarlin : public TMC2208Stepper, public TMCStorage { + public: + TMCMarlin(Stream * SerialPort, const float RS, const uint8_t) : + TMC2208Stepper(SerialPort, RS) + {} + TMCMarlin(Stream * SerialPort, const float RS, uint8_t addr, const uint16_t mul_pin1, const uint16_t mul_pin2) : + TMC2208Stepper(SerialPort, RS, addr, mul_pin1, mul_pin2) + {} + TMCMarlin(const uint16_t RX, const uint16_t TX, const float RS, const uint8_t) : + TMC2208Stepper(RX, TX, RS) + {} + + uint16_t rms_current() { return TMC2208Stepper::rms_current(); } + void rms_current(const uint16_t mA) { + this->val_mA = mA; + TMC2208Stepper::rms_current(mA); + } + void rms_current(const uint16_t mA, const float mult) { + this->val_mA = mA; + TMC2208Stepper::rms_current(mA, mult); + } + uint16_t get_microstep_counter() { return TMC2208Stepper::MSCNT(); } + + #if HAS_STEALTHCHOP + bool get_stealthChop() { return !this->en_spreadCycle(); } + bool get_stored_stealthChop() { return this->stored.stealthChop_enabled; } + void refresh_stepping_mode() { this->en_spreadCycle(!this->stored.stealthChop_enabled); } + void set_stealthChop(const bool stch) { this->stored.stealthChop_enabled = stch; refresh_stepping_mode(); } + bool toggle_stepping_mode() { set_stealthChop(!this->stored.stealthChop_enabled); return get_stealthChop(); } + #endif + + void set_chopper_times(const chopper_timing_t &ct) { + TMC2208Stepper::toff(ct.toff); + TMC2208Stepper::hysteresis_end(ct.hend); + TMC2208Stepper::hysteresis_start(ct.hstrt); + } + + #if ENABLED(HYBRID_THRESHOLD) + uint32_t get_pwm_thrs() { + return _tmc_thrs(this->microsteps(), this->TPWMTHRS(), planner.settings.axis_steps_per_mm[AXIS_ID]); + } + void set_pwm_thrs(const uint32_t thrs) { + TMC2208Stepper::TPWMTHRS(_tmc_thrs(this->microsteps(), thrs, planner.settings.axis_steps_per_mm[AXIS_ID])); + TERN_(HAS_MARLINUI_MENU, this->stored.hybrid_thrs = thrs); + } + #endif + + #if HAS_MARLINUI_MENU + void refresh_stepper_current() { rms_current(this->val_mA); } + + #if ENABLED(HYBRID_THRESHOLD) + void refresh_hybrid_thrs() { set_pwm_thrs(this->stored.hybrid_thrs); } + #endif + #endif +}; + +template +class TMCMarlin : public TMC2209Stepper, public TMCStorage { + public: + TMCMarlin(Stream * SerialPort, const float RS, const uint8_t addr) : + TMC2209Stepper(SerialPort, RS, addr) + {} + TMCMarlin(const uint16_t RX, const uint16_t TX, const float RS, const uint8_t addr) : + TMC2209Stepper(RX, TX, RS, addr) + {} + uint8_t get_address() { return slave_address; } + uint16_t rms_current() { return TMC2209Stepper::rms_current(); } + void rms_current(const uint16_t mA) { + this->val_mA = mA; + TMC2209Stepper::rms_current(mA); + } + void rms_current(const uint16_t mA, const float mult) { + this->val_mA = mA; + TMC2209Stepper::rms_current(mA, mult); + } + uint16_t get_microstep_counter() { return TMC2209Stepper::MSCNT(); } + + #if HAS_STEALTHCHOP + bool get_stealthChop() { return !this->en_spreadCycle(); } + bool get_stored_stealthChop() { return this->stored.stealthChop_enabled; } + void refresh_stepping_mode() { this->en_spreadCycle(!this->stored.stealthChop_enabled); } + void set_stealthChop(const bool stch) { this->stored.stealthChop_enabled = stch; refresh_stepping_mode(); } + bool toggle_stepping_mode() { set_stealthChop(!this->stored.stealthChop_enabled); return get_stealthChop(); } + #endif + + void set_chopper_times(const chopper_timing_t &ct) { + TMC2209Stepper::toff(ct.toff); + TMC2209Stepper::hysteresis_end(ct.hend); + TMC2209Stepper::hysteresis_start(ct.hstrt); + } + + #if ENABLED(HYBRID_THRESHOLD) + uint32_t get_pwm_thrs() { + return _tmc_thrs(this->microsteps(), this->TPWMTHRS(), planner.settings.axis_steps_per_mm[AXIS_ID]); + } + void set_pwm_thrs(const uint32_t thrs) { + TMC2209Stepper::TPWMTHRS(_tmc_thrs(this->microsteps(), thrs, planner.settings.axis_steps_per_mm[AXIS_ID])); + TERN_(HAS_MARLINUI_MENU, this->stored.hybrid_thrs = thrs); + } + #endif + #if USE_SENSORLESS + int16_t homing_threshold() { return TMC2209Stepper::SGTHRS(); } + void homing_threshold(int16_t sgt_val) { + sgt_val = (int16_t)constrain(sgt_val, sgt_min, sgt_max); + TMC2209Stepper::SGTHRS(sgt_val); + TERN_(HAS_MARLINUI_MENU, this->stored.homing_thrs = sgt_val); + } + #endif + + #if HAS_MARLINUI_MENU + void refresh_stepper_current() { rms_current(this->val_mA); } + + #if ENABLED(HYBRID_THRESHOLD) + void refresh_hybrid_thrs() { set_pwm_thrs(this->stored.hybrid_thrs); } + #endif + #if USE_SENSORLESS + void refresh_homing_thrs() { homing_threshold(this->stored.homing_thrs); } + #endif + #endif + + static constexpr uint8_t sgt_min = 0, + sgt_max = 255; +}; + +template +class TMCMarlin : public TMC2660Stepper, public TMCStorage { + public: + TMCMarlin(const uint16_t cs_pin, const float RS, const uint8_t) : + TMC2660Stepper(cs_pin, RS) + {} + TMCMarlin(const uint16_t CS, const float RS, const uint16_t pinMOSI, const uint16_t pinMISO, const uint16_t pinSCK, const uint8_t) : + TMC2660Stepper(CS, RS, pinMOSI, pinMISO, pinSCK) + {} + uint16_t rms_current() { return TMC2660Stepper::rms_current(); } + void rms_current(const uint16_t mA) { + this->val_mA = mA; + TMC2660Stepper::rms_current(mA); + } + uint16_t get_microstep_counter() { return TMC2660Stepper::mstep(); } + + void set_chopper_times(const chopper_timing_t &ct) { + TMC2660Stepper::toff(ct.toff); + TMC2660Stepper::hysteresis_end(ct.hend); + TMC2660Stepper::hysteresis_start(ct.hstrt); + } + + #if USE_SENSORLESS + int16_t homing_threshold() { return TMC2660Stepper::sgt(); } + void homing_threshold(int16_t sgt_val) { + sgt_val = (int16_t)constrain(sgt_val, sgt_min, sgt_max); + TMC2660Stepper::sgt(sgt_val); + TERN_(HAS_MARLINUI_MENU, this->stored.homing_thrs = sgt_val); + } + #endif + + #if HAS_MARLINUI_MENU + void refresh_stepper_current() { rms_current(this->val_mA); } + + #if USE_SENSORLESS + void refresh_homing_thrs() { homing_threshold(this->stored.homing_thrs); } + #endif + #endif + + static constexpr int8_t sgt_min = -64, + sgt_max = 63; +}; + +void monitor_tmc_drivers(); +void test_tmc_connection(LOGICAL_AXIS_DECL(const bool, true)); + +#if ENABLED(TMC_DEBUG) + #if ENABLED(MONITOR_DRIVER_STATUS) + void tmc_set_report_interval(const uint16_t update_interval); + #endif + void tmc_report_all(LOGICAL_AXIS_DECL(const bool, true)); + void tmc_get_registers(LOGICAL_AXIS_ARGS(const bool)); +#endif + +/** + * TMC2130-specific sensorless homing using stallGuard2. + * stallGuard2 only works when in spreadCycle mode. + * spreadCycle and stealthChop are mutually-exclusive. + * + * Defined here because of limitations with templates and headers. + */ +#if USE_SENSORLESS + + // Track enabled status of stealthChop and only re-enable where applicable + struct sensorless_t { bool NUM_AXIS_ARGS(), x2, y2, z2, z3, z4; }; + + #if ENABLED(IMPROVE_HOMING_RELIABILITY) + extern millis_t sg_guard_period; + constexpr uint16_t default_sg_guard_duration = 400; + #endif + + bool tmc_enable_stallguard(TMC2130Stepper &st); + void tmc_disable_stallguard(TMC2130Stepper &st, const bool restore_stealth); + + bool tmc_enable_stallguard(TMC2209Stepper &st); + void tmc_disable_stallguard(TMC2209Stepper &st, const bool restore_stealth); + + bool tmc_enable_stallguard(TMC2660Stepper); + void tmc_disable_stallguard(TMC2660Stepper, const bool); + + #if ENABLED(SPI_ENDSTOPS) + + template + bool TMCMarlin::test_stall_status() { + this->switchCSpin(LOW); + + // read stallGuard flag from TMC library, will handle HW and SW SPI + TMC2130_n::DRV_STATUS_t drv_status{0}; + drv_status.sr = this->DRV_STATUS(); + + this->switchCSpin(HIGH); + + return drv_status.stallGuard; + } + #endif // SPI_ENDSTOPS + +#endif // USE_SENSORLESS + +#endif // HAS_TRINAMIC_CONFIG + +#if HAS_TMC_SPI + void tmc_init_cs_pins(); +#endif diff --git a/src/feature/tramming.cpp b/src/feature/tramming.cpp new file mode 100644 index 0000000..d03f0cf --- /dev/null +++ b/src/feature/tramming.cpp @@ -0,0 +1,69 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(ASSISTED_TRAMMING) + +#include "tramming.h" + +#define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) +#include "../core/debug_out.h" + +PGMSTR(point_name_1, TRAMMING_POINT_NAME_1); +PGMSTR(point_name_2, TRAMMING_POINT_NAME_2); +PGMSTR(point_name_3, TRAMMING_POINT_NAME_3); +#ifdef TRAMMING_POINT_NAME_4 + PGMSTR(point_name_4, TRAMMING_POINT_NAME_4); + #ifdef TRAMMING_POINT_NAME_5 + PGMSTR(point_name_5, TRAMMING_POINT_NAME_5); + #ifdef TRAMMING_POINT_NAME_6 + PGMSTR(point_name_6, TRAMMING_POINT_NAME_6); + #endif + #endif +#endif + +PGM_P const tramming_point_name[] PROGMEM = { + point_name_1, point_name_2, point_name_3 + #ifdef TRAMMING_POINT_NAME_4 + , point_name_4 + #ifdef TRAMMING_POINT_NAME_5 + , point_name_5 + #ifdef TRAMMING_POINT_NAME_6 + , point_name_6 + #endif + #endif + #endif +}; + +#ifdef ASSISTED_TRAMMING_WAIT_POSITION + + // Move to the defined wait position + void move_to_tramming_wait_pos() { + constexpr xyz_pos_t wait_pos = ASSISTED_TRAMMING_WAIT_POSITION; + if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Moving away"); + do_blocking_move_to(wait_pos, XY_PROBE_FEEDRATE_MM_S); + } + +#endif + +#endif // ASSISTED_TRAMMING diff --git a/src/feature/tramming.h b/src/feature/tramming.h new file mode 100644 index 0000000..925659e --- /dev/null +++ b/src/feature/tramming.h @@ -0,0 +1,78 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfig.h" +#include "../module/probe.h" + +#if !WITHIN(TRAMMING_SCREW_THREAD, 30, 51) || TRAMMING_SCREW_THREAD % 10 > 1 + #error "TRAMMING_SCREW_THREAD must be equal to 30, 31, 40, 41, 50, or 51." +#endif + +constexpr xy_pos_t tramming_points[] = TRAMMING_POINT_XY; + +#define G35_PROBE_COUNT COUNT(tramming_points) +static_assert(WITHIN(G35_PROBE_COUNT, 3, 6), "TRAMMING_POINT_XY requires between 3 and 6 XY positions."); + +#define VALIDATE_TRAMMING_POINT(N) static_assert(N >= G35_PROBE_COUNT || Probe::build_time::can_reach(tramming_points[N]), \ + "TRAMMING_POINT_XY point " STRINGIFY(N) " is not reachable with the default NOZZLE_TO_PROBE offset and PROBING_MARGIN.") +VALIDATE_TRAMMING_POINT(0); VALIDATE_TRAMMING_POINT(1); VALIDATE_TRAMMING_POINT(2); VALIDATE_TRAMMING_POINT(3); VALIDATE_TRAMMING_POINT(4); VALIDATE_TRAMMING_POINT(5); + +extern const char point_name_1[], point_name_2[], point_name_3[] + #ifdef TRAMMING_POINT_NAME_4 + , point_name_4[] + #ifdef TRAMMING_POINT_NAME_5 + , point_name_5[] + #ifdef TRAMMING_POINT_NAME_6 + , point_name_6[] + #endif + #endif + #endif +; + +#define _NR_TRAM_NAMES 2 +#ifdef TRAMMING_POINT_NAME_3 + #undef _NR_TRAM_NAMES + #define _NR_TRAM_NAMES 3 + #ifdef TRAMMING_POINT_NAME_4 + #undef _NR_TRAM_NAMES + #define _NR_TRAM_NAMES 4 + #ifdef TRAMMING_POINT_NAME_5 + #undef _NR_TRAM_NAMES + #define _NR_TRAM_NAMES 5 + #ifdef TRAMMING_POINT_NAME_6 + #undef _NR_TRAM_NAMES + #define _NR_TRAM_NAMES 6 + #endif + #endif + #endif +#endif +static_assert(_NR_TRAM_NAMES >= G35_PROBE_COUNT, "Define enough TRAMMING_POINT_NAME_s for all TRAMMING_POINT_XY entries."); +#undef _NR_TRAM_NAMES + +extern PGM_P const tramming_point_name[]; + +#ifdef ASSISTED_TRAMMING_WAIT_POSITION + void move_to_tramming_wait_pos(); +#else + inline void move_to_tramming_wait_pos() {} +#endif diff --git a/src/feature/twibus.cpp b/src/feature/twibus.cpp new file mode 100644 index 0000000..9aec6b0 --- /dev/null +++ b/src/feature/twibus.cpp @@ -0,0 +1,237 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include "../inc/MarlinConfig.h" + +#if ENABLED(EXPERIMENTAL_I2CBUS) + +#include "twibus.h" + +#include + +#include "../libs/hex_print.h" + +TWIBus i2c; + +TWIBus::TWIBus() { + #if I2C_SLAVE_ADDRESS == 0 + + #if PINS_EXIST(I2C_SCL, I2C_SDA) && DISABLED(SOFT_I2C_EEPROM) + Wire.setSDA(pin_t(I2C_SDA_PIN)); + Wire.setSCL(pin_t(I2C_SCL_PIN)); + #endif + + Wire.begin(); // No address joins the BUS as the master + + #else + + Wire.begin(I2C_SLAVE_ADDRESS); // Join the bus as a slave + + #endif + reset(); +} + +void TWIBus::reset() { + buffer_s = 0; + buffer[0] = 0x00; +} + +void TWIBus::address(const uint8_t adr) { + if (!WITHIN(adr, 8, 127)) + SERIAL_ECHO_MSG("Bad I2C address (8-127)"); + + addr = adr; + + debug(F("address"), adr); +} + +void TWIBus::addbyte(const char c) { + if (buffer_s >= COUNT(buffer)) return; + buffer[buffer_s++] = c; + debug(F("addbyte"), c); +} + +void TWIBus::addbytes(char src[], uint8_t bytes) { + debug(F("addbytes"), bytes); + while (bytes--) addbyte(*src++); +} + +void TWIBus::addstring(char str[]) { + debug(F("addstring"), str); + while (char c = *str++) addbyte(c); +} + +void TWIBus::send() { + debug(F("send"), addr); + + Wire.beginTransmission(I2C_ADDRESS(addr)); + Wire.write(buffer, buffer_s); + Wire.endTransmission(); + + reset(); +} + +// static +void TWIBus::echoprefix(uint8_t bytes, FSTR_P const pref, uint8_t adr) { + SERIAL_ECHO_START(); + SERIAL_ECHOF(pref); + SERIAL_ECHOPGM(": from:", adr, " bytes:", bytes, " data:"); +} + +// static +void TWIBus::echodata(uint8_t bytes, FSTR_P const pref, uint8_t adr, const uint8_t style/*=0*/) { + union TwoBytesToInt16 { uint8_t bytes[2]; int16_t integervalue; }; + TwoBytesToInt16 ConversionUnion; + + echoprefix(bytes, pref, adr); + + while (bytes-- && Wire.available()) { + int value = Wire.read(); + switch (style) { + + // Style 1, HEX DUMP + case 1: + SERIAL_CHAR(hex_nybble((value & 0xF0) >> 4)); + SERIAL_CHAR(hex_nybble(value & 0x0F)); + if (bytes) SERIAL_CHAR(' '); + break; + + // Style 2, signed two byte integer (int16) + case 2: + if (bytes == 1) + ConversionUnion.bytes[1] = (uint8_t)value; + else if (bytes == 0) { + ConversionUnion.bytes[0] = (uint8_t)value; + // Output value in base 10 (standard decimal) + SERIAL_ECHO(ConversionUnion.integervalue); + } + break; + + // Style 3, unsigned byte, base 10 (uint8) + case 3: + SERIAL_ECHO(value); + if (bytes) SERIAL_CHAR(' '); + break; + + // Default style (zero), raw serial output + default: + // This can cause issues with some serial consoles, Pronterface is an example where things go wrong + SERIAL_CHAR(value); + break; + } + } + + SERIAL_EOL(); +} + +void TWIBus::echobuffer(FSTR_P const prefix, uint8_t adr) { + echoprefix(buffer_s, prefix, adr); + LOOP_L_N(i, buffer_s) SERIAL_CHAR(buffer[i]); + SERIAL_EOL(); +} + +bool TWIBus::request(const uint8_t bytes) { + if (!addr) return false; + + debug(F("request"), bytes); + + // requestFrom() is a blocking function + if (Wire.requestFrom(I2C_ADDRESS(addr), bytes) == 0) { + debug(F("request fail"), I2C_ADDRESS(addr)); + return false; + } + + return true; +} + +void TWIBus::relay(const uint8_t bytes, const uint8_t style/*=0*/) { + debug(F("relay"), bytes); + + if (request(bytes)) + echodata(bytes, F("i2c-reply"), addr, style); +} + +uint8_t TWIBus::capture(char *dst, const uint8_t bytes) { + reset(); + uint8_t count = 0; + while (count < bytes && Wire.available()) + dst[count++] = Wire.read(); + + debug(F("capture"), count); + + return count; +} + +// static +void TWIBus::flush() { + while (Wire.available()) Wire.read(); +} + +#if I2C_SLAVE_ADDRESS > 0 + + void TWIBus::receive(uint8_t bytes) { + debug(F("receive"), bytes); + echodata(bytes, F("i2c-receive"), 0); + } + + void TWIBus::reply(char str[]/*=nullptr*/) { + debug(F("reply"), str); + + if (str) { + reset(); + addstring(str); + } + + Wire.write(buffer, buffer_s); + + reset(); + } + + void i2c_on_receive(int bytes) { // just echo all bytes received to serial + i2c.receive(bytes); + } + + void i2c_on_request() { // just send dummy data for now + i2c.reply("Hello World!\n"); + } + +#endif + +#if ENABLED(DEBUG_TWIBUS) + + // static + void TWIBus::prefix(FSTR_P const func) { + SERIAL_ECHOPGM("TWIBus::", func, ": "); + } + void TWIBus::debug(FSTR_P const func, uint32_t adr) { + if (DEBUGGING(INFO)) { prefix(func); SERIAL_ECHOLN(adr); } + } + void TWIBus::debug(FSTR_P const func, char c) { + if (DEBUGGING(INFO)) { prefix(func); SERIAL_ECHOLN(c); } + } + void TWIBus::debug(FSTR_P const func, char str[]) { + if (DEBUGGING(INFO)) { prefix(func); SERIAL_ECHOLN(str); } + } + +#endif + +#endif // EXPERIMENTAL_I2CBUS diff --git a/src/feature/twibus.h b/src/feature/twibus.h new file mode 100644 index 0000000..806e2a1 --- /dev/null +++ b/src/feature/twibus.h @@ -0,0 +1,254 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../core/macros.h" + +#include + +// Print debug messages with M111 S2 (Uses 236 bytes of PROGMEM) +//#define DEBUG_TWIBUS + +typedef void (*twiReceiveFunc_t)(int bytes); +typedef void (*twiRequestFunc_t)(); + +/** + * For a light i2c protocol that runs on two boards running Marlin see: + * See https://github.com/MarlinFirmware/Marlin/issues/4776#issuecomment-246262879 + */ +#if I2C_SLAVE_ADDRESS > 0 + + void i2c_on_receive(int bytes); // Demo i2c onReceive handler + void i2c_on_request(); // Demo i2c onRequest handler + +#endif + +#define TWIBUS_BUFFER_SIZE 32 + +/** + * TWIBUS class + * + * This class implements a wrapper around the two wire (I2C) bus, allowing + * Marlin to send and request data from any slave device on the bus. + * + * The two main consumers of this class are M260 and M261. M260 provides a way + * to send an I2C packet to a device (no repeated starts) by caching up to 32 + * bytes in a buffer and then sending the buffer. + * M261 requests data from a device. The received data is relayed to serial out + * for the host to interpret. + * + * For more information see + * - https://marlinfw.org/docs/gcode/M260.html + * - https://marlinfw.org/docs/gcode/M261.html + */ +class TWIBus { + private: + /** + * @brief Number of bytes on buffer + * @description Number of bytes in the buffer waiting to be flushed to the bus + */ + uint8_t buffer_s = 0; + + /** + * @brief Internal buffer + * @details A fixed buffer. TWI commands can be no longer than this. + */ + uint8_t buffer[TWIBUS_BUFFER_SIZE]; + + + public: + /** + * @brief Target device address + * @description The target device address. Persists until changed. + */ + uint8_t addr = 0; + + /** + * @brief Class constructor + * @details Initialize the TWI bus and clear the buffer + */ + TWIBus(); + + /** + * @brief Reset the buffer + * @details Set the buffer to a known-empty state + */ + void reset(); + + /** + * @brief Send the buffer data to the bus + * @details Flush the buffer to the target address + */ + void send(); + + /** + * @brief Add one byte to the buffer + * @details Add a byte to the end of the buffer. + * Silently fails if the buffer is full. + * + * @param c a data byte + */ + void addbyte(const char c); + + /** + * @brief Add some bytes to the buffer + * @details Add bytes to the end of the buffer. + * Concatenates at the buffer size. + * + * @param src source data address + * @param bytes the number of bytes to add + */ + void addbytes(char src[], uint8_t bytes); + + /** + * @brief Add a null-terminated string to the buffer + * @details Add bytes to the end of the buffer up to a nul. + * Concatenates at the buffer size. + * + * @param str source string address + */ + void addstring(char str[]); + + /** + * @brief Set the target slave address + * @details The target slave address for sending the full packet + * + * @param adr 7-bit integer address + */ + void address(const uint8_t adr); + + /** + * @brief Prefix for echo to serial + * @details Echo a label, length, address, and "data:" + * + * @param bytes the number of bytes to request + */ + static void echoprefix(uint8_t bytes, FSTR_P const prefix, uint8_t adr); + + /** + * @brief Echo data on the bus to serial + * @details Echo some number of bytes from the bus + * to serial in a parser-friendly format. + * + * @param bytes the number of bytes to request + * @param style Output format for the bytes, 0 = Raw byte [default], 1 = Hex characters, 2 = uint16_t + */ + static void echodata(uint8_t bytes, FSTR_P const prefix, uint8_t adr, const uint8_t style=0); + + /** + * @brief Echo data in the buffer to serial + * @details Echo the entire buffer to serial + * to serial in a parser-friendly format. + * + * @param bytes the number of bytes to request + */ + void echobuffer(FSTR_P const prefix, uint8_t adr); + + /** + * @brief Request data from the slave device and wait. + * @details Request a number of bytes from a slave device. + * Wait for the data to arrive, and return true + * on success. + * + * @param bytes the number of bytes to request + * @return status of the request: true=success, false=fail + */ + bool request(const uint8_t bytes); + + /** + * @brief Capture data from the bus into the buffer. + * @details Capture data after a request has succeeded. + * + * @param bytes the number of bytes to request + * @return the number of bytes captured to the buffer + */ + uint8_t capture(char *dst, const uint8_t bytes); + + /** + * @brief Flush the i2c bus. + * @details Get all bytes on the bus and throw them away. + */ + static void flush(); + + /** + * @brief Request data from the slave device, echo to serial. + * @details Request a number of bytes from a slave device and output + * the returned data to serial in a parser-friendly format. + * @style Output format for the bytes, 0 = raw byte [default], 1 = Hex characters, 2 = uint16_t + * + * @param bytes the number of bytes to request + */ + void relay(const uint8_t bytes, const uint8_t style=0); + + #if I2C_SLAVE_ADDRESS > 0 + + /** + * @brief Register a slave receive handler + * @details Set a handler to receive data addressed to us + * + * @param handler A function to handle receiving bytes + */ + inline void onReceive(const twiReceiveFunc_t handler) { Wire.onReceive(handler); } + + /** + * @brief Register a slave request handler + * @details Set a handler to send data requested from us + * + * @param handler A function to handle receiving bytes + */ + inline void onRequest(const twiRequestFunc_t handler) { Wire.onRequest(handler); } + + /** + * @brief Default handler to receive + * @details Receive bytes sent to our slave address + * and simply echo them to serial. + */ + void receive(uint8_t bytes); + + /** + * @brief Send a reply to the bus + * @details Send the buffer and clear it. + * If a string is passed, write it into the buffer first. + */ + void reply(char str[]=nullptr); + inline void reply(const char str[]) { reply((char*)str); } + + #endif + + #if ENABLED(DEBUG_TWIBUS) + /** + * @brief Prints a debug message + * @details Prints a simple debug message "TWIBus::function: value" + */ + static void prefix(FSTR_P const func); + static void debug(FSTR_P const func, uint32_t adr); + static void debug(FSTR_P const func, char c); + static void debug(FSTR_P const func, char adr[]); + #else + static void debug(FSTR_P const, uint32_t) {} + static void debug(FSTR_P const, char) {} + static void debug(FSTR_P const, char[]) {} + #endif + static void debug(FSTR_P const func, uint8_t v) { debug(func, (uint32_t)v); } +}; + +extern TWIBus i2c; diff --git a/src/feature/x_twist.cpp b/src/feature/x_twist.cpp new file mode 100644 index 0000000..b5ad25c --- /dev/null +++ b/src/feature/x_twist.cpp @@ -0,0 +1,67 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "../inc/MarlinConfig.h" + +#if ENABLED(X_AXIS_TWIST_COMPENSATION) + +#include "x_twist.h" +#include "../module/probe.h" + +XATC xatc; + +bool XATC::enabled; +float XATC::spacing, XATC::start; +xatc_array_t XATC::z_offset; // Initialized by settings.load() + +void XATC::reset() { + constexpr float xzo[] = XATC_Z_OFFSETS; + static_assert(COUNT(xzo) == XATC_MAX_POINTS, "XATC_Z_OFFSETS is the wrong size."); + COPY(z_offset, xzo); + start = probe.min_x(); + spacing = (probe.max_x() - start) / (XATC_MAX_POINTS - 1); + enabled = true; +} + +void XATC::print_points() { + SERIAL_ECHOLNPGM(" X-Twist Correction:"); + LOOP_L_N(x, XATC_MAX_POINTS) { + SERIAL_CHAR(' '); + if (!isnan(z_offset[x])) + serial_offset(z_offset[x]); + else + LOOP_L_N(i, 6) SERIAL_CHAR(i ? '=' : ' '); + } + SERIAL_EOL(); +} + +float lerp(const_float_t t, const_float_t a, const_float_t b) { return a + t * (b - a); } + +float XATC::compensation(const xy_pos_t &raw) { + if (!enabled) return 0; + if (NEAR_ZERO(spacing)) return 0; + float t = (raw.x - start) / spacing; + const int i = constrain(FLOOR(t), 0, XATC_MAX_POINTS - 2); + t -= i; + return lerp(t, z_offset[i], z_offset[i + 1]); +} + +#endif // X_AXIS_TWIST_COMPENSATION diff --git a/src/feature/x_twist.h b/src/feature/x_twist.h new file mode 100644 index 0000000..6a2ff27 --- /dev/null +++ b/src/feature/x_twist.h @@ -0,0 +1,40 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +#include "../inc/MarlinConfigPre.h" + +typedef float xatc_array_t[XATC_MAX_POINTS]; + +class XATC { + static bool enabled; +public: + static float spacing, start; + static xatc_array_t z_offset; + + static void reset(); + static void set_enabled(const bool ena) { enabled = ena; } + static float compensation(const xy_pos_t &raw); + static void print_points(); +}; + +extern XATC xatc; diff --git a/src/feature/z_stepper_align.cpp b/src/feature/z_stepper_align.cpp new file mode 100644 index 0000000..9dba21d --- /dev/null +++ b/src/feature/z_stepper_align.cpp @@ -0,0 +1,121 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * feature/z_stepper_align.cpp + */ + +#include "../inc/MarlinConfigPre.h" + +#if ENABLED(Z_STEPPER_AUTO_ALIGN) + +#include "z_stepper_align.h" +#include "../module/probe.h" + +ZStepperAlign z_stepper_align; + +xy_pos_t ZStepperAlign::xy[NUM_Z_STEPPERS]; + +#if HAS_Z_STEPPER_ALIGN_STEPPER_XY + xy_pos_t ZStepperAlign::stepper_xy[NUM_Z_STEPPERS]; +#endif + +void ZStepperAlign::reset_to_default() { + #ifdef Z_STEPPER_ALIGN_XY + + constexpr xy_pos_t xy_init[] = Z_STEPPER_ALIGN_XY; + static_assert(COUNT(xy_init) == NUM_Z_STEPPERS, + "Z_STEPPER_ALIGN_XY requires " + #if NUM_Z_STEPPERS == 4 + "four {X,Y} entries (Z, Z2, Z3, and Z4)." + #elif NUM_Z_STEPPERS == 3 + "three {X,Y} entries (Z, Z2, and Z3)." + #else + "two {X,Y} entries (Z and Z2)." + #endif + ); + + #define VALIDATE_ALIGN_POINT(N) static_assert(N >= NUM_Z_STEPPERS || Probe::build_time::can_reach(xy_init[N]), \ + "Z_STEPPER_ALIGN_XY point " STRINGIFY(N) " is not reachable with the default NOZZLE_TO_PROBE offset and PROBING_MARGIN.") + VALIDATE_ALIGN_POINT(0); VALIDATE_ALIGN_POINT(1); VALIDATE_ALIGN_POINT(2); VALIDATE_ALIGN_POINT(3); + + #else // !Z_STEPPER_ALIGN_XY + + const xy_pos_t xy_init[] = { + #if NUM_Z_STEPPERS >= 3 // First probe point... + #if !Z_STEPPERS_ORIENTATION + { probe.min_x(), probe.min_y() }, // SW + #elif Z_STEPPERS_ORIENTATION == 1 + { probe.min_x(), probe.max_y() }, // NW + #elif Z_STEPPERS_ORIENTATION == 2 + { probe.max_x(), probe.max_y() }, // NE + #elif Z_STEPPERS_ORIENTATION == 3 + { probe.max_x(), probe.min_y() }, // SE + #else + #error "Z_STEPPERS_ORIENTATION must be from 0 to 3 (first point SW, NW, NE, SE)." + #endif + #if NUM_Z_STEPPERS == 4 // 3 more points... + #if !Z_STEPPERS_ORIENTATION + { probe.min_x(), probe.max_y() }, { probe.max_x(), probe.max_y() }, { probe.max_x(), probe.min_y() } // SW + #elif Z_STEPPERS_ORIENTATION == 1 + { probe.max_x(), probe.max_y() }, { probe.max_x(), probe.min_y() }, { probe.min_x(), probe.min_y() } // NW + #elif Z_STEPPERS_ORIENTATION == 2 + { probe.max_x(), probe.min_y() }, { probe.min_x(), probe.min_y() }, { probe.min_x(), probe.max_y() } // NE + #elif Z_STEPPERS_ORIENTATION == 3 + { probe.min_x(), probe.min_y() }, { probe.min_x(), probe.max_y() }, { probe.max_x(), probe.max_y() } // SE + #endif + #elif !Z_STEPPERS_ORIENTATION // or 2 more points... + { probe.max_x(), probe.min_y() }, { X_CENTER, probe.max_y() } // SW + #elif Z_STEPPERS_ORIENTATION == 1 + { probe.min_x(), probe.min_y() }, { probe.max_x(), Y_CENTER } // NW + #elif Z_STEPPERS_ORIENTATION == 2 + { probe.min_x(), probe.max_y() }, { X_CENTER, probe.min_y() } // NE + #elif Z_STEPPERS_ORIENTATION == 3 + { probe.max_x(), probe.max_y() }, { probe.min_x(), Y_CENTER } // SE + #endif + #elif Z_STEPPERS_ORIENTATION + { X_CENTER, probe.min_y() }, { X_CENTER, probe.max_y() } + #else + { probe.min_x(), Y_CENTER }, { probe.max_x(), Y_CENTER } + #endif + }; + + #endif // !Z_STEPPER_ALIGN_XY + + COPY(xy, xy_init); + + #if HAS_Z_STEPPER_ALIGN_STEPPER_XY + constexpr xy_pos_t stepper_xy_init[] = Z_STEPPER_ALIGN_STEPPER_XY; + static_assert( + COUNT(stepper_xy_init) == NUM_Z_STEPPERS, + "Z_STEPPER_ALIGN_STEPPER_XY requires " + #if NUM_Z_STEPPERS == 4 + "four {X,Y} entries (Z, Z2, Z3, and Z4)." + #elif NUM_Z_STEPPERS == 3 + "three {X,Y} entries (Z, Z2, and Z3)." + #endif + ); + COPY(stepper_xy, stepper_xy_init); + #endif +} + +#endif // Z_STEPPER_AUTO_ALIGN diff --git a/src/feature/z_stepper_align.h b/src/feature/z_stepper_align.h new file mode 100644 index 0000000..f3f9abb --- /dev/null +++ b/src/feature/z_stepper_align.h @@ -0,0 +1,41 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#pragma once + +/** + * feature/z_stepper_align.h + */ + +#include "../inc/MarlinConfig.h" + +class ZStepperAlign { + public: + static xy_pos_t xy[NUM_Z_STEPPERS]; + + #if HAS_Z_STEPPER_ALIGN_STEPPER_XY + static xy_pos_t stepper_xy[NUM_Z_STEPPERS]; + #endif + + static void reset_to_default(); +}; + +extern ZStepperAlign z_stepper_align;