src folder

This commit is contained in:
Malte Reents 2024-05-19 11:42:02 +02:00
parent b59a837d9d
commit 7930813118
143 changed files with 27244 additions and 0 deletions

475
src/core/boards.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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)

39
src/core/bug_on.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

120
src/core/debug_out.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
//
// 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

49
src/core/debug_section.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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);
}
};

203
src/core/drivers.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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))

564
src/core/language.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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<index> 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<seg-per-sec>"
#define STR_DELTA_SETTINGS "Delta (L<diagonal-rod> R<radius> H<height> S<seg-per-sec> XYZ<tower-angle-trim> ABC<rod-trim>)"
#define STR_SCARA_SETTINGS "SCARA"
#define STR_POLARGRAPH_SETTINGS "Polargraph"
#define STR_SCARA_P_T_Z "P<theta-psi-offset> T<theta-offset> Z<home-offset>"
#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<print-accel> R<retract-accel> T<travel-accel>)"
#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<length> F<feedrate> Z<lift>)"
#define STR_RECOVER_S_F "Recover (S<length> F<feedrate>)"
#define STR_AUTO_RETRACT_S "Auto-Retract (S<enable>)"
#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

720
src/core/macros.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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 <class V, class N> static constexpr void NOLESS(V& v, const N n) {
if (n > v) v = n;
}
template <class V, class N> static constexpr void NOMORE(V& v, const N n) {
if (n < v) v = n;
}
template <class V, class N1, class N2> 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' : '<nul>'
#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)' : '<nul>'
#define MINUS_TERN0(O,A) _TERN(_ENA_1(O),,- (A)) // OPTION ? '- (A)' : '<nul>'
#define SUM_TERN(O,B,A) ((B) PLUS_TERN0(O,A)) // ((B) (OPTION ? '+ (A)' : '<nul>'))
#define DIFF_TERN(O,B,A) ((B) MINUS_TERN0(O,A)) // ((B) (OPTION ? '- (A)' : '<nul>'))
#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 <class T> 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 <class L, class R> static constexpr auto _MIN(const L lhs, const R rhs) -> decltype(lhs + rhs) {
return lhs < rhs ? lhs : rhs;
}
template <class L, class R> static constexpr auto _MAX(const L lhs, const R rhs) -> decltype(lhs + rhs) {
return lhs > rhs ? lhs : rhs;
}
template<class T, class ... Ts> static constexpr const T _MIN(T V, Ts... Vs) { return _MIN(V, _MIN(Vs...)); }
template<class T, class ... Ts> 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<T>(static_cast<int>(x) & static_cast<int>(y)); } \
FORCE_INLINE constexpr T operator|(T x, T y) { return static_cast<T>(static_cast<int>(x) | static_cast<int>(y)); } \
FORCE_INLINE constexpr T operator^(T x, T y) { return static_cast<T>(static_cast<int>(x) ^ static_cast<int>(y)); } \
FORCE_INLINE constexpr T operator~(T x) { return static_cast<T>(~static_cast<int>(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. <type_traits> is not available on all platform
namespace Private {
template<bool, typename _Tp = void> struct enable_if { };
template<typename _Tp> struct enable_if<true, _Tp> { typedef _Tp type; };
template<typename T, typename U> struct is_same { enum { value = false }; };
template<typename T> struct is_same<T, T> { enum { value = true }; };
template <typename T, typename ... Args> struct first_type_of { typedef T type; };
template <typename T> struct first_type_of<T> { 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<Type> structure containing 'value' set to true if the member exists
#define HAS_MEMBER_IMPL(Member) \
namespace Private { \
template <typename Type, typename Yes=char, typename No=long> struct HasMember_ ## Member { \
template <typename C> static Yes& test( decltype(&C::Member) ) ; \
template <typename C> static No& test(...); \
enum { value = sizeof(test<Type>(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 <typename T, typename ... Args> FORCE_INLINE typename enable_if<HasMember_ ## Method <T>::value, Return>::type Call_ ## Method(T * t, Args... a) { return static_cast<Return>(t->Method(a...)); } \
_UNUSED static Return Call_ ## Method(...) { return __VA_ARGS__; } \
}
#define CALL_IF_EXISTS(Return, That, Method, ...) \
static_cast<Return>(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 <typename T>
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))

33
src/core/millis_t.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
#include <stdint.h>
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))

93
src/core/multi_language.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

110
src/core/serial.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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();
}

374
src/core/serial.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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<decltype(_SERIAL_LEAF_1)> 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<decltype(MYSERIAL2)> 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<decltype(_SERIAL_LEAF_2)> 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<decltype(_SERIAL_LEAF_3)> 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 <typename ... Args>
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 <typename T>
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 <typename T>
void SERIAL_ECHOLN(T x) { SERIAL_IMPL.println(x); }
// SERIAL_PRINT works like SERIAL_ECHO but also takes the numeric base
template <typename T, typename U>
void SERIAL_PRINT(T x, U y) { SERIAL_IMPL.print(x, y); }
template <typename T>
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 <typename T>
void SERIAL_ECHOLIST_IMPL(T && t) { SERIAL_IMPL.print(t); }
template <typename T, typename ... Args>
void SERIAL_ECHOLIST_IMPL(T && t, Args && ... args) {
SERIAL_IMPL.print(t);
serial_print(F(", "));
SERIAL_ECHOLIST_IMPL(args...);
}
template <typename ... Args>
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 <typename ... Args>
void SERIAL_ECHOLIST(FSTR_P const fstr, Args && ... args) {
serial_print(fstr);
typename Private::first_type_of<Args...>::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 <typename T>
inline void serial_echopair_P(PGM_P const pstr, T v) { serial_print_P(pstr); SERIAL_ECHO(v); }
// Add a newline.
template <typename T>
inline void serial_echolnpair_P(PGM_P const pstr, T v) { serial_echopair_P(pstr, v); SERIAL_EOL(); }
// Catch-all for __FlashStringHelper *
template <typename T>
inline void serial_echopair(FSTR_P const fstr, T v) { serial_echopair_P(FTOP(fstr), v); }
// Add a newline to the serial output
template <typename T>
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

258
src/core/serial_base.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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 <class Child>
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<Child*>(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<const Child*>(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 <typename T>
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 <typename T>
void println(T c, PrintBase base) { print(c, base); println(); }
template <typename T>
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.

308
src/core/serial_hook.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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 <class SerialT>
struct BaseSerial : public SerialBase< BaseSerial<SerialT> >, public SerialT {
typedef SerialBase< BaseSerial<SerialT> > 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<SerialT*>(this), connected);; }
void flushTX() { CALL_IF_EXISTS(void, static_cast<SerialT*>(this), flushTX); }
SerialFeature features(serial_index_t index) const { return CALL_IF_EXISTS(SerialFeature, static_cast<const SerialT*>(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 <typename... Args>
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 <class SerialT>
struct ConditionalSerial : public SerialBase< ConditionalSerial<SerialT> > {
typedef SerialBase< ConditionalSerial<SerialT> > 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 <class SerialT>
struct ForwardSerial : public SerialBase< ForwardSerial<SerialT> > {
typedef SerialBase< ForwardSerial<SerialT> > 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<SerialT>::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 <class SerialT>
struct RuntimeSerial : public SerialBase< RuntimeSerial<SerialT> >, public SerialT {
typedef SerialBase< RuntimeSerial<SerialT> > 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<SerialT>::value
? CALL_IF_EXISTS(bool, static_cast<SerialT*>(this), connected)
: static_cast<SerialT*>(this)->operator bool();
}
void flushTX() { CALL_IF_EXISTS(void, static_cast<SerialT*>(this), flushTX); }
// Append Hookable for this class
SerialFeature features(serial_index_t index) const { return SerialFeature::Hookable | CALL_IF_EXISTS(SerialFeature, static_cast<const SerialT*>(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 <typename... Args>
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

743
src/core/types.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
#include <math.h>
#include <stddef.h>
#include "../inc/MarlinConfigPre.h"
//
// Conditional type assignment magic. For example...
//
// typename IF<(MYOPT==12), int, float>::type myvar;
//
template <bool, class L, class R>
struct IF { typedef R type; };
template <class L, class R>
struct IF<true, L, R> { 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<size_t N>
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<LOGICAL_AXES> 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<float>(MM_M) / 60.0f)
#define MMS_TO_MMM(MM_S) (static_cast<float>(MM_S) * 60.0f)
//
// Coordinates structures for XY, XYZ, XYZE...
//
// Helpers
#define _RECIP(N) ((N) ? 1.0f / static_cast<float>(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<typename T> struct XYval;
template<typename T> struct XYZval;
template<typename T> struct XYZEval;
typedef struct XYval<bool> xy_bool_t;
typedef struct XYZval<bool> xyz_bool_t;
typedef struct XYZEval<bool> xyze_bool_t;
typedef struct XYval<char> xy_char_t;
typedef struct XYZval<char> xyz_char_t;
typedef struct XYZEval<char> xyze_char_t;
typedef struct XYval<unsigned char> xy_uchar_t;
typedef struct XYZval<unsigned char> xyz_uchar_t;
typedef struct XYZEval<unsigned char> xyze_uchar_t;
typedef struct XYval<int8_t> xy_int8_t;
typedef struct XYZval<int8_t> xyz_int8_t;
typedef struct XYZEval<int8_t> xyze_int8_t;
typedef struct XYval<uint8_t> xy_uint8_t;
typedef struct XYZval<uint8_t> xyz_uint8_t;
typedef struct XYZEval<uint8_t> xyze_uint8_t;
typedef struct XYval<int16_t> xy_int_t;
typedef struct XYZval<int16_t> xyz_int_t;
typedef struct XYZEval<int16_t> xyze_int_t;
typedef struct XYval<uint16_t> xy_uint_t;
typedef struct XYZval<uint16_t> xyz_uint_t;
typedef struct XYZEval<uint16_t> xyze_uint_t;
typedef struct XYval<int32_t> xy_long_t;
typedef struct XYZval<int32_t> xyz_long_t;
typedef struct XYZEval<int32_t> xyze_long_t;
typedef struct XYval<uint32_t> xy_ulong_t;
typedef struct XYZval<uint32_t> xyz_ulong_t;
typedef struct XYZEval<uint32_t> xyze_ulong_t;
typedef struct XYZval<volatile int32_t> xyz_vlong_t;
typedef struct XYZEval<volatile int32_t> xyze_vlong_t;
typedef struct XYval<float> xy_float_t;
typedef struct XYZval<float> xyz_float_t;
typedef struct XYZEval<float> xyze_float_t;
typedef struct XYval<feedRate_t> xy_feedrate_t;
typedef struct XYZval<feedRate_t> xyz_feedrate_t;
typedef struct XYZEval<feedRate_t> 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<typename T>
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<T> copy() const { return *this; }
FI XYval<T> ABS() const { return { T(_ABS(x)), T(_ABS(y)) }; }
FI XYval<int16_t> asInt() { return { int16_t(x), int16_t(y) }; }
FI XYval<int16_t> asInt() const { return { int16_t(x), int16_t(y) }; }
FI XYval<int32_t> asLong() { return { int32_t(x), int32_t(y) }; }
FI XYval<int32_t> asLong() const { return { int32_t(x), int32_t(y) }; }
FI XYval<int32_t> ROUNDL() { return { int32_t(LROUND(x)), int32_t(LROUND(y)) }; }
FI XYval<int32_t> ROUNDL() const { return { int32_t(LROUND(x)), int32_t(LROUND(y)) }; }
FI XYval<float> asFloat() { return { static_cast<float>(x), static_cast<float>(y) }; }
FI XYval<float> asFloat() const { return { static_cast<float>(x), static_cast<float>(y) }; }
FI XYval<float> reciprocal() const { return { _RECIP(x), _RECIP(y) }; }
// Marlin workspace shifting is done with G92 and M206
FI XYval<float> asLogical() const { XYval<float> o = asFloat(); toLogical(o); return o; }
FI XYval<float> asNative() const { XYval<float> o = asFloat(); toNative(o); return o; }
// Cast to a type with more fields by making a new object
FI operator XYZval<T>() { return { x, y }; }
FI operator XYZval<T>() const { return { x, y }; }
FI operator XYZEval<T>() { return { x, y }; }
FI operator XYZEval<T>() 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<T>& operator= (const T v) { set(v, v ); return *this; }
FI XYval<T>& operator= (const XYZval<T> &rs) { set(rs.x, rs.y); return *this; }
FI XYval<T>& operator= (const XYZEval<T> &rs) { set(rs.x, rs.y); return *this; }
// Override other operators to get intuitive behaviors
FI XYval<T> operator+ (const XYval<T> &rs) const { XYval<T> ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; }
FI XYval<T> operator+ (const XYval<T> &rs) { XYval<T> ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; }
FI XYval<T> operator- (const XYval<T> &rs) const { XYval<T> ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; }
FI XYval<T> operator- (const XYval<T> &rs) { XYval<T> ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; }
FI XYval<T> operator* (const XYval<T> &rs) const { XYval<T> ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; }
FI XYval<T> operator* (const XYval<T> &rs) { XYval<T> ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; }
FI XYval<T> operator/ (const XYval<T> &rs) const { XYval<T> ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; }
FI XYval<T> operator/ (const XYval<T> &rs) { XYval<T> ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; }
FI XYval<T> operator+ (const XYZval<T> &rs) const { XYval<T> ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; }
FI XYval<T> operator+ (const XYZval<T> &rs) { XYval<T> ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; }
FI XYval<T> operator- (const XYZval<T> &rs) const { XYval<T> ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; }
FI XYval<T> operator- (const XYZval<T> &rs) { XYval<T> ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; }
FI XYval<T> operator* (const XYZval<T> &rs) const { XYval<T> ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; }
FI XYval<T> operator* (const XYZval<T> &rs) { XYval<T> ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; }
FI XYval<T> operator/ (const XYZval<T> &rs) const { XYval<T> ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; }
FI XYval<T> operator/ (const XYZval<T> &rs) { XYval<T> ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; }
FI XYval<T> operator+ (const XYZEval<T> &rs) const { XYval<T> ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; }
FI XYval<T> operator+ (const XYZEval<T> &rs) { XYval<T> ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; }
FI XYval<T> operator- (const XYZEval<T> &rs) const { XYval<T> ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; }
FI XYval<T> operator- (const XYZEval<T> &rs) { XYval<T> ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; }
FI XYval<T> operator* (const XYZEval<T> &rs) const { XYval<T> ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; }
FI XYval<T> operator* (const XYZEval<T> &rs) { XYval<T> ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; }
FI XYval<T> operator/ (const XYZEval<T> &rs) const { XYval<T> ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; }
FI XYval<T> operator/ (const XYZEval<T> &rs) { XYval<T> ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; }
FI XYval<T> operator* (const float &v) const { XYval<T> ls = *this; ls.x *= v; ls.y *= v; return ls; }
FI XYval<T> operator* (const float &v) { XYval<T> ls = *this; ls.x *= v; ls.y *= v; return ls; }
FI XYval<T> operator* (const int &v) const { XYval<T> ls = *this; ls.x *= v; ls.y *= v; return ls; }
FI XYval<T> operator* (const int &v) { XYval<T> ls = *this; ls.x *= v; ls.y *= v; return ls; }
FI XYval<T> operator/ (const float &v) const { XYval<T> ls = *this; ls.x /= v; ls.y /= v; return ls; }
FI XYval<T> operator/ (const float &v) { XYval<T> ls = *this; ls.x /= v; ls.y /= v; return ls; }
FI XYval<T> operator/ (const int &v) const { XYval<T> ls = *this; ls.x /= v; ls.y /= v; return ls; }
FI XYval<T> operator/ (const int &v) { XYval<T> ls = *this; ls.x /= v; ls.y /= v; return ls; }
FI XYval<T> operator>>(const int &v) const { XYval<T> ls = *this; _RS(ls.x); _RS(ls.y); return ls; }
FI XYval<T> operator>>(const int &v) { XYval<T> ls = *this; _RS(ls.x); _RS(ls.y); return ls; }
FI XYval<T> operator<<(const int &v) const { XYval<T> ls = *this; _LS(ls.x); _LS(ls.y); return ls; }
FI XYval<T> operator<<(const int &v) { XYval<T> ls = *this; _LS(ls.x); _LS(ls.y); return ls; }
FI const XYval<T> operator-() const { XYval<T> o = *this; o.x = -x; o.y = -y; return o; }
FI XYval<T> operator-() { XYval<T> o = *this; o.x = -x; o.y = -y; return o; }
// Modifier operators
FI XYval<T>& operator+=(const XYval<T> &rs) { x += rs.x; y += rs.y; return *this; }
FI XYval<T>& operator-=(const XYval<T> &rs) { x -= rs.x; y -= rs.y; return *this; }
FI XYval<T>& operator*=(const XYval<T> &rs) { x *= rs.x; y *= rs.y; return *this; }
FI XYval<T>& operator+=(const XYZval<T> &rs) { x += rs.x; y += rs.y; return *this; }
FI XYval<T>& operator-=(const XYZval<T> &rs) { x -= rs.x; y -= rs.y; return *this; }
FI XYval<T>& operator*=(const XYZval<T> &rs) { x *= rs.x; y *= rs.y; return *this; }
FI XYval<T>& operator+=(const XYZEval<T> &rs) { x += rs.x; y += rs.y; return *this; }
FI XYval<T>& operator-=(const XYZEval<T> &rs) { x -= rs.x; y -= rs.y; return *this; }
FI XYval<T>& operator*=(const XYZEval<T> &rs) { x *= rs.x; y *= rs.y; return *this; }
FI XYval<T>& operator*=(const float &v) { x *= v; y *= v; return *this; }
FI XYval<T>& operator*=(const int &v) { x *= v; y *= v; return *this; }
FI XYval<T>& operator>>=(const int &v) { _RS(x); _RS(y); return *this; }
FI XYval<T>& 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<T> &rs) { return x == rs.x && y == rs.y; }
FI bool operator==(const XYZval<T> &rs) { return x == rs.x && y == rs.y; }
FI bool operator==(const XYZEval<T> &rs) { return x == rs.x && y == rs.y; }
FI bool operator==(const XYval<T> &rs) const { return x == rs.x && y == rs.y; }
FI bool operator==(const XYZval<T> &rs) const { return x == rs.x && y == rs.y; }
FI bool operator==(const XYZEval<T> &rs) const { return x == rs.x && y == rs.y; }
FI bool operator!=(const XYval<T> &rs) { return !operator==(rs); }
FI bool operator!=(const XYZval<T> &rs) { return !operator==(rs); }
FI bool operator!=(const XYZEval<T> &rs) { return !operator==(rs); }
FI bool operator!=(const XYval<T> &rs) const { return !operator==(rs); }
FI bool operator!=(const XYZval<T> &rs) const { return !operator==(rs); }
FI bool operator!=(const XYZEval<T> &rs) const { return !operator==(rs); }
};
//
// Linear Axes coordinates, counters, flags, etc.
//
template<typename T>
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<T> pxy) { x = pxy.x; y = pxy.y; }
FI void set(const XYval<T> 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<T> copy() const { XYZval<T> o = *this; return o; }
FI XYZval<T> 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<int16_t> 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<int16_t> 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<int32_t> 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<int32_t> 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<int32_t> 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<int32_t> 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<float> asFloat() { return NUM_AXIS_ARRAY(static_cast<float>(x), static_cast<float>(y), static_cast<float>(z), static_cast<float>(i), static_cast<float>(j), static_cast<float>(k)); }
FI XYZval<float> asFloat() const { return NUM_AXIS_ARRAY(static_cast<float>(x), static_cast<float>(y), static_cast<float>(z), static_cast<float>(i), static_cast<float>(j), static_cast<float>(k)); }
FI XYZval<float> 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<float> asLogical() const { XYZval<float> o = asFloat(); toLogical(o); return o; }
FI XYZval<float> asNative() const { XYZval<float> o = asFloat(); toNative(o); return o; }
// In-place cast to types having fewer fields
FI operator XYval<T>&() { return *(XYval<T>*)this; }
FI operator const XYval<T>&() const { return *(const XYval<T>*)this; }
// Cast to a type with more fields by making a new object
FI operator XYZEval<T>() 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<T>& operator= (const T v) { set(ARRAY_N_1(NUM_AXES, v)); return *this; }
FI XYZval<T>& operator= (const XYval<T> &rs) { set(rs.x, rs.y ); return *this; }
FI XYZval<T>& operator= (const XYZEval<T> &rs) { set(NUM_AXIS_ELEM(rs)); return *this; }
// Override other operators to get intuitive behaviors
FI XYZval<T> operator+ (const XYval<T> &rs) const { XYZval<T> ls = *this; NUM_AXIS_CODE(ls.x += rs.x, ls.y += rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; }
FI XYZval<T> operator+ (const XYval<T> &rs) { XYZval<T> ls = *this; NUM_AXIS_CODE(ls.x += rs.x, ls.y += rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; }
FI XYZval<T> operator- (const XYval<T> &rs) const { XYZval<T> ls = *this; NUM_AXIS_CODE(ls.x -= rs.x, ls.y -= rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; }
FI XYZval<T> operator- (const XYval<T> &rs) { XYZval<T> ls = *this; NUM_AXIS_CODE(ls.x -= rs.x, ls.y -= rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; }
FI XYZval<T> operator* (const XYval<T> &rs) const { XYZval<T> ls = *this; NUM_AXIS_CODE(ls.x *= rs.x, ls.y *= rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; }
FI XYZval<T> operator* (const XYval<T> &rs) { XYZval<T> ls = *this; NUM_AXIS_CODE(ls.x *= rs.x, ls.y *= rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; }
FI XYZval<T> operator/ (const XYval<T> &rs) const { XYZval<T> ls = *this; NUM_AXIS_CODE(ls.x /= rs.x, ls.y /= rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; }
FI XYZval<T> operator/ (const XYval<T> &rs) { XYZval<T> ls = *this; NUM_AXIS_CODE(ls.x /= rs.x, ls.y /= rs.y, NOOP , NOOP , NOOP , NOOP ); return ls; }
FI XYZval<T> operator+ (const XYZval<T> &rs) const { XYZval<T> 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<T> operator+ (const XYZval<T> &rs) { XYZval<T> 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<T> operator- (const XYZval<T> &rs) const { XYZval<T> 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<T> operator- (const XYZval<T> &rs) { XYZval<T> 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<T> operator* (const XYZval<T> &rs) const { XYZval<T> 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<T> operator* (const XYZval<T> &rs) { XYZval<T> 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<T> operator/ (const XYZval<T> &rs) const { XYZval<T> 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<T> operator/ (const XYZval<T> &rs) { XYZval<T> 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<T> operator+ (const XYZEval<T> &rs) const { XYZval<T> 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<T> operator+ (const XYZEval<T> &rs) { XYZval<T> 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<T> operator- (const XYZEval<T> &rs) const { XYZval<T> 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<T> operator- (const XYZEval<T> &rs) { XYZval<T> 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<T> operator* (const XYZEval<T> &rs) const { XYZval<T> 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<T> operator* (const XYZEval<T> &rs) { XYZval<T> 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<T> operator/ (const XYZEval<T> &rs) const { XYZval<T> 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<T> operator/ (const XYZEval<T> &rs) { XYZval<T> 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<T> operator* (const float &v) const { XYZval<T> 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<T> operator* (const float &v) { XYZval<T> 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<T> operator* (const int &v) const { XYZval<T> 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<T> operator* (const int &v) { XYZval<T> 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<T> operator/ (const float &v) const { XYZval<T> 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<T> operator/ (const float &v) { XYZval<T> 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<T> operator/ (const int &v) const { XYZval<T> 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<T> operator/ (const int &v) { XYZval<T> 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<T> operator>>(const int &v) const { XYZval<T> 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<T> operator>>(const int &v) { XYZval<T> 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<T> operator<<(const int &v) const { XYZval<T> 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<T> operator<<(const int &v) { XYZval<T> 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<T> operator-() const { XYZval<T> 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<T> operator-() { XYZval<T> 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<T>& operator+=(const XYval<T> &rs) { NUM_AXIS_CODE(x += rs.x, y += rs.y, NOOP, NOOP, NOOP, NOOP ); return *this; }
FI XYZval<T>& operator-=(const XYval<T> &rs) { NUM_AXIS_CODE(x -= rs.x, y -= rs.y, NOOP, NOOP, NOOP, NOOP ); return *this; }
FI XYZval<T>& operator*=(const XYval<T> &rs) { NUM_AXIS_CODE(x *= rs.x, y *= rs.y, NOOP, NOOP, NOOP, NOOP ); return *this; }
FI XYZval<T>& operator/=(const XYval<T> &rs) { NUM_AXIS_CODE(x /= rs.x, y /= rs.y, NOOP, NOOP, NOOP, NOOP ); return *this; }
FI XYZval<T>& operator+=(const XYZval<T> &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<T>& operator-=(const XYZval<T> &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<T>& operator*=(const XYZval<T> &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<T>& operator/=(const XYZval<T> &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<T>& operator+=(const XYZEval<T> &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<T>& operator-=(const XYZEval<T> &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<T>& operator*=(const XYZEval<T> &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<T>& operator/=(const XYZEval<T> &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<T>& operator*=(const float &v) { NUM_AXIS_CODE(x *= v, y *= v, z *= v, i *= v, j *= v, k *= v); return *this; }
FI XYZval<T>& operator*=(const int &v) { NUM_AXIS_CODE(x *= v, y *= v, z *= v, i *= v, j *= v, k *= v); return *this; }
FI XYZval<T>& operator>>=(const int &v) { NUM_AXIS_CODE(_RS(x), _RS(y), _RS(z), _RS(i), _RS(j), _RS(k)); return *this; }
FI XYZval<T>& 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<T> &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<T> &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<T> &rs) { return !operator==(rs); }
FI bool operator!=(const XYZEval<T> &rs) const { return !operator==(rs); }
};
//
// Logical Axes coordinates, counters, etc.
//
template<typename T>
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<T> pxy) { x = pxy.x; y = pxy.y; }
FI void set(const XYZval<T> 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<T> pxy, const T pz) { set(pxy); TERN_(HAS_Z_AXIS, z = pz); }
#if LOGICAL_AXES > NUM_AXES
FI void set(const XYval<T> pxy, const T pz, const T pe) { set(pxy, pz); e = pe; }
FI void set(const XYZval<T> 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<T> copy() const { XYZEval<T> o = *this; return o; }
FI XYZEval<T> 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<int16_t> 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<int16_t> 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<int32_t> 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<int32_t> 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<int32_t> 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<int32_t> 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<float> asFloat() { return LOGICAL_AXIS_ARRAY(static_cast<float>(e), static_cast<float>(x), static_cast<float>(y), static_cast<float>(z), static_cast<float>(i), static_cast<float>(j), static_cast<float>(k)); }
FI XYZEval<float> asFloat() const { return LOGICAL_AXIS_ARRAY(static_cast<float>(e), static_cast<float>(x), static_cast<float>(y), static_cast<float>(z), static_cast<float>(i), static_cast<float>(j), static_cast<float>(k)); }
FI XYZEval<float> 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<float> asLogical() const { XYZEval<float> o = asFloat(); toLogical(o); return o; }
FI XYZEval<float> asNative() const { XYZEval<float> o = asFloat(); toNative(o); return o; }
// In-place cast to types having fewer fields
FI operator XYval<T>&() { return *(XYval<T>*)this; }
FI operator const XYval<T>&() const { return *(const XYval<T>*)this; }
FI operator XYZval<T>&() { return *(XYZval<T>*)this; }
FI operator const XYZval<T>&() const { return *(const XYZval<T>*)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<T>& operator= (const T v) { set(LOGICAL_AXIS_LIST_1(v)); return *this; }
FI XYZEval<T>& operator= (const XYval<T> &rs) { set(rs.x, rs.y); return *this; }
FI XYZEval<T>& operator= (const XYZval<T> &rs) { set(NUM_AXIS_ELEM(rs)); return *this; }
// Override other operators to get intuitive behaviors
FI XYZEval<T> operator+ (const XYval<T> &rs) const { XYZEval<T> ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; }
FI XYZEval<T> operator+ (const XYval<T> &rs) { XYZEval<T> ls = *this; ls.x += rs.x; ls.y += rs.y; return ls; }
FI XYZEval<T> operator- (const XYval<T> &rs) const { XYZEval<T> ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; }
FI XYZEval<T> operator- (const XYval<T> &rs) { XYZEval<T> ls = *this; ls.x -= rs.x; ls.y -= rs.y; return ls; }
FI XYZEval<T> operator* (const XYval<T> &rs) const { XYZEval<T> ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; }
FI XYZEval<T> operator* (const XYval<T> &rs) { XYZEval<T> ls = *this; ls.x *= rs.x; ls.y *= rs.y; return ls; }
FI XYZEval<T> operator/ (const XYval<T> &rs) const { XYZEval<T> ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; }
FI XYZEval<T> operator/ (const XYval<T> &rs) { XYZEval<T> ls = *this; ls.x /= rs.x; ls.y /= rs.y; return ls; }
FI XYZEval<T> operator+ (const XYZval<T> &rs) const { XYZval<T> 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<T> operator+ (const XYZval<T> &rs) { XYZval<T> 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<T> operator- (const XYZval<T> &rs) const { XYZval<T> 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<T> operator- (const XYZval<T> &rs) { XYZval<T> 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<T> operator* (const XYZval<T> &rs) const { XYZval<T> 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<T> operator* (const XYZval<T> &rs) { XYZval<T> 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<T> operator/ (const XYZval<T> &rs) const { XYZval<T> 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<T> operator/ (const XYZval<T> &rs) { XYZval<T> 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<T> operator+ (const XYZEval<T> &rs) const { XYZEval<T> 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<T> operator+ (const XYZEval<T> &rs) { XYZEval<T> 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<T> operator- (const XYZEval<T> &rs) const { XYZEval<T> 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<T> operator- (const XYZEval<T> &rs) { XYZEval<T> 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<T> operator* (const XYZEval<T> &rs) const { XYZEval<T> 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<T> operator* (const XYZEval<T> &rs) { XYZEval<T> 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<T> operator/ (const XYZEval<T> &rs) const { XYZEval<T> 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<T> operator/ (const XYZEval<T> &rs) { XYZEval<T> 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<T> operator* (const float &v) const { XYZEval<T> 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<T> operator* (const float &v) { XYZEval<T> 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<T> operator* (const int &v) const { XYZEval<T> 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<T> operator* (const int &v) { XYZEval<T> 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<T> operator/ (const float &v) const { XYZEval<T> 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<T> operator/ (const float &v) { XYZEval<T> 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<T> operator/ (const int &v) const { XYZEval<T> 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<T> operator/ (const int &v) { XYZEval<T> 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<T> operator>>(const int &v) const { XYZEval<T> 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<T> operator>>(const int &v) { XYZEval<T> 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<T> operator<<(const int &v) const { XYZEval<T> 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<T> operator<<(const int &v) { XYZEval<T> 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<T> operator-() const { return LOGICAL_AXIS_ARRAY(-e, -x, -y, -z, -i, -j, -k); }
FI XYZEval<T> operator-() { return LOGICAL_AXIS_ARRAY(-e, -x, -y, -z, -i, -j, -k); }
// Modifier operators
FI XYZEval<T>& operator+=(const XYval<T> &rs) { x += rs.x; y += rs.y; return *this; }
FI XYZEval<T>& operator-=(const XYval<T> &rs) { x -= rs.x; y -= rs.y; return *this; }
FI XYZEval<T>& operator*=(const XYval<T> &rs) { x *= rs.x; y *= rs.y; return *this; }
FI XYZEval<T>& operator/=(const XYval<T> &rs) { x /= rs.x; y /= rs.y; return *this; }
FI XYZEval<T>& operator+=(const XYZval<T> &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<T>& operator-=(const XYZval<T> &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<T>& operator*=(const XYZval<T> &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<T>& operator/=(const XYZval<T> &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<T>& operator+=(const XYZEval<T> &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<T>& operator-=(const XYZEval<T> &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<T>& operator*=(const XYZEval<T> &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<T>& operator/=(const XYZEval<T> &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<T>& 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<T>& 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<T>& 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<T> &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<T> &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<T> &rs) { return !operator==(rs); }
FI bool operator!=(const XYZval<T> &rs) const { return !operator==(rs); }
};
#undef _RECIP
#undef _ABS
#undef _LS
#undef _RS
#undef FI

178
src/core/utility.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

94
src/core/utility.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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 <int W, int H>
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<GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y> 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<typename T>
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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
/**
* Arduino library for MicroChip MCP3426 I2C A/D converter.
* https://www.microchip.com/en-us/product/MCP3426
*/
#include <stdint.h>
#include <Wire.h>
class MCP3426 {
public:
int16_t ReadValue(uint8_t channel, uint8_t gain, uint8_t address);
bool Error;
};
extern MCP3426 mcp3426;

54
src/feature/ammeter.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

39
src/feature/ammeter.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
#include "../inc/MarlinConfigPre.h"
#include <Wire.h>
#include <INA226.h>
class Ammeter {
private:
static float scale;
public:
static float current;
static void init();
static float read();
};
extern Ammeter ammeter;

67
src/feature/babystep.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

82
src/feature/babystep.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

217
src/feature/backlash.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

96
src/feature/backlash.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

32
src/feature/baricuda.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#include "../inc/MarlinConfigPre.h"
#if ENABLED(BARICUDA)
#include "baricuda.h"
uint8_t baricuda_valve_pressure = 0,
baricuda_e_to_p_pressure = 0;
#endif // BARICUDA

25
src/feature/baricuda.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
extern uint8_t baricuda_valve_pressure,
baricuda_e_to_p_pressure;

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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 <stdint.h>
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

View File

@ -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: <https://www.gnu.org/licenses/>. *
****************************************************************************/
#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

View File

@ -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: <https://www.gnu.org/licenses/>. *
****************************************************************************/
#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);
};

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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"

File diff suppressed because it is too large Load Diff

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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 <math.h>
//#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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

456
src/feature/binary_stream.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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<Open*>(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<uint8_t*>(&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<FileTransfer>(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<const size_t buffer_size>
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<Protocol>(packet.header.protocol()) == Protocol::CONTROL && static_cast<ProtocolControl>(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<char *>(&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<Protocol>(packet.header.protocol())) {
case Protocol::CONTROL:
switch (static_cast<ProtocolControl>(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];

196
src/feature/bltouch.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

118
src/feature/bltouch.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
#include <stdint.h>
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;

103
src/feature/caselight.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

57
src/feature/caselight.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

32
src/feature/closedloop.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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))

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

48
src/feature/cooler.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

109
src/feature/cooler.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

View File

@ -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)

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
class dac084s085 {
public:
dac084s085();
static void begin();
static void setValue(const uint8_t channel, const uint8_t value);
private:
static void cshigh();
};

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
/**
* Arduino library for MicroChip MCP4728 I2C D/A converter.
*/
#include "../../core/types.h"
#include <Wire.h>
/**
* 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;

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#include "../../inc/MarlinConfig.h"
#if ENABLED(DIGIPOT_MCP4018)
#include "digipot.h"
#include <Stream.h>
#include <SlowSoftI2CMaster.h> // 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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#include "../../inc/MarlinConfig.h"
#if ENABLED(DIGIPOT_MCP4451)
#include "digipot.h"
#include <Stream.h>
#include <Wire.h>
#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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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<typename Cfg>
State SerialPageManager<Cfg>::state;
template<typename Cfg>
volatile bool SerialPageManager<Cfg>::fatal_error;
template<typename Cfg>
volatile PageState SerialPageManager<Cfg>::page_states[Cfg::PAGE_COUNT];
template<typename Cfg>
volatile bool SerialPageManager<Cfg>::page_states_dirty;
template<typename Cfg>
uint8_t SerialPageManager<Cfg>::pages[Cfg::PAGE_COUNT][Cfg::PAGE_SIZE];
template<typename Cfg>
uint8_t SerialPageManager<Cfg>::checksum;
template<typename Cfg>
typename Cfg::write_byte_idx_t SerialPageManager<Cfg>::write_byte_idx;
template<typename Cfg>
typename Cfg::page_idx_t SerialPageManager<Cfg>::write_page_idx;
template<typename Cfg>
typename Cfg::write_byte_idx_t SerialPageManager<Cfg>::write_page_size;
template <typename Cfg>
void SerialPageManager<Cfg>::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<typename Cfg>
FORCE_INLINE bool SerialPageManager<Cfg>::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 <typename Cfg>
void SerialPageManager<Cfg>::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 <typename Cfg>
FORCE_INLINE void SerialPageManager<Cfg>::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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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<typename Cfg>
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<bool b, typename T, typename F> struct TypeSelector { typedef T type;} ;
template<typename T, typename F> struct TypeSelector<false, T, F> { typedef F type; };
template <int num_pages, int num_axes, int bits_segment, bool dir, int segments>
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 <uint8_t num_pages>
using SP_4x4D_128 = config_t<num_pages, 4, 4, true, 128>;
template <uint8_t num_pages>
using SP_4x2_256 = config_t<num_pages, 4, 2, false, 256>;
template <uint8_t num_pages>
using SP_4x1_512 = config_t<num_pages, 4, 1, false, 512>;
// configured types
typedef STEPPER_PAGE_FORMAT<STEPPER_PAGES> Config;
template class PAGE_MANAGER<Config>;
typedef PAGE_MANAGER<Config> 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;

45
src/feature/e_parser.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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

225
src/feature/e_parser.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

1128
src/feature/encoder_i2c.cpp Normal file

File diff suppressed because it is too large Load Diff

320
src/feature/encoder_i2c.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
#include "../inc/MarlinConfig.h"
#include "../module/planner.h"
#include <Wire.h>
//=========== 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;

175
src/feature/ethernet.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

39
src/feature/ethernet.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
#ifdef __IMXRT1062__
#include <NativeEthernet.h>
#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;

207
src/feature/fancheck.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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<TACHO_COUNT> 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::AutoReportFan> FanCheck::auto_reporter;
void FanCheck::AutoReportFan::report() { print_fan_states(); }
#endif
#endif // HAS_FANCHECK

89
src/feature/fancheck.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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_COUNT> 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<AutoReportFan> auto_reporter;
#endif
};
extern FanCheck fan_check;
#endif // HAS_FANCHECK

55
src/feature/fanmux.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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

29
src/feature/fanmux.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
/**
* feature/fanmux.h - Cooling Fan Multiplexer support functions
*/
void fanmux_switch(const uint8_t e);
void fanmux_init();

49
src/feature/filwidth.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

120
src/feature/filwidth.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

269
src/feature/fwretract.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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<EXTRUDERS> 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<EXTRUDERS> 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

89
src/feature/fwretract.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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<EXTRUDERS> 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<EXTRUDERS> 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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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

114
src/feature/host_actions.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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[];

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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

37
src/feature/hotend_idle.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

184
src/feature/joystick.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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

52
src/feature/joystick.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* blinkm.cpp - Control a BlinkM over i2c
*/
#include "../../inc/MarlinConfig.h"
#if ENABLED(BLINKM)
#include "blinkm.h"
#include "leds.h"
#include <Wire.h>
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

31
src/feature/leds/blinkm.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
/**
* blinkm.h - Control a BlinkM over i2c
*/
struct LEDColor;
typedef LEDColor LEDColor;
void blinkm_set_led_color(const LEDColor &color);

219
src/feature/leds/leds.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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

216
src/feature/leds/leds.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
/**
* leds.h - Marlin general RGB LED support
*/
#include "../../inc/MarlinConfigPre.h"
#include <string.h>
// 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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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

187
src/feature/leds/neopixel.h Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
/**
* NeoPixel support
*/
#ifndef _NEOPIXEL_INCLUDE_
#error "Always include 'leds.h' and not 'neopixel.h' directly."
#endif
// ------------------------
// Includes
// ------------------------
#include "../../inc/MarlinConfig.h"
#include <Adafruit_NeoPixel.h>
#include <stdint.h>
// ------------------------
// 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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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 <Wire.h>
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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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 <Arduino.h>
#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();

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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 <Wire.h>
#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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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 <stdint.h>
void PCA9632_buzz(const long, const uint16_t);
#endif

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#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;

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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

View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
#pragma once
/**
* Marlin general RGB LED support
*/
void handle_status_leds();

698
src/feature/max7219.cpp Normal file
View File

@ -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 <https://www.gnu.org/licenses/>.
*
*/
/**
* 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

Some files were not shown because too many files have changed in this diff Show More