code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2024 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
|
2301_81045437/Marlin
|
Marlin/src/HAL/TEENSY40_41/inc/Conditionals_type.h
|
C
|
agpl-3.0
| 875
|
/**
* 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
/**
* Test TEENSY41 specific configuration values for errors at compile-time.
*/
#if HAS_SPI_TFT || HAS_FSMC_TFT
#error "Sorry! TFT displays are not available for Teensy 4.0/4.1."
#endif
#if ENABLED(EMERGENCY_PARSER)
#error "EMERGENCY_PARSER is not yet implemented for Teensy 4.0/4.1. Disable EMERGENCY_PARSER to continue."
#endif
#if ENABLED(FAST_PWM_FAN) || SPINDLE_LASER_FREQUENCY
#error "Features requiring Hardware PWM (FAST_PWM_FAN, SPINDLE_LASER_FREQUENCY) are not yet supported for Teensy 4.0/4.1."
#endif
#if HAS_TMC_SW_SERIAL
#error "TMC220x Software Serial is not supported for Teensy 4.0/4.1."
#endif
#if ENABLED(POSTMORTEM_DEBUGGING)
#error "POSTMORTEM_DEBUGGING is not yet supported for Teensy 4.0/4.1."
#endif
|
2301_81045437/Marlin
|
Marlin/src/HAL/TEENSY40_41/inc/SanityCheck.h
|
C
|
agpl-3.0
| 1,618
|
/**
* 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
/**
* HAL Pins Debugging for Teensy 4.0 (IMXRT1062DVL6A) / 4.1 (IMXRT1062DVJ6A)
*/
#warning "PINS_DEBUGGING is not fully supported for Teensy 4.0 / 4.1 so 'M43' may cause hangs."
#define NUMBER_PINS_TOTAL NUM_DIGITAL_PINS
#define digitalRead_mod(p) extDigitalRead(p) // AVR digitalRead disabled PWM before it read the pin
#define PRINT_ARRAY_NAME(x) do{ sprintf_P(buffer, PSTR("%-" STRINGIFY(MAX_NAME_LENGTH) "s"), pin_array[x].name); SERIAL_ECHO(buffer); }while(0)
#define PRINT_PIN(p) do{ sprintf_P(buffer, PSTR("%02d"), p); SERIAL_ECHO(buffer); }while(0)
#define PRINT_PIN_ANALOG(p) do{ sprintf_P(buffer, PSTR(" (A%2d) "), DIGITAL_PIN_TO_ANALOG_PIN(pin)); SERIAL_ECHO(buffer); }while(0)
#define GET_ARRAY_PIN(p) pin_array[p].pin
#define GET_ARRAY_IS_DIGITAL(p) pin_array[p].is_digital
#define VALID_PIN(pin) (pin >= 0 && pin < int8_t(NUMBER_PINS_TOTAL))
#define DIGITAL_PIN_TO_ANALOG_PIN(p) int(p - analogInputToDigitalPin(0))
#define IS_ANALOG(P) ((P) >= analogInputToDigitalPin(0) && (P) <= analogInputToDigitalPin(13)) || ((P) >= analogInputToDigitalPin(14) && (P) <= analogInputToDigitalPin(17))
#define GET_PINMODE(PIN) (VALID_PIN(pin) && IS_OUTPUT(pin))
#define MULTI_NAME_PAD 16 // space needed to be pretty if not first name assigned to a pin
struct pwm_pin_info_struct {
uint8_t type; // 0=no pwm, 1=flexpwm, 2=quad
uint8_t module; // 0-3, 0-3
uint8_t channel; // 0=X, 1=A, 2=B
uint8_t muxval; //
};
#define M(a, b) ((((a) - 1) << 4) | (b))
const struct pwm_pin_info_struct pwm_pin_info[] = {
{1, M(1, 1), 0, 4}, // FlexPWM1_1_X 0 // AD_B0_03
{1, M(1, 0), 0, 4}, // FlexPWM1_0_X 1 // AD_B0_02
{1, M(4, 2), 1, 1}, // FlexPWM4_2_A 2 // EMC_04
{1, M(4, 2), 2, 1}, // FlexPWM4_2_B 3 // EMC_05
{1, M(2, 0), 1, 1}, // FlexPWM2_0_A 4 // EMC_06
{1, M(2, 1), 1, 1}, // FlexPWM2_1_A 5 // EMC_08
{1, M(2, 2), 1, 2}, // FlexPWM2_2_A 6 // B0_10
{1, M(1, 3), 2, 6}, // FlexPWM1_3_B 7 // B1_01
{1, M(1, 3), 1, 6}, // FlexPWM1_3_A 8 // B1_00
{1, M(2, 2), 2, 2}, // FlexPWM2_2_B 9 // B0_11
{2, M(1, 0), 0, 1}, // QuadTimer1_0 10 // B0_00
{2, M(1, 2), 0, 1}, // QuadTimer1_2 11 // B0_02
{2, M(1, 1), 0, 1}, // QuadTimer1_1 12 // B0_01
{2, M(2, 0), 0, 1}, // QuadTimer2_0 13 // B0_03
{2, M(3, 2), 0, 1}, // QuadTimer3_2 14 // AD_B1_02
{2, M(3, 3), 0, 1}, // QuadTimer3_3 15 // AD_B1_03
{0, M(1, 0), 0, 0},
{0, M(1, 0), 0, 0},
{2, M(3, 1), 0, 1}, // QuadTimer3_1 18 // AD_B1_01
{2, M(3, 0), 0, 1}, // QuadTimer3_0 19 // AD_B1_00
{0, M(1, 0), 0, 0},
{0, M(1, 0), 0, 0},
{1, M(4, 0), 1, 1}, // FlexPWM4_0_A 22 // AD_B1_08
{1, M(4, 1), 1, 1}, // FlexPWM4_1_A 23 // AD_B1_09
{1, M(1, 2), 0, 4}, // FlexPWM1_2_X 24 // AD_B0_12
{1, M(1, 3), 0, 4}, // FlexPWM1_3_X 25 // AD_B0_13
{0, M(1, 0), 0, 0},
{0, M(1, 0), 0, 0},
{1, M(3, 1), 2, 1}, // FlexPWM3_1_B 28 // EMC_32
{1, M(3, 1), 1, 1}, // FlexPWM3_1_A 29 // EMC_31
{0, M(1, 0), 0, 0},
{0, M(1, 0), 0, 0},
{0, M(1, 0), 0, 0},
{1, M(2, 0), 2, 1}, // FlexPWM2_0_B 33 // EMC_07
#ifdef ARDUINO_TEENSY40
{1, M(1, 1), 2, 1}, // FlexPWM1_1_B 34 // SD_B0_03
{1, M(1, 1), 1, 1}, // FlexPWM1_1_A 35 // SD_B0_02
{1, M(1, 0), 2, 1}, // FlexPWM1_0_B 36 // SD_B0_01
{1, M(1, 0), 1, 1}, // FlexPWM1_0_A 37 // SD_B0_00
{1, M(1, 2), 2, 1}, // FlexPWM1_2_B 38 // SD_B0_05
{1, M(1, 2), 1, 1}, // FlexPWM1_2_A 39 // SD_B0_04
#endif
#ifdef ARDUINO_TEENSY41
{0, M(1, 0), 0, 0},
{0, M(1, 0), 0, 0},
{1, M(2, 3), 1, 6}, // FlexPWM2_3_A 36 // B1_00
{1, M(2, 3), 2, 6}, // FlexPWM2_3_B 37 // B1_01
{0, M(1, 0), 0, 0},
{0, M(1, 0), 0, 0},
{0, M(1, 0), 0, 0},
{0, M(1, 0), 0, 0},
{1, M(1, 1), 2, 1}, // FlexPWM1_1_B 42 // SD_B0_03
{1, M(1, 1), 1, 1}, // FlexPWM1_1_A 43 // SD_B0_02
{1, M(1, 0), 2, 1}, // FlexPWM1_0_B 44 // SD_B0_01
{1, M(1, 0), 1, 1}, // FlexPWM1_0_A 45 // SD_B0_00
{1, M(1, 2), 2, 1}, // FlexPWM1_2_B 46 // SD_B0_05
{1, M(1, 2), 1, 1}, // FlexPWM1_2_A 47 // SD_B0_04
{0, M(1, 0), 0, 0}, // duplicate FlexPWM1_0_B
{0, M(1, 0), 0, 0}, // duplicate FlexPWM1_2_A
{0, M(1, 0), 0, 0}, // duplicate FlexPWM1_2_B
{1, M(3, 3), 2, 1}, // FlexPWM3_3_B 51 // EMC_22
{0, M(1, 0), 0, 0}, // duplicate FlexPWM1_1_B
{0, M(1, 0), 0, 0}, // duplicate FlexPWM1_1_A
{1, M(3, 0), 1, 1}, // FlexPWM3_0_A 53 // EMC_29
#endif
};
void print_analog_pin(char buffer[], const pin_t pin) {
if (pin <= 23) sprintf_P(buffer, PSTR("(A%2d) "), int(pin - 14));
else if (pin <= 41) sprintf_P(buffer, PSTR("(A%2d) "), int(pin - 24));
}
void analog_pin_state(char buffer[], const pin_t pin) {
if (pin <= 23) sprintf_P(buffer, PSTR("Analog in =% 5d"), analogRead(pin - 14));
else if (pin <= 41) sprintf_P(buffer, PSTR("Analog in =% 5d"), analogRead(pin - 24));
}
#define PWM_PRINT(V) do{ sprintf_P(buffer, PSTR("PWM: %4d"), V); SERIAL_ECHO(buffer); }while(0)
/**
* Print a pin's PWM status.
* Return true if it's currently a PWM pin.
*/
bool pwm_status(const pin_t pin) {
char buffer[20]; // for the sprintf statements
const struct pwm_pin_info_struct *info;
if (pin >= CORE_NUM_DIGITAL) return false;
info = pwm_pin_info + pin;
if (info->type == 0) return false;
/* TODO decode pwm value from timers */
// for now just indicate if output is set as pwm
PWM_PRINT(*(portConfigRegister(pin)) == info->muxval);
return (*(portConfigRegister(pin)) == info->muxval);
}
void pwm_details(const pin_t) { /* TODO */ }
void print_port(const pin_t) {}
|
2301_81045437/Marlin
|
Marlin/src/HAL/TEENSY40_41/pinsDebug.h
|
C
|
agpl-3.0
| 6,504
|
/**
* 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
/**
* HAL SPI Pins for Teensy 4.0 (IMXRT1062DVL6A) / 4.1 (IMXRT1062DVJ6A)
*/
#define SD_SCK_PIN 13
#define SD_MISO_PIN 12
#define SD_MOSI_PIN 11
#define SD_SS_PIN 20 // SDSS // A.28, A.29, B.21, C.26, C.29
|
2301_81045437/Marlin
|
Marlin/src/HAL/TEENSY40_41/spi_pins.h
|
C
|
agpl-3.0
| 1,092
|
/**
* 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/>.
*
*/
/**
* HAL Timers for Teensy 4.0 (IMXRT1062DVL6A) / 4.1 (IMXRT1062DVJ6A)
*/
#ifdef __IMXRT1062__
#include "../../inc/MarlinConfig.h"
void HAL_timer_start(const uint8_t timer_num, const uint32_t frequency) {
switch (timer_num) {
case MF_TIMER_STEP:
CCM_CSCMR1 &= ~CCM_CSCMR1_PERCLK_CLK_SEL; // turn off 24mhz mode
CCM_CCGR1 |= CCM_CCGR1_GPT1_BUS(CCM_CCGR_ON);
GPT1_CR = 0; // disable timer
GPT1_SR = 0x3F; // clear all prior status
GPT1_PR = GPT1_TIMER_PRESCALE - 1;
GPT1_CR |= GPT_CR_CLKSRC(1); //clock selection #1 (peripheral clock = 150 MHz)
GPT1_CR |= GPT_CR_ENMOD; //reset count to zero before enabling
GPT1_CR |= GPT_CR_OM1(1); // toggle mode
GPT1_OCR1 = (GPT1_TIMER_RATE / frequency) -1; // Initial compare value
GPT1_IR = GPT_IR_OF1IE; // Compare3 value
GPT1_CR |= GPT_CR_EN; //enable GPT2 counting at 150 MHz
OUT_WRITE(15, HIGH);
attachInterruptVector(IRQ_GPT1, &stepTC_Handler);
NVIC_SET_PRIORITY(IRQ_GPT1, 16);
break;
case MF_TIMER_TEMP:
CCM_CSCMR1 &= ~CCM_CSCMR1_PERCLK_CLK_SEL; // turn off 24mhz mode
CCM_CCGR0 |= CCM_CCGR0_GPT2_BUS(CCM_CCGR_ON);
GPT2_CR = 0; // disable timer
GPT2_SR = 0x3F; // clear all prior status
GPT2_PR = GPT2_TIMER_PRESCALE - 1;
GPT2_CR |= GPT_CR_CLKSRC(1); //clock selection #1 (peripheral clock = 150 MHz)
GPT2_CR |= GPT_CR_ENMOD; //reset count to zero before enabling
GPT2_CR |= GPT_CR_OM1(1); // toggle mode
GPT2_OCR1 = (GPT2_TIMER_RATE / frequency) -1; // Initial compare value
GPT2_IR = GPT_IR_OF1IE; // Compare3 value
GPT2_CR |= GPT_CR_EN; //enable GPT2 counting at 150 MHz
OUT_WRITE(14, HIGH);
attachInterruptVector(IRQ_GPT2, &tempTC_Handler);
NVIC_SET_PRIORITY(IRQ_GPT2, 32);
break;
}
}
void HAL_timer_enable_interrupt(const uint8_t timer_num) {
switch (timer_num) {
case MF_TIMER_STEP: NVIC_ENABLE_IRQ(IRQ_GPT1); break;
case MF_TIMER_TEMP: NVIC_ENABLE_IRQ(IRQ_GPT2); break;
}
}
void HAL_timer_disable_interrupt(const uint8_t timer_num) {
switch (timer_num) {
case MF_TIMER_STEP: NVIC_DISABLE_IRQ(IRQ_GPT1); break;
case MF_TIMER_TEMP: NVIC_DISABLE_IRQ(IRQ_GPT2); break;
}
// We NEED memory barriers to ensure Interrupts are actually disabled!
// ( https://dzone.com/articles/nvic-disabling-interrupts-on-arm-cortex-m-and-the )
asm volatile("dsb");
}
bool HAL_timer_interrupt_enabled(const uint8_t timer_num) {
switch (timer_num) {
case MF_TIMER_STEP: return (NVIC_IS_ENABLED(IRQ_GPT1));
case MF_TIMER_TEMP: return (NVIC_IS_ENABLED(IRQ_GPT2));
}
return false;
}
void HAL_timer_isr_prologue(const uint8_t timer_num) {
switch (timer_num) {
case MF_TIMER_STEP: GPT1_SR = GPT_IR_OF1IE; break; // clear OF3 bit
case MF_TIMER_TEMP: GPT2_SR = GPT_IR_OF1IE; break; // clear OF3 bit
}
asm volatile("dsb");
}
#endif // __IMXRT1062__
|
2301_81045437/Marlin
|
Marlin/src/HAL/TEENSY40_41/timers.cpp
|
C++
|
agpl-3.0
| 3,920
|
/**
* 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
/**
* HAL Timers for Teensy 4.0 (IMXRT1062DVL6A) / 4.1 (IMXRT1062DVJ6A)
*/
#include <stdint.h>
// ------------------------
// Defines
// ------------------------
#define FORCE_INLINE __attribute__((always_inline)) inline
typedef uint32_t hal_timer_t;
#define HAL_TIMER_TYPE_MAX 0xFFFFFFFE
#define GPT_TIMER_RATE F_BUS_ACTUAL // 150MHz
#define GPT1_TIMER_PRESCALE 2
#define GPT2_TIMER_PRESCALE 10
#define GPT1_TIMER_RATE (GPT_TIMER_RATE / GPT1_TIMER_PRESCALE) // 75MHz
#define GPT2_TIMER_RATE (GPT_TIMER_RATE / GPT2_TIMER_PRESCALE) // 15MHz
#ifndef MF_TIMER_STEP
#define MF_TIMER_STEP 0 // Timer Index for Stepper
#endif
#ifndef MF_TIMER_PULSE
#define MF_TIMER_PULSE MF_TIMER_STEP
#endif
#ifndef MF_TIMER_TEMP
#define MF_TIMER_TEMP 1 // Timer Index for Temperature
#endif
#define TEMP_TIMER_RATE 1000000
#define TEMP_TIMER_FREQUENCY 1000
#define STEPPER_TIMER_RATE GPT1_TIMER_RATE
#define STEPPER_TIMER_TICKS_PER_US ((STEPPER_TIMER_RATE) / 1000000)
#define STEPPER_TIMER_PRESCALE ((GPT_TIMER_RATE / 1000000) / STEPPER_TIMER_TICKS_PER_US)
#define PULSE_TIMER_RATE STEPPER_TIMER_RATE // frequency of pulse timer
#define PULSE_TIMER_PRESCALE STEPPER_TIMER_PRESCALE
#define PULSE_TIMER_TICKS_PER_US STEPPER_TIMER_TICKS_PER_US
#define ENABLE_STEPPER_DRIVER_INTERRUPT() HAL_timer_enable_interrupt(MF_TIMER_STEP)
#define DISABLE_STEPPER_DRIVER_INTERRUPT() HAL_timer_disable_interrupt(MF_TIMER_STEP)
#define STEPPER_ISR_ENABLED() HAL_timer_interrupt_enabled(MF_TIMER_STEP)
#define ENABLE_TEMPERATURE_INTERRUPT() HAL_timer_enable_interrupt(MF_TIMER_TEMP)
#define DISABLE_TEMPERATURE_INTERRUPT() HAL_timer_disable_interrupt(MF_TIMER_TEMP)
#ifndef HAL_STEP_TIMER_ISR
#define HAL_STEP_TIMER_ISR() extern "C" void stepTC_Handler() // GPT1_Handler()
#endif
#ifndef HAL_TEMP_TIMER_ISR
#define HAL_TEMP_TIMER_ISR() extern "C" void tempTC_Handler() // GPT2_Handler()
#endif
extern "C" {
void stepTC_Handler();
void tempTC_Handler();
}
void HAL_timer_start(const uint8_t timer_num, const uint32_t frequency);
FORCE_INLINE static void HAL_timer_set_compare(const uint8_t timer_num, const hal_timer_t compare) {
switch (timer_num) {
case MF_TIMER_STEP: GPT1_OCR1 = compare - 1; break;
case MF_TIMER_TEMP: GPT2_OCR1 = compare - 1; break;
}
}
FORCE_INLINE static hal_timer_t HAL_timer_get_compare(const uint8_t timer_num) {
switch (timer_num) {
case MF_TIMER_STEP: return GPT1_OCR1;
case MF_TIMER_TEMP: return GPT2_OCR1;
}
return 0;
}
FORCE_INLINE static hal_timer_t HAL_timer_get_count(const uint8_t timer_num) {
switch (timer_num) {
case MF_TIMER_STEP: return GPT1_CNT;
case MF_TIMER_TEMP: return GPT2_CNT;
}
return 0;
}
void HAL_timer_enable_interrupt(const uint8_t timer_num);
void HAL_timer_disable_interrupt(const uint8_t timer_num);
bool HAL_timer_interrupt_enabled(const uint8_t timer_num);
void HAL_timer_isr_prologue(const uint8_t timer_num);
//void HAL_timer_isr_epilogue(const uint8_t timer_num) {}
#define HAL_timer_isr_epilogue(T) NOOP
|
2301_81045437/Marlin
|
Marlin/src/HAL/TEENSY40_41/timers.h
|
C
|
agpl-3.0
| 3,930
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2023 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
/**
* Teensy 4.0/4.1 LCD-specific defines
*/
|
2301_81045437/Marlin
|
Marlin/src/HAL/TEENSY40_41/u8g/LCD_defines.h
|
C
|
agpl-3.0
| 923
|
/**
* 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 XSTR(V...) #V
#ifdef __AVR__
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/AVR/NAME)
#elif defined(ARDUINO_ARCH_SAM)
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/DUE/NAME)
#elif defined(__MK20DX256__)
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/TEENSY31_32/NAME)
#elif defined(__MK64FX512__) || defined(__MK66FX1M0__)
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/TEENSY35_36/NAME)
#elif defined(__IMXRT1062__)
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/TEENSY40_41/NAME)
#elif defined(TARGET_LPC1768)
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/LPC1768/NAME)
#elif defined(ARDUINO_ARCH_HC32)
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/HC32/NAME)
#elif defined(__STM32F1__) || defined(TARGET_STM32F1)
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/STM32F1/NAME)
#elif defined(ARDUINO_ARCH_STM32)
#ifndef HAL_STM32
#define HAL_STM32
#endif
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/STM32/NAME)
#elif defined(ARDUINO_ARCH_ESP32)
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/ESP32/NAME)
#elif defined(__PLAT_LINUX__)
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/LINUX/NAME)
#elif defined(__PLAT_NATIVE_SIM__)
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/NATIVE_SIM/NAME)
#elif defined(__SAMD51__)
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/SAMD51/NAME)
#elif defined(__SAMD21__)
#define HAL_PATH(PATH, NAME) XSTR(PATH/HAL/SAMD21/NAME)
#else
#error "Unsupported Platform!"
#endif
|
2301_81045437/Marlin
|
Marlin/src/HAL/platforms.h
|
C
|
agpl-3.0
| 2,280
|
/**
* 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 "Delay.h"
#include "../../inc/MarlinConfig.h"
#if defined(__arm__) || defined(__thumb__)
static uint32_t ASM_CYCLES_PER_ITERATION = 4; // Initial bet which will be adjusted in calibrate_delay_loop
// Simple assembler loop counting down
void delay_asm(uint32_t cy) {
cy = _MAX(cy / ASM_CYCLES_PER_ITERATION, 1U); // Zero is forbidden here
__asm__ __volatile__(
A(".syntax unified") // is to prevent CM0,CM1 non-unified syntax
L("1")
A("subs %[cnt],#1")
A("bne 1b")
: [cnt]"+r"(cy) // output: +r means input+output
: // input:
: "cc" // clobbers:
);
}
// We can't use CMSIS since it's not available on all platform, so fallback to hardcoded register values
#define HW_REG(X) *(volatile uint32_t *)(X)
#define _DWT_CTRL 0xE0001000
#define _DWT_CYCCNT 0xE0001004 // CYCCNT is 32bits, takes 37s or so to wrap.
#define _DEM_CR 0xE000EDFC
#define _LAR 0xE0001FB0
// Use hardware cycle counter instead, it's much safer
void delay_dwt(uint32_t count) {
// Reuse the ASM_CYCLES_PER_ITERATION variable to avoid wasting another useless variable
uint32_t start = HW_REG(_DWT_CYCCNT) - ASM_CYCLES_PER_ITERATION, elapsed;
do {
elapsed = HW_REG(_DWT_CYCCNT) - start;
} while (elapsed < count);
}
// Pointer to asm function, calling the functions has a ~20 cycles overhead
DelayImpl DelayCycleFnc = delay_asm;
void calibrate_delay_loop() {
// Check if we have a working DWT implementation in the CPU (see https://developer.arm.com/documentation/ddi0439/b/Data-Watchpoint-and-Trace-Unit/DWT-Programmers-Model)
if (!HW_REG(_DWT_CTRL)) {
// No DWT present, so fallback to plain old ASM nop counting
// Unfortunately, we don't exactly know how many iteration it'll take to decrement a counter in a loop
// It depends on the CPU architecture, the code current position (flash vs SRAM)
// So, instead of wild guessing and making mistake, instead
// compute it once for all
ASM_CYCLES_PER_ITERATION = 1;
// We need to fetch some reference clock before waiting
cli();
uint32_t start = micros();
delay_asm(1000); // On a typical CPU running in MHz, waiting 1000 "unknown cycles" means it'll take between 1ms to 6ms, that's perfectly acceptable
uint32_t end = micros();
sei();
uint32_t expectedCycles = (end - start) * ((F_CPU) / 1000000UL); // Convert microseconds to cycles
// Finally compute the right scale
ASM_CYCLES_PER_ITERATION = (uint32_t)(expectedCycles / 1000);
// No DWT present, likely a Cortex M0 so NOP counting is our best bet here
DelayCycleFnc = delay_asm;
}
else {
// Enable DWT counter
// From https://stackoverflow.com/a/41188674/1469714
HW_REG(_DEM_CR) = HW_REG(_DEM_CR) | 0x01000000; // Enable trace
#if __CORTEX_M == 7
HW_REG(_LAR) = 0xC5ACCE55; // Unlock access to DWT registers, see https://developer.arm.com/documentation/ihi0029/e/ section B2.3.10
#endif
HW_REG(_DWT_CYCCNT) = 0; // Clear DWT cycle counter
HW_REG(_DWT_CTRL) = HW_REG(_DWT_CTRL) | 1; // Enable DWT cycle counter
// Then calibrate the constant offset from the counter
ASM_CYCLES_PER_ITERATION = 0;
uint32_t s = HW_REG(_DWT_CYCCNT);
uint32_t e = HW_REG(_DWT_CYCCNT); // (e - s) contains the number of cycle required to read the cycle counter
delay_dwt(0);
uint32_t f = HW_REG(_DWT_CYCCNT); // (f - e) contains the delay to call the delay function + the time to read the cycle counter
ASM_CYCLES_PER_ITERATION = (f - e) - (e - s);
// Use safer DWT function
DelayCycleFnc = delay_dwt;
}
}
#if ENABLED(MARLIN_DEV_MODE)
void dump_delay_accuracy_check() {
auto report_call_time = [](FSTR_P const name, FSTR_P const unit, const uint32_t cycles, const uint32_t total, const bool do_flush=true) {
SERIAL_ECHOLN(F("Calling "), name, F(" for "), cycles, C(' '), unit, F(" took: "), total, C(' '), unit);
if (do_flush) SERIAL_FLUSHTX();
};
uint32_t s, e;
SERIAL_ECHOLNPGM("Computed delay calibration value: ", ASM_CYCLES_PER_ITERATION);
SERIAL_FLUSH();
// Display the results of the calibration above
constexpr uint32_t testValues[] = { 1, 5, 10, 20, 50, 100, 150, 200, 350, 500, 750, 1000 };
for (auto i : testValues) {
s = micros(); DELAY_US(i); e = micros();
report_call_time(F("delay"), F("us"), i, e - s);
}
if (HW_REG(_DWT_CTRL)) {
static FSTR_P cyc = F("cycles");
static FSTR_P dcd = F("DELAY_CYCLES directly ");
for (auto i : testValues) {
s = HW_REG(_DWT_CYCCNT); DELAY_CYCLES(i); e = HW_REG(_DWT_CYCCNT);
report_call_time(F("runtime delay"), cyc, i, e - s);
}
// Measure the delay to call a real function compared to a function pointer
s = HW_REG(_DWT_CYCCNT); delay_dwt(1); e = HW_REG(_DWT_CYCCNT);
report_call_time(F("delay_dwt"), cyc, 1, e - s);
s = HW_REG(_DWT_CYCCNT); DELAY_CYCLES( 1); e = HW_REG(_DWT_CYCCNT);
report_call_time(dcd, cyc, 1, e - s, false);
s = HW_REG(_DWT_CYCCNT); DELAY_CYCLES( 5); e = HW_REG(_DWT_CYCCNT);
report_call_time(dcd, cyc, 5, e - s, false);
s = HW_REG(_DWT_CYCCNT); DELAY_CYCLES(10); e = HW_REG(_DWT_CYCCNT);
report_call_time(dcd, cyc, 10, e - s, false);
s = HW_REG(_DWT_CYCCNT); DELAY_CYCLES(20); e = HW_REG(_DWT_CYCCNT);
report_call_time(dcd, cyc, 20, e - s, false);
s = HW_REG(_DWT_CYCCNT); DELAY_CYCLES(50); e = HW_REG(_DWT_CYCCNT);
report_call_time(dcd, cyc, 50, e - s, false);
s = HW_REG(_DWT_CYCCNT); DELAY_CYCLES(100); e = HW_REG(_DWT_CYCCNT);
report_call_time(dcd, cyc, 100, e - s, false);
s = HW_REG(_DWT_CYCCNT); DELAY_CYCLES(200); e = HW_REG(_DWT_CYCCNT);
report_call_time(dcd, cyc, 200, e - s, false);
}
}
#endif // MARLIN_DEV_MODE
#else
void calibrate_delay_loop() {}
#if ENABLED(MARLIN_DEV_MODE)
void dump_delay_accuracy_check() { SERIAL_ECHOPGM("N/A on this platform"); }
#endif
#endif
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/Delay.cpp
|
C++
|
agpl-3.0
| 7,159
|
/**
* 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"
/**
* Busy wait delay cycles routines:
*
* DELAY_CYCLES(count): Delay execution in cycles
* DELAY_NS(count): Delay execution in nanoseconds
* DELAY_US(count): Delay execution in microseconds
*/
#include "../../core/macros.h"
void calibrate_delay_loop();
#if defined(__arm__) || defined(__thumb__)
// We want to have delay_cycle function with the lowest possible overhead, so we adjust at the function at runtime based on the current CPU best feature
typedef void (*DelayImpl)(uint32_t);
extern DelayImpl DelayCycleFnc;
// I've measured 36 cycles on my system to call the cycle waiting method, but it shouldn't change much to have a bit more margin, it only consume a bit more flash
#define TRIP_POINT_FOR_CALLING_FUNCTION 40
// A simple recursive template class that output exactly one 'nop' of code per recursion
template <int N> struct NopWriter {
FORCE_INLINE static void build() {
__asm__ __volatile__("nop");
NopWriter<N-1>::build();
}
};
// End the loop
template <> struct NopWriter<0> { FORCE_INLINE static void build() {} };
namespace Private {
// Split recursing template in 2 different class so we don't reach the maximum template instantiation depth limit
template <bool belowTP, int N> struct Helper {
FORCE_INLINE static void build() {
DelayCycleFnc(N - 2); // Approximative cost of calling the function (might be off by one or 2 cycles)
}
};
template <int N> struct Helper<true, N> {
FORCE_INLINE static void build() {
NopWriter<N - 1>::build();
}
};
template <> struct Helper<true, 0> {
FORCE_INLINE static void build() {}
};
}
// Select a behavior based on the constexpr'ness of the parameter
// If called with a compile-time parameter, then write as many NOP as required to reach the asked cycle count
// (there is some tripping point here to start looping when it's more profitable than gruntly executing NOPs)
// If not called from a compile-time parameter, fallback to a runtime loop counting version instead
template <bool compileTime, int Cycles>
struct SmartDelay {
FORCE_INLINE SmartDelay(int) {
if (Cycles == 0) return;
Private::Helper<Cycles < TRIP_POINT_FOR_CALLING_FUNCTION, Cycles>::build();
}
};
// Runtime version below. There is no way this would run under less than ~TRIP_POINT_FOR_CALLING_FUNCTION cycles
template <int T>
struct SmartDelay<false, T> {
FORCE_INLINE SmartDelay(int v) { DelayCycleFnc(v); }
};
#define DELAY_CYCLES(X) do { SmartDelay<IS_CONSTEXPR(X), IS_CONSTEXPR(X) ? X : 0> _smrtdly_X(X); } while(0)
#if GCC_VERSION <= 70000
#define DELAY_CYCLES_VAR(X) DelayCycleFnc(X)
#else
#define DELAY_CYCLES_VAR DELAY_CYCLES
#endif
// For delay in microseconds, no smart delay selection is required, directly call the delay function
// Teensy compiler is too old and does not accept smart delay compile-time / run-time selection correctly
#define DELAY_US(x) DelayCycleFnc((x) * ((F_CPU) / 1000000UL))
#elif defined(__AVR__)
FORCE_INLINE static void __delay_up_to_3c(uint8_t cycles) {
switch (cycles) {
case 3:
__asm__ __volatile__(A("RJMP .+0") A("NOP"));
break;
case 2:
__asm__ __volatile__(A("RJMP .+0"));
break;
case 1:
__asm__ __volatile__(A("NOP"));
break;
}
}
// Delay in cycles
FORCE_INLINE static void DELAY_CYCLES(uint16_t cycles) {
if (__builtin_constant_p(cycles)) {
if (cycles <= 3) {
__delay_up_to_3c(cycles);
}
else if (cycles == 4) {
__delay_up_to_3c(2);
__delay_up_to_3c(2);
}
else {
cycles -= 1 + 4; // Compensate for the first LDI (1) and the first round (4)
__delay_up_to_3c(cycles % 4);
cycles /= 4;
// The following code burns [1 + 4 * (rounds+1)] cycles
uint16_t dummy;
__asm__ __volatile__(
// "manually" load counter from constants, otherwise the compiler may optimize this part away
A("LDI %A[rounds], %[l]") // 1c
A("LDI %B[rounds], %[h]") // 1c (compensating the non branching BRCC)
L("1")
A("SBIW %[rounds], 1") // 2c
A("BRCC 1b") // 2c when branching, else 1c (end of loop)
: // Outputs ...
[rounds] "=w" (dummy) // Restrict to a wo (=) 16 bit register pair (w)
: // Inputs ...
[l] "M" (cycles%256), // Restrict to 0..255 constant (M)
[h] "M" (cycles/256) // Restrict to 0..255 constant (M)
:// Clobbers ...
"cc" // Indicate we are modifying flags like Carry (cc)
);
}
}
else {
__asm__ __volatile__(
L("1")
A("SBIW %[cycles], 4") // 2c
A("BRCC 1b") // 2c when branching, else 1c (end of loop)
: [cycles] "+w" (cycles) // output: Restrict to a rw (+) 16 bit register pair (w)
: // input: -
: "cc" // clobbers: We are modifying flags like Carry (cc)
);
}
}
// Delay in microseconds
#define DELAY_US(x) DELAY_CYCLES((x) * ((F_CPU) / 1000000UL))
#define DELAY_CYCLES_VAR DELAY_CYCLES
#elif defined(ESP32) || defined(__PLAT_LINUX__) || defined(__PLAT_NATIVE_SIM__)
// DELAY_CYCLES specified inside platform
// Delay in microseconds
#define DELAY_US(x) DELAY_CYCLES((x) * ((F_CPU) / 1000000UL))
#else
#error "Unsupported MCU architecture"
#endif
/**************************************************************
* Delay in nanoseconds. Requires the F_CPU macro.
* These macros follow avr-libc delay conventions.
*
* For AVR there are three possible operation modes, due to its
* slower clock speeds and thus coarser delay resolution. For
* example, when F_CPU = 16000000 the resolution is 62.5ns.
*
* Round up (default)
* Round up the delay according to the CPU clock resolution.
* e.g., 100 will give a delay of 2 cycles (125ns).
*
* Round down (DELAY_NS_ROUND_DOWN)
* Round down the delay according to the CPU clock resolution.
* e.g., 100 will be rounded down to 1 cycle (62.5ns).
*
* Nearest (DELAY_NS_ROUND_CLOSEST)
* Round the delay to the nearest number of clock cycles.
* e.g., 165 will be rounded up to 3 cycles (187.5ns) because
* it's closer to the requested delay than 2 cycle (125ns).
*/
#ifndef __AVR__
#undef DELAY_NS_ROUND_DOWN
#undef DELAY_NS_ROUND_CLOSEST
#endif
#if ENABLED(DELAY_NS_ROUND_DOWN)
#define _NS_TO_CYCLES(x) ( (x) * ((F_CPU) / 1000000UL) / 1000UL) // floor
#elif ENABLED(DELAY_NS_ROUND_CLOSEST)
#define _NS_TO_CYCLES(x) (((x) * ((F_CPU) / 1000000UL) + 500) / 1000UL) // round
#else
#define _NS_TO_CYCLES(x) (((x) * ((F_CPU) / 1000000UL) + 999) / 1000UL) // "ceil"
#endif
#define DELAY_NS(x) DELAY_CYCLES(_NS_TO_CYCLES(x))
#define DELAY_NS_VAR(x) DELAY_CYCLES_VAR(_NS_TO_CYCLES(x))
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/Delay.h
|
C++
|
agpl-3.0
| 7,900
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2022 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/>.
*
*/
/**
* HAL/shared/HAL.cpp
*/
#include "../../inc/MarlinConfig.h"
MarlinHAL hal;
#if ENABLED(SOFT_RESET_VIA_SERIAL)
// Global for use by e_parser.h
void HAL_reboot() { hal.reboot(); }
#endif
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/HAL.cpp
|
C++
|
agpl-3.0
| 1,063
|
/**
* 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
/**
* HAL/shared/HAL_SPI.h
* Core Marlin definitions for SPI, implemented in the HALs
*/
#include "Marduino.h"
#include <stdint.h>
/**
* SPI speed where 0 <= index <= 6
*
* Approximate rates :
*
* 0 : 8 - 10 MHz
* 1 : 4 - 5 MHz
* 2 : 2 - 2.5 MHz
* 3 : 1 - 1.25 MHz
* 4 : 500 - 625 kHz
* 5 : 250 - 312 kHz
* 6 : 125 - 156 kHz
*
* On AVR, actual speed is F_CPU/2^(1 + index).
* On other platforms, speed should be in range given above where possible.
*/
#define SPI_FULL_SPEED 0 // Set SCK to max rate
#define SPI_HALF_SPEED 1 // Set SCK rate to half of max rate
#define SPI_QUARTER_SPEED 2 // Set SCK rate to quarter of max rate
#define SPI_EIGHTH_SPEED 3 // Set SCK rate to 1/8 of max rate
#define SPI_SIXTEENTH_SPEED 4 // Set SCK rate to 1/16 of max rate
#define SPI_SPEED_5 5 // Set SCK rate to 1/32 of max rate
#define SPI_SPEED_6 6 // Set SCK rate to 1/64 of max rate
//
// Standard SPI functions
//
// Initialize SPI bus
void spiBegin();
// Configure SPI for specified SPI speed
void spiInit(uint8_t spiRate);
// Write single byte to SPI
void spiSend(uint8_t b);
// Read single byte from SPI
uint8_t spiRec();
// Read from SPI into buffer
void spiRead(uint8_t *buf, uint16_t nbyte);
// Write token and then write from 512 byte buffer to SPI (for SD card)
void spiSendBlock(uint8_t token, const uint8_t *buf);
// Begin SPI transaction, set clock, bit order, data mode
void spiBeginTransaction(uint32_t spiClock, uint8_t bitOrder, uint8_t dataMode);
//
// Extended SPI functions taking a channel number (Hardware SPI only)
//
// Write single byte to specified SPI channel
void spiSend(uint32_t chan, byte b);
// Write buffer to specified SPI channel
void spiSend(uint32_t chan, const uint8_t *buf, size_t n);
// Read single byte from specified SPI channel
uint8_t spiRec(uint32_t chan);
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/HAL_SPI.h
|
C
|
agpl-3.0
| 2,760
|
/**
* 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
/**
* HAL/ST7920.h
* For the HALs that provide direct access to the ST7920 display
* (bypassing U8G), it will allow the LIGHTWEIGHT_UI to operate.
*/
#if ALL(HAS_MARLINUI_U8GLIB, LIGHTWEIGHT_UI)
void ST7920_cs();
void ST7920_ncs();
void ST7920_set_cmd();
void ST7920_set_dat();
void ST7920_write_byte(const uint8_t data);
#endif
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/HAL_ST7920.h
|
C
|
agpl-3.0
| 1,220
|
/**
* 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
/**
* HAL/shared/Marduino.h
*/
#undef DISABLED // Redefined by ESP32
#undef M_PI // Redefined by all
#undef _BV // Redefined by some
#undef SBI // Redefined by arduino/const_functions.h
#undef CBI // Redefined by arduino/const_functions.h
#undef sq // Redefined by teensy3/wiring.h
#undef UNUSED // Redefined by stm32f4xx_hal_def.h
#include <Arduino.h> // NOTE: If included earlier then this line is a NOOP
#undef DISABLED
#define DISABLED(V...) DO(DIS,&&,V)
#undef _BV
#define _BV(b) (1 << (b))
#ifndef SBI
#define SBI(A,B) (A |= _BV(B))
#endif
#ifndef CBI
#define CBI(A,B) (A &= ~_BV(B))
#endif
#undef sq
#define sq(x) ((x)*(x))
#ifndef __AVR__
#ifndef strchr_P // Some platforms define a macro (DUE, teensy35)
inline const char* strchr_P(const char *s, int c) { return strchr(s,c); }
//#define strchr_P(s,c) strchr(s,c)
#endif
#ifndef snprintf_P
#define snprintf_P snprintf
#endif
#ifndef vsnprintf_P
#define vsnprintf_P vsnprintf
#endif
#endif
// Restart causes
#define RST_POWER_ON 1
#define RST_EXTERNAL 2
#define RST_BROWN_OUT 4
#define RST_WATCHDOG 8
#define RST_JTAG 16
#define RST_SOFTWARE 32
#define RST_BACKUP 64
#ifndef M_PI
#define M_PI 3.14159265358979323846f
#endif
// Remove compiler warning on an unused variable
#ifndef UNUSED
#define UNUSED(x) ((void)(x))
#endif
#ifndef FORCE_INLINE
#define FORCE_INLINE __attribute__((always_inline)) inline
#endif
#include "progmem.h"
class __FlashStringHelper;
typedef const __FlashStringHelper* FSTR_P;
#ifndef FPSTR
#define FPSTR(S) (reinterpret_cast<FSTR_P>(S))
#endif
#define FTOP(S) (reinterpret_cast<const char*>(S))
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/Marduino.h
|
C++
|
agpl-3.0
| 2,604
|
/**
* 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 "MinSerial.h"
#if ENABLED(POSTMORTEM_DEBUGGING)
void HAL_min_serial_init_default() {}
void HAL_min_serial_out_default(char ch) { SERIAL_CHAR(ch); }
void (*HAL_min_serial_init)() = &HAL_min_serial_init_default;
void (*HAL_min_serial_out)(char) = &HAL_min_serial_out_default;
bool MinSerial::force_using_default_output = false;
#endif
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/MinSerial.cpp
|
C++
|
agpl-3.0
| 1,208
|
/**
* 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 "../../core/serial.h"
#include <stdint.h>
// Serial stuff here
// Inside an exception handler, the CPU state is not safe, we can't expect the handler to resume
// and the software to continue. UART communication can't rely on later callback/interrupt as it might never happen.
// So, you need to provide some method to send one byte to the usual UART with the interrupts disabled
// By default, the method uses SERIAL_CHAR but it's 100% guaranteed to break (couldn't be worse than nothing...)7
extern void (*HAL_min_serial_init)();
extern void (*HAL_min_serial_out)(char ch);
struct MinSerial {
static bool force_using_default_output;
// Serial output
static void TX(char ch) {
if (force_using_default_output)
SERIAL_CHAR(ch);
else
HAL_min_serial_out(ch);
}
// Send String through UART
static void TX(const char *s) { while (*s) TX(*s++); }
// Send a digit through UART
static void TXDigit(uint32_t d) {
if (d < 10) TX((char)(d+'0'));
else if (d < 16) TX((char)(d+'A'-10));
else TX('?');
}
// Send Hex number through UART
static void TXHex(uint32_t v) {
TX("0x");
for (uint8_t i = 0; i < 8; i++, v <<= 4)
TXDigit((v >> 28) & 0xF);
}
// Send Decimal number through UART
static void TXDec(uint32_t v) {
if (!v) {
TX('0');
return;
}
char nbrs[14];
char *p = &nbrs[0];
while (v != 0) {
*p++ = '0' + (v % 10);
v /= 10;
}
do {
p--;
TX(*p);
} while (p != &nbrs[0]);
}
static void init() { if (!force_using_default_output) HAL_min_serial_init(); }
};
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/MinSerial.h
|
C
|
agpl-3.0
| 2,479
|
/**
* 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/>.
*
*/
#if defined(__arm__) || defined(__thumb__)
#include "backtrace.h"
#include "unwinder.h"
#include "unwmemaccess.h"
#include "../MinSerial.h"
#include <stdarg.h>
// Dump a backtrace entry
static bool UnwReportOut(void *ctx, const UnwReport *bte) {
int *p = (int*)ctx;
(*p)++;
const uint32_t a = bte->address, f = bte->function;
MinSerial::TX('#'); MinSerial::TXDec(*p); MinSerial::TX(" : ");
MinSerial::TX(bte->name?:"unknown"); MinSerial::TX('@'); MinSerial::TXHex(f);
MinSerial::TX('+'); MinSerial::TXDec(a - f);
MinSerial::TX(" PC:"); MinSerial::TXHex(a);
MinSerial::TX('\n');
return true;
}
#ifdef UNW_DEBUG
void UnwPrintf(const char *format, ...) {
char dest[256];
va_list argptr;
va_start(argptr, format);
vsprintf(dest, format, argptr);
va_end(argptr);
MinSerial::TX(&dest[0]);
}
#endif
/* Table of function pointers for passing to the unwinder */
static const UnwindCallbacks UnwCallbacks = {
UnwReportOut,
UnwReadW,
UnwReadH,
UnwReadB
#ifdef UNW_DEBUG
, UnwPrintf
#endif
};
// Perform a backtrace to the serial port
void backtrace() {
unsigned long sp = 0, lr = 0, pc = 0;
// Capture the values of the registers to perform the traceback
__asm__ __volatile__ (
" mov %[lrv],lr\n"
" mov %[spv],sp\n"
" mov %[pcv],pc\n"
: [spv]"+r"( sp ),
[lrv]"+r"( lr ),
[pcv]"+r"( pc )
::
);
backtrace_ex(sp, lr, pc);
}
void backtrace_ex(unsigned long sp, unsigned long lr, unsigned long pc) {
UnwindFrame btf;
// Fill the traceback structure
btf.sp = sp;
btf.fp = btf.sp;
btf.lr = lr;
btf.pc = pc | 1; // Force Thumb, as CORTEX only support it
// Perform a backtrace
MinSerial::TX("Backtrace:");
int ctr = 0;
UnwindStart(&btf, &UnwCallbacks, &ctr);
}
#else // !__arm__ && !__thumb__
void backtrace() {}
#endif // __arm__ || __thumb__
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/backtrace.cpp
|
C++
|
agpl-3.0
| 2,749
|
/**
* 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
// Perform a backtrace to the serial port
void backtrace();
// Perform a backtrace to the serial port
void backtrace_ex(unsigned long sp, unsigned long lr, unsigned long pc);
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/backtrace.h
|
C
|
agpl-3.0
| 1,052
|
/***************************************************************************
* ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk
* Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle
*
* This program is PUBLIC DOMAIN.
* This means that there is no copyright and anyone is able to take a copy
* for free and use it as they wish, with or without modifications, and in
* any context, commercially or otherwise. The only limitation is that I
* don't guarantee that the software is fit for any purpose or accept any
* liability for its use or misuse - this software is without warranty.
***************************************************************************
* File Description: Utility functions and glue for ARM unwinding sub-modules.
**************************************************************************/
#if defined(__arm__) || defined(__thumb__)
#define MODULE_NAME "UNWARM"
#include <stdint.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "unwarm.h"
#include "unwarmmem.h"
#ifdef UNW_DEBUG
/**
* Printf wrapper.
* This is used such that alternative outputs for any output can be selected
* by modification of this wrapper function.
*/
void UnwPrintf(const char *format, ...) {
va_list args;
va_start(args, format);
vprintf(format, args);
va_end(args);
}
#endif
/**
* Invalidate all general purpose registers.
*/
void UnwInvalidateRegisterFile(RegData *regFile) {
uint8_t t = 0;
do {
regFile[t].o = REG_VAL_INVALID;
t++;
} while (t < 13);
}
/**
* Initialize the data used for unwinding.
*/
void UnwInitState(UnwState * const state, /**< Pointer to structure to fill. */
const UnwindCallbacks *cb, /**< Callbacks. */
void *rptData, /**< Data to pass to report function. */
uint32_t pcValue, /**< PC at which to start unwinding. */
uint32_t spValue) { /**< SP at which to start unwinding. */
UnwInvalidateRegisterFile(state->regData);
/* Store the pointer to the callbacks */
state->cb = cb;
state->reportData = rptData;
/* Setup the SP and PC */
state->regData[13].v = spValue;
state->regData[13].o = REG_VAL_FROM_CONST;
state->regData[15].v = pcValue;
state->regData[15].o = REG_VAL_FROM_CONST;
UnwPrintd3("\nInitial: PC=0x%08x SP=0x%08x\n", pcValue, spValue);
/* Invalidate all memory addresses */
memset(state->memData.used, 0, sizeof(state->memData.used));
}
// Detect if function names are available
static int __attribute__ ((noinline)) has_function_names() {
uint32_t flag_word = ((uint32_t*)(((uint32_t)(&has_function_names)) & (-4))) [-1];
return ((flag_word & 0xFF000000) == 0xFF000000) ? 1 : 0;
}
/**
* Call the report function to indicate some return address.
* This returns the value of the report function, which if true
* indicates that unwinding may continue.
*/
bool UnwReportRetAddr(UnwState * const state, uint32_t addr) {
UnwReport entry;
// We found two acceptable values.
entry.name = nullptr;
entry.address = addr & 0xFFFFFFFE; // Remove Thumb bit
entry.function = 0;
// If there are function names, try to solve name
if (has_function_names()) {
// Lets find the function name, if possible
// Align address to 4 bytes
uint32_t pf = addr & (-4);
// Scan backwards until we find the function name
uint32_t v;
while (state->cb->readW(pf-4,&v)) {
// Check if name descriptor is valid
if ((v & 0xFFFFFF00) == 0xFF000000 && (v & 0xFF) > 1) {
// Assume the name was found!
entry.name = ((const char*)pf) - 4 - (v & 0xFF);
entry.function = pf;
break;
}
// Go backwards to the previous word
pf -= 4;
}
}
/* Cast away const from reportData.
* The const is only to prevent the unw module modifying the data.
*/
return state->cb->report((void *)state->reportData, &entry);
}
/**
* Write some register to memory.
* This will store some register and meta data onto the virtual stack.
* The address for the write
* \param state [in/out] The unwinding state.
* \param wAddr [in] The address at which to write the data.
* \param reg [in] The register to store.
* \return true if the write was successful, false otherwise.
*/
bool UnwMemWriteRegister(UnwState * const state, const uint32_t addr, const RegData * const reg) {
return UnwMemHashWrite(&state->memData, addr, reg->v, M_IsOriginValid(reg->o));
}
/**
* Read a register from memory.
* This will read a register from memory, and setup the meta data.
* If the register has been previously written to memory using
* UnwMemWriteRegister, the local hash will be used to return the
* value while respecting whether the data was valid or not. If the
* register was previously written and was invalid at that point,
* REG_VAL_INVALID will be returned in *reg.
* \param state [in] The unwinding state.
* \param addr [in] The address to read.
* \param reg [out] The result, containing the data value and the origin
* which will be REG_VAL_FROM_MEMORY, or REG_VAL_INVALID.
* \return true if the address could be read and *reg has been filled in.
* false is the data could not be read.
*/
bool UnwMemReadRegister(UnwState * const state, const uint32_t addr, RegData * const reg) {
bool tracked;
// Check if the value can be found in the hash
if (UnwMemHashRead(&state->memData, addr, ®->v, &tracked)) {
reg->o = tracked ? REG_VAL_FROM_MEMORY : REG_VAL_INVALID;
return true;
}
else if (state->cb->readW(addr, ®->v)) { // Not in the hash, so read from real memory
reg->o = REG_VAL_FROM_MEMORY;
return true;
}
else return false; // Not in the hash, and failed to read from memory
}
#endif // __arm__ || __thumb__
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/unwarm.cpp
|
C++
|
agpl-3.0
| 5,872
|
/***************************************************************************
* ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk
*
* This program is PUBLIC DOMAIN.
* This means that there is no copyright and anyone is able to take a copy
* for free and use it as they wish, with or without modifications, and in
* any context, commercially or otherwise. The only limitation is that I
* don't guarantee that the software is fit for any purpose or accept any
* liability for its use or misuse - this software is without warranty.
***************************************************************************
* File Description: Internal interface between the ARM unwinding sub-modules.
**************************************************************************/
#pragma once
#include "unwinder.h"
/** The maximum number of instructions to interpet in a function.
* Unwinding will be unconditionally stopped and UNWIND_EXHAUSTED returned
* if more than this number of instructions are interpreted in a single
* function without unwinding a stack frame. This prevents infinite loops
* or corrupted program memory from preventing unwinding from progressing.
*/
#define UNW_MAX_INSTR_COUNT 500
/** The size of the hash used to track reads and writes to memory.
* This should be a prime value for efficiency.
*/
#define MEM_HASH_SIZE 31
/***************************************************************************
* Type Definitions
**************************************************************************/
typedef enum {
/** Invalid value. */
REG_VAL_INVALID = 0x00,
REG_VAL_FROM_STACK = 0x01,
REG_VAL_FROM_MEMORY = 0x02,
REG_VAL_FROM_CONST = 0x04,
REG_VAL_ARITHMETIC = 0x80
} RegValOrigin;
/** Type for tracking information about a register.
* This stores the register value, as well as other data that helps unwinding.
*/
typedef struct {
/** The value held in the register. */
uint32_t v;
/** The origin of the register value.
* This is used to track how the value in the register was loaded.
*/
int o; /* (RegValOrigin) */
} RegData;
/** Structure used to track reads and writes to memory.
* This structure is used as a hash to store a small number of writes
* to memory.
*/
typedef struct {
/** Memory contents. */
uint32_t v[MEM_HASH_SIZE];
/** Address at which v[n] represents. */
uint32_t a[MEM_HASH_SIZE];
/** Indicates whether the data in v[n] and a[n] is occupied.
* Each bit represents one hash value.
*/
uint8_t used[(MEM_HASH_SIZE + 7) / 8];
/** Indicates whether the data in v[n] is valid.
* This allows a[n] to be set, but for v[n] to be marked as invalid.
* Specifically this is needed for when an untracked register value
* is written to memory.
*/
uint8_t tracked[(MEM_HASH_SIZE + 7) / 8];
} MemData;
/** Structure that is used to keep track of unwinding meta-data.
* This data is passed between all the unwinding functions.
*/
typedef struct {
/** The register values and meta-data. */
RegData regData[16];
/** Memory tracking data. */
MemData memData;
/** Pointer to the callback functions */
const UnwindCallbacks *cb;
/** Pointer to pass to the report function. */
const void *reportData;
} UnwState;
/***************************************************************************
* Macros
**************************************************************************/
#define M_IsOriginValid(v) !!((v) & 0x7F)
#define M_Origin2Str(v) ((v) ? "VALID" : "INVALID")
#ifdef UNW_DEBUG
#define UnwPrintd1(a) state->cb->printf(a)
#define UnwPrintd2(a,b) state->cb->printf(a,b)
#define UnwPrintd3(a,b,c) state->cb->printf(a,b,c)
#define UnwPrintd4(a,b,c,d) state->cb->printf(a,b,c,d)
#define UnwPrintd5(a,b,c,d,e) state->cb->printf(a,b,c,d,e)
#define UnwPrintd6(a,b,c,d,e,f) state->cb->printf(a,b,c,d,e,f)
#define UnwPrintd7(a,b,c,d,e,f,g) state->cb->printf(a,b,c,d,e,f,g)
#define UnwPrintd8(a,b,c,d,e,f,g,h) state->cb->printf(a,b,c,d,e,f,g,h)
#else
#define UnwPrintd1(a)
#define UnwPrintd2(a,b)
#define UnwPrintd3(a,b,c)
#define UnwPrintd4(a,b,c,d)
#define UnwPrintd5(a,b,c,d,e)
#define UnwPrintd6(a,b,c,d,e,f)
#define UnwPrintd7(a,b,c,d,e,f,g)
#define UnwPrintd8(a,b,c,d,e,f,g,h)
#endif
/***************************************************************************
* Function Prototypes
**************************************************************************/
UnwResult UnwStartArm(UnwState * const state);
UnwResult UnwStartThumb(UnwState * const state);
void UnwInvalidateRegisterFile(RegData *regFile);
void UnwInitState(UnwState * const state, const UnwindCallbacks *cb, void *rptData, uint32_t pcValue, uint32_t spValue);
bool UnwReportRetAddr(UnwState * const state, uint32_t addr);
bool UnwMemWriteRegister(UnwState * const state, const uint32_t addr, const RegData * const reg);
bool UnwMemReadRegister(UnwState * const state, const uint32_t addr, RegData * const reg);
void UnwMemHashGC(UnwState * const state);
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/unwarm.h
|
C
|
agpl-3.0
| 5,038
|
/***************************************************************************
* ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk
* Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle
*
* This program is PUBLIC DOMAIN.
* This means that there is no copyright and anyone is able to take a copy
* for free and use it as they wish, with or without modifications, and in
* any context, commercially or otherwise. The only limitation is that I
* don't guarantee that the software is fit for any purpose or accept any
* liability for its use or misuse - this software is without warranty.
***************************************************************************
* File Description: Abstract interpreter for ARM mode.
**************************************************************************/
#if defined(__arm__) || defined(__thumb__)
#define MODULE_NAME "UNWARM_ARM"
#include <stdio.h>
#include "unwarm.h"
/** Check if some instruction is a data-processing instruction.
* Decodes the passed instruction, checks if it is a data-processing and
* verifies that the parameters and operation really indicate a data-
* processing instruction. This is needed because some parts of the
* instruction space under this instruction can be extended or represent
* other operations such as MRS, MSR.
*
* \param[in] inst The instruction word.
* \retval true Further decoding of the instruction indicates that this is
* a valid data-processing instruction.
* \retval false This is not a data-processing instruction,
*/
static bool isDataProc(uint32_t instr) {
uint8_t opcode = (instr & 0x01E00000) >> 21;
if ((instr & 0xFC000000) != 0xE0000000) return false;
/* TST, TEQ, CMP and CMN all require S to be set */
bool S = !!(instr & 0x00100000);
if (!S && opcode >= 8 && opcode <= 11) return false;
return true;
}
UnwResult UnwStartArm(UnwState * const state) {
uint16_t t = UNW_MAX_INSTR_COUNT;
for (;;) {
uint32_t instr;
/* Attempt to read the instruction */
if (!state->cb->readW(state->regData[15].v, &instr))
return UNWIND_IREAD_W_FAIL;
UnwPrintd4("A %x %x %08x:", state->regData[13].v, state->regData[15].v, instr);
/* Check that the PC is still on Arm alignment */
if (state->regData[15].v & 0x3) {
UnwPrintd1("\nError: PC misalignment\n");
return UNWIND_INCONSISTENT;
}
/* Check that the SP and PC have not been invalidated */
if (!M_IsOriginValid(state->regData[13].o) || !M_IsOriginValid(state->regData[15].o)) {
UnwPrintd1("\nError: PC or SP invalidated\n");
return UNWIND_INCONSISTENT;
}
/* Branch and Exchange (BX)
* This is tested prior to data processing to prevent
* mis-interpretation as an invalid TEQ instruction.
*/
if ((instr & 0xFFFFFFF0) == 0xE12FFF10) {
uint8_t rn = instr & 0xF;
UnwPrintd4("BX r%d\t ; r%d %s\n", rn, rn, M_Origin2Str(state->regData[rn].o));
if (!M_IsOriginValid(state->regData[rn].o)) {
UnwPrintd1("\nUnwind failure: BX to untracked register\n");
return UNWIND_FAILURE;
}
/* Set the new PC value */
state->regData[15].v = state->regData[rn].v;
/* Check if the return value is from the stack */
if (state->regData[rn].o == REG_VAL_FROM_STACK) {
/* Now have the return address */
UnwPrintd2(" Return PC=%x\n", state->regData[15].v & (~0x1));
/* Report the return address */
if (!UnwReportRetAddr(state, state->regData[rn].v))
return UNWIND_TRUNCATED;
}
/* Determine the return mode */
if (state->regData[rn].v & 0x1) /* Branching to THUMB */
return UnwStartThumb(state);
/* Branch to ARM */
/* Account for the auto-increment which isn't needed */
state->regData[15].v -= 4;
}
/* Branch */
else if ((instr & 0xFF000000) == 0xEA000000) {
int32_t offset = (instr & 0x00FFFFFF) << 2;
/* Sign extend if needed */
if (offset & 0x02000000) offset |= 0xFC000000;
UnwPrintd2("B %d\n", offset);
/* Adjust PC */
state->regData[15].v += offset;
/* Account for pre-fetch, where normally the PC is 8 bytes
* ahead of the instruction just executed.
*/
state->regData[15].v += 4;
}
/* MRS */
else if ((instr & 0xFFBF0FFF) == 0xE10F0000) {
uint8_t rd = (instr & 0x0000F000) >> 12;
#ifdef UNW_DEBUG
const bool R = !!(instr & 0x00400000);
UnwPrintd4("MRS r%d,%s\t; r%d invalidated", rd, R ? "SPSR" : "CPSR", rd);
#endif
/* Status registers untracked */
state->regData[rd].o = REG_VAL_INVALID;
}
/* MSR */
else if ((instr & 0xFFB0F000) == 0xE120F000) {
#ifdef UNW_DEBUG
UnwPrintd2("MSR %s_?, ???", (instr & 0x00400000) ? "SPSR" : "CPSR");
#endif
/* Status registers untracked.
* Potentially this could change processor mode and switch
* banked registers r8-r14. Most likely is that r13 (sp) will
* be banked. However, invalidating r13 will stop unwinding
* when potentially this write is being used to disable/enable
* interrupts (a common case). Therefore no invalidation is
* performed.
*/
}
/* Data processing */
else if (isDataProc(instr)) {
bool I = !!(instr & 0x02000000);
uint8_t opcode = (instr & 0x01E00000) >> 21;
#ifdef UNW_DEBUG
bool S = !!(instr & 0x00100000);
#endif
uint8_t rn = (instr & 0x000F0000) >> 16;
uint8_t rd = (instr & 0x0000F000) >> 12;
uint16_t operand2 = (instr & 0x00000FFF);
uint32_t op2val;
int op2origin;
switch (opcode) {
case 0: UnwPrintd4("AND%s r%d,r%d,", S ? "S" : "", rd, rn); break;
case 1: UnwPrintd4("EOR%s r%d,r%d,", S ? "S" : "", rd, rn); break;
case 2: UnwPrintd4("SUB%s r%d,r%d,", S ? "S" : "", rd, rn); break;
case 3: UnwPrintd4("RSB%s r%d,r%d,", S ? "S" : "", rd, rn); break;
case 4: UnwPrintd4("ADD%s r%d,r%d,", S ? "S" : "", rd, rn); break;
case 5: UnwPrintd4("ADC%s r%d,r%d,", S ? "S" : "", rd, rn); break;
case 6: UnwPrintd4("SBC%s r%d,r%d,", S ? "S" : "", rd, rn); break;
case 7: UnwPrintd4("RSC%s r%d,r%d,", S ? "S" : "", rd, rn); break;
case 8: UnwPrintd3("TST%s r%d,", S ? "S" : "", rn); break;
case 9: UnwPrintd3("TEQ%s r%d,", S ? "S" : "", rn); break;
case 10: UnwPrintd3("CMP%s r%d,", S ? "S" : "", rn); break;
case 11: UnwPrintd3("CMN%s r%d,", S ? "S" : "", rn); break;
case 12: UnwPrintd3("ORR%s r%d,", S ? "S" : "", rn); break;
case 13: UnwPrintd3("MOV%s r%d,", S ? "S" : "", rd); break;
case 14: UnwPrintd4("BIC%s r%d,r%d", S ? "S" : "", rd, rn); break;
case 15: UnwPrintd3("MVN%s r%d,", S ? "S" : "", rd); break;
}
/* Decode operand 2 */
if (I) {
uint8_t shiftDist = (operand2 & 0x0F00) >> 8;
uint8_t shiftConst = (operand2 & 0x00FF);
/* rotate const right by 2 * shiftDist */
shiftDist *= 2;
op2val = (shiftConst >> shiftDist) |
(shiftConst << (32 - shiftDist));
op2origin = REG_VAL_FROM_CONST;
UnwPrintd2("#0x%x", op2val);
}
else {
/* Register and shift */
uint8_t rm = (operand2 & 0x000F);
uint8_t regShift = !!(operand2 & 0x0010);
uint8_t shiftType = (operand2 & 0x0060) >> 5;
uint32_t shiftDist;
#ifdef UNW_DEBUG
const char * const shiftMnu[4] = { "LSL", "LSR", "ASR", "ROR" };
#endif
UnwPrintd2("r%d ", rm);
/* Get the shift distance */
if (regShift) {
uint8_t rs = (operand2 & 0x0F00) >> 8;
if (operand2 & 0x00800) {
UnwPrintd1("\nError: Bit should be zero\n");
return UNWIND_ILLEGAL_INSTR;
}
else if (rs == 15) {
UnwPrintd1("\nError: Cannot use R15 with register shift\n");
return UNWIND_ILLEGAL_INSTR;
}
/* Get shift distance */
shiftDist = state->regData[rs].v;
op2origin = state->regData[rs].o;
UnwPrintd7("%s r%d\t; r%d %s r%d %s", shiftMnu[shiftType], rs, rm, M_Origin2Str(state->regData[rm].o), rs, M_Origin2Str(state->regData[rs].o));
}
else {
shiftDist = (operand2 & 0x0F80) >> 7;
op2origin = REG_VAL_FROM_CONST;
if (shiftDist) UnwPrintd3("%s #%d", shiftMnu[shiftType], shiftDist);
UnwPrintd3("\t; r%d %s", rm, M_Origin2Str(state->regData[rm].o));
}
/* Apply the shift type to the source register */
switch (shiftType) {
case 0: /* logical left */
op2val = state->regData[rm].v << shiftDist;
break;
case 1: /* logical right */
if (!regShift && shiftDist == 0) shiftDist = 32;
op2val = state->regData[rm].v >> shiftDist;
break;
case 2: /* arithmetic right */
if (!regShift && shiftDist == 0) shiftDist = 32;
if (state->regData[rm].v & 0x80000000) {
/* Register shifts maybe greater than 32 */
if (shiftDist >= 32)
op2val = 0xFFFFFFFF;
else
op2val = (state->regData[rm].v >> shiftDist) | (0xFFFFFFFF << (32 - shiftDist));
}
else
op2val = state->regData[rm].v >> shiftDist;
break;
case 3: /* rotate right */
if (!regShift && shiftDist == 0) {
/* Rotate right with extend.
* This uses the carry bit and so always has an
* untracked result.
*/
op2origin = REG_VAL_INVALID;
op2val = 0;
}
else {
/* Limit shift distance to 0-31 incase of register shift */
shiftDist &= 0x1F;
op2val = (state->regData[rm].v >> shiftDist) |
(state->regData[rm].v << (32 - shiftDist));
}
break;
default:
UnwPrintd2("\nError: Invalid shift type: %d\n", shiftType);
return UNWIND_FAILURE;
}
/* Decide the data origin */
if (M_IsOriginValid(op2origin) && M_IsOriginValid(state->regData[rm].o))
op2origin = REG_VAL_ARITHMETIC | state->regData[rm].o;
else
op2origin = REG_VAL_INVALID;
}
/* Propagate register validity */
switch (opcode) {
case 0: /* AND: Rd := Op1 AND Op2 */
case 1: /* EOR: Rd := Op1 EOR Op2 */
case 2: /* SUB: Rd:= Op1 - Op2 */
case 3: /* RSB: Rd:= Op2 - Op1 */
case 4: /* ADD: Rd:= Op1 + Op2 */
case 12: /* ORR: Rd:= Op1 OR Op2 */
case 14: /* BIC: Rd:= Op1 AND NOT Op2 */
if (!M_IsOriginValid(state->regData[rn].o) ||
!M_IsOriginValid(op2origin)) {
state->regData[rd].o = REG_VAL_INVALID;
}
else {
state->regData[rd].o = state->regData[rn].o;
state->regData[rd].o = (RegValOrigin)(state->regData[rd].o | op2origin);
}
break;
case 5: /* ADC: Rd:= Op1 + Op2 + C */
case 6: /* SBC: Rd:= Op1 - Op2 + C */
case 7: /* RSC: Rd:= Op2 - Op1 + C */
/* CPSR is not tracked */
state->regData[rd].o = REG_VAL_INVALID;
break;
case 8: /* TST: set condition codes on Op1 AND Op2 */
case 9: /* TEQ: set condition codes on Op1 EOR Op2 */
case 10: /* CMP: set condition codes on Op1 - Op2 */
case 11: /* CMN: set condition codes on Op1 + Op2 */
break;
case 13: /* MOV: Rd:= Op2 */
case 15: /* MVN: Rd:= NOT Op2 */
state->regData[rd].o = (RegValOrigin) op2origin;
break;
}
/* Account for pre-fetch by temporarily adjusting PC */
if (rn == 15) {
/* If the shift amount is specified in the instruction,
* the PC will be 8 bytes ahead. If a register is used
* to specify the shift amount the PC will be 12 bytes
* ahead.
*/
state->regData[rn].v += ((!I && (operand2 & 0x0010)) ? 12 : 8);
}
/* Compute values */
switch (opcode) {
case 0: /* AND: Rd := Op1 AND Op2 */
state->regData[rd].v = state->regData[rn].v & op2val;
break;
case 1: /* EOR: Rd := Op1 EOR Op2 */
state->regData[rd].v = state->regData[rn].v ^ op2val;
break;
case 2: /* SUB: Rd:= Op1 - Op2 */
state->regData[rd].v = state->regData[rn].v - op2val;
break;
case 3: /* RSB: Rd:= Op2 - Op1 */
state->regData[rd].v = op2val - state->regData[rn].v;
break;
case 4: /* ADD: Rd:= Op1 + Op2 */
state->regData[rd].v = state->regData[rn].v + op2val;
break;
case 5: /* ADC: Rd:= Op1 + Op2 + C */
case 6: /* SBC: Rd:= Op1 - Op2 + C */
case 7: /* RSC: Rd:= Op2 - Op1 + C */
case 8: /* TST: set condition codes on Op1 AND Op2 */
case 9: /* TEQ: set condition codes on Op1 EOR Op2 */
case 10: /* CMP: set condition codes on Op1 - Op2 */
case 11: /* CMN: set condition codes on Op1 + Op2 */
UnwPrintd1("\t; ????");
break;
case 12: /* ORR: Rd:= Op1 OR Op2 */
state->regData[rd].v = state->regData[rn].v | op2val;
break;
case 13: /* MOV: Rd:= Op2 */
state->regData[rd].v = op2val;
break;
case 14: /* BIC: Rd:= Op1 AND NOT Op2 */
state->regData[rd].v = state->regData[rn].v & (~op2val);
break;
case 15: /* MVN: Rd:= NOT Op2 */
state->regData[rd].v = ~op2val;
break;
}
/* Remove the prefetch offset from the PC */
if (rd != 15 && rn == 15)
state->regData[rn].v -= ((!I && (operand2 & 0x0010)) ? 12 : 8);
}
/* Block Data Transfer
* LDM, STM
*/
else if ((instr & 0xFE000000) == 0xE8000000) {
bool P = !!(instr & 0x01000000),
U = !!(instr & 0x00800000),
S = !!(instr & 0x00400000),
W = !!(instr & 0x00200000),
L = !!(instr & 0x00100000);
uint16_t baseReg = (instr & 0x000F0000) >> 16;
uint16_t regList = (instr & 0x0000FFFF);
uint32_t addr = state->regData[baseReg].v;
bool addrValid = M_IsOriginValid(state->regData[baseReg].o);
int8_t r;
#ifdef UNW_DEBUG
/* Display the instruction */
if (L)
UnwPrintd6("LDM%c%c r%d%s, {reglist}%s\n", P ? 'E' : 'F', U ? 'D' : 'A', baseReg, W ? "!" : "", S ? "^" : "");
else
UnwPrintd6("STM%c%c r%d%s, {reglist}%s\n", !P ? 'E' : 'F', !U ? 'D' : 'A', baseReg, W ? "!" : "", S ? "^" : "");
#endif
/* S indicates that banked registers (untracked) are used, unless
* this is a load including the PC when the S-bit indicates that
* that CPSR is loaded from SPSR (also untracked, but ignored).
*/
if (S && (!L || (regList & (0x01 << 15)) == 0)) {
UnwPrintd1("\nError:S-bit set requiring banked registers\n");
return UNWIND_FAILURE;
}
else if (baseReg == 15) {
UnwPrintd1("\nError: r15 used as base register\n");
return UNWIND_FAILURE;
}
else if (regList == 0) {
UnwPrintd1("\nError: Register list empty\n");
return UNWIND_FAILURE;
}
/* Check if ascending or descending.
* Registers are loaded/stored in order of address.
* i.e. r0 is at the lowest address, r15 at the highest.
*/
r = U ? 0 : 15;
do {
/* Check if the register is to be transferred */
if (regList & (0x01 << r)) {
if (P) addr += U ? 4 : -4;
if (L) {
if (addrValid) {
if (!UnwMemReadRegister(state, addr, &state->regData[r]))
return UNWIND_DREAD_W_FAIL;
/* Update the origin if read via the stack pointer */
if (M_IsOriginValid(state->regData[r].o) && baseReg == 13)
state->regData[r].o = REG_VAL_FROM_STACK;
UnwPrintd5(" R%d = 0x%08x\t; r%d %s\n",r,state->regData[r].v,r, M_Origin2Str(state->regData[r].o));
}
else {
/* Invalidate the register as the base reg was invalid */
state->regData[r].o = REG_VAL_INVALID;
UnwPrintd2(" R%d = ???\n", r);
}
}
else {
if (addrValid && !UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DWRITE_W_FAIL;
UnwPrintd2(" R%d = 0x%08x\n", r);
}
if (!P) addr += U ? 4 : -4;
}
/* Check the next register */
r += U ? 1 : -1;
} while (r >= 0 && r <= 15);
/* Check the writeback bit */
if (W) state->regData[baseReg].v = addr;
/* Check if the PC was loaded */
if (L && (regList & (0x01 << 15))) {
if (!M_IsOriginValid(state->regData[15].o)) {
/* Return address is not valid */
UnwPrintd1("PC popped with invalid address\n");
return UNWIND_FAILURE;
}
else {
/* Store the return address */
if (!UnwReportRetAddr(state, state->regData[15].v))
return UNWIND_TRUNCATED;
UnwPrintd2(" Return PC=0x%x", state->regData[15].v);
/* Determine the return mode */
if (state->regData[15].v & 0x1) {
/* Branching to THUMB */
return UnwStartThumb(state);
}
else {
/* Branch to ARM */
/* Account for the auto-increment which isn't needed */
state->regData[15].v -= 4;
}
}
}
}
else {
UnwPrintd1("????");
/* Unknown/undecoded. May alter some register, so invalidate file */
UnwInvalidateRegisterFile(state->regData);
}
UnwPrintd1("\n");
/* Should never hit the reset vector */
if (state->regData[15].v == 0) return UNWIND_RESET;
/* Check next address */
state->regData[15].v += 4;
/* Garbage collect the memory hash (used only for the stack) */
UnwMemHashGC(state);
if (--t == 0) return UNWIND_EXHAUSTED;
}
return UNWIND_UNSUPPORTED;
}
#endif // __arm__ || __thumb__
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/unwarm_arm.cpp
|
C++
|
agpl-3.0
| 18,679
|
/***************************************************************************
* ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk
* Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle
*
* This program is PUBLIC DOMAIN.
* This means that there is no copyright and anyone is able to take a copy
* for free and use it as they wish, with or without modifications, and in
* any context, commercially or otherwise. The only limitation is that I
* don't guarantee that the software is fit for any purpose or accept any
* liability for its use or misuse - this software is without warranty.
***************************************************************************
* File Description: Abstract interpretation for Thumb mode.
**************************************************************************/
#if defined(__arm__) || defined(__thumb__)
#define MODULE_NAME "UNWARM_THUMB"
#include <stdio.h>
#include "unwarm.h"
/** Sign extend an 11 bit value.
* This function simply inspects bit 11 of the input \a value, and if
* set, the top 5 bits are set to give a 2's compliment signed value.
* \param value The value to sign extend.
* \return The signed-11 bit value stored in a 16bit data type.
*/
static int32_t signExtend11(const uint16_t value) {
return (value & 0x400) ? value | 0xFFFFF800 : value;
}
UnwResult UnwStartThumb(UnwState * const state) {
uint16_t t = UNW_MAX_INSTR_COUNT;
uint32_t lastJumpAddr = 0; // Last JUMP address, to try to detect infinite loops
bool loopDetected = false; // If a loop was detected
for (;;) {
uint16_t instr;
/* Attempt to read the instruction */
if (!state->cb->readH(state->regData[15].v & (~0x1), &instr))
return UNWIND_IREAD_H_FAIL;
UnwPrintd4("T %x %x %04x:", state->regData[13].v, state->regData[15].v, instr);
/* Check that the PC is still on Thumb alignment */
if (!(state->regData[15].v & 0x1)) {
UnwPrintd1("\nError: PC misalignment\n");
return UNWIND_INCONSISTENT;
}
/* Check that the SP and PC have not been invalidated */
if (!M_IsOriginValid(state->regData[13].o) || !M_IsOriginValid(state->regData[15].o)) {
UnwPrintd1("\nError: PC or SP invalidated\n");
return UNWIND_INCONSISTENT;
}
/*
* Detect 32bit thumb instructions
*/
if ((instr & 0xE000) == 0xE000 && (instr & 0x1800) != 0) {
uint16_t instr2;
/* Check next address */
state->regData[15].v += 2;
/* Attempt to read the 2nd part of the instruction */
if (!state->cb->readH(state->regData[15].v & (~0x1), &instr2))
return UNWIND_IREAD_H_FAIL;
UnwPrintd3(" %x %04x:", state->regData[15].v, instr2);
/*
* Load/Store multiple: Only interpret
* PUSH and POP
*/
if ((instr & 0xFE6F) == 0xE82D) {
bool L = !!(instr & 0x10);
uint16_t rList = instr2;
if (L) {
uint8_t r;
/* Load from memory: POP */
UnwPrintd1("POP {Rlist}\n");
/* Load registers from stack */
for (r = 0; r < 16; r++) {
if (rList & (0x1 << r)) {
/* Read the word */
if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DREAD_W_FAIL;
/* Alter the origin to be from the stack if it was valid */
if (M_IsOriginValid(state->regData[r].o)) {
state->regData[r].o = REG_VAL_FROM_STACK;
/* If restoring the PC */
if (r == 15) {
/* The bottom bit should have been set to indicate that
* the caller was from Thumb. This would allow return
* by BX for interworking APCS.
*/
if ((state->regData[15].v & 0x1) == 0) {
UnwPrintd2("Warning: Return address not to Thumb: 0x%08x\n", state->regData[15].v);
/* Pop into the PC will not switch mode */
return UNWIND_INCONSISTENT;
}
/* Store the return address */
if (!UnwReportRetAddr(state, state->regData[15].v))
return UNWIND_TRUNCATED;
/* Now have the return address */
UnwPrintd2(" Return PC=%x\n", state->regData[15].v);
/* Compensate for the auto-increment, which isn't needed here */
state->regData[15].v -= 2;
}
} else {
if (r == 15) {
/* Return address is not valid */
UnwPrintd1("PC popped with invalid address\n");
return UNWIND_FAILURE;
}
}
state->regData[13].v += 4;
UnwPrintd3(" r%d = 0x%08x\n", r, state->regData[r].v);
}
}
}
else {
int8_t r;
/* Store to memory: PUSH */
UnwPrintd1("PUSH {Rlist}");
for (r = 15; r >= 0; r--) {
if (rList & (0x1 << r)) {
UnwPrintd4("\n r%d = 0x%08x\t; %s", r, state->regData[r].v, M_Origin2Str(state->regData[r].o));
state->regData[13].v -= 4;
if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DWRITE_W_FAIL;
}
}
}
}
/*
* PUSH register
*/
else if (instr == 0xF84D && (instr2 & 0x0FFF) == 0x0D04) {
uint8_t r = instr2 >> 12;
/* Store to memory: PUSH */
UnwPrintd2("PUSH {R%d}\n", r);
UnwPrintd4("\n r%d = 0x%08x\t; %s", r, state->regData[r].v, M_Origin2Str(state->regData[r].o));
state->regData[13].v -= 4;
if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DWRITE_W_FAIL;
}
/*
* POP register
*/
else if (instr == 0xF85D && (instr2 & 0x0FFF) == 0x0B04) {
uint8_t r = instr2 >> 12;
/* Load from memory: POP */
UnwPrintd2("POP {R%d}\n", r);
/* Read the word */
if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DREAD_W_FAIL;
/* Alter the origin to be from the stack if it was valid */
if (M_IsOriginValid(state->regData[r].o)) {
state->regData[r].o = REG_VAL_FROM_STACK;
/* If restoring the PC */
if (r == 15) {
/* The bottom bit should have been set to indicate that
* the caller was from Thumb. This would allow return
* by BX for interworking APCS.
*/
if ((state->regData[15].v & 0x1) == 0) {
UnwPrintd2("Warning: Return address not to Thumb: 0x%08x\n", state->regData[15].v);
/* Pop into the PC will not switch mode */
return UNWIND_INCONSISTENT;
}
/* Store the return address */
if (!UnwReportRetAddr(state, state->regData[15].v))
return UNWIND_TRUNCATED;
/* Now have the return address */
UnwPrintd2(" Return PC=%x\n", state->regData[15].v);
/* Compensate for the auto-increment, which isn't needed here */
state->regData[15].v -= 2;
}
} else {
if (r == 15) {
/* Return address is not valid */
UnwPrintd1("PC popped with invalid address\n");
return UNWIND_FAILURE;
}
}
state->regData[13].v += 4;
UnwPrintd3(" r%d = 0x%08x\n", r, state->regData[r].v);
}
/*
* TBB / TBH
*/
else if ((instr & 0xFFF0) == 0xE8D0 && (instr2 & 0xFFE0) == 0xF000) {
/* We are only interested in
* the forms
* TBB [PC, ...]
* TBH [PC, ..., LSL #1]
* as those are used by the C compiler to implement
* the switch clauses
*/
uint8_t rn = instr & 0xF;
bool H = !!(instr2 & 0x10);
UnwPrintd5("TB%c [r%d,r%d%s]\n", H ? 'H' : 'B', rn, (instr2 & 0xF), H ? ",LSL #1" : "");
// We are only interested if the RN is the PC. Let's choose the 1st destination
if (rn == 15) {
if (H) {
uint16_t rv;
if (!state->cb->readH((state->regData[15].v & (~1)) + 2, &rv))
return UNWIND_DREAD_H_FAIL;
state->regData[15].v += rv * 2;
}
else {
uint8_t rv;
if (!state->cb->readB((state->regData[15].v & (~1)) + 2, &rv))
return UNWIND_DREAD_B_FAIL;
state->regData[15].v += rv * 2;
}
}
}
/*
* Unconditional branch
*/
else if ((instr & 0xF800) == 0xF000 && (instr2 & 0xD000) == 0x9000) {
uint32_t v;
uint8_t S = (instr & 0x400) >> 10;
uint16_t imm10 = (instr & 0x3FF);
uint8_t J1 = (instr2 & 0x2000) >> 13;
uint8_t J2 = (instr2 & 0x0800) >> 11;
uint16_t imm11 = (instr2 & 0x7FF);
uint8_t I1 = J1 ^ S ^ 1;
uint8_t I2 = J2 ^ S ^ 1;
uint32_t imm32 = (S << 24) | (I1 << 23) | (I2 << 22) |(imm10 << 12) | (imm11 << 1);
if (S) imm32 |= 0xFE000000;
UnwPrintd2("B %d \n", imm32);
/* Update PC */
state->regData[15].v += imm32;
/* Need to advance by a word to account for pre-fetch.
* Advance by a half word here, allowing the normal address
* advance to account for the other half word.
*/
state->regData[15].v += 2;
/* Compute the jump address */
v = state->regData[15].v + 2;
/* Display PC of next instruction */
UnwPrintd2(" New PC=%x", v);
/* Did we detect an infinite loop ? */
loopDetected = lastJumpAddr == v;
/* Remember the last address we jumped to */
lastJumpAddr = v;
}
/*
* Branch with link
*/
else if ((instr & 0xF800) == 0xF000 && (instr2 & 0xD000) == 0xD000) {
uint8_t S = (instr & 0x400) >> 10;
uint16_t imm10 = (instr & 0x3FF);
uint8_t J1 = (instr2 & 0x2000) >> 13;
uint8_t J2 = (instr2 & 0x0800) >> 11;
uint16_t imm11 = (instr2 & 0x7FF);
uint8_t I1 = J1 ^ S ^ 1;
uint8_t I2 = J2 ^ S ^ 1;
uint32_t imm32 = (S << 24) | (I1 << 23) | (I2 << 22) |(imm10 << 12) | (imm11 << 1);
if (S) imm32 |= 0xFE000000;
UnwPrintd2("BL %d \n", imm32);
/* Never taken, as we are unwinding the stack */
if (0) {
/* Store return address in LR register */
state->regData[14].v = state->regData[15].v + 2;
state->regData[14].o = REG_VAL_FROM_CONST;
/* Update PC */
state->regData[15].v += imm32;
/* Need to advance by a word to account for pre-fetch.
* Advance by a half word here, allowing the normal address
* advance to account for the other half word.
*/
state->regData[15].v += 2;
/* Display PC of next instruction */
UnwPrintd2(" Return PC=%x", state->regData[15].v);
/* Report the return address, including mode bit */
if (!UnwReportRetAddr(state, state->regData[15].v))
return UNWIND_TRUNCATED;
/* Determine the new mode */
if (state->regData[15].v & 0x1) {
/* Branching to THUMB */
/* Account for the auto-increment which isn't needed */
state->regData[15].v -= 2;
}
else {
/* Branch to ARM */
return UnwStartArm(state);
}
}
}
/*
* Conditional branches. Usually not taken, unless infinite loop is detected
*/
else if ((instr & 0xF800) == 0xF000 && (instr2 & 0xD000) == 0x8000) {
uint8_t S = (instr & 0x400) >> 10;
uint16_t imm6 = (instr & 0x3F);
uint8_t J1 = (instr2 & 0x2000) >> 13;
uint8_t J2 = (instr2 & 0x0800) >> 11;
uint16_t imm11 = (instr2 & 0x7FF);
uint8_t I1 = J1 ^ S ^ 1;
uint8_t I2 = J2 ^ S ^ 1;
uint32_t imm32 = (S << 20) | (I1 << 19) | (I2 << 18) |(imm6 << 12) | (imm11 << 1);
if (S) imm32 |= 0xFFE00000;
UnwPrintd2("Bcond %d\n", imm32);
/* Take the jump only if a loop is detected */
if (loopDetected) {
/* Update PC */
state->regData[15].v += imm32;
/* Need to advance by a word to account for pre-fetch.
* Advance by a half word here, allowing the normal address
* advance to account for the other half word.
*/
state->regData[15].v += 2;
/* Display PC of next instruction */
UnwPrintd2(" New PC=%x", state->regData[15].v + 2);
}
}
/*
* PC-relative load
* LDR Rd,[PC, #+/-imm]
*/
else if ((instr & 0xFF7F) == 0xF85F) {
uint8_t rt = (instr2 & 0xF000) >> 12;
uint8_t imm12 = (instr2 & 0x0FFF);
bool A = !!(instr & 0x80);
uint32_t address;
/* Compute load address, adding a word to account for prefetch */
address = (state->regData[15].v & (~0x3)) + 4;
if (A) address += imm12;
else address -= imm12;
UnwPrintd4("LDR r%d,[PC #%c0x%08x]", rt, A?'+':'-', address);
if (!UnwMemReadRegister(state, address, &state->regData[rt]))
return UNWIND_DREAD_W_FAIL;
}
/*
* LDR immediate.
* We are only interested when destination is PC.
* LDR Rt,[Rn , #n]
*/
else if ((instr & 0xFFF0) == 0xF8D0) {
uint8_t rn = (instr & 0xF);
uint8_t rt = (instr2 & 0xF000) >> 12;
uint16_t imm12 = (instr2 & 0xFFF);
/* If destination is PC and we don't know the source value, then fail */
if (!M_IsOriginValid(state->regData[rn].o)) {
state->regData[rt].o = state->regData[rn].o;
}
else {
uint32_t address = state->regData[rn].v + imm12;
if (!UnwMemReadRegister(state, address, &state->regData[rt]))
return UNWIND_DREAD_W_FAIL;
}
}
/*
* LDR immediate
* We are only interested when destination is PC.
* LDR Rt,[Rn , #-n]
* LDR Rt,[Rn], #+/-n]
* LDR Rt,[Rn, #+/-n]!
*/
else if ((instr & 0xFFF0) == 0xF850 && (instr2 & 0x0800) == 0x0800) {
uint8_t rn = (instr & 0xF);
uint8_t rt = (instr2 & 0xF000) >> 12;
uint16_t imm8 = (instr2 & 0xFF);
bool P = !!(instr2 & 0x400);
bool U = !!(instr2 & 0x200);
bool W = !!(instr2 & 0x100);
if (!M_IsOriginValid(state->regData[rn].o))
state->regData[rt].o = state->regData[rn].o;
else {
uint32_t offaddress = state->regData[rn].v + (U ? imm8 + imm8 : 0),
address = P ? offaddress : state->regData[rn].v;
if (!UnwMemReadRegister(state, address, &state->regData[rt]))
return UNWIND_DREAD_W_FAIL;
if (W) state->regData[rn].v = offaddress;
}
}
/*
* LDR (register).
* We are interested in the form
* ldr Rt, [Rn, Rm, lsl #x]
* Where Rt is PC, Rn value is known, Rm is not known or unknown
*/
else if ((instr & 0xFFF0) == 0xF850 && (instr2 & 0x0FC0) == 0x0000) {
const uint8_t rn = (instr & 0xF),
rt = (instr2 & 0xF000) >> 12,
rm = (instr2 & 0xF),
imm2 = (instr2 & 0x30) >> 4;
if (!M_IsOriginValid(state->regData[rn].o) || !M_IsOriginValid(state->regData[rm].o)) {
/* If Rt is PC, and Rn is known, then do an exception and assume
Rm equals 0 => This takes the first case in a switch() */
if (rt == 15 && M_IsOriginValid(state->regData[rn].o)) {
uint32_t address = state->regData[rn].v;
if (!UnwMemReadRegister(state, address, &state->regData[rt]))
return UNWIND_DREAD_W_FAIL;
}
else /* Propagate unknown value */
state->regData[rt].o = state->regData[rn].o;
}
else {
uint32_t address = state->regData[rn].v + (state->regData[rm].v << imm2);
if (!UnwMemReadRegister(state, address, &state->regData[rt]))
return UNWIND_DREAD_W_FAIL;
}
}
else {
UnwPrintd1("???? (32)");
/* Unknown/undecoded. May alter some register, so invalidate file */
UnwInvalidateRegisterFile(state->regData);
}
/* End of thumb 32bit code */
}
/* Format 1: Move shifted register
* LSL Rd, Rs, #Offset5
* LSR Rd, Rs, #Offset5
* ASR Rd, Rs, #Offset5
*/
else if ((instr & 0xE000) == 0x0000 && (instr & 0x1800) != 0x1800) {
bool signExtend;
const uint8_t op = (instr & 0x1800) >> 11,
offset5 = (instr & 0x07C0) >> 6,
rs = (instr & 0x0038) >> 3,
rd = (instr & 0x0007);
switch (op) {
case 0: /* LSL */
UnwPrintd6("LSL r%d, r%d, #%d\t; r%d %s", rd, rs, offset5, rs, M_Origin2Str(state->regData[rs].o));
state->regData[rd].v = state->regData[rs].v << offset5;
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
break;
case 1: /* LSR */
UnwPrintd6("LSR r%d, r%d, #%d\t; r%d %s", rd, rs, offset5, rs, M_Origin2Str(state->regData[rs].o));
state->regData[rd].v = state->regData[rs].v >> offset5;
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
break;
case 2: /* ASR */
UnwPrintd6("ASL r%d, r%d, #%d\t; r%d %s", rd, rs, offset5, rs, M_Origin2Str(state->regData[rs].o));
signExtend = !!(state->regData[rs].v & 0x8000);
state->regData[rd].v = state->regData[rs].v >> offset5;
if (signExtend) state->regData[rd].v |= 0xFFFFFFFF << (32 - offset5);
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
break;
}
}
/* Format 2: add/subtract
* ADD Rd, Rs, Rn
* ADD Rd, Rs, #Offset3
* SUB Rd, Rs, Rn
* SUB Rd, Rs, #Offset3
*/
else if ((instr & 0xF800) == 0x1800) {
bool I = !!(instr & 0x0400);
bool op = !!(instr & 0x0200);
uint8_t rn = (instr & 0x01C0) >> 6;
uint8_t rs = (instr & 0x0038) >> 3;
uint8_t rd = (instr & 0x0007);
/* Print decoding */
UnwPrintd6("%s r%d, r%d, %c%d\t;",op ? "SUB" : "ADD",rd, rs,I ? '#' : 'r',rn);
UnwPrintd5("r%d %s, r%d %s",rd, M_Origin2Str(state->regData[rd].o),rs, M_Origin2Str(state->regData[rs].o));
if (!I) {
UnwPrintd3(", r%d %s", rn, M_Origin2Str(state->regData[rn].o));
/* Perform calculation */
state->regData[rd].v = state->regData[rs].v + (op ? -state->regData[rn].v : state->regData[rn].v);
/* Propagate the origin */
if (M_IsOriginValid(state->regData[rs].o) && M_IsOriginValid(state->regData[rn].o)) {
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
}
else
state->regData[rd].o = REG_VAL_INVALID;
}
else {
/* Perform calculation */
state->regData[rd].v = state->regData[rs].v + (op ? -rn : rn);
/* Propagate the origin */
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
}
}
/* Format 3: move/compare/add/subtract immediate
* MOV Rd, #Offset8
* CMP Rd, #Offset8
* ADD Rd, #Offset8
* SUB Rd, #Offset8
*/
else if ((instr & 0xE000) == 0x2000) {
uint8_t op = (instr & 0x1800) >> 11;
uint8_t rd = (instr & 0x0700) >> 8;
uint8_t offset8 = (instr & 0x00FF);
switch (op) {
case 0: /* MOV */
UnwPrintd3("MOV r%d, #0x%x", rd, offset8);
state->regData[rd].v = offset8;
state->regData[rd].o = REG_VAL_FROM_CONST;
break;
case 1: /* CMP */
/* Irrelevant to unwinding */
UnwPrintd1("CMP ???");
break;
case 2: /* ADD */
UnwPrintd5("ADD r%d, #0x%x\t; r%d %s", rd, offset8, rd, M_Origin2Str(state->regData[rd].o));
state->regData[rd].v += offset8;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
break;
case 3: /* SUB */
UnwPrintd5("SUB r%d, #0x%d\t; r%d %s", rd, offset8, rd, M_Origin2Str(state->regData[rd].o));
state->regData[rd].v -= offset8;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
break;
}
}
/* Format 4: ALU operations
* AND Rd, Rs
* EOR Rd, Rs
* LSL Rd, Rs
* LSR Rd, Rs
* ASR Rd, Rs
* ADC Rd, Rs
* SBC Rd, Rs
* ROR Rd, Rs
* TST Rd, Rs
* NEG Rd, Rs
* CMP Rd, Rs
* CMN Rd, Rs
* ORR Rd, Rs
* MUL Rd, Rs
* BIC Rd, Rs
* MVN Rd, Rs
*/
else if ((instr & 0xFC00) == 0x4000) {
uint8_t op = (instr & 0x03C0) >> 6;
uint8_t rs = (instr & 0x0038) >> 3;
uint8_t rd = (instr & 0x0007);
#ifdef UNW_DEBUG
static const char * const mnu[16] = {
"AND", "EOR", "LSL", "LSR",
"ASR", "ADC", "SBC", "ROR",
"TST", "NEG", "CMP", "CMN",
"ORR", "MUL", "BIC", "MVN" };
#endif
/* Print the mnemonic and registers */
switch (op) {
case 0: /* AND */
case 1: /* EOR */
case 2: /* LSL */
case 3: /* LSR */
case 4: /* ASR */
case 7: /* ROR */
case 9: /* NEG */
case 12: /* ORR */
case 13: /* MUL */
case 15: /* MVN */
UnwPrintd8("%s r%d ,r%d\t; r%d %s, r%d %s",mnu[op],rd, rs, rd, M_Origin2Str(state->regData[rd].o), rs, M_Origin2Str(state->regData[rs].o));
break;
case 5: /* ADC */
case 6: /* SBC */
UnwPrintd4("%s r%d, r%d", mnu[op], rd, rs);
break;
case 8: /* TST */
case 10: /* CMP */
case 11: /* CMN */
/* Irrelevant to unwinding */
UnwPrintd2("%s ???", mnu[op]);
break;
case 14: /* BIC */
UnwPrintd5("r%d ,r%d\t; r%d %s", rd, rs, rs, M_Origin2Str(state->regData[rs].o));
break;
}
/* Perform operation */
switch (op) {
case 0: /* AND */
state->regData[rd].v &= state->regData[rs].v;
break;
case 1: /* EOR */
state->regData[rd].v ^= state->regData[rs].v;
break;
case 2: /* LSL */
state->regData[rd].v <<= state->regData[rs].v;
break;
case 3: /* LSR */
state->regData[rd].v >>= state->regData[rs].v;
break;
case 4: /* ASR */
if (state->regData[rd].v & 0x80000000) {
state->regData[rd].v >>= state->regData[rs].v;
state->regData[rd].v |= 0xFFFFFFFF << (32 - state->regData[rs].v);
}
else {
state->regData[rd].v >>= state->regData[rs].v;
}
break;
case 5: /* ADC */
case 6: /* SBC */
case 8: /* TST */
case 10: /* CMP */
case 11: /* CMN */
break;
case 7: /* ROR */
state->regData[rd].v = (state->regData[rd].v >> state->regData[rs].v) |
(state->regData[rd].v << (32 - state->regData[rs].v));
break;
case 9: /* NEG */
state->regData[rd].v = -state->regData[rs].v;
break;
case 12: /* ORR */
state->regData[rd].v |= state->regData[rs].v;
break;
case 13: /* MUL */
state->regData[rd].v *= state->regData[rs].v;
break;
case 14: /* BIC */
state->regData[rd].v &= ~state->regData[rs].v;
break;
case 15: /* MVN */
state->regData[rd].v = ~state->regData[rs].v;
break;
}
/* Propagate data origins */
switch (op) {
case 0: /* AND */
case 1: /* EOR */
case 2: /* LSL */
case 3: /* LSR */
case 4: /* ASR */
case 7: /* ROR */
case 12: /* ORR */
case 13: /* MUL */
case 14: /* BIC */
if (M_IsOriginValid(state->regData[rd].o) && M_IsOriginValid(state->regData[rs].o)) {
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
}
else
state->regData[rd].o = REG_VAL_INVALID;
break;
case 5: /* ADC */
case 6: /* SBC */
/* C-bit not tracked */
state->regData[rd].o = REG_VAL_INVALID;
break;
case 8: /* TST */
case 10: /* CMP */
case 11: /* CMN */
/* Nothing propagated */
break;
case 9: /* NEG */
case 15: /* MVN */
state->regData[rd].o = state->regData[rs].o;
state->regData[rd].o |= REG_VAL_ARITHMETIC;
break;
}
}
/* Format 5: Hi register operations/branch exchange
* ADD Rd, Hs
* CMP Hd, Rs
* MOV Hd, Hs
*/
else if ((instr & 0xFC00) == 0x4400) {
uint8_t op = (instr & 0x0300) >> 8;
bool h1 = (instr & 0x0080) ? true: false;
bool h2 = (instr & 0x0040) ? true: false;
uint8_t rhs = (instr & 0x0038) >> 3;
uint8_t rhd = (instr & 0x0007);
/* Adjust the register numbers */
if (h2) rhs += 8;
if (h1) rhd += 8;
switch (op) {
case 0: /* ADD */
UnwPrintd5("ADD r%d, r%d\t; r%d %s", rhd, rhs, rhs, M_Origin2Str(state->regData[rhs].o));
state->regData[rhd].v += state->regData[rhs].v;
state->regData[rhd].o = state->regData[rhs].o;
state->regData[rhd].o |= REG_VAL_ARITHMETIC;
break;
case 1: /* CMP */
/* Irrelevant to unwinding */
UnwPrintd1("CMP ???");
break;
case 2: /* MOV */
UnwPrintd5("MOV r%d, r%d\t; r%d %s", rhd, rhs, rhd, M_Origin2Str(state->regData[rhs].o));
state->regData[rhd].v = state->regData[rhs].v;
state->regData[rhd].o = state->regData[rhs].o;
break;
case 3: /* BX */
UnwPrintd4("BX r%d\t; r%d %s\n", rhs, rhs, M_Origin2Str(state->regData[rhs].o));
/* Only follow BX if the data was from the stack or BX LR */
if (rhs == 14 || state->regData[rhs].o == REG_VAL_FROM_STACK) {
UnwPrintd2(" Return PC=0x%x\n", state->regData[rhs].v & (~0x1));
/* Report the return address, including mode bit */
if (!UnwReportRetAddr(state, state->regData[rhs].v))
return UNWIND_TRUNCATED;
/* Update the PC */
state->regData[15].v = state->regData[rhs].v;
/* Determine the new mode */
if (state->regData[rhs].v & 0x1) {
/* Branching to THUMB */
/* Account for the auto-increment which isn't needed */
state->regData[15].v -= 2;
}
else /* Branch to ARM */
return UnwStartArm(state);
}
else {
UnwPrintd4("\nError: BX to invalid register: r%d = 0x%x (%s)\n", rhs, state->regData[rhs].o, M_Origin2Str(state->regData[rhs].o));
return UNWIND_FAILURE;
}
}
}
/* Format 9: PC-relative load
* LDR Rd,[PC, #imm]
*/
else if ((instr & 0xF800) == 0x4800) {
uint8_t rd = (instr & 0x0700) >> 8;
uint8_t word8 = (instr & 0x00FF);
uint32_t address;
/* Compute load address, adding a word to account for prefetch */
address = (state->regData[15].v & (~0x3)) + 4 + (word8 << 2);
UnwPrintd3("LDR r%d, 0x%08x", rd, address);
if (!UnwMemReadRegister(state, address, &state->regData[rd]))
return UNWIND_DREAD_W_FAIL;
}
/* Format 13: add offset to Stack Pointer
* ADD sp,#+imm
* ADD sp,#-imm
*/
else if ((instr & 0xFF00) == 0xB000) {
uint8_t value = (instr & 0x7F) * 4;
/* Check the negative bit */
if ((instr & 0x80) != 0) {
UnwPrintd2("SUB sp,#0x%x", value);
state->regData[13].v -= value;
}
else {
UnwPrintd2("ADD sp,#0x%x", value);
state->regData[13].v += value;
}
}
/* Format 14: push/pop registers
* PUSH {Rlist}
* PUSH {Rlist, LR}
* POP {Rlist}
* POP {Rlist, PC}
*/
else if ((instr & 0xF600) == 0xB400) {
bool L = !!(instr & 0x0800);
bool R = !!(instr & 0x0100);
uint8_t rList = (instr & 0x00FF);
if (L) {
uint8_t r;
/* Load from memory: POP */
UnwPrintd2("POP {Rlist%s}\n", R ? ", PC" : "");
for (r = 0; r < 8; r++) {
if (rList & (0x1 << r)) {
/* Read the word */
if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DREAD_W_FAIL;
/* Alter the origin to be from the stack if it was valid */
if (M_IsOriginValid(state->regData[r].o))
state->regData[r].o = REG_VAL_FROM_STACK;
state->regData[13].v += 4;
UnwPrintd3(" r%d = 0x%08x\n", r, state->regData[r].v);
}
}
/* Check if the PC is to be popped */
if (R) {
/* Get the return address */
if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[15]))
return UNWIND_DREAD_W_FAIL;
/* Alter the origin to be from the stack if it was valid */
if (!M_IsOriginValid(state->regData[15].o)) {
/* Return address is not valid */
UnwPrintd1("PC popped with invalid address\n");
return UNWIND_FAILURE;
}
else {
/* The bottom bit should have been set to indicate that
* the caller was from Thumb. This would allow return
* by BX for interworking APCS.
*/
if ((state->regData[15].v & 0x1) == 0) {
UnwPrintd2("Warning: Return address not to Thumb: 0x%08x\n", state->regData[15].v);
/* Pop into the PC will not switch mode */
return UNWIND_INCONSISTENT;
}
/* Store the return address */
if (!UnwReportRetAddr(state, state->regData[15].v))
return UNWIND_TRUNCATED;
/* Now have the return address */
UnwPrintd2(" Return PC=%x\n", state->regData[15].v);
/* Update the pc */
state->regData[13].v += 4;
/* Compensate for the auto-increment, which isn't needed here */
state->regData[15].v -= 2;
}
}
}
else {
int8_t r;
/* Store to memory: PUSH */
UnwPrintd2("PUSH {Rlist%s}", R ? ", LR" : "");
/* Check if the LR is to be pushed */
if (R) {
UnwPrintd3("\n lr = 0x%08x\t; %s", state->regData[14].v, M_Origin2Str(state->regData[14].o));
state->regData[13].v -= 4;
/* Write the register value to memory */
if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[14]))
return UNWIND_DWRITE_W_FAIL;
}
for (r = 7; r >= 0; r--) {
if (rList & (0x1 << r)) {
UnwPrintd4("\n r%d = 0x%08x\t; %s", r, state->regData[r].v, M_Origin2Str(state->regData[r].o));
state->regData[13].v -= 4;
if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r]))
return UNWIND_DWRITE_W_FAIL;
}
}
}
}
/*
* Conditional branches
* Bcond
*/
else if ((instr & 0xF000) == 0xD000) {
int32_t branchValue = (instr & 0xFF);
if (branchValue & 0x80) branchValue |= 0xFFFFFF00;
/* Branch distance is twice that specified in the instruction. */
branchValue *= 2;
UnwPrintd2("Bcond %d \n", branchValue);
/* Only take the branch if a loop was detected */
if (loopDetected) {
/* Update PC */
state->regData[15].v += branchValue;
/* Need to advance by a word to account for pre-fetch.
* Advance by a half word here, allowing the normal address
* advance to account for the other half word.
*/
state->regData[15].v += 2;
/* Display PC of next instruction */
UnwPrintd2(" New PC=%x", state->regData[15].v + 2);
}
}
/* Format 18: unconditional branch
* B label
*/
else if ((instr & 0xF800) == 0xE000) {
uint32_t v;
int32_t branchValue = signExtend11(instr & 0x07FF);
/* Branch distance is twice that specified in the instruction. */
branchValue *= 2;
UnwPrintd2("B %d \n", branchValue);
/* Update PC */
state->regData[15].v += branchValue;
/* Need to advance by a word to account for pre-fetch.
* Advance by a half word here, allowing the normal address
* advance to account for the other half word.
*/
state->regData[15].v += 2;
/* Compute the jump address */
v = state->regData[15].v + 2;
/* Display PC of next instruction */
UnwPrintd2(" New PC=%x", v);
/* Did we detect an infinite loop ? */
loopDetected = lastJumpAddr == v;
/* Remember the last address we jumped to */
lastJumpAddr = v;
}
else {
UnwPrintd1("????");
/* Unknown/undecoded. May alter some register, so invalidate file */
UnwInvalidateRegisterFile(state->regData);
}
UnwPrintd1("\n");
/* Should never hit the reset vector */
if (state->regData[15].v == 0) return UNWIND_RESET;
/* Check next address */
state->regData[15].v += 2;
/* Garbage collect the memory hash (used only for the stack) */
UnwMemHashGC(state);
if (--t == 0) return UNWIND_EXHAUSTED;
}
return UNWIND_SUCCESS;
}
#endif // __arm__ || __thumb__
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/unwarm_thumb.cpp
|
C++
|
agpl-3.0
| 34,489
|
/*
* Libbacktrace
* Copyright 2015 Stephen Street <stephen@redrocketcomputing.com>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://www.mozilla.org/en-US/MPL/2.0/
*
* This library was modified, some bugs fixed, stack address validated
* and adapted to be used in Marlin 3D printer firmware as backtracer
* for exceptions for debugging purposes in 2018 by Eduardo José Tagle.
*/
#if defined(__arm__) || defined(__thumb__)
#include "unwarmbytab.h"
#include <stdint.h>
#include <string.h>
/* These symbols point to the unwind index and should be provide by the linker script */
extern "C" const UnwTabEntry __exidx_start[];
extern "C" const UnwTabEntry __exidx_end[];
/* This prevents the linking of libgcc unwinder code */
void __aeabi_unwind_cpp_pr0() {};
void __aeabi_unwind_cpp_pr1() {};
void __aeabi_unwind_cpp_pr2() {};
static inline __attribute__((always_inline)) uint32_t prel31_to_addr(const uint32_t *prel31) {
uint32_t offset = (((uint32_t)(*prel31)) << 1) >> 1;
return ((uint32_t)prel31 + offset) & 0x7FFFFFFF;
}
static const UnwTabEntry *UnwTabSearchIndex(const UnwTabEntry *start, const UnwTabEntry *end, uint32_t ip) {
const UnwTabEntry *middle;
/* Perform a binary search of the unwind index */
while (start < end - 1) {
middle = start + ((end - start + 1) >> 1);
if (ip < prel31_to_addr(&middle->addr_offset))
end = middle;
else
start = middle;
}
return start;
}
/*
* Get the function name or nullptr if not found
*/
static const char *UnwTabGetFunctionName(const UnwindCallbacks *cb, uint32_t address) {
uint32_t flag_word = 0;
if (!cb->readW(address-4,&flag_word))
return nullptr;
if ((flag_word & 0xFF000000) == 0xFF000000) {
const uint32_t fn_name_addr = address - 4 - (flag_word & 0x00FFFFFF);
// Ensure the address is readable to avoid returning a bogus pointer
uint8_t dummy = 0;
if (cb->readB(fn_name_addr, &dummy))
return (const char *)fn_name_addr;
}
return nullptr;
}
/**
* Get the next frame unwinding instruction
*
* Return either the instruction or -1 to signal no more instructions
* are available
*/
static int UnwTabGetNextInstruction(const UnwindCallbacks *cb, UnwTabState *ucb) {
int instruction;
/* Are there more instructions */
if (ucb->remaining == 0)
return -1;
/* Extract the current instruction */
uint32_t v = 0;
if (!cb->readW(ucb->current, &v))
return -1;
instruction = (v >> (ucb->byte << 3)) & 0xFF;
/* Move the next byte */
--ucb->byte;
if (ucb->byte < 0) {
ucb->current += 4;
ucb->byte = 3;
}
--ucb->remaining;
return instruction;
}
/**
* Initialize the frame unwinding state
*/
static UnwResult UnwTabStateInit(const UnwindCallbacks *cb, UnwTabState *ucb, uint32_t instructions, const UnwindFrame *frame) {
/* Initialize control block */
memset(ucb, 0, sizeof(UnwTabState));
ucb->current = instructions;
/* Is a short unwind description */
uint32_t v = 0;
if (!cb->readW(instructions, &v))
return UNWIND_DREAD_W_FAIL;
if ((v & 0xFF000000) == 0x80000000) {
ucb->remaining = 3;
ucb->byte = 2;
/* Is a long unwind description */
} else if ((v & 0xFF000000) == 0x81000000) {
ucb->remaining = ((v & 0x00FF0000) >> 14) + 2;
ucb->byte = 1;
} else
return UNWIND_UNSUPPORTED_DWARF_PERSONALITY;
/* Initialize the virtual register set */
ucb->vrs[7] = frame->fp;
ucb->vrs[13] = frame->sp;
ucb->vrs[14] = frame->lr;
ucb->vrs[15] = 0;
/* All good */
return UNWIND_SUCCESS;
}
/*
* Execute unwinding instructions
*/
static UnwResult UnwTabExecuteInstructions(const UnwindCallbacks *cb, UnwTabState *ucb) {
int instruction;
uint32_t mask, reg, vsp;
/* Consume all instruction byte */
while ((instruction = UnwTabGetNextInstruction(cb, ucb)) != -1) {
if ((instruction & 0xC0) == 0x00) { // ARM_EXIDX_CMD_DATA_POP
/* vsp += (xxxxxx << 2) + 4 */
ucb->vrs[13] += ((instruction & 0x3F) << 2) + 4;
}
else if ((instruction & 0xC0) == 0x40) { // ARM_EXIDX_CMD_DATA_PUSH
/* vsp -= (xxxxxx << 2) - 4 */
ucb->vrs[13] -= ((instruction & 0x3F) << 2) - 4;
}
else if ((instruction & 0xF0) == 0x80) {
/* pop under mask {r15-r12},{r11-r4} or refuse to unwind */
instruction = instruction << 8 | UnwTabGetNextInstruction(cb, ucb);
/* Check for refuse to unwind */
if (instruction == 0x8000) // ARM_EXIDX_CMD_REFUSED
return UNWIND_REFUSED;
/* Pop registers using mask */ // ARM_EXIDX_CMD_REG_POP
vsp = ucb->vrs[13];
mask = instruction & 0xFFF;
reg = 4;
while (mask) {
if ((mask & 1) != 0) {
uint32_t v;
if (!cb->readW(vsp,&v))
return UNWIND_DREAD_W_FAIL;
ucb->vrs[reg] = v;
v += 4;
}
mask >>= 1;
++reg;
}
/* Patch up the vrs sp if it was in the mask */
if (instruction & (1 << (13 - 4)))
ucb->vrs[13] = vsp;
}
else if ((instruction & 0xF0) == 0x90 // ARM_EXIDX_CMD_REG_TO_SP
&& instruction != 0x9D
&& instruction != 0x9F
) {
/* vsp = r[nnnn] */
ucb->vrs[13] = ucb->vrs[instruction & 0x0F];
}
else if ((instruction & 0xF0) == 0xA0) { // ARM_EXIDX_CMD_REG_POP
/* pop r4-r[4+nnn] or pop r4-r[4+nnn], r14*/
vsp = ucb->vrs[13];
for (reg = 4; reg <= uint32_t((instruction & 0x07) + 4); ++reg) {
uint32_t v;
if (!cb->readW(vsp,&v))
return UNWIND_DREAD_W_FAIL;
ucb->vrs[reg] = v;
vsp += 4;
}
if (instruction & 0x08) { // ARM_EXIDX_CMD_REG_POP
uint32_t v;
if (!cb->readW(vsp,&v))
return UNWIND_DREAD_W_FAIL;
ucb->vrs[14] = v;
vsp += 4;
}
ucb->vrs[13] = vsp;
}
else if (instruction == 0xB0) { // ARM_EXIDX_CMD_FINISH
/* finished */
if (ucb->vrs[15] == 0)
ucb->vrs[15] = ucb->vrs[14];
/* All done unwinding */
return UNWIND_SUCCESS;
}
else if (instruction == 0xB1) { // ARM_EXIDX_CMD_REG_POP
/* pop register under mask {r3,r2,r1,r0} */
vsp = ucb->vrs[13];
mask = UnwTabGetNextInstruction(cb, ucb);
reg = 0;
while (mask) {
if ((mask & 1) != 0) {
uint32_t v;
if (!cb->readW(vsp,&v))
return UNWIND_DREAD_W_FAIL;
ucb->vrs[reg] = v;
vsp += 4;
}
mask >>= 1;
++reg;
}
ucb->vrs[13] = (uint32_t)vsp;
}
else if (instruction == 0xB2) { // ARM_EXIDX_CMD_DATA_POP
/* vps = vsp + 0x204 + (uleb128 << 2) */
ucb->vrs[13] += 0x204 + (UnwTabGetNextInstruction(cb, ucb) << 2);
}
else if (instruction == 0xB3 // ARM_EXIDX_CMD_VFP_POP
|| instruction == 0xC8
|| instruction == 0xC9
) {
/* pop VFP double-precision registers */
vsp = ucb->vrs[13];
/* D[ssss]-D[ssss+cccc] */
uint32_t v;
if (!cb->readW(vsp,&v))
return UNWIND_DREAD_W_FAIL;
ucb->vrs[14] = v;
vsp += 4;
if (instruction == 0xC8) {
/* D[16+sssss]-D[16+ssss+cccc] */
ucb->vrs[14] |= 1 << 16;
}
if (instruction != 0xB3) {
/* D[sssss]-D[ssss+cccc] */
ucb->vrs[14] |= 1 << 17;
}
ucb->vrs[13] = vsp;
}
else if ((instruction & 0xF8) == 0xB8 || (instruction & 0xF8) == 0xD0) {
/* Pop VFP double precision registers D[8]-D[8+nnn] */
ucb->vrs[14] = 0x80 | (instruction & 0x07);
if ((instruction & 0xF8) == 0xD0)
ucb->vrs[14] = 1 << 17;
}
else
return UNWIND_UNSUPPORTED_DWARF_INSTR;
}
return UNWIND_SUCCESS;
}
static inline __attribute__((always_inline)) uint32_t read_psp() {
/* Read the current PSP and return its value as a pointer */
uint32_t psp;
__asm__ volatile (
" mrs %0, psp \n"
: "=r" (psp) : :
);
return psp;
}
/*
* Unwind the specified frame and goto the previous one
*/
static UnwResult UnwTabUnwindFrame(const UnwindCallbacks *cb, UnwindFrame *frame) {
UnwResult err;
UnwTabState ucb;
const UnwTabEntry *index;
uint32_t instructions;
/* Search the unwind index for the matching unwind table */
index = UnwTabSearchIndex(__exidx_start, __exidx_end, frame->pc);
/* Make sure we can unwind this frame */
if (index->insn == 0x00000001)
return UNWIND_SUCCESS;
/* Get the pointer to the first unwind instruction */
if (index->insn & 0x80000000)
instructions = (uint32_t)&index->insn;
else
instructions = prel31_to_addr(&index->insn);
/* Initialize the unwind control block */
if ((err = UnwTabStateInit(cb, &ucb, instructions, frame)) < 0)
return err;
/* Execute the unwind instructions */
err = UnwTabExecuteInstructions(cb, &ucb);
if (err < 0)
return err;
/* Set the virtual pc to the virtual lr if this is the first unwind */
if (ucb.vrs[15] == 0)
ucb.vrs[15] = ucb.vrs[14];
/* Check for exception return */
/* TODO Test with other ARM processors to verify this method. */
if ((ucb.vrs[15] & 0xF0000000) == 0xF0000000) {
/* According to the Cortex Programming Manual (p.44), the stack address is always 8-byte aligned (Cortex-M7).
Depending on where the exception came from (MSP or PSP), we need the right SP value to work with.
ucb.vrs[7] contains the right value, so take it and align it by 8 bytes, store it as the current
SP to work with (ucb.vrs[13]) which is then saved as the current (virtual) frame's SP.
*/
uint32_t stack;
ucb.vrs[13] = (ucb.vrs[7] & ~7);
/* If we need to start from the MSP, we need to go down X words to find the PC, where:
X=2 if it was a non-floating-point exception
X=20 if it was a floating-point (VFP) exception
If we need to start from the PSP, we need to go up exactly 6 words to find the PC.
See the ARMv7-M Architecture Reference Manual p.594 and Cortex-M7 Processor Programming Manual p.44/p.45 for details.
*/
if ((ucb.vrs[15] & 0xC) == 0) {
/* Return to Handler Mode: MSP (0xFFFFFF-1) */
stack = ucb.vrs[13];
/* The PC is always 2 words down from the MSP, if it was a non-floating-point exception */
stack -= 2*4;
/* If there was a VFP exception (0xFFFFFFE1), the PC is located another 18 words down */
if ((ucb.vrs[15] & 0xF0) == 0xE0) {
stack -= 18*4;
}
}
else {
/* Return to Thread Mode: PSP (0xFFFFFF-d) */
stack = read_psp();
/* The PC is always 6 words up from the PSP */
stack += 6*4;
}
/* Store the PC */
uint32_t v;
if (!cb->readW(stack,&v))
return UNWIND_DREAD_W_FAIL;
ucb.vrs[15] = v;
stack -= 4;
/* Store the LR */
if (!cb->readW(stack,&v))
return UNWIND_DREAD_W_FAIL;
ucb.vrs[14] = v;
stack -= 4;
}
/* We are done if current frame pc is equal to the virtual pc, prevent infinite loop */
if (frame->pc == ucb.vrs[15])
return UNWIND_SUCCESS;
/* Update the frame */
frame->fp = ucb.vrs[7];
frame->sp = ucb.vrs[13];
frame->lr = ucb.vrs[14];
frame->pc = ucb.vrs[15];
/* All good - Continue unwinding */
return UNWIND_MORE_AVAILABLE;
}
UnwResult UnwindByTableStart(UnwindFrame* frame, const UnwindCallbacks *cb, void *data) {
UnwResult err = UNWIND_SUCCESS;
UnwReport entry;
/* Use DWARF unwind information to unwind frames */
do {
if (frame->pc == 0) {
/* Reached __exidx_end. */
break;
}
if (frame->pc == 0x00000001) {
/* Reached .cantunwind instruction. */
break;
}
/* Find the unwind index of the current frame pc */
const UnwTabEntry *index = UnwTabSearchIndex(__exidx_start, __exidx_end, frame->pc);
/* Clear last bit (Thumb indicator) */
frame->pc &= 0xFFFFFFFEU;
/* Generate the backtrace information */
entry.address = frame->pc;
entry.function = prel31_to_addr(&index->addr_offset);
entry.name = UnwTabGetFunctionName(cb, entry.function);
if (!cb->report(data,&entry))
break;
/* Unwind frame and repeat */
} while ((err = UnwTabUnwindFrame(cb, frame)) == UNWIND_MORE_AVAILABLE);
/* All done */
return err;
}
#endif // __arm__ || __thumb__
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/unwarmbytab.cpp
|
C++
|
agpl-3.0
| 12,374
|
/***************************************************************************
* ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk
* Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle
*
* This program is PUBLIC DOMAIN.
* This means that there is no copyright and anyone is able to take a copy
* for free and use it as they wish, with or without modifications, and in
* any context, commercially or otherwise. The only limitation is that I
* don't guarantee that the software is fit for any purpose or accept any
* liability for its use or misuse - this software is without warranty.
***************************************************************************
* File Description: Interface to the memory tracking sub-system.
**************************************************************************/
#pragma once
#include "unwarm.h"
typedef struct {
uint32_t vrs[16];
uint32_t current; /* Address of current byte */
int remaining;
int byte;
} UnwTabState;
typedef struct {
uint32_t addr_offset;
uint32_t insn;
} UnwTabEntry;
UnwResult UnwindByTableStart(UnwindFrame* frame, const UnwindCallbacks *cb, void *data);
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/unwarmbytab.h
|
C
|
agpl-3.0
| 1,166
|
/***************************************************************************
* ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk
* Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle
*
* This program is PUBLIC DOMAIN.
* This means that there is no copyright and anyone is able to take a copy
* for free and use it as they wish, with or without modifications, and in
* any context, commercially or otherwise. The only limitation is that I
* don't guarantee that the software is fit for any purpose or accept any
* liability for its use or misuse - this software is without warranty.
***************************************************************************
* File Description: Implementation of the memory tracking sub-system.
**************************************************************************/
#if defined(__arm__) || defined(__thumb__)
#define MODULE_NAME "UNWARMMEM"
#include <stdio.h>
#include "unwarmmem.h"
#include "unwarm.h"
#define M_IsIdxUsed(a, v) !!((a)[v >> 3] & (1 << (v & 0x7)))
#define M_SetIdxUsed(a, v) ((a)[v >> 3] |= (1 << (v & 0x7)))
#define M_ClrIdxUsed(a, v) ((a)[v >> 3] &= ~(1 << (v & 0x7)))
/** Search the memory hash to see if an entry is stored in the hash already.
* This will search the hash and either return the index where the item is
* stored, or -1 if the item was not found.
*/
static int16_t memHashIndex(MemData * const memData, const uint32_t addr) {
const uint16_t v = addr % MEM_HASH_SIZE;
uint16_t s = v;
do {
/* Check if the element is occupied */
if (M_IsIdxUsed(memData->used, s)) {
/* Check if it is occupied with the sought data */
if (memData->a[s] == addr) return s;
}
else {
/* Item is free, this is where the item should be stored */
return s;
}
/* Search the next entry */
s++;
if (s > MEM_HASH_SIZE) s = 0;
} while (s != v);
/* Search failed, hash is full and the address not stored */
return -1;
}
bool UnwMemHashRead(MemData * const memData, uint32_t addr,uint32_t * const data, bool * const tracked) {
const int16_t i = memHashIndex(memData, addr);
if (i >= 0 && M_IsIdxUsed(memData->used, i) && memData->a[i] == addr) {
*data = memData->v[i];
*tracked = M_IsIdxUsed(memData->tracked, i);
return true;
}
else {
/* Address not found in the hash */
return false;
}
}
bool UnwMemHashWrite(MemData * const memData, uint32_t addr, uint32_t val, bool valValid) {
const int16_t i = memHashIndex(memData, addr);
if (i < 0) return false; /* Hash full */
/* Store the item */
memData->a[i] = addr;
M_SetIdxUsed(memData->used, i);
if (valValid) {
memData->v[i] = val;
M_SetIdxUsed(memData->tracked, i);
}
else {
#ifdef UNW_DEBUG
memData->v[i] = 0xDEADBEEF;
#endif
M_ClrIdxUsed(memData->tracked, i);
}
return true;
}
void UnwMemHashGC(UnwState * const state) {
const uint32_t minValidAddr = state->regData[13].v;
MemData * const memData = &state->memData;
uint16_t t;
for (t = 0; t < MEM_HASH_SIZE; t++) {
if (M_IsIdxUsed(memData->used, t) && (memData->a[t] < minValidAddr)) {
UnwPrintd3("MemHashGC: Free elem %d, addr 0x%08x\n", t, memData->a[t]);
M_ClrIdxUsed(memData->used, t);
}
}
}
#endif // __arm__ || __thumb__
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/unwarmmem.cpp
|
C++
|
agpl-3.0
| 3,312
|
/***************************************************************************
* ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk
* Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle
*
* This program is PUBLIC DOMAIN.
* This means that there is no copyright and anyone is able to take a copy
* for free and use it as they wish, with or without modifications, and in
* any context, commercially or otherwise. The only limitation is that I
* don't guarantee that the software is fit for any purpose or accept any
* liability for its use or misuse - this software is without warranty.
***************************************************************************
* File Description: Interface to the memory tracking sub-system.
**************************************************************************/
#pragma once
#include "unwarm.h"
bool UnwMemHashRead(MemData * const memData, uint32_t addr, uint32_t * const data, bool * const tracked);
bool UnwMemHashWrite(MemData * const memData, uint32_t addr, uint32_t val, bool valValid);
void UnwMemHashGC(UnwState * const state);
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/unwarmmem.h
|
C
|
agpl-3.0
| 1,111
|
/***************************************************************************
* ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk
* Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle
*
* This program is PUBLIC DOMAIN.
* This means that there is no copyright and anyone is able to take a copy
* for free and use it as they wish, with or without modifications, and in
* any context, commercially or otherwise. The only limitation is that I
* don't guarantee that the software is fit for any purpose or accept any
* liability for its use or misuse - this software is without warranty.
***************************************************************************
* File Description: Implementation of the interface into the ARM unwinder.
**************************************************************************/
#if defined(__arm__) || defined(__thumb__)
#define MODULE_NAME "UNWINDER"
#include <stdio.h>
#include <string.h>
#include "unwinder.h"
#include "unwarm.h"
#include "unwarmbytab.h"
/* These symbols point to the unwind index and should be provide by the linker script */
extern "C" const UnwTabEntry __exidx_start[];
extern "C" const UnwTabEntry __exidx_end[];
// Detect if unwind information is present or not
static int HasUnwindTableInfo() {
// > 16 because there are default entries we can't suppress
return ((char*)(&__exidx_end) - (char*)(&__exidx_start)) > 16 ? 1 : 0;
}
UnwResult UnwindStart(UnwindFrame* frame, const UnwindCallbacks *cb, void *data) {
if (HasUnwindTableInfo()) {
/* We have unwind information tables */
return UnwindByTableStart(frame, cb, data);
}
else {
/* We don't have unwind information tables */
UnwState state;
/* Initialize the unwinding state */
UnwInitState(&state, cb, data, frame->pc, frame->sp);
/* Check the Thumb bit */
return (frame->pc & 0x1) ? UnwStartThumb(&state) : UnwStartArm(&state);
}
}
#endif
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/unwinder.cpp
|
C++
|
agpl-3.0
| 1,940
|
/***************************************************************************
* ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk
* Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle
*
* This program is PUBLIC DOMAIN.
* This means that there is no copyright and anyone is able to take a copy
* for free and use it as they wish, with or without modifications, and in
* any context, commercially or otherwise. The only limitation is that I
* don't guarantee that the software is fit for any purpose or accept any
* liability for its use or misuse - this software is without warranty.
**************************************************************************/
/** \file
* Interface to the ARM stack unwinding module.
**************************************************************************/
#pragma once
#include <stdint.h>
/** \def UNW_DEBUG
* If this define is set, additional information will be produced while
* unwinding the stack to allow debug of the unwind module itself.
*/
/* #define UNW_DEBUG 1 */
/***************************************************************************
* Type Definitions
**************************************************************************/
/** Possible results for UnwindStart to return.
*/
typedef enum {
/** Unwinding was successful and complete. */
UNWIND_SUCCESS = 0,
/** Not an error: More frames are available. */
UNWIND_MORE_AVAILABLE = 1,
/** Unsupported DWARF unwind personality. */
UNWIND_UNSUPPORTED_DWARF_PERSONALITY = -1,
/** Refused to perform unwind. */
UNWIND_REFUSED = -2,
/** Reached an invalid SP. */
UNWIND_INVALID_SP = -3,
/** Reached an invalid PC */
UNWIND_INVALID_PC = -4,
/** Unsupported DWARF instruction */
UNWIND_UNSUPPORTED_DWARF_INSTR = -5,
/** More than UNW_MAX_INSTR_COUNT instructions were interpreted. */
UNWIND_EXHAUSTED = -6,
/** Unwinding stopped because the reporting func returned false. */
UNWIND_TRUNCATED = -7,
/** Read data was found to be inconsistent. */
UNWIND_INCONSISTENT = -8,
/** Unsupported instruction or data found. */
UNWIND_UNSUPPORTED = -9,
/** General failure. */
UNWIND_FAILURE = -10,
/** Illegal instruction. */
UNWIND_ILLEGAL_INSTR = -11,
/** Unwinding hit the reset vector. */
UNWIND_RESET = -12,
/** Failed read for an instruction word. */
UNWIND_IREAD_W_FAIL = -13,
/** Failed read for an instruction half-word. */
UNWIND_IREAD_H_FAIL = -14,
/** Failed read for an instruction byte. */
UNWIND_IREAD_B_FAIL = -15,
/** Failed read for a data word. */
UNWIND_DREAD_W_FAIL = -16,
/** Failed read for a data half-word. */
UNWIND_DREAD_H_FAIL = -17,
/** Failed read for a data byte. */
UNWIND_DREAD_B_FAIL = -18,
/** Failed write for a data word. */
UNWIND_DWRITE_W_FAIL = -19
} UnwResult;
/** A backtrace report */
typedef struct {
uint32_t function; /** Starts address of function */
const char *name; /** Function name, or null if not available */
uint32_t address; /** PC on that function */
} UnwReport;
/** Type for function pointer for result callback.
* The function is passed two parameters, the first is a void * pointer,
* and the second is the return address of the function. The bottom bit
* of the passed address indicates the execution mode; if it is set,
* the execution mode at the return address is Thumb, otherwise it is
* ARM.
*
* The return value of this function determines whether unwinding should
* continue or not. If true is returned, unwinding will continue and the
* report function maybe called again in future. If false is returned,
* unwinding will stop with UnwindStart() returning UNWIND_TRUNCATED.
*/
typedef bool (*UnwindReportFunc)(void *data, const UnwReport *bte);
/** Structure that holds memory callback function pointers.
*/
typedef struct {
/** Report an unwind result. */
UnwindReportFunc report;
/** Read a 32 bit word from memory.
* The memory address to be read is passed as \a address, and
* \a *val is expected to be populated with the read value.
* If the address cannot or should not be read, false can be
* returned to indicate that unwinding should stop. If true
* is returned, \a *val is assumed to be valid and unwinding
* will continue.
*/
bool (*readW)(const uint32_t address, uint32_t *val);
/** Read a 16 bit half-word from memory.
* This function has the same usage as for readW, but is expected
* to read only a 16 bit value.
*/
bool (*readH)(const uint32_t address, uint16_t *val);
/** Read a byte from memory.
* This function has the same usage as for readW, but is expected
* to read only an 8 bit value.
*/
bool (*readB)(const uint32_t address, uint8_t *val);
#ifdef UNW_DEBUG
/** Print a formatted line for debug. */
void (*printf)(const char *format, ...);
#endif
} UnwindCallbacks;
/* A frame */
typedef struct {
uint32_t fp;
uint32_t sp;
uint32_t lr;
uint32_t pc;
} UnwindFrame;
/** Start unwinding the current stack.
* This will unwind the stack starting at the PC value supplied to in the
* link register (i.e. not a normal register) and the stack pointer value
* supplied.
*
* -If the program was compiled with -funwind-tables it will use them to
* perform the traceback. Otherwise, brute force will be employed
* -If the program was compiled with -mpoke-function-name, then you will
* get function names in the traceback. Otherwise, you will not.
*/
UnwResult UnwindStart(UnwindFrame* frame, const UnwindCallbacks *cb, void *data);
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/unwinder.h
|
C
|
agpl-3.0
| 5,576
|
/***************************************************************************
* ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk
* Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle
*
* This program is PUBLIC DOMAIN.
* This means that there is no copyright and anyone is able to take a copy
* for free and use it as they wish, with or without modifications, and in
* any context, commercially or otherwise. The only limitation is that I
* don't guarantee that the software is fit for any purpose or accept any
* liability for its use or misuse - this software is without warranty.
***************************************************************************
* File Description: Utility functions to access memory
**************************************************************************/
#if defined(__arm__) || defined(__thumb__)
#include "unwmemaccess.h"
#include "../../../inc/MarlinConfig.h"
/* Validate address */
#ifdef ARDUINO_ARCH_SAM
// For DUE, valid address ranges are
// SRAM (0x20070000 - 0x20088000) (96kb)
// FLASH (0x00080000 - 0x00100000) (512kb)
//
#define START_SRAM_ADDR 0x20070000
#define END_SRAM_ADDR 0x20088000
#define START_FLASH_ADDR 0x00080000
#define END_FLASH_ADDR 0x00100000
#elif defined(TARGET_LPC1768)
// For LPC1769:
// SRAM (0x10000000 - 0x10008000) (32kb)
// FLASH (0x00000000 - 0x00080000) (512kb)
//
#define START_SRAM_ADDR 0x10000000
#define END_SRAM_ADDR 0x10008000
#define START_FLASH_ADDR 0x00000000
#define END_FLASH_ADDR 0x00080000
#elif defined(__STM32F1__) || defined(STM32F1xx) || defined(STM32F0xx) || defined(STM32G0xx)
// For STM32F103ZET6/STM32F103VET6/STM32F0xx
// SRAM (0x20000000 - 0x20010000) (64kb)
// FLASH (0x08000000 - 0x08080000) (512kb)
//
#define START_SRAM_ADDR 0x20000000
#define END_SRAM_ADDR 0x20010000
#define START_FLASH_ADDR 0x08000000
#define END_FLASH_ADDR 0x08080000
#elif defined(STM32F4) || defined(STM32F4xx)
// For STM32F407VET
// SRAM (0x20000000 - 0x20030000) (192kb)
// FLASH (0x08000000 - 0x08080000) (512kb)
//
#define START_SRAM_ADDR 0x20000000
#define END_SRAM_ADDR 0x20030000
#define START_FLASH_ADDR 0x08000000
#define END_FLASH_ADDR 0x08080000
#elif MB(REMRAM_V1, NUCLEO_F767ZI)
// For STM32F765VI in RemRam v1
// SRAM (0x20000000 - 0x20080000) (512kb)
// FLASH (0x08000000 - 0x08200000) (2048kb)
//
#define START_SRAM_ADDR 0x20000000
#define END_SRAM_ADDR 0x20080000
#define START_FLASH_ADDR 0x08000000
#define END_FLASH_ADDR 0x08200000
#elif defined(__MK20DX256__)
// For MK20DX256 in TEENSY 3.1 or TEENSY 3.2
// SRAM (0x1FFF8000 - 0x20008000) (64kb)
// FLASH (0x00000000 - 0x00040000) (256kb)
//
#define START_SRAM_ADDR 0x1FFF8000
#define END_SRAM_ADDR 0x20008000
#define START_FLASH_ADDR 0x00000000
#define END_FLASH_ADDR 0x00040000
#elif defined(__MK64FX512__)
// For MK64FX512 in TEENSY 3.5
// SRAM (0x1FFF0000 - 0x20020000) (192kb)
// FLASH (0x00000000 - 0x00080000) (512kb)
//
#define START_SRAM_ADDR 0x1FFF0000
#define END_SRAM_ADDR 0x20020000
#define START_FLASH_ADDR 0x00000000
#define END_FLASH_ADDR 0x00080000
#elif defined(__MK66FX1M0__)
// For MK66FX1M0 in TEENSY 3.6
// SRAM (0x1FFF0000 - 0x20030000) (256kb)
// FLASH (0x00000000 - 0x00140000) (1.25Mb)
//
#define START_SRAM_ADDR 0x1FFF0000
#define END_SRAM_ADDR 0x20030000
#define START_FLASH_ADDR 0x00000000
#define END_FLASH_ADDR 0x00140000
#elif defined(__IMXRT1062__)
// For IMXRT1062 in TEENSY 4.0/4/1
// ITCM (rwx): ORIGIN = 0x00000000, LENGTH = 512K
// DTCM (rwx): ORIGIN = 0x20000000, LENGTH = 512K
// RAM (rwx): ORIGIN = 0x20200000, LENGTH = 512K
// FLASH (rwx): ORIGIN = 0x60000000, LENGTH = 1984K
//
#define START_SRAM_ADDR 0x00000000
#define END_SRAM_ADDR 0x20280000
#define START_FLASH_ADDR 0x60000000
#define END_FLASH_ADDR 0x601F0000
#elif defined(__SAMD51P20A__)
// For SAMD51x20, valid address ranges are
// SRAM (0x20000000 - 0x20040000) (256kb)
// FLASH (0x00000000 - 0x00100000) (1024kb)
//
#define START_SRAM_ADDR 0x20000000
#define END_SRAM_ADDR 0x20040000
#define START_FLASH_ADDR 0x00000000
#define END_FLASH_ADDR 0x00100000
#else
// Generic ARM code, that's testing if an access to the given address would cause a fault or not
// It can't guarantee an address is in RAM or Flash only, but we usually don't care
#define NVIC_FAULT_STAT 0xE000ED28 // Configurable Fault Status reg.
#define NVIC_CFG_CTRL 0xE000ED14 // Configuration Control Register
#define NVIC_FAULT_STAT_BFARV 0x00008000 // BFAR is valid
#define NVIC_CFG_CTRL_BFHFNMIGN 0x00000100 // Ignore bus fault in NMI/fault
#define HW_REG(X) (*((volatile unsigned long *)(X)))
static bool validate_addr(uint32_t read_address) {
bool works = true;
uint32_t intDisabled = 0;
// Read current interrupt state
__asm__ __volatile__ ("MRS %[result], PRIMASK\n\t" : [result]"=r"(intDisabled) :: ); // 0 is int enabled, 1 for disabled
// Clear bus fault indicator first (write 1 to clear)
HW_REG(NVIC_FAULT_STAT) |= NVIC_FAULT_STAT_BFARV;
// Ignore bus fault interrupt
HW_REG(NVIC_CFG_CTRL) |= NVIC_CFG_CTRL_BFHFNMIGN;
// Disable interrupts if not disabled previously
if (!intDisabled) __asm__ __volatile__ ("CPSID f");
// Probe address
*(volatile uint32_t*)read_address;
// Check if a fault happened
if ((HW_REG(NVIC_FAULT_STAT) & NVIC_FAULT_STAT_BFARV) != 0)
works = false;
// Enable interrupts again if previously disabled
if (!intDisabled) __asm__ __volatile__ ("CPSIE f");
// Enable fault interrupt flag
HW_REG(NVIC_CFG_CTRL) &= ~NVIC_CFG_CTRL_BFHFNMIGN;
return works;
}
#endif
#ifdef START_SRAM_ADDR
static bool validate_addr(uint32_t addr) {
// Address must be in SRAM range
if (addr >= START_SRAM_ADDR && addr < END_SRAM_ADDR)
return true;
// Or in FLASH range
if (addr >= START_FLASH_ADDR && addr < END_FLASH_ADDR)
return true;
return false;
}
#endif
bool UnwReadW(const uint32_t a, uint32_t *v) {
if (!validate_addr(a))
return false;
*v = *(uint32_t *)a;
return true;
}
bool UnwReadH(const uint32_t a, uint16_t *v) {
if (!validate_addr(a))
return false;
*v = *(uint16_t *)a;
return true;
}
bool UnwReadB(const uint32_t a, uint8_t *v) {
if (!validate_addr(a))
return false;
*v = *(uint8_t *)a;
return true;
}
#endif // __arm__ || __thumb__
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/unwmemaccess.cpp
|
C++
|
agpl-3.0
| 6,646
|
/***************************************************************************
* ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk
* Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle
*
* This program is PUBLIC DOMAIN.
* This means that there is no copyright and anyone is able to take a copy
* for free and use it as they wish, with or without modifications, and in
* any context, commercially or otherwise. The only limitation is that I
* don't guarantee that the software is fit for any purpose or accept any
* liability for its use or misuse - this software is without warranty.
***************************************************************************
* File Description: Utility functions to access memory
**************************************************************************/
#pragma once
#include "unwarm.h"
#include <stdint.h>
bool UnwReadW(const uint32_t a, uint32_t *v);
bool UnwReadH(const uint32_t a, uint16_t *v);
bool UnwReadB(const uint32_t a, uint8_t *v);
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/backtrace/unwmemaccess.h
|
C
|
agpl-3.0
| 1,018
|
/**
* 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/>.
*
*/
/***************************************************************************
* ARM CPU Exception handler
***************************************************************************/
#if defined(__arm__) || defined(__thumb__)
/*
On ARM CPUs exception handling is quite powerful.
By default, upon a crash, the CPU enters the handlers that have a higher priority than any other interrupts,
so, in effect, no (real) interrupt can "interrupt" the handler (it's acting like if interrupts were disabled).
If the handler is not called as re-entrant (that is, if the crash is not happening inside an interrupt or an handler),
then it'll patch the return address to a dumping function (resume_from_fault) and save the crash state.
The CPU will exit the handler and, as such, re-allow the other interrupts, and jump to the dumping function.
In this function, the usual serial port (USB / HW) will be used to dump the crash (no special configuration required).
The only case where it requires hardware UART is when it's crashing in an interrupt or a crash handler.
In that case, instead of returning to the resume_from_fault function (and thus, re-enabling interrupts),
it jumps to this function directly (so with interrupts disabled), after changing the behavior of the serial output
wrapper to use the HW uart (and in effect, calling MinSerial::init which triggers a warning if you are using
a USB serial port).
In the case you have a USB serial port, this part will be disabled, and only that part (so that's the reason for
the warning).
This means that you can't have a crash report if the crash happens in an interrupt or an handler if you are using
a USB serial port since it's physically impossible.
You will get a crash report in all other cases.
*/
#include "exception_hook.h"
#include "../backtrace/backtrace.h"
#include "../MinSerial.h"
#define HW_REG(X) (*((volatile unsigned long *)(X)))
// Default function use the CPU VTOR register to get the vector table.
// Accessing the CPU VTOR register is done in assembly since it's the only way that's common to all current tool
unsigned long get_vtor() { return HW_REG(0xE000ED08); } // Even if it looks like an error, it is not an error
void * hook_get_hardfault_vector_address(unsigned vtor) { return (void*)(vtor + 0x03); }
void * hook_get_memfault_vector_address(unsigned vtor) { return (void*)(vtor + 0x04); }
void * hook_get_busfault_vector_address(unsigned vtor) { return (void*)(vtor + 0x05); }
void * hook_get_usagefault_vector_address(unsigned vtor) { return (void*)(vtor + 0x06); }
void * hook_get_reserved_vector_address(unsigned vtor) { return (void*)(vtor + 0x07); }
// Common exception frame for ARM, should work for all ARM CPU
// Described here (modified for convenience): https://interrupt.memfault.com/blog/cortex-m-fault-debug
struct __attribute__((packed)) ContextStateFrame {
uint32_t r0;
uint32_t r1;
uint32_t r2;
uint32_t r3;
uint32_t r12;
uint32_t lr;
uint32_t pc;
uint32_t xpsr;
};
struct __attribute__((packed)) ContextSavedFrame {
uint32_t R0;
uint32_t R1;
uint32_t R2;
uint32_t R3;
uint32_t R12;
uint32_t LR;
uint32_t PC;
uint32_t XPSR;
uint32_t CFSR;
uint32_t HFSR;
uint32_t DFSR;
uint32_t AFSR;
uint32_t MMAR;
uint32_t BFAR;
uint32_t ESP;
uint32_t ELR;
};
#if NONE(STM32F0xx, STM32G0xx)
extern "C"
__attribute__((naked)) void CommonHandler_ASM() {
__asm__ __volatile__ (
// Bit 2 of LR tells which stack pointer to use (either main or process, only main should be used anyway)
"tst lr, #4\n"
"ite eq\n"
"mrseq r0, msp\n"
"mrsne r0, psp\n"
// Save the LR in use when being interrupted
"mov r1, lr\n"
// Get the exception number from the ICSR register
"ldr r2, =0xE000ED00\n"
"ldr r2, [r2, #4]\n"
"b CommonHandler_C\n"
);
}
#else // Cortex M0 does not support conditional mov and testing with a constant, so let's have a specific handler for it
extern "C"
__attribute__((naked)) void CommonHandler_ASM() {
__asm__ __volatile__ (
".syntax unified\n"
// Save the LR in use when being interrupted
"mov r1, lr\n"
// Get the exception number from the ICSR register
"ldr r2, =0xE000ED00\n"
"ldr r2, [r2, #4]\n"
"movs r0, #4\n"
"tst r1, r0\n"
"beq _MSP\n"
"mrs r0, psp\n"
"b CommonHandler_C\n"
"_MSP:\n"
"mrs r0, msp\n"
"b CommonHandler_C\n"
);
}
#if DISABLED(DYNAMIC_VECTORTABLE) // Cortex M0 requires the handler's address to be within 32kB to the actual function to be able to branch to it
extern "C" {
void __attribute__((naked, alias("CommonHandler_ASM"), nothrow)) __exc_hardfault();
void __attribute__((naked, alias("CommonHandler_ASM"), nothrow)) __exc_busfault();
void __attribute__((naked, alias("CommonHandler_ASM"), nothrow)) __exc_usagefault();
void __attribute__((naked, alias("CommonHandler_ASM"), nothrow)) __exc_memmanage();
void __attribute__((naked, alias("CommonHandler_ASM"), nothrow)) __exc_nmi();
void __attribute__((naked, alias("CommonHandler_ASM"), nothrow)) __stm32reservedexception7();
void __attribute__((naked, alias("CommonHandler_ASM"), nothrow)) __stm32reservedexception8();
void __attribute__((naked, alias("CommonHandler_ASM"), nothrow)) __stm32reservedexception9();
void __attribute__((naked, alias("CommonHandler_ASM"), nothrow)) __stm32reservedexception10();
void __attribute__((naked, alias("CommonHandler_ASM"), nothrow)) __stm32reservedexception13();
}
//TODO When going off from libmaple, you'll need to replace those by the one from STM32/HAL_MinSerial.cpp
#endif
#endif
// Must be a macro to avoid creating a function frame
#define HALT_IF_DEBUGGING() \
do { \
if (HW_REG(0xE000EDF0) & _BV(0)) { \
__asm("bkpt 1"); \
} \
} while (0)
// Resume from a fault (if possible) so we can still use interrupt based code for serial output
// In that case, we will not jump back to the faulty code, but instead to a dumping code and then a
// basic loop with watchdog calling or manual resetting
static ContextSavedFrame savedFrame;
static uint8_t lastCause;
bool resume_from_fault() {
static const char* causestr[] = { "Thread", "Rsvd", "NMI", "Hard", "Mem", "Bus", "Usage", "7", "8", "9", "10", "SVC", "Dbg", "13", "PendSV", "SysTk", "IRQ" };
// Reinit the serial link (might only work if implemented in each of your boards)
MinSerial::init();
MinSerial::TX("\n\n## Software Fault detected ##\n");
MinSerial::TX("Cause: "); MinSerial::TX(causestr[min(lastCause, (uint8_t)16)]); MinSerial::TX('\n');
MinSerial::TX("R0 : "); MinSerial::TXHex(savedFrame.R0); MinSerial::TX('\n');
MinSerial::TX("R1 : "); MinSerial::TXHex(savedFrame.R1); MinSerial::TX('\n');
MinSerial::TX("R2 : "); MinSerial::TXHex(savedFrame.R2); MinSerial::TX('\n');
MinSerial::TX("R3 : "); MinSerial::TXHex(savedFrame.R3); MinSerial::TX('\n');
MinSerial::TX("R12 : "); MinSerial::TXHex(savedFrame.R12); MinSerial::TX('\n');
MinSerial::TX("LR : "); MinSerial::TXHex(savedFrame.LR); MinSerial::TX('\n');
MinSerial::TX("PC : "); MinSerial::TXHex(savedFrame.PC); MinSerial::TX('\n');
MinSerial::TX("PSR : "); MinSerial::TXHex(savedFrame.XPSR); MinSerial::TX('\n');
// Configurable Fault Status Register
// Consists of MMSR, BFSR and UFSR
MinSerial::TX("CFSR : "); MinSerial::TXHex(savedFrame.CFSR); MinSerial::TX('\n');
// Hard Fault Status Register
MinSerial::TX("HFSR : "); MinSerial::TXHex(savedFrame.HFSR); MinSerial::TX('\n');
// Debug Fault Status Register
MinSerial::TX("DFSR : "); MinSerial::TXHex(savedFrame.DFSR); MinSerial::TX('\n');
// Auxiliary Fault Status Register
MinSerial::TX("AFSR : "); MinSerial::TXHex(savedFrame.AFSR); MinSerial::TX('\n');
// Read the Fault Address Registers. These may not contain valid values.
// Check BFARVALID/MMARVALID to see if they are valid values
// MemManage Fault Address Register
MinSerial::TX("MMAR : "); MinSerial::TXHex(savedFrame.MMAR); MinSerial::TX('\n');
// Bus Fault Address Register
MinSerial::TX("BFAR : "); MinSerial::TXHex(savedFrame.BFAR); MinSerial::TX('\n');
MinSerial::TX("ExcLR: "); MinSerial::TXHex(savedFrame.ELR); MinSerial::TX('\n');
MinSerial::TX("ExcSP: "); MinSerial::TXHex(savedFrame.ESP); MinSerial::TX('\n');
// The stack pointer is pushed by 8 words upon entering an exception, so we need to revert this
backtrace_ex(savedFrame.ESP + 8*4, savedFrame.LR, savedFrame.PC);
// Call the last resort function here
hook_last_resort_func();
const uint32_t start = millis(), end = start + 100; // 100ms should be enough
// We need to wait for the serial buffers to be output but we don't know for how long
// So we'll just need to refresh the watchdog for a while and then stop for the system to reboot
uint32_t last = start;
while (PENDING(last, end)) {
hal.watchdog_refresh();
while (millis() == last) { /* nada */ }
last = millis();
MinSerial::TX('.');
}
// Reset now by reinstantiating the bootloader's vector table
HW_REG(0xE000ED08) = 0;
// Restart watchdog
#if DISABLED(USE_WATCHDOG)
// No watchdog, let's perform ARMv7 reset instead by writing to AIRCR register with VECTKEY set to SYSRESETREQ
HW_REG(0xE000ED0C) = (HW_REG(0xE000ED0C) & 0x0000FFFF) | 0x05FA0004;
#endif
while(1) {} // Bad luck, nothing worked
}
// Make sure the compiler does not optimize the frame argument away
extern "C"
__attribute__((optimize("O0")))
void CommonHandler_C(ContextStateFrame * frame, unsigned long lr, unsigned long cause) {
// If you are using it'll stop here
HALT_IF_DEBUGGING();
// Save the state to backtrace later on (don't call memcpy here since the stack can be corrupted)
savedFrame.R0 = frame->r0;
savedFrame.R1 = frame->r1;
savedFrame.R2 = frame->r2;
savedFrame.R3 = frame->r3;
savedFrame.R12 = frame->r12;
savedFrame.LR = frame->lr;
savedFrame.PC = frame->pc;
savedFrame.XPSR= frame->xpsr;
lastCause = cause & 0x1FF;
volatile uint32_t &CFSR = HW_REG(0xE000ED28);
savedFrame.CFSR = CFSR;
savedFrame.HFSR = HW_REG(0xE000ED2C);
savedFrame.DFSR = HW_REG(0xE000ED30);
savedFrame.AFSR = HW_REG(0xE000ED3C);
savedFrame.MMAR = HW_REG(0xE000ED34);
savedFrame.BFAR = HW_REG(0xE000ED38);
savedFrame.ESP = (unsigned long)frame; // Even on return, this should not be overwritten by the CPU
savedFrame.ELR = lr;
// First check if we can resume from this exception to our own handler safely
// If we can, then we don't need to disable interrupts and the usual serial code
// can be used
//const uint32_t non_usage_fault_mask = 0x0000FFFF;
//const bool non_usage_fault_occurred = (CFSR & non_usage_fault_mask) != 0;
// the bottom 8 bits of the xpsr hold the exception number of the
// executing exception or 0 if the processor is in Thread mode
const bool faulted_from_exception = ((frame->xpsr & 0xFF) != 0);
if (!faulted_from_exception) { // Not sure about the non_usage_fault, we want to try anyway, don't we ? && !non_usage_fault_occurred)
// Try to resume to our handler here
CFSR |= CFSR; // The ARM programmer manual says you must write to 1 all fault bits to clear them so this instruction is correct
frame->pc = (uint32_t)resume_from_fault; // Patch where to return to
frame->lr = 0xDEADBEEF; // If our handler returns (it shouldn't), let's make it trigger an exception immediately
frame->xpsr = _BV(24); // Need to clean the PSR register to thumb II only
MinSerial::force_using_default_output = true;
return; // The CPU will resume in our handler hopefully, and we'll try to use default serial output
}
// Sorry, we need to emergency code here since the fault is too dangerous to recover from
MinSerial::force_using_default_output = false;
resume_from_fault();
}
void hook_cpu_exceptions() {
#if ENABLED(DYNAMIC_VECTORTABLE)
// On ARM 32bits CPU, the vector table is like this:
// 0x0C => Hardfault
// 0x10 => MemFault
// 0x14 => BusFault
// 0x18 => UsageFault
// Unfortunately, it's usually run from flash, and we can't write to flash here directly to hook our instruction
// We could set an hardware breakpoint, and hook on the fly when it's being called, but this
// is hard to get right and would probably break debugger when attached
// So instead, we'll allocate a new vector table filled with the previous value except
// for the fault we are interested in.
// Now, comes the issue to figure out what is the current vector table size
// There is nothing telling us what is the vector table as it's per-cpu vendor specific.
// BUT: we are being called at the end of the setup, so we assume the setup is done
// Thus, we can read the current vector table until we find an address that's not in flash, and it would mark the
// end of the vector table (skipping the fist entry obviously)
// The position of the program in flash is expected to be at 0x08xxx xxxx on all known platform for ARM and the
// flash size is available via register 0x1FFFF7E0 on STM32 family, but it's not the case for all ARM boards
// (accessing this register might trigger a fault if it's not implemented).
// So we'll simply mask the top 8 bits of the first handler as an hint of being in the flash or not -that's poor and will
// probably break if the flash happens to be more than 128MB, but in this case, we are not magician, we need help from outside.
unsigned long *vecAddr = (unsigned long*)get_vtor();
SERIAL_ECHOPGM("Vector table addr: ");
SERIAL_PRINTLN(get_vtor(), PrintBase::Hex);
#ifdef VECTOR_TABLE_SIZE
uint32_t vec_size = VECTOR_TABLE_SIZE;
alignas(128) static unsigned long vectable[VECTOR_TABLE_SIZE] ;
#else
#ifndef IS_IN_FLASH
#define IS_IN_FLASH(X) (((unsigned long)X & 0xFF000000) == 0x08000000)
#endif
// When searching for the end of the vector table, this acts as a limit not to overcome
#ifndef VECTOR_TABLE_SENTINEL
#define VECTOR_TABLE_SENTINEL 80
#endif
// Find the vector table size
uint32_t vec_size = 1;
while (IS_IN_FLASH(vecAddr[vec_size]) && vec_size < VECTOR_TABLE_SENTINEL)
vec_size++;
// We failed to find a valid vector table size, let's abort hooking up
if (vec_size == VECTOR_TABLE_SENTINEL) return;
// Poor method that's wasting RAM here, but allocating with malloc and alignment would be worst
// 128 bytes alignment is required for writing the VTOR register
alignas(128) static unsigned long vectable[VECTOR_TABLE_SENTINEL];
SERIAL_ECHOPGM("Detected vector table size: ");
SERIAL_PRINTLN(vec_size, PrintBase::Hex);
#endif
uint32_t defaultFaultHandler = vecAddr[(unsigned)7];
// Copy the current vector table into the new table
for (uint32_t i = 0; i < vec_size; i++) {
vectable[i] = vecAddr[i];
// Replace all default handler by our own handler
if (vectable[i] == defaultFaultHandler)
vectable[i] = (unsigned long)&CommonHandler_ASM;
}
// Let's hook now with our functions
vectable[(unsigned long)hook_get_hardfault_vector_address(0)] = (unsigned long)&CommonHandler_ASM;
vectable[(unsigned long)hook_get_memfault_vector_address(0)] = (unsigned long)&CommonHandler_ASM;
vectable[(unsigned long)hook_get_busfault_vector_address(0)] = (unsigned long)&CommonHandler_ASM;
vectable[(unsigned long)hook_get_usagefault_vector_address(0)] = (unsigned long)&CommonHandler_ASM;
// Finally swap with our own vector table
// This is supposed to be atomic, but let's do that with interrupt disabled
HW_REG(0xE000ED08) = (unsigned long)vectable | _BV32(29); // 29th bit is for telling the CPU the table is now in SRAM (should be present already)
SERIAL_ECHOLNPGM("Installed fault handlers");
#endif
}
#endif // __arm__ || __thumb__
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/cpu_exception/exception_arm.cpp
|
C++
|
agpl-3.0
| 17,039
|
/**
* 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 "exception_hook.h"
void * __attribute__((weak)) hook_get_hardfault_vector_address(unsigned) { return 0; }
void * __attribute__((weak)) hook_get_memfault_vector_address(unsigned) { return 0; }
void * __attribute__((weak)) hook_get_busfault_vector_address(unsigned) { return 0; }
void * __attribute__((weak)) hook_get_usagefault_vector_address(unsigned) { return 0; }
void __attribute__((weak)) hook_last_resort_func() {}
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/cpu_exception/exception_hook.cpp
|
C++
|
agpl-3.0
| 1,292
|
/**
* 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
/* Here is the expected behavior of a system producing a CPU exception with this hook installed:
1. Before the system is crashed
1.1 Upon validation (not done yet in this code, but we could be using DEBUG flags here to allow/disallow hooking)
1.2 Install the hook by overwriting the vector table exception handler with the hooked function
2. Upon system crash (for example, by a dereference of a NULL pointer or anything else)
2.1 The CPU triggers its exception and jump into the vector table for the exception type
2.2 Instead of finding the default handler, it finds the updated pointer to our hook
2.3 The CPU jumps into our hook function (likely a naked function to keep all information about crash point intact)
2.4 The hook (naked) function saves the important registers (stack pointer, program counter, current mode) and jumps to a common exception handler (in C)
2.5 The common exception handler dumps the registers on the serial link and perform a backtrace around the crashing point
2.6 Once the backtrace is performed the last resort function is called (platform specific).
On some platform with a LCD screen, this might display the crash information as a QR code or as text for the
user to capture by taking a picture
2.7 The CPU is reset and/or halted by triggering a debug breakpoint if a debugger is attached */
// Hook into CPU exception interrupt table to call the backtracing code upon an exception
// Most platform will simply do nothing here, but those who can will install/overwrite the default exception handler
// with a more performant exception handler
void hook_cpu_exceptions();
// Some platform might deal without a hard fault handler, in that case, return 0 in your platform here or skip implementing it
void * __attribute__((weak)) hook_get_hardfault_vector_address(unsigned base_address);
// Some platform might deal without a memory management fault handler, in that case, return 0 in your platform here or skip implementing it
void * __attribute__((weak)) hook_get_memfault_vector_address(unsigned base_address);
// Some platform might deal without a bus fault handler, in that case, return 0 in your platform here or skip implementing it
void * __attribute__((weak)) hook_get_busfault_vector_address(unsigned base_address);
// Some platform might deal without a usage fault handler, in that case, return 0 in your platform here or skip implementing it
void * __attribute__((weak)) hook_get_usagefault_vector_address(unsigned base_address);
// Last resort function that can be called after the exception handler was called.
void __attribute__((weak)) hook_last_resort_func();
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/cpu_exception/exception_hook.h
|
C
|
agpl-3.0
| 3,557
|
/**
* 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 ANY(EEPROM_SETTINGS, SD_FIRMWARE_UPDATE)
#include "eeprom_api.h"
PersistentStore persistentStore;
#endif
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/eeprom_api.cpp
|
C++
|
agpl-3.0
| 1,017
|
/**
* 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 <stddef.h>
#include <stdint.h>
#include "../../libs/crc16.h"
// For testing. Define with -DEEPROM_EXCL_ZONE=916,926 in INI files.
//#define EEPROM_EXCL_ZONE 916,926 // Test a range
//#define EEPROM_EXCL_ZONE 333 // Test a single byte
#ifdef EEPROM_EXCL_ZONE
static constexpr int eeprom_exclude_zone[] = { EEPROM_EXCL_ZONE },
eeprom_exclude_size = eeprom_exclude_zone[COUNT(eeprom_exclude_zone) - 1] - eeprom_exclude_zone[0] + 1;
#define REAL_EEPROM_ADDR(A) (A < eeprom_exclude_zone[0] ? (A) : (A) + eeprom_exclude_size)
#else
#define REAL_EEPROM_ADDR(A) (A)
static constexpr int eeprom_exclude_size = 0;
#endif
class PersistentStore {
public:
// Total available persistent storage space (in bytes)
static size_t capacity();
// Prepare to read or write
static bool access_start();
// Housecleaning after read or write
static bool access_finish();
// Write one or more bytes of data and update the CRC
// Return 'true' on write error
static bool write_data(int &pos, const uint8_t *value, size_t size, uint16_t *crc);
// Read one or more bytes of data and update the CRC
// Return 'true' on read error
static bool read_data(int &pos, uint8_t *value, size_t size, uint16_t *crc, const bool writing=true);
// Write one or more bytes of data
// Return 'true' on write error
static bool write_data(const int pos, const uint8_t *value, const size_t size=sizeof(uint8_t)) {
int data_pos = pos;
uint16_t crc = 0;
return write_data(data_pos, value, size, &crc);
}
// Write a single byte of data
// Return 'true' on write error
static bool write_data(const int pos, const uint8_t value) { return write_data(pos, &value); }
// Read one or more bytes of data
// Return 'true' on read error
static bool read_data(const int pos, uint8_t *value, const size_t size=1) {
int data_pos = pos;
uint16_t crc = 0;
return read_data(data_pos, value, size, &crc);
}
};
extern PersistentStore persistentStore;
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/eeprom_api.h
|
C++
|
agpl-3.0
| 2,888
|
/**
* 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
//
// EEPROM
//
void eeprom_init();
void eeprom_write_byte(uint8_t *pos, uint8_t value);
uint8_t eeprom_read_byte(uint8_t *pos);
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/eeprom_if.h
|
C
|
agpl-3.0
| 1,005
|
/**
* 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/>.
*
*/
/**
* Platform-independent Arduino functions for I2C EEPROM.
* Enable USE_SHARED_EEPROM if not supplied by the framework.
*/
#include "../../inc/MarlinConfig.h"
#if ENABLED(I2C_EEPROM)
#include "eeprom_if.h"
#if ENABLED(SOFT_I2C_EEPROM)
#include <SlowSoftWire.h>
SlowSoftWire eWire = SlowSoftWire(I2C_SDA_PIN, I2C_SCL_PIN, true);
#else
#include <Wire.h>
#define eWire Wire
#endif
void eeprom_init() {
eWire.begin(
#if PINS_EXIST(I2C_SCL, I2C_SDA) && DISABLED(SOFT_I2C_EEPROM)
uint8_t(I2C_SDA_PIN), uint8_t(I2C_SCL_PIN)
#endif
);
}
#if ENABLED(USE_SHARED_EEPROM)
#ifndef EEPROM_WRITE_DELAY
#define EEPROM_WRITE_DELAY 5
#endif
#ifndef EEPROM_DEVICE_ADDRESS
#define EEPROM_DEVICE_ADDRESS 0x50
#endif
static constexpr uint8_t eeprom_device_address = I2C_ADDRESS(EEPROM_DEVICE_ADDRESS);
// ------------------------
// Public functions
// ------------------------
#define SMALL_EEPROM (MARLIN_EEPROM_SIZE <= 2048)
// Combine Address high bits into the device address on <=16Kbit (2K) and >512Kbit (64K) EEPROMs.
// Note: MARLIN_EEPROM_SIZE is specified in bytes, whereas EEPROM model numbers refer to bits.
// e.g., The "16" in BL24C16 indicates a 16Kbit (2KB) size.
static uint8_t _eeprom_calc_device_address(uint8_t * const pos) {
const unsigned eeprom_address = (unsigned)pos;
return (SMALL_EEPROM || MARLIN_EEPROM_SIZE > 65536)
? uint8_t(eeprom_device_address | ((eeprom_address >> (SMALL_EEPROM ? 8 : 16)) & 0x07))
: eeprom_device_address;
}
static void _eeprom_begin(uint8_t * const pos) {
const unsigned eeprom_address = (unsigned)pos;
eWire.beginTransmission(_eeprom_calc_device_address(pos));
if (!SMALL_EEPROM)
eWire.write(uint8_t((eeprom_address >> 8) & 0xFF)); // Address High, if needed
eWire.write(uint8_t(eeprom_address & 0xFF)); // Address Low
}
void eeprom_write_byte(uint8_t *pos, uint8_t value) {
_eeprom_begin(pos);
eWire.write(value);
eWire.endTransmission();
// wait for write cycle to complete
// this could be done more efficiently with "acknowledge polling"
delay(EEPROM_WRITE_DELAY);
}
uint8_t eeprom_read_byte(uint8_t *pos) {
_eeprom_begin(pos);
eWire.endTransmission();
eWire.requestFrom(_eeprom_calc_device_address(pos), (byte)1);
return eWire.available() ? eWire.read() : 0xFF;
}
#endif // USE_SHARED_EEPROM
#endif // I2C_EEPROM
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/eeprom_if_i2c.cpp
|
C++
|
agpl-3.0
| 3,230
|
/**
* 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/>.
*
*/
/**
* Platform-independent Arduino functions for SPI EEPROM.
* Enable USE_SHARED_EEPROM if not supplied by the framework.
*/
#include "../../inc/MarlinConfig.h"
#if ENABLED(SPI_EEPROM)
#include "eeprom_if.h"
void eeprom_init() {}
#if ENABLED(USE_SHARED_EEPROM)
#define CMD_WREN 6 // WREN
#define CMD_READ 2 // WRITE
#define CMD_WRITE 2 // WRITE
#ifndef EEPROM_WRITE_DELAY
#define EEPROM_WRITE_DELAY 7
#endif
static void _eeprom_begin(uint8_t * const pos, const uint8_t cmd) {
const uint8_t eeprom_temp[3] = {
cmd,
(unsigned(pos) >> 8) & 0xFF, // Address High
unsigned(pos) & 0xFF // Address Low
};
WRITE(SPI_EEPROM1_CS_PIN, HIGH); // Usually free already
WRITE(SPI_EEPROM1_CS_PIN, LOW); // Activate the Bus
spiSend(SPI_CHAN_EEPROM1, eeprom_temp, 3);
// Leave the Bus in-use
}
uint8_t eeprom_read_byte(uint8_t *pos) {
_eeprom_begin(pos, CMD_READ); // Set read location and begin transmission
const uint8_t v = spiRec(SPI_CHAN_EEPROM1); // After READ a value sits on the Bus
WRITE(SPI_EEPROM1_CS_PIN, HIGH); // Done with device
return v;
}
void eeprom_write_byte(uint8_t *pos, uint8_t value) {
const uint8_t eeprom_temp = CMD_WREN;
WRITE(SPI_EEPROM1_CS_PIN, LOW);
spiSend(SPI_CHAN_EEPROM1, &eeprom_temp, 1); // Write Enable
WRITE(SPI_EEPROM1_CS_PIN, HIGH); // Done with the Bus
delay(1); // For a small amount of time
_eeprom_begin(pos, CMD_WRITE); // Set write address and begin transmission
spiSend(SPI_CHAN_EEPROM1, value); // Send the value to be written
WRITE(SPI_EEPROM1_CS_PIN, HIGH); // Done with the Bus
delay(EEPROM_WRITE_DELAY); // Give page write time to complete
}
#endif // USE_SHARED_EEPROM
#endif // I2C_EEPROM
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/eeprom_if_spi.cpp
|
C++
|
agpl-3.0
| 2,669
|
/**
* 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(WIFISUPPORT)
#include "Delay.h"
void esp_wifi_init(void) { // init ESP01 WIFI module pins
#if PIN_EXISTS(ESP_WIFI_MODULE_GPIO0)
OUT_WRITE(ESP_WIFI_MODULE_GPIO0_PIN, HIGH);
#endif
#if PIN_EXISTS(ESP_WIFI_MODULE_GPIO2)
OUT_WRITE(ESP_WIFI_MODULE_GPIO2_PIN, HIGH);
#endif
#if PIN_EXISTS(ESP_WIFI_MODULE_RESET)
delay(1); // power up delay (0.1mS minimum)
OUT_WRITE(ESP_WIFI_MODULE_RESET_PIN, LOW);
delay(1);
OUT_WRITE(ESP_WIFI_MODULE_RESET_PIN, HIGH);
#endif
#if PIN_EXISTS(ESP_WIFI_MODULE_ENABLE)
delay(1); // delay after reset released (0.1mS minimum)
OUT_WRITE(ESP_WIFI_MODULE_ENABLE_PIN, HIGH);
#endif
}
#endif // WIFISUPPORT
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/esp_wifi.cpp
|
C++
|
agpl-3.0
| 1,615
|
/**
* 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
void esp_wifi_init();
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/esp_wifi.h
|
C
|
agpl-3.0
| 898
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2023 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
//
// Faux pins for Dependency Check
//
//
// STM32 Pin Names
//
#define PA0 0x10
#define PA1 0x11
#define PA2 0x12
#define PA3 0x13
#define PA4 0x14
#define PA5 0x15
#define PA6 0x16
#define PA7 0x17
#define PA8 0x18
#define PA9 0x19
#define PA10 0x1A
#define PA11 0x1B
#define PA12 0x1C
#define PA13 0x1D
#define PA14 0x1E
#define PA15 0x1F
#define PB0 0x20
#define PB1 0x21
#define PB2 0x22
#define PB3 0x23
#define PB4 0x24
#define PB5 0x25
#define PB6 0x26
#define PB7 0x27
#define PB8 0x28
#define PB9 0x29
#define PB10 0x2A
#define PB11 0x2B
#define PB12 0x2C
#define PB13 0x2D
#define PB14 0x2E
#define PB15 0x2F
#define PC0 0x30
#define PC1 0x31
#define PC2 0x32
#define PC3 0x33
#define PC4 0x34
#define PC5 0x35
#define PC6 0x36
#define PC7 0x37
#define PC8 0x38
#define PC9 0x39
#define PC10 0x3A
#define PC11 0x3B
#define PC12 0x3C
#define PC13 0x3D
#define PC14 0x3E
#define PC15 0x3F
#define PD0 0x40
#define PD1 0x41
#define PD2 0x42
#define PD3 0x43
#define PD4 0x44
#define PD5 0x45
#define PD6 0x46
#define PD7 0x47
#define PD8 0x48
#define PD9 0x49
#define PD10 0x4A
#define PD11 0x4B
#define PD12 0x4C
#define PD13 0x4D
#define PD14 0x4E
#define PD15 0x4F
#define PE0 0x50
#define PE1 0x51
#define PE2 0x52
#define PE3 0x53
#define PE4 0x54
#define PE5 0x55
#define PE6 0x56
#define PE7 0x57
#define PE8 0x58
#define PE9 0x59
#define PE10 0x5A
#define PE11 0x5B
#define PE12 0x5C
#define PE13 0x5D
#define PE14 0x5E
#define PE15 0x5F
#define PF0 0x60
#define PF1 0x61
#define PF2 0x62
#define PF3 0x63
#define PF4 0x64
#define PF5 0x65
#define PF6 0x66
#define PF7 0x67
#define PF8 0x68
#define PF9 0x69
#define PF10 0x6A
#define PF11 0x6B
#define PF12 0x6C
#define PF13 0x6D
#define PF14 0x6E
#define PF15 0x6F
#define PG0 0x70
#define PG1 0x71
#define PG2 0x72
#define PG3 0x73
#define PG4 0x74
#define PG5 0x75
#define PG6 0x76
#define PG7 0x77
#define PG8 0x78
#define PG9 0x79
#define PG10 0x7A
#define PG11 0x7B
#define PG12 0x7C
#define PG13 0x7D
#define PG14 0x7E
#define PG15 0x7F
#define PH0 0x80
#define PH1 0x81
#define PH2 0x82
#define PH3 0x83
#define PH4 0x84
#define PH5 0x85
#define PH6 0x86
#define PH7 0x87
#define PH8 0x88
#define PH9 0x89
#define PH10 0x8A
#define PH11 0x8B
#define PH12 0x8C
#define PH13 0x8D
#define PH14 0x8E
#define PH15 0x8F
#define PI0 0x90
#define PI1 0x91
#define PI2 0x92
#define PI3 0x93
#define PI4 0x94
#define PI5 0x95
#define PI6 0x96
#define PI7 0x97
#define PI8 0x98
#define PI9 0x99
#define PI10 0x9A
#define PI11 0x9B
#define PI12 0x9C
#define PI13 0x9D
#define PI14 0x9E
#define PI15 0x9F
#define PJ0 0xA0
#define PJ1 0xA1
#define PJ2 0xA2
#define PJ3 0xA3
#define PJ4 0xA4
#define PJ5 0xA5
#define PJ6 0xA6
#define PJ7 0xA7
#define PJ8 0xA8
#define PJ9 0xA9
#define PJ10 0xAA
#define PJ11 0xAB
#define PJ12 0xAC
#define PJ13 0xAD
#define PJ14 0xAE
#define PJ15 0xAF
//
// LPC Pin Names
//
#define P0_00 100
#define P0_01 101
#define P0_02 102
#define P0_03 103
#define P0_04 104
#define P0_05 105
#define P0_06 106
#define P0_07 107
#define P0_08 108
#define P0_09 109
#define P0_10 110
#define P0_11 111
#define P0_12 112
#define P0_13 113
#define P0_14 114
#define P0_15 115
#define P0_16 116
#define P0_17 117
#define P0_18 118
#define P0_19 119
#define P0_20 120
#define P0_21 121
#define P0_22 122
#define P0_23 123
#define P0_24 124
#define P0_25 125
#define P0_26 126
#define P0_27 127
#define P0_28 128
#define P0_29 129
#define P0_30 130
#define P0_31 131
#define P1_00 200
#define P1_01 201
#define P1_02 202
#define P1_03 203
#define P1_04 204
#define P1_05 205
#define P1_06 206
#define P1_07 207
#define P1_08 208
#define P1_09 209
#define P1_10 210
#define P1_11 211
#define P1_12 212
#define P1_13 213
#define P1_14 214
#define P1_15 215
#define P1_16 216
#define P1_17 217
#define P1_18 218
#define P1_19 219
#define P1_20 220
#define P1_21 221
#define P1_22 222
#define P1_23 223
#define P1_24 224
#define P1_25 225
#define P1_26 226
#define P1_27 227
#define P1_28 228
#define P1_29 229
#define P1_30 230
#define P1_31 231
#define P2_00 300
#define P2_01 301
#define P2_02 302
#define P2_03 303
#define P2_04 304
#define P2_05 305
#define P2_06 306
#define P2_07 307
#define P2_08 308
#define P2_09 309
#define P2_10 310
#define P2_11 311
#define P2_12 312
#define P2_13 313
#define P2_14 314
#define P2_15 315
#define P2_16 316
#define P2_17 317
#define P2_18 318
#define P2_19 319
#define P2_20 320
#define P2_21 321
#define P2_22 322
#define P2_23 323
#define P2_24 324
#define P2_25 325
#define P2_26 326
#define P2_27 327
#define P2_28 328
#define P2_29 329
#define P2_30 330
#define P2_31 331
#define P3_00 400
#define P3_01 401
#define P3_02 402
#define P3_03 403
#define P3_04 404
#define P3_05 405
#define P3_06 406
#define P3_07 407
#define P3_08 408
#define P3_09 409
#define P3_10 410
#define P3_11 411
#define P3_12 412
#define P3_13 413
#define P3_14 414
#define P3_15 415
#define P3_16 416
#define P3_17 417
#define P3_18 418
#define P3_19 419
#define P3_20 420
#define P3_21 421
#define P3_22 422
#define P3_23 423
#define P3_24 424
#define P3_25 425
#define P3_26 426
#define P3_27 427
#define P3_28 428
#define P3_29 429
#define P3_30 430
#define P3_31 431
#define P4_00 500
#define P4_01 501
#define P4_02 502
#define P4_03 503
#define P4_04 504
#define P4_05 505
#define P4_06 506
#define P4_07 507
#define P4_08 508
#define P4_09 509
#define P4_10 510
#define P4_11 511
#define P4_12 512
#define P4_13 513
#define P4_14 514
#define P4_15 515
#define P4_16 516
#define P4_17 517
#define P4_18 518
#define P4_19 519
#define P4_20 520
#define P4_21 521
#define P4_22 522
#define P4_23 523
#define P4_24 524
#define P4_25 525
#define P4_26 526
#define P4_27 527
#define P4_28 528
#define P4_29 529
#define P4_30 530
#define P4_31 531
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/fauxpins.h
|
C
|
agpl-3.0
| 6,739
|
/**
* 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/macros.h"
/**
* Math helper functions for 32 bit CPUs
*/
FORCE_INLINE static uint32_t MultiU32X24toH32(uint32_t longIn1, uint32_t longIn2) {
return ((uint64_t)longIn1 * longIn2 + 0x00800000) >> 24;
}
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/math_32bit.h
|
C
|
agpl-3.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/>.
*
*/
#pragma once
#ifndef __AVR__
#ifndef __PGMSPACE_H_
// This define should prevent reading the system pgmspace.h if included elsewhere
// This is not normally needed.
#define __PGMSPACE_H_ 1
#endif
#ifndef PROGMEM
#define PROGMEM
#endif
#ifndef PGM_P
#define PGM_P const char *
#endif
#ifndef PSTR
#define PSTR(str) (str)
#endif
#ifndef F
class __FlashStringHelper;
#define F(str) (reinterpret_cast<const __FlashStringHelper *>(PSTR(str)))
#endif
#ifndef _SFR_BYTE
#define _SFR_BYTE(n) (n)
#endif
#ifndef memchr_P
#define memchr_P(str, c, len) memchr((str), (c), (len))
#endif
#ifndef memcmp_P
#define memcmp_P(a, b, n) memcmp((a), (b), (n))
#endif
#ifndef memcpy_P
#define memcpy_P(dest, src, num) memcpy((dest), (src), (num))
#endif
#ifndef memmem_P
#define memmem_P(a, alen, b, blen) memmem((a), (alen), (b), (blen))
#endif
#ifndef memrchr_P
#define memrchr_P(str, val, len) memrchr((str), (val), (len))
#endif
#ifndef strcat_P
#define strcat_P(dest, src) strcat((dest), (src))
#endif
#ifndef strchr_P
#define strchr_P(str, c) strchr((str), (c))
#endif
#ifndef strchrnul_P
#define strchrnul_P(str, c) strchrnul((str), (c))
#endif
#ifndef strcmp_P
#define strcmp_P(a, b) strcmp((a), (b))
#endif
#ifndef strcpy_P
#define strcpy_P(dest, src) strcpy((dest), (src))
#endif
#ifndef strcasecmp_P
#define strcasecmp_P(a, b) strcasecmp((a), (b))
#endif
#ifndef strcasestr_P
#define strcasestr_P(a, b) strcasestr((a), (b))
#endif
#ifndef strlcat_P
#define strlcat_P(dest, src, len) strlcat((dest), (src), (len))
#endif
#ifndef strlcpy_P
#define strlcpy_P(dest, src, len) strlcpy((dest), (src), (len))
#endif
#ifndef strlen_P
#define strlen_P(s) strlen((const char *)(s))
#endif
#ifndef strnlen_P
#define strnlen_P(str, len) strnlen((str), (len))
#endif
#ifndef strncmp_P
#define strncmp_P(a, b, n) strncmp((a), (b), (n))
#endif
#ifndef strncasecmp_P
#define strncasecmp_P(a, b, n) strncasecmp((a), (b), (n))
#endif
#ifndef strncat_P
#define strncat_P(a, b, n) strncat((a), (b), (n))
#endif
#ifndef strncpy_P
#define strncpy_P(a, b, n) strncpy((a), (b), (n))
#endif
#ifndef strpbrk_P
#define strpbrk_P(str, chrs) strpbrk((str), (chrs))
#endif
#ifndef strrchr_P
#define strrchr_P(str, c) strrchr((str), (c))
#endif
#ifndef strsep_P
#define strsep_P(pstr, delim) strsep((pstr), (delim))
#endif
#ifndef strspn_P
#define strspn_P(str, chrs) strspn((str), (chrs))
#endif
#ifndef strstr_P
#define strstr_P(a, b) strstr((a), (b))
#endif
#ifndef sprintf_P
#define sprintf_P(s, ...) sprintf((s), __VA_ARGS__)
#endif
#ifndef vfprintf_P
#define vfprintf_P(s, ...) vfprintf((s), __VA_ARGS__)
#endif
#ifndef printf_P
#define printf_P(...) printf(__VA_ARGS__)
#endif
#ifndef snprintf_P
#define snprintf_P(s, n, ...) snprintf((s), (n), __VA_ARGS__)
#endif
#ifndef vsprintf_P
#define vsprintf_P(s, ...) vsprintf((s),__VA_ARGS__)
#endif
#ifndef vsnprintf_P
#define vsnprintf_P(s, n, ...) vsnprintf((s), (n),__VA_ARGS__)
#endif
#ifndef fprintf_P
#define fprintf_P(s, ...) fprintf((s), __VA_ARGS__)
#endif
#ifndef pgm_read_byte
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
#endif
#ifndef pgm_read_word
#define pgm_read_word(addr) (*(const unsigned short *)(addr))
#endif
#ifndef pgm_read_dword
#define pgm_read_dword(addr) (*(const unsigned long *)(addr))
#endif
#ifndef pgm_read_float
#define pgm_read_float(addr) (*(const float *)(addr))
#endif
#ifndef pgm_read_byte_near
#define pgm_read_byte_near(addr) pgm_read_byte(addr)
#endif
#ifndef pgm_read_word_near
#define pgm_read_word_near(addr) pgm_read_word(addr)
#endif
#ifndef pgm_read_dword_near
#define pgm_read_dword_near(addr) pgm_read_dword(addr)
#endif
#ifndef pgm_read_float_near
#define pgm_read_float_near(addr) pgm_read_float(addr)
#endif
#ifndef pgm_read_byte_far
#define pgm_read_byte_far(addr) pgm_read_byte(addr)
#endif
#ifndef pgm_read_word_far
#define pgm_read_word_far(addr) pgm_read_word(addr)
#endif
#ifndef pgm_read_dword_far
#define pgm_read_dword_far(addr) pgm_read_dword(addr)
#endif
#ifndef pgm_read_float_far
#define pgm_read_float_far(addr) pgm_read_float(addr)
#endif
#ifndef pgm_read_pointer
#define pgm_read_pointer
#endif
// Fix bug in pgm_read_ptr
#undef pgm_read_ptr
#define pgm_read_ptr(addr) (*((void**)(addr)))
#endif // __AVR__
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/progmem.h
|
C++
|
agpl-3.0
| 5,073
|
/**
* 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/>.
*
*/
/**
* servo.cpp - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2
* Copyright (c) 2009 Michael Margolis. All right reserved.
*/
/**
* A servo is activated by creating an instance of the Servo class passing the desired pin to the attach() method.
* The servos are pulsed in the background using the value most recently written using the write() method
*
* Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached.
* Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four.
*
* The methods are:
*
* Servo - Class for manipulating servo motors connected to Arduino pins.
*
* attach(pin) - Attach a servo motor to an i/o pin.
* attach(pin, min, max) - Attach to a pin, setting min and max values in microseconds
* Default min is 544, max is 2400
*
* write() - Set the servo angle in degrees. (Invalid angles —over MIN_PULSE_WIDTH— are treated as µs.)
* writeMicroseconds() - Set the servo pulse width in microseconds.
* move(pin, angle) - Sequence of attach(pin), write(angle), safe_delay(servo_delay[servoIndex]).
* With DEACTIVATE_SERVOS_AFTER_MOVE it detaches after servo_delay[servoIndex].
* read() - Get the last-written servo pulse width as an angle between 0 and 180.
* readMicroseconds() - Get the last-written servo pulse width in microseconds.
* attached() - Return true if a servo is attached.
* detach() - Stop an attached servo from pulsing its i/o pin.
*/
#include "../../inc/MarlinConfig.h"
#if SHARED_SERVOS
#include "servo.h"
#include "servo_private.h"
ServoInfo_t servo_info[MAX_SERVOS]; // static array of servo info structures
uint8_t ServoCount = 0; // the total number of attached servos
#define SERVO_MIN_US(v) (MIN_PULSE_WIDTH - (v) * 4) // minimum value in uS for this servo
#define SERVO_MAX_US(v) (MAX_PULSE_WIDTH - (v) * 4) // maximum value in uS for this servo
/************ static functions common to all instances ***********************/
static bool anyTimerChannelActive(const timer16_Sequence_t timer) {
// returns true if any servo is active on this timer
for (uint8_t channel = 0; channel < SERVOS_PER_TIMER; ++channel) {
if (SERVO(timer, channel).Pin.isActive)
return true;
}
return false;
}
/****************** end of static functions ******************************/
Servo::Servo() {
if (ServoCount < MAX_SERVOS) {
servoIndex = ServoCount++; // assign a servo index to this instance
servo_info[servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values - 12 Aug 2009
}
else
servoIndex = INVALID_SERVO; // too many servos
}
int8_t Servo::attach(const int inPin) {
return attach(inPin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
}
int8_t Servo::attach(const int inPin, const int inMin, const int inMax) {
if (servoIndex >= MAX_SERVOS) return -1;
if (inPin > 0) servo_info[servoIndex].Pin.nbr = inPin;
pinMode(servo_info[servoIndex].Pin.nbr, OUTPUT); // set servo pin to output
// TODO: min/max check: ABS(min - MIN_PULSE_WIDTH) / 4 < 128
min = (MIN_PULSE_WIDTH - inMin) / 4; //resolution of min/max is 4 uS
max = (MAX_PULSE_WIDTH - inMax) / 4;
// initialize the timer if it has not already been initialized
const timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex);
if (!anyTimerChannelActive(timer)) initISR(timer);
servo_info[servoIndex].Pin.isActive = true; // this must be set after the check for anyTimerChannelActive
return servoIndex;
}
void Servo::detach() {
servo_info[servoIndex].Pin.isActive = false;
const timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex);
if (!anyTimerChannelActive(timer)) finISR(timer);
//pinMode(servo_info[servoIndex].Pin.nbr, INPUT); // set servo pin to input
}
void Servo::write(int value) {
if (value < MIN_PULSE_WIDTH) // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
value = map(constrain(value, 0, 180), 0, 180, SERVO_MIN_US(min), SERVO_MAX_US(max));
writeMicroseconds(value);
}
void Servo::writeMicroseconds(int value) {
// calculate and store the values for the given channel
byte channel = servoIndex;
if (channel < MAX_SERVOS) { // ensure channel is valid
// ensure pulse width is valid
LIMIT(value, SERVO_MIN_US(min), SERVO_MAX_US(max));
value = usToTicks(value - (TRIM_DURATION)); // convert to ticks after compensating for interrupt overhead - 12 Aug 2009
CRITICAL_SECTION_START();
servo_info[channel].ticks = value;
CRITICAL_SECTION_END();
}
}
// return the value as degrees
int Servo::read() { return map(readMicroseconds() + 1, SERVO_MIN_US(min), SERVO_MAX_US(max), 0, 180); }
int Servo::readMicroseconds() {
return (servoIndex == INVALID_SERVO) ? 0 : ticksToUs(servo_info[servoIndex].ticks) + (TRIM_DURATION);
}
bool Servo::attached() { return servo_info[servoIndex].Pin.isActive; }
void Servo::move(const int value) {
constexpr uint16_t servo_delay[] = SERVO_DELAY;
static_assert(COUNT(servo_delay) == NUM_SERVOS, "SERVO_DELAY must be an array NUM_SERVOS long.");
if (attach(0) >= 0) {
write(value);
safe_delay(servo_delay[servoIndex]);
TERN_(DEACTIVATE_SERVOS_AFTER_MOVE, detach());
}
}
#endif // SHARED_SERVOS
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/servo.cpp
|
C++
|
agpl-3.0
| 6,346
|
/**
* 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
/**
* servo.h - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2
* Copyright (c) 2009 Michael Margolis. All right reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* A servo is activated by creating an instance of the Servo class passing the desired pin to the attach() method.
* The servos are pulsed in the background using the value most recently written using the write() method
*
* Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached.
* Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four.
* The sequence used to seize timers is defined in timers.h
*
* The methods are:
*
* Servo - Class for manipulating servo motors connected to Arduino pins.
*
* attach(pin ) - Attaches a servo motor to an i/o pin.
* attach(pin, min, max ) - Attaches to a pin setting min and max values in microseconds
* default min is 544, max is 2400
*
* write() - Sets the servo angle in degrees. (invalid angle that is valid as pulse in microseconds is treated as microseconds)
* writeMicroseconds() - Sets the servo pulse width in microseconds
* read() - Gets the last written servo pulse width as an angle between 0 and 180.
* readMicroseconds() - Gets the last written servo pulse width in microseconds. (was read_us() in first release)
* attached() - Returns true if there is a servo attached.
* detach() - Stops an attached servos from pulsing its i/o pin.
* move(angle) - Sequence of attach(0), write(angle),
* With DEACTIVATE_SERVOS_AFTER_MOVE wait SERVO_DELAY and detach.
*/
#if IS_TEENSY32
#include "../TEENSY31_32/Servo.h"
#elif IS_TEENSY35 || IS_TEENSY36
#include "../TEENSY35_36/Servo.h"
#elif IS_TEENSY40 || IS_TEENSY41
#include "../TEENSY40_41/Servo.h"
#elif defined(TARGET_LPC1768)
#include "../LPC1768/Servo.h"
#elif defined(ARDUINO_ARCH_HC32)
#include "../HC32/Servo.h"
#elif defined(__STM32F1__) || defined(TARGET_STM32F1)
#include "../STM32F1/Servo.h"
#elif defined(ARDUINO_ARCH_STM32)
#include "../STM32/Servo.h"
#elif defined(ARDUINO_ARCH_ESP32)
#include "../ESP32/Servo.h"
#else
#include <stdint.h>
#if defined(__AVR__) || defined(ARDUINO_ARCH_SAM) || defined(__SAMD51__) || defined(__SAMD21__)
// we're good to go
#else
#error "This library only supports boards with an AVR, SAM3X, SAMD21 or SAMD51 processor."
#endif
#define Servo_VERSION 2 // software version of this library
class Servo {
public:
Servo();
int8_t attach(const int pin); // attach the given pin to the next free channel, set pinMode, return channel number (-1 on fail)
int8_t attach(const int pin, const int min, const int max); // as above but also sets min and max values for writes.
void detach();
void write(int value); // if value is < 200 it is treated as an angle, otherwise as pulse width in microseconds
void writeMicroseconds(int value); // write pulse width in microseconds
void move(const int value); // attach the servo, then move to value
// if value is < 200 it is treated as an angle, otherwise as pulse width in microseconds
// if DEACTIVATE_SERVOS_AFTER_MOVE wait SERVO_DELAY, then detach
int read(); // returns current pulse width as an angle between 0 and 180 degrees
int readMicroseconds(); // returns current pulse width in microseconds for this servo (was read_us() in first release)
bool attached(); // return true if this servo is attached, otherwise false
private:
uint8_t servoIndex; // index into the channel data for this servo
int8_t min; // minimum is this value times 4 added to MIN_PULSE_WIDTH
int8_t max; // maximum is this value times 4 added to MAX_PULSE_WIDTH
};
#endif
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/servo.h
|
C++
|
agpl-3.0
| 5,628
|
/**
* 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
/**
* servo_private.h - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2
* Copyright (c) 2009 Michael Margolis. All right reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
// Architecture specific include
#ifdef __AVR__
#include "../AVR/ServoTimers.h"
#elif defined(ARDUINO_ARCH_SAM)
#include "../DUE/ServoTimers.h"
#elif defined(__SAMD51__)
#include "../SAMD51/ServoTimers.h"
#elif defined(__SAMD21__)
#include "../SAMD21/ServoTimers.h"
#else
#error "This library only supports boards with an AVR, SAM3X, SAMD21 or SAMD51 processor."
#endif
// Macros
#define MIN_PULSE_WIDTH 544 // the shortest pulse sent to a servo
#define MAX_PULSE_WIDTH 2400 // the longest pulse sent to a servo
#define DEFAULT_PULSE_WIDTH 1500 // default pulse width when servo is attached
#define REFRESH_INTERVAL 20000 // minimum time to refresh servos in microseconds
#define SERVOS_PER_TIMER 12 // the maximum number of servos controlled by one timer
#define MAX_SERVOS (_Nbr_16timers * SERVOS_PER_TIMER)
#define INVALID_SERVO 255 // flag indicating an invalid servo index
// Convert microseconds to ticks and back (PRESCALER depends on architecture)
#define usToTicks(_us) (clockCyclesPerMicrosecond() * (_us) / (SERVO_TIMER_PRESCALER))
#define ticksToUs(_ticks) (unsigned(_ticks) * (SERVO_TIMER_PRESCALER) / clockCyclesPerMicrosecond())
// convenience macros
#define SERVO_INDEX_TO_TIMER(_servo_nbr) timer16_Sequence_t(_servo_nbr / (SERVOS_PER_TIMER)) // the timer controlling this servo
#define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % (SERVOS_PER_TIMER)) // the index of the servo on this timer
#define SERVO_INDEX(_timer,_channel) ((_timer*(SERVOS_PER_TIMER)) + _channel) // servo index by timer and channel
#define SERVO(_timer,_channel) servo_info[SERVO_INDEX(_timer,_channel)] // servo class by timer and channel
// Types
typedef struct {
uint8_t nbr : 7 ; // a pin number from 0 to 127
uint8_t isActive : 1 ; // true if this channel is enabled, pin not pulsed if false
} ServoPin_t;
typedef struct {
ServoPin_t Pin;
unsigned int ticks;
} ServoInfo_t;
// Global variables
extern uint8_t ServoCount;
extern ServoInfo_t servo_info[MAX_SERVOS];
// Public functions
void initISR(const timer16_Sequence_t timer_index);
void finISR(const timer16_Sequence_t timer_index);
|
2301_81045437/Marlin
|
Marlin/src/HAL/shared/servo_private.h
|
C
|
agpl-3.0
| 4,028
|
/**
* 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/>.
*
*/
/**
* About Marlin
*
* This firmware is a mashup between Sprinter and grbl.
* - https://github.com/kliment/Sprinter
* - https://github.com/grbl/grbl
*/
#include "MarlinCore.h"
#include "HAL/shared/Delay.h"
#include "HAL/shared/esp_wifi.h"
#include "HAL/shared/cpu_exception/exception_hook.h"
#if ENABLED(WIFISUPPORT)
#include "HAL/shared/esp_wifi.h"
#endif
#ifdef ARDUINO
#include <pins_arduino.h>
#endif
#include <math.h>
#include "module/endstops.h"
#include "module/motion.h"
#include "module/planner.h"
#include "module/printcounter.h" // PrintCounter or Stopwatch
#include "module/settings.h"
#include "module/stepper.h"
#include "module/temperature.h"
#if ENABLED(FT_MOTION)
#include "module/ft_motion.h"
#endif
#include "gcode/gcode.h"
#include "gcode/parser.h"
#include "gcode/queue.h"
#include "feature/pause.h"
#include "sd/cardreader.h"
#include "lcd/marlinui.h"
#if HAS_TOUCH_BUTTONS
#include "lcd/touch/touch_buttons.h"
#endif
#if HAS_TFT_LVGL_UI
#include "lcd/extui/mks_ui/tft_lvgl_configuration.h"
#include "lcd/extui/mks_ui/draw_ui.h"
#include "lcd/extui/mks_ui/mks_hardware.h"
#include <lvgl.h>
#endif
#if HAS_DWIN_E3V2
#include "lcd/e3v2/common/encoder.h"
#if ENABLED(DWIN_CREALITY_LCD)
#include "lcd/e3v2/creality/dwin.h"
#elif ENABLED(DWIN_CREALITY_LCD_JYERSUI)
#include "lcd/e3v2/jyersui/dwin.h"
#endif
#endif
#if HAS_ETHERNET
#include "feature/ethernet.h"
#endif
#if ENABLED(IIC_BL24CXX_EEPROM)
#include "libs/BL24CXX.h"
#endif
#if ENABLED(DIRECT_STEPPING)
#include "feature/direct_stepping.h"
#endif
#if ENABLED(HOST_ACTION_COMMANDS)
#include "feature/host_actions.h"
#endif
#if HAS_BEEPER
#include "libs/buzzer.h"
#endif
#if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER)
#include "feature/closedloop.h"
#endif
#if HAS_MOTOR_CURRENT_I2C
#include "feature/digipot/digipot.h"
#endif
#if ENABLED(MIXING_EXTRUDER)
#include "feature/mixing.h"
#endif
#if ENABLED(MAX7219_DEBUG)
#include "feature/max7219.h"
#endif
#if HAS_COLOR_LEDS
#include "feature/leds/leds.h"
#endif
#if ENABLED(BLTOUCH)
#include "feature/bltouch.h"
#endif
#if ENABLED(BD_SENSOR)
#include "feature/bedlevel/bdl/bdl.h"
#endif
#if ENABLED(POLL_JOG)
#include "feature/joystick.h"
#endif
#if HAS_SERVOS
#include "module/servo.h"
#endif
#if HAS_MOTOR_CURRENT_DAC
#include "feature/dac/stepper_dac.h"
#endif
#if ENABLED(EXPERIMENTAL_I2CBUS)
#include "feature/twibus.h"
#endif
#if ENABLED(I2C_POSITION_ENCODERS)
#include "feature/encoder_i2c.h"
#endif
#if (HAS_TRINAMIC_CONFIG || HAS_TMC_SPI) && DISABLED(PSU_DEFAULT_OFF)
#include "feature/tmc_util.h"
#endif
#if HAS_CUTTER
#include "feature/spindle_laser.h"
#endif
#if HAS_MEDIA
CardReader card;
#endif
#if ENABLED(G38_PROBE_TARGET)
uint8_t G38_move; // = 0
bool G38_did_trigger; // = false
#endif
#if ENABLED(DELTA)
#include "module/delta.h"
#elif ENABLED(POLARGRAPH)
#include "module/polargraph.h"
#elif IS_SCARA
#include "module/scara.h"
#elif ENABLED(POLAR)
#include "module/polar.h"
#endif
#if HAS_LEVELING
#include "feature/bedlevel/bedlevel.h"
#endif
#if ENABLED(GCODE_REPEAT_MARKERS)
#include "feature/repeat.h"
#endif
#if ENABLED(POWER_LOSS_RECOVERY)
#include "feature/powerloss.h"
#endif
#if ENABLED(CANCEL_OBJECTS)
#include "feature/cancel_object.h"
#endif
#if HAS_FILAMENT_SENSOR
#include "feature/runout.h"
#endif
#if ANY(PROBE_TARE, HAS_Z_SERVO_PROBE)
#include "module/probe.h"
#endif
#if ENABLED(HOTEND_IDLE_TIMEOUT)
#include "feature/hotend_idle.h"
#endif
#if ENABLED(TEMP_STAT_LEDS)
#include "feature/leds/tempstat.h"
#endif
#if ENABLED(CASE_LIGHT_ENABLE)
#include "feature/caselight.h"
#endif
#if HAS_FANMUX
#include "feature/fanmux.h"
#endif
#if HAS_TOOLCHANGE
#include "module/tool_change.h"
#endif
#if HAS_FANCHECK
#include "feature/fancheck.h"
#endif
#if ENABLED(USE_CONTROLLER_FAN)
#include "feature/controllerfan.h"
#endif
#if HAS_PRUSA_MMU1
#include "feature/mmu/mmu.h"
#endif
#if HAS_PRUSA_MMU2
#include "feature/mmu/mmu2.h"
#endif
#if ENABLED(PASSWORD_FEATURE)
#include "feature/password/password.h"
#endif
#if DGUS_LCD_UI_MKS
#include "lcd/extui/dgus/DGUSScreenHandler.h"
#endif
#if HAS_DRIVER_SAFE_POWER_PROTECT
#include "feature/stepper_driver_safety.h"
#endif
#if ENABLED(PSU_CONTROL)
#include "feature/power.h"
#endif
#if ENABLED(EASYTHREED_UI)
#include "feature/easythreed_ui.h"
#endif
#if ENABLED(MARLIN_TEST_BUILD)
#include "tests/marlin_tests.h"
#endif
PGMSTR(M112_KILL_STR, "M112 Shutdown");
MarlinState marlin_state = MF_INITIALIZING;
// For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
bool wait_for_heatup = false;
// For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
#if HAS_RESUME_CONTINUE
bool wait_for_user; // = false;
void wait_for_user_response(millis_t ms/*=0*/, const bool no_sleep/*=false*/) {
UNUSED(no_sleep);
KEEPALIVE_STATE(PAUSED_FOR_USER);
wait_for_user = true;
if (ms) ms += millis(); // expire time
while (wait_for_user && !(ms && ELAPSED(millis(), ms)))
idle(TERN_(ADVANCED_PAUSE_FEATURE, no_sleep));
wait_for_user = false;
while (ui.button_pressed()) safe_delay(50);
}
#endif
/**
* ***************************************************************************
* ******************************** FUNCTIONS ********************************
* ***************************************************************************
*/
/**
* Stepper Reset (RigidBoard, et.al.)
*/
#if HAS_STEPPER_RESET
void disableStepperDrivers() { OUT_WRITE(STEPPER_RESET_PIN, LOW); } // Drive down to keep motor driver chips in reset
void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // Set to input, allowing pullups to pull the pin high
#endif
/**
* Sensitive pin test for M42, M226
*/
#include "pins/sensitive_pins.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnarrowing"
#ifndef RUNTIME_ONLY_ANALOG_TO_DIGITAL
template <pin_t ...D>
constexpr pin_t OnlyPins<_SP_END, D...>::table[sizeof...(D)];
#endif
bool pin_is_protected(const pin_t pin) {
#ifdef RUNTIME_ONLY_ANALOG_TO_DIGITAL
static const pin_t sensitive_pins[] PROGMEM = { SENSITIVE_PINS };
const size_t pincount = COUNT(sensitive_pins);
#else
static constexpr size_t pincount = OnlyPins<SENSITIVE_PINS>::size;
static const pin_t (&sensitive_pins)[pincount] PROGMEM = OnlyPins<SENSITIVE_PINS>::table;
#endif
for (uint8_t i = 0; i < pincount; ++i) {
const pin_t * const pptr = &sensitive_pins[i];
if (pin == (sizeof(pin_t) == 2 ? (pin_t)pgm_read_word(pptr) : (pin_t)pgm_read_byte(pptr))) return true;
}
return false;
}
#pragma GCC diagnostic pop
bool printer_busy() {
return planner.movesplanned() || printingIsActive();
}
/**
* A Print Job exists when the timer is running or SD is printing
*/
bool printJobOngoing() { return print_job_timer.isRunning() || IS_SD_PRINTING(); }
/**
* Printing is active when a job is underway but not paused
*/
bool printingIsActive() { return !did_pause_print && printJobOngoing(); }
/**
* Printing is paused according to SD or host indicators
*/
bool printingIsPaused() {
return did_pause_print || print_job_timer.isPaused() || IS_SD_PAUSED();
}
void startOrResumeJob() {
if (!printingIsPaused()) {
TERN_(GCODE_REPEAT_MARKERS, repeat.reset());
TERN_(CANCEL_OBJECTS, cancelable.reset());
TERN_(LCD_SHOW_E_TOTAL, e_move_accumulator = 0);
TERN_(SET_REMAINING_TIME, ui.reset_remaining_time());
}
print_job_timer.start();
}
#if HAS_MEDIA
inline void abortSDPrinting() {
IF_DISABLED(NO_SD_AUTOSTART, card.autofile_cancel());
card.abortFilePrintNow(TERN_(SD_RESORT, true));
queue.clear();
quickstop_stepper();
print_job_timer.abort();
IF_DISABLED(SD_ABORT_NO_COOLDOWN, thermalManager.disable_all_heaters());
TERN(HAS_CUTTER, cutter.kill(), thermalManager.zero_fan_speeds()); // Full cutter shutdown including ISR control
wait_for_heatup = false;
TERN_(POWER_LOSS_RECOVERY, recovery.purge());
#ifdef EVENT_GCODE_SD_ABORT
queue.inject(F(EVENT_GCODE_SD_ABORT));
#endif
TERN_(PASSWORD_AFTER_SD_PRINT_ABORT, password.lock_machine());
}
inline void finishSDPrinting() {
if (queue.enqueue_one(F("M1001"))) { // Keep trying until it gets queued
marlin_state = MF_RUNNING; // Signal to stop trying
TERN_(PASSWORD_AFTER_SD_PRINT_END, password.lock_machine());
TERN_(DGUS_LCD_UI_MKS, screen.sdPrintingFinished());
}
}
#endif // HAS_MEDIA
/**
* Minimal management of Marlin's core activities:
* - Keep the command buffer full
* - Check for maximum inactive time between commands
* - Check for maximum inactive time between stepper commands
* - Check if CHDK_PIN needs to go LOW
* - Check for KILL button held down
* - Check for HOME button held down
* - Check for CUSTOM USER button held down
* - Check if cooling fan needs to be switched on
* - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
* - Pulse FET_SAFETY_PIN if it exists
*/
inline void manage_inactivity(const bool no_stepper_sleep=false) {
queue.get_available_commands();
const millis_t ms = millis();
// Prevent steppers timing-out
const bool do_reset_timeout = no_stepper_sleep
|| TERN0(PAUSE_PARK_NO_STEPPER_TIMEOUT, did_pause_print);
// Reset both the M18/M84 activity timeout and the M85 max 'kill' timeout
if (do_reset_timeout) gcode.reset_stepper_timeout(ms);
if (gcode.stepper_max_timed_out(ms)) {
SERIAL_ERROR_START();
SERIAL_ECHOPGM(STR_KILL_PRE);
SERIAL_ECHOLNPGM(STR_KILL_INACTIVE_TIME, parser.command_ptr);
kill();
}
const bool has_blocks = planner.has_blocks_queued(); // Any moves in the planner?
if (has_blocks) gcode.reset_stepper_timeout(ms); // Reset timeout for M18/M84, M85 max 'kill', and laser.
// M18 / M84 : Handle steppers inactive time timeout
#if HAS_DISABLE_IDLE_AXES
if (gcode.stepper_inactive_time) {
static bool already_shutdown_steppers; // = false
if (!has_blocks && !do_reset_timeout && gcode.stepper_inactive_timeout()) {
if (!already_shutdown_steppers) {
already_shutdown_steppers = true;
// Individual axes will be disabled if configured
TERN_(DISABLE_IDLE_X, stepper.disable_axis(X_AXIS));
TERN_(DISABLE_IDLE_Y, stepper.disable_axis(Y_AXIS));
TERN_(DISABLE_IDLE_Z, stepper.disable_axis(Z_AXIS));
TERN_(DISABLE_IDLE_I, stepper.disable_axis(I_AXIS));
TERN_(DISABLE_IDLE_J, stepper.disable_axis(J_AXIS));
TERN_(DISABLE_IDLE_K, stepper.disable_axis(K_AXIS));
TERN_(DISABLE_IDLE_U, stepper.disable_axis(U_AXIS));
TERN_(DISABLE_IDLE_V, stepper.disable_axis(V_AXIS));
TERN_(DISABLE_IDLE_W, stepper.disable_axis(W_AXIS));
TERN_(DISABLE_IDLE_E, stepper.disable_e_steppers());
TERN_(AUTO_BED_LEVELING_UBL, bedlevel.steppers_were_disabled());
}
}
else
already_shutdown_steppers = false;
}
#endif
#if ENABLED(PHOTO_GCODE) && PIN_EXISTS(CHDK)
// Check if CHDK should be set to LOW (after M240 set it HIGH)
extern millis_t chdk_timeout;
if (chdk_timeout && ELAPSED(ms, chdk_timeout)) {
chdk_timeout = 0;
WRITE(CHDK_PIN, LOW);
}
#endif
#if HAS_KILL
// Check if the kill button was pressed and wait to ensure the signal is not noise
// typically caused by poor insulation and grounding on LCD cables.
// Lower numbers here will increase response time and therefore safety rating.
// It is recommended to set this as low as possibe without false triggers.
// -------------------------------------------------------------------------------
#ifndef KILL_DELAY
#define KILL_DELAY 250
#endif
static int killCount = 0; // make the inactivity button a bit less responsive
if (kill_state())
killCount++;
else if (killCount > 0)
killCount--;
// Exceeded threshold and we can confirm that it was not accidental
// KILL the machine
// ----------------------------------------------------------------
if (killCount >= KILL_DELAY) {
SERIAL_ERROR_START();
SERIAL_ECHOPGM(STR_KILL_PRE);
SERIAL_ECHOLNPGM(STR_KILL_BUTTON);
kill();
}
#endif
#if ENABLED(FREEZE_FEATURE)
stepper.frozen = READ(FREEZE_PIN) == FREEZE_STATE;
#endif
#if HAS_HOME
// Handle a standalone HOME button
constexpr millis_t HOME_DEBOUNCE_DELAY = 1000UL;
static millis_t next_home_key_ms; // = 0
if (!IS_SD_PRINTING() && !READ(HOME_PIN)) { // HOME_PIN goes LOW when pressed
if (ELAPSED(ms, next_home_key_ms)) {
next_home_key_ms = ms + HOME_DEBOUNCE_DELAY;
LCD_MESSAGE(MSG_AUTO_HOME);
queue.inject_P(G28_STR);
}
}
#endif
#if ENABLED(CUSTOM_USER_BUTTONS)
// Handle a custom user button if defined
const bool printer_not_busy = !printingIsActive();
#define HAS_CUSTOM_USER_BUTTON(N) (PIN_EXISTS(BUTTON##N) && defined(BUTTON##N##_HIT_STATE) && defined(BUTTON##N##_GCODE))
#define HAS_BETTER_USER_BUTTON(N) HAS_CUSTOM_USER_BUTTON(N) && defined(BUTTON##N##_DESC)
#define _CHECK_CUSTOM_USER_BUTTON(N, CODE) do{ \
constexpr millis_t CUB_DEBOUNCE_DELAY_##N = 250UL; \
static millis_t next_cub_ms_##N; \
if (BUTTON##N##_HIT_STATE == READ(BUTTON##N##_PIN) \
&& (ENABLED(BUTTON##N##_WHEN_PRINTING) || printer_not_busy)) { \
if (ELAPSED(ms, next_cub_ms_##N)) { \
next_cub_ms_##N = ms + CUB_DEBOUNCE_DELAY_##N; \
CODE; \
queue.inject(F(BUTTON##N##_GCODE)); \
TERN_(HAS_MARLINUI_MENU, ui.quick_feedback()); \
} \
} \
}while(0)
#define CHECK_CUSTOM_USER_BUTTON(N) _CHECK_CUSTOM_USER_BUTTON(N, NOOP)
#define CHECK_BETTER_USER_BUTTON(N) _CHECK_CUSTOM_USER_BUTTON(N, if (strlen(BUTTON##N##_DESC)) LCD_MESSAGE_F(BUTTON##N##_DESC))
#if HAS_BETTER_USER_BUTTON(1)
CHECK_BETTER_USER_BUTTON(1);
#elif HAS_CUSTOM_USER_BUTTON(1)
CHECK_CUSTOM_USER_BUTTON(1);
#endif
#if HAS_BETTER_USER_BUTTON(2)
CHECK_BETTER_USER_BUTTON(2);
#elif HAS_CUSTOM_USER_BUTTON(2)
CHECK_CUSTOM_USER_BUTTON(2);
#endif
#if HAS_BETTER_USER_BUTTON(3)
CHECK_BETTER_USER_BUTTON(3);
#elif HAS_CUSTOM_USER_BUTTON(3)
CHECK_CUSTOM_USER_BUTTON(3);
#endif
#if HAS_BETTER_USER_BUTTON(4)
CHECK_BETTER_USER_BUTTON(4);
#elif HAS_CUSTOM_USER_BUTTON(4)
CHECK_CUSTOM_USER_BUTTON(4);
#endif
#if HAS_BETTER_USER_BUTTON(5)
CHECK_BETTER_USER_BUTTON(5);
#elif HAS_CUSTOM_USER_BUTTON(5)
CHECK_CUSTOM_USER_BUTTON(5);
#endif
#if HAS_BETTER_USER_BUTTON(6)
CHECK_BETTER_USER_BUTTON(6);
#elif HAS_CUSTOM_USER_BUTTON(6)
CHECK_CUSTOM_USER_BUTTON(6);
#endif
#if HAS_BETTER_USER_BUTTON(7)
CHECK_BETTER_USER_BUTTON(7);
#elif HAS_CUSTOM_USER_BUTTON(7)
CHECK_CUSTOM_USER_BUTTON(7);
#endif
#if HAS_BETTER_USER_BUTTON(8)
CHECK_BETTER_USER_BUTTON(8);
#elif HAS_CUSTOM_USER_BUTTON(8)
CHECK_CUSTOM_USER_BUTTON(8);
#endif
#if HAS_BETTER_USER_BUTTON(9)
CHECK_BETTER_USER_BUTTON(9);
#elif HAS_CUSTOM_USER_BUTTON(9)
CHECK_CUSTOM_USER_BUTTON(9);
#endif
#if HAS_BETTER_USER_BUTTON(10)
CHECK_BETTER_USER_BUTTON(10);
#elif HAS_CUSTOM_USER_BUTTON(10)
CHECK_CUSTOM_USER_BUTTON(10);
#endif
#if HAS_BETTER_USER_BUTTON(11)
CHECK_BETTER_USER_BUTTON(11);
#elif HAS_CUSTOM_USER_BUTTON(11)
CHECK_CUSTOM_USER_BUTTON(11);
#endif
#if HAS_BETTER_USER_BUTTON(12)
CHECK_BETTER_USER_BUTTON(12);
#elif HAS_CUSTOM_USER_BUTTON(12)
CHECK_CUSTOM_USER_BUTTON(12);
#endif
#if HAS_BETTER_USER_BUTTON(13)
CHECK_BETTER_USER_BUTTON(13);
#elif HAS_CUSTOM_USER_BUTTON(13)
CHECK_CUSTOM_USER_BUTTON(13);
#endif
#if HAS_BETTER_USER_BUTTON(14)
CHECK_BETTER_USER_BUTTON(14);
#elif HAS_CUSTOM_USER_BUTTON(14)
CHECK_CUSTOM_USER_BUTTON(14);
#endif
#if HAS_BETTER_USER_BUTTON(15)
CHECK_BETTER_USER_BUTTON(15);
#elif HAS_CUSTOM_USER_BUTTON(15)
CHECK_CUSTOM_USER_BUTTON(15);
#endif
#if HAS_BETTER_USER_BUTTON(16)
CHECK_BETTER_USER_BUTTON(16);
#elif HAS_CUSTOM_USER_BUTTON(16)
CHECK_CUSTOM_USER_BUTTON(16);
#endif
#if HAS_BETTER_USER_BUTTON(17)
CHECK_BETTER_USER_BUTTON(17);
#elif HAS_CUSTOM_USER_BUTTON(17)
CHECK_CUSTOM_USER_BUTTON(17);
#endif
#if HAS_BETTER_USER_BUTTON(18)
CHECK_BETTER_USER_BUTTON(18);
#elif HAS_CUSTOM_USER_BUTTON(18)
CHECK_CUSTOM_USER_BUTTON(18);
#endif
#if HAS_BETTER_USER_BUTTON(19)
CHECK_BETTER_USER_BUTTON(19);
#elif HAS_CUSTOM_USER_BUTTON(19)
CHECK_CUSTOM_USER_BUTTON(19);
#endif
#if HAS_BETTER_USER_BUTTON(20)
CHECK_BETTER_USER_BUTTON(20);
#elif HAS_CUSTOM_USER_BUTTON(20)
CHECK_CUSTOM_USER_BUTTON(20);
#endif
#if HAS_BETTER_USER_BUTTON(21)
CHECK_BETTER_USER_BUTTON(21);
#elif HAS_CUSTOM_USER_BUTTON(21)
CHECK_CUSTOM_USER_BUTTON(21);
#endif
#if HAS_BETTER_USER_BUTTON(22)
CHECK_BETTER_USER_BUTTON(22);
#elif HAS_CUSTOM_USER_BUTTON(22)
CHECK_CUSTOM_USER_BUTTON(22);
#endif
#if HAS_BETTER_USER_BUTTON(23)
CHECK_BETTER_USER_BUTTON(23);
#elif HAS_CUSTOM_USER_BUTTON(23)
CHECK_CUSTOM_USER_BUTTON(23);
#endif
#if HAS_BETTER_USER_BUTTON(24)
CHECK_BETTER_USER_BUTTON(24);
#elif HAS_CUSTOM_USER_BUTTON(24)
CHECK_CUSTOM_USER_BUTTON(24);
#endif
#if HAS_BETTER_USER_BUTTON(25)
CHECK_BETTER_USER_BUTTON(25);
#elif HAS_CUSTOM_USER_BUTTON(25)
CHECK_CUSTOM_USER_BUTTON(25);
#endif
#endif
TERN_(EASYTHREED_UI, easythreed_ui.run());
TERN_(USE_CONTROLLER_FAN, controllerFan.update()); // Check if fan should be turned on to cool stepper drivers down
TERN_(AUTO_POWER_CONTROL, powerManager.check(!ui.on_status_screen() || printJobOngoing() || printingIsPaused()));
TERN_(HOTEND_IDLE_TIMEOUT, hotend_idle.check());
#if ANY(PSU_CONTROL, AUTO_POWER_CONTROL) && PIN_EXISTS(PS_ON_EDM)
if ( ELAPSED(ms, powerManager.last_state_change_ms + PS_EDM_RESPONSE)
&& (READ(PS_ON_PIN) != READ(PS_ON_EDM_PIN) || TERN0(PSU_OFF_REDUNDANT, extDigitalRead(PS_ON1_PIN) != extDigitalRead(PS_ON1_EDM_PIN)))
) kill(GET_TEXT_F(MSG_POWER_EDM_FAULT));
#endif
#if ENABLED(EXTRUDER_RUNOUT_PREVENT)
if (thermalManager.degHotend(active_extruder) > (EXTRUDER_RUNOUT_MINTEMP)
&& ELAPSED(ms, gcode.previous_move_ms + SEC_TO_MS(EXTRUDER_RUNOUT_SECONDS))
&& !planner.has_blocks_queued()
) {
const int8_t e_stepper = TERN(HAS_SWITCHING_EXTRUDER, active_extruder >> 1, active_extruder);
const bool e_off = !stepper.AXIS_IS_ENABLED(E_AXIS, e_stepper);
if (e_off) stepper.ENABLE_EXTRUDER(e_stepper);
const float olde = current_position.e;
current_position.e += EXTRUDER_RUNOUT_EXTRUDE;
line_to_current_position(MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED));
current_position.e = olde;
planner.set_e_position_mm(olde);
planner.synchronize();
if (e_off) stepper.DISABLE_EXTRUDER(e_stepper);
gcode.reset_stepper_timeout(ms);
}
#endif // EXTRUDER_RUNOUT_PREVENT
#if ENABLED(DUAL_X_CARRIAGE)
// handle delayed move timeout
if (delayed_move_time && ELAPSED(ms, delayed_move_time) && IsRunning()) {
// travel moves have been received so enact them
delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
destination = current_position;
prepare_line_to_destination();
planner.synchronize();
}
#endif
TERN_(TEMP_STAT_LEDS, handle_status_leds());
TERN_(MONITOR_DRIVER_STATUS, monitor_tmc_drivers());
// Limit check_axes_activity frequency to 10Hz
static millis_t next_check_axes_ms = 0;
if (ELAPSED(ms, next_check_axes_ms)) {
planner.check_axes_activity();
next_check_axes_ms = ms + 100UL;
}
#if PIN_EXISTS(FET_SAFETY)
static millis_t FET_next;
if (ELAPSED(ms, FET_next)) {
FET_next = ms + FET_SAFETY_DELAY; // 2µs pulse every FET_SAFETY_DELAY mS
OUT_WRITE(FET_SAFETY_PIN, !FET_SAFETY_INVERTED);
DELAY_US(2);
WRITE(FET_SAFETY_PIN, FET_SAFETY_INVERTED);
}
#endif
}
#if ALL(EP_BABYSTEPPING, EMERGENCY_PARSER)
#include "feature/babystep.h"
#endif
/**
* Standard idle routine keeps the machine alive:
* - Core Marlin activities
* - Manage heaters (and Watchdog)
* - Max7219 heartbeat, animation, etc.
*
* Only after setup() is complete:
* - Handle filament runout sensors
* - Run HAL idle tasks
* - Handle Power-Loss Recovery
* - Run StallGuard endstop checks
* - Handle SD Card insert / remove
* - Handle USB Flash Drive insert / remove
* - Announce Host Keepalive state (if any)
* - Update the Print Job Timer state
* - Update the Beeper queue
* - Read Buttons and Update the LCD
* - Run i2c Position Encoders
* - Auto-report Temperatures / SD Status
* - Update the Průša MMU2
* - Handle Joystick jogging
*/
void idle(const bool no_stepper_sleep/*=false*/) {
#ifdef MAX7219_DEBUG_PROFILE
CodeProfiler idle_profiler;
#endif
#if ENABLED(MARLIN_DEV_MODE)
static uint16_t idle_depth = 0;
if (++idle_depth > 5) SERIAL_ECHOLNPGM("idle() call depth: ", idle_depth);
#endif
// Bed Distance Sensor task
TERN_(BD_SENSOR, bdl.process());
// Core Marlin activities
manage_inactivity(no_stepper_sleep);
// Manage Heaters (and Watchdog)
thermalManager.task();
// Max7219 heartbeat, animation, etc
TERN_(MAX7219_DEBUG, max7219.idle_tasks());
// Return if setup() isn't completed
if (marlin_state == MF_INITIALIZING) goto IDLE_DONE;
// TODO: Still causing errors
TERN_(TOOL_SENSOR, (void)check_tool_sensor_stats(active_extruder, true));
// Handle filament runout sensors
#if HAS_FILAMENT_SENSOR
if (TERN1(HAS_PRUSA_MMU2, !mmu2.enabled()))
runout.run();
#endif
// Run HAL idle tasks
hal.idletask();
// Check network connection
TERN_(HAS_ETHERNET, ethernet.check());
// Handle Power-Loss Recovery
#if ENABLED(POWER_LOSS_RECOVERY) && PIN_EXISTS(POWER_LOSS)
if (IS_SD_PRINTING()) recovery.outage();
#endif
// Run StallGuard endstop checks
#if ENABLED(SPI_ENDSTOPS)
if (endstops.tmc_spi_homing.any && TERN1(IMPROVE_HOMING_RELIABILITY, ELAPSED(millis(), sg_guard_period)))
for (uint8_t i = 0; i < 4; ++i) if (endstops.tmc_spi_homing_check()) break; // Read SGT 4 times per idle loop
#endif
// Handle SD Card insert / remove
TERN_(HAS_MEDIA, card.manage_media());
// Handle USB Flash Drive insert / remove
TERN_(USB_FLASH_DRIVE_SUPPORT, card.diskIODriver()->idle());
// Announce Host Keepalive state (if any)
TERN_(HOST_KEEPALIVE_FEATURE, gcode.host_keepalive());
// Update the Print Job Timer state
TERN_(PRINTCOUNTER, print_job_timer.tick());
// Update the Beeper queue
TERN_(HAS_BEEPER, buzzer.tick());
// Handle UI input / draw events
ui.update();
// Run i2c Position Encoders
#if ENABLED(I2C_POSITION_ENCODERS)
{
static millis_t i2cpem_next_update_ms;
if (planner.has_blocks_queued()) {
const millis_t ms = millis();
if (ELAPSED(ms, i2cpem_next_update_ms)) {
I2CPEM.update();
i2cpem_next_update_ms = ms + I2CPE_MIN_UPD_TIME_MS;
}
}
}
#endif
// Auto-report Temperatures / SD Status
#if HAS_AUTO_REPORTING
if (!gcode.autoreport_paused) {
TERN_(AUTO_REPORT_TEMPERATURES, thermalManager.auto_reporter.tick());
TERN_(AUTO_REPORT_FANS, fan_check.auto_reporter.tick());
TERN_(AUTO_REPORT_SD_STATUS, card.auto_reporter.tick());
TERN_(AUTO_REPORT_POSITION, position_auto_reporter.tick());
TERN_(BUFFER_MONITORING, queue.auto_report_buffer_statistics());
}
#endif
// Update the Průša MMU2
TERN_(HAS_PRUSA_MMU2, mmu2.mmu_loop());
// Handle Joystick jogging
TERN_(POLL_JOG, joystick.inject_jog_moves());
// Async Babystepping via the Emergency Parser
#if ALL(EP_BABYSTEPPING, EMERGENCY_PARSER)
babystep.do_ep_steps();
#endif
// Direct Stepping
TERN_(DIRECT_STEPPING, page_manager.write_responses());
// Update the LVGL interface
TERN_(HAS_TFT_LVGL_UI, LV_TASK_HANDLER());
// Manage Fixed-time Motion Control
TERN_(FT_MOTION, ftMotion.loop());
IDLE_DONE:
TERN_(MARLIN_DEV_MODE, idle_depth--);
return;
}
/**
* Kill all activity and lock the machine.
* After this the machine will need to be reset.
*/
void kill(FSTR_P const lcd_error/*=nullptr*/, FSTR_P const lcd_component/*=nullptr*/, const bool steppers_off/*=false*/) {
thermalManager.disable_all_heaters();
TERN_(HAS_CUTTER, cutter.kill()); // Full cutter shutdown including ISR control
// Echo the LCD message to serial for extra context
if (lcd_error) { SERIAL_ECHO_START(); SERIAL_ECHOLN(lcd_error); }
#if HAS_DISPLAY
ui.kill_screen(lcd_error ?: GET_TEXT_F(MSG_KILLED), lcd_component ?: FPSTR(NUL_STR));
#else
UNUSED(lcd_error); UNUSED(lcd_component);
#endif
TERN_(HAS_TFT_LVGL_UI, lv_draw_error_message(lcd_error));
// "Error:Printer halted. kill() called!"
SERIAL_ERROR_MSG(STR_ERR_KILLED);
#ifdef ACTION_ON_KILL
hostui.kill();
#endif
minkill(steppers_off);
}
void minkill(const bool steppers_off/*=false*/) {
// Wait a short time (allows messages to get out before shutting down.
for (int i = 1000; i--;) DELAY_US(600);
cli(); // Stop interrupts
// Wait to ensure all interrupts stopped
for (int i = 1000; i--;) DELAY_US(250);
// Reiterate heaters off
thermalManager.disable_all_heaters();
TERN_(HAS_CUTTER, cutter.kill()); // Reiterate cutter shutdown
// Power off all steppers (for M112) or just the E steppers
steppers_off ? stepper.disable_all_steppers() : stepper.disable_e_steppers();
TERN_(PSU_CONTROL, powerManager.power_off());
TERN_(HAS_SUICIDE, suicide());
#if ANY(HAS_KILL, SOFT_RESET_ON_KILL)
// Wait for both KILL and ENC to be released
while (TERN0(HAS_KILL, kill_state()) || TERN0(SOFT_RESET_ON_KILL, ui.button_pressed()))
hal.watchdog_refresh();
// Wait for either KILL or ENC to be pressed again
while (TERN1(HAS_KILL, !kill_state()) && TERN1(SOFT_RESET_ON_KILL, !ui.button_pressed()))
hal.watchdog_refresh();
// Reboot the board
hal.reboot();
#else
for (;;) hal.watchdog_refresh(); // Wait for RESET button or power-cycle
#endif
}
/**
* Turn off heaters and stop the print in progress
* After a stop the machine may be resumed with M999
*/
void stop() {
thermalManager.disable_all_heaters(); // 'unpause' taken care of in here
print_job_timer.stop();
#if ANY(PROBING_FANS_OFF, ADVANCED_PAUSE_FANS_PAUSE)
thermalManager.set_fans_paused(false); // Un-pause fans for safety
#endif
if (!IsStopped()) {
SERIAL_ERROR_MSG(STR_ERR_STOPPED);
LCD_MESSAGE(MSG_STOPPED);
safe_delay(350); // allow enough time for messages to get out before stopping
marlin_state = MF_STOPPED;
}
}
inline void tmc_standby_setup() {
#if PIN_EXISTS(X_STDBY)
SET_INPUT_PULLDOWN(X_STDBY_PIN);
#endif
#if PIN_EXISTS(X2_STDBY)
SET_INPUT_PULLDOWN(X2_STDBY_PIN);
#endif
#if PIN_EXISTS(Y_STDBY)
SET_INPUT_PULLDOWN(Y_STDBY_PIN);
#endif
#if PIN_EXISTS(Y2_STDBY)
SET_INPUT_PULLDOWN(Y2_STDBY_PIN);
#endif
#if PIN_EXISTS(Z_STDBY)
SET_INPUT_PULLDOWN(Z_STDBY_PIN);
#endif
#if PIN_EXISTS(Z2_STDBY)
SET_INPUT_PULLDOWN(Z2_STDBY_PIN);
#endif
#if PIN_EXISTS(Z3_STDBY)
SET_INPUT_PULLDOWN(Z3_STDBY_PIN);
#endif
#if PIN_EXISTS(Z4_STDBY)
SET_INPUT_PULLDOWN(Z4_STDBY_PIN);
#endif
#if PIN_EXISTS(I_STDBY)
SET_INPUT_PULLDOWN(I_STDBY_PIN);
#endif
#if PIN_EXISTS(J_STDBY)
SET_INPUT_PULLDOWN(J_STDBY_PIN);
#endif
#if PIN_EXISTS(K_STDBY)
SET_INPUT_PULLDOWN(K_STDBY_PIN);
#endif
#if PIN_EXISTS(U_STDBY)
SET_INPUT_PULLDOWN(U_STDBY_PIN);
#endif
#if PIN_EXISTS(V_STDBY)
SET_INPUT_PULLDOWN(V_STDBY_PIN);
#endif
#if PIN_EXISTS(W_STDBY)
SET_INPUT_PULLDOWN(W_STDBY_PIN);
#endif
#if PIN_EXISTS(E0_STDBY)
SET_INPUT_PULLDOWN(E0_STDBY_PIN);
#endif
#if PIN_EXISTS(E1_STDBY)
SET_INPUT_PULLDOWN(E1_STDBY_PIN);
#endif
#if PIN_EXISTS(E2_STDBY)
SET_INPUT_PULLDOWN(E2_STDBY_PIN);
#endif
#if PIN_EXISTS(E3_STDBY)
SET_INPUT_PULLDOWN(E3_STDBY_PIN);
#endif
#if PIN_EXISTS(E4_STDBY)
SET_INPUT_PULLDOWN(E4_STDBY_PIN);
#endif
#if PIN_EXISTS(E5_STDBY)
SET_INPUT_PULLDOWN(E5_STDBY_PIN);
#endif
#if PIN_EXISTS(E6_STDBY)
SET_INPUT_PULLDOWN(E6_STDBY_PIN);
#endif
#if PIN_EXISTS(E7_STDBY)
SET_INPUT_PULLDOWN(E7_STDBY_PIN);
#endif
}
/**
* Marlin Firmware entry-point. Abandon Hope All Ye Who Enter Here.
* Setup before the program loop:
*
* - Call any special pre-init set for the board
* - Put TMC drivers into Low Power Standby mode
* - Init the serial ports (so setup can be debugged)
* - Set up the kill and suicide pins
* - Prepare (disable) board JTAG and Debug ports
* - Init serial for a connected MKS TFT with WiFi
* - Install Marlin custom Exception Handlers, if set.
* - Init Marlin's HAL interfaces (for SPI, i2c, etc.)
* - Init some optional hardware and features:
* • MAX Thermocouple pins
* • Duet Smart Effector
* • Filament Runout Sensor
* • TMC220x Stepper Drivers (Serial)
* • PSU control
* • Power-loss Recovery
* • Stepper Driver Reset: DISABLE
* • TMC Stepper Drivers (SPI)
* • Run hal.init_board() for additional pins setup
* • ESP WiFi
* - Get the Reset Reason and report it
* - Print startup messages and diagnostics
* - Calibrate the HAL DELAY for precise timing
* - Init the buzzer, possibly a custom timer
* - Init more optional hardware:
* • Color LED illumination
* • NeoPixel illumination
* • Controller Fan
* • Creality DWIN LCD (show boot image)
* • Tare the Probe if possible
* - Mount the (most likely external) SD Card
* - Load settings from EEPROM (or use defaults)
* - Init the Ethernet Port
* - Init Touch Buttons (for emulated DOGLCD)
* - Adjust the (certainly wrong) current position by the home offset
* - Init the Planner::position (steps) based on current (native) position
* - Initialize more managers and peripherals:
* • Temperatures
* • Print Job Timer
* • Endstops and Endstop Interrupts
* • Stepper ISR - Kind of Important!
* • Servos
* • Servo-based Probe
* • Photograph Pin
* • Laser/Spindle tool Power / PWM
* • Coolant Control
* • Bed Probe
* • Stepper Driver Reset: ENABLE
* • Digipot I2C - Stepper driver current control
* • Stepper DAC - Stepper driver current control
* • Solenoid (probe, or for other use)
* • Home Pin
* • Custom User Buttons
* • Red/Blue Status LEDs
* • Case Light
* • Prusa MMU filament changer
* • Fan Multiplexer
* • Mixing Extruder
* • BLTouch Probe
* • I2C Position Encoders
* • Custom I2C Bus handlers
* • Enhanced tools or extruders:
* • Switching Extruder
* • Switching Nozzle
* • Parking Extruder
* • Magnetic Parking Extruder
* • Switching Toolhead
* • Electromagnetic Switching Toolhead
* • Watchdog Timer - Also Kind of Important!
* • Closed Loop Controller
* - Run Startup Commands, if defined
* - Tell host to close Host Prompts
* - Test Trinamic driver connections
* - Init Prusa MMU2 filament changer
* - Init and test BL24Cxx EEPROM
* - Init Creality DWIN encoder, show faux progress bar
* - Reset Status Message / Show Service Messages
* - Init MAX7219 LED Matrix
* - Init Direct Stepping (Klipper-style motion control)
* - Init TFT LVGL UI (with 3D Graphics)
* - Apply Password Lock - Hold for Authentication
* - Open Touch Screen Calibration screen, if not calibrated
* - Set Marlin to RUNNING State
*/
void setup() {
#ifdef FASTIO_INIT
FASTIO_INIT();
#endif
#ifdef BOARD_PREINIT
BOARD_PREINIT(); // Low-level init (before serial init)
#endif
tmc_standby_setup(); // TMC Low Power Standby pins must be set early or they're not usable
// Check startup - does nothing if bootloader sets MCUSR to 0
const byte mcu = hal.get_reset_source();
hal.clear_reset_source();
#if ENABLED(MARLIN_DEV_MODE)
auto log_current_ms = [&](PGM_P const msg) {
SERIAL_ECHO_START();
TSS('[', millis(), F("] ")).echo();
SERIAL_ECHOLNPGM_P(msg);
};
#define SETUP_LOG(M) log_current_ms(PSTR(M))
#else
#define SETUP_LOG(...) NOOP
#endif
#define SETUP_RUN(C) do{ SETUP_LOG(STRINGIFY(C)); C; }while(0)
MYSERIAL1.begin(BAUDRATE);
millis_t serial_connect_timeout = millis() + 1000UL;
while (!MYSERIAL1.connected() && PENDING(millis(), serial_connect_timeout)) { /*nada*/ }
#if HAS_MULTI_SERIAL && !HAS_ETHERNET
#ifndef BAUDRATE_2
#define BAUDRATE_2 BAUDRATE
#endif
MYSERIAL2.begin(BAUDRATE_2);
serial_connect_timeout = millis() + 1000UL;
while (!MYSERIAL2.connected() && PENDING(millis(), serial_connect_timeout)) { /*nada*/ }
#ifdef SERIAL_PORT_3
#ifndef BAUDRATE_3
#define BAUDRATE_3 BAUDRATE
#endif
MYSERIAL3.begin(BAUDRATE_3);
serial_connect_timeout = millis() + 1000UL;
while (!MYSERIAL3.connected() && PENDING(millis(), serial_connect_timeout)) { /*nada*/ }
#endif
#endif
SERIAL_ECHOLNPGM("start");
// Set up these pins early to prevent suicide
#if HAS_KILL
SETUP_LOG("KILL_PIN");
#if KILL_PIN_STATE
SET_INPUT_PULLDOWN(KILL_PIN);
#else
SET_INPUT_PULLUP(KILL_PIN);
#endif
#endif
#if ENABLED(FREEZE_FEATURE)
SETUP_LOG("FREEZE_PIN");
#if FREEZE_STATE
SET_INPUT_PULLDOWN(FREEZE_PIN);
#else
SET_INPUT_PULLUP(FREEZE_PIN);
#endif
#endif
#if HAS_SUICIDE
SETUP_LOG("SUICIDE_PIN");
OUT_WRITE(SUICIDE_PIN, !SUICIDE_PIN_STATE);
#endif
#ifdef JTAGSWD_RESET
SETUP_LOG("JTAGSWD_RESET");
JTAGSWD_RESET();
#endif
// Disable any hardware debug to free up pins for IO
#if ENABLED(DISABLE_DEBUG) && defined(JTAGSWD_DISABLE)
delay(10);
SETUP_LOG("JTAGSWD_DISABLE");
JTAGSWD_DISABLE();
#elif ENABLED(DISABLE_JTAG) && defined(JTAG_DISABLE)
delay(10);
SETUP_LOG("JTAG_DISABLE");
JTAG_DISABLE();
#endif
TERN_(DYNAMIC_VECTORTABLE, hook_cpu_exceptions()); // If supported, install Marlin exception handlers at runtime
SETUP_RUN(hal.init());
// Init and disable SPI thermocouples; this is still needed
#if TEMP_SENSOR_IS_MAX_TC(0) || (TEMP_SENSOR_IS_MAX_TC(REDUNDANT) && REDUNDANT_TEMP_MATCH(SOURCE, E0))
OUT_WRITE(TEMP_0_CS_PIN, HIGH); // Disable
#endif
#if TEMP_SENSOR_IS_MAX_TC(1) || (TEMP_SENSOR_IS_MAX_TC(REDUNDANT) && REDUNDANT_TEMP_MATCH(SOURCE, E1))
OUT_WRITE(TEMP_1_CS_PIN, HIGH);
#endif
#if TEMP_SENSOR_IS_MAX_TC(2) || (TEMP_SENSOR_IS_MAX_TC(REDUNDANT) && REDUNDANT_TEMP_MATCH(SOURCE, E2))
OUT_WRITE(TEMP_2_CS_PIN, HIGH);
#endif
#if TEMP_SENSOR_IS_MAX_TC(BED)
OUT_WRITE(TEMP_BED_CS_PIN, HIGH);
#endif
#if ENABLED(DUET_SMART_EFFECTOR) && PIN_EXISTS(SMART_EFFECTOR_MOD)
OUT_WRITE(SMART_EFFECTOR_MOD_PIN, LOW); // Put Smart Effector into NORMAL mode
#endif
#if HAS_FILAMENT_SENSOR
SETUP_RUN(runout.setup());
#endif
#if HAS_TMC220x
SETUP_RUN(tmc_serial_begin());
#endif
#if HAS_TMC_SPI
#if DISABLED(TMC_USE_SW_SPI)
SETUP_RUN(SPI.begin());
#endif
SETUP_RUN(tmc_init_cs_pins());
#endif
#if ENABLED(PSU_CONTROL)
SETUP_LOG("PSU_CONTROL");
powerManager.init();
#endif
#if ENABLED(POWER_LOSS_RECOVERY)
SETUP_RUN(recovery.setup());
#endif
#if HAS_STEPPER_RESET
SETUP_RUN(disableStepperDrivers());
#endif
SETUP_RUN(hal.init_board());
#if ENABLED(WIFISUPPORT)
SETUP_RUN(esp_wifi_init());
#endif
// Report Reset Reason
if (mcu & RST_POWER_ON) SERIAL_ECHOLNPGM(STR_POWERUP);
if (mcu & RST_EXTERNAL) SERIAL_ECHOLNPGM(STR_EXTERNAL_RESET);
if (mcu & RST_BROWN_OUT) SERIAL_ECHOLNPGM(STR_BROWNOUT_RESET);
if (mcu & RST_WATCHDOG) SERIAL_ECHOLNPGM(STR_WATCHDOG_RESET);
if (mcu & RST_SOFTWARE) SERIAL_ECHOLNPGM(STR_SOFTWARE_RESET);
// Identify myself as Marlin x.x.x
SERIAL_ECHOLNPGM("Marlin " SHORT_BUILD_VERSION);
#if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
SERIAL_ECHO_MSG(
" Last Updated: " STRING_DISTRIBUTION_DATE
" | Author: " STRING_CONFIG_H_AUTHOR
);
#endif
SERIAL_ECHO_MSG(" Compiled: " __DATE__);
SERIAL_ECHO_MSG(STR_FREE_MEMORY, hal.freeMemory(), STR_PLANNER_BUFFER_BYTES, sizeof(block_t) * (BLOCK_BUFFER_SIZE));
// Some HAL need precise delay adjustment
calibrate_delay_loop();
// Init buzzer pin(s)
#if HAS_BEEPER
SETUP_RUN(buzzer.init());
#endif
// Set up LEDs early
#if HAS_COLOR_LEDS
SETUP_RUN(leds.setup());
#endif
#if ENABLED(NEOPIXEL2_SEPARATE)
SETUP_RUN(leds2.setup());
#endif
#if ENABLED(USE_CONTROLLER_FAN) // Set up fan controller to initialize also the default configurations.
SETUP_RUN(controllerFan.setup());
#endif
TERN_(HAS_FANCHECK, fan_check.init());
// UI must be initialized before EEPROM
// (because EEPROM code calls the UI).
SETUP_RUN(ui.init());
#if PIN_EXISTS(SAFE_POWER)
#if HAS_DRIVER_SAFE_POWER_PROTECT
SETUP_RUN(stepper_driver_backward_check());
#else
SETUP_LOG("SAFE_POWER");
OUT_WRITE(SAFE_POWER_PIN, HIGH);
#endif
#endif
#if ALL(HAS_MEDIA, SDCARD_EEPROM_EMULATION)
SETUP_RUN(card.mount()); // Mount media with settings before first_load
#endif
SETUP_RUN(settings.first_load()); // Load data from EEPROM if available (or use defaults)
// This also updates variables in the planner, elsewhere
#if ALL(HAS_WIRED_LCD, SHOW_BOOTSCREEN)
SETUP_RUN(ui.show_bootscreen());
const millis_t bootscreen_ms = millis();
#endif
#if ENABLED(PROBE_TARE)
SETUP_RUN(probe.tare_init());
#endif
#if HAS_ETHERNET
SETUP_RUN(ethernet.init());
#endif
#if HAS_TOUCH_BUTTONS
SETUP_RUN(touchBt.init());
#endif
TERN_(HAS_HOME_OFFSET, current_position += home_offset); // Init current position based on home_offset
sync_plan_position(); // Vital to init stepper/planner equivalent for current_position
SETUP_RUN(thermalManager.init()); // Initialize temperature loop
SETUP_RUN(print_job_timer.init()); // Initial setup of print job timer
SETUP_RUN(endstops.init()); // Init endstops and pullups
#if ENABLED(DELTA) && !HAS_SOFTWARE_ENDSTOPS
SETUP_RUN(refresh_delta_clip_start_height()); // Init safe delta height without soft endstops
#endif
SETUP_RUN(stepper.init()); // Init stepper. This enables interrupts!
#if HAS_SERVOS
SETUP_RUN(servo_init());
#endif
#if HAS_Z_SERVO_PROBE
SETUP_RUN(probe.servo_probe_init());
#endif
#if HAS_PHOTOGRAPH
OUT_WRITE(PHOTOGRAPH_PIN, LOW);
#endif
#if HAS_CUTTER
SETUP_RUN(cutter.init());
#endif
#if ENABLED(COOLANT_MIST)
OUT_WRITE(COOLANT_MIST_PIN, COOLANT_MIST_INVERT); // Init Mist Coolant OFF
#endif
#if ENABLED(COOLANT_FLOOD)
OUT_WRITE(COOLANT_FLOOD_PIN, COOLANT_FLOOD_INVERT); // Init Flood Coolant OFF
#endif
#if HAS_BED_PROBE
#if PIN_EXISTS(PROBE_ENABLE)
OUT_WRITE(PROBE_ENABLE_PIN, LOW); // Disable
#endif
SETUP_RUN(endstops.enable_z_probe(false));
#endif
#if HAS_STEPPER_RESET
SETUP_RUN(enableStepperDrivers());
#endif
#if HAS_MOTOR_CURRENT_I2C
SETUP_RUN(digipot_i2c.init());
#endif
#if HAS_MOTOR_CURRENT_DAC
SETUP_RUN(stepper_dac.init());
#endif
#if ANY(Z_PROBE_SLED, SOLENOID_PROBE) && HAS_SOLENOID_1
OUT_WRITE(SOL1_PIN, LOW); // OFF
#endif
#if HAS_HOME
SET_INPUT_PULLUP(HOME_PIN);
#endif
#if ENABLED(CUSTOM_USER_BUTTONS)
#define INIT_CUSTOM_USER_BUTTON_PIN(N) do{ SET_INPUT(BUTTON##N##_PIN); WRITE(BUTTON##N##_PIN, !BUTTON##N##_HIT_STATE); }while(0)
#if HAS_CUSTOM_USER_BUTTON(1)
INIT_CUSTOM_USER_BUTTON_PIN(1);
#endif
#if HAS_CUSTOM_USER_BUTTON(2)
INIT_CUSTOM_USER_BUTTON_PIN(2);
#endif
#if HAS_CUSTOM_USER_BUTTON(3)
INIT_CUSTOM_USER_BUTTON_PIN(3);
#endif
#if HAS_CUSTOM_USER_BUTTON(4)
INIT_CUSTOM_USER_BUTTON_PIN(4);
#endif
#if HAS_CUSTOM_USER_BUTTON(5)
INIT_CUSTOM_USER_BUTTON_PIN(5);
#endif
#if HAS_CUSTOM_USER_BUTTON(6)
INIT_CUSTOM_USER_BUTTON_PIN(6);
#endif
#if HAS_CUSTOM_USER_BUTTON(7)
INIT_CUSTOM_USER_BUTTON_PIN(7);
#endif
#if HAS_CUSTOM_USER_BUTTON(8)
INIT_CUSTOM_USER_BUTTON_PIN(8);
#endif
#if HAS_CUSTOM_USER_BUTTON(9)
INIT_CUSTOM_USER_BUTTON_PIN(9);
#endif
#if HAS_CUSTOM_USER_BUTTON(10)
INIT_CUSTOM_USER_BUTTON_PIN(10);
#endif
#if HAS_CUSTOM_USER_BUTTON(11)
INIT_CUSTOM_USER_BUTTON_PIN(11);
#endif
#if HAS_CUSTOM_USER_BUTTON(12)
INIT_CUSTOM_USER_BUTTON_PIN(12);
#endif
#if HAS_CUSTOM_USER_BUTTON(13)
INIT_CUSTOM_USER_BUTTON_PIN(13);
#endif
#if HAS_CUSTOM_USER_BUTTON(14)
INIT_CUSTOM_USER_BUTTON_PIN(14);
#endif
#if HAS_CUSTOM_USER_BUTTON(15)
INIT_CUSTOM_USER_BUTTON_PIN(15);
#endif
#if HAS_CUSTOM_USER_BUTTON(16)
INIT_CUSTOM_USER_BUTTON_PIN(16);
#endif
#if HAS_CUSTOM_USER_BUTTON(17)
INIT_CUSTOM_USER_BUTTON_PIN(17);
#endif
#if HAS_CUSTOM_USER_BUTTON(18)
INIT_CUSTOM_USER_BUTTON_PIN(18);
#endif
#if HAS_CUSTOM_USER_BUTTON(19)
INIT_CUSTOM_USER_BUTTON_PIN(19);
#endif
#if HAS_CUSTOM_USER_BUTTON(20)
INIT_CUSTOM_USER_BUTTON_PIN(20);
#endif
#if HAS_CUSTOM_USER_BUTTON(21)
INIT_CUSTOM_USER_BUTTON_PIN(21);
#endif
#if HAS_CUSTOM_USER_BUTTON(22)
INIT_CUSTOM_USER_BUTTON_PIN(22);
#endif
#if HAS_CUSTOM_USER_BUTTON(23)
INIT_CUSTOM_USER_BUTTON_PIN(23);
#endif
#if HAS_CUSTOM_USER_BUTTON(24)
INIT_CUSTOM_USER_BUTTON_PIN(24);
#endif
#if HAS_CUSTOM_USER_BUTTON(25)
INIT_CUSTOM_USER_BUTTON_PIN(25);
#endif
#endif
#if PIN_EXISTS(STAT_LED_RED)
OUT_WRITE(STAT_LED_RED_PIN, LOW); // OFF
#endif
#if PIN_EXISTS(STAT_LED_BLUE)
OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // OFF
#endif
#if ENABLED(CASE_LIGHT_ENABLE)
SETUP_RUN(caselight.init());
#endif
#if HAS_PRUSA_MMU1
SETUP_RUN(mmu_init());
#endif
#if HAS_FANMUX
SETUP_RUN(fanmux_init());
#endif
#if ENABLED(MIXING_EXTRUDER)
SETUP_RUN(mixer.init());
#endif
#if ENABLED(BLTOUCH)
SETUP_RUN(bltouch.init(/*set_voltage=*/true));
#endif
#if ENABLED(MAGLEV4)
OUT_WRITE(MAGLEV_TRIGGER_PIN, LOW);
#endif
#if ENABLED(I2C_POSITION_ENCODERS)
SETUP_RUN(I2CPEM.init());
#endif
#if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
SETUP_LOG("i2c...");
i2c.onReceive(i2c_on_receive);
i2c.onRequest(i2c_on_request);
#endif
#if DO_SWITCH_EXTRUDER
SETUP_RUN(move_extruder_servo(0)); // Initialize extruder servo
#endif
#if ENABLED(SWITCHING_NOZZLE)
SETUP_LOG("SWITCHING_NOZZLE");
// Initialize nozzle servo(s)
#if SWITCHING_NOZZLE_TWO_SERVOS
lower_nozzle(0);
raise_nozzle(1);
#else
move_nozzle_servo(0);
#endif
#endif
#if ENABLED(PARKING_EXTRUDER)
SETUP_RUN(pe_solenoid_init());
#elif ENABLED(MAGNETIC_PARKING_EXTRUDER)
SETUP_RUN(mpe_settings_init());
#elif ENABLED(SWITCHING_TOOLHEAD)
SETUP_RUN(swt_init());
#elif ENABLED(ELECTROMAGNETIC_SWITCHING_TOOLHEAD)
SETUP_RUN(est_init());
#endif
#if ENABLED(USE_WATCHDOG)
SETUP_RUN(hal.watchdog_init()); // Reinit watchdog after hal.get_reset_source call
#endif
#if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER)
SETUP_RUN(closedloop.init());
#endif
#ifdef STARTUP_COMMANDS
SETUP_LOG("STARTUP_COMMANDS");
queue.inject(F(STARTUP_COMMANDS));
#endif
#if ENABLED(HOST_PROMPT_SUPPORT)
SETUP_RUN(hostui.prompt_end());
#endif
#if HAS_DRIVER_SAFE_POWER_PROTECT
SETUP_RUN(stepper_driver_backward_report());
#endif
#if HAS_PRUSA_MMU2
SETUP_RUN(mmu2.init());
#endif
#if ENABLED(IIC_BL24CXX_EEPROM)
BL24CXX::init();
const uint8_t err = BL24CXX::check();
SERIAL_ECHO_TERNARY(err, "BL24CXX Check ", "failed", "succeeded", "!\n");
#endif
#if ENABLED(DWIN_CREALITY_LCD)
SETUP_RUN(dwinInitScreen());
#endif
#if HAS_SERVICE_INTERVALS && DISABLED(DWIN_CREALITY_LCD)
SETUP_RUN(ui.reset_status(true)); // Show service messages or keep current status
#endif
#if ENABLED(MAX7219_DEBUG)
SETUP_RUN(max7219.init());
#endif
#if ENABLED(DIRECT_STEPPING)
SETUP_RUN(page_manager.init());
#endif
#if HAS_TFT_LVGL_UI
#if HAS_MEDIA
if (!card.isMounted()) SETUP_RUN(card.mount()); // Mount SD to load graphics and fonts
#endif
SETUP_RUN(tft_lvgl_init());
#endif
#if ALL(HAS_WIRED_LCD, SHOW_BOOTSCREEN)
const millis_t elapsed = millis() - bootscreen_ms;
#if ENABLED(MARLIN_DEV_MODE)
SERIAL_ECHOLNPGM("elapsed=", elapsed);
#endif
SETUP_RUN(ui.bootscreen_completion(elapsed));
#endif
#if ENABLED(PASSWORD_ON_STARTUP)
SETUP_RUN(password.lock_machine()); // Will not proceed until correct password provided
#endif
#if ALL(HAS_MARLINUI_MENU, TOUCH_SCREEN_CALIBRATION) && ANY(TFT_CLASSIC_UI, TFT_COLOR_UI)
SETUP_RUN(ui.check_touch_calibration());
#endif
#if ENABLED(EASYTHREED_UI)
SETUP_RUN(easythreed_ui.init());
#endif
#if HAS_TRINAMIC_CONFIG && DISABLED(PSU_DEFAULT_OFF)
SETUP_RUN(test_tmc_connection());
#endif
#if ENABLED(BD_SENSOR)
SETUP_RUN(bdl.init(I2C_BD_SDA_PIN, I2C_BD_SCL_PIN, I2C_BD_DELAY));
#endif
#if ENABLED(FT_MOTION)
SETUP_RUN(ftMotion.init());
#endif
marlin_state = MF_RUNNING;
#ifdef STARTUP_TUNE
// Play a short startup tune before continuing.
constexpr uint16_t tune[] = STARTUP_TUNE;
for (uint8_t i = 0; i < COUNT(tune) - 1; i += 2) BUZZ(tune[i + 1], tune[i]);
#endif
SETUP_LOG("setup() completed.");
TERN_(MARLIN_TEST_BUILD, runStartupTests());
}
/**
* The main Marlin program loop
*
* - Call idle() to handle all tasks between G-code commands
* Note that no G-codes from the queue can be executed during idle()
* but many G-codes can be called directly anytime like macros.
* - Check whether SD card auto-start is needed now.
* - Check whether SD print finishing is needed now.
* - Run one G-code command from the immediate or main command queue
* and open up one space. Commands in the main queue may come from sd
* card, host, or by direct injection. The queue will continue to fill
* as long as idle() or manage_inactivity() are being called.
*/
void loop() {
do {
idle();
#if HAS_MEDIA
if (card.flag.abort_sd_printing) abortSDPrinting();
if (marlin_state == MF_SD_COMPLETE) finishSDPrinting();
#endif
queue.advance();
#if ANY(POWER_OFF_TIMER, POWER_OFF_WAIT_FOR_COOLDOWN)
powerManager.checkAutoPowerOff();
#endif
endstops.event_handler();
TERN_(HAS_TFT_LVGL_UI, printer_state_polling());
TERN_(MARLIN_TEST_BUILD, runPeriodicTests());
} while (ENABLED(__AVR__)); // Loop forever on slower (AVR) boards
}
|
2301_81045437/Marlin
|
Marlin/src/MarlinCore.cpp
|
C++
|
agpl-3.0
| 48,846
|
/**
* 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 <math.h>
#include <stdio.h>
#include <stdlib.h>
void stop();
// Pass true to keep steppers from timing out
void idle(const bool no_stepper_sleep=false);
inline void idle_no_sleep() { idle(true); }
#if ENABLED(G38_PROBE_TARGET)
extern uint8_t G38_move; // Flag to tell the ISR that G38 is in progress, and the type
extern bool G38_did_trigger; // Flag from the ISR to indicate the endstop changed
#endif
void kill(FSTR_P const lcd_error=nullptr, FSTR_P const lcd_component=nullptr, const bool steppers_off=false);
void minkill(const bool steppers_off=false);
// Global State of the firmware
enum MarlinState : uint8_t {
MF_INITIALIZING = 0,
MF_STOPPED,
MF_KILLED,
MF_RUNNING,
MF_SD_COMPLETE,
MF_PAUSED,
MF_WAITING,
};
extern MarlinState marlin_state;
inline bool IsRunning() { return marlin_state >= MF_RUNNING; }
inline bool IsStopped() { return marlin_state == MF_STOPPED; }
bool printingIsActive();
bool printJobOngoing();
bool printingIsPaused();
void startOrResumeJob();
bool printer_busy();
extern bool wait_for_heatup;
#if HAS_RESUME_CONTINUE
extern bool wait_for_user;
void wait_for_user_response(millis_t ms=0, const bool no_sleep=false);
#endif
bool pin_is_protected(const pin_t pin);
#if HAS_SUICIDE
inline void suicide() { OUT_WRITE(SUICIDE_PIN, SUICIDE_PIN_STATE); }
#endif
#if HAS_KILL
#ifndef KILL_PIN_STATE
#define KILL_PIN_STATE LOW
#endif
inline bool kill_state() { return READ(KILL_PIN) == KILL_PIN_STATE; }
#endif
extern const char M112_KILL_STR[];
|
2301_81045437/Marlin
|
Marlin/src/MarlinCore.h
|
C
|
agpl-3.0
| 2,446
|
/**
* 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
/**
* Whenever changes are made to this file, please update Marlin/Makefile
* and _data/boards.yml in the MarlinDocumentation repo.
*/
#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)
#define BOARD_RAMPS_BTT_16_PLUS_EFB 1035 // RAMPS 1.6+ (Power outputs: Hotend, Fan, Bed)
#define BOARD_RAMPS_BTT_16_PLUS_EEB 1036 // RAMPS 1.6+ (Power outputs: Hotend0, Hotend1, Bed)
#define BOARD_RAMPS_BTT_16_PLUS_EFF 1037 // RAMPS 1.6+ (Power outputs: Hotend, Fan0, Fan1)
#define BOARD_RAMPS_BTT_16_PLUS_EEF 1038 // RAMPS 1.6+ (Power outputs: Hotend0, Hotend1, Fan)
#define BOARD_RAMPS_BTT_16_PLUS_SF 1039 // RAMPS 1.6+ (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_TENLOG_MB1_V23 1157 // Tenlog D3, D5, D6 IDEX Printer
#define BOARD_RAMPS_S_12_EEFB 1158 // Ramps S 1.2 by Sakul.cz (Power outputs: Hotend0, Hotend1, Fan, Bed)
#define BOARD_RAMPS_S_12_EEEB 1159 // Ramps S 1.2 by Sakul.cz (Power outputs: Hotend0, Hotend1, Hotend2, Bed)
#define BOARD_RAMPS_S_12_EFFB 1160 // Ramps S 1.2 by Sakul.cz (Power outputs: Hotend, Fan0, Fan1, Bed)
#define BOARD_LONGER3D_LK1_PRO 1161 // Longer LK1 PRO / Alfawise U20 Pro (PRO version)
#define BOARD_LONGER3D_LKx_PRO 1162 // Longer LKx PRO / Alfawise Uxx Pro (PRO version)
#define BOARD_ZRIB_V53 1163 // Zonestar zrib V5.3 (Chinese RAMPS replica)
#define BOARD_PXMALION_CORE_I3 1164 // Pxmalion Core I3
#define BOARD_PANOWIN_CUTLASS 1165 // Panowin Cutlass (as found in the Panowin F1)
#define BOARD_KODAMA_BARDO 1166 // Kodama Bardo V1.x (as found in the Kodama Trinus)
#define BOARD_DAGOMA_D6 1167 // Dagoma D6 (as found in the Dagoma DiscoUltimate V2 TMC)
//
// 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.)
#define BOARD_GT2560_V41B 1331 // Geeetech GT2560 V4.1B for A10(M/T/D)
//
// 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_CREALITY_ENDER2 1506 // Melzi Creality3D (for Ender-2)
#define BOARD_MELZI_MALYAN 1507 // Melzi Malyan M150
#define BOARD_MELZI_TRONXY 1508 // Tronxy X5S
#define BOARD_STB_11 1509 // STB V1.1
#define BOARD_AZTEEG_X1 1510 // Azteeg X1
#define BOARD_ANET_10 1511 // Anet 1.0 (Melzi clone)
#define BOARD_ZMIB_V2 1512 // 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-M0+
//
#define BOARD_BTT_EBB42_V1_1 4000 // BigTreeTech EBB42 V1.1 (STM32G0B1CB)
#define BOARD_BTT_SKR_MINI_E3_V3_0 4001 // BigTreeTech SKR Mini E3 V3.0 (STM32G0B0RE / STM32G0B1RE)
#define BOARD_BTT_MANTA_E3_EZ_V1_0 4002 // BigTreeTech Manta E3 EZ V1.0 (STM32G0B1RE)
#define BOARD_BTT_MANTA_M4P_V2_1 4003 // BigTreeTech Manta M4P V2.1 (STM32G0B0RE)
#define BOARD_BTT_MANTA_M5P_V1_0 4004 // BigTreeTech Manta M5P V1.0 (STM32G0B1RE)
#define BOARD_BTT_MANTA_M8P_V1_0 4005 // BigTreeTech Manta M8P V1.0 (STM32G0B1VE)
#define BOARD_BTT_MANTA_M8P_V1_1 4006 // BigTreeTech Manta M8P V1.1 (STM32G0B1VE)
//
// STM32 ARM Cortex-M3
//
#define BOARD_MALYAN_M200_V2 5000 // STM32F070CB controller
#define BOARD_MALYAN_M300 5001 // STM32F070-based delta
#define BOARD_STM32F103RE 5002 // STM32F103RE Libmaple-based STM32F1 controller
#define BOARD_MALYAN_M200 5003 // STM32C8 Libmaple-based STM32F1 controller
#define BOARD_STM3R_MINI 5004 // STM32F103RE Libmaple-based STM32F1 controller
#define BOARD_GTM32_PRO_VB 5005 // STM32F103VE controller
#define BOARD_GTM32_MINI 5006 // STM32F103VE controller
#define BOARD_GTM32_MINI_A30 5007 // STM32F103VE controller
#define BOARD_GTM32_REV_B 5008 // STM32F103VE controller
#define BOARD_MORPHEUS 5009 // STM32F103C8 / STM32F103CB Libmaple-based STM32F1 controller
#define BOARD_CHITU3D 5010 // Chitu3D (STM32F103RE)
#define BOARD_MKS_ROBIN 5011 // MKS Robin (STM32F103ZE)
#define BOARD_MKS_ROBIN_MINI 5012 // MKS Robin Mini (STM32F103VE)
#define BOARD_MKS_ROBIN_NANO 5013 // MKS Robin Nano (STM32F103VE)
#define BOARD_MKS_ROBIN_NANO_V2 5014 // MKS Robin Nano V2 (STM32F103VE)
#define BOARD_MKS_ROBIN_LITE 5015 // MKS Robin Lite/Lite2 (STM32F103RC)
#define BOARD_MKS_ROBIN_LITE3 5016 // MKS Robin Lite3 (STM32F103RC)
#define BOARD_MKS_ROBIN_PRO 5017 // MKS Robin Pro (STM32F103ZE)
#define BOARD_MKS_ROBIN_E3 5018 // MKS Robin E3 (STM32F103RC)
#define BOARD_MKS_ROBIN_E3_V1_1 5019 // MKS Robin E3 V1.1 (STM32F103RC)
#define BOARD_MKS_ROBIN_E3D 5020 // MKS Robin E3D (STM32F103RC)
#define BOARD_MKS_ROBIN_E3D_V1_1 5021 // MKS Robin E3D V1.1 (STM32F103RC)
#define BOARD_MKS_ROBIN_E3P 5022 // MKS Robin E3P (STM32F103VE)
#define BOARD_BTT_SKR_MINI_V1_1 5023 // BigTreeTech SKR Mini v1.1 (STM32F103RC)
#define BOARD_BTT_SKR_MINI_E3_V1_0 5024 // BigTreeTech SKR Mini E3 (STM32F103RC)
#define BOARD_BTT_SKR_MINI_E3_V1_2 5025 // BigTreeTech SKR Mini E3 V1.2 (STM32F103RC)
#define BOARD_BTT_SKR_MINI_E3_V2_0 5026 // BigTreeTech SKR Mini E3 V2.0 (STM32F103RC / STM32F103RE)
#define BOARD_BTT_SKR_MINI_MZ_V1_0 5027 // BigTreeTech SKR Mini MZ V1.0 (STM32F103RC)
#define BOARD_BTT_SKR_E3_DIP 5028 // BigTreeTech SKR E3 DIP V1.0 (STM32F103RC / STM32F103RE)
#define BOARD_BTT_SKR_CR6 5029 // BigTreeTech SKR CR6 v1.0 (STM32F103RE)
#define BOARD_JGAURORA_A5S_A1 5030 // JGAurora A5S A1 (STM32F103ZE)
#define BOARD_FYSETC_AIO_II 5031 // FYSETC AIO_II (STM32F103RC)
#define BOARD_FYSETC_CHEETAH 5032 // FYSETC Cheetah (STM32F103RC)
#define BOARD_FYSETC_CHEETAH_V12 5033 // FYSETC Cheetah V1.2 (STM32F103RC)
#define BOARD_LONGER3D_LK 5034 // Longer3D LK1/2 - Alfawise U20/U20+/U30 (STM32F103VE)
#define BOARD_CCROBOT_MEEB_3DP 5035 // ccrobot-online.com MEEB_3DP (STM32F103RC)
#define BOARD_CHITU3D_V5 5036 // Chitu3D TronXY X5SA V5 Board (STM32F103ZE)
#define BOARD_CHITU3D_V6 5037 // Chitu3D TronXY X5SA V6 Board (STM32F103ZE)
#define BOARD_CHITU3D_V9 5038 // Chitu3D TronXY X5SA V9 Board (STM32F103ZE)
#define BOARD_CREALITY_V4 5039 // Creality v4.x (STM32F103RC / STM32F103RE)
#define BOARD_CREALITY_V422 5040 // Creality v4.2.2 (STM32F103RC / STM32F103RE)
#define BOARD_CREALITY_V423 5041 // Creality v4.2.3 (STM32F103RC / STM32F103RE)
#define BOARD_CREALITY_V425 5042 // Creality v4.2.5 (STM32F103RC / STM32F103RE)
#define BOARD_CREALITY_V427 5043 // Creality v4.2.7 (STM32F103RC / STM32F103RE)
#define BOARD_CREALITY_V4210 5044 // Creality v4.2.10 (STM32F103RC / STM32F103RE) as found in the CR-30
#define BOARD_CREALITY_V431 5045 // Creality v4.3.1 (STM32F103RC / STM32F103RE)
#define BOARD_CREALITY_V431_A 5046 // Creality v4.3.1a (STM32F103RC / STM32F103RE)
#define BOARD_CREALITY_V431_B 5047 // Creality v4.3.1b (STM32F103RC / STM32F103RE)
#define BOARD_CREALITY_V431_C 5048 // Creality v4.3.1c (STM32F103RC / STM32F103RE)
#define BOARD_CREALITY_V431_D 5049 // Creality v4.3.1d (STM32F103RC / STM32F103RE)
#define BOARD_CREALITY_V452 5050 // Creality v4.5.2 (STM32F103RC / STM32F103RE)
#define BOARD_CREALITY_V453 5051 // Creality v4.5.3 (STM32F103RC / STM32F103RE)
#define BOARD_CREALITY_V521 5052 // Creality v5.2.1 (STM32F103VE) as found in the SV04
#define BOARD_CREALITY_V24S1 5053 // Creality v2.4.S1 (STM32F103RC / STM32F103RE) CR-FDM-v2.4.S1_v101 as found in the Ender-7
#define BOARD_CREALITY_V24S1_301 5054 // Creality v2.4.S1_301 (STM32F103RC / STM32F103RE) CR-FDM-v24S1_301 as found in the Ender-3 S1
#define BOARD_CREALITY_V25S1 5055 // Creality v2.5.S1 (STM32F103RE) CR-FDM-v2.5.S1_100 as found in the CR-10 Smart Pro
#define BOARD_TRIGORILLA_PRO 5056 // Trigorilla Pro (STM32F103ZE)
#define BOARD_FLY_MINI 5057 // FLYmaker FLY MINI (STM32F103RC)
#define BOARD_FLSUN_HISPEED 5058 // FLSUN HiSpeedV1 (STM32F103VE)
#define BOARD_BEAST 5059 // STM32F103RE Libmaple-based controller
#define BOARD_MINGDA_MPX_ARM_MINI 5060 // STM32F103ZE Mingda MD-16
#define BOARD_GTM32_PRO_VD 5061 // STM32F103VE controller
#define BOARD_ZONESTAR_ZM3E2 5062 // Zonestar ZM3E2 (STM32F103RC)
#define BOARD_ZONESTAR_ZM3E4 5063 // Zonestar ZM3E4 V1 (STM32F103VC)
#define BOARD_ZONESTAR_ZM3E4V2 5064 // Zonestar ZM3E4 V2 (STM32F103VC)
#define BOARD_ERYONE_ERY32_MINI 5065 // Eryone Ery32 mini (STM32F103VE)
#define BOARD_PANDA_PI_V29 5066 // Panda Pi V2.9 - Standalone (STM32F103RC)
#define BOARD_SOVOL_V131 5067 // Sovol V1.3.1 (GD32F103RE)
#define BOARD_TRIGORILLA_V006 5068 // Trigorilla V0.0.6 (GD32F103RE)
#define BOARD_KEDI_CONTROLLER_V1_2 5069 // EDUTRONICS Kedi Controller V1.2 (STM32F103RC)
#define BOARD_MD_D301 5070 // Mingda D2 DZ301 V1.0 (STM32F103ZE)
#define BOARD_VOXELAB_AQUILA 5071 // Voxelab Aquila V1.0.0/V1.0.1 (GD32F103RC / N32G455RE / STM32F103RE)
#define BOARD_SPRINGER_CONTROLLER 5072 // ORCA 3D SPRINGER Modular Controller (STM32F103VC)
//
// ARM Cortex-M4F
//
#define BOARD_TEENSY31_32 5100 // Teensy3.1 and Teensy3.2
#define BOARD_TEENSY35_36 5101 // Teensy3.5 and Teensy3.6
//
// STM32 ARM Cortex-M4F
//
#define BOARD_ARMED 5200 // Arm'ed STM32F4-based controller
#define BOARD_RUMBA32_V1_0 5201 // RUMBA32 STM32F446VE based controller from Aus3D
#define BOARD_RUMBA32_V1_1 5202 // RUMBA32 STM32F446VE based controller from Aus3D
#define BOARD_RUMBA32_MKS 5203 // RUMBA32 STM32F446VE based controller from Makerbase
#define BOARD_RUMBA32_BTT 5204 // RUMBA32 STM32F446VE based controller from BIGTREETECH
#define BOARD_BLACK_STM32F407VE 5205 // BLACK_STM32F407VE
#define BOARD_BLACK_STM32F407ZE 5206 // BLACK_STM32F407ZE
#define BOARD_BTT_SKR_MINI_E3_V3_0_1 5207 // BigTreeTech SKR Mini E3 V3.0.1 (STM32F401RC)
#define BOARD_BTT_SKR_PRO_V1_1 5208 // BigTreeTech SKR Pro v1.1 (STM32F407ZG)
#define BOARD_BTT_SKR_PRO_V1_2 5209 // BigTreeTech SKR Pro v1.2 (STM32F407ZG)
#define BOARD_BTT_BTT002_V1_0 5210 // BigTreeTech BTT002 v1.0 (STM32F407VG)
#define BOARD_BTT_E3_RRF 5211 // BigTreeTech E3 RRF (STM32F407VG)
#define BOARD_BTT_SKR_V2_0_REV_A 5212 // BigTreeTech SKR v2.0 Rev A (STM32F407VG)
#define BOARD_BTT_SKR_V2_0_REV_B 5213 // BigTreeTech SKR v2.0 Rev B (STM32F407VG/STM32F429VG)
#define BOARD_BTT_GTR_V1_0 5214 // BigTreeTech GTR v1.0 (STM32F407IGT)
#define BOARD_BTT_OCTOPUS_V1_0 5215 // BigTreeTech Octopus v1.0 (STM32F446ZE)
#define BOARD_BTT_OCTOPUS_V1_1 5216 // BigTreeTech Octopus v1.1 (STM32F446ZE)
#define BOARD_BTT_OCTOPUS_PRO_V1_0 5217 // BigTreeTech Octopus Pro v1.0 (STM32F446ZE / STM32F429ZG)
#define BOARD_LERDGE_K 5218 // Lerdge K (STM32F407ZG)
#define BOARD_LERDGE_S 5219 // Lerdge S (STM32F407VE)
#define BOARD_LERDGE_X 5220 // Lerdge X (STM32F407VE)
#define BOARD_FYSETC_S6 5221 // FYSETC S6 (STM32F446VE)
#define BOARD_FYSETC_S6_V2_0 5222 // FYSETC S6 v2.0 (STM32F446VE)
#define BOARD_FYSETC_SPIDER 5223 // FYSETC Spider (STM32F446VE)
#define BOARD_FLYF407ZG 5224 // FLYmaker FLYF407ZG (STM32F407ZG)
#define BOARD_MKS_ROBIN2 5225 // MKS Robin2 V1.0 (STM32F407ZE)
#define BOARD_MKS_ROBIN_PRO_V2 5226 // MKS Robin Pro V2 (STM32F407VE)
#define BOARD_MKS_ROBIN_NANO_V3 5227 // MKS Robin Nano V3 (STM32F407VG)
#define BOARD_MKS_ROBIN_NANO_V3_1 5228 // MKS Robin Nano V3.1 (STM32F407VE)
#define BOARD_MKS_MONSTER8_V1 5229 // MKS Monster8 V1 (STM32F407VE)
#define BOARD_MKS_MONSTER8_V2 5230 // MKS Monster8 V2 (STM32F407VE)
#define BOARD_ANET_ET4 5231 // ANET ET4 V1.x (STM32F407VG)
#define BOARD_ANET_ET4P 5232 // ANET ET4P V1.x (STM32F407VG)
#define BOARD_FYSETC_CHEETAH_V20 5233 // FYSETC Cheetah V2.0 (STM32F401RC)
#define BOARD_TH3D_EZBOARD_V2 5234 // TH3D EZBoard v2.0 (STM32F405RG)
#define BOARD_OPULO_LUMEN_REV3 5235 // Opulo Lumen PnP Controller REV3 (STM32F407VE / STM32F407VG)
#define BOARD_MKS_ROBIN_NANO_V1_3_F4 5236 // MKS Robin Nano V1.3 and MKS Robin Nano-S V1.3 (STM32F407VE)
#define BOARD_MKS_EAGLE 5237 // MKS Eagle (STM32F407VE)
#define BOARD_ARTILLERY_RUBY 5238 // Artillery Ruby (STM32F401RC)
#define BOARD_FYSETC_SPIDER_V2_2 5239 // FYSETC Spider V2.2 (STM32F446VE)
#define BOARD_CREALITY_V24S1_301F4 5240 // Creality v2.4.S1_301F4 (STM32F401RC) as found in the Ender-3 S1 F4
#define BOARD_CREALITY_CR4NTXXC10 5241 // Creality E3 Free-runs Silent Motherboard (STM32F401RET6)
#define BOARD_OPULO_LUMEN_REV4 5242 // Opulo Lumen PnP Controller REV4 (STM32F407VE / STM32F407VG)
#define BOARD_FYSETC_SPIDER_KING407 5243 // FYSETC Spider King407 (STM32F407ZG)
#define BOARD_MKS_SKIPR_V1 5244 // MKS SKIPR v1.0 all-in-one board (STM32F407VE)
#define BOARD_TRONXY_CXY_446_V10 5245 // TRONXY CXY-446-V10-220413/CXY-V6-191121 (STM32F446ZE)
#define BOARD_CREALITY_F401RE 5246 // Creality CR4NS200141C13 (STM32F401RE) as found in the Ender-5 S1
#define BOARD_BLACKPILL_CUSTOM 5247 // Custom board based on STM32F401CDU6.
#define BOARD_I3DBEEZ9_V1 5248 // I3DBEEZ9 V1 (STM32F407ZG)
#define BOARD_MELLOW_FLY_E3_V2 5249 // Mellow Fly E3 V2 (STM32F407VG)
#define BOARD_FYSETC_CHEETAH_V30 5250 // FYSETC Cheetah V3.0 (STM32F446RC)
#define BOARD_BLACKBEEZMINI_V1 5251 // BlackBeezMini V1 (STM32F401CCU6)
//
// ARM Cortex-M7
//
#define BOARD_REMRAM_V1 6000 // RemRam v1
#define BOARD_TEENSY41 6001 // Teensy 4.1
#define BOARD_T41U5XBB 6002 // T41U5XBB Teensy 4.1 breakout board
#define BOARD_NUCLEO_F767ZI 6003 // ST NUCLEO-F767ZI Dev Board
#define BOARD_BTT_SKR_SE_BX_V2 6004 // BigTreeTech SKR SE BX V2.0 (STM32H743II)
#define BOARD_BTT_SKR_SE_BX_V3 6005 // BigTreeTech SKR SE BX V3.0 (STM32H743II)
#define BOARD_BTT_SKR_V3_0 6006 // BigTreeTech SKR V3.0 (STM32H743VI / STM32H723VG)
#define BOARD_BTT_SKR_V3_0_EZ 6007 // BigTreeTech SKR V3.0 EZ (STM32H743VI / STM32H723VG)
#define BOARD_BTT_OCTOPUS_MAX_EZ_V1_0 6008 // BigTreeTech Octopus Max EZ V1.0 (STM32H723ZE)
#define BOARD_BTT_OCTOPUS_PRO_V1_0_1 6009 // BigTreeTech Octopus Pro v1.0.1 (STM32H723ZE)
#define BOARD_BTT_OCTOPUS_PRO_V1_1 6010 // BigTreeTech Octopus Pro v1.1 (STM32H723ZE)
#define BOARD_BTT_MANTA_M8P_V2_0 6011 // BigTreeTech Manta M8P V2.0 (STM32H723ZE)
#define BOARD_BTT_KRAKEN_V1_0 6012 // BigTreeTech Kraken v1.0 (STM32H723ZG)
//
// Espressif ESP32 WiFi
//
#define BOARD_ESPRESSIF_ESP32 7000 // Generic ESP32
#define BOARD_MRR_ESPA 7001 // MRR ESPA based on ESP32 (native pins only)
#define BOARD_MRR_ESPE 7002 // MRR ESPE based on ESP32 (with I2S stepper stream)
#define BOARD_E4D_BOX 7003 // E4d@BOX
#define BOARD_RESP32_CUSTOM 7004 // Rutilea ESP32 custom board
#define BOARD_FYSETC_E4 7005 // FYSETC E4
#define BOARD_PANDA_ZHU 7006 // Panda_ZHU
#define BOARD_PANDA_M4 7007 // Panda_M4
#define BOARD_MKS_TINYBEE 7008 // MKS TinyBee based on ESP32 (with I2S stepper stream)
#define BOARD_ENWI_ESPNP 7009 // enwi ESPNP based on ESP32 (with I2S stepper stream)
#define BOARD_GODI_CONTROLLER_V1_0 7010 // Godi Controller based on ESP32 32-Bit V1.0
#define BOARD_MM_JOKER 7011 // MagicMaker JOKER based on ESP32 (with I2S stepper stream)
//
// SAMD51 ARM Cortex-M4
//
#define BOARD_AGCM4_RAMPS_144 7100 // RAMPS 1.4.4
#define BOARD_BRICOLEMON_V1_0 7101 // Bricolemon
#define BOARD_BRICOLEMON_LITE_V1_0 7102 // Bricolemon Lite
//
// SAMD21 ARM Cortex-M4
//
#define BOARD_MINITRONICS20 7103 // Minitronics v2.0
//
// HC32 ARM Cortex-M4
//
#define BOARD_AQUILA_V101 7200 // Voxelab Aquila V1.0.0/V1.0.1/V1.0.2/V1.0.3 as found in the Voxelab Aquila X2 and C2
#define BOARD_CREALITY_ENDER2P_V24S4 7201 // Creality Ender 2 Pro v2.4.S4_170 (HC32f460kcta)
//
// Custom board
//
#define BOARD_CUSTOM 9998 // Custom pins definition for development and/or rare boards
//
// Simulations
//
#define BOARD_SIMULATED 9999
#define _MB_1(B) (defined(BOARD_##B) && MOTHERBOARD==BOARD_##B)
#define MB(V...) DO(MB,||,V)
|
2301_81045437/Marlin
|
Marlin/src/core/boards.h
|
C
|
agpl-3.0
| 33,008
|
/**
* 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
|
2301_81045437/Marlin
|
Marlin/src/core/bug_on.h
|
C
|
agpl-3.0
| 1,982
|
/**
* 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_WARN_START
#undef DEBUG_CHAR
#undef DEBUG_ECHO
#undef DEBUG_ECHOLN
#undef DEBUG_ECHOPGM
#undef DEBUG_ECHOLNPGM
#undef DEBUG_ECHOPGM_P
#undef DEBUG_ECHOLNPGM_P
#undef DEBUG_ECHO_MSG
#undef DEBUG_ERROR_MSG
#undef DEBUG_WARN_MSG
#undef DEBUG_ECHO_TERNARY
#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_WARN_START SERIAL_WARN_START
#define DEBUG_CHAR SERIAL_CHAR
#define DEBUG_ECHO SERIAL_ECHO
#define DEBUG_ECHOLN SERIAL_ECHOLN
#define DEBUG_ECHOPGM SERIAL_ECHOPGM
#define DEBUG_ECHOLNPGM SERIAL_ECHOLNPGM
#define DEBUG_ECHOPGM SERIAL_ECHOPGM
#define DEBUG_ECHOPGM_P SERIAL_ECHOPGM_P
#define DEBUG_ECHOLNPGM SERIAL_ECHOLNPGM
#define DEBUG_ECHOLNPGM_P SERIAL_ECHOLNPGM_P
#define DEBUG_ECHO_MSG SERIAL_ECHO_MSG
#define DEBUG_ERROR_MSG SERIAL_ERROR_MSG
#define DEBUG_WARN_MSG SERIAL_WARN_MSG
#define DEBUG_ECHO_TERNARY SERIAL_ECHO_TERNARY
#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_WARN_START() NOOP
#define DEBUG_CHAR(...) NOOP
#define DEBUG_ECHO(...) NOOP
#define DEBUG_ECHOLN(...) NOOP
#define DEBUG_ECHOPGM(...) NOOP
#define DEBUG_ECHOLNPGM(...) NOOP
#define DEBUG_ECHOPGM_P(...) NOOP
#define DEBUG_ECHOLNPGM_P(...) NOOP
#define DEBUG_ECHO_MSG(...) NOOP
#define DEBUG_ERROR_MSG(...) NOOP
#define DEBUG_WARN_MSG(...) NOOP
#define DEBUG_ECHO_TERNARY(...) 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
|
2301_81045437/Marlin
|
Marlin/src/core/debug_out.h
|
C
|
agpl-3.0
| 3,525
|
/**
* 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_ECHO(fpre);
if (the_msg) SERIAL_ECHO(C(' '), the_msg);
SERIAL_CHAR(' ');
print_xyz(xyz_pos_t(current_position));
}
};
|
2301_81045437/Marlin
|
Marlin/src/core/debug_section.h
|
C++
|
agpl-3.0
| 1,357
|
/**
* 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 _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 _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_U(T) _AXIS_DRIVER_TYPE(U,T)
#define AXIS_DRIVER_TYPE_V(T) _AXIS_DRIVER_TYPE(V,T)
#define AXIS_DRIVER_TYPE_W(T) _AXIS_DRIVER_TYPE(W,T)
#define AXIS_DRIVER_TYPE_X2(T) (HAS_X2_STEPPER && _AXIS_DRIVER_TYPE(X2,T))
#define AXIS_DRIVER_TYPE_Y2(T) (HAS_Y2_STEPPER && _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_U(T) || AXIS_DRIVER_TYPE_V(T) || AXIS_DRIVER_TYPE_W(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(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) )
#define AXIS_IS_TMC_CONFIG AXIS_IS_TMC
// 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,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) \
|| AXIS_HAS_##T(U) || AXIS_HAS_##T(V) || AXIS_HAS_##T(W) \
|| 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
#if HAS_STALLGUARD || HAS_DRIVER(TMC2160_STANDALONE) || HAS_DRIVER(TMC2130_STANDALONE) \
|| HAS_DRIVER(TMC2209_STANDALONE) || HAS_DRIVER(TMC2660_STANDALONE) \
|| HAS_DRIVER(TMC5130_STANDALONE) || HAS_DRIVER(TMC5160_STANDALONE)
#define HAS_DIAG_PINS 1
#endif
|
2301_81045437/Marlin
|
Marlin/src/core/drivers.h
|
C
|
agpl-3.0
| 8,249
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2023 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/types.h"
#include "../core/macros.h"
#ifdef __cplusplus
namespace Endianness {
static constexpr uint32_t _dword = 0x01020304;
static constexpr uint8_t _lsb = (const uint8_t&)_dword;
static constexpr bool cpuIsLittleEndian = _lsb == 0x04;
static constexpr bool cpuIsBigEndian = _lsb == 0x01;
static_assert(cpuIsLittleEndian ^ cpuIsBigEndian, "Unknown CPU endianness");
// constexpr byte swapping for integral types
template<typename T> static constexpr typename Private::enable_if<Private::is_integral<T>::value, T>::type swap(T V, T swappedV=(T)0, size_t byteIndex=0) {
return byteIndex == sizeof(T)
? swappedV
: swap<T>((T)(V >> 8), (swappedV << 8) | (V & (T)0xFF), byteIndex + 1);
}
// constexpr byte swapping for types derived from integral types (e.g. enums)
template<typename T> static constexpr typename Private::enable_if<
Private::is_same<uint16_t, typename Private::underlying_type<T>::type>::value, T>::type swap(T V) { return (T)swap<uint16_t>((uint16_t)V); }
template<typename T> static constexpr typename Private::enable_if<
Private::is_same<uint32_t, typename Private::underlying_type<T>::type>::value, T>::type swap(T V) { return (T)swap<uint32_t>((uint32_t)V); }
template<typename T> static constexpr typename Private::enable_if<
Private::is_same<uint64_t, typename Private::underlying_type<T>::type>::value, T>::type swap(T V) { return (T)swap<uint64_t>((uint64_t)V); }
// Generic byte swapping
// CANNOT be used to initialize constexpr declarations
template<typename T> static constexpr typename Private::enable_if<!Private::is_integral<T>::value && !Private::is_enum<T>::value, T>::type swap(T V) {
union {
T val;
char byte[sizeof(T)];
} src{}, dst{};
src.val = V;
for (uint8_t i = 0; i < sizeof(T); ++i) dst.byte[i] = src.byte[sizeof(T) - i - 1];
return dst.val;
}
// Convert to / from known endianness, depending on the host endianness
template<typename T> static constexpr T toBE(T V) { return cpuIsLittleEndian ? swap(V) : V; }
template<typename T> static constexpr T toLE(T V) { return cpuIsLittleEndian ? V : swap(V); }
template<typename T> static constexpr T fromBE(T V) { return cpuIsLittleEndian ? swap(V) : V; }
template<typename T> static constexpr T fromLE(T V) { return cpuIsLittleEndian ? V : swap(V); }
// Reads a big/little endian from a pointer and converts it to the host endianness
template<typename T> static constexpr T fromBE_P(void* V) { return fromBE(*(T*)V); }
template<typename T> static constexpr T fromLE_P(void* V) { return fromLE(*(T*)V); }
};
#endif // __cplusplus
|
2301_81045437/Marlin
|
Marlin/src/core/endianness.h
|
C++
|
agpl-3.0
| 3,537
|
/**
* 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
// fr_na French without accents (DWIN T5UID1 touchscreen)
// 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
#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 MIN/MAX"
#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_CARD_RELEASED "SD card released"
#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_ERR_EEPROM_CORRUPT "EEPROM Corrupt"
#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_START "MPC Autotune start for " STR_E
#define STR_MPC_AUTOTUNE_INTERRUPTED "MPC Autotune interrupted!"
#define STR_MPC_AUTOTUNE_FINISHED "MPC Autotune 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_SOC "soc"
#define STR_PROBE "probe"
#define STR_REDUNDANT "redundant "
#define STR_LASER_TEMP "laser temperature"
#define STR_STOPPED_HEATER ", system stopped! Heater_ID: "
#define STR_DETECTED_TEMP_B " (temp: "
#define STR_DETECTED_TEMP_E ")"
#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_THERMAL_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_FT_MOTION "Fixed-Time Motion"
#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_POLAR_SETTINGS "Polar"
#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_NONLINEAR_EXTRUSION "Nonlinear Extrusion"
#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
//
#if HAS_X_AXIS
#define STR_X_MIN "x_min"
#define STR_X_MAX "x_max"
#define STR_X2_MIN "x2_min"
#define STR_X2_MAX "x2_max"
#endif
#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 HAS_U_AXIS
#if AXIS7_NAME == 'U'
#define STR_U "U"
#define STR_U_MIN "u_min"
#define STR_U_MAX "u_max"
#elif AXIS7_NAME == 'V'
#define STR_U "V"
#define STR_U_MIN "v_min"
#define STR_U_MAX "v_max"
#elif AXIS7_NAME == 'W'
#define STR_U "W"
#define STR_U_MIN "w_min"
#define STR_U_MAX "w_max"
#else
#error "AXIS7_NAME can only be one of 'U', 'V', or 'W'."
#endif
#else
#define STR_U ""
#endif
#if HAS_V_AXIS
#if AXIS8_NAME == 'V'
#define STR_V "V"
#define STR_V_MIN "v_min"
#define STR_V_MAX "v_max"
#elif AXIS8_NAME == 'W'
#define STR_V "W"
#define STR_V_MIN "w_min"
#define STR_V_MAX "w_max"
#else
#error "AXIS8_NAME can only be one of 'V', or 'W'."
#endif
#else
#define STR_V ""
#endif
#if HAS_W_AXIS
#if AXIS9_NAME == 'W'
#define STR_W "W"
#define STR_W_MIN "w_min"
#define STR_W_MAX "w_max"
#else
#error "AXIS9_NAME can only be 'W'."
#endif
#else
#define STR_W ""
#endif
#if ANY(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
|
2301_81045437/Marlin
|
Marlin/src/core/language.h
|
C
|
agpl-3.0
| 24,570
|
/**
* 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
#ifndef __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 _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"))) // No optimization and less debug info
#define __Og __attribute__((optimize("Og"))) // Optimize the debugging experience
#define __Os __attribute__((optimize("Os"))) // Optimize for size
#define __O1 __attribute__((optimize("O1"))) // Try to reduce size and cycles; nothing that takes a lot of time to compile
#define __O2 __attribute__((optimize("O2"))) // Optimize even more
#define __O3 __attribute__((optimize("O3"))) // Optimize yet more
#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))
// Concatenate symbol names, without or with pre-expansion
#define _CAT(a,V...) a##V
#define CAT(a,V...) _CAT(a,V)
// Recognize "true" values: blank, 1, 0x1, true
#define _ISENA_ ~,1
#define _ISENA_1 ~,1
#define _ISENA_0x1 ~,1
#define _ISENA_true ~,1
#define _ISENA(V...) IS_PROBE(V)
// Macros to evaluate simple option switches
#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 ANY(V...) !DISABLED(V)
#define ALL ENABLED
#define NONE DISABLED
#define COUNT_ENABLED(V...) DO(ENA,+,V)
#define MANY(V...) (COUNT_ENABLED(V) > 1)
// Ternary pre-compiler macros conceal non-emitted content from the compiler
#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 IF_DISABLED(O,A) TERN(O,,A)
// Macros to conditionally emit array items and function arguments
#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 operations that aren't always optimized away (e.g., 'f + 0.0' and 'f * 1.0').
// 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 MUL_TERN1(O,A) _TERN(_ENA_1(O),,* (A)) // OPTION ? '* (A)' : '<nul>'
#define DIV_TERN1(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 MUL_TERN(O,B,A) ((B) MUL_TERN1(O,A)) // ((B) (OPTION ? '* (A)' : '<nul>'))
#define DIV_TERN(O,B,A) ((B) DIV_TERN1(O,A)) // ((B) (OPTION ? '/ (A)' : '<nul>'))
// 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)
// Value helper macros
#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) == '+')
// Array shorthand
#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)
// Expansion of some code
#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)
// Expansion of some non-delimited content
#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)
// Expansion of some list items
#define LIST_26(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z
#define LIST_25(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y
#define LIST_24(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X
#define LIST_23(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W
#define LIST_22(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V
#define LIST_21(A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,...) A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U
#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 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 N> static constexpr N _MIN(const N val) { return val; }
template <class N> static constexpr N _MAX(const N val) { return val; }
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) { x = x & y; return x; } \
FORCE_INLINE T & operator|=(T &x, T y) { x = x | y; return x; } \
FORCE_INLINE T & operator^=(T &x, T y) { x = x ^ y; return x; }
// 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; };
// remove const/volatile type qualifiers
template<typename T> struct remove_const { typedef T type; };
template<typename T> struct remove_const<T const> { typedef T type; };
template<typename T> struct remove_volatile { typedef T type; };
template<typename T> struct remove_volatile<T volatile> { typedef T type; };
template<typename T> struct remove_cv { typedef typename remove_const<typename remove_volatile<T>::type>::type type; };
// test if type is integral
template<typename> struct _is_integral { enum { value = false }; };
template<> struct _is_integral<unsigned char> { enum { value = true }; };
template<> struct _is_integral<unsigned short> { enum { value = true }; };
template<> struct _is_integral<unsigned int> { enum { value = true }; };
template<> struct _is_integral<unsigned long> { enum { value = true }; };
template<> struct _is_integral<unsigned long long> { enum { value = true }; };
template<> struct _is_integral<char> { enum { value = true }; };
template<> struct _is_integral<short> { enum { value = true }; };
template<> struct _is_integral<int> { enum { value = true }; };
template<> struct _is_integral<long> { enum { value = true }; };
template<> struct _is_integral<long long> { enum { value = true }; };
template<typename T> struct is_integral : public _is_integral<typename remove_cv<T>::type> {};
}
// enum type check and regression to its underlying integral.
namespace Private {
template<typename T> struct is_enum { enum { value = __is_enum(T) }; };
template<typename T, bool = is_enum<T>::value> struct _underlying_type { using type = __underlying_type(T); };
template<typename T> struct _underlying_type<T, false> { };
template<typename T> struct underlying_type : public _underlying_type<T> { };
}
// 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 EVAL16
#define EVAL4096(V...) EVAL2048(EVAL2048(V))
#define EVAL2048(V...) EVAL1024(EVAL1024(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 RREPEAT_1(N,OP) RREPEAT_S(1,INCREMENT(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)
// Emit a list of N OP(I) items with ascending counter.
#define _REPLIST(_RPT_I,_RPT_N,_RPT_OP) \
_RPT_OP(_RPT_I) \
IF_ELSE(SUB1(_RPT_N)) \
( , DEFER2(__REPLIST)()(ADD1(_RPT_I),SUB1(_RPT_N),_RPT_OP) ) \
( /* Do nothing */ )
#define __REPLIST() _REPLIST
// Repeat a macro, comma-separated, passing S...N-1.
#define REPLIST_S(S,N,OP) EVAL(_REPLIST(S,SUB##S(N),OP))
#define REPLIST(N,OP) REPLIST_S(0,N,OP)
#define REPLIST_1(N,OP) REPLIST_S(1,INCREMENT(N),OP)
// 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))
// Temperature Sensor Config
#define TEMP_SENSOR(N) TEMP_SENSOR_##N
#define _HAS_E_TEMP(N) || TEMP_SENSOR(N)
#define HAS_E_TEMP_SENSOR (0 REPEAT(EXTRUDERS, _HAS_E_TEMP))
#define TEMP_SENSOR_IS_MAX_TC(T) (TEMP_SENSOR(T) == -5 || TEMP_SENSOR(T) == -3 || TEMP_SENSOR(T) == -2)
#define _UI_NONE 0
#define _UI_ORIGIN 101
#define _UI_FYSETC 102
#define _UI_HIPRECY 103
#define _UI_MKS 104
#define _UI_RELOADED 105
#define _UI_IA_CREALITY 106
#define _UI_E3S1PRO 107
#define _DGUS_UI_IS(N) || (CAT(_UI_, DGUS_LCD_UI) == CAT(_UI_, N))
#define DGUS_UI_IS(V...) (0 MAP(_DGUS_UI_IS, V))
|
2301_81045437/Marlin
|
Marlin/src/core/macros.h
|
C++
|
agpl-3.0
| 32,773
|
/**
* 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 MS_TO_SEC_PRECISE(N) (float(N)/1000.0f)
#define PENDING(NOW,SOON) ((int32_t)(NOW-(SOON))<0)
#define ELAPSED(NOW,SOON) (!PENDING(NOW,SOON))
|
2301_81045437/Marlin
|
Marlin/src/core/millis_t.h
|
C
|
agpl-3.0
| 1,198
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2022 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
/**
* Lightweight string class template providing operators for all common tasks
* and conversion from F() and PSTR() strings into SRAM strings that reside
* on the stack or persistently, with overflow prevention.
*
* Examples:
*
* MString<50> mystr(F("Hello "), intvar, " World"); // "Hello 3 World"
*
* mystr.append(" (", p_float_t(123.4, 2), ')'); // "Hello 3 World (123.40)"
*
* mystr.clear();
*
* mystr.append(spaces_t(10), repchr_t('-', 5)); // Repeats are sometimes cheaper than strings
*
* mystr.appendf(F(" ... %i/%i"), count, total); // Works like printf, requires F string
*
*/
#include "types.h"
#include "utility.h" // AXIS_CHAR
#include "../lcd/utf8.h"
#ifndef DEFAULT_MSTRING_SIZE
#define DEFAULT_MSTRING_SIZE 20
#endif
//#define UNSAFE_MSTRING // Don't initialize the string to "" or set a terminating nul
//#define USE_SPRINTF // Use sprintf instead of snprintf
//#define DJB2_HASH // 32-bit hash with Djb2 algorithm
//#define MSTRING_DEBUG // Debug string operations to diagnose memory leaks
//#define FASTER_APPEND // Append without using an intermediate buffer
// Declare externs for serial debug output
template <typename T> extern void SERIAL_ECHO(T x);
template <typename T> extern void SERIAL_ECHOLN(T x);
extern void SERIAL_ECHO(serial_char_t x);
extern void SERIAL_CHAR(char c);
#define START_OF_UTF8_CHAR(C) (((C) & 0xC0u) != 0x80U)
#if ENABLED(USE_SPRINTF)
#define SNPRINTF(A, S, V...) sprintf(A, V)
#define SNPRINTF_P(A, S, V...) sprintf_P(A, V)
#else
#define SNPRINTF(V...) snprintf(V)
#define SNPRINTF_P(V...) snprintf_P(V)
#endif
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#if DISABLED(UNSAFE_MSTRING) && GCC_VERSION >= 80000
#pragma GCC diagnostic ignored "-Wstringop-truncation"
#endif
/**
* @brief MString class template
* @details A class template providing convenient string operators,
* very similar to the Arduino String class, as it turns out.
*
* @tparam SIZE The pre-allocated storage for the string buffer
*/
template <int SIZE=DEFAULT_MSTRING_SIZE, bool SAFE=DISABLED(UNSAFE_MSTRING)>
class MString {
protected:
char str[SIZE+1];
public:
MString() { safety(0); safety(SIZE); }
template<typename T>
MString(const T v) { set(v); safety(SIZE); }
static_assert(SIZE > 0, "Bad SIZE for MString!");
void debug(FSTR_P const f) {
#if ENABLED(MSTRING_DEBUG)
SERIAL_ECHOLN(f, C(':'), uintptr_t(str), C(' '), length(), C(' '), str);
#endif
}
void safety(const int n) { if (SAFE && n <= SIZE) str[n] = '\0'; }
// Chainable String Setters
MString& set() { str[0] = '\0'; debug(F("clear")); return *this; }
MString& set(char *s) { strlcpy(str, s, SIZE + 1); debug(F("string")); return *this; }
MString& set(const char *s) { return set(const_cast<char*>(s)); }
MString& set_P(PGM_P const s) { strlcpy_P(str, s, SIZE + 1); debug(F("pstring")); return *this; }
MString& set(FSTR_P const f) { return set_P(FTOP(f)); }
MString& set(const bool &b) { return set(b ? F("true") : F("false")); }
MString& set(const char c) { str[0] = c; str[1] = '\0'; debug(F("char")); return *this; }
MString& set(const int8_t &i) { SNPRINTF_P(str, SIZE, PSTR("%d"), i); debug(F("int8_t")); return *this; }
MString& set(const short &i) { SNPRINTF_P(str, SIZE, PSTR("%d"), i); debug(F("short")); return *this; }
MString& set(const int &i) { SNPRINTF_P(str, SIZE, PSTR("%d"), i); debug(F("int")); return *this; }
MString& set(const long &l) { SNPRINTF_P(str, SIZE, PSTR("%ld"), l); debug(F("long")); return *this; }
MString& set(const unsigned char &i) { SNPRINTF_P(str, SIZE, PSTR("%u"), i); debug(F("uchar")); return *this; }
MString& set(const unsigned short &i) { SNPRINTF_P(str, SIZE, PSTR("%u"), i); debug(F("ushort")); return *this; }
MString& set(const unsigned int &i) { SNPRINTF_P(str, SIZE, PSTR("%u"), i); debug(F("uint")); return *this; }
MString& set(const unsigned long &l) { SNPRINTF_P(str, SIZE, PSTR("%lu"), l); debug(F("ulong")); return *this; }
MString& set(const float &f) { return set(p_float_t(f, SERIAL_FLOAT_PRECISION)); }
MString& set(const p_float_t &pf) { return set(w_float_t(pf.value, 1, pf.prec)); }
MString& set(const w_float_t &wf) { char f1[20]; return set(dtostrf(wf.value, wf.width, wf.prec, f1)); }
MString& set(const serial_char_t &v) { return set(char(v.c)); }
MString& set(const xyz_pos_t &v) { set(); return append(v); }
MString& set(const xyze_pos_t &v) { set(); return append(v); }
template <int S>
MString& set(const MString<S> &m) { strlcpy(str, &m, SIZE + 1); debug(F("MString")); return *this; }
MString& setn(char *s, int len) { int c = _MIN(len, SIZE); strlcpy(str, s, c + 1); debug(F("string")); return *this; }
MString& setn(const char *s, int len) { return setn(const_cast<char*>(s), len); }
MString& setn_P(PGM_P const s, int len) { int c = _MIN(len, SIZE); strlcpy_P(str, s, c + 1); debug(F("pstring")); return *this; }
MString& setn(FSTR_P const f, int len) { return setn_P(FTOP(f), len); }
// set(repchr_t('-', 10))
MString& set(const repchr_t &s) { int c = _MIN(s.count, SIZE); if (c >= 0) { if (c > 0) memset(str, s.asc, c); str[c] = '\0'; } debug(F("repchr_t")); return *this; }
// set(spaces_t(10))
MString& set(const spaces_t &s) { repchr_t r(' ', s.count); return set(r); }
// Set with format string and arguments, like printf
template<typename... Args>
MString& setf_P(PGM_P const pfmt, Args... more) { SNPRINTF_P(str, SIZE, pfmt, more...); debug(F("setf_P")); return *this; }
template<typename... Args>
MString& setf(const char *fmt, Args... more) { SNPRINTF(str, SIZE, fmt, more...); debug(F("setf")); return *this; }
template<typename... Args>
MString& setf(FSTR_P const ffmt, Args... more) { return setf_P(FTOP(ffmt), more...); }
// Chainable String appenders
MString& append() { debug(F("nil")); return *this; } // for macros that might emit no output
MString& append(char *s) { int sz = length(); if (sz < SIZE) strlcpy(str + sz, s, SIZE - sz + 1); debug(F("string")); return *this; }
MString& append(const char *s) { return append(const_cast<char *>(s)); }
MString& append_P(PGM_P const s) { int sz = length(); if (sz < SIZE) strlcpy_P(str + sz, s, SIZE - sz + 1); debug(F("pstring")); return *this; }
MString& append(FSTR_P const f) { return append_P(FTOP(f)); }
MString& append(const bool &b) { return append(b ? F("true") : F("false")); }
MString& append(const char c) { int sz = length(); if (sz < SIZE) { str[sz] = c; if (sz < SIZE - 1) str[sz + 1] = '\0'; } return *this; }
#if ENABLED(FASTER_APPEND)
MString& append(const int8_t &i) { int sz = length(); SNPRINTF(&str[sz], SIZE - sz, "%d", i); return *this; }
MString& append(const short &i) { int sz = length(); SNPRINTF(&str[sz], SIZE - sz, "%d", i); return *this; }
MString& append(const int &i) { int sz = length(); SNPRINTF(&str[sz], SIZE - sz, "%d", i); return *this; }
MString& append(const long &l) { int sz = length(); SNPRINTF(&str[sz], SIZE - sz, "%ld", l); return *this; }
MString& append(const unsigned char &i) { int sz = length(); SNPRINTF(&str[sz], SIZE - sz, "%u", i); return *this; }
MString& append(const unsigned short &i) { int sz = length(); SNPRINTF(&str[sz], SIZE - sz, "%u", i); return *this; }
MString& append(const unsigned int &i) { int sz = length(); SNPRINTF(&str[sz], SIZE - sz, "%u", i); return *this; }
MString& append(const unsigned long &l) { int sz = length(); SNPRINTF(&str[sz], SIZE - sz, "%lu", l); return *this; }
#else
MString& append(const int8_t &i) { char buf[ 5]; sprintf(buf, "%d", i); return append(buf); }
MString& append(const short &i) { char buf[12]; sprintf(buf, "%d", i); return append(buf); }
MString& append(const int &i) { char buf[12]; sprintf(buf, "%d", i); return append(buf); }
MString& append(const long &l) { char buf[12]; sprintf(buf, "%ld", l); return append(buf); }
MString& append(const unsigned char &i) { char buf[ 5]; sprintf(buf, "%u", i); return append(buf); }
MString& append(const unsigned short &i) { char buf[11]; sprintf(buf, "%u", i); return append(buf); }
MString& append(const unsigned int &i) { char buf[11]; sprintf(buf, "%u", i); return append(buf); }
MString& append(const unsigned long &l) { char buf[11]; sprintf(buf, "%lu", l); return append(buf); }
#endif
MString& append(const float &f) { return append(p_float_t(f, SERIAL_FLOAT_PRECISION)); }
MString& append(const p_float_t &pf) { return append(w_float_t(pf.value, 1, pf.prec)); }
MString& append(const w_float_t &wf) { char f1[20]; return append(dtostrf(wf.value, wf.width, wf.prec, f1)); }
MString& append(const serial_char_t &v) { return append(char(v.c)); }
MString& append(const xyz_pos_t &v) { LOOP_NUM_AXES(i) { if (i) append(' '); append(AXIS_CHAR(i), v[i]); } debug(F("xyz")); return *this; }
MString& append(const xyze_pos_t &v) { LOOP_LOGICAL_AXES(i) { if (i) append(' '); append(AXIS_CHAR(i), v[i]); } debug(F("xyze")); return *this; }
template<int S>
MString& append(const MString<S> &m) { return append(&m); }
// Append only if the given space is available
MString& appendn(char *s, int len) { int sz = length(), c = _MIN(len, SIZE - sz); if (c > 0) { strlcpy(str + sz, s, c + 1); } debug(F("string")); return *this; }
MString& appendn(const char *s, int len) { return appendn(const_cast<char *>(s), len); }
MString& appendn_P(PGM_P const s, int len) { int sz = length(), c = _MIN(len, SIZE - sz); if (c > 0) { strlcpy_P(str + sz, s, c + 1); } debug(F("pstring")); return *this; }
MString& appendn(FSTR_P const f, int len) { return appendn_P(FTOP(f), len); }
// append(repchr_t('-', 10))
MString& append(const repchr_t &s) {
const int sz = length(), c = _MIN(s.count, SIZE - sz);
if (c > 0) { memset(str + sz, s.asc, c); str[sz + c] = '\0'; }
debug(F("repchr"));
return *this;
}
// append(spaces_t(10))
MString& append(const spaces_t &s) { return append(repchr_t(' ', s.count)); }
template<typename... Args>
MString& appendf_P(PGM_P const pfmt, Args... more) {
int sz = length();
if (sz < SIZE) SNPRINTF_P(str + sz, SIZE - sz, pfmt, more...);
debug(F("appendf_P"));
return *this;
}
template<typename... Args>
MString& appendf(const char *fmt, Args... more) {
const int sz = length();
if (sz < SIZE) SNPRINTF(str + sz, SIZE - sz, fmt, more...);
debug(F("appendf"));
return *this;
}
template<typename... Args>
MString& appendf(FSTR_P const fmt, Args... more) { return appendf_P(FTOP(fmt), more...); }
// Instantiate with a list of things
template <typename T, typename... Args>
MString(T arg1, Args... more) { set(arg1); append(more...); }
// Catch unhandled types to prevent infinite recursion
template<typename T> MString& append(T) { return append(TERN(MSTRING_DEBUG, typeid(T).name(), '?')); }
// Take a list of any number of arguments and append them to the string
template<typename T, typename... Args>
MString& append(T arg1, Args... more) { return append(arg1).append(more...); }
// Take a list of any number of arguments and set them in the string
template<typename T, typename... Args>
MString& set(T arg1, Args... more) { return set(arg1).append(more...); }
// Operator = as shorthand for set()
template<typename T>
MString& operator=(const T &v) { return set(v); }
// Operator += as shorthand for append()
template<typename T>
MString& operator+=(const T &v) { return append(v); }
// Operator + as shorthand for append-to-copy
template<typename T>
MString operator+(const T &v) { return MString(str, v); }
#ifndef __AVR__
MString(const double d) { set(d); }
MString& set(const double &f) { return set(p_double_t(f, SERIAL_FLOAT_PRECISION)); }
MString& set(const p_double_t &pf) { return set(w_double_t(pf.value, 1, pf.prec)); }
MString& set(const w_double_t &wf) { char d1[20]; return set(dtostrf(wf.value, wf.width, wf.prec, d1)); }
MString& append(const double &f) { return append(p_double_t(f, SERIAL_FLOAT_PRECISION)); }
MString& append(const p_double_t &pf) { return append(w_double_t(pf.value, 1, pf.prec)); }
MString& append(const w_double_t &wf) { char d1[20]; return append(dtostrf(wf.value, wf.width, wf.prec, d1)); }
#endif
// Get the character at a given index
char operator[](const int i) const { return str[i]; }
// Cast to char* (explicit?)
operator char* () { return str; }
// Use &mystring as shorthand for mystring.str
char* operator&() { return str; }
// Return the buffer address (same as &)
char* buffer() { return str; }
int length() const { return strlen(str); }
int glyphs() { return utf8_strlen(str); }
bool empty() { return !str[0]; }
// Quick hash to detect change (e.g., to avoid expensive drawing)
typedef IF<ENABLED(DJB2_HASH), uint32_t, uint16_t>::type hash_t;
hash_t hash() const {
#if ENABLED(DJB2_HASH)
hash_t hval = 5381;
char c;
while ((c = *str++)) hval += (hval << 5) + c; // = hval * 33 + c
#else
const int sz = length();
hash_t hval = hash_t(sz);
for (int i = 0; i < sz; i++) hval = ((hval << 1) | (hval >> 15)) ^ str[i]; // ROL, XOR
#endif
return hval;
}
void copyto(char * const dst) const { strcpy(dst, str); }
void copyto(char * const dst, int len) const { strlcpy(dst, str, len + 1); }
MString& clear() { return set(); }
MString& eol() { return append('\n'); }
MString& trunc(const int &i) { if (i <= SIZE) str[i] = '\0'; debug(F("trunc")); return *this; }
// Truncate on a Unicode boundary
MString& utrunc(const int &n=SIZE) {
const int sz = length();
if (sz && n <= sz)
for (int i = n; i >= 0; i--) if (START_OF_UTF8_CHAR(str[i])) { str[i] = '\0'; break; }
debug(F("utrunc"));
return *this;
}
};
#pragma GCC diagnostic pop
// Temporary inline string typically used to compose a G-code command
#ifndef TS_SIZE
#define TS_SIZE 63
#endif
typedef MString<TS_SIZE, DISABLED(UNSAFE_MSTRING)> TString;
#define TS(V...) TString(V)
|
2301_81045437/Marlin
|
Marlin/src/core/mstring.h
|
C++
|
agpl-3.0
| 15,733
|
/**
* 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
#if HAS_MARLINUI_MENU
#define HAS_MENU_MULTI_LANGUAGE 1
#endif
#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
|
2301_81045437/Marlin
|
Marlin/src/core/multi_language.h
|
C
|
agpl-3.0
| 3,284
|
/**
* 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
// Echo commands to the terminal by default in dev mode
uint8_t marlin_debug_flags = TERN(MARLIN_DEV_MODE, MARLIN_DEBUG_ECHO, 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
// Specializations for float, p_float_t, w_float_t
template <> void SERIAL_ECHO(const float f) { SERIAL_IMPL.print(f, SERIAL_FLOAT_PRECISION); }
template <> void SERIAL_ECHO(const p_float_t pf) { SERIAL_IMPL.print(pf.value, pf.prec); }
template <> void SERIAL_ECHO(const w_float_t wf) { char f1[20]; SERIAL_IMPL.print(dtostrf(wf.value, wf.width, wf.prec, f1)); }
// Specializations for F-string
template <> void SERIAL_ECHO(const FSTR_P fstr) { SERIAL_ECHO_P(FTOP(fstr)); }
template <> void SERIAL_ECHOLN(const FSTR_P fstr) { SERIAL_ECHOLN_P(FTOP(fstr)); }
void SERIAL_CHAR(char a) { SERIAL_IMPL.write(a); }
void SERIAL_EOL() { SERIAL_CHAR('\n'); }
void SERIAL_ECHO(serial_char_t x) { SERIAL_IMPL.write(x.c); }
void SERIAL_FLUSH() { SERIAL_IMPL.flush(); }
void SERIAL_FLUSHTX() { SERIAL_IMPL.flushTX(); }
void SERIAL_ECHO_P(PGM_P pstr) {
while (const char c = pgm_read_byte(pstr++)) SERIAL_CHAR(c);
}
void SERIAL_ECHOLN_P(PGM_P pstr) { SERIAL_ECHO_P(pstr); SERIAL_EOL(); }
void SERIAL_ECHO_START() { SERIAL_ECHO(F("echo:")); }
void SERIAL_ERROR_START() { SERIAL_ECHO(F("Error:")); }
void SERIAL_WARN_START() { SERIAL_ECHO(F("Warning:")); }
void SERIAL_ECHO_SP(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_ECHO(v);
}
void serial_ternary(FSTR_P const pre, const bool onoff, FSTR_P const on, FSTR_P const off, FSTR_P const post/*=nullptr*/) {
if (pre) SERIAL_ECHO(pre);
if (onoff && on) SERIAL_ECHO(on);
if (!onoff && off) SERIAL_ECHO(off);
if (post) SERIAL_ECHO(post);
}
void serialprint_onoff(const bool onoff) { SERIAL_ECHO(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_ECHO(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_xyz(NUM_AXIS_ARGS_(const_float_t) FSTR_P const prefix) {
if (prefix) SERIAL_ECHO(prefix);
#if NUM_AXES
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, SP_U_STR, u, SP_V_STR, v, SP_W_STR, w)
);
#endif
}
void print_xyz(NUM_AXIS_ARGS_(const_float_t) FSTR_P const prefix/*=nullptr*/, FSTR_P const suffix/*=nullptr*/) {
_print_xyz(NUM_AXIS_LIST_(x, y, z, i, j, k, u, v, w) prefix);
if (suffix) SERIAL_ECHO(suffix); else SERIAL_EOL();
}
void print_xyze(LOGICAL_AXIS_ARGS_(const_float_t) FSTR_P const prefix/*=nullptr*/, FSTR_P const suffix/*=nullptr*/) {
_print_xyz(NUM_AXIS_LIST_(x, y, z, i, j, k, u, v, w) prefix);
#if HAS_EXTRUDERS
SERIAL_ECHOPGM_P(SP_E_STR, e);
#endif
if (suffix) SERIAL_ECHO(suffix); else SERIAL_EOL();
}
|
2301_81045437/Marlin
|
Marlin/src/core/serial.cpp
|
C++
|
agpl-3.0
| 5,433
|
/**
* 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 = TERN0(DEBUG_FLAGS_GCODE, _BV(0)), //!< Echo commands in order as they are processed
MARLIN_DEBUG_INFO = TERN0(DEBUG_FLAGS_GCODE, _BV(1)), //!< Print messages for code that has debug output
MARLIN_DEBUG_ERRORS = TERN0(DEBUG_FLAGS_GCODE, _BV(2)), //!< Not implemented
MARLIN_DEBUG_DRYRUN = _BV(3), //!< Ignore temperature setting and E movement commands
MARLIN_DEBUG_COMMUNICATION = TERN0(DEBUG_FLAGS_GCODE, _BV(4)), //!< Not implemented
MARLIN_DEBUG_LEVELING = TERN0(DEBUG_LEVELING_FEATURE, _BV(5)), //!< Print detailed output for homing and leveling
MARLIN_DEBUG_MESH_ADJUST = TERN0(DEBUG_LEVELING_FEATURE, _BV(6)), //!< UBL bed leveling
MARLIN_DEBUG_ALL = MARLIN_DEBUG_ECHO|MARLIN_DEBUG_INFO|MARLIN_DEBUG_ERRORS|MARLIN_DEBUG_COMMUNICATION|MARLIN_DEBUG_LEVELING|MARLIN_DEBUG_MESH_ADJUST
};
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 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
//
void SERIAL_CHAR(char a);
template <typename ... Args>
void SERIAL_CHAR(char a, Args ... args) { SERIAL_IMPL.write(a); SERIAL_CHAR(args ...); }
/**
* SERIAL_ECHO / SERIAL_ECHOLN - 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); }
template <typename T> void SERIAL_ECHOLN(T x) { SERIAL_IMPL.println(x); }
// Wrapper for ECHO commands to interpret a char
void SERIAL_ECHO(serial_char_t x);
#define AS_DIGIT(n) C('0' + (n))
// Print an integer with a numeric base such as PrintBase::Hex
template <typename T> void SERIAL_PRINT(T x, PrintBase 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
void SERIAL_FLUSH();
void SERIAL_FLUSHTX();
// Start an echo: or error: output
void SERIAL_ECHO_START();
void SERIAL_ERROR_START();
void SERIAL_WARN_START();
// Serial end-of-line
void SERIAL_EOL();
// Print a single PROGMEM, PGM_P, or PSTR() string.
void SERIAL_ECHO_P(PGM_P pstr);
void SERIAL_ECHOLN_P(PGM_P pstr);
// Specializations for float, p_float_t, and w_float_t
template<> void SERIAL_ECHO(const float f);
template<> void SERIAL_ECHO(const p_float_t pf);
template<> void SERIAL_ECHO(const w_float_t wf);
// Specializations for F-string
template<> void SERIAL_ECHO(const FSTR_P fstr);
template<> void SERIAL_ECHOLN(const FSTR_P fstr);
// Print any number of items with arbitrary types (except loose PROGMEM strings)
template <typename T, typename ... Args>
void SERIAL_ECHO(T arg1, Args ... args) { SERIAL_ECHO(arg1); SERIAL_ECHO(args ...); }
template <typename T, typename ... Args>
void SERIAL_ECHOLN(T arg1, Args ... args) { SERIAL_ECHO(arg1); SERIAL_ECHO(args ...); SERIAL_EOL(); }
//
// SERIAL_ECHOPGM... macros are used to output string-value pairs, wrapping
// all the odd loose string elements as PROGMEM strings.
//
// 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_ECHO(F(s));
#define _SEP_2(s,v) SERIAL_ECHO(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_ECHO(F(s "\n"));
#define _SELP_2(s,v) SERIAL_ECHOLN(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_ECHO(FPSTR(p));
#define _SEP_2_P(p,v) SERIAL_ECHO(FPSTR(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_ECHOLN(FPSTR(p));
#define _SELP_2_P(p,v) SERIAL_ECHOLN(FPSTR(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)
#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_WARN_MSG(V...) do{ SERIAL_WARN_START(); SERIAL_ECHOLNPGM(V); }while(0)
// Print a prefix, conditional string, and suffix
void serial_ternary(FSTR_P const pre, const bool onoff, FSTR_P const on, FSTR_P const off, FSTR_P const post=nullptr);
// Shorthand to put loose strings in PROGMEM
#define SERIAL_ECHO_TERNARY(TF, PRE, ON, OFF, POST) serial_ternary(F(PRE), TF, F(ON), F(OFF), F(POST))
// Print up to 255 spaces
void SERIAL_ECHO_SP(uint8_t count);
void serialprint_onoff(const bool onoff);
void serialprintln_onoff(const bool onoff);
void serialprint_truefalse(const bool tf);
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_xyz(NUM_AXIS_ARGS_(const_float_t) FSTR_P const prefix=nullptr, FSTR_P const suffix=nullptr);
inline void print_xyz(const xyz_pos_t &xyz, FSTR_P const prefix=nullptr, FSTR_P const suffix=nullptr) {
print_xyz(NUM_AXIS_ELEM_(xyz) prefix, suffix);
}
void print_xyze(LOGICAL_AXIS_ARGS_(const_float_t) FSTR_P const prefix=nullptr, FSTR_P const suffix=nullptr);
inline void print_xyze(const xyze_pos_t &xyze, FSTR_P const prefix=nullptr, FSTR_P const suffix=nullptr) {
print_xyze(LOGICAL_AXIS_ELEM_(xyze) prefix, suffix);
}
#define SERIAL_POS(SUFFIX,VAR) do { print_xyz(VAR, F(" " STRINGIFY(VAR) "="), F(" : " SUFFIX "\n")); }while(0)
#define SERIAL_XYZ(PREFIX,V...) do { print_xyz(V, F(PREFIX)); }while(0)
/**
* Extended string that can echo itself to serial
*/
template <int SIZE=DEFAULT_MSTRING_SIZE>
class SString : public MString<SIZE> {
public:
typedef MString<SIZE> super;
using super::str;
using super::debug;
SString() : super() {}
template <typename T, typename... Args>
SString(T arg1, Args... more) : super(arg1, more...) {}
SString& set() { super::set(); return *this; }
template<typename... Args>
SString& setf_P(PGM_P const pfmt, Args... more) { super::setf_P(pfmt, more...); return *this; }
template<typename... Args>
SString& setf(const char *fmt, Args... more) { super::setf(fmt, more...); return *this; }
template<typename... Args>
SString& setf(FSTR_P const ffmt, Args... more) { super::setf(ffmt, more...); return *this; }
template <typename T>
SString& set(const T &v) { super::set(v); return *this; }
template <typename T>
SString& append(const T &v) { super::append(v); return *this; }
template<typename T, typename... Args>
SString& set(T arg1, Args... more) { set(arg1).append(more...); return *this; }
template<typename T, typename... Args>
SString& append(T arg1, Args... more) { append(arg1).append(more...); return *this; }
SString& clear() { set(); return *this; }
SString& eol() { append('\n'); return *this; }
SString& trunc(const int &i) { super::trunc(i); return *this; }
// Extended with methods to print to serial
SString& echo() { SERIAL_ECHO(str); return *this; }
SString& echoln() { SERIAL_ECHOLN(str); return *this; }
};
#define TSS(V...) SString<>(V)
//
// 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
|
2301_81045437/Marlin
|
Marlin/src/core/serial.h
|
C++
|
agpl-3.0
| 12,906
|
/**
* 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 <stddef.h> // for size_t
#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;
for (uint8_t i = 0; i < digits; ++i) 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.
|
2301_81045437/Marlin
|
Marlin/src/core/serial_base.h
|
C++
|
agpl-3.0
| 11,151
|
/**
* 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
|
2301_81045437/Marlin
|
Marlin/src/core/serial_hook.h
|
C++
|
agpl-3.0
| 12,410
|
/**
* 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 ALL_AXIS_NAMES X, X2, Y, Y2, Z, Z2, Z3, Z4, I, J, K, U, V, W, E0, E1, E2, E3, E4, E5, E6, E7
#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, T u, T v, T w)
#define NUM_AXIS_ELEM(O) NUM_AXIS_LIST(O.x, O.y, O.z, O.i, O.j, O.k, O.u, O.v, O.w)
#define NUM_AXIS_DECL(T,V) NUM_AXIS_LIST(T x=V, T y=V, T z=V, T i=V, T j=V, T k=V, T u=V, T v=V, T w=V)
#define MAIN_AXIS_NAMES NUM_AXIS_LIST(X, Y, Z, I, J, K, U, V, W)
#define MAIN_AXIS_NAMES_LC NUM_AXIS_LIST(x, y, z, i, j, k, u, v, w)
#define STR_AXES_MAIN NUM_AXIS_GANG("X", "Y", "Z", STR_I, STR_J, STR_K, STR_U, STR_V, STR_W)
#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, T u, T v, T w)
#define LOGICAL_AXIS_ELEM(O) LOGICAL_AXIS_LIST(O.e, O.x, O.y, O.z, O.i, O.j, O.k, O.u, O.v, O.w)
#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, T u=V, T v=V, T w=V)
#define LOGICAL_AXIS_NAMES LOGICAL_AXIS_LIST(E, X, Y, Z, I, J, K, U, V, W)
#define LOGICAL_AXIS_NAMES_LC LOGICAL_AXIS_LIST(e, x, y, z, i, j, k, u, v, w)
#define LOGICAL_AXIS_MAP(F) MAP(F, LOGICAL_AXIS_NAMES)
#define LOGICAL_AXIS_MAP_LC(F) MAP(F, LOGICAL_AXIS_NAMES_LC)
#define STR_AXES_LOGICAL LOGICAL_AXIS_GANG("E", "X", "Y", "Z", STR_I, STR_J, STR_K, STR_U, STR_V, STR_W)
#if NUM_AXES
#define NUM_AXES_SEP ,
#define MAIN_AXIS_MAP(F) MAP(F, MAIN_AXIS_NAMES)
#define MAIN_AXIS_MAP_LC(F) MAP(F, MAIN_AXIS_NAMES_LC)
#define OPTARGS_NUM(T) , NUM_AXIS_ARGS(T)
#define OPTARGS_LOGICAL(T) , LOGICAL_AXIS_ARGS(T)
#else
#define NUM_AXES_SEP
#define MAIN_AXIS_MAP(F)
#define MAIN_AXIS_MAP_LC(F)
#define OPTARGS_NUM(T)
#define OPTARGS_LOGICAL(T)
#endif
#define NUM_AXIS_GANG_(V...) NUM_AXIS_GANG(V) NUM_AXES_SEP
#define NUM_AXIS_LIST_(V...) NUM_AXIS_LIST(V) NUM_AXES_SEP
#define NUM_AXIS_LIST_1_(V...) NUM_AXIS_LIST_1(V) NUM_AXES_SEP
#define NUM_AXIS_ARGS_(T) NUM_AXIS_ARGS(T) NUM_AXES_SEP
#define NUM_AXIS_ELEM_(T) NUM_AXIS_ELEM(T) NUM_AXES_SEP
#define MAIN_AXIS_NAMES_ MAIN_AXIS_NAMES NUM_AXES_SEP
#define MAIN_AXIS_NAMES_LC_ MAIN_AXIS_NAMES_LC NUM_AXES_SEP
#if LOGICAL_AXES
#define LOGICAL_AXES_SEP ,
#else
#define LOGICAL_AXES_SEP
#endif
#define LOGICAL_AXIS_GANG_(V...) LOGICAL_AXIS_GANG(V) LOGICAL_AXES_SEP
#define LOGICAL_AXIS_LIST_(V...) LOGICAL_AXIS_LIST(V) LOGICAL_AXES_SEP
#define LOGICAL_AXIS_LIST_1_(V...) LOGICAL_AXIS_LIST_1(V) LOGICAL_AXES_SEP
#define LOGICAL_AXIS_ARGS_(T) LOGICAL_AXIS_ARGS(T) LOGICAL_AXES_SEP
#define LOGICAL_AXIS_ELEM_(T) LOGICAL_AXIS_ELEM(T) LOGICAL_AXES_SEP
#define LOGICAL_AXIS_NAMES_ LOGICAL_AXIS_NAMES LOGICAL_AXES_SEP
#define LOGICAL_AXIS_NAMES_LC_ LOGICAL_AXIS_NAMES_LC LOGICAL_AXES_SEP
#define SECONDARY_AXIS_GANG(V...) GANG_N(SECONDARY_AXES, V)
#define SECONDARY_AXIS_CODE(V...) CODE_N(SECONDARY_AXES, V)
#define SECONDARY_AXIS_LIST(V...) LIST_N(SECONDARY_AXES, V)
#define SECONDARY_AXIS_ARGS(T) SECONDARY_AXIS_LIST(T i, T j, T k, T u, T v, T w)
// Just the XY or XYZ elements
#if HAS_Z_AXIS
#define XYZ_COUNT 3
#define XY_COUNT 2
#elif HAS_Y_AXIS
#define XY_COUNT 2
#elif HAS_X_AXIS
#define XY_COUNT 1
#else
#define XY_COUNT 0
#endif
#ifndef XYZ_COUNT
#define XYZ_COUNT XY_COUNT
#endif
#define XY_LIST(V...) LIST_N(XY_COUNT, V)
#define XY_ARRAY(V...) ARRAY_N(XY_COUNT, V)
#define XY_CODE(V...) CODE_N(XY_COUNT, V)
#define XY_GANG(V...) GANG_N(XY_COUNT, V)
#define XYZ_LIST(V...) LIST_N(XYZ_COUNT, V)
#define XYZ_ARRAY(V...) ARRAY_N(XYZ_COUNT, V)
#define XYZ_CODE(V...) CODE_N(XYZ_COUNT, V)
#define XYZ_GANG(V...) GANG_N(XYZ_COUNT, V)
#if HAS_ROTATIONAL_AXES
#define ROTATIONAL_AXIS_GANG(V...) GANG_N(ROTATIONAL_AXES, V)
#endif
#if HAS_EXTRUDERS
#if NUM_AXES
#define LIST_ITEM_E(N) , N
#define CODE_ITEM_E(N) ; N
#else
#define LIST_ITEM_E(N) N
#define CODE_ITEM_E(N) N
#endif
#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 || AXIS7_NAME == L || AXIS8_NAME == L || AXIS9_NAME == L)
// Helpers
#define _RECIP(N) ((N) ? 1.0f / static_cast<float>(N) : 0.0f)
#define _ABS(N) ((N) < 0 ? -(N) : (N))
#define _LS(N) T(uint32_t(N) << p)
#define _RS(N) T(uint32_t(N) >> p)
#define _LSE(N) N = T(uint32_t(N) << p)
#define _RSE(N) N = T(uint32_t(N) >> p)
#define FI FORCE_INLINE
// Define types based on largest bit width stored value required
#define bits_t(W) typename IF<((W)> 16), uint32_t, typename IF<((W)> 8), uint16_t, uint8_t>::type>::type
#define uvalue_t(V) typename IF<((V)>65535), uint32_t, typename IF<((V)>255), uint16_t, uint8_t>::type>::type
#define value_t(V) typename IF<((V)>32767), int32_t, typename IF<((V)>127), int16_t, int8_t>::type>::type
// General Flags for some number of states
template<size_t N>
struct Flags {
typedef bits_t(N) flagbits_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;
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,
b16:1, b17:1, b18:1, b19:1, b20:1, b21:1, b22:1, b23:1, b24:1, b25:1, b26:1, b27:1, b28:1, b29:1, b30:1, b31:1; } N32;
union {
flagbits_t b;
typename IF<(N>16), N32, typename IF<(N>8), N16, N8>::type>::type flag;
};
FI void reset() { b = 0; }
FI void set(const int n, const bool onoff) { onoff ? set(n) : clear(n); }
FI void set(const int n) { b |= (flagbits_t)_BV(n); }
FI void clear(const int n) { b &= ~(flagbits_t)_BV(n); }
FI bool test(const int n) const { return TEST(b, n); }
FI bool operator[](const int n) { return test(n); }
FI bool operator[](const int n) const { return test(n); }
FI int size() const { return sizeof(b); }
FI operator bool() const { return b; }
};
// Specialization for a single bool flag
template<>
struct Flags<1> {
bool b;
FI void reset() { b = false; }
FI void set(const int n, const bool onoff) { onoff ? set(n) : clear(n); }
FI void set(const int) { b = true; }
FI void clear(const int) { b = false; }
FI bool test(const int) const { return b; }
FI bool& operator[](const int) { return b; }
FI bool operator[](const int) const { return b; }
FI int size() const { return sizeof(b); }
FI operator bool() const { return 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 {
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); };
};
FI void reset() { flags.reset(); }
FI void set(const int n) { flags.set(n); }
FI void set(const int n, const bool onoff) { flags.set(n, onoff); }
FI void clear(const int n) { flags.clear(n); }
FI bool test(const int n) const { return flags.test(n); }
FI bool operator[](const int n) { return flags[n]; }
FI bool operator[](const int n) const { return flags[n]; }
FI int size() const { return sizeof(flags); }
FI operator bool() const { return flags; }
} AxisFlags;
//
// 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 axes 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, U_AXIS, V_AXIS, W_AXIS)
#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.
#if HAS_X_AXIS
A_AXIS = X_AXIS,
#endif
#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
};
//
// Loop over axes
//
#define LOOP_ABC(VAR) for (uint8_t VAR = A_AXIS; VAR <= C_AXIS; ++VAR)
#define LOOP_NUM_AXES(VAR) for (uint8_t VAR = 0; VAR < NUM_AXES; ++VAR)
#define LOOP_LOGICAL_AXES(VAR) for (uint8_t VAR = 0; VAR < LOGICAL_AXES; ++VAR)
#define LOOP_DISTINCT_AXES(VAR) for (uint8_t VAR = 0; VAR < DISTINCT_AXES; ++VAR)
#define LOOP_DISTINCT_E(VAR) for (uint8_t VAR = 0; VAR < DISTINCT_E; ++VAR)
//
// 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;
// Type large enough to count leveling grid points
typedef IF<TERN0(ABL_USES_GRID, (GRID_MAX_POINTS > 255)), uint16_t, uint8_t>::type grid_count_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)
// Packaged character for C macro and other usage
typedef struct SerialChar { char c; SerialChar(char n) : c(n) { } } serial_char_t;
#define C(c) serial_char_t(c)
// Packaged types: float with precision and/or width; a repeated space/character
typedef struct WFloat { float value; char width; char prec;
WFloat(float v, char w, char p) : value(v), width(w), prec(p) {}
} w_float_t;
typedef struct PFloat { float value; char prec;
PFloat(float v, char p) : value(v), prec(p) {}
} p_float_t;
typedef struct RepChr { char asc; int8_t count;
RepChr(char a, uint8_t c) : asc(a), count(c) {}
} repchr_t;
typedef struct Spaces { int8_t count;
Spaces(uint8_t c) : count(c) {}
} spaces_t;
#ifdef __AVR__
typedef w_float_t w_double_t;
typedef p_float_t p_double_t;
#else
typedef struct WDouble { double value; char width; char prec;
WDouble(double v, char w, char p) : value(v), width(w), prec(p) {}
} w_double_t;
typedef struct PDouble { double value; char prec;
PDouble(double v, char p) : value(v), prec(p) {}
} p_double_t;
#endif
//
// Coordinates structures for XY, XYZ, XYZE...
//
// 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 &lpos);
void toNative(xyz_pos_t &lpos);
void toNative(xyze_pos_t &lpos);
//
// Paired XY coordinates, counters, flags, etc.
// Always has XY elements regardless of the number of configured axes.
//
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
#if HAS_X_AXIS
FI void set(const T px) { x = px; }
#endif
#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 constexpr T magnitude() const { return (T)sqrtf(x*x + y*y); }
// Pointer to the data as a simple array
explicit FI operator T* () { return pos; }
// If any element is true then it's true
FI constexpr operator bool() const { return x || y; }
// Smallest element
FI constexpr T small() const { return _MIN(x, y); }
// Largest element
FI constexpr T large() const { return _MAX(x, y); }
// Explicit copy and copies with conversion
FI constexpr XYval<T> copy() const { return *this; }
FI constexpr XYval<T> ABS() const { return { T(_ABS(x)), T(_ABS(y)) }; }
FI constexpr XYval<int16_t> asInt() const { return { int16_t(x), int16_t(y) }; }
FI constexpr XYval<int32_t> asLong() const { return { int32_t(x), int32_t(y) }; }
FI constexpr XYval<int32_t> ROUNDL() const { return { int32_t(LROUND(x)), int32_t(LROUND(y)) }; }
FI constexpr XYval<float> asFloat() const { return { static_cast<float>(x), static_cast<float>(y) }; }
FI constexpr 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 constexpr operator XYZval<T>() const { return { x, y }; }
FI constexpr 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(XY_LIST(rs.x, rs.y)); return *this; }
FI XYval<T>& operator= (const XYZEval<T> &rs) { set(XY_LIST(rs.x, rs.y)); return *this; }
// Override other operators to get intuitive behaviors
#define XY_OP(OP) { x TERN_(HAS_X_AXIS, OP rs.x), y TERN_(HAS_Y_AXIS, OP rs.y) }
FI constexpr XYval<T> operator+ (const XYval<T> &rs) const { return { x + rs.x, y + rs.y }; }
FI constexpr XYval<T> operator- (const XYval<T> &rs) const { return { x - rs.x, y - rs.y }; }
FI constexpr XYval<T> operator* (const XYval<T> &rs) const { return { x * rs.x, y * rs.y }; }
FI constexpr XYval<T> operator/ (const XYval<T> &rs) const { return { x / rs.x, y / rs.y }; }
FI constexpr XYval<T> operator+ (const XYZval<T> &rs) const { return { XY_OP(+) }; }
FI constexpr XYval<T> operator- (const XYZval<T> &rs) const { return { XY_OP(-) }; }
FI constexpr XYval<T> operator* (const XYZval<T> &rs) const { return { XY_OP(*) }; }
FI constexpr XYval<T> operator/ (const XYZval<T> &rs) const { return { XY_OP(/) }; }
FI constexpr XYval<T> operator+ (const XYZEval<T> &rs) const { return { XY_OP(+) }; }
FI constexpr XYval<T> operator- (const XYZEval<T> &rs) const { return { XY_OP(-) }; }
FI constexpr XYval<T> operator* (const XYZEval<T> &rs) const { return { XY_OP(*) }; }
FI constexpr XYval<T> operator/ (const XYZEval<T> &rs) const { return { XY_OP(/) }; }
FI constexpr XYval<T> operator* (const float &p) const { return { (T)(x * p), (T)(y * p) }; }
FI constexpr XYval<T> operator* (const int &p) const { return { x * p, y * p }; }
FI constexpr XYval<T> operator/ (const float &p) const { return { (T)(x / p), (T)(y / p) }; }
FI constexpr XYval<T> operator/ (const int &p) const { return { x / p, y / p }; }
FI constexpr XYval<T> operator>>(const int &p) const { return { _RS(x), _RS(y) }; }
FI constexpr XYval<T> operator<<(const int &p) const { return { _LS(x), _LS(y) }; }
FI constexpr XYval<T> operator-() const { return { -x, -y }; }
#undef XY_OP
// 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 XYval<T> &rs) { x /= rs.x; y /= rs.y; return *this; }
FI XYval<T>& operator+=(const XYZval<T> &rs) { XY_CODE(x += rs.x, y += rs.y); return *this; }
FI XYval<T>& operator-=(const XYZval<T> &rs) { XY_CODE(x -= rs.x, y -= rs.y); return *this; }
FI XYval<T>& operator*=(const XYZval<T> &rs) { XY_CODE(x *= rs.x, y *= rs.y); return *this; }
FI XYval<T>& operator/=(const XYZval<T> &rs) { XY_CODE(x /= rs.x, y /= rs.y); return *this; }
FI XYval<T>& operator+=(const XYZEval<T> &rs) { XY_CODE(x += rs.x, y += rs.y); return *this; }
FI XYval<T>& operator-=(const XYZEval<T> &rs) { XY_CODE(x -= rs.x, y -= rs.y); return *this; }
FI XYval<T>& operator*=(const XYZEval<T> &rs) { XY_CODE(x *= rs.x, y *= rs.y); return *this; }
FI XYval<T>& operator/=(const XYZEval<T> &rs) { XY_CODE(x /= rs.x, y /= rs.y); return *this; }
FI XYval<T>& operator*=(const float &p) { x *= p; y *= p; return *this; }
FI XYval<T>& operator*=(const int &p) { x *= p; y *= p; return *this; }
FI XYval<T>& operator>>=(const int &p) { _RSE(x); _RSE(y); return *this; }
FI XYval<T>& operator<<=(const int &p) { _LSE(x); _LSE(y); return *this; }
// Absolute difference between two objects
FI constexpr XYval<T> diff(const XYZEval<T> &rs) const { return { TERN(HAS_X_AXIS, T(_ABS(x - rs.x)), x), TERN(HAS_Y_AXIS, T(_ABS(y - rs.y)), y) }; }
FI constexpr XYval<T> diff(const XYZval<T> &rs) const { return { TERN(HAS_X_AXIS, T(_ABS(x - rs.x)), x), TERN(HAS_Y_AXIS, T(_ABS(y - rs.y)), y) }; }
FI constexpr XYval<T> diff(const XYval<T> &rs) const { return { T(_ABS(x - rs.x)), T(_ABS(y - rs.y)) }; }
// Exact comparisons. For floats a "NEAR" operation may be better.
FI bool operator==(const XYval<T> &rs) const { return x == rs.x && y == rs.y; }
FI bool operator==(const XYZval<T> &rs) const { return ENABLED(HAS_X_AXIS) XY_GANG(&& x == rs.x, && y == rs.y); }
FI bool operator==(const XYZEval<T> &rs) const { return ENABLED(HAS_X_AXIS) XY_GANG(&& x == rs.x, && y == rs.y); }
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.
// May have any number of axes according to configuration, including zero axes.
//
template<typename T>
struct XYZval {
union {
#if NUM_AXES
struct { NUM_AXIS_CODE(T x, T y, T z, T i, T j, T k, T u, T v, T w); };
struct { NUM_AXIS_CODE(T a, T b, T c, T _i, T _j, T _k, T _u, T _v, T _w); };
#endif
T pos[NUM_AXES];
};
// Set all to 0
FI void reset() { NUM_AXIS_CODE(x = 0, y = 0, z = 0, i = 0, j = 0, k = 0, u = 0, v = 0, w = 0); }
// Setters taking struct types and arrays
FI void set(const XYval<T> pxy) { XY_CODE(x = pxy.x, y = pxy.y); }
FI void set(const XYval<T> pxy, const T pz) { XYZ_CODE(x = pxy.x, y = pxy.y, z = pz); }
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], u = arr[6], v = arr[7], w = arr[8]); }
#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], u = arr[6], v = arr[7], w = arr[8]); }
FI void set(LOGICAL_AXIS_ARGS(const T)) { NUM_AXIS_CODE(a = x, b = y, c = z, _i = i, _j = j, _k = k, _u = u, _v = v, _w = w); }
#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], u = arr[6], v = arr[7], w = arr[8]); }
#endif
#endif
// Setter for all individual args
FI void set(NUM_AXIS_ARGS(const T)) { NUM_AXIS_CODE(a = x, b = y, c = z, _i = i, _j = j, _k = k, _u = u, _v = v, _w = w); }
// Setters with fewer elements leave the rest untouched
#if HAS_Y_AXIS
FI void set(const T px) { x = px; }
#endif
#if HAS_Z_AXIS
FI void set(const T px, const T py) { x = px; y = py; }
#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
#if HAS_U_AXIS
FI void set(const T px, const T py, const T pz, const T pi, const T pj, const T pk) { x = px; y = py; z = pz; i = pi; j = pj; k = pk; }
#endif
#if HAS_V_AXIS
FI void set(const T px, const T py, const T pz, const T pi, const T pj, const T pk, const T pu) { x = px; y = py; z = pz; i = pi; j = pj; k = pk; u = pu; }
#endif
#if HAS_W_AXIS
FI void set(const T px, const T py, const T pz, const T pi, const T pj, const T pk, const T pu, const T pv) { x = px; y = py; z = pz; i = pi; j = pj; k = pk; u = pu; v = pv; }
#endif
// Length reduced to one dimension
FI constexpr T magnitude() const { return (T)TERN(HAS_X_AXIS, sqrtf(NUM_AXIS_GANG(x*x, + y*y, + z*z, + i*i, + j*j, + k*k, + u*u, + v*v, + w*w)), 0); }
// Pointer to the data as a simple array
explicit FI operator T* () { return pos; }
// If any element is true then it's true
FI constexpr operator bool() const { return 0 NUM_AXIS_GANG(|| x, || y, || z, || i, || j, || k, || u, || v, || w); }
// Smallest element
FI constexpr T small() const { return TERN(HAS_X_AXIS, _MIN(NUM_AXIS_LIST(x, y, z, i, j, k, u, v, w)), 0); }
// Largest element
FI constexpr T large() const { return TERN(HAS_X_AXIS, _MAX(NUM_AXIS_LIST(x, y, z, i, j, k, u, v, w)), 0); }
// Explicit copy and copies with conversion
FI constexpr XYZval<T> copy() const { XYZval<T> o = *this; return o; }
FI constexpr 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)), T(_ABS(u)), T(_ABS(v)), T(_ABS(w))); }
FI constexpr 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), int16_t(u), int16_t(v), int16_t(w)); }
FI constexpr 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), int32_t(u), int32_t(v), int32_t(w)); }
FI constexpr 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)), int32_t(LROUND(u)), int32_t(LROUND(v)), int32_t(LROUND(w))); }
FI constexpr 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), static_cast<float>(u), static_cast<float>(v), static_cast<float>(w)); }
FI constexpr XYZval<float> reciprocal() const { return NUM_AXIS_ARRAY(_RECIP(x), _RECIP(y), _RECIP(z), _RECIP(i), _RECIP(j), _RECIP(k), _RECIP(u), _RECIP(v), _RECIP(w)); }
// 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 constexpr operator XYZEval<T>() const { return NUM_AXIS_ARRAY(x, y, z, i, j, k, u, v, w); }
// 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 constexpr XYZval<T> operator+ (const XYval<T> &rs) const { return NUM_AXIS_ARRAY(x + rs.x, y + rs.y, z, i, j, k, u, v, w ); }
FI constexpr XYZval<T> operator- (const XYval<T> &rs) const { return NUM_AXIS_ARRAY(x - rs.x, y - rs.y, z, i, j, k, u, v, w ); }
FI constexpr XYZval<T> operator* (const XYval<T> &rs) const { return NUM_AXIS_ARRAY(x * rs.x, y * rs.y, z, i, j, k, u, v, w ); }
FI constexpr XYZval<T> operator/ (const XYval<T> &rs) const { return NUM_AXIS_ARRAY(x / rs.x, y / rs.y, z, i, j, k, u, v, w ); }
FI constexpr XYZval<T> operator+ (const XYZval<T> &rs) const { return NUM_AXIS_ARRAY(x + rs.x, y + rs.y, z + rs.z, i + rs.i, j + rs.j, k + rs.k, u + rs.u, v + rs.v, w + rs.w ); }
FI constexpr XYZval<T> operator- (const XYZval<T> &rs) const { return NUM_AXIS_ARRAY(x - rs.x, y - rs.y, z - rs.z, i - rs.i, j - rs.j, k - rs.k, u - rs.u, v - rs.v, w - rs.w ); }
FI constexpr XYZval<T> operator* (const XYZval<T> &rs) const { return NUM_AXIS_ARRAY(x * rs.x, y * rs.y, z * rs.z, i * rs.i, j * rs.j, k * rs.k, u * rs.u, v * rs.v, w * rs.w ); }
FI constexpr XYZval<T> operator/ (const XYZval<T> &rs) const { return NUM_AXIS_ARRAY(x / rs.x, y / rs.y, z / rs.z, i / rs.i, j / rs.j, k / rs.k, u / rs.u, v / rs.v, w / rs.w ); }
FI constexpr XYZval<T> operator+ (const XYZEval<T> &rs) const { return NUM_AXIS_ARRAY(x + rs.x, y + rs.y, z + rs.z, i + rs.i, j + rs.j, k + rs.k, u + rs.u, v + rs.v, w + rs.w ); }
FI constexpr XYZval<T> operator- (const XYZEval<T> &rs) const { return NUM_AXIS_ARRAY(x - rs.x, y - rs.y, z - rs.z, i - rs.i, j - rs.j, k - rs.k, u - rs.u, v - rs.v, w - rs.w ); }
FI constexpr XYZval<T> operator* (const XYZEval<T> &rs) const { return NUM_AXIS_ARRAY(x * rs.x, y * rs.y, z * rs.z, i * rs.i, j * rs.j, k * rs.k, u * rs.u, v * rs.v, w * rs.w ); }
FI constexpr XYZval<T> operator/ (const XYZEval<T> &rs) const { return NUM_AXIS_ARRAY(x / rs.x, y / rs.y, z / rs.z, i / rs.i, j / rs.j, k / rs.k, u / rs.u, v / rs.v, w / rs.w ); }
FI constexpr XYZval<T> operator* (const float &p) const { return NUM_AXIS_ARRAY((T)(x * p), (T)(y * p), (T)(z * p), (T)(i * p), (T)(j * p), (T)(k * p), (T)(u * p), (T)(v * p), (T)(w * p)); }
FI constexpr XYZval<T> operator* (const int &p) const { return NUM_AXIS_ARRAY(x * p, y * p, z * p, i * p, j * p, k * p, u * p, v * p, w * p); }
FI constexpr XYZval<T> operator/ (const float &p) const { return NUM_AXIS_ARRAY((T)(x / p), (T)(y / p), (T)(z / p), (T)(i / p), (T)(j / p), (T)(k / p), (T)(u / p), (T)(v / p), (T)(w / p)); }
FI constexpr XYZval<T> operator/ (const int &p) const { return NUM_AXIS_ARRAY(x / p, y / p, z / p, i / p, j / p, k / p, u / p, v / p, w / p); }
FI constexpr XYZval<T> operator>>(const int &p) const { return NUM_AXIS_ARRAY(_RS(x), _RS(y), _RS(z), _RS(i), _RS(j), _RS(k), _RS(u), _RS(v), _RS(w)); }
FI constexpr XYZval<T> operator<<(const int &p) const { return NUM_AXIS_ARRAY(_LS(x), _LS(y), _LS(z), _LS(i), _LS(j), _LS(k), _LS(u), _LS(v), _LS(w)); }
FI constexpr XYZval<T> operator-() const { return NUM_AXIS_ARRAY(-x, -y, -z, -i, -j, -k, -u, -v, -w); }
// Absolute difference between two objects
FI constexpr XYZval<T> diff(const XYZEval<T> &rs) const { return NUM_AXIS_ARRAY(T(_ABS(x - rs.x)), T(_ABS(y - rs.y)), T(_ABS(z - rs.z)), T(_ABS(i - rs.i)), T(_ABS(j - rs.j)), T(_ABS(k - rs.k)), T(_ABS(u - rs.u)), T(_ABS(v - rs.v)), T(_ABS(w - rs.w)) ); }
FI constexpr XYZval<T> diff(const XYZval<T> &rs) const { return NUM_AXIS_ARRAY(T(_ABS(x - rs.x)), T(_ABS(y - rs.y)), T(_ABS(z - rs.z)), T(_ABS(i - rs.i)), T(_ABS(j - rs.j)), T(_ABS(k - rs.k)), T(_ABS(u - rs.u)), T(_ABS(v - rs.v)), T(_ABS(w - rs.w)) ); }
FI constexpr XYZval<T> diff(const XYval<T> &rs) const { return NUM_AXIS_ARRAY(T(_ABS(x - rs.x)), T(_ABS(y - rs.y)), z, i, j, k, u, v, w ); }
// Modifier operators
FI XYZval<T>& operator+=(const XYval<T> &rs) { XY_CODE(x += rs.x, y += rs.y); return *this; }
FI XYZval<T>& operator-=(const XYval<T> &rs) { XY_CODE(x -= rs.x, y -= rs.y); return *this; }
FI XYZval<T>& operator*=(const XYval<T> &rs) { XY_CODE(x *= rs.x, y *= rs.y); return *this; }
FI XYZval<T>& operator/=(const XYval<T> &rs) { XY_CODE(x /= rs.x, y /= rs.y); 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, u += rs.u, v += rs.v, w += rs.w); 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, u -= rs.u, v -= rs.v, w -= rs.w); 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, u *= rs.u, v *= rs.v, w *= rs.w); 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, u /= rs.u, v /= rs.v, w /= rs.w); 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, u += rs.u, v += rs.v, w += rs.w); 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, u -= rs.u, v -= rs.v, w -= rs.w); 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, u *= rs.u, v *= rs.v, w *= rs.w); 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, u /= rs.u, v /= rs.v, w /= rs.w); return *this; }
FI XYZval<T>& operator*=(const float &p) { NUM_AXIS_CODE(x *= p, y *= p, z *= p, i *= p, j *= p, k *= p, u *= p, v *= p, w *= p); return *this; }
FI XYZval<T>& operator*=(const int &p) { NUM_AXIS_CODE(x *= p, y *= p, z *= p, i *= p, j *= p, k *= p, u *= p, v *= p, w *= p); return *this; }
FI XYZval<T>& operator>>=(const int &p) { NUM_AXIS_CODE(_RSE(x), _RSE(y), _RSE(z), _RSE(i), _RSE(j), _RSE(k), _RSE(u), _RSE(v), _RSE(w)); return *this; }
FI XYZval<T>& operator<<=(const int &p) { NUM_AXIS_CODE(_LSE(x), _LSE(y), _LSE(z), _LSE(i), _LSE(j), _LSE(k), _LSE(u), _LSE(v), _LSE(w)); return *this; }
// Exact comparisons. For floats a "NEAR" operation may be better.
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, && u == rs.u, && v == rs.v, && w == rs.w); }
FI bool operator!=(const XYZEval<T> &rs) const { return !operator==(rs); }
};
//
// Logical Axes coordinates, counters, etc.
// May have any number of axes according to configuration, including zero axes.
// When there is no extruder, essentially identical to XYZval.
//
template<typename T>
struct XYZEval {
union {
struct { T LOGICAL_AXIS_ARGS(); };
struct { T LOGICAL_AXIS_LIST(_e, a, b, c, _i, _j, _k, _u, _v, _w); };
T pos[LOGICAL_AXES];
};
// Reset all to 0
FI void reset() { LOGICAL_AXIS_GANG(e =, x =, y =, z =, i =, j =, k =, u =, v =, w =) 0; }
// Setters taking struct types and arrays
FI void set(const XYval<T> pxy) { XY_CODE(x = pxy.x, y = pxy.y); }
FI void set(const XYval<T> pxy, const T pz) { XYZ_CODE(x = pxy.x, y = pxy.y, z = pz); }
FI void set(const XYZval<T> pxyz) { set(NUM_AXIS_ELEM(pxyz)); }
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], u = arr[6], v = arr[7], w = arr[8]); }
#if LOGICAL_AXES > NUM_AXES
FI void set(const T (&arr)[LOGICAL_AXES]) { LOGICAL_AXIS_CODE(e = arr[LOGICAL_AXES-1], x = arr[0], y = arr[1], z = arr[2], i = arr[3], j = arr[4], k = arr[5], u = arr[6], v = arr[7], w = arr[8]); }
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, _u = u, _v = v, _w = w); }
#if DISTINCT_AXES > LOGICAL_AXES
FI void set(const T (&arr)[DISTINCT_AXES]) { LOGICAL_AXIS_CODE(e = arr[LOGICAL_AXES-1], x = arr[0], y = arr[1], z = arr[2], i = arr[3], j = arr[4], k = arr[5], u = arr[6], v = arr[7], w = arr[8]); }
#endif
#endif
// Setter for all individual args
FI void set(NUM_AXIS_ARGS(const T)) { NUM_AXIS_CODE(a = x, b = y, c = z, _i = i, _j = j, _k = k, _u = u, _v = v, _w = w); }
// Setters with fewer elements leave the rest untouched
#if HAS_Y_AXIS
FI void set(const T px) { x = px; }
#endif
#if HAS_Z_AXIS
FI void set(const T px, const T py) { x = px; y = py; }
#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
#if HAS_U_AXIS
FI void set(const T px, const T py, const T pz, const T pi, const T pj, const T pk) { x = px; y = py; z = pz; i = pi; j = pj; k = pk; }
#endif
#if HAS_V_AXIS
FI void set(const T px, const T py, const T pz, const T pi, const T pj, const T pk, const T pu) { x = px; y = py; z = pz; i = pi; j = pj; k = pk; u = pu; }
#endif
#if HAS_W_AXIS
FI void set(const T px, const T py, const T pz, const T pi, const T pj, const T pk, const T pu, const T pv) { x = px; y = py; z = pz; i = pi; j = pj; k = pk; u = pu; v = pv; }
#endif
// Length reduced to one dimension
FI constexpr T magnitude() const { return (T)sqrtf(LOGICAL_AXIS_GANG(+ e*e, + x*x, + y*y, + z*z, + i*i, + j*j, + k*k, + u*u, + v*v, + w*w)); }
// Pointer to the data as a simple array
explicit FI operator T* () { return pos; }
// If any element is true then it's true
FI constexpr operator bool() const { return 0 LOGICAL_AXIS_GANG(|| e, || x, || y, || z, || i, || j, || k, || u, || v, || w); }
// Smallest element
FI constexpr T small() const { return _MIN(LOGICAL_AXIS_LIST(e, x, y, z, i, j, k, u, v, w)); }
// Largest element
FI constexpr T large() const { return _MAX(LOGICAL_AXIS_LIST(e, x, y, z, i, j, k, u, v, w)); }
// Explicit copy and copies with conversion
FI constexpr XYZEval<T> copy() const { XYZEval<T> v = *this; return v; }
FI constexpr 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)), T(_ABS(u)), T(_ABS(v)), T(_ABS(w))); }
FI constexpr 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), int16_t(u), int16_t(v), int16_t(w)); }
FI constexpr 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), int32_t(u), int32_t(v), int32_t(w)); }
FI constexpr 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)), int32_t(LROUND(u)), int32_t(LROUND(v)), int32_t(LROUND(w))); }
FI constexpr 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), static_cast<float>(u), static_cast<float>(v), static_cast<float>(w)); }
FI constexpr XYZEval<float> reciprocal() const { return LOGICAL_AXIS_ARRAY(_RECIP(e), _RECIP(x), _RECIP(y), _RECIP(z), _RECIP(i), _RECIP(j), _RECIP(k), _RECIP(u), _RECIP(v), _RECIP(w)); }
// 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 constexpr XYZEval<T> operator+ (const XYval<T> &rs) const { return LOGICAL_AXIS_ARRAY(e, x + rs.x, y + rs.y, z, i, j, k, u, v, w); }
FI constexpr XYZEval<T> operator- (const XYval<T> &rs) const { return LOGICAL_AXIS_ARRAY(e, x - rs.x, y - rs.y, z, i, j, k, u, v, w); }
FI constexpr XYZEval<T> operator* (const XYval<T> &rs) const { return LOGICAL_AXIS_ARRAY(e, x * rs.x, y * rs.y, z, i, j, k, u, v, w); }
FI constexpr XYZEval<T> operator/ (const XYval<T> &rs) const { return LOGICAL_AXIS_ARRAY(e, x / rs.x, y / rs.y, z, i, j, k, u, v, w); }
FI constexpr XYZEval<T> operator+ (const XYZval<T> &rs) const { return LOGICAL_AXIS_ARRAY(e, x + rs.x, y + rs.y, z + rs.z, i + rs.i, j + rs.j, k + rs.k, u + rs.u, v + rs.v, w + rs.w); }
FI constexpr XYZEval<T> operator- (const XYZval<T> &rs) const { return LOGICAL_AXIS_ARRAY(e, x - rs.x, y - rs.y, z - rs.z, i - rs.i, j - rs.j, k - rs.k, u - rs.u, v - rs.v, w - rs.w); }
FI constexpr XYZEval<T> operator* (const XYZval<T> &rs) const { return LOGICAL_AXIS_ARRAY(e, x * rs.x, y * rs.y, z * rs.z, i * rs.i, j * rs.j, k * rs.k, u * rs.u, v * rs.v, w * rs.w); }
FI constexpr XYZEval<T> operator/ (const XYZval<T> &rs) const { return LOGICAL_AXIS_ARRAY(e, x / rs.x, y / rs.y, z / rs.z, i / rs.i, j / rs.j, k / rs.k, u / rs.u, v / rs.v, w / rs.w); }
FI constexpr XYZEval<T> operator+ (const XYZEval<T> &rs) const { return LOGICAL_AXIS_ARRAY(e + rs.e, x + rs.x, y + rs.y, z + rs.z, i + rs.i, j + rs.j, k + rs.k, u + rs.u, v + rs.v, w + rs.w); }
FI constexpr XYZEval<T> operator- (const XYZEval<T> &rs) const { return LOGICAL_AXIS_ARRAY(e - rs.e, x - rs.x, y - rs.y, z - rs.z, i - rs.i, j - rs.j, k - rs.k, u - rs.u, v - rs.v, w - rs.w); }
FI constexpr XYZEval<T> operator* (const XYZEval<T> &rs) const { return LOGICAL_AXIS_ARRAY(e * rs.e, x * rs.x, y * rs.y, z * rs.z, i * rs.i, j * rs.j, k * rs.k, u * rs.u, v * rs.v, w * rs.w); }
FI constexpr XYZEval<T> operator/ (const XYZEval<T> &rs) const { return LOGICAL_AXIS_ARRAY(e / rs.e, x / rs.x, y / rs.y, z / rs.z, i / rs.i, j / rs.j, k / rs.k, u / rs.u, v / rs.v, w / rs.w); }
FI constexpr XYZEval<T> operator* (const float &p) const { return LOGICAL_AXIS_ARRAY((T)(e * p), (T)(x * p), (T)(y * p), (T)(z * p), (T)(i * p), (T)(j * p), (T)(k * p), (T)(u * p), (T)(v * p), (T)(w * p)); }
FI constexpr XYZEval<T> operator* (const int &p) const { return LOGICAL_AXIS_ARRAY(e * p, x * p, y * p, z * p, i * p, j * p, k * p, u * p, v * p, w * p); }
FI constexpr XYZEval<T> operator/ (const float &p) const { return LOGICAL_AXIS_ARRAY((T)(e / p), (T)(x / p), (T)(y / p), (T)(z / p), (T)(i / p), (T)(j / p), (T)(k / p), (T)(u / p), (T)(v / p), (T)(w / p)); }
FI constexpr XYZEval<T> operator/ (const int &p) const { return LOGICAL_AXIS_ARRAY(e / p, x / p, y / p, z / p, i / p, j / p, k / p, u / p, v / p, w / p); }
FI constexpr XYZEval<T> operator>>(const int &p) const { return LOGICAL_AXIS_ARRAY(_RS(e), _RS(x), _RS(y), _RS(z), _RS(i), _RS(j), _RS(k), _RS(u), _RS(v), _RS(w)); }
FI constexpr XYZEval<T> operator<<(const int &p) const { return LOGICAL_AXIS_ARRAY(_LS(e), _LS(x), _LS(y), _LS(z), _LS(i), _LS(j), _LS(k), _LS(u), _LS(v), _LS(w)); }
FI constexpr XYZEval<T> operator-() const { return LOGICAL_AXIS_ARRAY(-e, -x, -y, -z, -i, -j, -k, -u, -v, -w); }
// Absolute difference between two objects
FI constexpr XYZEval<T> diff(const XYZEval<T> &rs) const { return LOGICAL_AXIS_ARRAY(T(_ABS(e - rs.e)), T(_ABS(x - rs.x)), T(_ABS(y - rs.y)), T(_ABS(z - rs.z)), T(_ABS(i - rs.i)), T(_ABS(j - rs.j)), T(_ABS(k - rs.k)), T(_ABS(u - rs.u)), T(_ABS(v - rs.v)), T(_ABS(w - rs.w)) ); }
FI constexpr XYZEval<T> diff(const XYZval<T> &rs) const { return LOGICAL_AXIS_ARRAY(0 , T(_ABS(x - rs.x)), T(_ABS(y - rs.y)), T(_ABS(z - rs.z)), T(_ABS(i - rs.i)), T(_ABS(j - rs.j)), T(_ABS(k - rs.k)), T(_ABS(u - rs.u)), T(_ABS(v - rs.v)), T(_ABS(w - rs.w)) ); }
FI constexpr XYZEval<T> diff(const XYval<T> &rs) const { return LOGICAL_AXIS_ARRAY(0 , T(_ABS(x - rs.x)), T(_ABS(y - rs.y)), z, i, j, k, u, v, w ); }
// Modifier operators
FI XYZEval<T>& operator+=(const XYval<T> &rs) { XY_CODE(x += rs.x, y += rs.y); return *this; }
FI XYZEval<T>& operator-=(const XYval<T> &rs) { XY_CODE(x -= rs.x, y -= rs.y); return *this; }
FI XYZEval<T>& operator*=(const XYval<T> &rs) { XY_CODE(x *= rs.x, y *= rs.y); return *this; }
FI XYZEval<T>& operator/=(const XYval<T> &rs) { XY_CODE(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, u += rs.u, v += rs.v, w += rs.w); 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, u -= rs.u, v -= rs.v, w -= rs.w); 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, u *= rs.u, v *= rs.v, w *= rs.w); 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, u /= rs.u, v /= rs.v, w /= rs.w); 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, u += rs.u, v += rs.v, w += rs.w); 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, u -= rs.u, v -= rs.v, w -= rs.w); 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, u *= rs.u, v *= rs.v, w *= rs.w); 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, u /= rs.u, v /= rs.v, w /= rs.w); return *this; }
FI XYZEval<T>& operator*=(const T &p) { LOGICAL_AXIS_CODE(e *= p, x *= p, y *= p, z *= p, i *= p, j *= p, k *= p, u *= p, v *= p, w *= p); return *this; }
FI XYZEval<T>& operator>>=(const int &p) { LOGICAL_AXIS_CODE(_RSE(e), _RSE(x), _RSE(y), _RSE(z), _RSE(i), _RSE(j), _RSE(k), _RSE(u), _RSE(v), _RSE(w)); return *this; }
FI XYZEval<T>& operator<<=(const int &p) { LOGICAL_AXIS_CODE(_LSE(e), _LSE(x), _LSE(y), _LSE(z), _LSE(i), _LSE(j), _LSE(k), _LSE(u), _LSE(v), _LSE(w)); return *this; }
// Exact comparisons. For floats a "NEAR" operation may be better.
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, && u == rs.u, && v == rs.v, && w == rs.w); }
FI bool operator==(const XYZEval<T> &rs) const { return true LOGICAL_AXIS_GANG(&& e == rs.e, && x == rs.x, && y == rs.y, && z == rs.z, && i == rs.i, && j == rs.j, && k == rs.k, && u == rs.u, && v == rs.v, && w == rs.w); }
FI bool operator!=(const XYZval<T> &rs) const { return !operator==(rs); }
FI bool operator!=(const XYZEval<T> &rs) const { return !operator==(rs); }
};
#include <string.h> // for memset
template<typename T, int SIZE>
struct XYZarray {
typedef T el[SIZE];
union {
el data[LOGICAL_AXES];
struct { NUM_AXIS_CODE(T x, T y, T z, T i, T j, T k, T u, T v, T w); };
struct { NUM_AXIS_CODE(T a, T b, T c, T _i, T _j, T _k, T _u, T _v, T _w); };
};
FI void reset() { ZERO(data); }
FI void set(const int n, const XYval<T> p) { NUM_AXIS_CODE(x[n]=p.x, y[n]=p.y,,,,,,,); }
FI void set(const int n, const XYZval<T> p) { NUM_AXIS_CODE(x[n]=p.x, y[n]=p.y, z[n]=p.z, i[n]=p.i, j[n]=p.j, k[n]=p.k, u[n]=p.u, v[n]=p.v, w[n]=p.w ); }
FI void set(const int n, const XYZEval<T> p) { NUM_AXIS_CODE(x[n]=p.x, y[n]=p.y, z[n]=p.z, i[n]=p.i, j[n]=p.j, k[n]=p.k, u[n]=p.u, v[n]=p.v, w[n]=p.w ); }
// Setter for all individual args
FI void set(const int n OPTARGS_NUM(const T)) { NUM_AXIS_CODE(a[n] = x, b[n] = y, c[n] = z, _i[n] = i, _j[n] = j, _k[n] = k, _u[n] = u, _v[n] = v, _w[n] = w); }
// Setters with fewer elements leave the rest untouched
#if HAS_Y_AXIS
FI void set(const int n, const T px) { x[n] = px; }
#endif
#if HAS_Z_AXIS
FI void set(const int n, const T px, const T py) { x[n] = px; y[n] = py; }
#endif
#if HAS_I_AXIS
FI void set(const int n, const T px, const T py, const T pz) { x[n] = px; y[n] = py; z[n] = pz; }
#endif
#if HAS_J_AXIS
FI void set(const int n, const T px, const T py, const T pz, const T pi) { x[n] = px; y[n] = py; z[n] = pz; i[n] = pi; }
#endif
#if HAS_K_AXIS
FI void set(const int n, const T px, const T py, const T pz, const T pi, const T pj) { x[n] = px; y[n] = py; z[n] = pz; i[n] = pi; j[n] = pj; }
#endif
#if HAS_U_AXIS
FI void set(const int n, const T px, const T py, const T pz, const T pi, const T pj, const T pk) { x[n] = px; y[n] = py; z[n] = pz; i[n] = pi; j[n] = pj; k[n] = pk; }
#endif
#if HAS_V_AXIS
FI void set(const int n, const T px, const T py, const T pz, const T pi, const T pj, const T pk, const T pu) { x[n] = px; y[n] = py; z[n] = pz; i[n] = pi; j[n] = pj; k[n] = pk; u[n] = pu; }
#endif
#if HAS_W_AXIS
FI void set(const int n, const T px, const T py, const T pz, const T pi, const T pj, const T pk, const T pu, const T pv) { x[n] = px; y[n] = py; z[n] = pz; i[n] = pi; j[n] = pj; k[n] = pk; u[n] = pu; v[n] = pv; }
#endif
FI XYZval<T> operator[](const int n) const { return XYZval<T>(NUM_AXIS_ARRAY(x[n], y[n], z[n], i[n], j[n], k[n], u[n], v[n], w[n])); }
};
template<typename T, int SIZE>
struct XYZEarray {
typedef T el[SIZE];
union {
el data[LOGICAL_AXES];
struct { el LOGICAL_AXIS_ARGS(); };
struct { el LOGICAL_AXIS_LIST(_e, a, b, c, _i, _j, _k, _u, _v, _w); };
};
FI void reset() { ZERO(data); }
FI void set(const int n, const XYval<T> p) { NUM_AXIS_CODE(x[n]=p.x, y[n]=p.y,,,,,,,); }
FI void set(const int n, const XYZval<T> p) { NUM_AXIS_CODE(x[n]=p.x, y[n]=p.y, z[n]=p.z, i[n]=p.i, j[n]=p.j, k[n]=p.k, u[n]=p.u, v[n]=p.v, w[n]=p.w ); }
FI void set(const int n, const XYZEval<T> p) { LOGICAL_AXIS_CODE(e[n]=p.e, x[n]=p.x, y[n]=p.y, z[n]=p.z, i[n]=p.i, j[n]=p.j, k[n]=p.k, u[n]=p.u, v[n]=p.v, w[n]=p.w ); }
// Setter for all individual args
FI void set(const int n OPTARGS_NUM(const T)) { NUM_AXIS_CODE(a[n] = x, b[n] = y, c[n] = z, _i[n] = i, _j[n] = j, _k[n] = k, _u[n] = u, _v[n] = v, _w[n] = w); }
#if LOGICAL_AXES > NUM_AXES
FI void set(const int n, LOGICAL_AXIS_ARGS(const T)) { LOGICAL_AXIS_CODE(_e[n] = e, a[n] = x, b[n] = y, c[n] = z, _i[n] = i, _j[n] = j, _k[n] = k, _u[n] = u, _v[n] = v, _w[n] = w); }
#endif
// Setters with fewer elements leave the rest untouched
#if HAS_Y_AXIS
FI void set(const int n, const T px) { x[n] = px; }
#endif
#if HAS_Z_AXIS
FI void set(const int n, const T px, const T py) { x[n] = px; y[n] = py; }
#endif
#if HAS_I_AXIS
FI void set(const int n, const T px, const T py, const T pz) { x[n] = px; y[n] = py; z[n] = pz; }
#endif
#if HAS_J_AXIS
FI void set(const int n, const T px, const T py, const T pz, const T pi) { x[n] = px; y[n] = py; z[n] = pz; i[n] = pi; }
#endif
#if HAS_K_AXIS
FI void set(const int n, const T px, const T py, const T pz, const T pi, const T pj) { x[n] = px; y[n] = py; z[n] = pz; i[n] = pi; j[n] = pj; }
#endif
#if HAS_U_AXIS
FI void set(const int n, const T px, const T py, const T pz, const T pi, const T pj, const T pk) { x[n] = px; y[n] = py; z[n] = pz; i[n] = pi; j[n] = pj; k[n] = pk; }
#endif
#if HAS_V_AXIS
FI void set(const int n, const T px, const T py, const T pz, const T pi, const T pj, const T pk, const T pu) { x[n] = px; y[n] = py; z[n] = pz; i[n] = pi; j[n] = pj; k[n] = pk; u[n] = pu; }
#endif
#if HAS_W_AXIS
FI void set(const int n, const T px, const T py, const T pz, const T pi, const T pj, const T pk, const T pu, const T pv) { x[n] = px; y[n] = py; z[n] = pz; i[n] = pi; j[n] = pj; k[n] = pk; u[n] = pu; v[n] = pv; }
#endif
FI XYZEval<T> operator[](const int n) const { return XYZval<T>(LOGICAL_AXIS_ARRAY(e[n], x[n], y[n], z[n], i[n], j[n], k[n], u[n], v[n], w[n])); }
};
class AxisBits;
class AxisBits {
public:
typedef bits_t(NUM_AXIS_ENUMS) el;
union {
el bits;
// Axes x, y, z ... e0, e1, e2 ... hx, hy, hz
struct {
#if NUM_AXES
bool NUM_AXIS_LIST(x:1, y:1, z:1, i:1, j:1, k:1, u:1, v:1, w:1);
#endif
#define _EN_ITEM(N) bool e##N:1;
REPEAT(EXTRUDERS,_EN_ITEM)
#undef _EN_ITEM
#if ANY(IS_CORE, MARKFORGED_XY, MARKFORGED_YX)
bool hx:1, hy:1, hz:1;
#endif
};
// Axes X, Y, Z ... E0, E1, E2 ... HX, HY, HZ
struct {
#if NUM_AXES
bool NUM_AXIS_LIST(X:1, Y:1, Z:1, I:1, J:1, K:1, U:1, V:1, W:1);
#endif
#define _EN_ITEM(N) bool E##N:1;
REPEAT(EXTRUDERS,_EN_ITEM)
#undef _EN_ITEM
#if ANY(IS_CORE, MARKFORGED_XY, MARKFORGED_YX)
bool HX:1, HY:1, HZ:1;
#endif
};
// a, b, c, e ... ha, hb, hc
struct {
bool LOGICAL_AXIS_LIST(e:1, a:1, b:1, c:1, ii:1, jj:1, kk:1, uu:1, vv:1, ww:1);
#if EXTRUDERS > 1
#define _EN_ITEM(N) bool _e##N:1;
REPEAT_S(1,EXTRUDERS,_EN_ITEM)
#undef _EN_ITEM
#endif
#if ANY(IS_CORE, MARKFORGED_XY, MARKFORGED_YX)
bool ha:1, hb:1, hc:1;
#endif
};
// A, B, C, E ... HA, HB, HC
struct {
bool LOGICAL_AXIS_LIST(E:1, A:1, B:1, C:1, II:1, JJ:1, KK:1, UU:1, VV:1, WW:1);
#if EXTRUDERS > 1
#define _EN_ITEM(N) bool _E##N:1;
REPEAT_S(1,EXTRUDERS,_EN_ITEM)
#undef _EN_ITEM
#endif
#if ANY(IS_CORE, MARKFORGED_XY, MARKFORGED_YX)
bool HA:1, HB:1, HC:1;
#endif
};
};
AxisBits() { reset(); }
// Constructor, setter, and operator= for bit mask
AxisBits(const el p) { set(p); }
FI void set(const el p) { bits = el(p); }
FI AxisBits& operator=(const el p) { set(p); return *this; }
FI void reset() { set(0); }
FI void fill() { set(_BV(NUM_AXIS_ENUMS) - 1); }
#define MSET(pE,pX,pY,pZ,pI,pJ,pK,pU,pV,pW) LOGICAL_AXIS_CODE(e=pE, x=pX, y=pY, z=pZ, i=pI, j=pJ, k=pK, u=pU, v=pV, w=pW)
// Constructor, setter, and operator= for XYZE type
AxisBits(const xyze_bool_t &p) { set(p); }
FI void set(const xyze_bool_t &p) {
MSET(p.e, p.x, p.y, p.z, p.i, p.j, p.k, p.u, p.v, p.w);
}
FI AxisBits& operator=(const xyze_bool_t &p) { set(p); return *this; }
// Constructor, setter, and operator= for bool array
AxisBits(const bool (&p)[LOGICAL_AXES]) { set(p); }
FI void set(const bool (&p)[LOGICAL_AXES]) {
MSET(p[E_AXIS], p[X_AXIS], p[Y_AXIS], p[Z_AXIS],
p[I_AXIS], p[J_AXIS], p[K_AXIS],
p[U_AXIS], p[V_AXIS], p[W_AXIS]);
}
FI AxisBits& operator=(const bool (&p)[LOGICAL_AXES]) { set(p); return *this; }
// Constructor, setter, and operator= for undersized bool arrays
#if LOGICAL_AXES > 1
AxisBits(const bool (&p)[1]) { set(p); }
FI void set(const bool (&p)[1]) {
MSET(0, p[X_AXIS], 0, 0, 0, 0, 0, 0, 0, 0);
}
FI AxisBits& operator=(const bool (&p)[1]) { set(p); return *this; }
#endif
#if LOGICAL_AXES > 2
AxisBits(const bool (&p)[2]) { set(p); }
FI void set(const bool (&p)[2]) {
MSET(0, p[X_AXIS], p[Y_AXIS], 0, 0, 0, 0, 0, 0, 0);
}
FI AxisBits& operator=(const bool (&p)[2]) { set(p); return *this; }
#endif
#if LOGICAL_AXES > 3
AxisBits(const bool (&p)[3]) { set(p); }
FI void set(const bool (&p)[3]) {
MSET(0, p[X_AXIS], p[Y_AXIS], p[Z_AXIS], 0, 0, 0, 0, 0, 0);
}
FI AxisBits& operator=(const bool (&p)[3]) { set(p); return *this; }
#endif
#if LOGICAL_AXES > 4
AxisBits(const bool (&p)[4]) { set(p); }
FI void set(const bool (&p)[4]) {
MSET(0, p[X_AXIS], p[Y_AXIS], p[Z_AXIS], p[I_AXIS], 0, 0, 0, 0, 0);
}
FI AxisBits& operator=(const bool (&p)[4]) { set(p); return *this; }
#endif
#if LOGICAL_AXES > 5
AxisBits(const bool (&p)[5]) { set(p); }
FI void set(const bool (&p)[5]) {
MSET(0, p[X_AXIS], p[Y_AXIS], p[Z_AXIS], p[I_AXIS], p[J_AXIS], 0, 0, 0, 0);
}
FI AxisBits& operator=(const bool (&p)[5]) { set(p); return *this; }
#endif
#if LOGICAL_AXES > 6
AxisBits(const bool (&p)[6]) { set(p); }
FI void set(const bool (&p)[6]) {
MSET(0, p[X_AXIS], p[Y_AXIS], p[Z_AXIS], p[I_AXIS], p[J_AXIS], p[K_AXIS], 0, 0, 0);
}
FI AxisBits& operator=(const bool (&p)[6]) { set(p); return *this; }
#endif
#if LOGICAL_AXES > 7
AxisBits(const bool (&p)[7]) { set(p); }
FI void set(const bool (&p)[7]) {
MSET(0, p[X_AXIS], p[Y_AXIS], p[Z_AXIS], p[I_AXIS], p[J_AXIS], p[K_AXIS], p[U_AXIS], 0, 0);
}
FI AxisBits& operator=(const bool (&p)[7]) { set(p); return *this; }
#endif
#if LOGICAL_AXES > 8
AxisBits(const bool (&p)[8]) { set(p); }
FI void set(const bool (&p)[8]) {
MSET(0, p[X_AXIS], p[Y_AXIS], p[Z_AXIS], p[I_AXIS], p[J_AXIS], p[K_AXIS], p[U_AXIS], p[V_AXIS], 0);
}
FI AxisBits& operator=(const bool (&p)[8]) { set(p); return *this; }
#endif
#if LOGICAL_AXES > 9
AxisBits(const bool (&p)[9]) { set(p); }
FI void set(const bool (&p)[9]) {
MSET(0, p[X_AXIS], p[Y_AXIS], p[Z_AXIS], p[I_AXIS], p[J_AXIS], p[K_AXIS], p[U_AXIS], p[V_AXIS], p[W_AXIS]);
}
FI AxisBits& operator=(const bool (&p)[9]) { set(p); return *this; }
#endif
#undef MSET
FI bool toggle(const AxisEnum n) { TBI(bits, n); return TEST(bits, n); }
FI void bset(const AxisEnum n) { SBI(bits, n); }
FI void bclr(const AxisEnum n) { CBI(bits, n); }
FI void bset(const AxisEnum n, const bool b) { if (b) bset(n); else bclr(n); }
// Accessor via an AxisEnum (or any integer) [index]
FI bool operator[](const int n) const { return TEST(bits, n); }
FI bool operator[](const AxisEnum n) const { return TEST(bits, n); }
FI AxisBits& operator|=(const el &p) { bits |= el(p); return *this; }
FI AxisBits& operator&=(const el &p) { bits &= el(p); return *this; }
FI AxisBits& operator^=(const el &p) { bits ^= el(p); return *this; }
FI AxisBits& operator|=(const AxisBits &p) { bits |= p.bits; return *this; }
FI AxisBits& operator&=(const AxisBits &p) { bits &= p.bits; return *this; }
FI AxisBits& operator^=(const AxisBits &p) { bits ^= p.bits; return *this; }
FI bool operator==(const AxisBits &p) const { return p.bits == bits; }
FI bool operator!=(const AxisBits &p) const { return p.bits != bits; }
FI el operator|(const el &p) const { return bits | el(p); }
FI el operator&(const el &p) const { return bits & el(p); }
FI el operator^(const el &p) const { return bits ^ el(p); }
FI AxisBits operator|(const AxisBits &p) const { return AxisBits(bits | p.bits); }
FI AxisBits operator&(const AxisBits &p) const { return AxisBits(bits & p.bits); }
FI AxisBits operator^(const AxisBits &p) const { return AxisBits(bits ^ p.bits); }
FI operator bool() const { return !!bits; }
FI operator uint16_t() const { return uint16_t(bits & 0xFFFF); }
FI operator uint32_t() const { return uint32_t(bits); }
};
#undef _RECIP
#undef _ABS
#undef _LS
#undef _RS
#undef _LSE
#undef _RSE
#undef FI
|
2301_81045437/Marlin
|
Marlin/src/core/types.h
|
C++
|
agpl-3.0
| 62,693
|
/**
* 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"
#if ENABLED(MARLIN_DEV_MODE)
MarlinError marlin_error_number; // Error Number - Marlin can beep X times periodically, display, and emit...
#endif
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_(BD_SENSOR, "BD_SENSOR")
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")
TERN_(BIQU_MICROPROBE_V1, "BIQU_MICROPROBE_V1")
TERN_(BIQU_MICROPROBE_V2, "BIQU_MICROPROBE_V2")
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_ECHO(F(TERN(IS_SCARA, "-Distal", "-Back")));
else if (probe.offset_xy.y < 0)
SERIAL_ECHO(F(TERN(IS_SCARA, "-Proximal", "-Front")));
else if (probe.offset_xy.x != 0)
SERIAL_ECHOPGM("-Center");
SERIAL_ECHOPGM(" & ");
#endif
SERIAL_ECHO(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
|
2301_81045437/Marlin
|
Marlin/src/core/utility.cpp
|
C++
|
agpl-3.0
| 6,180
|
/**
* 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
// 16x16 bit arrays
template <int W, int H>
struct FlagBits {
bits_t(W) flags[H];
void fill() { memset(flags, 0xFF, sizeof(flags)); }
void reset() { memset(flags, 0x00, sizeof(flags)); }
void unmark(const uint8_t x, const uint8_t y) { CBI(flags[y], x); }
void mark(const uint8_t x, const uint8_t y) { SBI(flags[y], x); }
bool marked(const uint8_t x, const uint8_t y) { return TEST(flags[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, AXIS7_NAME, AXIS8_NAME, AXIS9_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', 'U', 'V', 'W');
#define AXIS_CHAR(A) axis_codes[A]
#define IAXIS_CHAR(A) iaxis_codes[A]
#endif
#if ENABLED(MARLIN_DEV_MODE)
enum MarlinError : uint8_t {
ERR_NONE,
ERR_STRING_RANGE, // A string buffer was too small to set the whole blob
ERR_ASSERTION, // An assertion was triggered
ERR_MALFUNCTION,
ERR_MEMORY_LEAK,
ERR_COMMS_SERIAL,
ERR_COMMS_SPI,
ERR_PLANNER_STARVED,
ERR_TMC_SHUTDOWN,
ERR_PROCEDURE_FAILED,
ERR_TOO_WACK,
ERR_PLAID_IN_SUMMER
};
extern MarlinError marlin_error_number; // Error Number - Marlin can beep, display, and emit...
inline void error(const MarlinError err) { marlin_error_number = err; }
#endif
|
2301_81045437/Marlin
|
Marlin/src/core/utility.h
|
C++
|
agpl-3.0
| 4,057
|
/**
* 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
|
2301_81045437/Marlin
|
Marlin/src/feature/adc/adc_mcp3426.cpp
|
C++
|
agpl-3.0
| 2,919
|
/**
* 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;
|
2301_81045437/Marlin
|
Marlin/src/feature/adc/adc_mcp3426.h
|
C++
|
agpl-3.0
| 1,176
|
/**
* 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
|
2301_81045437/Marlin
|
Marlin/src/feature/ammeter.cpp
|
C++
|
agpl-3.0
| 1,613
|
/**
* 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;
|
2301_81045437/Marlin
|
Marlin/src/feature/ammeter.h
|
C++
|
agpl-3.0
| 1,105
|
/**
* 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(), BABYSTEP_ALLOWED
#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;
#if ALL(EP_BABYSTEPPING, EMERGENCY_PARSER)
int16_t Babystep::ep_babysteps;
#endif
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]);
}
#if ENABLED(BD_SENSOR)
void Babystep::set_mm(const AxisEnum axis, const_float_t mm) {
//if (DISABLED(BABYSTEP_WITHOUT_HOMING) && axes_should_home(_BV(axis))) return;
const int16_t distance = mm * planner.settings.axis_steps_per_mm[axis];
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_(BABYSTEPPING, if (has_steps()) stepper.initiateBabystepping());
}
#endif
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_(BABYSTEPPING, if (has_steps()) stepper.initiateBabystepping());
}
#if ENABLED(EP_BABYSTEPPING)
// Step Z for M293 / M294
void Babystep::z_up() { if (BABYSTEP_ALLOWED()) add_steps(Z_AXIS, +BABYSTEP_SIZE_Z); }
void Babystep::z_down() { if (BABYSTEP_ALLOWED()) add_steps(Z_AXIS, -BABYSTEP_SIZE_Z); }
#endif
#endif // BABYSTEPPING
|
2301_81045437/Marlin
|
Marlin/src/feature/babystep.cpp
|
C++
|
agpl-3.0
| 3,252
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
#pragma once
#include "../inc/MarlinConfigPre.h"
#define BABYSTEPS_PER_SEC 1000UL
#define BABYSTEP_TICKS ((STEPPER_TIMER_RATE) / (BABYSTEPS_PER_SEC))
#if ANY(IS_CORE, 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 ALL(EP_BABYSTEPPING, EMERGENCY_PARSER)
static int16_t ep_babysteps;
#endif
#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);
#if ENABLED(EP_BABYSTEPPING)
// Step Z for M293 / M294
static void z_up();
static void z_down();
#if ENABLED(EMERGENCY_PARSER)
// Step Z according to steps accumulated by the EP
FORCE_INLINE static void do_ep_steps() {
if (ep_babysteps) {
if (ep_babysteps > 0) { z_up(); ep_babysteps--; }
else { z_down(); ep_babysteps++; }
}
}
#endif
#endif // EP_BABYSTEPPING
#if ENABLED(BD_SENSOR)
static void set_mm(const AxisEnum axis, const_float_t mm);
#endif
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() {
for (uint8_t i = 0; i <= BS_AXIS_IND(Z_AXIS); ++i) step_axis(BS_AXIS(i));
}
private:
static void step_axis(const AxisEnum axis);
};
extern Babystep babystep;
|
2301_81045437/Marlin
|
Marlin/src/feature/babystep.h
|
C++
|
agpl-3.0
| 3,012
|
/**
* 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"
AxisBits 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 xyze_long_t &dist, const AxisBits dm, block_t * const block) {
AxisBits changed_dir = last_direction_bits ^ dm;
// Ignore direction change unless steps are taken in that direction
#if DISABLED(CORE_BACKLASH) || ANY(MARKFORGED_XY, MARKFORGED_YX)
if (!dist.a) changed_dir.x = false;
if (!dist.b) changed_dir.y = false;
if (!dist.c) changed_dir.z = false;
#elif CORE_IS_XY
if (!(dist.a + dist.b)) changed_dir.x = false;
if (!(dist.a - dist.b)) changed_dir.y = false;
if (!dist.c) changed_dir.z = false;
#elif CORE_IS_XZ
if (!(dist.a + dist.c)) changed_dir.x = false;
if (!(dist.a - dist.c)) changed_dir.z = false;
if (!dist.b) changed_dir.y = false;
#elif CORE_IS_YZ
if (!(dist.b + dist.c)) changed_dir.y = false;
if (!(dist.b - dist.c)) changed_dir.z = false;
if (!dist.a) changed_dir.x = false;
#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;
bool changed = false;
float millimeters_delta = 0.0f;
#if IS_KINEMATIC
float sqr_stepper_space_mm = 0.0f;
#endif
LOOP_NUM_AXES(axis) {
TERN_(IS_KINEMATIC, sqr_stepper_space_mm += sq(dist[axis] * planner.mm_per_step[axis]));
if (distance_mm[axis]) {
const bool forward = dm[axis];
// When an axis changes direction, add axis backlash to the residual error
if (changed_dir[axis])
residual_error[axis] += (forward ? 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];
#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
// Don't correct backlash in the opposite direction to movement on this axis and for accuracy in
// updating block->millimeters, don't add too many steps to the movement on this axis
if (forward)
LIMIT(error_correction, 0, dist[axis]);
else
LIMIT(error_correction, dist[axis], 0);
// This correction reduces the residual error and adds block steps
if (error_correction) {
changed = true;
block->steps[axis] += ABS(error_correction);
millimeters_delta += dist[axis] * error_correction * sq(planner.mm_per_step[axis]);
#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
}
}
}
// If backlash correction steps were added modify block->millimeters with a linear approximation
// See https://github.com/MarlinFirmware/Marlin/pull/26392
if (changed)
block->millimeters += TERN(IS_KINEMATIC, millimeters_delta * block->millimeters / sqr_stepper_space_mm, millimeters_delta / block->millimeters);
}
int32_t Backlash::get_applied_steps(const AxisEnum axis) {
if (axis >= NUM_AXES) return 0;
const bool forward = last_direction_bits[axis];
const int32_t residual_error_axis = residual_error[axis];
// At startup it is assumed the last move was forward.
// So the applied steps will always be negative.
if (forward) 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
|
2301_81045437/Marlin
|
Marlin/src/feature/backlash.cpp
|
C++
|
agpl-3.0
| 8,803
|
/**
* 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 AxisBits 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 xyze_long_t &dist, const AxisBits 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;
|
2301_81045437/Marlin
|
Marlin/src/feature/backlash.h
|
C++
|
agpl-3.0
| 3,176
|
/**
* 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
|
2301_81045437/Marlin
|
Marlin/src/feature/baricuda.cpp
|
C++
|
agpl-3.0
| 1,041
|
/**
* 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;
|
2301_81045437/Marlin
|
Marlin/src/feature/baricuda.h
|
C
|
agpl-3.0
| 957
|
/**
* 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
for (uint8_t xo = 0; xo <= xend; ++xo)
for (uint8_t yo = 0; yo <= yend; ++yo) {
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/*=nullptr*/) {
// 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::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 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(
virt_coord(ep + 1, y),
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(
virt_coord(x, ep + 1),
virt_coord(x, ip + 1)
);
}
return z_values[x - 1][y - 1];
}
float LevelingBilinear::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::virt_2cmr(const uint8_t x, const uint8_t y, const_float_t tx, const_float_t ty) {
float row[4], column[4];
for (uint8_t i = 0; i < 4; ++i) {
for (uint8_t j = 0; j < 4; ++j) {
column[j] = virt_coord(i + x - 1, j + y - 1);
}
row[i] = virt_cmr(column, 1, ty);
}
return virt_cmr(row, 1, tx);
}
void LevelingBilinear::subdivide_mesh() {
grid_spacing_virt = grid_spacing / (BILINEAR_SUBDIVISIONS);
grid_factor_virt = grid_spacing_virt.reciprocal();
for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; ++y)
for (uint8_t x = 0; x < GRID_MAX_POINTS_X; ++x)
for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ++ty)
for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; ++tx) {
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] =
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, subdivide_mesh());
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
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/abl/bbl.cpp
|
C++
|
agpl-3.0
| 15,021
|
/**
* 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 virt_coord(const uint8_t x, const uint8_t y);
static float virt_cmr(const float p[4], const uint8_t i, const float t);
static float virt_2cmr(const uint8_t x, const uint8_t y, const_float_t tx, const_float_t ty);
static void subdivide_mesh();
#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=nullptr);
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;
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/abl/bbl.h
|
C++
|
agpl-3.0
| 2,780
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2022 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(BD_SENSOR)
#include "../../../MarlinCore.h"
#include "../../../gcode/gcode.h"
#include "../../../module/settings.h"
#include "../../../module/motion.h"
#include "../../../module/planner.h"
#include "../../../module/stepper.h"
#include "../../../module/probe.h"
#include "../../../module/temperature.h"
#include "../../../module/endstops.h"
#include "../../babystep.h"
#include "../../../lcd/marlinui.h"
// I2C software Master library for segment bed heating and bed distance sensor
#include <Panda_segmentBed_I2C.h>
#include "bdl.h"
BDS_Leveling bdl;
//#define DEBUG_OUT_BD
#define DEBUG_OUT ENABLED(DEBUG_OUT_BD)
#include "../../../core/debug_out.h"
// M102 S-5 Read raw Calibrate data
// M102 S-6 Start Calibrate
// M102 S4 Set the adjustable Z height value (e.g., 'M102 S4' means it will do adjusting while the Z height <= 0.4mm , disable with 'M102 S0'.)
// M102 S-1 Read sensor information
#define MAX_BD_HEIGHT 4.0f
#define CMD_READ_VERSION 1016
#define CMD_START_READ_CALIBRATE_DATA 1017
#define CMD_END_READ_CALIBRATE_DATA 1018
#define CMD_START_CALIBRATE 1019
#define CMD_END_CALIBRATE 1021
#define BD_SENSOR_I2C_ADDR 0x3C
I2C_SegmentBED BD_I2C_SENSOR;
float BDS_Leveling::pos_zero_offset;
int8_t BDS_Leveling::config_state;
void BDS_Leveling::init(uint8_t _sda, uint8_t _scl, uint16_t delay_s) {
config_state = BDS_IDLE;
const int ret = BD_I2C_SENSOR.i2c_init(_sda, _scl, BD_SENSOR_I2C_ADDR, delay_s);
if (ret != 1) SERIAL_ECHOLNPGM("BD Sensor Init Fail (", ret, ")");
sync_plan_position();
pos_zero_offset = planner.get_axis_position_mm(Z_AXIS) - current_position.z;
SERIAL_ECHOLNPGM("BD Sensor Zero Offset:", pos_zero_offset);
}
bool BDS_Leveling::check(const uint16_t data, const bool raw_data/*=false*/, const bool hicheck/*=false*/) {
if (BD_I2C_SENSOR.BD_Check_OddEven(data) == 0) {
SERIAL_ECHOLNPGM("Read Error.");
return true; // error
}
if (raw_data == true) {
if (hicheck && (data & 0x3FF) > 400)
SERIAL_ECHOLNPGM("Bad BD Sensor height! Recommended distance 0.5-2.0mm");
else if (!good_data(data))
SERIAL_ECHOLNPGM("Invalid data, please calibrate.");
else
return false;
}
else {
if ((data & 0x3FF) >= (MAX_BD_HEIGHT) * 100 - 10)
SERIAL_ECHOLNPGM("Out of Range.");
else
return false;
}
return true; // error
}
float BDS_Leveling::interpret(const uint16_t data) {
return (data & 0x3FF) / 100.0f;
}
float BDS_Leveling::read() {
const uint16_t data = BD_I2C_SENSOR.BD_i2c_read();
return check(data) ? NAN : interpret(data);
}
void BDS_Leveling::process() {
if (config_state == BDS_IDLE && printingIsActive()) return;
static millis_t next_check_ms = 0; // starting at T=0
static float zpos = 0.0f;
const millis_t ms = millis();
if (ELAPSED(ms, next_check_ms)) { // timed out (or first run)
// Check at 1KHz, 5Hz, or 20Hz
next_check_ms = ms + (config_state == BDS_HOMING_Z ? 1 : (config_state < BDS_IDLE ? 200 : 50));
uint16_t tmp = 0;
const float cur_z = planner.get_axis_position_mm(Z_AXIS) - pos_zero_offset;
static float old_cur_z = cur_z, old_buf_z = current_position.z;
tmp = BD_I2C_SENSOR.BD_i2c_read();
if (BD_I2C_SENSOR.BD_Check_OddEven(tmp) && good_data(tmp)) {
const float z_sensor = interpret(tmp);
#if ENABLED(BABYSTEPPING)
if (config_state > 0) {
if (cur_z < config_state * 0.1f
&& old_cur_z == cur_z
&& old_buf_z == current_position.z
&& z_sensor < (MAX_BD_HEIGHT) - 0.1f
) {
babystep.set_mm(Z_AXIS, cur_z - z_sensor);
DEBUG_ECHOLNPGM("BD:", z_sensor, ", Z:", cur_z, "|", current_position.z);
}
else
babystep.set_mm(Z_AXIS, 0);
}
#endif
old_cur_z = cur_z;
old_buf_z = current_position.z;
endstops.bdp_state_update(z_sensor <= BD_SENSOR_HOME_Z_POSITION);
#if HAS_STATUS_MESSAGE
static float old_z_sensor = 0;
if (old_z_sensor != z_sensor) {
old_z_sensor = z_sensor;
char tmp_1[32];
sprintf_P(tmp_1, PSTR("BD:%d.%02dmm"), int(z_sensor), int(z_sensor * 100) % 100);
//SERIAL_ECHOLNPGM("Bed Dis:", z_sensor, "mm");
ui.set_status(tmp_1, true);
}
#endif
}
else if (config_state == BDS_HOMING_Z) {
SERIAL_ECHOLNPGM("Read:", tmp);
kill(F("BDsensor connect Err!"));
}
DEBUG_ECHOLNPGM("BD:", tmp & 0x3FF, " Z:", cur_z, "|", current_position.z);
if (TERN0(DEBUG_OUT_BD, BD_I2C_SENSOR.BD_Check_OddEven(tmp) == 0)) DEBUG_ECHOLNPGM("CRC error");
if (!good_data(tmp)) {
BD_I2C_SENSOR.BD_i2c_stop();
safe_delay(10);
}
// Read version. Usually used as a connection check
if (config_state == BDS_VERSION) {
config_state = BDS_IDLE;
BD_I2C_SENSOR.BD_i2c_write(CMD_READ_VERSION);
safe_delay(100);
char tmp_1[21];
for (int i = 0; i < 19; i++) {
tmp_1[i] = BD_I2C_SENSOR.BD_i2c_read() & 0xFF;
safe_delay(50);
}
BD_I2C_SENSOR.BD_i2c_write(CMD_END_READ_CALIBRATE_DATA);
SERIAL_ECHOLNPGM("BD Sensor version:", tmp_1);
if (tmp_1[0] != 'V') SERIAL_ECHOLNPGM("Read Error. Check connection and delay.");
safe_delay(50);
}
// read raw calibrate data
else if (config_state == BDS_READ_RAW) {
BD_I2C_SENSOR.BD_i2c_write(CMD_START_READ_CALIBRATE_DATA);
safe_delay(100);
for (int i = 0; i < MAX_BD_HEIGHT * 10; i++) {
tmp = BD_I2C_SENSOR.BD_i2c_read();
SERIAL_ECHOLNPGM("Calibrate data:", i, ",", tmp & 0x3FF);
(void)check(tmp, true, i == 0);
safe_delay(50);
}
BD_I2C_SENSOR.BD_i2c_write(CMD_END_READ_CALIBRATE_DATA);
safe_delay(50);
config_state = BDS_IDLE;
}
else if (config_state <= BDS_CALIBRATE_START) { // Start Calibrate
safe_delay(10);
if (config_state == BDS_CALIBRATE_START) {
config_state = BDS_CALIBRATING;
REMEMBER(gsit, gcode.stepper_inactive_time, MIN_TO_MS(5));
SERIAL_ECHOLNPGM("c_z0:", planner.get_axis_position_mm(Z_AXIS), "-", pos_zero_offset);
// Move the z axis instead of enabling the Z axis with M17
// TODO: Use do_blocking_move_to_z for synchronized move.
current_position.z = 0;
sync_plan_position();
gcode.process_subcommands_now(F("G1Z0.05"));
safe_delay(300);
gcode.process_subcommands_now(F("G1Z0.00"));
safe_delay(300);
current_position.z = 0;
sync_plan_position();
//safe_delay(1000);
while ((planner.get_axis_position_mm(Z_AXIS) - pos_zero_offset) > 0.00001f) {
safe_delay(200);
SERIAL_ECHOLNPGM("waiting cur_z:", planner.get_axis_position_mm(Z_AXIS));
}
zpos = 0.00001f;
safe_delay(100);
BD_I2C_SENSOR.BD_i2c_write(CMD_START_CALIBRATE); // Begin calibrate
SERIAL_ECHOLNPGM("BD Sensor Calibrating...");
safe_delay(200);
}
else if ((planner.get_axis_position_mm(Z_AXIS) - pos_zero_offset) < 10.0f) {
if (zpos >= MAX_BD_HEIGHT) {
config_state = BDS_IDLE;
BD_I2C_SENSOR.BD_i2c_write(CMD_END_CALIBRATE); // End calibrate
SERIAL_ECHOLNPGM("BD Sensor calibrated.");
zpos = 7.0f;
safe_delay(500);
}
else {
char tmp_1[32];
// TODO: Use prepare_internal_move_to_destination to guarantee machine space
sprintf_P(tmp_1, PSTR("G1Z%d.%d"), int(zpos), int(zpos * 10) % 10);
gcode.process_subcommands_now(tmp_1);
SERIAL_ECHO(tmp_1); SERIAL_ECHOLNPGM(", Z:", current_position.z);
uint16_t failcount = 300;
for (float tmp_k = 0; abs(zpos - tmp_k) > 0.006f && failcount--;) {
tmp_k = planner.get_axis_position_mm(Z_AXIS) - pos_zero_offset;
safe_delay(10);
if (!failcount--) break;
}
safe_delay(600);
tmp = uint16_t((zpos + 0.00001f) * 10);
BD_I2C_SENSOR.BD_i2c_write(tmp);
SERIAL_ECHOLNPGM("w:", tmp, ", Z:", zpos);
zpos += 0.1001f;
}
}
}
}
}
#endif // BD_SENSOR
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/bdl/bdl.cpp
|
C++
|
agpl-3.0
| 9,166
|
/**
* Marlin 3D Printer Firmware
* Copyright (c) 2022 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>
#ifndef BD_SENSOR_HOME_Z_POSITION
#define BD_SENSOR_HOME_Z_POSITION 0.5
#endif
enum BDS_State : int8_t {
BDS_IDLE,
BDS_VERSION = -1,
BDS_READ_MM = -2,
BDS_HOMING_Z = -3,
BDS_READ_RAW = -5,
BDS_CALIBRATE_START = -6,
BDS_CALIBRATING = -7
};
class BDS_Leveling {
public:
static int8_t config_state;
static float pos_zero_offset;
static void init(uint8_t _sda, uint8_t _scl, uint16_t delay_s);
static void process();
static float read();
static float interpret(const uint16_t data);
static float good_data(const uint16_t data) { return (data & 0x3FF) < 1016; }
static bool check(const uint16_t data, const bool raw_data=false, const bool hicheck=false);
};
extern BDS_Leveling bdl;
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/bdl/bdl.h
|
C++
|
agpl-3.0
| 1,644
|
/**
* 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 ANY(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*/) {
DEBUG_SECTION(log_sble, "set_bed_leveling_enabled", DEBUGGING(LEVELING));
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, true); // Physical position with all modifiers
planner.leveling_active ^= true; // Toggle leveling between apply and unapply
planner.unapply_modifiers(current_position, true); // 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 ANY(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
for (uint8_t x = 0; x < sx; ++x) {
SERIAL_ECHO_SP(precision + (x < 10 ? 3 : 2));
SERIAL_ECHO(x);
}
SERIAL_EOL();
#endif
#ifdef SCAD_MESH_OUTPUT
SERIAL_ECHOLNPGM("measured_z = ["); // open 2D array
#endif
for (uint8_t y = 0; y < sy; ++y) {
#ifdef SCAD_MESH_OUTPUT
SERIAL_ECHOPGM(" ["); // open sub-array
#else
if (y < 10) SERIAL_CHAR(' ');
SERIAL_ECHO(y);
#endif
for (uint8_t x = 0; x < sx; ++x) {
SERIAL_CHAR(' ');
const float offset = values[x * sy + y];
if (!isnan(offset)) {
if (offset >= 0) SERIAL_CHAR('+');
SERIAL_ECHO(p_float_t(offset, precision));
}
else {
#ifdef SCAD_MESH_OUTPUT
for (uint8_t i = 3; i < precision + 3; i++)
SERIAL_CHAR(' ');
SERIAL_ECHOPGM("NAN");
#else
for (uint8_t i = 0; i < precision + 3; ++i)
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 ANY(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
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/bedlevel.cpp
|
C++
|
agpl-3.0
| 7,148
|
/**
* 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 ANY(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 ANY(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 ANY(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
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/bedlevel.h
|
C++
|
agpl-3.0
| 2,988
|
/*********************
* 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(uint8_t(n >> 1)) : 0; }
constexpr uint8_t order(uint8_t n) { return uint8_t(log2(uint8_t(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
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/hilbert_curve.cpp
|
C++
|
agpl-3.0
| 4,852
|
/*******************
* 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);
};
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/hilbert_curve.h
|
C++
|
agpl-3.0
| 1,800
|
/**
* 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() {
for (uint8_t i = 0; i < GRID_MAX_POINTS_X; ++i)
index_to_xpos[i] = MESH_MIN_X + i * (MESH_X_DIST);
for (uint8_t i = 0; i < GRID_MAX_POINTS_Y; ++i)
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_uint8_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 uint8_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_ECHOLN(F(STRINGIFY(GRID_MAX_POINTS_X) "x" STRINGIFY(GRID_MAX_POINTS_Y) " mesh. Z offset: "), p_float_t(z_offset, 5), F("\nMeasured points:"));
print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 5, z_values[0]);
}
#endif // MESH_BED_LEVELING
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/mbl/mesh_bed_leveling.cpp
|
C++
|
agpl-3.0
| 4,655
|
/**
* 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 uint8_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 uint8_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_uint8_t cell_indexes(const_float_t x, const_float_t y) {
return { cell_index_x(x), cell_index_y(y) };
}
static xy_uint8_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_uint8_t ind = cell_indexes(pos);
const float x1 = index_to_xpos[ind.x], x2 = index_to_xpos[ind.x+1],
y1 = index_to_ypos[ind.y], y2 = index_to_ypos[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;
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/mbl/mesh_bed_leveling.h
|
C++
|
agpl-3.0
| 4,523
|
/**
* 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_ECHOLN(F(" M421 I"), x, F(" J"), y, FPSTR(SP_Z_STR), p_float_t(z_values[x][y], 4));
serial_delay(75); // Prevent Printrun from exploding
}
}
void unified_bed_leveling::report_state() {
echo_name();
serial_ternary(F(" System v" UBL_VERSION " "), planner.leveling_active, nullptr, F("in"), F("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);
for (uint8_t i = 0; i < GRID_MAX_POINTS_X; ++i) {
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)
for (uint8_t i = 0; i < GRID_MAX_POINTS_X; ++i) {
// 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_ECHO(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_ECHO(p_float_t(f, 3)); // 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\n", "")
#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 // 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
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/ubl/ubl.cpp
|
C++
|
agpl-3.0
| 9,972
|
/**
* 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;
grid_count_t R_repetition;
uint8_t 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_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(const bool is_done=true);
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 bool cell_index_x_valid(const_float_t x) {
return WITHIN(cell_index_x_raw(x), 0, GRID_MAX_CELLS_X - 1);
}
static bool cell_index_y_valid(const_float_t y) {
return WITHIN(cell_index_y_raw(y), 0, GRID_MAX_CELLS_Y - 1);
}
static uint8_t cell_index_x(const_float_t x) {
return constrain(cell_index_x_raw(x), 0, GRID_MAX_CELLS_X - 1);
}
static uint8_t cell_index_y(const_float_t y) {
return constrain(cell_index_y_raw(y), 0, GRID_MAX_CELLS_Y - 1);
}
static xy_uint8_t cell_indexes(const_float_t x, const_float_t y) {
return { cell_index_x(x), cell_index_y(y) };
}
static xy_uint8_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;
const float x0 = get_mesh_x(cx), x1 = get_mesh_x(cx + 1),
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_ECHOLN(F("get_z_correction("), rx0, F(", "), ry0, F(") => "), p_float_t(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"
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/ubl/ubl.h
|
C++
|
agpl-3.0
| 12,467
|
/**
* 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 "../../../MarlinCore.h"
#include "../../../HAL/shared/eeprom_api.h"
#include "../../../libs/hex_print.h"
#include "../../../module/settings.h"
#include "../../../lcd/marlinui.h"
#include "../../../module/planner.h"
#include "../../../module/motion.h"
#include "../../../module/probe.h"
#include "../../../gcode/gcode.h"
#include "../../../libs/least_squares_fit.h"
#define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE)
#include "../../../core/debug_out.h"
#if ENABLED(EXTENSIBLE_UI)
#include "../../../lcd/extui/ui_api.h"
#endif
#if ENABLED(UBL_HILBERT_CURVE)
#include "../hilbert_curve.h"
#endif
#include <math.h>
#define UBL_G29_P31
#if HAS_MARLINUI_MENU
bool unified_bed_leveling::lcd_map_control = false;
void unified_bed_leveling::steppers_were_disabled() {
if (lcd_map_control) {
lcd_map_control = false;
ui.defer_status_screen(false);
}
}
void ubl_map_screen();
#endif
#define SIZE_OF_LITTLE_RAISE 1
#define BIG_RAISE_NOT_NEEDED 0
/**
* G29: Unified Bed Leveling by Roxy
*
* Parameters understood by this leveling system:
*
* A Activate Activate the Unified Bed Leveling system.
*
* B # Business Use the 'Business Card' mode of the Manual Probe subsystem with P2.
* Note: A non-compressible Spark Gap feeler gauge is recommended over a business card.
* In this mode of G29 P2, a business or index card is used as a shim that the nozzle can
* grab onto as it is lowered. In principle, the nozzle-bed distance is the same when the
* same resistance is felt in the shim. You can omit the numerical value on first invocation
* of G29 P2 B to measure shim thickness. Subsequent use of 'B' will apply the previously-
* measured thickness by default.
*
* C Continue G29 P1 C continues the generation of a partially-constructed Mesh without invalidating
* previous measurements.
*
* C G29 P2 C tells the Manual Probe subsystem to not use the current nozzle
* location in its search for the closest unmeasured Mesh Point. Instead, attempt to
* start at one end of the uprobed points and Continue sequentially.
*
* G29 P3 C specifies the Constant for the fill. Otherwise, uses a "reasonable" value.
*
* C Current G29 Z C uses the Current location (instead of bed center or nearest edge).
*
* D Disable Disable the Unified Bed Leveling system.
*
* E Stow_probe Stow the probe after each sampled point.
*
* F # Fade Fade the amount of Mesh Based Compensation over a specified height. At the
* specified height, no correction is applied and natural printer kenimatics take over. If no
* number is specified for the command, 10mm is assumed to be reasonable.
*
* H # Height With P2, 'H' specifies the Height to raise the nozzle after each manual probe of the bed.
* If omitted, the nozzle will raise by Z_CLEARANCE_BETWEEN_PROBES.
*
* H # Offset With P4, 'H' specifies the Offset above the mesh height to place the nozzle.
* If omitted, Z_TWEEN_SAFE_CLEARANCE will be used.
*
* I # Invalidate Invalidate the specified number of Mesh Points near the given 'X' 'Y'. If X or Y are omitted,
* the nozzle location is used. If no 'I' value is given, only the point nearest to the location
* is invalidated. Use 'T' to produce a map afterward. This command is useful to invalidate a
* portion of the Mesh so it can be adjusted using other UBL tools. When attempting to invalidate
* an isolated bad mesh point, the 'T' option shows the nozzle position in the Mesh with (#). You
* can move the nozzle around and use this feature to select the center of the area (or cell) to
* invalidate.
*
* J # Grid Perform a Grid Based Leveling of the current Mesh using a grid with n points on a side.
* Not specifying a grid size will invoke the 3-Point leveling function.
*
* L Load Load Mesh from the previously activated location in the EEPROM.
*
* L # Load Load Mesh from the specified location in the EEPROM. Set this location as activated
* for subsequent Load and Store operations.
*
* The P or Phase commands are used for the bulk of the work to setup a Mesh. In general, your Mesh will
* start off being initialized with a G29 P0 or a G29 P1. Further refinement of the Mesh happens with
* each additional Phase that processes it.
*
* P0 Phase 0 Zero Mesh Data and turn off the Mesh Compensation System. This reverts the
* 3D Printer to the same state it was in before the Unified Bed Leveling Compensation
* was turned on. Setting the entire Mesh to Zero is a special case that allows
* a subsequent G or T leveling operation for backward compatibility.
*
* P1 Phase 1 Invalidate entire Mesh and continue with automatic generation of the Mesh data using
* the Z-Probe. Usually the probe can't reach all areas that the nozzle can reach. For delta
* printers only the areas where the probe and nozzle can both reach will be automatically probed.
*
* Unreachable points will be handled in Phase 2 and Phase 3.
*
* Use 'C' to leave the previous mesh intact and automatically probe needed points. This allows you
* to invalidate parts of the Mesh but still use Automatic Probing.
*
* The 'X' and 'Y' parameters prioritize where to try and measure points. If omitted, the current
* probe position is used.
*
* Use 'T' (Topology) to generate a report of mesh generation.
*
* P1 will suspend Mesh generation if the controller button is held down. Note that you may need
* to press and hold the switch for several seconds if moves are underway.
*
* P2 Phase 2 Probe unreachable points.
*
* Use 'H' to set the height between Mesh points. If omitted, Z_CLEARANCE_BETWEEN_PROBES is used.
* Smaller values will be quicker. Move the nozzle down till it barely touches the bed. Make sure the
* nozzle is clean and unobstructed. Use caution and move slowly. This can damage your printer!
* (Uses SIZE_OF_LITTLE_RAISE mm if the nozzle is moving less than BIG_RAISE_NOT_NEEDED mm.)
*
* The 'H' value can be negative if the Mesh dips in a large area. Press and hold the
* controller button to terminate the current Phase 2 command. You can then re-issue "G29 P 2"
* with an 'H' parameter more suitable for the area you're manually probing. Note that the command
* tries to start in a corner of the bed where movement will be predictable. Override the distance
* calculation location with the X and Y parameters. You can print a Mesh Map (G29 T) to see where
* the mesh is invalidated and where the nozzle needs to move to complete the command. Use 'C' to
* indicate that the search should be based on the current position.
*
* The 'B' parameter for this command is described above. It places the manual probe subsystem into
* Business Card mode where the thickness of a business card is measured and then used to accurately
* set the nozzle height in all manual probing for the duration of the command. A Business card can
* be used, but you'll get better results with a flexible Shim that doesn't compress. This makes it
* easier to produce similar amounts of force and get more accurate measurements. Google if you're
* not sure how to use a shim.
*
* The 'T' (Map) parameter helps track Mesh building progress.
*
* NOTE: P2 requires an LCD controller!
*
* P3 Phase 3 Fill the unpopulated regions of the Mesh with a fixed value. There are two different paths to
* go down:
*
* - If a 'C' constant is specified, the closest invalid mesh points to the nozzle will be filled,
* and a repeat count can then also be specified with 'R'.
*
* - Leaving out 'C' invokes Smart Fill, which scans the mesh from the edges inward looking for
* invalid mesh points. Adjacent points are used to determine the bed slope. If the bed is sloped
* upward from the invalid point, it takes the value of the nearest point. If sloped downward, it's
* replaced by a value that puts all three points in a line. This version of G29 P3 is a quick, easy
* and (usually) safe way to populate unprobed mesh regions before continuing to G26 Mesh Validation
* Pattern. Note that this populates the mesh with unverified values. Pay attention and use caution.
*
* P4 Phase 4 Fine tune the Mesh. The Delta Mesh Compensation System assumes the existence of
* an LCD Panel. It is possible to fine tune the mesh without an LCD Panel using
* G42 and M421. See the UBL documentation for further details.
*
* Phase 4 is meant to be used with G26 Mesh Validation to fine tune the mesh by direct editing
* of Mesh Points. Raise and lower points to fine tune the mesh until it gives consistently reliable
* adhesion.
*
* P4 moves to the closest Mesh Point (and/or the given X Y), raises the nozzle above the mesh height
* by the given 'H' offset (or default 0), and waits while the controller is used to adjust the nozzle
* height. On click the displayed height is saved in the mesh.
*
* Start Phase 4 at a specific location with X and Y. Adjust a specific number of Mesh Points with
* the 'R' (Repeat) parameter. (If 'R' is left out, the whole matrix is assumed.) This command can be
* terminated early (e.g., after editing the area of interest) by pressing and holding the encoder button.
*
* The general form is G29 P4 [R points] [X position] [Y position]
*
* The H [offset] parameter is useful if a shim is used to fine-tune the mesh. For a 0.4mm shim the
* command would be G29 P4 H0.4. The nozzle is moved to the shim height, you adjust height to the shim,
* and on click the height minus the shim thickness will be saved in the mesh.
*
* !!Use with caution, as a very poor mesh could cause the nozzle to crash into the bed!!
*
* NOTE: P4 is not available unless you have LCD support enabled!
*
* P5 Phase 5 Find Mean Mesh Height and Standard Deviation. Typically, it is easier to use and
* work with the Mesh if it is Mean Adjusted. You can specify a C parameter to
* Correct the Mesh to a 0.00 Mean Height. Adding a C parameter will automatically
* execute a G29 P6 C <mean height>.
*
* P6 Phase 6 Shift Mesh height. The entire Mesh's height is adjusted by the height specified
* with the C parameter. Being able to adjust the height of a Mesh is useful tool. It
* can be used to compensate for poorly calibrated Z-Probes and other errors. Ideally,
* you should have the Mesh adjusted for a Mean Height of 0.00 and the Z-Probe measuring
* 0.000 at the Z Home location.
*
* Q Test Load specified Test Pattern to assist in checking correct operation of system. This
* command is not anticipated to be of much value to the typical user. It is intended
* for developers to help them verify correct operation of the Unified Bed Leveling System.
*
* R # Repeat Repeat this command the specified number of times. If no number is specified the
* command will be repeated GRID_MAX_POINTS_X * GRID_MAX_POINTS_Y times.
*
* S Store Store the current Mesh in the Activated area of the EEPROM. It will also store the
* current state of the Unified Bed Leveling system in the EEPROM.
*
* S # Store Store the current Mesh at the specified location in EEPROM. Activate this location
* for subsequent Load and Store operations. Valid storage slot numbers begin at 0 and
* extend to a limit related to the available EEPROM storage.
*
* S -1 Store Print the current Mesh as G-code that can be used to restore the mesh anytime.
*
* T Topology Display the Mesh Map Topology.
* 'T' can be used alone (e.g., G29 T) or in combination with most of the other commands.
* This option works with all Phase commands (e.g., G29 P4 R 5 T X 50 Y100 C -.1 O)
* This parameter can also specify a Map Type. T0 (the default) is user-readable. T1
* is suitable to paste into a spreadsheet for a 3D graph of the mesh.
*
* U Unlevel Perform a probe of the outer perimeter to assist in physically leveling unlevel beds.
* Only used for G29 P1 T U. This speeds up the probing of the edge of the bed. Useful
* when the entire bed doesn't need to be probed because it will be adjusted.
*
* V # Verbosity Set the verbosity level (0-4) for extra details. (Default 0)
*
* X # X Location for this command
*
* Y # Y Location for this command
*
* With UBL_DEVEL_DEBUGGING:
*
* K # Kompare Kompare current Mesh with stored Mesh #, replacing current Mesh with the result.
* This command literally performs a diff between two Meshes.
*
* Q-1 Dump EEPROM Dump the UBL contents stored in EEPROM as HEX format. Useful for developers to help
* verify correct operation of the UBL.
*
* W What? Display valuable UBL data.
*
*
* Release Notes:
* You MUST do M502, M500 to initialize the storage. Failure to do this will cause all
* kinds of problems. Enabling EEPROM Storage is required.
*
* When you do a G28 and G29 P1 to automatically build your first mesh, you are going to notice that
* UBL probes points increasingly further from the starting location. (The starting location defaults
* to the center of the bed.) In contrast, ABL and MBL follow a zigzag pattern. The spiral pattern is
* especially better for Delta printers, since it populates the center of the mesh first, allowing for
* a quicker test print to verify settings. You don't need to populate the entire mesh to use it.
* After all, you don't want to spend a lot of time generating a mesh only to realize the resolution
* or probe offsets are incorrect. Mesh-generation gathers points starting closest to the nozzle unless
* an (X,Y) coordinate pair is given.
*
* Unified Bed Leveling uses a lot of EEPROM storage to hold its data, and it takes some effort to get
* the mesh just right. To prevent this valuable data from being destroyed as the EEPROM structure
* evolves, UBL stores all mesh data at the end of EEPROM.
*
* UBL is founded on Edward Patel's Mesh Bed Leveling code. A big 'Thanks!' to him and the creators of
* 3-Point and Grid Based leveling. Combining their contributions we now have the functionality and
* features of all three systems combined.
*/
G29_parameters_t unified_bed_leveling::param;
void unified_bed_leveling::G29() {
bool probe_deployed = false;
if (G29_parse_parameters()) return; // Abort on parameter error
const uint8_t p_val = parser.byteval('P');
const bool may_move = p_val == 1 || p_val == 2 || p_val == 4 || parser.seen_test('J');
// Check for commands that require the printer to be homed
if (may_move) {
planner.synchronize();
#if ALL(DWIN_LCD_PROUI, ZHOME_BEFORE_LEVELING)
save_ubl_active_state_and_disable();
gcode.process_subcommands_now(F("G28Z"));
restore_ubl_active_state(false); // ...without telling ExtUI "done"
#else
// Send 'N' to force homing before G29 (internal only)
if (axes_should_home() || parser.seen_test('N')) gcode.home_all_axes();
#endif
probe.use_probing_tool();
// Position bed horizontally and Z probe vertically.
#if HAS_SAFE_BED_LEVELING
xyze_pos_t safe_position = current_position;
#ifdef SAFE_BED_LEVELING_START_X
safe_position.x = SAFE_BED_LEVELING_START_X;
#endif
#ifdef SAFE_BED_LEVELING_START_Y
safe_position.y = SAFE_BED_LEVELING_START_Y;
#endif
#ifdef SAFE_BED_LEVELING_START_Z
safe_position.z = SAFE_BED_LEVELING_START_Z;
#endif
#ifdef SAFE_BED_LEVELING_START_I
safe_position.i = SAFE_BED_LEVELING_START_I;
#endif
#ifdef SAFE_BED_LEVELING_START_J
safe_position.j = SAFE_BED_LEVELING_START_J;
#endif
#ifdef SAFE_BED_LEVELING_START_K
safe_position.k = SAFE_BED_LEVELING_START_K;
#endif
#ifdef SAFE_BED_LEVELING_START_U
safe_position.u = SAFE_BED_LEVELING_START_U;
#endif
#ifdef SAFE_BED_LEVELING_START_V
safe_position.v = SAFE_BED_LEVELING_START_V;
#endif
#ifdef SAFE_BED_LEVELING_START_W
safe_position.w = SAFE_BED_LEVELING_START_W;
#endif
do_blocking_move_to(safe_position);
#endif // HAS_SAFE_BED_LEVELING
}
// Invalidate one or more nearby mesh points, possibly all.
if (parser.seen('I')) {
grid_count_t count = parser.has_value() ? parser.value_ushort() : 1;
bool invalidate_all = count >= GRID_MAX_POINTS;
if (!invalidate_all) {
while (count--) {
if ((count & 0x0F) == 0x0F) idle();
const mesh_index_pair closest = find_closest_mesh_point_of_type(REAL, param.XY_pos);
// No more REAL mesh points to invalidate? Assume the user meant
// to invalidate the ENTIRE mesh, which can't be done with
// find_closest_mesh_point (which only returns REAL points).
if (closest.pos.x < 0) { invalidate_all = true; break; }
z_values[closest.pos.x][closest.pos.y] = NAN;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(closest.pos, 0.0f));
}
}
if (invalidate_all) {
invalidate();
SERIAL_ECHOPGM("Entire Mesh");
}
else
SERIAL_ECHOPGM("Locations");
SERIAL_ECHOLNPGM(" invalidated.\n");
}
if (parser.seen('Q')) {
const int16_t test_pattern = parser.has_value() ? parser.value_int() : -99;
if (!WITHIN(test_pattern, TERN0(UBL_DEVEL_DEBUGGING, -1), 2)) {
SERIAL_ECHOLNPGM("?Invalid (Q) test pattern. (" TERN(UBL_DEVEL_DEBUGGING, "-1", "0") " to 2)\n");
return;
}
SERIAL_ECHOLNPGM("Applying test pattern.\n");
switch (test_pattern) {
default:
case -1: TERN_(UBL_DEVEL_DEBUGGING, g29_eeprom_dump()); break;
case 0:
GRID_LOOP(x, y) { // Create a bowl shape similar to a poorly-calibrated Delta
const float p1 = 0.5f * (GRID_MAX_POINTS_X) - x,
p2 = 0.5f * (GRID_MAX_POINTS_Y) - y;
z_values[x][y] += 2.0f * HYPOT(p1, p2);
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
}
break;
case 1:
for (uint8_t x = 0; x < GRID_MAX_POINTS_X; ++x) { // Create a diagonal line several Mesh cells thick that is raised
const uint8_t x2 = x + (x < (GRID_MAX_POINTS_Y) - 1 ? 1 : -1);
z_values[x][x] += 9.999f;
z_values[x][x2] += 9.999f; // We want the altered line several mesh points thick
#if ENABLED(EXTENSIBLE_UI)
ExtUI::onMeshUpdate(x, x, z_values[x][x]);
ExtUI::onMeshUpdate(x, x2, z_values[x][x2]);
#endif
}
break;
case 2:
// Allow the user to specify the height because 10mm is a little extreme in some cases.
for (uint8_t x = (GRID_MAX_POINTS_X) / 3; x < 2 * (GRID_MAX_POINTS_X) / 3; x++) // Create a rectangular raised area in
for (uint8_t y = (GRID_MAX_POINTS_Y) / 3; y < 2 * (GRID_MAX_POINTS_Y) / 3; y++) { // the center of the bed
z_values[x][y] += parser.seen_test('C') ? param.C_constant : 9.99f;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
}
break;
}
}
#if HAS_BED_PROBE
if (parser.seen_test('J')) {
save_ubl_active_state_and_disable();
tilt_mesh_based_on_probed_grid(param.J_grid_size == 0); // Zero size does 3-Point
restore_ubl_active_state();
#if ENABLED(UBL_G29_J_RECENTER)
do_blocking_move_to_xy(0.5f * ((MESH_MIN_X) + (MESH_MAX_X)), 0.5f * ((MESH_MIN_Y) + (MESH_MAX_Y)));
#endif
report_current_position();
probe_deployed = true;
}
#endif // HAS_BED_PROBE
if (parser.seen_test('P')) {
if (WITHIN(param.P_phase, 0, 1) && storage_slot == -1) {
storage_slot = 0;
SERIAL_ECHOLNPGM("Default storage slot 0 selected.");
}
switch (param.P_phase) {
case 0:
//
// Zero Mesh Data
//
reset();
SERIAL_ECHOLNPGM("Mesh zeroed.");
break;
#if HAS_BED_PROBE
case 1: {
//
// Invalidate Entire Mesh and Automatically Probe Mesh in areas that can be reached by the probe
//
if (!parser.seen_test('C')) {
invalidate();
SERIAL_ECHOLNPGM("Mesh invalidated. Probing mesh.");
}
if (param.V_verbosity > 1)
SERIAL_ECHOLN(F("Probing around ("), param.XY_pos.x, C(','), param.XY_pos.y, F(").\n"));
probe_entire_mesh(param.XY_pos, parser.seen_test('T'), parser.seen_test('E'), parser.seen_test('U'));
report_current_position();
probe_deployed = true;
} break;
#endif // HAS_BED_PROBE
case 2: {
#if HAS_MARLINUI_MENU
//
// Manually Probe Mesh in areas that can't be reached by the probe
//
SERIAL_ECHOLNPGM("Manually probing unreachable points.");
do_z_clearance(Z_CLEARANCE_BETWEEN_PROBES);
if (parser.seen_test('C') && !param.XY_seen) {
/**
* Use a good default location for the path.
* The flipped > and < operators in these comparisons is intentional.
* It should cause the probed points to follow a nice path on Cartesian printers.
* It may make sense to have Delta printers default to the center of the bed.
* Until that is decided, this can be forced with the X and Y parameters.
*/
param.XY_pos.set(
#if IS_KINEMATIC
X_HOME_POS, Y_HOME_POS
#else
probe.offset_xy.x > 0 ? X_BED_SIZE : 0,
probe.offset_xy.y < 0 ? Y_BED_SIZE : 0
#endif
);
}
if (parser.seen('B')) {
param.B_shim_thickness = parser.has_value() ? parser.value_float() : measure_business_card_thickness();
if (ABS(param.B_shim_thickness) > 1.5f) {
SERIAL_ECHOLNPGM("?Error in Business Card measurement.");
return;
}
probe_deployed = true;
}
if (!position_is_reachable(param.XY_pos)) {
SERIAL_ECHOLNPGM("XY outside printable radius.");
return;
}
const float height = parser.floatval('H', Z_CLEARANCE_BETWEEN_PROBES);
manually_probe_remaining_mesh(param.XY_pos, height, param.B_shim_thickness, parser.seen_test('T'));
SERIAL_ECHOLNPGM("G29 P2 finished.");
report_current_position();
#else
SERIAL_ECHOLNPGM("?P2 is only available when an LCD is present.");
return;
#endif
} break;
case 3: {
/**
* Populate invalid mesh areas. Proceed with caution.
* Two choices are available:
* - Specify a constant with the 'C' parameter.
* - Allow 'G29 P3' to choose a 'reasonable' constant.
*/
if (param.C_seen) {
if (param.R_repetition >= GRID_MAX_POINTS) {
set_all_mesh_points_to_value(param.C_constant);
}
else {
while (param.R_repetition--) { // this only populates reachable mesh points near
const mesh_index_pair closest = find_closest_mesh_point_of_type(INVALID, param.XY_pos);
const xy_int8_t &cpos = closest.pos;
if (cpos.x < 0) {
// No more REAL INVALID mesh points to populate, so we ASSUME
// user meant to populate ALL INVALID mesh points to value
GRID_LOOP(x, y) if (isnan(z_values[x][y])) z_values[x][y] = param.C_constant;
break; // No more invalid Mesh Points to populate
}
else {
z_values[cpos.x][cpos.y] = param.C_constant;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(cpos, param.C_constant));
}
}
}
}
else {
const float cvf = parser.value_float();
switch ((int)TRUNC(cvf * 10.0f) - 30) { // 3.1 -> 1
#if ENABLED(UBL_G29_P31)
case 1: {
// P3.1 use least squares fit to fill missing mesh values
// P3.10 zero weighting for distance, all grid points equal, best fit tilted plane
// P3.11 10X weighting for nearest grid points versus farthest grid points
// P3.12 100X distance weighting
// P3.13 1000X distance weighting, approaches simple average of nearest points
const float weight_power = (cvf - 3.10f) * 100.0f, // 3.12345 -> 2.345
weight_factor = weight_power ? POW(10.0f, weight_power) : 0;
smart_fill_wlsf(weight_factor);
}
break;
#endif
case 0: // P3 or P3.0
default: // and anything P3.x that's not P3.1
smart_fill_mesh(); // Do a 'Smart' fill using nearby known values
break;
}
}
break;
}
case 4: // Fine Tune (i.e., Edit) the Mesh
#if HAS_MARLINUI_MENU
fine_tune_mesh(param.XY_pos, parser.seen_test('T'));
#else
SERIAL_ECHOLNPGM("?P4 is only available when an LCD is present.");
return;
#endif
break;
case 5: adjust_mesh_to_mean(param.C_seen, param.C_constant); break;
case 6: shift_mesh_height(); break;
}
}
#if ENABLED(UBL_DEVEL_DEBUGGING)
//
// Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
// good to have the extra information. Soon... we prune this to just a few items
//
if (parser.seen_test('W')) g29_what_command();
//
// When we are fully debugged, this may go away. But there are some valid
// use cases for the users. So we can wait and see what to do with it.
//
if (parser.seen('K')) // Kompare Current Mesh Data to Specified Stored Mesh
g29_compare_current_mesh_to_stored_mesh();
#endif // UBL_DEVEL_DEBUGGING
//
// Load a Mesh from the EEPROM
//
if (parser.seen('L')) { // Load Current Mesh Data
param.KLS_storage_slot = parser.has_value() ? (int8_t)parser.value_int() : storage_slot;
int16_t a = settings.calc_num_meshes();
if (!a) {
SERIAL_ECHOLNPGM("?EEPROM storage not available.");
return;
}
if (!WITHIN(param.KLS_storage_slot, 0, a - 1)) {
SERIAL_ECHOLNPGM("?Invalid storage slot.\n?Use 0 to ", a - 1);
return;
}
settings.load_mesh(param.KLS_storage_slot);
storage_slot = param.KLS_storage_slot;
SERIAL_ECHOLNPGM(STR_DONE);
}
//
// Store a Mesh in the EEPROM
//
if (parser.seen('S')) { // Store (or Save) Current Mesh Data
param.KLS_storage_slot = parser.has_value() ? (int8_t)parser.value_int() : storage_slot;
if (param.KLS_storage_slot == -1) // Special case: 'Export' the mesh to the
return report_current_mesh(); // host so it can be saved in a file.
int16_t a = settings.calc_num_meshes();
if (!a) {
SERIAL_ECHOLNPGM("?EEPROM storage not available.");
goto LEAVE;
}
if (!WITHIN(param.KLS_storage_slot, 0, a - 1)) {
SERIAL_ECHOLNPGM("?Invalid storage slot.\n?Use 0 to ", a - 1);
goto LEAVE;
}
settings.store_mesh(param.KLS_storage_slot);
storage_slot = param.KLS_storage_slot;
SERIAL_ECHOLNPGM(STR_DONE);
}
if (parser.seen_test('T'))
display_map(param.T_map_type);
LEAVE:
#if HAS_MARLINUI_MENU
ui.reset_alert_level();
ui.quick_feedback();
ui.reset_status();
ui.release();
#endif
#ifdef EVENT_GCODE_AFTER_G29
if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Z Probe End Script: ", EVENT_GCODE_AFTER_G29);
if (probe_deployed) {
planner.synchronize();
gcode.process_subcommands_now(F(EVENT_GCODE_AFTER_G29));
}
#else
UNUSED(probe_deployed);
#endif
probe.use_probing_tool(false);
return;
}
/**
* M420 C<value>
* G29 P5 C<value> : Adjust Mesh To Mean (and subtract the given offset).
* Find the mean average and shift the mesh to center on that value.
*/
void unified_bed_leveling::adjust_mesh_to_mean(const bool cflag, const_float_t offset) {
float sum = 0;
uint8_t n = 0;
GRID_LOOP(x, y)
if (!isnan(z_values[x][y])) {
sum += z_values[x][y];
n++;
}
const float mean = sum / n;
//
// Sum the squares of difference from mean
//
float sum_of_diff_squared = 0;
GRID_LOOP(x, y)
if (!isnan(z_values[x][y]))
sum_of_diff_squared += sq(z_values[x][y] - mean);
SERIAL_ECHOLNPGM("# of samples: ", n);
SERIAL_ECHOLNPGM("Mean Mesh Height: ", p_float_t(mean, 6));
const float sigma = SQRT(sum_of_diff_squared / (n + 1));
SERIAL_ECHOLNPGM("Standard Deviation: ", p_float_t(sigma, 6));
if (cflag)
GRID_LOOP(x, y)
if (!isnan(z_values[x][y])) {
z_values[x][y] -= mean + offset;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
}
}
/**
* G29 P6 C<offset> : Shift Mesh Height by a uniform constant.
*/
void unified_bed_leveling::shift_mesh_height() {
GRID_LOOP(x, y)
if (!isnan(z_values[x][y])) {
z_values[x][y] += param.C_constant;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
}
}
#if HAS_BED_PROBE
/**
* G29 P1 T<maptype> V<verbosity> : Probe Entire Mesh
* Probe all invalidated locations of the mesh that can be reached by the probe.
* This attempts to fill in locations closest to the nozzle's start location first.
*/
void unified_bed_leveling::probe_entire_mesh(const xy_pos_t &nearby, const bool do_ubl_mesh_map, const bool stow_probe, const bool do_furthest) {
probe.deploy(); // Deploy before ui.capture() to allow for PAUSE_BEFORE_DEPLOY_STOW
TERN_(HAS_MARLINUI_MENU, ui.capture());
TERN_(EXTENSIBLE_UI, ExtUI::onLevelingStart());
save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
grid_count_t count = GRID_MAX_POINTS;
mesh_index_pair best;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(best.pos, ExtUI::G29_START));
do {
if (do_ubl_mesh_map) display_map(param.T_map_type);
const grid_count_t point_num = (GRID_MAX_POINTS - count) + 1;
SERIAL_ECHOLNPGM("Probing mesh point ", point_num, "/", GRID_MAX_POINTS, ".");
TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " %i/%i"), GET_TEXT_F(MSG_PROBING_POINT), point_num, int(GRID_MAX_POINTS)));
TERN_(HAS_BACKLIGHT_TIMEOUT, ui.refresh_backlight_timeout());
#if HAS_MARLINUI_MENU
if (ui.button_pressed()) {
ui.quick_feedback(false); // Preserve button state for click-and-hold
SERIAL_ECHOLNPGM("\nMesh only partially populated.\n");
ui.wait_for_release();
ui.quick_feedback();
ui.release();
probe.stow(); // Release UI before stow to allow for PAUSE_BEFORE_DEPLOY_STOW
return restore_ubl_active_state();
}
#endif
#ifndef HUGE_VALF
#define HUGE_VALF __FLT_MAX__
#endif
best = do_furthest // Points with valid data or HUGE_VALF are skipped
? find_furthest_invalid_mesh_point()
: find_closest_mesh_point_of_type(INVALID, nearby, true);
if (best.pos.x >= 0) { // mesh point found and is reachable by probe
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(best.pos, ExtUI::G29_POINT_START));
const float measured_z = probe.probe_at_point(best.meshpos(), stow_probe ? PROBE_PT_STOW : PROBE_PT_RAISE, param.V_verbosity);
z_values[best.pos.x][best.pos.y] = isnan(measured_z) ? HUGE_VALF : measured_z; // Mark invalid point already probed with HUGE_VALF to omit it in the next loop
#if ENABLED(EXTENSIBLE_UI)
ExtUI::onMeshUpdate(best.pos, ExtUI::G29_POINT_FINISH);
ExtUI::onMeshUpdate(best.pos, measured_z);
#endif
}
SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
} while (best.pos.x >= 0 && --count);
GRID_LOOP(x, y) if (z_values[x][y] == HUGE_VALF) z_values[x][y] = NAN; // Restore NAN for HUGE_VALF marks
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(best.pos, ExtUI::G29_FINISH));
// Release UI during stow to allow for PAUSE_BEFORE_DEPLOY_STOW
TERN_(HAS_MARLINUI_MENU, ui.release());
probe.stow();
TERN_(HAS_MARLINUI_MENU, ui.capture());
probe.move_z_after_probing();
do_blocking_move_to_xy(
constrain(nearby.x - probe.offset_xy.x, MESH_MIN_X, MESH_MAX_X),
constrain(nearby.y - probe.offset_xy.y, MESH_MIN_Y, MESH_MAX_Y)
);
restore_ubl_active_state();
}
#endif // HAS_BED_PROBE
void set_message_with_feedback(FSTR_P const fstr) {
#if HAS_MARLINUI_MENU
ui.set_status(fstr);
ui.quick_feedback();
#else
UNUSED(fstr);
#endif
}
#if HAS_MARLINUI_MENU
typedef void (*clickFunc_t)();
bool _click_and_hold(const clickFunc_t func=nullptr) {
if (ui.button_pressed()) {
ui.quick_feedback(false); // Preserve button state for click-and-hold
const millis_t nxt = millis() + 1500UL;
while (ui.button_pressed()) { // Loop while the encoder is pressed. Uses hardware flag!
idle(); // idle, of course
if (ELAPSED(millis(), nxt)) { // After 1.5 seconds
ui.quick_feedback();
if (func) (*func)();
ui.wait_for_release();
return true;
}
}
}
serial_delay(15);
return false;
}
void unified_bed_leveling::move_z_with_encoder(const_float_t multiplier) {
ui.wait_for_release();
while (!ui.button_pressed()) {
idle();
gcode.reset_stepper_timeout(); // Keep steppers powered
if (encoder_diff) {
do_blocking_move_to_z(current_position.z + float(encoder_diff) * multiplier);
encoder_diff = 0;
}
}
}
float unified_bed_leveling::measure_point_with_encoder() {
KEEPALIVE_STATE(PAUSED_FOR_USER);
const float z_step = 0.01f;
move_z_with_encoder(z_step);
return current_position.z;
}
static void echo_and_take_a_measurement() { SERIAL_ECHOLNPGM(" and take a measurement."); }
float unified_bed_leveling::measure_business_card_thickness() {
ui.capture();
save_ubl_active_state_and_disable(); // Disable bed level correction for probing
do_blocking_move_to(
xyz_pos_t({
0.5f * ((MESH_MAX_X) - (MESH_MIN_X)),
0.5f * ((MESH_MAX_Y) - (MESH_MIN_Y)),
MANUAL_PROBE_START_Z
#ifdef SAFE_BED_LEVELING_START_I
, SAFE_BED_LEVELING_START_I
#endif
#ifdef SAFE_BED_LEVELING_START_J
, SAFE_BED_LEVELING_START_J
#endif
#ifdef SAFE_BED_LEVELING_START_K
, SAFE_BED_LEVELING_START_K
#endif
#ifdef SAFE_BED_LEVELING_START_U
, SAFE_BED_LEVELING_START_U
#endif
#ifdef SAFE_BED_LEVELING_START_V
, SAFE_BED_LEVELING_START_V
#endif
#ifdef SAFE_BED_LEVELING_START_W
, SAFE_BED_LEVELING_START_W
#endif
})
//, _MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS]) * 0.5f
);
planner.synchronize();
SERIAL_ECHOPGM("Place shim under nozzle");
LCD_MESSAGE(MSG_UBL_BC_INSERT);
ui.return_to_status();
echo_and_take_a_measurement();
const float z1 = measure_point_with_encoder();
do_z_clearance_by(SIZE_OF_LITTLE_RAISE);
SERIAL_ECHOPGM("Remove shim");
LCD_MESSAGE(MSG_UBL_BC_REMOVE);
echo_and_take_a_measurement();
const float z2 = measure_point_with_encoder();
do_z_clearance_by(Z_CLEARANCE_BETWEEN_PROBES);
const float thickness = ABS(z1 - z2);
if (param.V_verbosity > 1)
SERIAL_ECHOLNPGM("Business Card is ", p_float_t(thickness, 4), "mm thick.");
restore_ubl_active_state();
return thickness;
}
/**
* G29 P2 : Manually Probe Remaining Mesh Points.
* Move to INVALID points and
* NOTE: Blocks the G-code queue and captures Marlin UI during use.
*/
void unified_bed_leveling::manually_probe_remaining_mesh(const xy_pos_t &pos, const_float_t z_clearance, const_float_t thick, const bool do_ubl_mesh_map) {
ui.capture();
TERN_(EXTENSIBLE_UI, ExtUI::onLevelingStart());
save_ubl_active_state_and_disable(); // No bed level correction so only raw data is obtained
do_blocking_move_to_xy_z(current_position, z_clearance);
ui.return_to_status();
mesh_index_pair location;
const xy_int8_t &lpos = location.pos;
do {
location = find_closest_mesh_point_of_type(INVALID, pos);
// It doesn't matter if the probe can't reach the NAN location. This is a manual probe.
if (!location.valid()) continue;
const xyz_pos_t ppos = { get_mesh_x(lpos.x), get_mesh_y(lpos.y), z_clearance };
if (!position_is_reachable(ppos)) break; // SHOULD NOT OCCUR (find_closest_mesh_point only returns reachable points)
LCD_MESSAGE(MSG_UBL_MOVING_TO_NEXT);
do_blocking_move_to(ppos);
do_z_clearance(z_clearance);
KEEPALIVE_STATE(PAUSED_FOR_USER);
ui.capture();
if (do_ubl_mesh_map) display_map(param.T_map_type); // Show user where we're probing
if (parser.seen_test('B')) {
SERIAL_ECHOPGM("Place Shim & Measure");
LCD_MESSAGE(MSG_UBL_BC_INSERT);
}
else {
SERIAL_ECHOPGM("Measure");
LCD_MESSAGE(MSG_UBL_BC_INSERT2);
}
const float z_step = 0.01f; // 0.01mm per encoder tick, occasionally step
move_z_with_encoder(z_step);
if (_click_and_hold([]{
SERIAL_ECHOLNPGM("\nMesh only partially populated.");
do_z_clearance(Z_CLEARANCE_DEPLOY_PROBE);
})) return restore_ubl_active_state();
// Store the Z position minus the shim height
z_values[lpos.x][lpos.y] = current_position.z - thick;
// Tell the external UI to update
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location, z_values[lpos.x][lpos.y]));
if (param.V_verbosity > 2)
SERIAL_ECHOLNPGM("Mesh Point Measured at: ", p_float_t(z_values[lpos.x][lpos.y], 6));
SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
} while (location.valid());
if (do_ubl_mesh_map) display_map(param.T_map_type); // show user where we're probing
restore_ubl_active_state();
do_blocking_move_to_xy_z(pos, Z_CLEARANCE_DEPLOY_PROBE);
}
/**
* G29 P4 : Mesh Fine-Tuning. Go to point(s) and adjust values with the LCD.
* NOTE: Blocks the G-code queue and captures Marlin UI during use.
*/
void unified_bed_leveling::fine_tune_mesh(const xy_pos_t &pos, const bool do_ubl_mesh_map) {
if (!parser.seen_test('R')) // fine_tune_mesh() is special. If no repetition count flag is specified
param.R_repetition = 1; // do exactly one mesh location. Otherwise use what the parser decided.
#if ENABLED(UBL_MESH_EDIT_MOVES_Z)
const float h_offset = parser.seenval('H') ? parser.value_linear_units() : MANUAL_PROBE_START_Z;
if (!WITHIN(h_offset, 0, 10)) {
SERIAL_ECHOLNPGM("Offset out of bounds. (0 to 10mm)\n");
return;
}
#endif
mesh_index_pair location;
if (!position_is_reachable(pos)) {
SERIAL_ECHOLNPGM("(X,Y) outside printable radius.");
return;
}
save_ubl_active_state_and_disable();
LCD_MESSAGE(MSG_UBL_FINE_TUNE_MESH);
ui.capture(); // Take over control of the LCD encoder
do_blocking_move_to_xy_z(pos, Z_TWEEN_SAFE_CLEARANCE); // Move to the given XY with probe clearance
MeshFlags done_flags{0};
const xy_int8_t &lpos = location.pos;
#if IS_TFTGLCD_PANEL
ui.ubl_mesh_edit_start(0); // Change current screen before calling ui.ubl_plot
safe_delay(50);
#endif
do {
location = find_closest_mesh_point_of_type(SET_IN_BITMAP, pos, false, &done_flags);
if (lpos.x < 0) break; // Stop when there are no more reachable points
done_flags.mark(lpos); // Mark this location as 'adjusted' so a new
// location is used on the next loop
const xyz_pos_t raw = { get_mesh_x(lpos.x), get_mesh_y(lpos.y), Z_TWEEN_SAFE_CLEARANCE };
if (!position_is_reachable(raw)) break; // SHOULD NOT OCCUR (find_closest_mesh_point_of_type only returns reachable)
do_blocking_move_to(raw); // Move the nozzle to the edit point with probe clearance
TERN_(UBL_MESH_EDIT_MOVES_Z, do_blocking_move_to_z(h_offset)); // Move Z to the given 'H' offset before editing
KEEPALIVE_STATE(PAUSED_FOR_USER);
if (do_ubl_mesh_map) display_map(param.T_map_type); // Display the current point
#if IS_TFTGLCD_PANEL
ui.ubl_plot(lpos.x, lpos.y); // update plot screen
#endif
ui.refresh();
float new_z = z_values[lpos.x][lpos.y];
if (isnan(new_z)) new_z = 0; // Invalid points begin at 0
new_z = FLOOR(new_z * 1000) * 0.001f; // Chop off digits after the 1000ths place
ui.ubl_mesh_edit_start(new_z);
SET_SOFT_ENDSTOP_LOOSE(true);
do {
idle_no_sleep();
new_z = ui.ubl_mesh_value();
TERN_(UBL_MESH_EDIT_MOVES_Z, do_blocking_move_to_z(h_offset + new_z)); // Move the nozzle as the point is edited
SERIAL_FLUSH(); // Prevent host M105 buffer overrun.
} while (!ui.button_pressed());
SET_SOFT_ENDSTOP_LOOSE(false);
if (!lcd_map_control) ui.return_to_status(); // Just editing a single point? Return to status
// Button held down? Abort editing
if (_click_and_hold([]{
ui.return_to_status();
do_z_clearance(Z_TWEEN_SAFE_CLEARANCE);
set_message_with_feedback(GET_TEXT_F(MSG_EDITING_STOPPED));
})) break;
// TODO: Disable leveling here so the Z value becomes the 'native' Z value.
z_values[lpos.x][lpos.y] = new_z; // Save the updated Z value
// TODO: Re-enable leveling here so Z is correctly based on the updated mesh.
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location, new_z));
serial_delay(20); // No switch noise
ui.refresh();
} while (lpos.x >= 0 && --param.R_repetition > 0);
if (do_ubl_mesh_map) display_map(param.T_map_type);
restore_ubl_active_state();
do_blocking_move_to_xy_z(pos, Z_TWEEN_SAFE_CLEARANCE);
LCD_MESSAGE(MSG_UBL_DONE_EDITING_MESH);
SERIAL_ECHOLNPGM("Done Editing Mesh");
if (lcd_map_control)
ui.goto_screen(ubl_map_screen);
else
ui.return_to_status();
}
#endif // HAS_MARLINUI_MENU
/**
* Parse and validate most G29 parameters, store for use by G29 functions.
*/
bool unified_bed_leveling::G29_parse_parameters() {
bool err_flag = false;
set_message_with_feedback(GET_TEXT_F(MSG_UBL_DOING_G29));
param.C_constant = 0;
param.R_repetition = 0;
if (parser.seen('R')) {
param.R_repetition = parser.has_value() ? parser.value_ushort() : GRID_MAX_POINTS;
NOMORE(param.R_repetition, GRID_MAX_POINTS);
if (param.R_repetition < 1) {
SERIAL_ECHOLNPGM("?(R)epetition count invalid (1+).\n");
return UBL_ERR;
}
}
param.V_verbosity = parser.byteval('V');
if (!WITHIN(param.V_verbosity, 0, 4)) {
SERIAL_ECHOLNPGM("?(V)erbose level implausible (0-4).\n");
err_flag = true;
}
if (parser.seen('P')) {
const uint8_t pv = parser.value_byte();
#if !HAS_BED_PROBE
if (pv == 1) {
SERIAL_ECHOLNPGM("G29 P1 requires a probe.\n");
err_flag = true;
}
else
#endif
{
param.P_phase = pv;
if (!WITHIN(param.P_phase, 0, 6)) {
SERIAL_ECHOLNPGM("?(P)hase value invalid (0-6).\n");
err_flag = true;
}
}
}
if (parser.seen('J')) {
#if HAS_BED_PROBE
param.J_grid_size = parser.value_byte();
if (param.J_grid_size && !WITHIN(param.J_grid_size, 2, 9)) {
SERIAL_ECHOLNPGM("?Invalid grid size (J) specified (2-9).\n");
err_flag = true;
}
#else
SERIAL_ECHOLNPGM("G29 J action requires a probe.\n");
err_flag = true;
#endif
}
param.XY_seen.x = parser.seenval('X');
float sx = param.XY_seen.x ? parser.value_float() : current_position.x;
param.XY_seen.y = parser.seenval('Y');
float sy = param.XY_seen.y ? parser.value_float() : current_position.y;
if (param.XY_seen.x != param.XY_seen.y) {
SERIAL_ECHOLNPGM("Both X & Y locations must be specified.\n");
err_flag = true;
}
// If X or Y are not valid, use center of the bed values
// (for UBL_HILBERT_CURVE default to lower-left corner instead)
if (!COORDINATE_OKAY(sx, X_MIN_BED, X_MAX_BED)) sx = TERN(UBL_HILBERT_CURVE, 0, X_CENTER);
if (!COORDINATE_OKAY(sy, Y_MIN_BED, Y_MAX_BED)) sy = TERN(UBL_HILBERT_CURVE, 0, Y_CENTER);
if (err_flag) return UBL_ERR;
param.XY_pos.set(sx, sy);
/**
* Activate or deactivate UBL
* Note: UBL's G29 restores the state set here when done.
* Leveling is being enabled here with old data, possibly
* none. Error handling should disable for safety...
*/
if (parser.seen_test('A')) {
if (parser.seen_test('D')) {
SERIAL_ECHOLNPGM("?Can't activate and deactivate at the same time.\n");
return UBL_ERR;
}
set_bed_leveling_enabled(true);
report_state();
}
else if (parser.seen_test('D')) {
set_bed_leveling_enabled(false);
report_state();
}
// Set global 'C' flag and its value
if ((param.C_seen = parser.seen('C')))
param.C_constant = parser.value_float();
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
if (parser.seenval('F')) {
const float fh = parser.value_float();
if (!WITHIN(fh, 0, 100)) {
SERIAL_ECHOLNPGM("?(F)ade height for Bed Level Correction not plausible.\n");
return UBL_ERR;
}
set_z_fade_height(fh);
}
#endif
param.T_map_type = parser.byteval('T');
if (!WITHIN(param.T_map_type, 0, 2)) {
SERIAL_ECHOLNPGM("Invalid map type.\n");
return UBL_ERR;
}
return UBL_OK;
}
static uint8_t ubl_state_at_invocation = 0;
#if ENABLED(UBL_DEVEL_DEBUGGING)
static uint8_t ubl_state_recursion_chk = 0;
#endif
void unified_bed_leveling::save_ubl_active_state_and_disable() {
#if ENABLED(UBL_DEVEL_DEBUGGING)
ubl_state_recursion_chk++;
if (ubl_state_recursion_chk != 1) {
SERIAL_ECHOLNPGM("save_ubl_active_state_and_disabled() called multiple times in a row.");
set_message_with_feedback(GET_TEXT_F(MSG_UBL_SAVE_ERROR));
return;
}
#endif
ubl_state_at_invocation = planner.leveling_active;
set_bed_leveling_enabled(false);
}
void unified_bed_leveling::restore_ubl_active_state(const bool is_done/*=true*/) {
TERN_(HAS_MARLINUI_MENU, ui.release());
#if ENABLED(UBL_DEVEL_DEBUGGING)
if (--ubl_state_recursion_chk) {
SERIAL_ECHOLNPGM("restore_ubl_active_state() called too many times.");
set_message_with_feedback(GET_TEXT_F(MSG_UBL_RESTORE_ERROR));
return;
}
#endif
set_bed_leveling_enabled(ubl_state_at_invocation);
if (is_done) {
TERN_(EXTENSIBLE_UI, ExtUI::onLevelingDone());
}
}
mesh_index_pair unified_bed_leveling::find_furthest_invalid_mesh_point() {
bool found_a_NAN = false, found_a_real = false;
mesh_index_pair farthest { -1, -1, -99999.99 };
GRID_LOOP(i, j) {
if (!isnan(z_values[i][j])) continue; // Skip valid mesh points
// Skip unreachable points
if (!probe.can_reach(get_mesh_x(i), get_mesh_y(j)))
continue;
found_a_NAN = true;
xy_int8_t nearby { -1, -1 };
float d1, d2 = 99999.9f;
GRID_LOOP(k, l) {
if (isnan(z_values[k][l])) continue;
found_a_real = true;
// Add in a random weighting factor that scrambles the probing of the
// last half of the mesh (when every unprobed mesh point is one index
// from a probed location).
d1 = HYPOT(i - k, j - l) + (1.0f / ((millis() % 47) + 13));
if (d1 < d2) { // Invalid mesh point (i,j) is closer to the defined point (k,l)
d2 = d1;
nearby.set(i, j);
}
}
//
// At this point d2 should have the near defined mesh point to invalid mesh point (i,j)
//
if (found_a_real && nearby.x >= 0 && d2 > farthest.distance) {
farthest.pos = nearby; // Found an invalid location farther from the defined mesh point
farthest.distance = d2;
}
} // GRID_LOOP
if (!found_a_real && found_a_NAN) { // if the mesh is totally unpopulated, start the probing
farthest.pos.set((GRID_MAX_POINTS_X) / 2, (GRID_MAX_POINTS_Y) / 2);
farthest.distance = 1;
}
return farthest;
}
#if ENABLED(UBL_HILBERT_CURVE)
typedef struct {
MeshPointType type;
MeshFlags *done_flags;
bool probe_relative;
mesh_index_pair closest;
} find_closest_t;
static bool test_func(uint8_t i, uint8_t j, void *data) {
find_closest_t *d = (find_closest_t*)data;
if ( d->type == CLOSEST || d->type == (isnan(bedlevel.z_values[i][j]) ? INVALID : REAL)
|| (d->type == SET_IN_BITMAP && !d->done_flags->marked(i, j))
) {
// Found a Mesh Point of the specified type!
const xy_pos_t mpos = { bedlevel.get_mesh_x(i), bedlevel.get_mesh_y(j) };
// If using the probe as the reference there are some unreachable locations.
// Also for round beds, there are grid points outside the bed the nozzle can't reach.
// Prune them from the list and ignore them till the next Phase (manual nozzle probing).
if (!(d->probe_relative ? probe.can_reach(mpos) : position_is_reachable(mpos)))
return false;
d->closest.pos.set(i, j);
return true;
}
return false;
}
#endif
mesh_index_pair unified_bed_leveling::find_closest_mesh_point_of_type(const MeshPointType type, const xy_pos_t &pos, const bool probe_relative/*=false*/, MeshFlags *done_flags/*=nullptr*/) {
#if ENABLED(UBL_HILBERT_CURVE)
find_closest_t d;
d.type = type;
d.done_flags = done_flags;
d.probe_relative = probe_relative;
d.closest.invalidate();
hilbert_curve::search_from_closest(pos, test_func, &d);
return d.closest;
#else
mesh_index_pair closest;
closest.invalidate();
closest.distance = -99999.9f;
// Get the reference position, either nozzle or probe
const xy_pos_t ref = probe_relative ? pos + probe.offset_xy : pos;
float best_so_far = 99999.99f;
GRID_LOOP(i, j) {
if ( type == CLOSEST || type == (isnan(z_values[i][j]) ? INVALID : REAL)
|| (type == SET_IN_BITMAP && !done_flags->marked(i, j))
) {
// Found a Mesh Point of the specified type!
const xy_pos_t mpos = { get_mesh_x(i), get_mesh_y(j) };
// If using the probe as the reference there are some unreachable locations.
// Also for round beds, there are grid points outside the bed the nozzle can't reach.
// Prune them from the list and ignore them till the next Phase (manual nozzle probing).
if (!(probe_relative ? probe.can_reach(mpos) : position_is_reachable(mpos)))
continue;
// Reachable. Check if it's the best_so_far location to the nozzle.
const xy_pos_t diff = current_position - mpos;
const float distance = (ref - mpos).magnitude() + diff.magnitude() * 0.1f;
// factor in the distance from the current location for the normal case
// so the nozzle isn't running all over the bed.
if (distance < best_so_far) {
best_so_far = distance; // Found a closer location with the desired value type.
closest.pos.set(i, j);
closest.distance = best_so_far;
}
}
} // GRID_LOOP
return closest;
#endif
}
/**
* 'Smart Fill': Scan from the outward edges of the mesh towards the center.
* If an invalid location is found, use the next two points (if valid) to
* calculate a 'reasonable' value for the unprobed mesh point.
*/
bool unified_bed_leveling::smart_fill_one(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
const float v = z_values[x][y];
if (isnan(v)) { // A NAN...
const int8_t dx = x + xdir, dy = y + ydir;
const float v1 = z_values[dx][dy];
if (!isnan(v1)) { // ...next to a pair of real values?
const float v2 = z_values[dx + xdir][dy + ydir];
if (!isnan(v2)) {
z_values[x][y] = v1 < v2 ? v1 : v1 + v1 - v2;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
return true;
}
}
}
return false;
}
typedef struct { uint8_t sx, ex, sy, ey; bool yfirst; } smart_fill_info;
void unified_bed_leveling::smart_fill_mesh() {
static const smart_fill_info
info0 PROGMEM = { 0, GRID_MAX_POINTS_X, 0, (GRID_MAX_POINTS_Y) - 2, false }, // Bottom of the mesh looking up
info1 PROGMEM = { 0, GRID_MAX_POINTS_X, (GRID_MAX_POINTS_Y) - 1, 0, false }, // Top of the mesh looking down
info2 PROGMEM = { 0, (GRID_MAX_POINTS_X) - 2, 0, GRID_MAX_POINTS_Y, true }, // Left side of the mesh looking right
info3 PROGMEM = { (GRID_MAX_POINTS_X) - 1, 0, 0, GRID_MAX_POINTS_Y, true }; // Right side of the mesh looking left
static const smart_fill_info * const info[] PROGMEM = { &info0, &info1, &info2, &info3 };
for (uint8_t i = 0; i < COUNT(info); ++i) {
const smart_fill_info *f = (smart_fill_info*)pgm_read_ptr(&info[i]);
const int8_t sx = pgm_read_byte(&f->sx), sy = pgm_read_byte(&f->sy),
ex = pgm_read_byte(&f->ex), ey = pgm_read_byte(&f->ey);
if (pgm_read_byte(&f->yfirst)) {
const int8_t dir = ex > sx ? 1 : -1;
for (uint8_t y = sy; y != ey; ++y)
for (uint8_t x = sx; x != ex; x += dir)
if (smart_fill_one(x, y, dir, 0)) break;
}
else {
const int8_t dir = ey > sy ? 1 : -1;
for (uint8_t x = sx; x != ex; ++x)
for (uint8_t y = sy; y != ey; y += dir)
if (smart_fill_one(x, y, 0, dir)) break;
}
}
}
#if HAS_BED_PROBE
//#define VALIDATE_MESH_TILT
#include "../../../libs/vector_3.h"
void unified_bed_leveling::tilt_mesh_based_on_probed_grid(const bool do_3_pt_leveling) {
float measured_z;
bool abort_flag = false;
struct linear_fit_data lsf_results;
incremental_LSF_reset(&lsf_results);
if (do_3_pt_leveling) {
xy_float_t points[3];
probe.get_three_points(points);
#if ENABLED(UBL_TILT_ON_MESH_POINTS_3POINT)
mesh_index_pair cpos[3];
for (uint8_t ix = 0; ix < 3; ++ix) { // Convert points to coordinates of mesh points
cpos[ix] = find_closest_mesh_point_of_type(REAL, points[ix], true);
points[ix] = cpos[ix].meshpos();
}
#endif
#if ENABLED(VALIDATE_MESH_TILT)
float gotz[3]; // Used for algorithm validation below
#endif
for (uint8_t i = 0; i < 3; ++i) {
SERIAL_ECHOLNPGM("Tilting mesh (", i + 1, "/3)");
TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " %i/3"), GET_TEXT_F(MSG_LCD_TILTING_MESH), i + 1));
measured_z = probe.probe_at_point(points[i], i < 2 ? PROBE_PT_RAISE : PROBE_PT_LAST_STOW, param.V_verbosity);
if ((abort_flag = isnan(measured_z))) break;
measured_z -= TERN(UBL_TILT_ON_MESH_POINTS_3POINT, z_values[cpos[i].pos.x][cpos[i].pos.y], get_z_correction(points[i]));
TERN_(VALIDATE_MESH_TILT, gotz[i] = measured_z);
if (param.V_verbosity > 3) { SERIAL_ECHO_SP(16); SERIAL_ECHOLNPGM("Corrected_Z=", measured_z); }
incremental_LSF(&lsf_results, points[i], measured_z);
}
probe.stow();
probe.move_z_after_probing();
if (abort_flag) {
SERIAL_ECHOLNPGM("?Error probing point. Aborting operation.");
return;
}
}
else { // !do_3_pt_leveling
#ifndef G29J_MESH_TILT_MARGIN
#define G29J_MESH_TILT_MARGIN 0
#endif
const float x_min = _MAX((X_MIN_POS) + (G29J_MESH_TILT_MARGIN), MESH_MIN_X, probe.min_x()),
x_max = _MIN((X_MAX_POS) - (G29J_MESH_TILT_MARGIN), MESH_MAX_X, probe.max_x()),
y_min = _MAX((Y_MIN_POS) + (G29J_MESH_TILT_MARGIN), MESH_MIN_Y, probe.min_y()),
y_max = _MIN((Y_MAX_POS) - (G29J_MESH_TILT_MARGIN), MESH_MAX_Y, probe.max_y()),
dx = (x_max - x_min) / (param.J_grid_size - 1),
dy = (y_max - y_min) / (param.J_grid_size - 1);
bool zig_zag = false;
const uint16_t total_points = sq(param.J_grid_size);
uint16_t point_num = 1;
for (uint8_t ix = 0; ix < param.J_grid_size; ++ix) {
xy_pos_t rpos;
rpos.x = x_min + ix * dx;
for (uint8_t iy = 0; iy < param.J_grid_size; ++iy) {
rpos.y = y_min + dy * (zig_zag ? param.J_grid_size - 1 - iy : iy);
#if ENABLED(UBL_TILT_ON_MESH_POINTS)
#if ENABLED(DEBUG_LEVELING_FEATURE)
xy_pos_t oldRpos;
if (DEBUGGING(LEVELING)) oldRpos = rpos;
#endif
mesh_index_pair cpos;
rpos -= probe.offset;
cpos = find_closest_mesh_point_of_type(REAL, rpos, true);
rpos = cpos.meshpos();
#endif
SERIAL_ECHOLNPGM("Tilting mesh point ", point_num, "/", total_points, "\n");
TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " %i/%i"), GET_TEXT_F(MSG_LCD_TILTING_MESH), point_num, total_points));
measured_z = probe.probe_at_point(rpos, parser.seen_test('E') ? PROBE_PT_STOW : PROBE_PT_RAISE, param.V_verbosity); // TODO: Needs error handling
if ((abort_flag = isnan(measured_z))) break;
const float zcorr = TERN(UBL_TILT_ON_MESH_POINTS, z_values[cpos.pos.x][cpos.pos.y], get_z_correction(rpos));
#if ENABLED(DEBUG_LEVELING_FEATURE)
if (DEBUGGING(LEVELING)) {
#if ENABLED(UBL_TILT_ON_MESH_POINTS)
const xy_pos_t oldLpos = oldRpos.asLogical();
DEBUG_ECHO(F("Calculated point: ("), p_float_t(oldRpos.x, 7), C(','), p_float_t(oldRpos.y, 7),
F(") logical: ("), p_float_t(oldLpos.x, 7), C(','), p_float_t(oldLpos.y, 7),
F(")\nSelected mesh point: ")
);
#endif
const xy_pos_t lpos = rpos.asLogical();
DEBUG_ECHO( C('('), p_float_t(rpos.x, 7), C(','), p_float_t(rpos.y, 7),
F(") logical: ("), p_float_t(lpos.x, 7), C(','), p_float_t(lpos.y, 7),
F(") measured: "), p_float_t(measured_z, 7),
F(" correction: "), p_float_t(zcorr, 7)
);
}
#endif
measured_z -= zcorr;
if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM(" final >>>---> ", p_float_t(measured_z, 7));
if (param.V_verbosity > 3) {
SERIAL_ECHO_SP(16);
SERIAL_ECHOLNPGM("Corrected_Z=", measured_z);
}
incremental_LSF(&lsf_results, rpos, measured_z);
point_num++;
}
if (abort_flag) break;
zig_zag ^= true;
}
}
probe.stow();
probe.move_z_after_probing();
if (abort_flag || finish_incremental_LSF(&lsf_results)) {
SERIAL_ECHOLNPGM("Could not complete LSF!");
return;
}
vector_3 normal = vector_3(lsf_results.A, lsf_results.B, 1).get_normal();
if (param.V_verbosity > 2)
SERIAL_ECHOLN(F("bed plane normal = ["), p_float_t(normal.x, 7), C(','), p_float_t(normal.y, 7), C(','), p_float_t(normal.z, 7), C(']'));
matrix_3x3 rotation = matrix_3x3::create_look_at(vector_3(lsf_results.A, lsf_results.B, 1));
GRID_LOOP(i, j) {
float mx = get_mesh_x(i), my = get_mesh_y(j), mz = z_values[i][j];
if (DEBUGGING(LEVELING)) {
DEBUG_ECHOLN(F("before rotation = ["), p_float_t(mx, 7), C(','), p_float_t(my, 7), C(','), p_float_t(mz, 7), F("] ---> "));
DEBUG_DELAY(20);
}
rotation.apply_rotation_xyz(mx, my, mz);
if (DEBUGGING(LEVELING)) {
DEBUG_ECHOLN(F("after rotation = ["), p_float_t(mx, 7), C(','), p_float_t(my, 7), C(','), p_float_t(mz, 7), F("] ---> "));
DEBUG_DELAY(20);
}
z_values[i][j] = mz - lsf_results.D;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(i, j, z_values[i][j]));
}
if (DEBUGGING(LEVELING)) {
rotation.debug(F("rotation matrix:\n"));
DEBUG_ECHOLN(F("LSF Results A="), p_float_t(lsf_results.A, 7), F(" B="), p_float_t(lsf_results.B, 7), F(" D="), p_float_t(lsf_results.D, 7));
DEBUG_DELAY(55);
DEBUG_ECHOLN(F("bed plane normal = ["), p_float_t(normal.x, 7), C(','), p_float_t(normal.y, 7), C(','), p_float_t(normal.z, 7), C(']'));
DEBUG_EOL();
/**
* Use the code below to check the validity of the mesh tilting algorithm.
* 3-Point Mesh Tilt uses the same algorithm as grid-based tilting, but only
* three points are used in the calculation. This guarantees that each probed point
* has an exact match when get_z_correction() for that location is calculated.
* The Z error between the probed point locations and the get_z_correction()
* numbers for those locations should be 0.
*/
#if ENABLED(VALIDATE_MESH_TILT)
auto d_from = []{ DEBUG_ECHOPGM("D from "); };
auto normed = [&](const xy_pos_t &pos, const_float_t zadd) {
return normal.x * pos.x + normal.y * pos.y + zadd;
};
auto debug_pt = [](const int num, const xy_pos_t &pos, const_float_t zadd) {
d_from();
DEBUG_ECHOLN(F("Point "), num, C(':'), p_float_t(normed(pos, zadd), 6), F(" Z error = "), p_float_t(zadd - get_z_correction(pos), 6));
};
debug_pt(1, probe_pt[0], normal.z * gotz[0]);
debug_pt(2, probe_pt[1], normal.z * gotz[1]);
debug_pt(3, probe_pt[2], normal.z * gotz[2]);
#if ENABLED(Z_SAFE_HOMING)
constexpr xy_float_t safe_xy = { Z_SAFE_HOMING_X_POINT, Z_SAFE_HOMING_Y_POINT };
d_from(); DEBUG_ECHOLN(F("safe home with Z="), F("0 : "), p_float_t(normed(safe_xy, 0), 6));
d_from(); DEBUG_ECHOLN(F("safe home with Z="), F("mesh value "), p_float_t(normed(safe_xy, get_z_correction(safe_xy)), 6));
DEBUG_ECHO(F(" Z error = ("), Z_SAFE_HOMING_X_POINT, C(','), Z_SAFE_HOMING_Y_POINT, F(") = "), p_float_t(get_z_correction(safe_xy), 6));
#endif
#endif
} // DEBUGGING(LEVELING)
}
#endif // HAS_BED_PROBE
#if ENABLED(UBL_G29_P31)
void unified_bed_leveling::smart_fill_wlsf(const_float_t weight_factor) {
// For each undefined mesh point, compute a distance-weighted least squares fit
// from all the originally populated mesh points, weighted toward the point
// being extrapolated so that nearby points will have greater influence on
// the point being extrapolated. Then extrapolate the mesh point from WLSF.
static_assert((GRID_MAX_POINTS_Y) <= 16, "GRID_MAX_POINTS_Y too big");
uint16_t bitmap[GRID_MAX_POINTS_X] = { 0 };
struct linear_fit_data lsf_results;
SERIAL_ECHOPGM("Extrapolating mesh...");
const float weight_scaled = weight_factor * _MAX(MESH_X_DIST, MESH_Y_DIST);
GRID_LOOP(jx, jy) if (!isnan(z_values[jx][jy])) SBI(bitmap[jx], jy);
xy_pos_t ppos;
for (uint8_t ix = 0; ix < GRID_MAX_POINTS_X; ++ix) {
ppos.x = get_mesh_x(ix);
for (uint8_t iy = 0; iy < GRID_MAX_POINTS_Y; ++iy) {
ppos.y = get_mesh_y(iy);
if (isnan(z_values[ix][iy])) {
// undefined mesh point at (ppos.x,ppos.y), compute weighted LSF from original valid mesh points.
incremental_LSF_reset(&lsf_results);
xy_pos_t rpos;
for (uint8_t jx = 0; jx < GRID_MAX_POINTS_X; ++jx) {
rpos.x = get_mesh_x(jx);
for (uint8_t jy = 0; jy < GRID_MAX_POINTS_Y; ++jy) {
if (TEST(bitmap[jx], jy)) {
rpos.y = get_mesh_y(jy);
const float rz = z_values[jx][jy],
w = 1.0f + weight_scaled / (rpos - ppos).magnitude();
incremental_WLSF(&lsf_results, rpos, rz, w);
}
}
}
if (finish_incremental_LSF(&lsf_results)) {
SERIAL_ECHOLNPGM(" Insufficient data");
return;
}
const float ez = -lsf_results.D - lsf_results.A * ppos.x - lsf_results.B * ppos.y;
z_values[ix][iy] = ez;
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(ix, iy, z_values[ix][iy]));
idle(); // housekeeping
}
}
}
SERIAL_ECHOLNPGM(" done.");
}
#endif // UBL_G29_P31
#if ENABLED(UBL_DEVEL_DEBUGGING)
/**
* Much of the 'What?' command can be eliminated. But until we are fully debugged, it is
* good to have the extra information. Soon... we prune this to just a few items
*/
void unified_bed_leveling::g29_what_command() {
report_state();
if (storage_slot == -1)
SERIAL_ECHOLNPGM("No Mesh Loaded.");
else
SERIAL_ECHOLNPGM("Mesh ", storage_slot, " Loaded.");
serial_delay(50);
#if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
SERIAL_ECHOLN(F("Fade Height M420 Z"), p_float_t(planner.z_fade_height, 4));
#endif
adjust_mesh_to_mean(param.C_seen, param.C_constant);
#if HAS_BED_PROBE
SERIAL_ECHOLNPGM("Probe Offset M851 Z", p_float_t(probe.offset.z, 7));
#endif
SERIAL_ECHOLNPGM("MESH_MIN_X " STRINGIFY(MESH_MIN_X) "=", MESH_MIN_X); serial_delay(50);
SERIAL_ECHOLNPGM("MESH_MIN_Y " STRINGIFY(MESH_MIN_Y) "=", MESH_MIN_Y); serial_delay(50);
SERIAL_ECHOLNPGM("MESH_MAX_X " STRINGIFY(MESH_MAX_X) "=", MESH_MAX_X); serial_delay(50);
SERIAL_ECHOLNPGM("MESH_MAX_Y " STRINGIFY(MESH_MAX_Y) "=", MESH_MAX_Y); serial_delay(50);
SERIAL_ECHOLNPGM("GRID_MAX_POINTS_X ", GRID_MAX_POINTS_X); serial_delay(50);
SERIAL_ECHOLNPGM("GRID_MAX_POINTS_Y ", GRID_MAX_POINTS_Y); serial_delay(50);
SERIAL_ECHOLNPGM("MESH_X_DIST ", MESH_X_DIST);
SERIAL_ECHOLNPGM("MESH_Y_DIST ", MESH_Y_DIST); serial_delay(50);
SERIAL_ECHOPGM("X-Axis Mesh Points at: ");
for (uint8_t i = 0; i < GRID_MAX_POINTS_X; ++i) {
SERIAL_ECHO(p_float_t(LOGICAL_X_POSITION(get_mesh_x(i)), 3), F(" "));
serial_delay(25);
}
SERIAL_EOL();
SERIAL_ECHOPGM("Y-Axis Mesh Points at: ");
for (uint8_t i = 0; i < GRID_MAX_POINTS_Y; ++i) {
SERIAL_ECHO(p_float_t(LOGICAL_Y_POSITION(get_mesh_y(i)), 3), F(" "));
serial_delay(25);
}
SERIAL_EOL();
#if HAS_KILL
SERIAL_ECHOLNPGM("Kill pin on :", KILL_PIN, " state:", kill_state());
#endif
SERIAL_EOL();
serial_delay(50);
SERIAL_ECHOLNPGM("ubl_state_at_invocation :", ubl_state_at_invocation, "\nubl_state_recursion_chk :", ubl_state_recursion_chk);
serial_delay(50);
SERIAL_ECHOLNPGM("Meshes go from ", hex_address((void*)settings.meshes_start_index()), " to ", hex_address((void*)settings.meshes_end_index()));
serial_delay(50);
SERIAL_ECHOLNPGM("sizeof(unified_bed_leveling) : ", sizeof(unified_bed_leveling));
SERIAL_ECHOLNPGM("z_value[][] size: ", sizeof(z_values));
serial_delay(25);
SERIAL_ECHOLNPGM("EEPROM free for UBL: ", hex_address((void*)(settings.meshes_end_index() - settings.meshes_start_index())));
serial_delay(50);
SERIAL_ECHOLNPGM("EEPROM can hold ", settings.calc_num_meshes(), " meshes.\n");
serial_delay(25);
if (!sanity_check()) {
echo_name();
SERIAL_ECHOLNPGM(" sanity checks passed.");
}
}
/**
* When we are fully debugged, the EEPROM dump command will get deleted also. But
* right now, it is good to have the extra information. Soon... we prune this.
*/
void unified_bed_leveling::g29_eeprom_dump() {
uint8_t cccc;
SERIAL_ECHO_MSG("EEPROM Dump:");
persistentStore.access_start();
for (uint16_t i = 0; i < persistentStore.capacity(); i += 16) {
if (!(i & 0x3)) idle();
print_hex_word(i);
SERIAL_ECHOPGM(": ");
for (uint16_t j = 0; j < 16; j++) {
int pos = i + j;
persistentStore.read_data(pos, &cccc, sizeof(uint8_t));
print_hex_byte(cccc);
SERIAL_CHAR(' ');
}
SERIAL_EOL();
}
SERIAL_EOL();
persistentStore.access_finish();
}
/**
* When we are fully debugged, this may go away. But there are some valid
* use cases for the users. So we can wait and see what to do with it.
*/
void unified_bed_leveling::g29_compare_current_mesh_to_stored_mesh() {
const int16_t a = settings.calc_num_meshes();
if (!a) {
SERIAL_ECHOLNPGM("?EEPROM storage not available.");
return;
}
if (!parser.has_value() || !WITHIN(parser.value_int(), 0, a - 1)) {
SERIAL_ECHOLNPGM("?Invalid storage slot.\n?Use 0 to ", a - 1);
return;
}
param.KLS_storage_slot = (int8_t)parser.value_int();
float tmp_z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
settings.load_mesh(param.KLS_storage_slot, &tmp_z_values);
SERIAL_ECHOLNPGM("Subtracting mesh in slot ", param.KLS_storage_slot, " from current mesh.");
GRID_LOOP(x, y) {
z_values[x][y] -= tmp_z_values[x][y];
TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, z_values[x][y]));
}
}
#endif // UBL_DEVEL_DEBUGGING
#endif // AUTO_BED_LEVELING_UBL
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/ubl/ubl_G29.cpp
|
C++
|
agpl-3.0
| 72,689
|
/**
* 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_uint8_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_uint8_t ineg { uint8_t(neg.x), uint8_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_uint8_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_uint8_t cnt = istart.diff(iend);
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 SEGMENT_MIN_LENGTH 0.25 // SCARA minimum segment size is 0.25mm
#elif IS_KINEMATIC
#define SEGMENT_MIN_LENGTH 0.10 // (mm) Still subject to DEFAULT_SEGMENTS_PER_SECOND
#else // CARTESIAN
#ifdef LEVELED_SEGMENT_LENGTH
#define SEGMENT_MIN_LENGTH LEVELED_SEGMENT_LENGTH
#else
#define 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(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(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(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);
const int8_t ncellx = _MIN(icell.x+1, GRID_MAX_CELLS_X),
ncelly = _MIN(icell.y+1, GRID_MAX_CELLS_Y);
float z_x0y0 = z_values[icell.x][icell.y], // z at lower left corner
z_x1y0 = z_values[ncellx ][icell.y], // z at upper left corner
z_x0y1 = z_values[icell.x][ncelly ], // z at lower right corner
z_x1y1 = z_values[ncellx ][ncelly ]; // 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
|
2301_81045437/Marlin
|
Marlin/src/feature/bedlevel/ubl/ubl_motion.cpp
|
C++
|
agpl-3.0
| 20,695
|
/**
* 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
|
2301_81045437/Marlin
|
Marlin/src/feature/binary_stream.cpp
|
C++
|
agpl-3.0
| 1,349
|
/**
* 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 HAS_MEDIA
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];
|
2301_81045437/Marlin
|
Marlin/src/feature/binary_stream.h
|
C++
|
agpl-3.0
| 16,183
|
/**
* 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
#if HAS_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"
#define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE)
#include "../core/debug_out.h"
bool BLTouch::command(const BLTCommand cmd, const millis_t &ms) {
const BLTCommand current = servo[Z_PROBE_SERVO_NR].read();
if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("BLTouch from ", current, " to ", cmd);
// If the new command is the same, skip it (and the delay).
// The previous write should've already delayed to detect the alarm.
if (cmd != current) {
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
|
2301_81045437/Marlin
|
Marlin/src/feature/bltouch.cpp
|
C++
|
agpl-3.0
| 7,937
|
/**
* 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
#if HAS_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 TERN0(HAS_BLTOUCH_HS_MODE, high_speed_mode ? BLTOUCH_HS_EXTRA_CLEARANCE : 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;
|
2301_81045437/Marlin
|
Marlin/src/feature/bltouch.h
|
C++
|
agpl-3.0
| 4,215
|
/**
* 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 ALL(HAS_STATUS_MESSAGE, CANCEL_OBJECTS_REPORTING)
if (active_object >= 0)
ui.set_status(MString<30>(GET_TEXT_F(MSG_PRINTING_OBJECT), ' ', 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
|
2301_81045437/Marlin
|
Marlin/src/feature/cancel_object.cpp
|
C++
|
agpl-3.0
| 2,323
|
/**
* 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;
|
2301_81045437/Marlin
|
Marlin/src/feature/cancel_object.h
|
C++
|
agpl-3.0
| 1,526
|
/**
* 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
|
2301_81045437/Marlin
|
Marlin/src/feature/caselight.cpp
|
C++
|
agpl-3.0
| 3,643
|
/**
* 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 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;
|
2301_81045437/Marlin
|
Marlin/src/feature/caselight.h
|
C++
|
agpl-3.0
| 1,766
|
/**
* 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
|
2301_81045437/Marlin
|
Marlin/src/feature/closedloop.cpp
|
C++
|
agpl-3.0
| 1,444
|
/**
* 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))
|
2301_81045437/Marlin
|
Marlin/src/feature/closedloop.h
|
C++
|
agpl-3.0
| 1,096
|