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) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfig.h" #if ENABLED(USE_CONTROLLER_FAN) #include "controllerfan.h" #include "../module/stepper.h" #include "../module/temperature.h" ControllerFan controllerFan; uint8_t ControllerFan::speed; #if ENABLED(CONTROLLER_FAN_EDITABLE) controllerFan_settings_t ControllerFan::settings; // {0} #else const controllerFan_settings_t &ControllerFan::settings = controllerFan_defaults; #endif #if ENABLED(FAN_SOFT_PWM) uint8_t ControllerFan::soft_pwm_speed; #endif void ControllerFan::setup() { SET_OUTPUT(CONTROLLER_FAN_PIN); #ifdef CONTROLLER_FAN2_PIN SET_OUTPUT(CONTROLLER_FAN2_PIN); #endif init(); } void ControllerFan::set_fan_speed(const uint8_t s) { speed = s < (CONTROLLERFAN_SPEED_MIN) ? 0 : s; // Fan OFF below minimum } void ControllerFan::update() { static millis_t lastComponentOn = 0, // Last time a stepper, heater, etc. was turned on nextFanCheck = 0; // Last time the state was checked const millis_t ms = millis(); if (ELAPSED(ms, nextFanCheck)) { nextFanCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s /** * If any triggers for the controller fan are true... * - At least one stepper driver is enabled * - The heated bed (MOSFET) is enabled * - TEMP_SENSOR_BOARD is reporting >= CONTROLLER_FAN_MIN_BOARD_TEMP * - TEMP_SENSOR_SOC is reporting >= CONTROLLER_FAN_MIN_SOC_TEMP */ const ena_mask_t axis_mask = TERN(CONTROLLER_FAN_USE_Z_ONLY, _BV(Z_AXIS), (ena_mask_t)~TERN0(CONTROLLER_FAN_IGNORE_Z, _BV(Z_AXIS))); if ( (stepper.axis_enabled.bits & axis_mask) || TERN0(HAS_HEATED_BED, thermalManager.temp_bed.soft_pwm_amount > 0) #ifdef CONTROLLER_FAN_MIN_BOARD_TEMP || thermalManager.wholeDegBoard() >= CONTROLLER_FAN_MIN_BOARD_TEMP #endif #ifdef CONTROLLER_FAN_MIN_SOC_TEMP || thermalManager.wholeDegSoc() >= CONTROLLER_FAN_MIN_SOC_TEMP #endif ) lastComponentOn = ms; //... set time to NOW so the fan will turn on /** * Fan Settings. Set fan > 0: * - If AutoMode is on and hot components have been powered for CONTROLLERFAN_IDLE_TIME seconds. * - If System is on idle and idle fan speed settings is activated. */ set_fan_speed( settings.auto_mode && lastComponentOn && PENDING(ms, lastComponentOn + SEC_TO_MS(settings.duration)) ? settings.active_speed : settings.idle_speed ); speed = CALC_FAN_SPEED(speed); #if FAN_KICKSTART_TIME static millis_t fan_kick_end = 0; if (speed > FAN_OFF_PWM) { if (!fan_kick_end) { fan_kick_end = ms + FAN_KICKSTART_TIME; // May be longer based on slow update interval for controller fn check. Sets minimum speed = FAN_KICKSTART_POWER; } else if (PENDING(ms, fan_kick_end)) speed = FAN_KICKSTART_POWER; } else fan_kick_end = 0; #endif #if ENABLED(FAN_SOFT_PWM) soft_pwm_speed = speed; #else if (PWM_PIN(CONTROLLER_FAN_PIN)) hal.set_pwm_duty(pin_t(CONTROLLER_FAN_PIN), speed); else WRITE(CONTROLLER_FAN_PIN, speed > 0); #ifdef CONTROLLER_FAN2_PIN if (PWM_PIN(CONTROLLER_FAN2_PIN)) hal.set_pwm_duty(pin_t(CONTROLLER_FAN2_PIN), speed); else WRITE(CONTROLLER_FAN2_PIN, speed > 0); #endif #endif } } #endif // USE_CONTROLLER_FAN
2301_81045437/Marlin
Marlin/src/feature/controllerfan.cpp
C++
agpl-3.0
4,289
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfigPre.h" typedef struct { uint8_t active_speed, // 0-255 (fullspeed); Speed with enabled stepper motors idle_speed; // 0-255 (fullspeed); Speed after idle period with all motors are disabled uint16_t duration; // Duration in seconds for the fan to run after all motors are disabled bool auto_mode; // Default true } controllerFan_settings_t; #ifndef CONTROLLERFAN_SPEED_ACTIVE #define CONTROLLERFAN_SPEED_ACTIVE 255 #endif #ifndef CONTROLLERFAN_SPEED_IDLE #define CONTROLLERFAN_SPEED_IDLE 0 #endif #ifndef CONTROLLERFAN_IDLE_TIME #define CONTROLLERFAN_IDLE_TIME 60 #endif static constexpr controllerFan_settings_t controllerFan_defaults = { CONTROLLERFAN_SPEED_ACTIVE, CONTROLLERFAN_SPEED_IDLE, CONTROLLERFAN_IDLE_TIME, true }; #if ENABLED(USE_CONTROLLER_FAN) class ControllerFan { private: static uint8_t speed; static void set_fan_speed(const uint8_t s); public: #if ENABLED(CONTROLLER_FAN_EDITABLE) static controllerFan_settings_t settings; #else static const controllerFan_settings_t &settings; #endif #if ENABLED(FAN_SOFT_PWM) static uint8_t soft_pwm_speed; #endif static bool state() { return speed > 0; } static void init() { reset(); } static void reset() { TERN_(CONTROLLER_FAN_EDITABLE, settings = controllerFan_defaults); } static void setup(); static void update(); }; extern ControllerFan controllerFan; #endif
2301_81045437/Marlin
Marlin/src/feature/controllerfan.h
C++
agpl-3.0
2,374
/** * 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 ANY(HAS_COOLER, LASER_COOLANT_FLOW_METER) #include "cooler.h" Cooler cooler; #if HAS_COOLER uint8_t Cooler::mode = 0; uint16_t Cooler::capacity; uint16_t Cooler::load; bool Cooler::enabled = false; #endif #if ENABLED(LASER_COOLANT_FLOW_METER) bool Cooler::flowmeter = false; millis_t Cooler::flowmeter_next_ms; // = 0 volatile uint16_t Cooler::flowpulses; float Cooler::flowrate; #if ENABLED(FLOWMETER_SAFETY) bool Cooler::flowsafety_enabled = true; bool Cooler::flowfault = false; #endif #endif #endif // HAS_COOLER || LASER_COOLANT_FLOW_METER
2301_81045437/Marlin
Marlin/src/feature/cooler.cpp
C++
agpl-3.0
1,478
/** * Marlin 3D Printer Firmware * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfigPre.h" #ifndef FLOWMETER_PPL #define FLOWMETER_PPL 5880 // Pulses per liter #endif #ifndef FLOWMETER_INTERVAL #define FLOWMETER_INTERVAL 1000 // milliseconds #endif // Cooling device class Cooler { public: static uint16_t capacity; // Cooling capacity in watts static uint16_t load; // Cooling load in watts static bool enabled; static void enable() { enabled = true; } static void disable() { enabled = false; } static void toggle() { enabled = !enabled; } static uint8_t mode; // 0 = CO2 Liquid cooling, 1 = Laser Diode TEC Heatsink Cooling static void set_mode(const uint8_t m) { mode = m; } #if ENABLED(LASER_COOLANT_FLOW_METER) static float flowrate; // Flow meter reading in liters-per-minute. static bool flowmeter; // Flag to monitor the flow static volatile uint16_t flowpulses; // Flowmeter IRQ pulse count static millis_t flowmeter_next_ms; // Next time at which to calculate flow static void set_flowmeter(const bool sflag) { if (flowmeter != sflag) { flowmeter = sflag; if (sflag) { flowpulses = 0; flowmeter_next_ms = millis() + FLOWMETER_INTERVAL; } } } // To calculate flow we only need to count pulses static void flowmeter_ISR() { flowpulses++; } // Enable / Disable the flow meter interrupt static void flowmeter_interrupt_enable() { attachInterrupt(digitalPinToInterrupt(FLOWMETER_PIN), flowmeter_ISR, RISING); } static void flowmeter_interrupt_disable() { detachInterrupt(digitalPinToInterrupt(FLOWMETER_PIN)); } // Enable / Disable the flow meter interrupt static void flowmeter_enable() { set_flowmeter(true); flowpulses = 0; flowmeter_interrupt_enable(); } static void flowmeter_disable() { set_flowmeter(false); flowmeter_interrupt_disable(); flowpulses = 0; } // Get the total flow (in liters per minute) since the last reading static void calc_flowrate() { // flowrate = (litres) * (seconds) = litres per minute flowrate = (flowpulses / (float)FLOWMETER_PPL) * ((1000.0f / (float)FLOWMETER_INTERVAL) * 60.0f); flowpulses = 0; } // Userland task to update the flow meter static void flowmeter_task(const millis_t ms=millis()) { if (!flowmeter) // !! The flow meter must always be on !! flowmeter_enable(); // Init and prime if (ELAPSED(ms, flowmeter_next_ms)) { calc_flowrate(); flowmeter_next_ms = ms + FLOWMETER_INTERVAL; } } #if ENABLED(FLOWMETER_SAFETY) static bool flowfault; // Flag that the cooler is in a fault state static bool flowsafety_enabled; // Flag to disable the cutter if flow rate is too low static void flowsafety_toggle() { flowsafety_enabled = !flowsafety_enabled; } static bool check_flow_too_low() { const bool too_low = flowsafety_enabled && flowrate < (FLOWMETER_MIN_LITERS_PER_MINUTE); flowfault = too_low; return too_low; } #endif #endif }; extern Cooler cooler;
2301_81045437/Marlin
Marlin/src/feature/cooler.h
C++
agpl-3.0
4,035
/*************************************************************** * * External DAC for Alligator Board * ****************************************************************/ #include "../../inc/MarlinConfig.h" #if MB(ALLIGATOR) #include "dac_dac084s085.h" #include "../../MarlinCore.h" #include "../../HAL/shared/Delay.h" dac084s085::dac084s085() { } void dac084s085::begin() { uint8_t externalDac_buf[] = { 0x20, 0x00 }; // all off // All SPI chip-select HIGH SET_OUTPUT(DAC0_SYNC_PIN); #if HAS_MULTI_EXTRUDER SET_OUTPUT(DAC1_SYNC_PIN); #endif cshigh(); spiBegin(); //init onboard DAC DELAY_US(2); WRITE(DAC0_SYNC_PIN, LOW); DELAY_US(2); WRITE(DAC0_SYNC_PIN, HIGH); DELAY_US(2); WRITE(DAC0_SYNC_PIN, LOW); spiSend(SPI_CHAN_DAC, externalDac_buf, COUNT(externalDac_buf)); WRITE(DAC0_SYNC_PIN, HIGH); #if HAS_MULTI_EXTRUDER //init Piggy DAC DELAY_US(2); WRITE(DAC1_SYNC_PIN, LOW); DELAY_US(2); WRITE(DAC1_SYNC_PIN, HIGH); DELAY_US(2); WRITE(DAC1_SYNC_PIN, LOW); spiSend(SPI_CHAN_DAC, externalDac_buf, COUNT(externalDac_buf)); WRITE(DAC1_SYNC_PIN, HIGH); #endif return; } void dac084s085::setValue(const uint8_t channel, const uint8_t value) { if (channel >= 7) return; // max channel (X,Y,Z,E0,E1,E2,E3) const uint8_t externalDac_buf[] = { 0x10 | ((channel > 3 ? 7 : 3) - channel << 6) | (value >> 4), 0x00 | (value << 4) }; // All SPI chip-select HIGH cshigh(); if (channel > 3) { // DAC Piggy E1,E2,E3 WRITE(DAC1_SYNC_PIN, LOW); DELAY_US(2); WRITE(DAC1_SYNC_PIN, HIGH); DELAY_US(2); WRITE(DAC1_SYNC_PIN, LOW); } else { // DAC onboard X,Y,Z,E0 WRITE(DAC0_SYNC_PIN, LOW); DELAY_US(2); WRITE(DAC0_SYNC_PIN, HIGH); DELAY_US(2); WRITE(DAC0_SYNC_PIN, LOW); } DELAY_US(2); spiSend(SPI_CHAN_DAC, externalDac_buf, COUNT(externalDac_buf)); } void dac084s085::cshigh() { WRITE(DAC0_SYNC_PIN, HIGH); #if HAS_MULTI_EXTRUDER WRITE(DAC1_SYNC_PIN, HIGH); #endif WRITE(SPI_EEPROM1_CS_PIN, HIGH); WRITE(SPI_EEPROM2_CS_PIN, HIGH); WRITE(SPI_FLASH_CS_PIN, HIGH); WRITE(SD_SS_PIN, HIGH); } #endif // MB(ALLIGATOR)
2301_81045437/Marlin
Marlin/src/feature/dac/dac_dac084s085.cpp
C++
agpl-3.0
2,204
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once class dac084s085 { public: dac084s085(); static void begin(); static void setValue(const uint8_t channel, const uint8_t value); private: static void cshigh(); };
2301_81045437/Marlin
Marlin/src/feature/dac/dac_dac084s085.h
C++
agpl-3.0
1,058
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * mcp4728.cpp - Arduino library for MicroChip MCP4728 I2C D/A converter * * For implementation details, please take a look at the datasheet: * https://ww1.microchip.com/downloads/en/DeviceDoc/22187a.pdf * * For discussion and feedback, please go to: * https://forum.arduino.cc/index.php/topic,51842.0.html */ #include "../../inc/MarlinConfig.h" #if HAS_MOTOR_CURRENT_DAC #include "dac_mcp4728.h" MCP4728 mcp4728; xyze_uint_t dac_values; /** * Begin I2C, get current values (input register and eeprom) of mcp4728 */ void MCP4728::init() { Wire.begin(); Wire.requestFrom(I2C_ADDRESS(DAC_DEV_ADDRESS), uint8_t(24)); while (Wire.available()) { char deviceID = Wire.read(), hiByte = Wire.read(), loByte = Wire.read(); if (!(deviceID & 0x08)) dac_values[(deviceID & 0x30) >> 4] = word((hiByte & 0x0F), loByte); } } /** * Write input resister value to specified channel using fastwrite method. * Channel : 0-3, Values : 0-4095 */ uint8_t MCP4728::analogWrite(const uint8_t channel, const uint16_t value) { dac_values[channel] = value; return fastWrite(); } /** * Write all input resistor values to EEPROM using SequentialWrite method. * This will update both input register and EEPROM value * This will also write current Vref, PowerDown, Gain settings to EEPROM */ uint8_t MCP4728::eepromWrite() { Wire.beginTransmission(I2C_ADDRESS(DAC_DEV_ADDRESS)); Wire.write(SEQWRITE); LOOP_LOGICAL_AXES(i) { Wire.write(DAC_STEPPER_VREF << 7 | DAC_STEPPER_GAIN << 4 | highByte(dac_values[i])); Wire.write(lowByte(dac_values[i])); } return Wire.endTransmission(); } /** * Write Voltage reference setting to all input registers */ uint8_t MCP4728::setVref_all(const uint8_t value) { Wire.beginTransmission(I2C_ADDRESS(DAC_DEV_ADDRESS)); Wire.write(VREFWRITE | (value ? 0x0F : 0x00)); return Wire.endTransmission(); } /** * Write Gain setting to all input registers */ uint8_t MCP4728::setGain_all(const uint8_t value) { Wire.beginTransmission(I2C_ADDRESS(DAC_DEV_ADDRESS)); Wire.write(GAINWRITE | (value ? 0x0F : 0x00)); return Wire.endTransmission(); } /** * Return Input Register value */ uint16_t MCP4728::getValue(const uint8_t channel) { return dac_values[channel]; } #if 0 /** * Steph: Might be useful in the future * Return Vout */ uint16_t MCP4728::getVout(const uint8_t channel) { const uint32_t vref = 2048, vOut = (vref * dac_values[channel] * (_DAC_STEPPER_GAIN + 1)) / 4096; return _MIN(vOut, defaultVDD); } #endif /** * Returns DAC values as a 0-100 percentage of drive strength */ uint8_t MCP4728::getDrvPct(const uint8_t channel) { return uint8_t(100.0 * dac_values[channel] / (DAC_STEPPER_MAX) + 0.5); } /** * Receives all Drive strengths as 0-100 percent values, updates * DAC Values array and calls fastwrite to update the DAC. */ void MCP4728::setDrvPct(xyze_uint_t &pct) { dac_values = pct * (DAC_STEPPER_MAX) * 0.01f; fastWrite(); } /** * FastWrite input register values - All DAC output update. refer to DATASHEET 5.6.1 * DAC Input and PowerDown bits update. * No EEPROM update */ uint8_t MCP4728::fastWrite() { Wire.beginTransmission(I2C_ADDRESS(DAC_DEV_ADDRESS)); LOOP_LOGICAL_AXES(i) { Wire.write(highByte(dac_values[i])); Wire.write(lowByte(dac_values[i])); } return Wire.endTransmission(); } /** * Common function for simple general commands */ uint8_t MCP4728::simpleCommand(const byte simpleCommand) { Wire.beginTransmission(I2C_ADDRESS(GENERALCALL)); Wire.write(simpleCommand); return Wire.endTransmission(); } #endif // HAS_MOTOR_CURRENT_DAC
2301_81045437/Marlin
Marlin/src/feature/dac/dac_mcp4728.cpp
C++
agpl-3.0
4,496
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * Arduino library for MicroChip MCP4728 I2C D/A converter. */ #include "../../core/types.h" #include <Wire.h> /** * The following three macros are only used in this piece of code related to mcp4728. * They are defined in the standard Arduino framework but could be undefined in 32 bits Arduino frameworks. * (For instance not defined in Arduino lpc176x framework) * So we have to define them if needed. */ #ifndef word #define word(h, l) ((uint8_t) ((h << 8) | l)) #endif #ifndef lowByte #define lowByte(w) ((uint8_t) ((w) & 0xFF)) #endif #ifndef highByte #define highByte(w) ((uint8_t) ((w) >> 8)) #endif #define defaultVDD DAC_STEPPER_MAX //was 5000 but differs with internal Vref #define BASE_ADDR 0x60 #define RESET 0b00000110 #define WAKE 0b00001001 #define UPDATE 0b00001000 #define MULTIWRITE 0b01000000 #define SINGLEWRITE 0b01011000 #define SEQWRITE 0b01010000 #define VREFWRITE 0b10000000 #define GAINWRITE 0b11000000 #define POWERDOWNWRITE 0b10100000 #define GENERALCALL 0b00000000 #define GAINWRITE 0b11000000 // This is taken from the original lib, makes it easy to edit if needed // DAC_OR_ADDRESS defined in pins_BOARD.h file #define DAC_DEV_ADDRESS (BASE_ADDR | DAC_OR_ADDRESS) class MCP4728 { public: static void init(); static uint8_t analogWrite(const uint8_t channel, const uint16_t value); static uint8_t eepromWrite(); static uint8_t setVref_all(const uint8_t value); static uint8_t setGain_all(const uint8_t value); static uint16_t getValue(const uint8_t channel); static uint8_t fastWrite(); static uint8_t simpleCommand(const byte simpleCommand); static uint8_t getDrvPct(const uint8_t channel); static void setDrvPct(xyze_uint_t &pct); }; extern MCP4728 mcp4728;
2301_81045437/Marlin
Marlin/src/feature/dac/dac_mcp4728.h
C++
agpl-3.0
2,696
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * stepper_dac.cpp - To set stepper current via DAC */ #include "../../inc/MarlinConfig.h" #if HAS_MOTOR_CURRENT_DAC #include "stepper_dac.h" bool dac_present = false; constexpr xyze_uint8_t dac_order = DAC_STEPPER_ORDER; xyze_uint_t dac_channel_pct = DAC_MOTOR_CURRENT_DEFAULT; StepperDAC stepper_dac; int StepperDAC::init() { #if PIN_EXISTS(DAC_DISABLE) OUT_WRITE(DAC_DISABLE_PIN, LOW); // set pin low to enable DAC #endif mcp4728.init(); if (mcp4728.simpleCommand(RESET)) return -1; dac_present = true; mcp4728.setVref_all(DAC_STEPPER_VREF); mcp4728.setGain_all(DAC_STEPPER_GAIN); if (mcp4728.getDrvPct(0) < 1 || mcp4728.getDrvPct(1) < 1 || mcp4728.getDrvPct(2) < 1 || mcp4728.getDrvPct(3) < 1) { mcp4728.setDrvPct(dac_channel_pct); mcp4728.eepromWrite(); } return 0; } void StepperDAC::set_current_value(const uint8_t channel, uint16_t val) { if (!(dac_present && channel < LOGICAL_AXES)) return; NOMORE(val, uint16_t(DAC_STEPPER_MAX)); mcp4728.analogWrite(dac_order[channel], val); mcp4728.simpleCommand(UPDATE); } void StepperDAC::set_current_percent(const uint8_t channel, float val) { set_current_value(channel, _MIN(val, 100.0f) * (DAC_STEPPER_MAX) / 100.0f); } static float dac_perc(int8_t n) { return mcp4728.getDrvPct(dac_order[n]); } static float dac_amps(int8_t n) { return mcp4728.getValue(dac_order[n]) * 0.125 * RECIPROCAL(DAC_STEPPER_SENSE * 1000); } uint8_t StepperDAC::get_current_percent(const AxisEnum axis) { return mcp4728.getDrvPct(dac_order[axis]); } void StepperDAC::set_current_percents(xyze_uint8_t &pct) { LOOP_LOGICAL_AXES(i) dac_channel_pct[i] = pct[dac_order[i]]; mcp4728.setDrvPct(dac_channel_pct); } void StepperDAC::print_values() { if (!dac_present) return; SERIAL_ECHO_MSG("Stepper current values in % (Amps):"); SERIAL_ECHO_START(); LOOP_LOGICAL_AXES(a) { SERIAL_CHAR(' ', IAXIS_CHAR(a), ':'); SERIAL_ECHO(dac_perc(a)); SERIAL_ECHOPGM_P(PSTR(" ("), dac_amps(AxisEnum(a)), PSTR(")")); } #if HAS_EXTRUDERS SERIAL_ECHOLNPGM_P(SP_E_LBL, dac_perc(E_AXIS), PSTR(" ("), dac_amps(E_AXIS), PSTR(")")); #endif } void StepperDAC::commit_eeprom() { if (!dac_present) return; mcp4728.eepromWrite(); } #endif // HAS_MOTOR_CURRENT_DAC
2301_81045437/Marlin
Marlin/src/feature/dac/stepper_dac.cpp
C++
agpl-3.0
3,129
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * stepper_dac.h - To set stepper current via DAC */ #include "dac_mcp4728.h" class StepperDAC { public: static int init(); static void set_current_percent(const uint8_t channel, float val); static void set_current_value(const uint8_t channel, uint16_t val); static void print_values(); static void commit_eeprom(); static uint8_t get_current_percent(const AxisEnum axis); static void set_current_percents(xyze_uint8_t &pct); }; extern StepperDAC stepper_dac;
2301_81045437/Marlin
Marlin/src/feature/dac/stepper_dac.h
C++
agpl-3.0
1,360
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once // // Header for MCP4018 and MCP4451 current control i2c devices // class DigipotI2C { public: static void init(); static void set_current(const uint8_t channel, const float current); }; extern DigipotI2C digipot_i2c;
2301_81045437/Marlin
Marlin/src/feature/digipot/digipot.h
C++
agpl-3.0
1,099
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../../inc/MarlinConfig.h" #if ENABLED(DIGIPOT_MCP4018) #include "digipot.h" #include <Stream.h> #include <SlowSoftI2CMaster.h> // https://github.com/felias-fogg/SlowSoftI2CMaster // Settings for the I2C based DIGIPOT (MCP4018) based on WT150 #ifndef DIGIPOT_A4988_Rsx #define DIGIPOT_A4988_Rsx 0.250 #endif #ifndef DIGIPOT_A4988_Vrefmax #define DIGIPOT_A4988_Vrefmax 1.666 #endif #define DIGIPOT_MCP4018_MAX_VALUE 127 #define DIGIPOT_A4988_Itripmax(Vref) ((Vref) / (8.0 * DIGIPOT_A4988_Rsx)) #define DIGIPOT_A4988_FACTOR ((DIGIPOT_MCP4018_MAX_VALUE) / DIGIPOT_A4988_Itripmax(DIGIPOT_A4988_Vrefmax)) #define DIGIPOT_A4988_MAX_CURRENT 2.0 static byte current_to_wiper(const float current) { const int16_t value = TERN(DIGIPOT_USE_RAW_VALUES, current, CEIL(current * DIGIPOT_A4988_FACTOR)); return byte(constrain(value, 0, DIGIPOT_MCP4018_MAX_VALUE)); } static SlowSoftI2CMaster pots[DIGIPOT_I2C_NUM_CHANNELS] = { SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_X, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) #if DIGIPOT_I2C_NUM_CHANNELS > 1 , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_Y, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) #if DIGIPOT_I2C_NUM_CHANNELS > 2 , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_Z, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) #if DIGIPOT_I2C_NUM_CHANNELS > 3 , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_E0, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) #if DIGIPOT_I2C_NUM_CHANNELS > 4 , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_E1, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) #if DIGIPOT_I2C_NUM_CHANNELS > 5 , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_E2, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) #if DIGIPOT_I2C_NUM_CHANNELS > 6 , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_E3, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) #if DIGIPOT_I2C_NUM_CHANNELS > 7 , SlowSoftI2CMaster(DIGIPOTS_I2C_SDA_E4, DIGIPOTS_I2C_SCL, ENABLED(DIGIPOT_ENABLE_I2C_PULLUPS)) #endif #endif #endif #endif #endif #endif #endif }; static void digipot_i2c_send(const uint8_t channel, const byte v) { if (WITHIN(channel, 0, DIGIPOT_I2C_NUM_CHANNELS - 1)) { pots[channel].i2c_start(((DIGIPOT_I2C_ADDRESS_A) << 1) | I2C_WRITE); pots[channel].i2c_write(v); pots[channel].i2c_stop(); } } // This is for the MCP4018 I2C based digipot void DigipotI2C::set_current(const uint8_t channel, const float current) { const float ival = _MIN(_MAX(current, 0), float(DIGIPOT_MCP4018_MAX_VALUE)); digipot_i2c_send(channel, current_to_wiper(ival)); } void DigipotI2C::init() { for (uint8_t i = 0; i < DIGIPOT_I2C_NUM_CHANNELS; ++i) pots[i].i2c_init(); // Init currents according to Configuration_adv.h static const float digipot_motor_current[] PROGMEM = #if ENABLED(DIGIPOT_USE_RAW_VALUES) DIGIPOT_MOTOR_CURRENT #else DIGIPOT_I2C_MOTOR_CURRENTS #endif ; for (uint8_t i = 0; i < COUNT(digipot_motor_current); ++i) set_current(i, pgm_read_float(&digipot_motor_current[i])); } DigipotI2C digipot_i2c; #endif // DIGIPOT_MCP4018
2301_81045437/Marlin
Marlin/src/feature/digipot/digipot_mcp4018.cpp
C++
agpl-3.0
4,115
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../../inc/MarlinConfig.h" #if ENABLED(DIGIPOT_MCP4451) #include "digipot.h" #include <Stream.h> #include <Wire.h> #if MB(MKS_SBASE) #include "digipot_mcp4451_I2C_routines.h" #endif // Settings for the I2C based DIGIPOT (MCP4451) on Azteeg X3 Pro #if MB(5DPRINT) #define DIGIPOT_I2C_FACTOR 117.96f #define DIGIPOT_I2C_MAX_CURRENT 1.736f #elif MB(AZTEEG_X5_MINI, AZTEEG_X5_MINI_WIFI) #define DIGIPOT_I2C_FACTOR 113.5f #define DIGIPOT_I2C_MAX_CURRENT 2.0f #elif MB(AZTEEG_X5_GT) #define DIGIPOT_I2C_FACTOR 51.0f #define DIGIPOT_I2C_MAX_CURRENT 3.0f #else #define DIGIPOT_I2C_FACTOR 106.7f #define DIGIPOT_I2C_MAX_CURRENT 2.5f #endif static byte current_to_wiper(const float current) { return byte(TERN(DIGIPOT_USE_RAW_VALUES, current, CEIL(DIGIPOT_I2C_FACTOR * current))); } static void digipot_i2c_send(const byte addr, const byte a, const byte b) { #if MB(MKS_SBASE) digipot_mcp4451_start(addr); digipot_mcp4451_send_byte(a); digipot_mcp4451_send_byte(b); #else Wire.beginTransmission(I2C_ADDRESS(addr)); Wire.write(a); Wire.write(b); Wire.endTransmission(); #endif } // This is for the MCP4451 I2C based digipot void DigipotI2C::set_current(const uint8_t channel, const float current) { // These addresses are specific to Azteeg X3 Pro, can be set to others. // In this case first digipot is at address A0=0, A1=0, second one is at A0=0, A1=1 const byte addr = channel < 4 ? DIGIPOT_I2C_ADDRESS_A : DIGIPOT_I2C_ADDRESS_B; // channel 0-3 vs 4-7 // Initial setup digipot_i2c_send(addr, 0x40, 0xFF); digipot_i2c_send(addr, 0xA0, 0xFF); // Set actual wiper value byte addresses[4] = { 0x00, 0x10, 0x60, 0x70 }; digipot_i2c_send(addr, addresses[channel & 0x3], current_to_wiper(_MIN(float(_MAX(current, 0)), DIGIPOT_I2C_MAX_CURRENT))); } void DigipotI2C::init() { #if MB(MKS_SBASE) configure_i2c(16); // Set clock_option to 16 ensure I2C is initialized at 400kHz #else Wire.begin(); #endif // Set up initial currents as defined in Configuration_adv.h static const float digipot_motor_current[] PROGMEM = #if ENABLED(DIGIPOT_USE_RAW_VALUES) DIGIPOT_MOTOR_CURRENT #else DIGIPOT_I2C_MOTOR_CURRENTS #endif ; for (uint8_t i = 0; i < COUNT(digipot_motor_current); ++i) set_current(i, pgm_read_float(&digipot_motor_current[i])); } DigipotI2C digipot_i2c; #endif // DIGIPOT_MCP4451
2301_81045437/Marlin
Marlin/src/feature/digipot/digipot_mcp4451.cpp
C++
agpl-3.0
3,303
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfigPre.h" #if ENABLED(DIRECT_STEPPING) #include "direct_stepping.h" #include "../MarlinCore.h" #define CHECK_PAGE(I, R) do{ \ if (I >= sizeof(page_states) / sizeof(page_states[0])) { \ fatal_error = true; \ return R; \ } \ }while(0) #define CHECK_PAGE_STATE(I, R, S) do { \ CHECK_PAGE(I, R); \ if (page_states[I] != S) { \ fatal_error = true; \ return R; \ } \ }while(0) namespace DirectStepping { template<typename Cfg> State SerialPageManager<Cfg>::state; template<typename Cfg> volatile bool SerialPageManager<Cfg>::fatal_error; template<typename Cfg> volatile PageState SerialPageManager<Cfg>::page_states[Cfg::PAGE_COUNT]; template<typename Cfg> volatile bool SerialPageManager<Cfg>::page_states_dirty; template<typename Cfg> uint8_t SerialPageManager<Cfg>::pages[Cfg::PAGE_COUNT][Cfg::PAGE_SIZE]; template<typename Cfg> uint8_t SerialPageManager<Cfg>::checksum; template<typename Cfg> typename Cfg::write_byte_idx_t SerialPageManager<Cfg>::write_byte_idx; template<typename Cfg> typename Cfg::page_idx_t SerialPageManager<Cfg>::write_page_idx; template<typename Cfg> typename Cfg::write_byte_idx_t SerialPageManager<Cfg>::write_page_size; template <typename Cfg> void SerialPageManager<Cfg>::init() { for (int i = 0 ; i < Cfg::PAGE_COUNT ; i++) page_states[i] = PageState::FREE; fatal_error = false; state = State::NEWLINE; page_states_dirty = false; SERIAL_ECHOLNPGM("pages_ready"); } template<typename Cfg> FORCE_INLINE bool SerialPageManager<Cfg>::maybe_store_rxd_char(uint8_t c) { switch (state) { default: case State::MONITOR: switch (c) { case '\n': case '\r': state = State::NEWLINE; default: return false; } case State::NEWLINE: switch (c) { case Cfg::CONTROL_CHAR: state = State::ADDRESS; return true; case '\n': case '\r': state = State::NEWLINE; return false; default: state = State::MONITOR; return false; } case State::ADDRESS: //TODO: 16 bit address, State::ADDRESS2 write_page_idx = c; write_byte_idx = 0; checksum = 0; CHECK_PAGE(write_page_idx, true); if (page_states[write_page_idx] == PageState::FAIL) { // Special case for fail state = State::UNFAIL; return true; } set_page_state(write_page_idx, PageState::WRITING); state = Cfg::DIRECTIONAL ? State::COLLECT : State::SIZE; return true; case State::SIZE: // Zero means full page size write_page_size = c; state = State::COLLECT; return true; case State::COLLECT: pages[write_page_idx][write_byte_idx++] = c; checksum ^= c; // check if still collecting if (Cfg::PAGE_SIZE == 256) { // special case for 8-bit, check if rolled back to 0 if (Cfg::DIRECTIONAL || !write_page_size) { // full 256 bytes if (write_byte_idx) return true; } else if (write_byte_idx < write_page_size) return true; } else if (Cfg::DIRECTIONAL) { if (write_byte_idx != Cfg::PAGE_SIZE) return true; } else if (write_byte_idx < write_page_size) return true; state = State::CHECKSUM; return true; case State::CHECKSUM: { const PageState page_state = (checksum == c) ? PageState::OK : PageState::FAIL; set_page_state(write_page_idx, page_state); state = State::MONITOR; return true; } case State::UNFAIL: if (c == 0) set_page_state(write_page_idx, PageState::FREE); else fatal_error = true; state = State::MONITOR; return true; } } template <typename Cfg> void SerialPageManager<Cfg>::write_responses() { if (fatal_error) { kill(GET_TEXT_F(MSG_BAD_PAGE)); return; } if (!page_states_dirty) return; page_states_dirty = false; SERIAL_CHAR(Cfg::CONTROL_CHAR); constexpr int state_bits = 2; constexpr int n_bytes = Cfg::PAGE_COUNT >> state_bits; volatile uint8_t bits_b[n_bytes] = { 0 }; for (page_idx_t i = 0 ; i < Cfg::PAGE_COUNT ; i++) { bits_b[i >> state_bits] |= page_states[i] << ((i * state_bits) & 0x7); } uint8_t crc = 0; for (uint8_t i = 0 ; i < n_bytes ; i++) { crc ^= bits_b[i]; SERIAL_CHAR(bits_b[i]); } SERIAL_CHAR(crc); SERIAL_EOL(); } template <typename Cfg> FORCE_INLINE void SerialPageManager<Cfg>::set_page_state(const page_idx_t page_idx, const PageState page_state) { CHECK_PAGE(page_idx,); page_states[page_idx] = page_state; page_states_dirty = true; } template <> FORCE_INLINE uint8_t *PageManager::get_page(const page_idx_t page_idx) { CHECK_PAGE(page_idx, nullptr); return pages[page_idx]; } template <> FORCE_INLINE void PageManager::free_page(const page_idx_t page_idx) { set_page_state(page_idx, PageState::FREE); } }; DirectStepping::PageManager page_manager; const uint8_t segment_table[DirectStepping::Config::NUM_SEGMENTS][DirectStepping::Config::SEGMENT_STEPS] PROGMEM = { #if STEPPER_PAGE_FORMAT == SP_4x4D_128 { 1, 1, 1, 1, 1, 1, 1 }, // 0 = -7 { 1, 1, 1, 0, 1, 1, 1 }, // 1 = -6 { 1, 1, 1, 0, 1, 0, 1 }, // 2 = -5 { 1, 1, 0, 1, 0, 1, 0 }, // 3 = -4 { 1, 1, 0, 0, 1, 0, 0 }, // 4 = -3 { 0, 0, 1, 0, 0, 0, 1 }, // 5 = -2 { 0, 0, 0, 1, 0, 0, 0 }, // 6 = -1 { 0, 0, 0, 0, 0, 0, 0 }, // 7 = 0 { 0, 0, 0, 1, 0, 0, 0 }, // 8 = 1 { 0, 0, 1, 0, 0, 0, 1 }, // 9 = 2 { 1, 1, 0, 0, 1, 0, 0 }, // 10 = 3 { 1, 1, 0, 1, 0, 1, 0 }, // 11 = 4 { 1, 1, 1, 0, 1, 0, 1 }, // 12 = 5 { 1, 1, 1, 0, 1, 1, 1 }, // 13 = 6 { 1, 1, 1, 1, 1, 1, 1 }, // 14 = 7 { 0 } #elif STEPPER_PAGE_FORMAT == SP_4x2_256 { 0, 0, 0 }, // 0 { 0, 1, 0 }, // 1 { 1, 0, 1 }, // 2 { 1, 1, 1 }, // 3 #elif STEPPER_PAGE_FORMAT == SP_4x1_512 {0} // Uncompressed format, table not used #endif }; #endif // DIRECT_STEPPING
2301_81045437/Marlin
Marlin/src/feature/direct_stepping.cpp
C++
agpl-3.0
7,468
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfig.h" namespace DirectStepping { enum State : char { MONITOR, NEWLINE, ADDRESS, SIZE, COLLECT, CHECKSUM, UNFAIL }; enum PageState : uint8_t { FREE, WRITING, OK, FAIL }; // Static state used for stepping through direct stepping pages struct page_step_state_t { // Current page uint8_t *page; // Current segment uint16_t segment_idx; // Current steps within segment uint8_t segment_steps; // Segment delta xyze_uint8_t sd; // Block delta xyze_int_t bd; }; template<typename Cfg> class SerialPageManager { public: typedef typename Cfg::page_idx_t page_idx_t; static bool maybe_store_rxd_char(uint8_t c); static void write_responses(); // common methods for page managers static void init(); static uint8_t *get_page(const page_idx_t page_idx); static void free_page(const page_idx_t page_idx); protected: typedef typename Cfg::write_byte_idx_t write_byte_idx_t; static State state; static volatile bool fatal_error; static volatile PageState page_states[Cfg::PAGE_COUNT]; static volatile bool page_states_dirty; static uint8_t pages[Cfg::PAGE_COUNT][Cfg::PAGE_SIZE]; static uint8_t checksum; static write_byte_idx_t write_byte_idx; static page_idx_t write_page_idx; static write_byte_idx_t write_page_size; static void set_page_state(const page_idx_t page_idx, const PageState page_state); }; template <int num_pages, int num_axes, int bits_segment, bool dir, int segments> struct config_t { static constexpr char CONTROL_CHAR = '!'; static constexpr int PAGE_COUNT = num_pages; static constexpr int AXIS_COUNT = num_axes; static constexpr int BITS_SEGMENT = bits_segment; static constexpr int DIRECTIONAL = dir ? 1 : 0; static constexpr int SEGMENTS = segments; static constexpr int NUM_SEGMENTS = _BV(BITS_SEGMENT); static constexpr int SEGMENT_STEPS = _BV(BITS_SEGMENT - DIRECTIONAL) - 1; static constexpr int TOTAL_STEPS = SEGMENT_STEPS * SEGMENTS; static constexpr int PAGE_SIZE = (AXIS_COUNT * BITS_SEGMENT * SEGMENTS) / 8; typedef uvalue_t(PAGE_SIZE - 1) write_byte_idx_t; typedef uvalue_t(PAGE_COUNT - 1) page_idx_t; }; template <uint8_t num_pages> using SP_4x4D_128 = config_t<num_pages, 4, 4, true, 128>; template <uint8_t num_pages> using SP_4x2_256 = config_t<num_pages, 4, 2, false, 256>; template <uint8_t num_pages> using SP_4x1_512 = config_t<num_pages, 4, 1, false, 512>; // configured types typedef STEPPER_PAGE_FORMAT<STEPPER_PAGES> Config; template class PAGE_MANAGER<Config>; typedef PAGE_MANAGER<Config> PageManager; }; #define SP_4x4D_128 1 //#define SP_4x4_128 2 //#define SP_4x2D_256 3 #define SP_4x2_256 4 #define SP_4x1_512 5 typedef typename DirectStepping::Config::page_idx_t page_idx_t; // TODO: use config typedef DirectStepping::page_step_state_t page_step_state_t; extern const uint8_t segment_table[DirectStepping::Config::NUM_SEGMENTS][DirectStepping::Config::SEGMENT_STEPS]; extern DirectStepping::PageManager page_manager;
2301_81045437/Marlin
Marlin/src/feature/direct_stepping.h
C++
agpl-3.0
4,039
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * e_parser.cpp - Intercept special commands directly in the serial stream */ #include "../inc/MarlinConfig.h" #if ENABLED(EMERGENCY_PARSER) #include "e_parser.h" // Static data members bool EmergencyParser::killed_by_M112, // = false EmergencyParser::quickstop_by_M410, #if HAS_MEDIA EmergencyParser::sd_abort_by_M524, #endif EmergencyParser::enabled; #if ENABLED(HOST_PROMPT_SUPPORT) #include "host_actions.h" uint8_t EmergencyParser::M876_reason; // = 0 #endif // Global instance EmergencyParser emergency_parser; // External references extern bool wait_for_user, wait_for_heatup; #if ENABLED(EP_BABYSTEPPING) #include "babystep.h" #endif #if ENABLED(REALTIME_REPORTING_COMMANDS) // From motion.h, which cannot be included here void report_current_position_moving(); void quickpause_stepper(); void quickresume_stepper(); #endif void EmergencyParser::update(EmergencyParser::State &state, const uint8_t c) { switch (state) { case EP_RESET: switch (c) { case ' ': case '\n': case '\r': break; case 'N': state = EP_N; break; case 'M': state = EP_M; break; #if ENABLED(REALTIME_REPORTING_COMMANDS) case 'S': state = EP_S; break; case 'P': state = EP_P; break; case 'R': state = EP_R; break; #endif #if ENABLED(SOFT_RESET_VIA_SERIAL) case '^': state = EP_ctrl; break; case 'K': state = EP_K; break; #endif default: state = EP_IGNORE; } break; case EP_N: switch (c) { case '0' ... '9': case '-': case ' ': break; case 'M': state = EP_M; break; #if ENABLED(REALTIME_REPORTING_COMMANDS) case 'S': state = EP_S; break; case 'P': state = EP_P; break; case 'R': state = EP_R; break; #endif default: state = EP_IGNORE; } break; #if ENABLED(REALTIME_REPORTING_COMMANDS) case EP_S: state = (c == '0') ? EP_S0 : EP_IGNORE; break; case EP_S0: state = (c == '0') ? EP_S00 : EP_IGNORE; break; case EP_S00: state = (c == '0') ? EP_GRBL_STATUS : EP_IGNORE; break; case EP_R: state = (c == '0') ? EP_R0 : EP_IGNORE; break; case EP_R0: state = (c == '0') ? EP_R00 : EP_IGNORE; break; case EP_R00: state = (c == '0') ? EP_GRBL_RESUME : EP_IGNORE; break; case EP_P: state = (c == '0') ? EP_P0 : EP_IGNORE; break; case EP_P0: state = (c == '0') ? EP_P00 : EP_IGNORE; break; case EP_P00: state = (c == '0') ? EP_GRBL_PAUSE : EP_IGNORE; break; #endif #if ENABLED(SOFT_RESET_VIA_SERIAL) case EP_ctrl: state = (c == 'X') ? EP_KILL : EP_IGNORE; break; case EP_K: state = (c == 'I') ? EP_KI : EP_IGNORE; break; case EP_KI: state = (c == 'L') ? EP_KIL : EP_IGNORE; break; case EP_KIL: state = (c == 'L') ? EP_KILL : EP_IGNORE; break; #endif case EP_M: switch (c) { case ' ': break; case '1': state = EP_M1; break; #if ENABLED(EP_BABYSTEPPING) case '2': state = EP_M2; break; #endif case '4': state = EP_M4; break; #if HAS_MEDIA case '5': state = EP_M5; break; #endif #if ENABLED(HOST_PROMPT_SUPPORT) case '8': state = EP_M8; break; #endif default: state = EP_IGNORE; } break; case EP_M1: switch (c) { case '0': state = EP_M10; break; case '1': state = EP_M11; break; default: state = EP_IGNORE; } break; case EP_M10: state = (c == '8') ? EP_M108 : EP_IGNORE; break; case EP_M11: state = (c == '2') ? EP_M112 : EP_IGNORE; break; case EP_M4: state = (c == '1') ? EP_M41 : EP_IGNORE; break; case EP_M41: state = (c == '0') ? EP_M410 : EP_IGNORE; break; #if HAS_MEDIA case EP_M5: state = (c == '2') ? EP_M52 : EP_IGNORE; break; case EP_M52: state = (c == '4') ? EP_M524 : EP_IGNORE; break; #endif #if ENABLED(EP_BABYSTEPPING) case EP_M2: switch (c) { case '9': state = EP_M29; break; default: state = EP_IGNORE; } break; case EP_M29: switch (c) { case '3': state = EP_M293; break; case '4': state = EP_M294; break; default: state = EP_IGNORE; } break; #endif #if ENABLED(HOST_PROMPT_SUPPORT) case EP_M8: state = (c == '7') ? EP_M87 : EP_IGNORE; break; case EP_M87: state = (c == '6') ? EP_M876 : EP_IGNORE; break; case EP_M876: switch (c) { case ' ': break; case 'S': state = EP_M876S; break; default: state = EP_IGNORE; break; } break; case EP_M876S: switch (c) { case ' ': break; case '0' ... '9': state = EP_M876SN; M876_reason = uint8_t(c - '0'); break; } break; #endif case EP_IGNORE: if (ISEOL(c)) state = EP_RESET; break; default: if (ISEOL(c)) { if (enabled) switch (state) { case EP_M108: wait_for_user = wait_for_heatup = false; break; case EP_M112: killed_by_M112 = true; break; case EP_M410: quickstop_by_M410 = true; break; #if ENABLED(EP_BABYSTEPPING) case EP_M293: babystep.ep_babysteps++; break; case EP_M294: babystep.ep_babysteps--; break; #endif #if HAS_MEDIA case EP_M524: sd_abort_by_M524 = true; break; #endif #if ENABLED(HOST_PROMPT_SUPPORT) case EP_M876SN: hostui.handle_response(M876_reason); break; #endif #if ENABLED(REALTIME_REPORTING_COMMANDS) case EP_GRBL_STATUS: report_current_position_moving(); break; case EP_GRBL_PAUSE: quickpause_stepper(); break; case EP_GRBL_RESUME: quickresume_stepper(); break; #endif #if ENABLED(SOFT_RESET_VIA_SERIAL) case EP_KILL: hal.reboot(); break; #endif default: break; } state = EP_RESET; } } } #endif // EMERGENCY_PARSER
2301_81045437/Marlin
Marlin/src/feature/e_parser.cpp
C++
agpl-3.0
7,129
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * e_parser.h - Intercept special commands directly in the serial stream */ #include "../inc/MarlinConfigPre.h" class EmergencyParser { public: // Currently looking for: M108, M112, M410, M524, M876 S[0-9], S000, P000, R000 enum State : uint8_t { EP_RESET, EP_N, EP_M, EP_M1, EP_M10, EP_M108, EP_M11, EP_M112, EP_M4, EP_M41, EP_M410, #if HAS_MEDIA EP_M5, EP_M52, EP_M524, #endif #if ENABLED(EP_BABYSTEPPING) EP_M2, EP_M29, EP_M293, EP_M294, #endif #if ENABLED(HOST_PROMPT_SUPPORT) EP_M8, EP_M87, EP_M876, EP_M876S, EP_M876SN, #endif #if ENABLED(REALTIME_REPORTING_COMMANDS) EP_S, EP_S0, EP_S00, EP_GRBL_STATUS, EP_R, EP_R0, EP_R00, EP_GRBL_RESUME, EP_P, EP_P0, EP_P00, EP_GRBL_PAUSE, #endif #if ENABLED(SOFT_RESET_VIA_SERIAL) EP_ctrl, EP_K, EP_KI, EP_KIL, EP_KILL, #endif EP_IGNORE // to '\n' }; static bool killed_by_M112; static bool quickstop_by_M410; #if HAS_MEDIA static bool sd_abort_by_M524; #endif #if ENABLED(HOST_PROMPT_SUPPORT) static uint8_t M876_reason; #endif EmergencyParser() { enable(); } FORCE_INLINE static void enable() { enabled = true; } FORCE_INLINE static void disable() { enabled = false; } static void update(State &state, const uint8_t c); private: static bool enabled; }; extern EmergencyParser emergency_parser;
2301_81045437/Marlin
Marlin/src/feature/e_parser.h
C++
agpl-3.0
2,291
/** * Marlin 3D Printer Firmware * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfigPre.h" #if ENABLED(EASYTHREED_UI) #include "easythreed_ui.h" #include "pause.h" #include "../module/temperature.h" #include "../module/printcounter.h" #include "../sd/cardreader.h" #include "../gcode/queue.h" #include "../module/motion.h" #include "../module/planner.h" #include "../MarlinCore.h" EasythreedUI easythreed_ui; #define BTN_DEBOUNCE_MS 20 void EasythreedUI::init() { SET_INPUT_PULLUP(BTN_HOME); SET_OUTPUT(BTN_HOME_GND); SET_INPUT_PULLUP(BTN_FEED); SET_OUTPUT(BTN_FEED_GND); SET_INPUT_PULLUP(BTN_RETRACT); SET_OUTPUT(BTN_RETRACT_GND); SET_INPUT_PULLUP(BTN_PRINT); SET_OUTPUT(EASYTHREED_LED_PIN); } void EasythreedUI::run() { blinkLED(); loadButton(); printButton(); } enum LEDInterval : uint16_t { LED_OFF = 0, LED_ON = 4000, LED_BLINK_0 = 2500, LED_BLINK_1 = 1500, LED_BLINK_2 = 1000, LED_BLINK_3 = 800, LED_BLINK_4 = 500, LED_BLINK_5 = 300, LED_BLINK_6 = 150, LED_BLINK_7 = 50 }; uint16_t blink_interval_ms = LED_ON; // Status LED on Start button void EasythreedUI::blinkLED() { static millis_t prev_blink_interval_ms = 0, blink_start_ms = 0; if (blink_interval_ms == LED_OFF) { WRITE(EASYTHREED_LED_PIN, HIGH); return; } // OFF if (blink_interval_ms >= LED_ON) { WRITE(EASYTHREED_LED_PIN, LOW); return; } // ON const millis_t ms = millis(); if (prev_blink_interval_ms != blink_interval_ms) { prev_blink_interval_ms = blink_interval_ms; blink_start_ms = ms; } if (PENDING(ms, blink_start_ms + blink_interval_ms)) WRITE(EASYTHREED_LED_PIN, LOW); else if (PENDING(ms, blink_start_ms + 2 * blink_interval_ms)) WRITE(EASYTHREED_LED_PIN, HIGH); else blink_start_ms = ms; } // // Filament Load/Unload Button // Load/Unload buttons are a 3 position switch with a common center ground. // void EasythreedUI::loadButton() { if (printingIsActive()) return; enum FilamentStatus : uint8_t { FS_IDLE, FS_PRESS, FS_CHECK, FS_PROCEED }; static uint8_t filament_status = FS_IDLE; static millis_t filament_time = 0; switch (filament_status) { case FS_IDLE: if (!READ(BTN_RETRACT) || !READ(BTN_FEED)) { // If feed/retract switch is toggled... filament_status++; // ...proceed to next test. filament_time = millis(); } break; case FS_PRESS: if (ELAPSED(millis(), filament_time + BTN_DEBOUNCE_MS)) { // After a short debounce delay... if (!READ(BTN_RETRACT) || !READ(BTN_FEED)) { // ...if switch still toggled... thermalManager.setTargetHotend(EXTRUDE_MINTEMP + 10, 0); // Start heating up blink_interval_ms = LED_BLINK_7; // Set the LED to blink fast filament_status++; } else filament_status = FS_IDLE; // Switch not toggled long enough } break; case FS_CHECK: if (READ(BTN_RETRACT) && READ(BTN_FEED)) { // Switch in center position (stop) blink_interval_ms = LED_ON; // LED on steady filament_status = FS_IDLE; thermalManager.disable_all_heaters(); } else if (thermalManager.hotEnoughToExtrude(0)) { // Is the hotend hot enough to move material? filament_status++; // Proceed to feed / retract. blink_interval_ms = LED_BLINK_5; // Blink ~3 times per second } break; case FS_PROCEED: { // Feed or Retract just once. Hard abort all moves and return to idle on swicth release. static bool flag = false; if (READ(BTN_RETRACT) && READ(BTN_FEED)) { // Switch in center position (stop) flag = false; // Restore flag to false filament_status = FS_IDLE; // Go back to idle state quickstop_stepper(); // Hard-stop all the steppers ... now! thermalManager.disable_all_heaters(); // And disable all the heaters blink_interval_ms = LED_ON; } else if (!flag) { flag = true; queue.inject(!READ(BTN_RETRACT) ? F("G91\nG0 E10 F180\nG0 E-120 F180\nM104 S0") : F("G91\nG0 E100 F120\nM104 S0")); } } break; } } #if HAS_STEPPER_RESET void disableStepperDrivers(); #endif // // Print Start/Pause/Resume Button // void EasythreedUI::printButton() { enum KeyStatus : uint8_t { KS_IDLE, KS_PRESS, KS_PROCEED }; static uint8_t key_status = KS_IDLE; static millis_t key_time = 0; enum PrintFlag : uint8_t { PF_START, PF_PAUSE, PF_RESUME }; static PrintFlag print_key_flag = PF_START; const millis_t ms = millis(); switch (key_status) { case KS_IDLE: if (!READ(BTN_PRINT)) { // Print/Pause/Resume button pressed? key_time = ms; // Save start time key_status++; // Go to debounce test } break; case KS_PRESS: if (ELAPSED(ms, key_time + BTN_DEBOUNCE_MS)) // Wait for debounce interval to expire key_status = READ(BTN_PRINT) ? KS_IDLE : KS_PROCEED; // Proceed if still pressed break; case KS_PROCEED: if (!READ(BTN_PRINT)) break; // Wait for the button to be released key_status = KS_IDLE; // Ready for the next press if (PENDING(ms, key_time + 1200 - BTN_DEBOUNCE_MS)) { // Register a press < 1.2 seconds switch (print_key_flag) { case PF_START: { // The "Print" button starts an SD card print if (printingIsActive()) break; // Already printing? (find another line that checks for 'is planner doing anything else right now?') blink_interval_ms = LED_BLINK_2; // Blink the indicator LED at 1 second intervals print_key_flag = PF_PAUSE; // The "Print" button now pauses the print card.mount(); // Force SD card to mount - now! if (!card.isMounted) { // Failed to mount? blink_interval_ms = LED_OFF; // Turn off LED print_key_flag = PF_START; return; // Bail out } card.ls(); // List all files to serial output const int16_t filecnt = card.get_num_items(); // Count printable files in cwd if (filecnt == 0) return; // None are printable? card.selectFileByIndex(filecnt); // Select the last file according to current sort options card.openAndPrintFile(card.filename); // Start printing it } break; case PF_PAUSE: { // Pause printing (not currently firing) if (!printingIsActive()) break; blink_interval_ms = LED_ON; // Set indicator to steady ON queue.inject(F("M25")); // Queue Pause print_key_flag = PF_RESUME; // The "Print" button now resumes the print } break; case PF_RESUME: { // Resume printing if (printingIsActive()) break; blink_interval_ms = LED_BLINK_2; // Blink the indicator LED at 1 second intervals queue.inject(F("M24")); // Queue resume print_key_flag = PF_PAUSE; // The "Print" button now pauses the print } break; } } else { // Register a longer press if (print_key_flag == PF_START && !printingIsActive()) { // While not printing, this moves Z up 10mm blink_interval_ms = LED_ON; queue.inject(F("G91\nG0 Z10 F600\nG90")); // Raise Z soon after returning to main loop } else { // While printing, cancel print card.abortFilePrintSoon(); // There is a delay while the current steps play out blink_interval_ms = LED_OFF; // Turn off LED } planner.synchronize(); // Wait for commands already in the planner to finish TERN_(HAS_STEPPER_RESET, disableStepperDrivers()); // Disable all steppers - now! print_key_flag = PF_START; // The "Print" button now starts a new print } break; } } #endif // EASYTHREED_UI
2301_81045437/Marlin
Marlin/src/feature/easythreed_ui.cpp
C++
agpl-3.0
10,158
/** * Marlin 3D Printer Firmware * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once class EasythreedUI { public: static void init(); static void run(); private: static void blinkLED(); static void loadButton(); static void printButton(); }; extern EasythreedUI easythreed_ui;
2301_81045437/Marlin
Marlin/src/feature/easythreed_ui.h
C++
agpl-3.0
1,094
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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/>. * */ //todo: add support for multiple encoders on a single axis //todo: add z axis auto-leveling //todo: consolidate some of the related M codes? //todo: add endstop-replacement mode? //todo: try faster I2C speed; tweak TWI_FREQ (400000L, or faster?); or just TWBR = ((CPU_FREQ / 400000L) - 16) / 2; //todo: consider Marlin-optimized Wire library; i.e. MarlinWire, like MarlinSerial #include "../inc/MarlinConfig.h" #if ENABLED(I2C_POSITION_ENCODERS) #include "encoder_i2c.h" #include "../module/stepper.h" #include "../gcode/parser.h" #include "../feature/babystep.h" #include <Wire.h> I2CPositionEncodersMgr I2CPEM; void I2CPositionEncoder::init(const uint8_t address, const AxisEnum axis) { encoderAxis = axis; i2cAddress = address; initialized = true; SERIAL_ECHOLNPGM("Setting up encoder on ", C(AXIS_CHAR(encoderAxis)), " axis, addr = ", address); position = get_position(); } void I2CPositionEncoder::update() { if (!initialized || !homed || !active) return; //check encoder is set up and active position = get_position(); //we don't want to stop things just because the encoder missed a message, //so we only care about responses that indicate bad magnetic strength if (!passes_test(false)) { //check encoder data is good lastErrorTime = millis(); /* if (trusted) { //commented out as part of the note below trusted = false; SERIAL_ECHOLNPGM("Fault detected on ", C(AXIS_CHAR(encoderAxis)), " axis encoder. Disengaging error correction until module is trusted again."); } */ return; } if (!trusted) { /** * This is commented out because it introduces error and can cause bad print quality. * * This code is intended to manage situations where the encoder has reported bad magnetic strength. * This indicates that the magnetic strip was too far away from the sensor to reliably track position. * When this happens, this code resets the offset based on where the printer thinks it is. This has been * shown to introduce errors in actual position which result in drifting prints and poor print quality. * Perhaps a better method would be to disable correction on the axis with a problem, report it to the * user via the status leds on the encoder module and prompt the user to re-home the axis at which point * the encoder would be re-enabled. */ #if 0 // If the magnetic strength has been good for a certain time, start trusting the module again if (millis() - lastErrorTime > I2CPE_TIME_TRUSTED) { trusted = true; SERIAL_ECHOLNPGM("Untrusted encoder module on ", C(AXIS_CHAR(encoderAxis)), " axis has been fault-free for set duration, reinstating error correction."); //the encoder likely lost its place when the error occurred, so we'll reset and use the printer's //idea of where it the axis is to re-initialize const float pos = planner.get_axis_position_mm(encoderAxis); int32_t positionInTicks = pos * get_ticks_unit(); //shift position from previous to current position zeroOffset -= (positionInTicks - get_position()); #ifdef I2CPE_DEBUG SERIAL_ECHOLNPGM("Current position is ", pos); SERIAL_ECHOLNPGM("Position in encoder ticks is ", positionInTicks); SERIAL_ECHOLNPGM("New zero-offset of ", zeroOffset); SERIAL_ECHOLN(F("New position reads as "), get_position(), C('('), mm_from_count(get_position()), C(')')); #endif } #endif return; } lastPosition = position; const millis_t positionTime = millis(); //only do error correction if setup and enabled if (ec && ecMethod != I2CPE_ECM_NONE) { #ifdef I2CPE_EC_THRESH_PROPORTIONAL const millis_t deltaTime = positionTime - lastPositionTime; const uint32_t distance = ABS(position - lastPosition), speed = distance / deltaTime; const float threshold = constrain((speed / 50), 1, 50) * ecThreshold; #else const float threshold = get_error_correct_threshold(); #endif //check error #if ENABLED(I2CPE_ERR_ROLLING_AVERAGE) float sum = 0, diffSum = 0; errIdx = (errIdx >= I2CPE_ERR_ARRAY_SIZE - 1) ? 0 : errIdx + 1; err[errIdx] = get_axis_error_steps(false); for (uint8_t i = 0; i < I2CPE_ERR_ARRAY_SIZE; ++i) { sum += err[i]; if (i) diffSum += ABS(err[i-1] - err[i]); } const int32_t error = int32_t(sum / (I2CPE_ERR_ARRAY_SIZE + 1)); //calculate average for error #else const int32_t error = get_axis_error_steps(false); #endif //SERIAL_ECHOLNPGM("Axis error steps: ", error); #ifdef I2CPE_ERR_THRESH_ABORT if (ABS(error) > I2CPE_ERR_THRESH_ABORT * planner.settings.axis_steps_per_mm[encoderAxis]) { //kill(F("Significant Error")); SERIAL_ECHOLNPGM("Axis error over threshold, aborting!", error); safe_delay(5000); } #endif #if ENABLED(I2CPE_ERR_ROLLING_AVERAGE) if (errIdx == 0) { // In order to correct for "error" but avoid correcting for noise and non-skips // it must be > threshold and have a difference average of < 10 and be < 2000 steps if (ABS(error) > threshold * planner.settings.axis_steps_per_mm[encoderAxis] && diffSum < 10 * (I2CPE_ERR_ARRAY_SIZE - 1) && ABS(error) < 2000 ) { // Check for persistent error (skip) errPrst[errPrstIdx++] = error; // Error must persist for I2CPE_ERR_PRST_ARRAY_SIZE error cycles. This also serves to improve the average accuracy if (errPrstIdx >= I2CPE_ERR_PRST_ARRAY_SIZE) { float sumP = 0; for (uint8_t i = 0; i < I2CPE_ERR_PRST_ARRAY_SIZE; ++i) sumP += errPrst[i]; const int32_t errorP = int32_t(sumP * RECIPROCAL(I2CPE_ERR_PRST_ARRAY_SIZE)); SERIAL_CHAR(AXIS_CHAR(encoderAxis)); SERIAL_ECHOLNPGM(" : CORRECT ERR ", errorP * planner.mm_per_step[encoderAxis], "mm"); babystep.add_steps(encoderAxis, -LROUND(errorP)); errPrstIdx = 0; } } else errPrstIdx = 0; } #else if (ABS(error) > threshold * planner.settings.axis_steps_per_mm[encoderAxis]) { //SERIAL_ECHOLN(error); //SERIAL_ECHOLN(position); babystep.add_steps(encoderAxis, -LROUND(error / 2)); } #endif if (ABS(error) > I2CPE_ERR_CNT_THRESH * planner.settings.axis_steps_per_mm[encoderAxis]) { const millis_t ms = millis(); if (ELAPSED(ms, nextErrorCountTime)) { SERIAL_CHAR(AXIS_CHAR(encoderAxis)); SERIAL_ECHOLNPGM(" : LARGE ERR ", error, "; diffSum=", diffSum); errorCount++; nextErrorCountTime = ms + I2CPE_ERR_CNT_DEBOUNCE_MS; } } } lastPositionTime = positionTime; } void I2CPositionEncoder::set_homed() { if (active) { reset(); // Reset module's offset to zero (so current position is homed / zero) delay(10); zeroOffset = get_raw_count(); homed = trusted = true; #ifdef I2CPE_DEBUG SERIAL_CHAR(AXIS_CHAR(encoderAxis)); SERIAL_ECHOLNPGM(" axis encoder homed, offset of ", zeroOffset, " ticks."); #endif } } void I2CPositionEncoder::set_unhomed() { zeroOffset = 0; homed = trusted = false; #ifdef I2CPE_DEBUG SERIAL_CHAR(AXIS_CHAR(encoderAxis)); SERIAL_ECHOLNPGM(" axis encoder unhomed."); #endif } bool I2CPositionEncoder::passes_test(const bool report) { if (report) { if (H != I2CPE_MAG_SIG_GOOD) SERIAL_ECHOPGM("Warning. "); SERIAL_CHAR(AXIS_CHAR(encoderAxis)); serial_ternary(F(" axis "), H == I2CPE_MAG_SIG_BAD, F("magnetic strip "), F("encoder ")); switch (H) { case I2CPE_MAG_SIG_GOOD: case I2CPE_MAG_SIG_MID: SERIAL_ECHO_TERNARY(H == I2CPE_MAG_SIG_GOOD, "passes test; field strength ", "good", "fair", ".\n"); break; default: SERIAL_ECHOLNPGM("not detected!"); } } return (H == I2CPE_MAG_SIG_GOOD || H == I2CPE_MAG_SIG_MID); } float I2CPositionEncoder::get_axis_error_mm(const bool report) { const float target = planner.get_axis_position_mm(encoderAxis), actual = mm_from_count(position), diff = actual - target, error = ABS(diff) > 10000 ? 0 : diff; // Huge error is a bad reading if (report) { SERIAL_CHAR(AXIS_CHAR(encoderAxis)); SERIAL_ECHOLNPGM(" axis target=", target, "mm; actual=", actual, "mm; err=", error, "mm"); } return error; } int32_t I2CPositionEncoder::get_axis_error_steps(const bool report) { if (!active) { if (report) { SERIAL_CHAR(AXIS_CHAR(encoderAxis)); SERIAL_ECHOLNPGM(" axis encoder not active!"); } return 0; } float stepperTicksPerUnit; int32_t encoderTicks = position, encoderCountInStepperTicksScaled; //int32_t stepperTicks = stepper.position(encoderAxis); // With a rotary encoder we're concerned with ticks/rev; whereas with a linear we're concerned with ticks/mm stepperTicksPerUnit = (type == I2CPE_ENC_TYPE_ROTARY) ? stepperTicks : planner.settings.axis_steps_per_mm[encoderAxis]; //convert both 'ticks' into same units / base encoderCountInStepperTicksScaled = LROUND((stepperTicksPerUnit * encoderTicks) / encoderTicksPerUnit); const int32_t target = stepper.position(encoderAxis); int32_t error = encoderCountInStepperTicksScaled - target; //suppress discontinuities (might be caused by bad I2C readings...?) const bool suppressOutput = (ABS(error - errorPrev) > 100); errorPrev = error; if (report) { SERIAL_CHAR(AXIS_CHAR(encoderAxis)); SERIAL_ECHOLNPGM(" axis target=", target, "; actual=", encoderCountInStepperTicksScaled, "; err=", error); } if (suppressOutput) { if (report) SERIAL_ECHOLNPGM("!Discontinuity. Suppressing error."); error = 0; } return error; } int32_t I2CPositionEncoder::get_raw_count() { uint8_t index = 0; i2cLong encoderCount; encoderCount.val = 0x00; if (Wire.requestFrom(I2C_ADDRESS(i2cAddress), uint8_t(3)) != 3) { //houston, we have a problem... H = I2CPE_MAG_SIG_NF; return 0; } while (Wire.available()) encoderCount.bval[index++] = (uint8_t)Wire.read(); //extract the magnetic strength H = (B00000011 & (encoderCount.bval[2] >> 6)); //extract sign bit; sign = (encoderCount.bval[2] & B00100000); //set all upper bits to the sign value to overwrite H encoderCount.val = (encoderCount.bval[2] & B00100000) ? (encoderCount.val | 0xFFC00000) : (encoderCount.val & 0x003FFFFF); if (invert) encoderCount.val *= -1; return encoderCount.val; } bool I2CPositionEncoder::test_axis() { // Only works on XYZ Cartesian machines for the time being if (!(encoderAxis == X_AXIS || encoderAxis == Y_AXIS || encoderAxis == Z_AXIS)) return false; const float startPosition = soft_endstop.min[encoderAxis] + 10, endPosition = soft_endstop.max[encoderAxis] - 10; const feedRate_t fr_mm_s = FLOOR(homing_feedrate(encoderAxis)); ec = false; xyze_pos_t startCoord, endCoord; LOOP_NUM_AXES(a) { startCoord[a] = planner.get_axis_position_mm((AxisEnum)a); endCoord[a] = planner.get_axis_position_mm((AxisEnum)a); } startCoord[encoderAxis] = startPosition; endCoord[encoderAxis] = endPosition; planner.synchronize(); #if HAS_EXTRUDERS startCoord.e = planner.get_axis_position_mm(E_AXIS); planner.buffer_line(startCoord, fr_mm_s, 0); planner.synchronize(); #endif // if the module isn't currently trusted, wait until it is (or until it should be if things are working) if (!trusted) { int32_t startWaitingTime = millis(); while (!trusted && millis() - startWaitingTime < I2CPE_TIME_TRUSTED) safe_delay(500); } if (trusted) { // if trusted, commence test TERN_(HAS_EXTRUDERS, endCoord.e = planner.get_axis_position_mm(E_AXIS)); planner.buffer_line(endCoord, fr_mm_s, 0); planner.synchronize(); } return trusted; } void I2CPositionEncoder::calibrate_steps_mm(const uint8_t iter) { if (type != I2CPE_ENC_TYPE_LINEAR) { SERIAL_ECHOLNPGM("Steps/mm calibration requires linear encoder."); return; } if (!(encoderAxis == X_AXIS || encoderAxis == Y_AXIS || encoderAxis == Z_AXIS)) { SERIAL_ECHOLNPGM("Steps/mm calibration not supported for this axis."); return; } float old_steps_mm, new_steps_mm, startDistance, endDistance, travelDistance, travelledDistance, total = 0; int32_t startCount, stopCount; const feedRate_t fr_mm_s = homing_feedrate(encoderAxis); bool oldec = ec; ec = false; startDistance = 20; endDistance = soft_endstop.max[encoderAxis] - 20; travelDistance = endDistance - startDistance; xyze_pos_t startCoord, endCoord; LOOP_NUM_AXES(a) { startCoord[a] = planner.get_axis_position_mm((AxisEnum)a); endCoord[a] = planner.get_axis_position_mm((AxisEnum)a); } startCoord[encoderAxis] = startDistance; endCoord[encoderAxis] = endDistance; planner.synchronize(); for (uint8_t i = 0; i < iter; ++i) { TERN_(HAS_EXTRUDERS, startCoord.e = planner.get_axis_position_mm(E_AXIS)); planner.buffer_line(startCoord, fr_mm_s, 0); planner.synchronize(); delay(250); startCount = get_position(); //do_blocking_move_to(endCoord); TERN_(HAS_EXTRUDERS, endCoord.e = planner.get_axis_position_mm(E_AXIS)); planner.buffer_line(endCoord, fr_mm_s, 0); planner.synchronize(); //Read encoder distance delay(250); stopCount = get_position(); travelledDistance = mm_from_count(ABS(stopCount - startCount)); SERIAL_ECHOLNPGM("Attempted travel: ", travelDistance, "mm"); SERIAL_ECHOLNPGM(" Actual travel: ", travelledDistance, "mm"); // Calculate new axis steps per unit old_steps_mm = planner.settings.axis_steps_per_mm[encoderAxis]; new_steps_mm = (old_steps_mm * travelDistance) / travelledDistance; SERIAL_ECHOLNPGM("Old steps/mm: ", old_steps_mm); SERIAL_ECHOLNPGM("New steps/mm: ", new_steps_mm); // Save new value planner.settings.axis_steps_per_mm[encoderAxis] = new_steps_mm; if (iter > 1) { total += new_steps_mm; // Swap start and end points so next loop runs from current position const float tempCoord = startCoord[encoderAxis]; startCoord[encoderAxis] = endCoord[encoderAxis]; endCoord[encoderAxis] = tempCoord; } } if (iter > 1) { total /= (float)iter; SERIAL_ECHOLNPGM("Average steps/mm: ", total); } ec = oldec; SERIAL_ECHOLNPGM("Calculated steps/mm set. Use M500 to save to EEPROM."); } void I2CPositionEncoder::reset() { Wire.beginTransmission(I2C_ADDRESS(i2cAddress)); Wire.write(I2CPE_RESET_COUNT); Wire.endTransmission(); TERN_(I2CPE_ERR_ROLLING_AVERAGE, ZERO(err)); } bool I2CPositionEncodersMgr::I2CPE_anyaxis; uint8_t I2CPositionEncodersMgr::I2CPE_addr, I2CPositionEncodersMgr::I2CPE_idx; I2CPositionEncoder I2CPositionEncodersMgr::encoders[I2CPE_ENCODER_CNT]; void I2CPositionEncodersMgr::init() { Wire.begin(); #if I2CPE_ENCODER_CNT > 0 uint8_t i = 0; encoders[i].init(I2CPE_ENC_1_ADDR, I2CPE_ENC_1_AXIS); #ifdef I2CPE_ENC_1_TYPE encoders[i].set_type(I2CPE_ENC_1_TYPE); #endif #ifdef I2CPE_ENC_1_TICKS_UNIT encoders[i].set_ticks_unit(I2CPE_ENC_1_TICKS_UNIT); #endif #ifdef I2CPE_ENC_1_TICKS_REV encoders[i].set_stepper_ticks(I2CPE_ENC_1_TICKS_REV); #endif #ifdef I2CPE_ENC_1_INVERT encoders[i].set_inverted(ENABLED(I2CPE_ENC_1_INVERT)); #endif #ifdef I2CPE_ENC_1_EC_METHOD encoders[i].set_ec_method(I2CPE_ENC_1_EC_METHOD); #endif #ifdef I2CPE_ENC_1_EC_THRESH encoders[i].set_ec_threshold(I2CPE_ENC_1_EC_THRESH); #endif encoders[i].set_active(encoders[i].passes_test(true)); TERN_(HAS_EXTRUDERS, if (I2CPE_ENC_1_AXIS == E_AXIS) encoders[i].set_homed()); #endif #if I2CPE_ENCODER_CNT > 1 i++; encoders[i].init(I2CPE_ENC_2_ADDR, I2CPE_ENC_2_AXIS); #ifdef I2CPE_ENC_2_TYPE encoders[i].set_type(I2CPE_ENC_2_TYPE); #endif #ifdef I2CPE_ENC_2_TICKS_UNIT encoders[i].set_ticks_unit(I2CPE_ENC_2_TICKS_UNIT); #endif #ifdef I2CPE_ENC_2_TICKS_REV encoders[i].set_stepper_ticks(I2CPE_ENC_2_TICKS_REV); #endif #ifdef I2CPE_ENC_2_INVERT encoders[i].set_inverted(ENABLED(I2CPE_ENC_2_INVERT)); #endif #ifdef I2CPE_ENC_2_EC_METHOD encoders[i].set_ec_method(I2CPE_ENC_2_EC_METHOD); #endif #ifdef I2CPE_ENC_2_EC_THRESH encoders[i].set_ec_threshold(I2CPE_ENC_2_EC_THRESH); #endif encoders[i].set_active(encoders[i].passes_test(true)); TERN_(HAS_EXTRUDERS, if (I2CPE_ENC_2_AXIS == E_AXIS) encoders[i].set_homed()); #endif #if I2CPE_ENCODER_CNT > 2 i++; encoders[i].init(I2CPE_ENC_3_ADDR, I2CPE_ENC_3_AXIS); #ifdef I2CPE_ENC_3_TYPE encoders[i].set_type(I2CPE_ENC_3_TYPE); #endif #ifdef I2CPE_ENC_3_TICKS_UNIT encoders[i].set_ticks_unit(I2CPE_ENC_3_TICKS_UNIT); #endif #ifdef I2CPE_ENC_3_TICKS_REV encoders[i].set_stepper_ticks(I2CPE_ENC_3_TICKS_REV); #endif #ifdef I2CPE_ENC_3_INVERT encoders[i].set_inverted(ENABLED(I2CPE_ENC_3_INVERT)); #endif #ifdef I2CPE_ENC_3_EC_METHOD encoders[i].set_ec_method(I2CPE_ENC_3_EC_METHOD); #endif #ifdef I2CPE_ENC_3_EC_THRESH encoders[i].set_ec_threshold(I2CPE_ENC_3_EC_THRESH); #endif encoders[i].set_active(encoders[i].passes_test(true)); TERN_(HAS_EXTRUDERS, if (I2CPE_ENC_3_AXIS == E_AXIS) encoders[i].set_homed()); #endif #if I2CPE_ENCODER_CNT > 3 i++; encoders[i].init(I2CPE_ENC_4_ADDR, I2CPE_ENC_4_AXIS); #ifdef I2CPE_ENC_4_TYPE encoders[i].set_type(I2CPE_ENC_4_TYPE); #endif #ifdef I2CPE_ENC_4_TICKS_UNIT encoders[i].set_ticks_unit(I2CPE_ENC_4_TICKS_UNIT); #endif #ifdef I2CPE_ENC_4_TICKS_REV encoders[i].set_stepper_ticks(I2CPE_ENC_4_TICKS_REV); #endif #ifdef I2CPE_ENC_4_INVERT encoders[i].set_inverted(ENABLED(I2CPE_ENC_4_INVERT)); #endif #ifdef I2CPE_ENC_4_EC_METHOD encoders[i].set_ec_method(I2CPE_ENC_4_EC_METHOD); #endif #ifdef I2CPE_ENC_4_EC_THRESH encoders[i].set_ec_threshold(I2CPE_ENC_4_EC_THRESH); #endif encoders[i].set_active(encoders[i].passes_test(true)); TERN_(HAS_EXTRUDERS, if (I2CPE_ENC_4_AXIS == E_AXIS) encoders[i].set_homed()); #endif #if I2CPE_ENCODER_CNT > 4 i++; encoders[i].init(I2CPE_ENC_5_ADDR, I2CPE_ENC_5_AXIS); #ifdef I2CPE_ENC_5_TYPE encoders[i].set_type(I2CPE_ENC_5_TYPE); #endif #ifdef I2CPE_ENC_5_TICKS_UNIT encoders[i].set_ticks_unit(I2CPE_ENC_5_TICKS_UNIT); #endif #ifdef I2CPE_ENC_5_TICKS_REV encoders[i].set_stepper_ticks(I2CPE_ENC_5_TICKS_REV); #endif #ifdef I2CPE_ENC_5_INVERT encoders[i].set_inverted(ENABLED(I2CPE_ENC_5_INVERT)); #endif #ifdef I2CPE_ENC_5_EC_METHOD encoders[i].set_ec_method(I2CPE_ENC_5_EC_METHOD); #endif #ifdef I2CPE_ENC_5_EC_THRESH encoders[i].set_ec_threshold(I2CPE_ENC_5_EC_THRESH); #endif encoders[i].set_active(encoders[i].passes_test(true)); TERN_(HAS_EXTRUDERS, if (I2CPE_ENC_5_AXIS == E_AXIS) encoders[i].set_homed()); #endif #if I2CPE_ENCODER_CNT > 5 i++; encoders[i].init(I2CPE_ENC_6_ADDR, I2CPE_ENC_6_AXIS); #ifdef I2CPE_ENC_6_TYPE encoders[i].set_type(I2CPE_ENC_6_TYPE); #endif #ifdef I2CPE_ENC_6_TICKS_UNIT encoders[i].set_ticks_unit(I2CPE_ENC_6_TICKS_UNIT); #endif #ifdef I2CPE_ENC_6_TICKS_REV encoders[i].set_stepper_ticks(I2CPE_ENC_6_TICKS_REV); #endif #ifdef I2CPE_ENC_6_INVERT encoders[i].set_inverted(ENABLED(I2CPE_ENC_6_INVERT)); #endif #ifdef I2CPE_ENC_6_EC_METHOD encoders[i].set_ec_method(I2CPE_ENC_6_EC_METHOD); #endif #ifdef I2CPE_ENC_6_EC_THRESH encoders[i].set_ec_threshold(I2CPE_ENC_6_EC_THRESH); #endif encoders[i].set_active(encoders[i].passes_test(true)); TERN_(HAS_EXTRUDERS, if (I2CPE_ENC_6_AXIS == E_AXIS) encoders[i].set_homed()); #endif } void I2CPositionEncodersMgr::report_position(const int8_t idx, const bool units, const bool noOffset) { CHECK_IDX(); if (units) SERIAL_ECHOLN(noOffset ? encoders[idx].mm_from_count(encoders[idx].get_raw_count()) : encoders[idx].get_position_mm()); else { if (noOffset) { const int32_t raw_count = encoders[idx].get_raw_count(); SERIAL_CHAR(AXIS_CHAR(encoders[idx).get_axis()], ' '); for (uint8_t j = 31; j > 0; j--) SERIAL_ECHO((bool)(0x00000001 & (raw_count >> j))); SERIAL_ECHO((bool)(0x00000001 & raw_count)); SERIAL_CHAR(' '); SERIAL_ECHOLN(raw_count); } else SERIAL_ECHOLN(encoders[idx].get_position()); } } void I2CPositionEncodersMgr::change_module_address(const uint8_t oldaddr, const uint8_t newaddr) { // First check 'new' address is not in use Wire.beginTransmission(I2C_ADDRESS(newaddr)); if (!Wire.endTransmission()) { SERIAL_ECHOLNPGM("?There is already a device with that address on the I2C bus! (", newaddr, ")"); return; } // Now check that we can find the module on the oldaddr address Wire.beginTransmission(I2C_ADDRESS(oldaddr)); if (Wire.endTransmission()) { SERIAL_ECHOLNPGM("?No module detected at this address! (", oldaddr, ")"); return; } SERIAL_ECHOLNPGM("Module found at ", oldaddr, ", changing address to ", newaddr); // Change the modules address Wire.beginTransmission(I2C_ADDRESS(oldaddr)); Wire.write(I2CPE_SET_ADDR); Wire.write(newaddr); Wire.endTransmission(); SERIAL_ECHOLNPGM("Address changed, resetting and waiting for confirmation.."); // Wait for the module to reset (can probably be improved by polling address with a timeout). safe_delay(I2CPE_REBOOT_TIME); // Look for the module at the new address. Wire.beginTransmission(I2C_ADDRESS(newaddr)); if (Wire.endTransmission()) { SERIAL_ECHOLNPGM("Address change failed! Check encoder module."); return; } SERIAL_ECHOLNPGM("Address change successful!"); // Now, if this module is configured, find which encoder instance it's supposed to correspond to // and enable it (it will likely have failed initialization on power-up, before the address change). const int8_t idx = idx_from_addr(newaddr); if (idx >= 0 && !encoders[idx].get_active()) { SERIAL_CHAR(AXIS_CHAR(encoders[idx).get_axis()]); SERIAL_ECHOLNPGM(" axis encoder was not detected on printer startup. Trying again."); encoders[idx].set_active(encoders[idx].passes_test(true)); } } void I2CPositionEncodersMgr::report_module_firmware(const uint8_t address) { // First check there is a module Wire.beginTransmission(I2C_ADDRESS(address)); if (Wire.endTransmission()) { SERIAL_ECHOLNPGM("?No module detected at this address! (", address, ")"); return; } SERIAL_ECHOLNPGM("Requesting version info from module at address ", address, ":"); Wire.beginTransmission(I2C_ADDRESS(address)); Wire.write(I2CPE_SET_REPORT_MODE); Wire.write(I2CPE_REPORT_VERSION); Wire.endTransmission(); // Read value if (Wire.requestFrom(I2C_ADDRESS(address), uint8_t(32))) { char c; while (Wire.available() > 0 && (c = (char)Wire.read()) > 0) SERIAL_CHAR(c); SERIAL_EOL(); } // Set module back to normal (distance) mode Wire.beginTransmission(I2C_ADDRESS(address)); Wire.write(I2CPE_SET_REPORT_MODE); Wire.write(I2CPE_REPORT_DISTANCE); Wire.endTransmission(); } int8_t I2CPositionEncodersMgr::parse() { I2CPE_addr = 0; if (parser.seen('A')) { if (!parser.has_value()) { SERIAL_ECHOLNPGM("?A seen, but no address specified! [30-200]"); return I2CPE_PARSE_ERR; } I2CPE_addr = parser.value_byte(); if (!WITHIN(I2CPE_addr, 30, 200)) { // reserve the first 30 and last 55 SERIAL_ECHOLNPGM("?Address out of range. [30-200]"); return I2CPE_PARSE_ERR; } I2CPE_idx = idx_from_addr(I2CPE_addr); if (I2CPE_idx >= I2CPE_ENCODER_CNT) { SERIAL_ECHOLNPGM("?No device with this address!"); return I2CPE_PARSE_ERR; } } else if (parser.seenval('I')) { if (!parser.has_value()) { SERIAL_ECHOLNPGM("?I seen, but no index specified! [0-", I2CPE_ENCODER_CNT - 1, "]"); return I2CPE_PARSE_ERR; } I2CPE_idx = parser.value_byte(); if (I2CPE_idx >= I2CPE_ENCODER_CNT) { SERIAL_ECHOLNPGM("?Index out of range. [0-", I2CPE_ENCODER_CNT - 1, "]"); return I2CPE_PARSE_ERR; } I2CPE_addr = encoders[I2CPE_idx].get_address(); } else I2CPE_idx = 0xFF; I2CPE_anyaxis = parser.seen_axis(); return I2CPE_PARSE_OK; } /** * M860: Report the position(s) of position encoder module(s). * * A<addr> Module I2C address. [30, 200]. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1] * O Include homed zero-offset in returned position. * U Units in mm or raw step count. * * If A or I not specified: * X Report on X axis encoder, if present. * Y Report on Y axis encoder, if present. * Z Report on Z axis encoder, if present. * E Report on E axis encoder, if present. */ void I2CPositionEncodersMgr::M860() { if (parse()) return; const bool hasU = parser.seen_test('U'), hasO = parser.seen_test('O'); if (I2CPE_idx == 0xFF) { LOOP_LOGICAL_AXES(i) { if (!I2CPE_anyaxis || parser.seen_test(AXIS_CHAR(i))) { const uint8_t idx = idx_from_axis(AxisEnum(i)); if ((int8_t)idx >= 0) report_position(idx, hasU, hasO); } } } else report_position(I2CPE_idx, hasU, hasO); } /** * M861: Report the status of position encoder modules. * * A<addr> Module I2C address. [30, 200]. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1] * * If A or I not specified: * X Report on X axis encoder, if present. * Y Report on Y axis encoder, if present. * Z Report on Z axis encoder, if present. * E Report on E axis encoder, if present. */ void I2CPositionEncodersMgr::M861() { if (parse()) return; if (I2CPE_idx == 0xFF) { LOOP_LOGICAL_AXES(i) { if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { const uint8_t idx = idx_from_axis(AxisEnum(i)); if ((int8_t)idx >= 0) report_status(idx); } } } else report_status(I2CPE_idx); } /** * M862: Perform an axis continuity test for position encoder * modules. * * A<addr> Module I2C address. [30, 200]. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1] * * If A or I not specified: * X Report on X axis encoder, if present. * Y Report on Y axis encoder, if present. * Z Report on Z axis encoder, if present. * E Report on E axis encoder, if present. */ void I2CPositionEncodersMgr::M862() { if (parse()) return; if (I2CPE_idx == 0xFF) { LOOP_LOGICAL_AXES(i) { if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { const uint8_t idx = idx_from_axis(AxisEnum(i)); if ((int8_t)idx >= 0) test_axis(idx); } } } else test_axis(I2CPE_idx); } /** * M863: Perform steps-per-mm calibration for * position encoder modules. * * A<addr> Module I2C address. [30, 200]. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1] * P Number of rePeats/iterations. * * If A or I not specified: * X Report on X axis encoder, if present. * Y Report on Y axis encoder, if present. * Z Report on Z axis encoder, if present. * E Report on E axis encoder, if present. */ void I2CPositionEncodersMgr::M863() { if (parse()) return; const uint8_t iterations = constrain(parser.byteval('P', 1), 1, 10); if (I2CPE_idx == 0xFF) { LOOP_LOGICAL_AXES(i) { if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { const uint8_t idx = idx_from_axis(AxisEnum(i)); if ((int8_t)idx >= 0) calibrate_steps_mm(idx, iterations); } } } else calibrate_steps_mm(I2CPE_idx, iterations); } /** * M864: Change position encoder module I2C address. * * A<addr> Module current/old I2C address. If not present, * assumes default address (030). [30, 200]. * S<addr> Module new I2C address. [30, 200]. * * If S is not specified: * X Use I2CPE_PRESET_ADDR_X (030). * Y Use I2CPE_PRESET_ADDR_Y (031). * Z Use I2CPE_PRESET_ADDR_Z (032). * E Use I2CPE_PRESET_ADDR_E (033). */ void I2CPositionEncodersMgr::M864() { uint8_t newAddress; if (parse()) return; if (!I2CPE_addr) I2CPE_addr = I2CPE_PRESET_ADDR_X; if (parser.seen('S')) { if (!parser.has_value()) { SERIAL_ECHOLNPGM("?S seen, but no address specified! [30-200]"); return; } newAddress = parser.value_byte(); if (!WITHIN(newAddress, 30, 200)) { SERIAL_ECHOLNPGM("?New address out of range. [30-200]"); return; } } else if (!I2CPE_anyaxis) { SERIAL_ECHOLNPGM("?You must specify S or [XYZE]."); return; } else { if (parser.seen_test('X')) newAddress = I2CPE_PRESET_ADDR_X; else if (parser.seen_test('Y')) newAddress = I2CPE_PRESET_ADDR_Y; else if (parser.seen_test('Z')) newAddress = I2CPE_PRESET_ADDR_Z; else if (parser.seen_test('E')) newAddress = I2CPE_PRESET_ADDR_E; else return; } SERIAL_ECHOLNPGM("Changing module at address ", I2CPE_addr, " to address ", newAddress); change_module_address(I2CPE_addr, newAddress); } /** * M865: Check position encoder module firmware version. * * A<addr> Module I2C address. [30, 200]. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1]. * * If A or I not specified: * X Check X axis encoder, if present. * Y Check Y axis encoder, if present. * Z Check Z axis encoder, if present. * E Check E axis encoder, if present. */ void I2CPositionEncodersMgr::M865() { if (parse()) return; if (!I2CPE_addr) { LOOP_LOGICAL_AXES(i) { if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { const uint8_t idx = idx_from_axis(AxisEnum(i)); if ((int8_t)idx >= 0) report_module_firmware(encoders[idx].get_address()); } } } else report_module_firmware(I2CPE_addr); } /** * M866: Report or reset position encoder module error * count. * * A<addr> Module I2C address. [30, 200]. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1]. * R Reset error counter. * * If A or I not specified: * X Act on X axis encoder, if present. * Y Act on Y axis encoder, if present. * Z Act on Z axis encoder, if present. * E Act on E axis encoder, if present. */ void I2CPositionEncodersMgr::M866() { if (parse()) return; const bool hasR = parser.seen_test('R'); if (I2CPE_idx == 0xFF) { LOOP_LOGICAL_AXES(i) { if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { const uint8_t idx = idx_from_axis(AxisEnum(i)); if ((int8_t)idx >= 0) { if (hasR) reset_error_count(idx, AxisEnum(i)); else report_error_count(idx, AxisEnum(i)); } } } } else if (hasR) reset_error_count(I2CPE_idx, encoders[I2CPE_idx].get_axis()); else report_error_count(I2CPE_idx, encoders[I2CPE_idx].get_axis()); } /** * M867: Enable/disable or toggle error correction for position encoder modules. * * A<addr> Module I2C address. [30, 200]. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1]. * S<1|0> Enable/disable error correction. 1 enables, 0 disables. If not * supplied, toggle. * * If A or I not specified: * X Act on X axis encoder, if present. * Y Act on Y axis encoder, if present. * Z Act on Z axis encoder, if present. * E Act on E axis encoder, if present. */ void I2CPositionEncodersMgr::M867() { if (parse()) return; const int8_t onoff = parser.seenval('S') ? parser.value_int() : -1; if (I2CPE_idx == 0xFF) { LOOP_LOGICAL_AXES(i) { if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { const uint8_t idx = idx_from_axis(AxisEnum(i)); if ((int8_t)idx >= 0) { const bool ena = onoff == -1 ? !encoders[I2CPE_idx].get_ec_enabled() : !!onoff; enable_ec(idx, ena, AxisEnum(i)); } } } } else { const bool ena = onoff == -1 ? !encoders[I2CPE_idx].get_ec_enabled() : !!onoff; enable_ec(I2CPE_idx, ena, encoders[I2CPE_idx].get_axis()); } } /** * M868: Report or set position encoder module error correction * threshold. * * A<addr> Module I2C address. [30, 200]. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1]. * T New error correction threshold. * * If A not specified: * X Act on X axis encoder, if present. * Y Act on Y axis encoder, if present. * Z Act on Z axis encoder, if present. * E Act on E axis encoder, if present. */ void I2CPositionEncodersMgr::M868() { if (parse()) return; const float newThreshold = parser.seenval('T') ? parser.value_float() : -9999; if (I2CPE_idx == 0xFF) { LOOP_LOGICAL_AXES(i) { if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { const uint8_t idx = idx_from_axis(AxisEnum(i)); if ((int8_t)idx >= 0) { if (newThreshold != -9999) set_ec_threshold(idx, newThreshold, encoders[idx].get_axis()); else get_ec_threshold(idx, encoders[idx].get_axis()); } } } } else if (newThreshold != -9999) set_ec_threshold(I2CPE_idx, newThreshold, encoders[I2CPE_idx].get_axis()); else get_ec_threshold(I2CPE_idx, encoders[I2CPE_idx].get_axis()); } /** * M869: Report position encoder module error. * * A<addr> Module I2C address. [30, 200]. * I<index> Module index. [0, I2CPE_ENCODER_CNT - 1]. * * If A not specified: * X Act on X axis encoder, if present. * Y Act on Y axis encoder, if present. * Z Act on Z axis encoder, if present. * E Act on E axis encoder, if present. */ void I2CPositionEncodersMgr::M869() { if (parse()) return; if (I2CPE_idx == 0xFF) { LOOP_LOGICAL_AXES(i) { if (!I2CPE_anyaxis || parser.seen(AXIS_CHAR(i))) { const uint8_t idx = idx_from_axis(AxisEnum(i)); if ((int8_t)idx >= 0) report_error(idx); } } } else report_error(I2CPE_idx); } #endif // I2C_POSITION_ENCODERS
2301_81045437/Marlin
Marlin/src/feature/encoder_i2c.cpp
C++
agpl-3.0
35,507
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfig.h" #include "../module/planner.h" #include <Wire.h> //=========== Advanced / Less-Common Encoder Configuration Settings ========== #define I2CPE_EC_THRESH_PROPORTIONAL // if enabled adjusts the error correction threshold // proportional to the current speed of the axis allows // for very small error margin at low speeds without // stuttering due to reading latency at high speeds #define I2CPE_DEBUG // enable encoder-related debug serial echos #define I2CPE_REBOOT_TIME 5000 // time we wait for an encoder module to reboot // after changing address. #define I2CPE_MAG_SIG_GOOD 0 #define I2CPE_MAG_SIG_MID 1 #define I2CPE_MAG_SIG_BAD 2 #define I2CPE_MAG_SIG_NF 255 #define I2CPE_REQ_REPORT 0 #define I2CPE_RESET_COUNT 1 #define I2CPE_SET_ADDR 2 #define I2CPE_SET_REPORT_MODE 3 #define I2CPE_CLEAR_EEPROM 4 #define I2CPE_LED_PAR_MODE 10 #define I2CPE_LED_PAR_BRT 11 #define I2CPE_LED_PAR_RATE 14 #define I2CPE_REPORT_DISTANCE 0 #define I2CPE_REPORT_STRENGTH 1 #define I2CPE_REPORT_VERSION 2 // Default I2C addresses #define I2CPE_PRESET_ADDR_X 30 #define I2CPE_PRESET_ADDR_Y 31 #define I2CPE_PRESET_ADDR_Z 32 #define I2CPE_PRESET_ADDR_E 33 #define I2CPE_DEF_AXIS X_AXIS #define I2CPE_DEF_ADDR I2CPE_PRESET_ADDR_X // Error event counter; tracks how many times there is an error exceeding a certain threshold #define I2CPE_ERR_CNT_THRESH 3.00 #define I2CPE_ERR_CNT_DEBOUNCE_MS 2000 #if ENABLED(I2CPE_ERR_ROLLING_AVERAGE) #define I2CPE_ERR_ARRAY_SIZE 32 #define I2CPE_ERR_PRST_ARRAY_SIZE 10 #endif // Error Correction Methods #define I2CPE_ECM_NONE 0 #define I2CPE_ECM_MICROSTEP 1 #define I2CPE_ECM_PLANNER 2 #define I2CPE_ECM_STALLDETECT 3 // Encoder types #define I2CPE_ENC_TYPE_ROTARY 0 #define I2CPE_ENC_TYPE_LINEAR 1 // Parser #define I2CPE_PARSE_ERR 1 #define I2CPE_PARSE_OK 0 #define LOOP_PE(VAR) for (uint8_t VAR = 0; VAR < I2CPE_ENCODER_CNT; ++VAR) #define CHECK_IDX() do{ if (!WITHIN(idx, 0, I2CPE_ENCODER_CNT - 1)) return; }while(0) typedef union { volatile int32_t val = 0; uint8_t bval[4]; } i2cLong; class I2CPositionEncoder { private: AxisEnum encoderAxis = I2CPE_DEF_AXIS; uint8_t i2cAddress = I2CPE_DEF_ADDR, ecMethod = I2CPE_DEF_EC_METHOD, type = I2CPE_DEF_TYPE, H = I2CPE_MAG_SIG_NF; // Magnetic field strength int encoderTicksPerUnit = I2CPE_DEF_ENC_TICKS_UNIT, stepperTicks = I2CPE_DEF_TICKS_REV, errorCount = 0, errorPrev = 0; float ecThreshold = I2CPE_DEF_EC_THRESH; bool homed = false, trusted = false, initialized = false, active = false, invert = false, ec = true; int32_t zeroOffset = 0, lastPosition = 0, position; millis_t lastPositionTime = 0, nextErrorCountTime = 0, lastErrorTime; #if ENABLED(I2CPE_ERR_ROLLING_AVERAGE) uint8_t errIdx = 0, errPrstIdx = 0; int err[I2CPE_ERR_ARRAY_SIZE] = { 0 }, errPrst[I2CPE_ERR_PRST_ARRAY_SIZE] = { 0 }; #endif public: void init(const uint8_t address, const AxisEnum axis); void reset(); void update(); void set_homed(); void set_unhomed(); int32_t get_raw_count(); FORCE_INLINE float mm_from_count(const int32_t count) { switch (type) { default: return -1; case I2CPE_ENC_TYPE_LINEAR: return count / encoderTicksPerUnit; case I2CPE_ENC_TYPE_ROTARY: return (count * stepperTicks) / (encoderTicksPerUnit * planner.settings.axis_steps_per_mm[encoderAxis]); } } FORCE_INLINE float get_position_mm() { return mm_from_count(get_position()); } FORCE_INLINE int32_t get_position() { return get_raw_count() - zeroOffset; } int32_t get_axis_error_steps(const bool report); float get_axis_error_mm(const bool report); void calibrate_steps_mm(const uint8_t iter); bool passes_test(const bool report); bool test_axis(); FORCE_INLINE int get_error_count() { return errorCount; } FORCE_INLINE void set_error_count(const int newCount) { errorCount = newCount; } FORCE_INLINE uint8_t get_address() { return i2cAddress; } FORCE_INLINE void set_address(const uint8_t addr) { i2cAddress = addr; } FORCE_INLINE bool get_active() { return active; } FORCE_INLINE void set_active(const bool a) { active = a; } FORCE_INLINE void set_inverted(const bool i) { invert = i; } FORCE_INLINE AxisEnum get_axis() { return encoderAxis; } FORCE_INLINE bool get_ec_enabled() { return ec; } FORCE_INLINE void set_ec_enabled(const bool enabled) { ec = enabled; } FORCE_INLINE uint8_t get_ec_method() { return ecMethod; } FORCE_INLINE void set_ec_method(const byte method) { ecMethod = method; } FORCE_INLINE float get_ec_threshold() { return ecThreshold; } FORCE_INLINE void set_ec_threshold(const_float_t newThreshold) { ecThreshold = newThreshold; } FORCE_INLINE int get_encoder_ticks_mm() { switch (type) { default: return 0; case I2CPE_ENC_TYPE_LINEAR: return encoderTicksPerUnit; case I2CPE_ENC_TYPE_ROTARY: return (int)((encoderTicksPerUnit / stepperTicks) * planner.settings.axis_steps_per_mm[encoderAxis]); } } FORCE_INLINE int get_ticks_unit() { return encoderTicksPerUnit; } FORCE_INLINE void set_ticks_unit(const int ticks) { encoderTicksPerUnit = ticks; } FORCE_INLINE uint8_t get_type() { return type; } FORCE_INLINE void set_type(const byte newType) { type = newType; } FORCE_INLINE int get_stepper_ticks() { return stepperTicks; } FORCE_INLINE void set_stepper_ticks(const int ticks) { stepperTicks = ticks; } }; class I2CPositionEncodersMgr { private: static bool I2CPE_anyaxis; static uint8_t I2CPE_addr, I2CPE_idx; public: static void init(); // consider only updating one endoder per call / tick if encoders become too time intensive static void update() { LOOP_PE(i) encoders[i].update(); } static void homed(const AxisEnum axis) { LOOP_PE(i) if (encoders[i].get_axis() == axis) encoders[i].set_homed(); } static void unhomed(const AxisEnum axis) { LOOP_PE(i) if (encoders[i].get_axis() == axis) encoders[i].set_unhomed(); } static void report_position(const int8_t idx, const bool units, const bool noOffset); static void report_status(const int8_t idx) { CHECK_IDX(); SERIAL_ECHOLNPGM("Encoder ", idx, ": "); encoders[idx].get_raw_count(); encoders[idx].passes_test(true); } static void report_error(const int8_t idx) { CHECK_IDX(); encoders[idx].get_axis_error_steps(true); } static void test_axis(const int8_t idx) { CHECK_IDX(); encoders[idx].test_axis(); } static void calibrate_steps_mm(const int8_t idx, const int iterations) { CHECK_IDX(); encoders[idx].calibrate_steps_mm(iterations); } static void change_module_address(const uint8_t oldaddr, const uint8_t newaddr); static void report_module_firmware(const uint8_t address); static void report_error_count(const int8_t idx, const AxisEnum axis) { CHECK_IDX(); SERIAL_ECHOLNPGM("Error count on ", C(AXIS_CHAR(axis)), " axis is ", encoders[idx].get_error_count()); } static void reset_error_count(const int8_t idx, const AxisEnum axis) { CHECK_IDX(); encoders[idx].set_error_count(0); SERIAL_ECHOLNPGM("Error count on ", C(AXIS_CHAR(axis)), " axis has been reset."); } static void enable_ec(const int8_t idx, const bool enabled, const AxisEnum axis) { CHECK_IDX(); encoders[idx].set_ec_enabled(enabled); SERIAL_ECHOPGM("Error correction on ", C(AXIS_CHAR(axis))); SERIAL_ECHO_TERNARY(encoders[idx].get_ec_enabled(), " axis is ", "en", "dis", "abled.\n"); } static void set_ec_threshold(const int8_t idx, const float newThreshold, const AxisEnum axis) { CHECK_IDX(); encoders[idx].set_ec_threshold(newThreshold); SERIAL_ECHOLNPGM("Error correct threshold for ", C(AXIS_CHAR(axis)), " axis set to ", newThreshold, "mm."); } static void get_ec_threshold(const int8_t idx, const AxisEnum axis) { CHECK_IDX(); const float threshold = encoders[idx].get_ec_threshold(); SERIAL_ECHOLNPGM("Error correct threshold for ", C(AXIS_CHAR(axis)), " axis is ", threshold, "mm."); } static int8_t idx_from_axis(const AxisEnum axis) { LOOP_PE(i) if (encoders[i].get_axis() == axis) return i; return -1; } static int8_t idx_from_addr(const uint8_t addr) { LOOP_PE(i) if (encoders[i].get_address() == addr) return i; return -1; } static int8_t parse(); static void M860(); static void M861(); static void M862(); static void M863(); static void M864(); static void M865(); static void M866(); static void M867(); static void M868(); static void M869(); static I2CPositionEncoder encoders[I2CPE_ENCODER_CNT]; }; extern I2CPositionEncodersMgr I2CPEM;
2301_81045437/Marlin
Marlin/src/feature/encoder_i2c.h
C++
agpl-3.0
10,938
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfigPre.h" #if HAS_ETHERNET #include "ethernet.h" #include "../core/serial.h" #define DEBUG_OUT ENABLED(DEBUG_ETHERNET) #include "../core/debug_out.h" bool MarlinEthernet::hardware_enabled, // = false MarlinEthernet::have_telnet_client; // = false IPAddress MarlinEthernet::ip, MarlinEthernet::myDns, MarlinEthernet::gateway, MarlinEthernet::subnet; EthernetClient MarlinEthernet::telnetClient; // connected client MarlinEthernet ethernet; EthernetServer server(23); // telnet server enum linkStates { UNLINKED, LINKING, LINKED, CONNECTING, CONNECTED, NO_HARDWARE } linkState; #ifdef __IMXRT1062__ static void teensyMAC(uint8_t * const mac) { const uint32_t m1 = HW_OCOTP_MAC1, m2 = HW_OCOTP_MAC0; mac[0] = m1 >> 8; mac[1] = m1 >> 0; mac[2] = m2 >> 24; mac[3] = m2 >> 16; mac[4] = m2 >> 8; mac[5] = m2 >> 0; } #else byte mac[] = MAC_ADDRESS; #endif void ethernet_cable_error() { SERIAL_ERROR_MSG("Ethernet cable is not connected."); } void MarlinEthernet::init() { if (!hardware_enabled) return; SERIAL_ECHO_MSG("Starting network..."); // Init the Ethernet device #ifdef __IMXRT1062__ uint8_t mac[6]; teensyMAC(mac); #endif if (!ip) { Ethernet.begin(mac); // use DHCP } else { if (!gateway) { gateway = ip; gateway[3] = 1; myDns = gateway; subnet = IPAddress(255,255,255,0); } if (!myDns) myDns = gateway; if (!subnet) subnet = IPAddress(255,255,255,0); Ethernet.begin(mac, ip, myDns, gateway, subnet); } // Check for Ethernet hardware present if (Ethernet.hardwareStatus() == EthernetNoHardware) { SERIAL_ERROR_MSG("No Ethernet hardware found."); linkState = NO_HARDWARE; return; } linkState = UNLINKED; if (Ethernet.linkStatus() == LinkOFF) ethernet_cable_error(); } void MarlinEthernet::check() { if (!hardware_enabled) return; switch (linkState) { case NO_HARDWARE: break; case UNLINKED: if (Ethernet.linkStatus() == LinkOFF) break; SERIAL_ECHOLNPGM("Ethernet cable connected"); server.begin(); linkState = LINKING; break; case LINKING: if (!Ethernet.localIP()) break; SERIAL_ECHOPGM("Successfully started telnet server with IP "); MYSERIAL1.println(Ethernet.localIP()); linkState = LINKED; break; case LINKED: if (Ethernet.linkStatus() == LinkOFF) { ethernet_cable_error(); linkState = UNLINKED; break; } telnetClient = server.accept(); if (telnetClient) linkState = CONNECTING; break; case CONNECTING: telnetClient.println("Marlin " SHORT_BUILD_VERSION); #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR) telnetClient.println( " Last Updated: " STRING_DISTRIBUTION_DATE " | Author: " STRING_CONFIG_H_AUTHOR ); #endif telnetClient.println(" Compiled: " __DATE__); SERIAL_ECHOLNPGM("Client connected"); have_telnet_client = true; linkState = CONNECTED; break; case CONNECTED: if (telnetClient && !telnetClient.connected()) { SERIAL_ECHOLNPGM("Client disconnected"); telnetClient.stop(); have_telnet_client = false; linkState = LINKED; } if (Ethernet.linkStatus() == LinkOFF) { ethernet_cable_error(); if (telnetClient) telnetClient.stop(); linkState = UNLINKED; } break; default: break; } } #endif // HAS_ETHERNET
2301_81045437/Marlin
Marlin/src/feature/ethernet.cpp
C++
agpl-3.0
4,462
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #ifdef __IMXRT1062__ #include <NativeEthernet.h> #endif // Teensy 4.1 uses internal MAC Address class MarlinEthernet { public: static bool hardware_enabled, have_telnet_client; static IPAddress ip, myDns, gateway, subnet; static EthernetClient telnetClient; static void init(); static void check(); }; extern MarlinEthernet ethernet;
2301_81045437/Marlin
Marlin/src/feature/ethernet.h
C++
agpl-3.0
1,237
/** * Marlin 3D Printer Firmware * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * fancheck.cpp - fan tachometer check */ #include "../inc/MarlinConfig.h" #if HAS_FANCHECK #include "fancheck.h" #include "../module/temperature.h" #if HAS_AUTO_FAN && EXTRUDER_AUTO_FAN_SPEED != 255 && DISABLED(FOURWIRES_FANS) bool FanCheck::measuring = false; #endif Flags<TACHO_COUNT> FanCheck::tacho_state; uint16_t FanCheck::edge_counter[TACHO_COUNT]; uint8_t FanCheck::rps[TACHO_COUNT]; FanCheck::TachoError FanCheck::error = FanCheck::TachoError::NONE; bool FanCheck::enabled; void FanCheck::init() { #define _TACHINIT(N) TERN(E##N##_FAN_TACHO_PULLUP, SET_INPUT_PULLUP, TERN(E##N##_FAN_TACHO_PULLDOWN, SET_INPUT_PULLDOWN, SET_INPUT))(E##N##_FAN_TACHO_PIN) #if HAS_E0_FAN_TACHO _TACHINIT(0); #endif #if HAS_E1_FAN_TACHO _TACHINIT(1); #endif #if HAS_E2_FAN_TACHO _TACHINIT(2); #endif #if HAS_E3_FAN_TACHO _TACHINIT(3); #endif #if HAS_E4_FAN_TACHO _TACHINIT(4); #endif #if HAS_E5_FAN_TACHO _TACHINIT(5); #endif #if HAS_E6_FAN_TACHO _TACHINIT(6); #endif #if HAS_E7_FAN_TACHO _TACHINIT(7); #endif } void FanCheck::update_tachometers() { bool status; #define _TACHO_CASE(N) case N: status = READ(E##N##_FAN_TACHO_PIN); break; for (uint8_t f = 0; f < TACHO_COUNT; ++f) { switch (f) { #if HAS_E0_FAN_TACHO _TACHO_CASE(0) #endif #if HAS_E1_FAN_TACHO _TACHO_CASE(1) #endif #if HAS_E2_FAN_TACHO _TACHO_CASE(2) #endif #if HAS_E3_FAN_TACHO _TACHO_CASE(3) #endif #if HAS_E4_FAN_TACHO _TACHO_CASE(4) #endif #if HAS_E5_FAN_TACHO _TACHO_CASE(5) #endif #if HAS_E6_FAN_TACHO _TACHO_CASE(6) #endif #if HAS_E7_FAN_TACHO _TACHO_CASE(7) #endif default: continue; } if (status != tacho_state[f]) { if (measuring) ++edge_counter[f]; tacho_state.set(f, status); } } } void FanCheck::compute_speed(uint16_t elapsedTime) { static uint8_t errors_count[TACHO_COUNT]; static uint8_t fan_reported_errors_msk = 0; uint8_t fan_error_msk = 0; for (uint8_t f = 0; f < TACHO_COUNT; ++f) { switch (f) { TERN_(HAS_E0_FAN_TACHO, case 0:) TERN_(HAS_E1_FAN_TACHO, case 1:) TERN_(HAS_E2_FAN_TACHO, case 2:) TERN_(HAS_E3_FAN_TACHO, case 3:) TERN_(HAS_E4_FAN_TACHO, case 4:) TERN_(HAS_E5_FAN_TACHO, case 5:) TERN_(HAS_E6_FAN_TACHO, case 6:) TERN_(HAS_E7_FAN_TACHO, case 7:) // Compute fan speed rps[f] = edge_counter[f] * float(250) / elapsedTime; edge_counter[f] = 0; // Check fan speed constexpr int8_t max_extruder_fan_errors = TERN(HAS_PWMFANCHECK, 10000, 5000) / Temperature::fan_update_interval_ms; if (rps[f] >= 20 || TERN0(HAS_AUTO_FAN, thermalManager.autofan_speed[f] == 0)) errors_count[f] = 0; else if (errors_count[f] < max_extruder_fan_errors) ++errors_count[f]; else if (enabled) SBI(fan_error_msk, f); break; } } // Drop the error when all fans are ok if (!fan_error_msk && error == TachoError::REPORTED) error = TachoError::FIXED; if (error == TachoError::FIXED && !printJobOngoing() && !printingIsPaused()) { error = TachoError::NONE; // if the issue has been fixed while the printer is idle, reenable immediately ui.reset_alert_level(); } if (fan_error_msk & ~fan_reported_errors_msk) { // Handle new faults only for (uint8_t f = 0; f < TACHO_COUNT; ++f) if (TEST(fan_error_msk, f)) report_speed_error(f); } fan_reported_errors_msk = fan_error_msk; } void FanCheck::report_speed_error(uint8_t fan) { if (printJobOngoing()) { if (error == TachoError::NONE) { if (thermalManager.degTargetHotend(fan) != 0) { kill(GET_TEXT_F(MSG_FAN_SPEED_FAULT)); error = TachoError::REPORTED; } else error = TachoError::DETECTED; // Plans error for next processed command } } else if (!printingIsPaused()) { thermalManager.setTargetHotend(0, fan); // Always disable heating if (error == TachoError::NONE) error = TachoError::REPORTED; } SERIAL_ERROR_MSG(STR_ERR_FANSPEED, fan); LCD_ALERTMESSAGE(MSG_FAN_SPEED_FAULT); } void FanCheck::print_fan_states() { for (uint8_t s = 0; s < 2; ++s) { for (uint8_t f = 0; f < TACHO_COUNT; ++f) { switch (f) { TERN_(HAS_E0_FAN_TACHO, case 0:) TERN_(HAS_E1_FAN_TACHO, case 1:) TERN_(HAS_E2_FAN_TACHO, case 2:) TERN_(HAS_E3_FAN_TACHO, case 3:) TERN_(HAS_E4_FAN_TACHO, case 4:) TERN_(HAS_E5_FAN_TACHO, case 5:) TERN_(HAS_E6_FAN_TACHO, case 6:) TERN_(HAS_E7_FAN_TACHO, case 7:) SERIAL_ECHOPGM("E", f); if (s == 0) SERIAL_ECHOPGM(":", 60 * rps[f], " RPM "); else SERIAL_ECHOPGM("@:", TERN(HAS_AUTO_FAN, thermalManager.autofan_speed[f], 255), " "); break; } } } SERIAL_EOL(); } #if ENABLED(AUTO_REPORT_FANS) AutoReporter<FanCheck::AutoReportFan> FanCheck::auto_reporter; void FanCheck::AutoReportFan::report() { print_fan_states(); } #endif #endif // HAS_FANCHECK
2301_81045437/Marlin
Marlin/src/feature/fancheck.cpp
C++
agpl-3.0
6,046
/** * Marlin 3D Printer Firmware * Copyright (c) 2021 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfig.h" #if HAS_FANCHECK #include "../MarlinCore.h" #include "../lcd/marlinui.h" #if ENABLED(AUTO_REPORT_FANS) #include "../libs/autoreport.h" #endif #if ENABLED(PARK_HEAD_ON_PAUSE) #include "../gcode/queue.h" #endif /** * fancheck.h */ #define TACHO_COUNT TERN(HAS_E7_FAN_TACHO, 8, TERN(HAS_E6_FAN_TACHO, 7, TERN(HAS_E5_FAN_TACHO, 6, TERN(HAS_E4_FAN_TACHO, 5, TERN(HAS_E3_FAN_TACHO, 4, TERN(HAS_E2_FAN_TACHO, 3, TERN(HAS_E1_FAN_TACHO, 2, 1))))))) class FanCheck { private: enum class TachoError : uint8_t { NONE, DETECTED, REPORTED, FIXED }; #if HAS_PWMFANCHECK static bool measuring; // For future use (3 wires PWM controlled fans) #else static constexpr bool measuring = true; #endif static Flags<TACHO_COUNT> tacho_state; static uint16_t edge_counter[TACHO_COUNT]; static uint8_t rps[TACHO_COUNT]; static TachoError error; static void report_speed_error(uint8_t fan); public: static bool enabled; static void init(); static void update_tachometers(); static void compute_speed(uint16_t elapsedTime); static void print_fan_states(); #if HAS_PWMFANCHECK static void toggle_measuring() { measuring = !measuring; } static bool is_measuring() { return measuring; } #endif static void check_deferred_error() { if (error == TachoError::DETECTED) { error = TachoError::REPORTED; TERN(PARK_HEAD_ON_PAUSE, queue.inject(F("M125")), kill(GET_TEXT_F(MSG_FAN_SPEED_FAULT))); } } #if ENABLED(AUTO_REPORT_FANS) struct AutoReportFan { static void report(); }; static AutoReporter<AutoReportFan> auto_reporter; #endif }; extern FanCheck fan_check; #endif // HAS_FANCHECK
2301_81045437/Marlin
Marlin/src/feature/fancheck.h
C++
agpl-3.0
2,629
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * feature/pause.cpp - Pause feature support functions * This may be combined with related G-codes if features are consolidated. */ #include "../inc/MarlinConfig.h" #if HAS_FANMUX #include "fanmux.h" void fanmux_switch(const uint8_t e) { WRITE(FANMUX0_PIN, TEST(e, 0) ? HIGH : LOW); #if PIN_EXISTS(FANMUX1) WRITE(FANMUX1_PIN, TEST(e, 1) ? HIGH : LOW); #if PIN_EXISTS(FANMUX2) WRITE(FANMUX2_PIN, TEST(e, 2) ? HIGH : LOW); #endif #endif } void fanmux_init() { SET_OUTPUT(FANMUX0_PIN); #if PIN_EXISTS(FANMUX1) SET_OUTPUT(FANMUX1_PIN); #if PIN_EXISTS(FANMUX2) SET_OUTPUT(FANMUX2_PIN); #endif #endif fanmux_switch(0); } #endif // HAS_FANMUX
2301_81045437/Marlin
Marlin/src/feature/fanmux.cpp
C++
agpl-3.0
1,561
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * feature/fanmux.h - Cooling Fan Multiplexer support functions */ void fanmux_switch(const uint8_t e); void fanmux_init();
2301_81045437/Marlin
Marlin/src/feature/fanmux.h
C
agpl-3.0
1,006
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfig.h" #if ENABLED(FILAMENT_WIDTH_SENSOR) #include "filwidth.h" FilamentWidthSensor filwidth; bool FilamentWidthSensor::enabled; // = false; // (M405-M406) Filament Width Sensor ON/OFF. uint32_t FilamentWidthSensor::accum; // = 0 // ADC accumulator uint16_t FilamentWidthSensor::raw; // = 0 // Measured filament diameter - one extruder only float FilamentWidthSensor::nominal_mm = DEFAULT_NOMINAL_FILAMENT_DIA, // (M104) Nominal filament width FilamentWidthSensor::measured_mm = DEFAULT_MEASURED_FILAMENT_DIA, // Measured filament diameter FilamentWidthSensor::e_count = 0, FilamentWidthSensor::delay_dist = 0; uint8_t FilamentWidthSensor::meas_delay_cm = MEASUREMENT_DELAY_CM; // Distance delay setting int8_t FilamentWidthSensor::ratios[MAX_MEASUREMENT_DELAY + 1], // Ring buffer to delay measurement. (Extruder factor minus 100) FilamentWidthSensor::index_r, // Indexes into ring buffer FilamentWidthSensor::index_w; void FilamentWidthSensor::init() { const int8_t ratio = sample_to_size_ratio(); for (uint8_t i = 0; i < COUNT(ratios); ++i) ratios[i] = ratio; index_r = index_w = 0; } #endif // FILAMENT_WIDTH_SENSOR
2301_81045437/Marlin
Marlin/src/feature/filwidth.cpp
C++
agpl-3.0
2,187
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfig.h" #include "../module/planner.h" #include "../module/thermistor/thermistors.h" class FilamentWidthSensor { public: static constexpr int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10; static bool enabled; // (M405-M406) Filament Width Sensor ON/OFF. static uint32_t accum; // ADC accumulator static uint16_t raw; // Measured filament diameter - one extruder only static float nominal_mm, // (M104) Nominal filament width measured_mm, // Measured filament diameter e_count, delay_dist; static uint8_t meas_delay_cm; // Distance delay setting static int8_t ratios[MMD_CM], // Ring buffer to delay measurement. (Extruder factor minus 100) index_r, index_w; // Indexes into ring buffer FilamentWidthSensor() { init(); } static void init(); static void enable(const bool ena) { enabled = ena; } static void set_delay_cm(const uint8_t cm) { meas_delay_cm = _MIN(cm, MAX_MEASUREMENT_DELAY); } /** * Convert Filament Width (mm) to an extrusion ratio * and reduce to an 8 bit value. * * A nominal width of 1.75 and measured width of 1.73 * gives (100 * 1.75 / 1.73) for a ratio of 101 and * a return value of 1. */ static int8_t sample_to_size_ratio() { return ABS(nominal_mm - measured_mm) <= FILWIDTH_ERROR_MARGIN ? int(100.0f * nominal_mm / measured_mm) - 100 : 0; } // Apply a single ADC reading to the raw value static void accumulate(const uint16_t adc) { if (adc > 102) // Ignore ADC under 0.5 volts accum += (uint32_t(adc) << 7) - (accum >> 7); } // Convert raw measurement to mm static float raw_to_mm(const uint16_t v) { return v * (float(ADC_VREF_MV) / 1000.0f) * RECIPROCAL(float(MAX_RAW_THERMISTOR_VALUE)); } static float raw_to_mm() { return raw_to_mm(raw); } // A scaled reading is ready // Divide to get to 0-16384 range since we used 1/128 IIR filter approach static void reading_ready() { raw = accum >> 10; } // Update mm from the raw measurement static void update_measured_mm() { measured_mm = raw_to_mm(); } // Update ring buffer used to delay filament measurements static void advance_e(const_float_t e_move) { // Increment counters with the E distance e_count += e_move; delay_dist += e_move; // Only get new measurements on forward E movement if (!UNEAR_ZERO(e_count)) { // Loop the delay distance counter (modulus by the mm length) while (delay_dist >= MMD_MM) delay_dist -= MMD_MM; // Convert into an index (cm) into the measurement array index_r = int8_t(delay_dist * 0.1f); // If the ring buffer is not full... if (index_r != index_w) { e_count = 0; // Reset the E movement counter const int8_t meas_sample = sample_to_size_ratio(); do { if (++index_w >= MMD_CM) index_w = 0; // The next unused slot ratios[index_w] = meas_sample; // Store the measurement } while (index_r != index_w); // More slots to fill? } } } // Dynamically set the volumetric multiplier based on the delayed width measurement. static void update_volumetric() { if (enabled) { int8_t read_index = index_r - meas_delay_cm; if (read_index < 0) read_index += MMD_CM; // Loop around buffer if needed LIMIT(read_index, 0, MAX_MEASUREMENT_DELAY); planner.apply_filament_width_sensor(ratios[read_index]); } } }; extern FilamentWidthSensor filwidth;
2301_81045437/Marlin
Marlin/src/feature/filwidth.h
C++
agpl-3.0
4,488
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * fwretract.cpp - Implement firmware-based retraction */ #include "../inc/MarlinConfig.h" #if ENABLED(FWRETRACT) #include "fwretract.h" FWRetract fwretract; // Single instance - this calls the constructor #include "../module/motion.h" #include "../module/planner.h" #include "../gcode/gcode.h" #if ENABLED(RETRACT_SYNC_MIXING) #include "mixing.h" #endif // private: #if HAS_MULTI_EXTRUDER Flags<EXTRUDERS> FWRetract::retracted_swap; // Which extruders are swap-retracted #endif // public: fwretract_settings_t FWRetract::settings; // M207 S F Z W, M208 S F W R #if ENABLED(FWRETRACT_AUTORETRACT) bool FWRetract::autoretract_enabled; // M209 S - Autoretract switch #endif Flags<EXTRUDERS> FWRetract::retracted; // Which extruders are currently retracted float FWRetract::current_retract[EXTRUDERS], // Retract value used by planner FWRetract::current_hop; void FWRetract::reset() { TERN_(FWRETRACT_AUTORETRACT, autoretract_enabled = false); settings.retract_length = RETRACT_LENGTH; settings.retract_feedrate_mm_s = RETRACT_FEEDRATE; settings.retract_zraise = RETRACT_ZRAISE; settings.retract_recover_extra = RETRACT_RECOVER_LENGTH; settings.retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE; settings.swap_retract_length = RETRACT_LENGTH_SWAP; settings.swap_retract_recover_extra = RETRACT_RECOVER_LENGTH_SWAP; settings.swap_retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE_SWAP; current_hop = 0.0; retracted.reset(); EXTRUDER_LOOP() { E_TERN_(retracted_swap.clear(e)); current_retract[e] = 0.0; } } /** * Retract or recover according to firmware settings * * This function handles retract/recover moves for G10 and G11, * plus auto-retract moves sent from G0/G1 when E-only moves are done. * * To simplify the logic, doubled retract/recover moves are ignored. * * Note: Auto-retract will apply the set Z hop in addition to any Z hop * included in the G-code. Use M207 Z0 to to prevent double hop. */ void FWRetract::retract(const bool retracting E_OPTARG(bool swapping/*=false*/)) { // Prevent two retracts or recovers in a row if (retracted[active_extruder] == retracting) return; // Prevent two swap-retract or recovers in a row #if HAS_MULTI_EXTRUDER // Allow G10 S1 only after G11 if (swapping && retracted_swap[active_extruder] == retracting) return; // G11 priority to recover the long retract if activated if (!retracting) swapping = retracted_swap[active_extruder]; #else constexpr bool swapping = false; #endif /* // debugging SERIAL_ECHOLNPGM( "retracting ", AS_DIGIT(retracting), " swapping ", swapping, " active extruder ", active_extruder ); EXTRUDER_LOOP() { SERIAL_ECHOLNPGM("retracted[", e, "] ", AS_DIGIT(retracted[e])); #if HAS_MULTI_EXTRUDER SERIAL_ECHOLNPGM("retracted_swap[", e, "] ", AS_DIGIT(retracted_swap[e])); #endif } SERIAL_ECHOLNPGM("current_position.z ", current_position.z); SERIAL_ECHOLNPGM("current_position.e ", current_position.e); SERIAL_ECHOLNPGM("current_hop ", current_hop); //*/ const float base_retract = TERN1(RETRACT_SYNC_MIXING, (MIXING_STEPPERS)) * (swapping ? settings.swap_retract_length : settings.retract_length); // The current position will be the destination for E and Z moves destination = current_position; #if ENABLED(RETRACT_SYNC_MIXING) const uint8_t old_mixing_tool = mixer.get_current_vtool(); mixer.T(MIXER_AUTORETRACT_TOOL); #endif const feedRate_t fr_max_z = planner.settings.max_feedrate_mm_s[Z_AXIS]; if (retracting) { // Retract by moving from a faux E position back to the current E position current_retract[active_extruder] = base_retract; prepare_internal_move_to_destination( // set current from destination settings.retract_feedrate_mm_s * TERN1(RETRACT_SYNC_MIXING, (MIXING_STEPPERS)) ); // Is a Z hop set, and has the hop not yet been done? if (!current_hop && settings.retract_zraise > 0.01f) { // Apply hop only once current_hop += settings.retract_zraise; // Add to the hop total (again, only once) // Raise up, set_current_to_destination. Maximum Z feedrate prepare_internal_move_to_destination(fr_max_z); } } else { // If a hop was done and Z hasn't changed, undo the Z hop if (current_hop) { current_hop = 0; // Lower Z, set_current_to_destination. Maximum Z feedrate prepare_internal_move_to_destination(fr_max_z); } const float extra_recover = swapping ? settings.swap_retract_recover_extra : settings.retract_recover_extra; if (extra_recover) { current_position.e -= extra_recover; // Adjust the current E position by the extra amount to recover sync_plan_position_e(); // Sync the planner position so the extra amount is recovered } current_retract[active_extruder] = 0; // Recover E, set_current_to_destination prepare_internal_move_to_destination( (swapping ? settings.swap_retract_recover_feedrate_mm_s : settings.retract_recover_feedrate_mm_s) * TERN1(RETRACT_SYNC_MIXING, (MIXING_STEPPERS)) ); } TERN_(RETRACT_SYNC_MIXING, mixer.T(old_mixing_tool)); // Restore original mixing tool retracted.set(active_extruder, retracting); // Active extruder now retracted / recovered // If swap retract/recover update the retracted_swap flag too #if HAS_MULTI_EXTRUDER if (swapping) retracted_swap.set(active_extruder, retracting); #endif /* // debugging SERIAL_ECHOLNPGM("retracting ", AS_DIGIT(retracting)); SERIAL_ECHOLNPGM("swapping ", AS_DIGIT(swapping)); SERIAL_ECHOLNPGM("active_extruder ", active_extruder); EXTRUDER_LOOP() { SERIAL_ECHOLNPGM("retracted[", e, "] ", AS_DIGIT(retracted[e])); #if HAS_MULTI_EXTRUDER SERIAL_ECHOLNPGM("retracted_swap[", e, "] ", AS_DIGIT(retracted_swap[e])); #endif } SERIAL_ECHOLNPGM("current_position.z ", current_position.z); SERIAL_ECHOLNPGM("current_position.e ", current_position.e); SERIAL_ECHOLNPGM("current_hop ", current_hop); //*/ } /** * M207: Set firmware retraction values * * S[+units] retract_length * W[+units] swap_retract_length (multi-extruder) * F[units/min] retract_feedrate_mm_s * Z[units] retract_zraise */ void FWRetract::M207() { if (!parser.seen("FSWZ")) return M207_report(); if (parser.seenval('S')) settings.retract_length = parser.value_axis_units(E_AXIS); if (parser.seenval('F')) settings.retract_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS)); if (parser.seenval('Z')) settings.retract_zraise = parser.value_linear_units(); if (parser.seenval('W')) settings.swap_retract_length = parser.value_axis_units(E_AXIS); } void FWRetract::M207_report() { TERN_(MARLIN_SMALL_BUILD, return); SERIAL_ECHOLNPGM_P( PSTR(" M207 S"), LINEAR_UNIT(settings.retract_length) , PSTR(" W"), LINEAR_UNIT(settings.swap_retract_length) , PSTR(" F"), LINEAR_UNIT(MMS_TO_MMM(settings.retract_feedrate_mm_s)) , SP_Z_STR, LINEAR_UNIT(settings.retract_zraise) ); } /** * M208: Set firmware un-retraction values * * S[+units] retract_recover_extra (in addition to M207 S*) * W[+units] swap_retract_recover_extra (multi-extruder) * F[units/min] retract_recover_feedrate_mm_s * R[units/min] swap_retract_recover_feedrate_mm_s */ void FWRetract::M208() { if (!parser.seen("FSRW")) return M208_report(); if (parser.seen('S')) settings.retract_recover_extra = parser.value_axis_units(E_AXIS); if (parser.seen('F')) settings.retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS)); if (parser.seen('R')) settings.swap_retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS)); if (parser.seen('W')) settings.swap_retract_recover_extra = parser.value_axis_units(E_AXIS); } void FWRetract::M208_report() { TERN_(MARLIN_SMALL_BUILD, return); SERIAL_ECHOLNPGM( " M208 S", LINEAR_UNIT(settings.retract_recover_extra) , " W", LINEAR_UNIT(settings.swap_retract_recover_extra) , " F", LINEAR_UNIT(MMS_TO_MMM(settings.retract_recover_feedrate_mm_s)) ); } #if ENABLED(FWRETRACT_AUTORETRACT) /** * M209: Enable automatic retract (M209 S1) * For slicers that don't support G10/11, reversed extrude-only * moves will be classified as retraction. */ void FWRetract::M209() { if (!parser.seen('S')) return M209_report(); if (MIN_AUTORETRACT <= MAX_AUTORETRACT) enable_autoretract(parser.value_bool()); } void FWRetract::M209_report() { TERN_(MARLIN_SMALL_BUILD, return); SERIAL_ECHOLNPGM(" M209 S", AS_DIGIT(autoretract_enabled)); } #endif // FWRETRACT_AUTORETRACT #endif // FWRETRACT
2301_81045437/Marlin
Marlin/src/feature/fwretract.cpp
C++
agpl-3.0
9,827
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * fwretract.h - Define firmware-based retraction interface */ #include "../inc/MarlinConfigPre.h" typedef struct { float retract_length; // M207 S - G10 Retract length feedRate_t retract_feedrate_mm_s; // M207 F - G10 Retract feedrate float retract_zraise, // M207 Z - G10 Retract hop size retract_recover_extra; // M208 S - G11 Recover length feedRate_t retract_recover_feedrate_mm_s; // M208 F - G11 Recover feedrate float swap_retract_length, // M207 W - G10 Swap Retract length swap_retract_recover_extra; // M208 W - G11 Swap Recover length feedRate_t swap_retract_recover_feedrate_mm_s; // M208 R - G11 Swap Recover feedrate } fwretract_settings_t; #if ENABLED(FWRETRACT) class FWRetract { private: #if HAS_MULTI_EXTRUDER static Flags<EXTRUDERS> retracted_swap; // Which extruders are swap-retracted #endif public: static fwretract_settings_t settings; #if ENABLED(FWRETRACT_AUTORETRACT) static bool autoretract_enabled; // M209 S - Autoretract switch #else static constexpr bool autoretract_enabled = false; #endif static Flags<EXTRUDERS> retracted; // Which extruders are currently retracted static float current_retract[EXTRUDERS], // Retract value used by planner current_hop; // Hop value used by planner FWRetract() { reset(); } static void reset(); static void refresh_autoretract() { retracted.reset(); } static void enable_autoretract(const bool enable) { #if ENABLED(FWRETRACT_AUTORETRACT) autoretract_enabled = enable; refresh_autoretract(); #endif } static void retract(const bool retracting E_OPTARG(bool swapping=false)); static void M207_report(); static void M207(); static void M208_report(); static void M208(); #if ENABLED(FWRETRACT_AUTORETRACT) static void M209_report(); static void M209(); #endif }; extern FWRetract fwretract; #endif // FWRETRACT
2301_81045437/Marlin
Marlin/src/feature/fwretract.h
C++
agpl-3.0
2,989
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfig.h" #if ENABLED(HOST_ACTION_COMMANDS) //#define DEBUG_HOST_ACTIONS #include "host_actions.h" #if ENABLED(ADVANCED_PAUSE_FEATURE) #include "pause.h" #include "../gcode/queue.h" #endif #if HAS_FILAMENT_SENSOR #include "runout.h" #endif HostUI hostui; void HostUI::action(FSTR_P const fstr, const bool eol) { PORT_REDIRECT(SerialMask::All); SERIAL_ECHOPGM("//action:", fstr); if (eol) SERIAL_EOL(); } #ifdef ACTION_ON_KILL void HostUI::kill() { action(F(ACTION_ON_KILL)); } #endif #ifdef ACTION_ON_PAUSE void HostUI::pause(const bool eol/*=true*/) { action(F(ACTION_ON_PAUSE), eol); } #endif #ifdef ACTION_ON_PAUSED void HostUI::paused(const bool eol/*=true*/) { action(F(ACTION_ON_PAUSED), eol); } #endif #ifdef ACTION_ON_RESUME void HostUI::resume() { action(F(ACTION_ON_RESUME)); } #endif #ifdef ACTION_ON_RESUMED void HostUI::resumed() { action(F(ACTION_ON_RESUMED)); } #endif #ifdef ACTION_ON_CANCEL void HostUI::cancel() { action(F(ACTION_ON_CANCEL)); } #endif #ifdef ACTION_ON_START void HostUI::start() { action(F(ACTION_ON_START)); } #endif #if ENABLED(G29_RETRY_AND_RECOVER) #ifdef ACTION_ON_G29_RECOVER void HostUI::g29_recover() { action(F(ACTION_ON_G29_RECOVER)); } #endif #ifdef ACTION_ON_G29_FAILURE void HostUI::g29_failure() { action(F(ACTION_ON_G29_FAILURE)); } #endif #endif #ifdef SHUTDOWN_ACTION void HostUI::shutdown() { action(F(SHUTDOWN_ACTION)); } #endif #if ENABLED(HOST_PROMPT_SUPPORT) PromptReason HostUI::host_prompt_reason = PROMPT_NOT_DEFINED; PGMSTR(CONTINUE_STR, "Continue"); PGMSTR(DISMISS_STR, "Dismiss"); #if HAS_RESUME_CONTINUE extern bool wait_for_user; #endif void HostUI::notify(const char * const cstr) { PORT_REDIRECT(SerialMask::All); action(F("notification "), false); SERIAL_ECHOLN(cstr); } void HostUI::notify_P(PGM_P const pstr) { PORT_REDIRECT(SerialMask::All); action(F("notification "), false); SERIAL_ECHOLNPGM_P(pstr); } void HostUI::prompt(FSTR_P const ptype, const bool eol/*=true*/) { PORT_REDIRECT(SerialMask::All); action(F("prompt_"), false); SERIAL_ECHO(ptype); if (eol) SERIAL_EOL(); } void HostUI::prompt_plus(const bool pgm, FSTR_P const ptype, const char * const str, const char extra_char/*='\0'*/) { prompt(ptype, false); PORT_REDIRECT(SerialMask::All); SERIAL_CHAR(' '); if (pgm) SERIAL_ECHOPGM_P(str); else SERIAL_ECHO(str); if (extra_char != '\0') SERIAL_CHAR(extra_char); SERIAL_EOL(); } void HostUI::prompt_begin(const PromptReason reason, FSTR_P const fstr, const char extra_char/*='\0'*/) { prompt_end(); host_prompt_reason = reason; prompt_plus(F("begin"), fstr, extra_char); } void HostUI::prompt_begin(const PromptReason reason, const char * const cstr, const char extra_char/*='\0'*/) { prompt_end(); host_prompt_reason = reason; prompt_plus(F("begin"), cstr, extra_char); } void HostUI::prompt_end() { prompt(F("end")); } void HostUI::prompt_show() { prompt(F("show")); } void HostUI::_prompt_show(FSTR_P const btn1, FSTR_P const btn2) { if (btn1) prompt_button(btn1); if (btn2) prompt_button(btn2); prompt_show(); } void HostUI::prompt_button(FSTR_P const fstr) { prompt_plus(F("button"), fstr); } void HostUI::prompt_button(const char * const cstr) { prompt_plus(F("button"), cstr); } void HostUI::prompt_do(const PromptReason reason, FSTR_P const fstr, FSTR_P const btn1/*=nullptr*/, FSTR_P const btn2/*=nullptr*/) { prompt_begin(reason, fstr); _prompt_show(btn1, btn2); } void HostUI::prompt_do(const PromptReason reason, const char * const cstr, FSTR_P const btn1/*=nullptr*/, FSTR_P const btn2/*=nullptr*/) { prompt_begin(reason, cstr); _prompt_show(btn1, btn2); } void HostUI::prompt_do(const PromptReason reason, FSTR_P const fstr, const char extra_char, FSTR_P const btn1/*=nullptr*/, FSTR_P const btn2/*=nullptr*/) { prompt_begin(reason, fstr, extra_char); _prompt_show(btn1, btn2); } void HostUI::prompt_do(const PromptReason reason, const char * const cstr, const char extra_char, FSTR_P const btn1/*=nullptr*/, FSTR_P const btn2/*=nullptr*/) { prompt_begin(reason, cstr, extra_char); _prompt_show(btn1, btn2); } #if ENABLED(ADVANCED_PAUSE_FEATURE) void HostUI::filament_load_prompt() { const bool disable_to_continue = TERN0(HAS_FILAMENT_SENSOR, runout.filament_ran_out); prompt_do(PROMPT_FILAMENT_RUNOUT, F("Paused"), F("PurgeMore"), disable_to_continue ? F("DisableRunout") : FPSTR(CONTINUE_STR) ); } #endif // // Handle responses from the host, such as: // - Filament runout responses: Purge More, Continue // - General "Continue" response // - Resume Print response // - Dismissal of info // void HostUI::handle_response(const uint8_t response) { const PromptReason hpr = host_prompt_reason; host_prompt_reason = PROMPT_NOT_DEFINED; // Reset now ahead of logic switch (hpr) { case PROMPT_FILAMENT_RUNOUT: switch (response) { case 0: // "Purge More" button #if ENABLED(M600_PURGE_MORE_RESUMABLE) pause_menu_response = PAUSE_RESPONSE_EXTRUDE_MORE; // Simulate menu selection (menu exits, doesn't extrude more) #endif break; case 1: // "Continue" / "Disable Runout" button #if ENABLED(M600_PURGE_MORE_RESUMABLE) pause_menu_response = PAUSE_RESPONSE_RESUME_PRINT; // Simulate menu selection #endif #if HAS_FILAMENT_SENSOR if (runout.filament_ran_out) { // Disable a triggered sensor runout.enabled = false; runout.reset(); } #endif break; } break; case PROMPT_USER_CONTINUE: TERN_(HAS_RESUME_CONTINUE, wait_for_user = false); break; case PROMPT_PAUSE_RESUME: #if ALL(ADVANCED_PAUSE_FEATURE, HAS_MEDIA) extern const char M24_STR[]; queue.inject_P(M24_STR); #endif break; case PROMPT_INFO: break; default: break; } } #endif // HOST_PROMPT_SUPPORT #endif // HOST_ACTION_COMMANDS
2301_81045437/Marlin
Marlin/src/feature/host_actions.cpp
C++
agpl-3.0
7,168
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfigPre.h" #include "../HAL/shared/Marduino.h" #if ENABLED(HOST_PROMPT_SUPPORT) enum PromptReason : uint8_t { PROMPT_NOT_DEFINED, PROMPT_FILAMENT_RUNOUT, PROMPT_USER_CONTINUE, PROMPT_FILAMENT_RUNOUT_REHEAT, PROMPT_PAUSE_RESUME, PROMPT_INFO }; extern const char CONTINUE_STR[], DISMISS_STR[]; #endif class HostUI { public: static void action(FSTR_P const fstr, const bool eol=true); #ifdef ACTION_ON_KILL static void kill(); #endif #ifdef ACTION_ON_PAUSE static void pause(const bool eol=true); #endif #ifdef ACTION_ON_PAUSED static void paused(const bool eol=true); #endif #ifdef ACTION_ON_RESUME static void resume(); #endif #ifdef ACTION_ON_RESUMED static void resumed(); #endif #ifdef ACTION_ON_CANCEL static void cancel(); #endif #ifdef ACTION_ON_START static void start(); #endif #ifdef SHUTDOWN_ACTION static void shutdown(); #endif #if ENABLED(G29_RETRY_AND_RECOVER) #ifdef ACTION_ON_G29_RECOVER static void g29_recover(); #endif #ifdef ACTION_ON_G29_FAILURE static void g29_failure(); #endif #endif #if ENABLED(HOST_PROMPT_SUPPORT) private: static void prompt(FSTR_P const ptype, const bool eol=true); static void prompt_plus(const bool pgm, FSTR_P const ptype, const char * const str, const char extra_char='\0'); static void prompt_plus(FSTR_P const ptype, FSTR_P const fstr, const char extra_char='\0') { prompt_plus(true, ptype, FTOP(fstr), extra_char); } static void prompt_plus(FSTR_P const ptype, const char * const cstr, const char extra_char='\0') { prompt_plus(false, ptype, cstr, extra_char); } static void prompt_show(); static void _prompt_show(FSTR_P const btn1, FSTR_P const btn2); public: static PromptReason host_prompt_reason; static void handle_response(const uint8_t response); static void notify_P(PGM_P const message); static void notify(FSTR_P const fmsg) { notify_P(FTOP(fmsg)); } static void notify(const char * const message); static void prompt_begin(const PromptReason reason, FSTR_P const fstr, const char extra_char='\0'); static void prompt_begin(const PromptReason reason, const char * const cstr, const char extra_char='\0'); static void prompt_end(); static void prompt_button(FSTR_P const fstr); static void prompt_button(const char * const cstr); static void prompt_do(const PromptReason reason, FSTR_P const pstr, FSTR_P const btn1=nullptr, FSTR_P const btn2=nullptr); static void prompt_do(const PromptReason reason, const char * const cstr, FSTR_P const btn1=nullptr, FSTR_P const btn2=nullptr); static void prompt_do(const PromptReason reason, FSTR_P const pstr, const char extra_char, FSTR_P const btn1=nullptr, FSTR_P const btn2=nullptr); static void prompt_do(const PromptReason reason, const char * const cstr, const char extra_char, FSTR_P const btn1=nullptr, FSTR_P const btn2=nullptr); static void continue_prompt(FSTR_P const fstr) { prompt_do(PROMPT_USER_CONTINUE, fstr, FPSTR(CONTINUE_STR)); } static void continue_prompt(const char * const cstr) { prompt_do(PROMPT_USER_CONTINUE, cstr, FPSTR(CONTINUE_STR)); } static void prompt_open(const PromptReason reason, FSTR_P const pstr, FSTR_P const btn1=nullptr, FSTR_P const btn2=nullptr) { if (host_prompt_reason == PROMPT_NOT_DEFINED) prompt_do(reason, pstr, btn1, btn2); } #if ENABLED(ADVANCED_PAUSE_FEATURE) static void filament_load_prompt(); #endif #endif }; extern HostUI hostui;
2301_81045437/Marlin
Marlin/src/feature/host_actions.h
C++
agpl-3.0
4,492
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * Hotend Idle Timeout * Prevent filament in the nozzle from charring and causing a critical jam. */ #include "../inc/MarlinConfig.h" #if ENABLED(HOTEND_IDLE_TIMEOUT) #include "hotend_idle.h" #include "../gcode/gcode.h" #include "../module/temperature.h" #include "../module/motion.h" #include "../module/planner.h" #include "../lcd/marlinui.h" HotendIdleProtection hotend_idle; millis_t HotendIdleProtection::next_protect_ms = 0; hotend_idle_settings_t HotendIdleProtection::cfg; // Initialized by settings.load() void HotendIdleProtection::check_hotends(const millis_t &ms) { const bool busy = (TERN0(HAS_RESUME_CONTINUE, wait_for_user) || planner.has_blocks_queued()); bool do_prot = false; if (!busy && cfg.timeout != 0) { HOTEND_LOOP() { if (thermalManager.degHotend(e) >= cfg.trigger) { do_prot = true; break; } } } if (!do_prot) next_protect_ms = 0; // No hotends are hot so cancel timeout else if (!next_protect_ms) // Timeout is possible? next_protect_ms = ms + 1000UL * cfg.timeout; // Start timeout if not already set } void HotendIdleProtection::check_e_motion(const millis_t &ms) { static float old_e_position = 0; if (old_e_position != current_position.e) { old_e_position = current_position.e; // Track filament motion if (next_protect_ms) // If some heater is on then... next_protect_ms = ms + 1000UL * cfg.timeout; // ...delay the timeout till later } } void HotendIdleProtection::check() { const millis_t ms = millis(); // Shared millis check_hotends(ms); // Any hotends need protection? check_e_motion(ms); // Motion will protect them // Hot and not moving for too long... if (next_protect_ms && ELAPSED(ms, next_protect_ms)) timed_out(); } // Lower (but don't raise) hotend / bed temperatures void HotendIdleProtection::timed_out() { next_protect_ms = 0; SERIAL_ECHOLNPGM("Hotend Idle Timeout"); LCD_MESSAGE(MSG_HOTEND_IDLE_TIMEOUT); HOTEND_LOOP() { if (cfg.nozzle_target < thermalManager.degTargetHotend(e)) thermalManager.setTargetHotend(cfg.nozzle_target, e); } #if HAS_HEATED_BED if (cfg.bed_target < thermalManager.degTargetBed()) thermalManager.setTargetBed(cfg.bed_target); #endif } #endif // HOTEND_IDLE_TIMEOUT
2301_81045437/Marlin
Marlin/src/feature/hotend_idle.cpp
C++
agpl-3.0
3,299
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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" typedef struct { int16_t timeout, trigger, nozzle_target; #if HAS_HEATED_BED int16_t bed_target; #endif void set_defaults() { timeout = HOTEND_IDLE_TIMEOUT_SEC; trigger = HOTEND_IDLE_MIN_TRIGGER; nozzle_target = HOTEND_IDLE_NOZZLE_TARGET; #if HAS_HEATED_BED bed_target = HOTEND_IDLE_BED_TARGET; #endif } } hotend_idle_settings_t; class HotendIdleProtection { public: static void check(); static hotend_idle_settings_t cfg; private: static millis_t next_protect_ms; static void check_hotends(const millis_t &ms); static void check_e_motion(const millis_t &ms); static void timed_out(); }; extern HotendIdleProtection hotend_idle;
2301_81045437/Marlin
Marlin/src/feature/hotend_idle.h
C++
agpl-3.0
1,606
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * joystick.cpp - joystick input / jogging */ #include "../inc/MarlinConfigPre.h" #if ENABLED(JOYSTICK) #include "joystick.h" #include "../inc/MarlinConfig.h" // for pins #include "../module/planner.h" Joystick joystick; #if ENABLED(EXTENSIBLE_UI) #include "../lcd/extui/ui_api.h" #endif #if HAS_JOY_ADC_X temp_info_t Joystick::x; // = { 0 } #if ENABLED(INVERT_JOY_X) #define JOY_X(N) (16383 - (N)) #else #define JOY_X(N) (N) #endif #endif #if HAS_JOY_ADC_Y temp_info_t Joystick::y; // = { 0 } #if ENABLED(INVERT_JOY_Y) #define JOY_Y(N) (16383 - (N)) #else #define JOY_Y(N) (N) #endif #endif #if HAS_JOY_ADC_Z temp_info_t Joystick::z; // = { 0 } #if ENABLED(INVERT_JOY_Z) #define JOY_Z(N) (16383 - (N)) #else #define JOY_Z(N) (N) #endif #endif #if ENABLED(JOYSTICK_DEBUG) void Joystick::report() { SERIAL_ECHOPGM("Joystick"); #if HAS_JOY_ADC_X SERIAL_ECHOPGM_P(SP_X_STR, JOY_X(x.getraw())); #endif #if HAS_JOY_ADC_Y SERIAL_ECHOPGM_P(SP_Y_STR, JOY_Y(y.getraw())); #endif #if HAS_JOY_ADC_Z SERIAL_ECHOPGM_P(SP_Z_STR, JOY_Z(z.getraw())); #endif #if HAS_JOY_ADC_EN SERIAL_ECHO_TERNARY(READ(JOY_EN_PIN), " EN=", "HIGH (dis", "LOW (en", "abled)"); #endif SERIAL_EOL(); } #endif #if HAS_JOY_ADC_X || HAS_JOY_ADC_Y || HAS_JOY_ADC_Z void Joystick::calculate(xyz_float_t &norm_jog) { // Do nothing if enable pin (active-low) is not LOW #if HAS_JOY_ADC_EN if (READ(JOY_EN_PIN)) return; #endif auto _normalize_joy = [](float &axis_jog, const raw_adc_t raw, const raw_adc_t (&joy_limits)[4]) { if (WITHIN(raw, joy_limits[0], joy_limits[3])) { // within limits, check deadzone if (raw > joy_limits[2]) axis_jog = (raw - joy_limits[2]) / float(joy_limits[3] - joy_limits[2]); else if (raw < joy_limits[1]) axis_jog = int16_t(raw - joy_limits[1]) / float(joy_limits[1] - joy_limits[0]); // negative value // Map normal to jog value via quadratic relationship axis_jog = SIGN(axis_jog) * sq(axis_jog); } }; #if HAS_JOY_ADC_X static constexpr raw_adc_t joy_x_limits[4] = JOY_X_LIMITS; _normalize_joy(norm_jog.x, JOY_X(x.getraw()), joy_x_limits); #endif #if HAS_JOY_ADC_Y static constexpr raw_adc_t joy_y_limits[4] = JOY_Y_LIMITS; _normalize_joy(norm_jog.y, JOY_Y(y.getraw()), joy_y_limits); #endif #if HAS_JOY_ADC_Z static constexpr raw_adc_t joy_z_limits[4] = JOY_Z_LIMITS; _normalize_joy(norm_jog.z, JOY_Z(z.getraw()), joy_z_limits); #endif } #endif #if ENABLED(POLL_JOG) void Joystick::inject_jog_moves() { // Recursion barrier static bool injecting_now; // = false; if (injecting_now) return; #if ENABLED(NO_MOTION_BEFORE_HOMING) if (TERN0(HAS_JOY_ADC_X, axis_should_home(X_AXIS)) || TERN0(HAS_JOY_ADC_Y, axis_should_home(Y_AXIS)) || TERN0(HAS_JOY_ADC_Z, axis_should_home(Z_AXIS))) return; #endif static constexpr int QUEUE_DEPTH = 5; // Insert up to this many movements static constexpr float target_lag = 0.25f, // Aim for 1/4 second lag seg_time = target_lag / QUEUE_DEPTH; // 0.05 seconds, short segments inserted every 1/20th of a second static constexpr millis_t timer_limit_ms = millis_t(seg_time * 500); // 25 ms minimum delay between insertions // The planner can merge/collapse small moves, so the movement queue is unreliable to control the lag static millis_t next_run = 0; if (PENDING(millis(), next_run)) return; next_run = millis() + timer_limit_ms; // Only inject a command if the planner has fewer than 5 moves and there are no unparsed commands if (planner.movesplanned() >= QUEUE_DEPTH || queue.has_commands_queued()) return; // Normalized jog values are 0 for no movement and -1 or +1 for as max feedrate (nonlinear relationship) // Jog are initialized to zero and handling input can update values but doesn't have to // You could use a two-axis joystick and a one-axis keypad and they might work together xyz_float_t norm_jog{0}; // Use ADC values and defined limits. The active zone is normalized: -1..0 (dead) 0..1 #if HAS_JOY_ADC_X || HAS_JOY_ADC_Y || HAS_JOY_ADC_Z joystick.calculate(norm_jog); #endif // Other non-joystick poll-based jogging could be implemented here // with "jogging" encapsulated as a more general class. TERN_(EXTENSIBLE_UI, ExtUI::_joystick_update(norm_jog)); // norm_jog values of [-1 .. 1] maps linearly to [-feedrate .. feedrate] xyz_float_t move_dist{0}; float hypot2 = 0; LOOP_NUM_AXES(i) if (norm_jog[i]) { move_dist[i] = seg_time * norm_jog[i] * TERN(EXTENSIBLE_UI, manual_feedrate_mm_s, planner.settings.max_feedrate_mm_s)[i]; hypot2 += sq(move_dist[i]); } if (!UNEAR_ZERO(hypot2)) { current_position += move_dist; apply_motion_limits(current_position); const float length = sqrt(hypot2); PlannerHints hints(length); injecting_now = true; planner.buffer_line(current_position, length / seg_time, active_extruder, hints); injecting_now = false; } } #endif // POLL_JOG #endif // JOYSTICK
2301_81045437/Marlin
Marlin/src/feature/joystick.cpp
C++
agpl-3.0
6,205
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * joystick.h - joystick input / jogging */ #include "../inc/MarlinConfigPre.h" #include "../core/types.h" #include "../module/temperature.h" class Joystick { friend class Temperature; private: #if HAS_JOY_ADC_X static temp_info_t x; #endif #if HAS_JOY_ADC_Y static temp_info_t y; #endif #if HAS_JOY_ADC_Z static temp_info_t z; #endif public: #if ENABLED(JOYSTICK_DEBUG) static void report(); #endif static void calculate(xyz_float_t &norm_jog); static void inject_jog_moves(); }; extern Joystick joystick;
2301_81045437/Marlin
Marlin/src/feature/joystick.h
C++
agpl-3.0
1,461
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * blinkm.cpp - Control a BlinkM over i2c */ #include "../../inc/MarlinConfig.h" #if ENABLED(BLINKM) #include "blinkm.h" #include "leds.h" #include <Wire.h> void blinkm_set_led_color(const LEDColor &color) { Wire.begin(); Wire.beginTransmission(I2C_ADDRESS(0x09)); Wire.write('o'); //to disable ongoing script, only needs to be used once Wire.write('n'); Wire.write(color.r); Wire.write(color.g); Wire.write(color.b); Wire.endTransmission(); } #endif // BLINKM
2301_81045437/Marlin
Marlin/src/feature/leds/blinkm.cpp
C++
agpl-3.0
1,369
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * blinkm.h - Control a BlinkM over i2c */ struct LEDColor; typedef LEDColor LEDColor; void blinkm_set_led_color(const LEDColor &color);
2301_81045437/Marlin
Marlin/src/feature/leds/blinkm.h
C
agpl-3.0
1,020
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * leds.cpp - Marlin RGB LED general support */ #include "../../inc/MarlinConfig.h" #if HAS_COLOR_LEDS #include "leds.h" #if ANY(CASE_LIGHT_USE_RGB_LED, CASE_LIGHT_USE_NEOPIXEL) #include "../../feature/caselight.h" #endif #if ENABLED(LED_COLOR_PRESETS) const LEDColor LEDLights::defaultLEDColor = LEDColor( LED_USER_PRESET_RED, LED_USER_PRESET_GREEN, LED_USER_PRESET_BLUE OPTARG(HAS_WHITE_LED, LED_USER_PRESET_WHITE) OPTARG(NEOPIXEL_LED, LED_USER_PRESET_BRIGHTNESS) ); #endif #if ANY(LED_CONTROL_MENU, PRINTER_EVENT_LEDS, CASE_LIGHT_IS_COLOR_LED) LEDColor LEDLights::color; bool LEDLights::lights_on; #endif LEDLights leds; void LEDLights::setup() { #if ANY(RGB_LED, RGBW_LED) if (PWM_PIN(RGB_LED_R_PIN)) SET_PWM(RGB_LED_R_PIN); else SET_OUTPUT(RGB_LED_R_PIN); if (PWM_PIN(RGB_LED_G_PIN)) SET_PWM(RGB_LED_G_PIN); else SET_OUTPUT(RGB_LED_G_PIN); if (PWM_PIN(RGB_LED_B_PIN)) SET_PWM(RGB_LED_B_PIN); else SET_OUTPUT(RGB_LED_B_PIN); #if ENABLED(RGBW_LED) if (PWM_PIN(RGB_LED_W_PIN)) SET_PWM(RGB_LED_W_PIN); else SET_OUTPUT(RGB_LED_W_PIN); #endif #if ENABLED(RGB_STARTUP_TEST) int8_t led_pin_count = 0; if (PWM_PIN(RGB_LED_R_PIN) && PWM_PIN(RGB_LED_G_PIN) && PWM_PIN(RGB_LED_B_PIN)) led_pin_count = 3; #if ENABLED(RGBW_LED) if (PWM_PIN(RGB_LED_W_PIN) && led_pin_count) led_pin_count++; #endif // Startup animation if (led_pin_count) { // blackout if (PWM_PIN(RGB_LED_R_PIN)) hal.set_pwm_duty(pin_t(RGB_LED_R_PIN), 0); else WRITE(RGB_LED_R_PIN, LOW); if (PWM_PIN(RGB_LED_G_PIN)) hal.set_pwm_duty(pin_t(RGB_LED_G_PIN), 0); else WRITE(RGB_LED_G_PIN, LOW); if (PWM_PIN(RGB_LED_B_PIN)) hal.set_pwm_duty(pin_t(RGB_LED_B_PIN), 0); else WRITE(RGB_LED_B_PIN, LOW); #if ENABLED(RGBW_LED) if (PWM_PIN(RGB_LED_W_PIN)) hal.set_pwm_duty(pin_t(RGB_LED_W_PIN), 0); else WRITE(RGB_LED_W_PIN, LOW); #endif delay(200); for (uint8_t i = 0; i < led_pin_count; ++i) { for (uint8_t b = 0; b <= 200; ++b) { const uint16_t led_pwm = b <= 100 ? b : 200 - b; if (i == 0 && PWM_PIN(RGB_LED_R_PIN)) hal.set_pwm_duty(pin_t(RGB_LED_R_PIN), led_pwm); else WRITE(RGB_LED_R_PIN, b < 100 ? HIGH : LOW); if (i == 1 && PWM_PIN(RGB_LED_G_PIN)) hal.set_pwm_duty(pin_t(RGB_LED_G_PIN), led_pwm); else WRITE(RGB_LED_G_PIN, b < 100 ? HIGH : LOW); if (i == 2 && PWM_PIN(RGB_LED_B_PIN)) hal.set_pwm_duty(pin_t(RGB_LED_B_PIN), led_pwm); else WRITE(RGB_LED_B_PIN, b < 100 ? HIGH : LOW); #if ENABLED(RGBW_LED) if (i == 3){ if (PWM_PIN(RGB_LED_W_PIN)) hal.set_pwm_duty(pin_t(RGB_LED_W_PIN), led_pwm); else WRITE(RGB_LED_W_PIN, b < 100 ? HIGH : LOW); delay(RGB_STARTUP_TEST_INNER_MS);//More slowing for ending } #endif delay(RGB_STARTUP_TEST_INNER_MS); } } delay(500); } #endif // RGB_STARTUP_TEST #elif ALL(PCA9632, RGB_STARTUP_TEST) // PCA9632 RGB_STARTUP_TEST constexpr int8_t led_pin_count = TERN(HAS_WHITE_LED, 4, 3); // Startup animation LEDColor curColor = LEDColorOff(); PCA9632_set_led_color(curColor); // blackout delay(200); /** * LED Pin Counter steps -> events * | 0-100 | 100-200 | 200-300 | 300-400 | * fade in steady | fade out * start next pin fade in */ uint16_t led_pin_counters[led_pin_count] = { 1, 0, 0 }; bool canEnd = false; while (led_pin_counters[0] != 99 || !canEnd) { if (led_pin_counters[0] == 99) // End loop next time pin0 counter is 99 canEnd = true; for (uint8_t i = 0; i < led_pin_count; ++i) { if (led_pin_counters[i] > 0) { if (++led_pin_counters[i] == 400) // turn off current pin counter in led_pin_counters led_pin_counters[i] = 0; else if (led_pin_counters[i] == 201) { // start next pin pwm led_pin_counters[i + 1 == led_pin_count ? 0 : i + 1] = 1; i++; // skip next pin in this loop so it doesn't increment twice } } } uint16_t r, g, b; r = led_pin_counters[0]; curColor.r = r <= 100 ? r : r <= 300 ? 100 : 400 - r; g = led_pin_counters[1]; curColor.g = g <= 100 ? g : g <= 300 ? 100 : 400 - g; b = led_pin_counters[2]; curColor.b = b <= 100 ? b : b <= 300 ? 100 : 400 - b; #if HAS_WHITE_LED const uint16_t w = led_pin_counters[3]; curColor.w = w <= 100 ? w : w <= 300 ? 100 : 400 - w; #endif PCA9632_set_led_color(curColor); delay(RGB_STARTUP_TEST_INNER_MS); } // Fade to white for (uint8_t led_pwm = 0; led_pwm <= 100; ++led_pwm) { NOLESS(curColor.r, led_pwm); NOLESS(curColor.g, led_pwm); NOLESS(curColor.b, led_pwm); TERN_(HAS_WHITE_LED, NOLESS(curColor.w, led_pwm)); PCA9632_set_led_color(curColor); delay(RGB_STARTUP_TEST_INNER_MS); } #endif // PCA9632 && RGB_STARTUP_TEST TERN_(NEOPIXEL_LED, neo.init()); TERN_(PCA9533, PCA9533_init()); TERN_(LED_USER_PRESET_STARTUP, set_default()); } void LEDLights::set_color(const LEDColor &incol OPTARG(NEOPIXEL_IS_SEQUENTIAL, bool isSequence/*=false*/) ) { #if ENABLED(NEOPIXEL_LED) const uint32_t neocolor = LEDColorWhite() == incol ? neo.Color(NEO_WHITE) : neo.Color(incol.r, incol.g, incol.b OPTARG(HAS_WHITE_LED, incol.w)); #if ENABLED(NEOPIXEL_IS_SEQUENTIAL) static uint16_t nextLed = 0; #ifdef NEOPIXEL_BKGD_INDEX_FIRST while (WITHIN(nextLed, NEOPIXEL_BKGD_INDEX_FIRST, NEOPIXEL_BKGD_INDEX_LAST)) { neo.reset_background_color(); if (++nextLed >= neo.pixels()) { nextLed = 0; return; } } #endif #endif #if ALL(CASE_LIGHT_MENU, CASE_LIGHT_USE_NEOPIXEL) // Update brightness only if caselight is ON or switching leds off if (caselight.on || incol.is_off()) #endif neo.set_brightness(incol.i); #if ENABLED(NEOPIXEL_IS_SEQUENTIAL) if (isSequence) { neo.set_pixel_color(nextLed, neocolor); neo.show(); if (++nextLed >= neo.pixels()) nextLed = 0; return; } #endif #if ALL(CASE_LIGHT_MENU, CASE_LIGHT_USE_NEOPIXEL) // Update color only if caselight is ON or switching leds off if (caselight.on || incol.is_off()) #endif neo.set_color(neocolor); #endif #if ENABLED(BLINKM) // This variant uses i2c to send the RGB components to the device. blinkm_set_led_color(incol); #endif #if ANY(RGB_LED, RGBW_LED) // This variant uses 3-4 separate pins for the RGB(W) components. // If the pins can do PWM then their intensity will be set. #define _UPDATE_RGBW(C,c) do { \ if (PWM_PIN(RGB_LED_##C##_PIN)) \ hal.set_pwm_duty(pin_t(RGB_LED_##C##_PIN), c); \ else \ WRITE(RGB_LED_##C##_PIN, c ? HIGH : LOW); \ }while(0) #define UPDATE_RGBW(C,c) _UPDATE_RGBW(C, TERN1(CASE_LIGHT_USE_RGB_LED, caselight.on) ? incol.c : 0) UPDATE_RGBW(R,r); UPDATE_RGBW(G,g); UPDATE_RGBW(B,b); #if ENABLED(RGBW_LED) UPDATE_RGBW(W,w); #endif #endif // Update I2C LED driver TERN_(PCA9632, PCA9632_set_led_color(incol)); TERN_(PCA9533, PCA9533_set_rgb(incol.r, incol.g, incol.b)); #if ANY(LED_CONTROL_MENU, PRINTER_EVENT_LEDS) // Don't update the color when OFF lights_on = !incol.is_off(); if (lights_on) color = incol; #endif } #if ENABLED(LED_CONTROL_MENU) void LEDLights::toggle() { if (lights_on) set_off(); else update(); } #endif #if LED_POWEROFF_TIMEOUT > 0 millis_t LEDLights::led_off_time; // = 0 void LEDLights::update_timeout(const bool power_on) { if (lights_on) { const millis_t ms = millis(); if (power_on) reset_timeout(ms); else if (ELAPSED(ms, led_off_time)) set_off(); } } #endif #if ENABLED(NEOPIXEL2_SEPARATE) #if ENABLED(NEO2_COLOR_PRESETS) const LEDColor LEDLights2::defaultLEDColor = LEDColor( NEO2_USER_PRESET_RED, NEO2_USER_PRESET_GREEN, NEO2_USER_PRESET_BLUE OPTARG(HAS_WHITE_LED2, NEO2_USER_PRESET_WHITE) OPTARG(NEOPIXEL_LED, NEO2_USER_PRESET_BRIGHTNESS) ); #endif #if ENABLED(LED_CONTROL_MENU) LEDColor LEDLights2::color; bool LEDLights2::lights_on; #endif LEDLights2 leds2; void LEDLights2::setup() { neo2.init(); TERN_(NEO2_USER_PRESET_STARTUP, set_default()); } void LEDLights2::set_color(const LEDColor &incol) { const uint32_t neocolor = LEDColorWhite() == incol ? neo2.Color(NEO2_WHITE) : neo2.Color(incol.r, incol.g, incol.b OPTARG(HAS_WHITE_LED2, incol.w)); neo2.set_brightness(incol.i); neo2.set_color(neocolor); #if ENABLED(LED_CONTROL_MENU) // Don't update the color when OFF lights_on = !incol.is_off(); if (lights_on) color = incol; #endif } #if ENABLED(LED_CONTROL_MENU) void LEDLights2::toggle() { if (lights_on) set_off(); else update(); } #endif #endif // NEOPIXEL2_SEPARATE #endif // HAS_COLOR_LEDS
2301_81045437/Marlin
Marlin/src/feature/leds/leds.cpp
C++
agpl-3.0
10,193
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * leds.h - Marlin general RGB LED support */ #include "../../inc/MarlinConfigPre.h" #include <string.h> // A white component can be passed #if ANY(RGBW_LED, PCA9632_RGBW) #define HAS_WHITE_LED 1 #endif #if ENABLED(NEOPIXEL_LED) #define _NEOPIXEL_INCLUDE_ #include "neopixel.h" #undef _NEOPIXEL_INCLUDE_ #endif #if ENABLED(BLINKM) #include "blinkm.h" #endif #if ENABLED(PCA9533) #include "pca9533.h" #endif #if ENABLED(PCA9632) #include "pca9632.h" #endif /** * LEDcolor type for use with leds.set_color */ typedef struct LEDColor { uint8_t r, g, b OPTARG(HAS_WHITE_LED, w) OPTARG(NEOPIXEL_LED, i) ; LEDColor() : r(255), g(255), b(255) OPTARG(HAS_WHITE_LED, w(255)) OPTARG(NEOPIXEL_LED, i(NEOPIXEL_BRIGHTNESS)) {} LEDColor(const LEDColor&) = default; LEDColor(uint8_t r, uint8_t g, uint8_t b OPTARG(HAS_WHITE_LED, uint8_t w=0) OPTARG(NEOPIXEL_LED, uint8_t i=NEOPIXEL_BRIGHTNESS)) : r(r), g(g), b(b) OPTARG(HAS_WHITE_LED, w(w)) OPTARG(NEOPIXEL_LED, i(i)) {} LEDColor(const uint8_t (&rgbw)[4]) : r(rgbw[0]), g(rgbw[1]), b(rgbw[2]) OPTARG(HAS_WHITE_LED, w(rgbw[3])) OPTARG(NEOPIXEL_LED, i(NEOPIXEL_BRIGHTNESS)) {} LEDColor& operator=(const uint8_t (&rgbw)[4]) { r = rgbw[0]; g = rgbw[1]; b = rgbw[2]; TERN_(HAS_WHITE_LED, w = rgbw[3]); return *this; } bool operator==(const LEDColor &right) { if (this == &right) return true; return 0 == memcmp(this, &right, sizeof(LEDColor)); } bool operator!=(const LEDColor &right) { return !operator==(right); } bool is_off() const { return 3 > r + g + b + TERN0(HAS_WHITE_LED, w); } } LEDColor; /** * Color presets */ #define LEDColorOff() LEDColor( 0, 0, 0) #define LEDColorRed() LEDColor(255, 0, 0) #if ENABLED(LED_COLORS_REDUCE_GREEN) #define LEDColorOrange() LEDColor(255, 25, 0) #define LEDColorYellow() LEDColor(255, 75, 0) #else #define LEDColorOrange() LEDColor(255, 80, 0) #define LEDColorYellow() LEDColor(255, 255, 0) #endif #define LEDColorGreen() LEDColor( 0, 255, 0) #define LEDColorBlue() LEDColor( 0, 0, 255) #define LEDColorIndigo() LEDColor( 0, 255, 255) #define LEDColorViolet() LEDColor(255, 0, 255) #if HAS_WHITE_LED && DISABLED(RGB_LED) #define LEDColorWhite() LEDColor( 0, 0, 0, 255) #else #define LEDColorWhite() LEDColor(255, 255, 255) #endif class LEDLights { public: #if ANY(LED_CONTROL_MENU, PRINTER_EVENT_LEDS, CASE_LIGHT_IS_COLOR_LED) static LEDColor color; // last non-off color static bool lights_on; // the last set color was "on" #else static constexpr bool lights_on = true; #endif LEDLights() {} // ctor static void setup(); // init() static void set_color(const LEDColor &color OPTARG(NEOPIXEL_IS_SEQUENTIAL, bool isSequence=false) ); static void set_color(uint8_t r, uint8_t g, uint8_t b OPTARG(HAS_WHITE_LED, uint8_t w=0) OPTARG(NEOPIXEL_LED, uint8_t i=NEOPIXEL_BRIGHTNESS) OPTARG(NEOPIXEL_IS_SEQUENTIAL, bool isSequence=false) ) { set_color(LEDColor(r, g, b OPTARG(HAS_WHITE_LED, w) OPTARG(NEOPIXEL_LED, i)) OPTARG(NEOPIXEL_IS_SEQUENTIAL, isSequence)); } static void set_off() { set_color(LEDColorOff()); } static void set_green() { set_color(LEDColorGreen()); } static void set_white() { set_color(LEDColorWhite()); } #if ENABLED(LED_COLOR_PRESETS) static const LEDColor defaultLEDColor; static void set_default() { set_color(defaultLEDColor); } static void set_red() { set_color(LEDColorRed()); } static void set_orange() { set_color(LEDColorOrange()); } static void set_yellow() { set_color(LEDColorYellow()); } static void set_blue() { set_color(LEDColorBlue()); } static void set_indigo() { set_color(LEDColorIndigo()); } static void set_violet() { set_color(LEDColorViolet()); } #endif #if ENABLED(PRINTER_EVENT_LEDS) static LEDColor get_color() { return lights_on ? color : LEDColorOff(); } #endif #if ENABLED(LED_CONTROL_MENU) static void toggle(); // swap "off" with color #endif #if ANY(LED_CONTROL_MENU, CASE_LIGHT_USE_RGB_LED) || LED_POWEROFF_TIMEOUT > 0 static void update() { set_color(color); } #endif #if LED_POWEROFF_TIMEOUT > 0 private: static millis_t led_off_time; public: static void reset_timeout(const millis_t &ms) { led_off_time = ms + LED_POWEROFF_TIMEOUT; if (!lights_on) update(); } static void update_timeout(const bool power_on); #endif }; extern LEDLights leds; #if ENABLED(NEOPIXEL2_SEPARATE) class LEDLights2 { public: LEDLights2() {} static void setup(); // init() static void set_color(const LEDColor &color); static void set_color(uint8_t r, uint8_t g, uint8_t b OPTARG(HAS_WHITE_LED, uint8_t w=0) OPTARG(NEOPIXEL_LED, uint8_t i=NEOPIXEL_BRIGHTNESS) ) { set_color(LEDColor(r, g, b OPTARG(HAS_WHITE_LED, w) OPTARG(NEOPIXEL_LED, i) )); } static void set_off() { set_color(LEDColorOff()); } static void set_green() { set_color(LEDColorGreen()); } static void set_white() { set_color(LEDColorWhite()); } #if ENABLED(NEO2_COLOR_PRESETS) static const LEDColor defaultLEDColor; static void set_default() { set_color(defaultLEDColor); } static void set_red() { set_color(LEDColorRed()); } static void set_orange() { set_color(LEDColorOrange()); } static void set_yellow() { set_color(LEDColorYellow()); } static void set_blue() { set_color(LEDColorBlue()); } static void set_indigo() { set_color(LEDColorIndigo()); } static void set_violet() { set_color(LEDColorViolet()); } #endif #if ENABLED(NEOPIXEL2_SEPARATE) static LEDColor color; // last non-off color static bool lights_on; // the last set color was "on" static void toggle(); // swap "off" with color static void update() { set_color(color); } #endif }; extern LEDLights2 leds2; #endif // NEOPIXEL2_SEPARATE
2301_81045437/Marlin
Marlin/src/feature/leds/leds.h
C++
agpl-3.0
7,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/>. * */ /** * Marlin RGB LED general support */ #include "../../inc/MarlinConfig.h" #if ENABLED(NEOPIXEL_LED) #include "leds.h" #if ANY(NEOPIXEL_STARTUP_TEST, NEOPIXEL2_STARTUP_TEST) #include "../../core/utility.h" #endif Marlin_NeoPixel neo; pixel_index_t Marlin_NeoPixel::neoindex; Adafruit_NeoPixel Marlin_NeoPixel::adaneo1(NEOPIXEL_PIXELS, NEOPIXEL_PIN, NEOPIXEL_TYPE + NEO_KHZ800); #if CONJOINED_NEOPIXEL Adafruit_NeoPixel Marlin_NeoPixel::adaneo2(NEOPIXEL_PIXELS, NEOPIXEL2_PIN, NEOPIXEL2_TYPE + NEO_KHZ800); #endif #ifdef NEOPIXEL_BKGD_INDEX_FIRST void Marlin_NeoPixel::set_background_color(const uint8_t r, const uint8_t g, const uint8_t b, const uint8_t w) { for (int background_led = NEOPIXEL_BKGD_INDEX_FIRST; background_led <= NEOPIXEL_BKGD_INDEX_LAST; background_led++) set_pixel_color(background_led, adaneo1.Color(r, g, b, w)); } void Marlin_NeoPixel::reset_background_color() { constexpr uint8_t background_color[4] = NEOPIXEL_BKGD_COLOR; set_background_color(background_color); } void Marlin_NeoPixel::set_background_off() { #ifndef NEOPIXEL_BKGD_TIMEOUT_COLOR #define NEOPIXEL_BKGD_TIMEOUT_COLOR { 0, 0, 0, 0 } #endif constexpr uint8_t background_color_off[4] = NEOPIXEL_BKGD_TIMEOUT_COLOR; set_background_color(background_color_off); } #endif // NEOPIXEL_BKGD_INDEX_FIRST void Marlin_NeoPixel::set_color(const uint32_t color) { if (neoindex >= 0) { set_pixel_color(neoindex, color); neoindex = -1; } else { for (uint16_t i = 0; i < pixels(); ++i) { #ifdef NEOPIXEL_BKGD_INDEX_FIRST if (i == NEOPIXEL_BKGD_INDEX_FIRST && TERN(NEOPIXEL_BKGD_ALWAYS_ON, true, color != 0x000000)) { reset_background_color(); i += NEOPIXEL_BKGD_INDEX_LAST - (NEOPIXEL_BKGD_INDEX_FIRST); continue; } #endif set_pixel_color(i, color); } } show(); } void Marlin_NeoPixel::set_color_startup(const uint32_t color) { for (uint16_t i = 0; i < pixels(); ++i) set_pixel_color(i, color); show(); } void Marlin_NeoPixel::init() { neoindex = -1; // -1 .. NEOPIXEL_PIXELS-1 range set_brightness(NEOPIXEL_BRIGHTNESS); // 0 .. 255 range begin(); show(); // initialize to all off #if ENABLED(NEOPIXEL_STARTUP_TEST) set_color_startup(adaneo1.Color(255, 0, 0, 0)); // red safe_delay(500); set_color_startup(adaneo1.Color(0, 255, 0, 0)); // green safe_delay(500); set_color_startup(adaneo1.Color(0, 0, 255, 0)); // blue safe_delay(500); #if HAS_WHITE_LED set_color_startup(adaneo1.Color(0, 0, 0, 255)); // white safe_delay(500); #endif #endif #ifdef NEOPIXEL_BKGD_INDEX_FIRST reset_background_color(); #endif set_color(adaneo1.Color TERN(LED_USER_PRESET_STARTUP, (LED_USER_PRESET_RED, LED_USER_PRESET_GREEN, LED_USER_PRESET_BLUE, LED_USER_PRESET_WHITE), (0, 0, 0, 0)) ); } #if ENABLED(NEOPIXEL2_SEPARATE) Marlin_NeoPixel2 neo2; pixel_index_t Marlin_NeoPixel2::neoindex; Adafruit_NeoPixel Marlin_NeoPixel2::adaneo(NEOPIXEL2_PIXELS, NEOPIXEL2_PIN, NEOPIXEL2_TYPE); void Marlin_NeoPixel2::set_color(const uint32_t color) { if (neoindex >= 0) { set_pixel_color(neoindex, color); neoindex = -1; } else { for (uint16_t i = 0; i < pixels(); ++i) set_pixel_color(i, color); } show(); } void Marlin_NeoPixel2::set_color_startup(const uint32_t color) { for (uint16_t i = 0; i < pixels(); ++i) set_pixel_color(i, color); show(); } void Marlin_NeoPixel2::init() { neoindex = -1; // -1 .. NEOPIXEL2_PIXELS-1 range set_brightness(NEOPIXEL2_BRIGHTNESS); // 0 .. 255 range begin(); show(); // initialize to all off #if ENABLED(NEOPIXEL2_STARTUP_TEST) set_color_startup(adaneo.Color(255, 0, 0, 0)); // red safe_delay(500); set_color_startup(adaneo.Color(0, 255, 0, 0)); // green safe_delay(500); set_color_startup(adaneo.Color(0, 0, 255, 0)); // blue safe_delay(500); #if HAS_WHITE_LED2 set_color_startup(adaneo.Color(0, 0, 0, 255)); // white safe_delay(500); #endif #endif set_color(adaneo.Color TERN(NEO2_USER_PRESET_STARTUP, (NEO2_USER_PRESET_RED, NEO2_USER_PRESET_GREEN, NEO2_USER_PRESET_BLUE, NEO2_USER_PRESET_WHITE), (0, 0, 0, 0)) ); } #endif // NEOPIXEL2_SEPARATE #endif // NEOPIXEL_LED
2301_81045437/Marlin
Marlin/src/feature/leds/neopixel.cpp
C++
agpl-3.0
5,330
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * NeoPixel support */ #ifndef _NEOPIXEL_INCLUDE_ #error "Always include 'leds.h' and not 'neopixel.h' directly." #endif // ------------------------ // Includes // ------------------------ #include "../../inc/MarlinConfig.h" #include <Adafruit_NeoPixel.h> #include <stdint.h> // ------------------------ // Defines // ------------------------ #define _NEO_IS_RGB(N) (N == NEO_RGB || N == NEO_RBG || N == NEO_GRB || N == NEO_GBR || N == NEO_BRG || N == NEO_BGR) #if !_NEO_IS_RGB(NEOPIXEL_TYPE) #define HAS_WHITE_LED 1 #endif #if HAS_WHITE_LED #define NEO_WHITE 0, 0, 0, 255 #else #define NEO_WHITE 255, 255, 255 #endif #if defined(NEOPIXEL2_TYPE) && NEOPIXEL2_TYPE != NEOPIXEL_TYPE && DISABLED(NEOPIXEL2_SEPARATE) #define MULTIPLE_NEOPIXEL_TYPES 1 #endif #if ANY(MULTIPLE_NEOPIXEL_TYPES, NEOPIXEL2_INSERIES) #define CONJOINED_NEOPIXEL 1 #endif // ------------------------ // Types // ------------------------ typedef value_t(TERN0(NEOPIXEL_LED, NEOPIXEL_PIXELS)) pixel_index_t; // ------------------------ // Classes // ------------------------ class Marlin_NeoPixel { private: static Adafruit_NeoPixel adaneo1; #if CONJOINED_NEOPIXEL static Adafruit_NeoPixel adaneo2; #endif public: static pixel_index_t neoindex; static void init(); static void set_color_startup(const uint32_t c); static void set_color(const uint32_t c); #ifdef NEOPIXEL_BKGD_INDEX_FIRST static void set_background_color(const uint8_t r, const uint8_t g, const uint8_t b, const uint8_t w); static void set_background_color(const uint8_t (&rgbw)[4]) { set_background_color(rgbw[0], rgbw[1], rgbw[2], rgbw[3]); } static void reset_background_color(); static void set_background_off(); #endif static void begin() { adaneo1.begin(); TERN_(CONJOINED_NEOPIXEL, adaneo2.begin()); } static void set_pixel_color(const uint16_t n, const uint32_t c) { #if ENABLED(NEOPIXEL2_INSERIES) if (n >= NEOPIXEL_PIXELS) adaneo2.setPixelColor(n - (NEOPIXEL_PIXELS), c); else adaneo1.setPixelColor(n, c); #else adaneo1.setPixelColor(n, c); TERN_(MULTIPLE_NEOPIXEL_TYPES, adaneo2.setPixelColor(n, c)); #endif } static void set_brightness(const uint8_t b) { adaneo1.setBrightness(b); TERN_(CONJOINED_NEOPIXEL, adaneo2.setBrightness(b)); } static void show() { // Some platforms cannot maintain PWM output when NeoPixel disables interrupts for long durations. TERN_(HAS_PAUSE_SERVO_OUTPUT, PAUSE_SERVO_OUTPUT()); adaneo1.show(); #if PIN_EXISTS(NEOPIXEL2) #if CONJOINED_NEOPIXEL adaneo2.show(); #else adaneo1.show(); adaneo1.setPin(NEOPIXEL_PIN); #endif #endif TERN_(HAS_PAUSE_SERVO_OUTPUT, RESUME_SERVO_OUTPUT()); } // Accessors static uint16_t pixels() { return adaneo1.numPixels() * TERN1(NEOPIXEL2_INSERIES, 2); } static uint32_t pixel_color(const uint16_t n) { #if ENABLED(NEOPIXEL2_INSERIES) if (n >= NEOPIXEL_PIXELS) return adaneo2.getPixelColor(n - (NEOPIXEL_PIXELS)); #endif return adaneo1.getPixelColor(n); } static uint8_t brightness() { return adaneo1.getBrightness(); } static uint32_t Color(uint8_t r, uint8_t g, uint8_t b OPTARG(HAS_WHITE_LED, uint8_t w)) { return adaneo1.Color(r, g, b OPTARG(HAS_WHITE_LED, w)); } }; extern Marlin_NeoPixel neo; // Neo pixel channel 2 #if ENABLED(NEOPIXEL2_SEPARATE) #if _NEO_IS_RGB(NEOPIXEL2_TYPE) #define NEOPIXEL2_IS_RGB 1 #define NEO2_WHITE 255, 255, 255 #else #define NEOPIXEL2_IS_RGBW 1 #define HAS_WHITE_LED2 1 // A white component can be passed for NEOPIXEL2 #define NEO2_WHITE 0, 0, 0, 255 #endif class Marlin_NeoPixel2 { private: static Adafruit_NeoPixel adaneo; public: static pixel_index_t neoindex; static void init(); static void set_color_startup(const uint32_t c); static void set_color(const uint32_t c); static void begin() { adaneo.begin(); } static void set_pixel_color(const uint16_t n, const uint32_t c) { adaneo.setPixelColor(n, c); } static void set_brightness(const uint8_t b) { adaneo.setBrightness(b); } static void show() { adaneo.show(); adaneo.setPin(NEOPIXEL2_PIN); } // Accessors static uint16_t pixels() { return adaneo.numPixels();} static uint32_t pixel_color(const uint16_t n) { return adaneo.getPixelColor(n); } static uint8_t brightness() { return adaneo.getBrightness(); } static uint32_t Color(uint8_t r, uint8_t g, uint8_t b OPTARG(HAS_WHITE_LED2, uint8_t w)) { return adaneo.Color(r, g, b OPTARG(HAS_WHITE_LED2, w)); } }; extern Marlin_NeoPixel2 neo2; #endif // NEOPIXEL2_SEPARATE #undef _NEO_IS_RGB
2301_81045437/Marlin
Marlin/src/feature/leds/neopixel.h
C++
agpl-3.0
5,596
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * PCA9533 LED controller driver (MightyBoard, FlashForge Creator Pro, etc.) * by @grauerfuchs - 1 Apr 2020 */ #include "../../inc/MarlinConfig.h" #if ENABLED(PCA9533) #include "pca9533.h" #include <Wire.h> void PCA9533_init() { Wire.begin(); PCA9533_reset(); } static void PCA9533_writeAllRegisters(uint8_t psc0, uint8_t pwm0, uint8_t psc1, uint8_t pwm1, uint8_t ls0) { uint8_t data[6] = { PCA9533_REG_PSC0 | PCA9533_REGM_AI, psc0, pwm0, psc1, pwm1, ls0 }; Wire.beginTransmission(PCA9533_Addr >> 1); Wire.write(data, 6); Wire.endTransmission(); delayMicroseconds(1); } static void PCA9533_writeRegister(uint8_t reg, uint8_t val) { uint8_t data[2] = { reg, val }; Wire.beginTransmission(PCA9533_Addr >> 1); Wire.write(data, 2); Wire.endTransmission(); delayMicroseconds(1); } // Reset (clear) all registers void PCA9533_reset() { PCA9533_writeAllRegisters(0, 0, 0, 0, 0); } // Turn all LEDs off void PCA9533_setOff() { PCA9533_writeRegister(PCA9533_REG_SEL, 0); } void PCA9533_set_rgb(uint8_t red, uint8_t green, uint8_t blue) { uint8_t r_pwm0 = 0; // Register data - PWM value uint8_t r_pwm1 = 0; // Register data - PWM value uint8_t op_g = 0, op_r = 0, op_b = 0; // Opcodes - Green, Red, Blue // Light theory! GREEN takes priority because // it's the most visible to the human eye. if (green == 0) op_g = PCA9533_LED_OP_OFF; else if (green == 255) op_g = PCA9533_LED_OP_ON; else { r_pwm0 = green; op_g = PCA9533_LED_OP_PWM0; } // RED if (red == 0) op_r = PCA9533_LED_OP_OFF; else if (red == 255) op_r = PCA9533_LED_OP_ON; else if (r_pwm0 == 0 || r_pwm0 == red) { r_pwm0 = red; op_r = PCA9533_LED_OP_PWM0; } else { r_pwm1 = red; op_r = PCA9533_LED_OP_PWM1; } // BLUE if (blue == 0) op_b = PCA9533_LED_OP_OFF; else if (blue == 255) op_b = PCA9533_LED_OP_ON; else if (r_pwm0 == 0 || r_pwm0 == blue) { r_pwm0 = blue; op_b = PCA9533_LED_OP_PWM0; } else if (r_pwm1 == 0 || r_pwm1 == blue) { r_pwm1 = blue; op_b = PCA9533_LED_OP_PWM1; } else { /** * Conflict. 3 values are requested but only 2 channels exist. * G is on channel 0 and R is on channel 1, so work from there. * Find the closest match, average the values, then use the free channel. */ uint8_t dgb = ABS(green - blue), dgr = ABS(green - red), dbr = ABS(blue - red); if (dgb < dgr && dgb < dbr) { // Mix with G on channel 0. op_b = PCA9533_LED_OP_PWM0; r_pwm0 = uint8_t(((uint16_t)green + (uint16_t)blue) / 2); } else if (dbr <= dgr && dbr <= dgb) { // Mix with R on channel 1. op_b = PCA9533_LED_OP_PWM1; r_pwm1 = uint8_t(((uint16_t)red + (uint16_t)blue) / 2); } else { // Mix R+G on 0 and put B on 1. op_r = PCA9533_LED_OP_PWM0; r_pwm0 = uint8_t(((uint16_t)green + (uint16_t)red) / 2); op_b = PCA9533_LED_OP_PWM1; r_pwm1 = blue; } } // Write the changes to the hardware PCA9533_writeAllRegisters(0, r_pwm0, 0, r_pwm1, (op_g << PCA9533_LED_OFS_GRN) | (op_r << PCA9533_LED_OFS_RED) | (op_b << PCA9533_LED_OFS_BLU) ); } #endif // PCA9533
2301_81045437/Marlin
Marlin/src/feature/leds/pca9533.cpp
C++
agpl-3.0
4,108
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * Driver for the PCA9533 LED controller found on the MightyBoard * used by FlashForge Creator Pro, MakerBot, etc. * Written 2020 APR 01 by grauerfuchs */ #include <Arduino.h> #define ENABLE_I2C_PULLUPS // Chip address (for Wire) #define PCA9533_Addr 0xC4 // Control registers #define PCA9533_REG_READ 0x00 #define PCA9533_REG_PSC0 0x01 #define PCA9533_REG_PWM0 0x02 #define PCA9533_REG_PSC1 0x03 #define PCA9533_REG_PWM1 0x04 #define PCA9533_REG_SEL 0x05 #define PCA9533_REGM_AI 0x10 // LED selector operation #define PCA9533_LED_OP_OFF 0B00 #define PCA9533_LED_OP_ON 0B01 #define PCA9533_LED_OP_PWM0 0B10 #define PCA9533_LED_OP_PWM1 0B11 // Select register bit offsets for LED colors #define PCA9533_LED_OFS_RED 0 #define PCA9533_LED_OFS_GRN 2 #define PCA9533_LED_OFS_BLU 4 void PCA9533_init(); void PCA9533_reset(); void PCA9533_set_rgb(uint8_t red, uint8_t green, uint8_t blue); void PCA9533_setOff();
2301_81045437/Marlin
Marlin/src/feature/leds/pca9533.h
C
agpl-3.0
1,828
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * Driver for the Philips PCA9632 LED driver. * Written by Robert Mendon Feb 2017. */ #include "../../inc/MarlinConfig.h" #if ENABLED(PCA9632) #include "pca9632.h" #include "leds.h" #include <Wire.h> #define PCA9632_MODE1_VALUE 0b00000001 //(ALLCALL) #define PCA9632_MODE2_VALUE 0b00010101 //(DIMMING, INVERT, CHANGE ON STOP,TOTEM) #define PCA9632_LEDOUT_VALUE 0b00101010 /* Register addresses */ #define PCA9632_MODE1 0x00 #define PCA9632_MODE2 0x01 #define PCA9632_PWM0 0x02 #define PCA9632_PWM1 0x03 #define PCA9632_PWM2 0x04 #define PCA9632_PWM3 0x05 #define PCA9632_GRPPWM 0x06 #define PCA9632_GRPFREQ 0x07 #define PCA9632_LEDOUT 0x08 #define PCA9632_SUBADR1 0x09 #define PCA9632_SUBADR2 0x0A #define PCA9632_SUBADR3 0x0B #define PCA9632_ALLCALLADDR 0x0C #define PCA9632_NO_AUTOINC 0x00 #define PCA9632_AUTO_ALL 0x80 #define PCA9632_AUTO_IND 0xA0 #define PCA9632_AUTOGLO 0xC0 #define PCA9632_AUTOGI 0xE0 // Red=LED0 Green=LED1 Blue=LED2 White=LED3 #ifndef PCA9632_RED #define PCA9632_RED 0x00 #endif #ifndef PCA9632_GRN #define PCA9632_GRN 0x02 #endif #ifndef PCA9632_BLU #define PCA9632_BLU 0x04 #endif #if HAS_WHITE_LED && !defined(PCA9632_WHT) #define PCA9632_WHT 0x06 #endif // If any of the color indexes are greater than 0x04 they can't use auto increment #if !defined(PCA9632_NO_AUTO_INC) && (PCA9632_RED > 0x04 || PCA9632_GRN > 0x04 || PCA9632_BLU > 0x04 || PCA9632_WHT > 0x04) #define PCA9632_NO_AUTO_INC #endif #define LED_OFF 0x00 #define LED_ON 0x01 #define LED_PWM 0x02 #define PCA9632_ADDRESS 0b01100000 byte PCA_init = 0; static void PCA9632_WriteRegister(const byte addr, const byte regadd, const byte value) { Wire.beginTransmission(I2C_ADDRESS(addr)); Wire.write(regadd); Wire.write(value); Wire.endTransmission(); } static void PCA9632_WriteAllRegisters(const byte addr, const byte regadd, const byte vr, const byte vg, const byte vb OPTARG(PCA9632_RGBW, const byte vw) ) { #if DISABLED(PCA9632_NO_AUTO_INC) uint8_t data[4]; data[0] = PCA9632_AUTO_IND | regadd; data[1 + (PCA9632_RED >> 1)] = vr; data[1 + (PCA9632_GRN >> 1)] = vg; data[1 + (PCA9632_BLU >> 1)] = vb; Wire.beginTransmission(I2C_ADDRESS(addr)); Wire.write(data, sizeof(data)); Wire.endTransmission(); #else PCA9632_WriteRegister(addr, regadd + (PCA9632_RED >> 1), vr); PCA9632_WriteRegister(addr, regadd + (PCA9632_GRN >> 1), vg); PCA9632_WriteRegister(addr, regadd + (PCA9632_BLU >> 1), vb); #if ENABLED(PCA9632_RGBW) PCA9632_WriteRegister(addr, regadd + (PCA9632_WHT >> 1), vw); #endif #endif } #if 0 static byte PCA9632_ReadRegister(const byte addr, const byte regadd) { Wire.beginTransmission(I2C_ADDRESS(addr)); Wire.write(regadd); const byte value = Wire.read(); Wire.endTransmission(); return value; } #endif void PCA9632_set_led_color(const LEDColor &color) { Wire.begin(); if (!PCA_init) { PCA_init = 1; PCA9632_WriteRegister(PCA9632_ADDRESS,PCA9632_MODE1, PCA9632_MODE1_VALUE); PCA9632_WriteRegister(PCA9632_ADDRESS,PCA9632_MODE2, PCA9632_MODE2_VALUE); } const byte LEDOUT = (color.r ? LED_PWM << PCA9632_RED : 0) | (color.g ? LED_PWM << PCA9632_GRN : 0) | (color.b ? LED_PWM << PCA9632_BLU : 0) #if ENABLED(PCA9632_RGBW) | (color.w ? LED_PWM << PCA9632_WHT : 0) #endif ; PCA9632_WriteAllRegisters(PCA9632_ADDRESS,PCA9632_PWM0, color.r, color.g, color.b OPTARG(PCA9632_RGBW, color.w) ); PCA9632_WriteRegister(PCA9632_ADDRESS,PCA9632_LEDOUT, LEDOUT); } #if ENABLED(PCA9632_BUZZER) void PCA9632_buzz(const long, const uint16_t=0) { uint8_t data[] = PCA9632_BUZZER_DATA; Wire.beginTransmission(I2C_ADDRESS(PCA9632_ADDRESS)); Wire.write(data, sizeof(data)); Wire.endTransmission(); } #endif // PCA9632_BUZZER #endif // PCA9632
2301_81045437/Marlin
Marlin/src/feature/leds/pca9632.cpp
C++
agpl-3.0
4,891
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * Driver for the Philips PCA9632 LED driver. * Written by Robert Mendon Feb 2017. */ struct LEDColor; typedef LEDColor LEDColor; void PCA9632_set_led_color(const LEDColor &color); #if ENABLED(PCA9632_BUZZER) #include <stdint.h> void PCA9632_buzz(const long, const uint16_t=0); #endif
2301_81045437/Marlin
Marlin/src/feature/leds/pca9632.h
C
agpl-3.0
1,174
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * feature/leds/printer_event_leds.cpp - LED color changing based on printer status */ #include "../../inc/MarlinConfigPre.h" #if ENABLED(PRINTER_EVENT_LEDS) #include "printer_event_leds.h" PrinterEventLEDs printerEventLEDs; #if HAS_LEDS_OFF_FLAG bool PrinterEventLEDs::leds_off_after_print; // = false #endif #if HAS_TEMP_HOTEND || HAS_HEATED_BED uint8_t PrinterEventLEDs::old_intensity = 0; inline uint8_t pel_intensity(const celsius_t start, const celsius_t current, const celsius_t target) { if (start == target) return 255; return (uint8_t)map(constrain(current, start, target), start, target, 0, 255); } inline void pel_set_rgb(const uint8_t r, const uint8_t g, const uint8_t b OPTARG(HAS_WHITE_LED, const uint8_t w=0)) { leds.set_color( LEDColor(r, g, b OPTARG(HAS_WHITE_LED, w) OPTARG(NEOPIXEL_LED, neo.brightness())) OPTARG(NEOPIXEL_IS_SEQUENTIAL, true) ); } #endif #if HAS_TEMP_HOTEND void PrinterEventLEDs::onHotendHeating(const celsius_t start, const celsius_t current, const celsius_t target) { const uint8_t blue = pel_intensity(start, current, target); if (blue != old_intensity) { old_intensity = blue; pel_set_rgb(255, 0, 255 - blue); } } #endif #if HAS_HEATED_BED void PrinterEventLEDs::onBedHeating(const celsius_t start, const celsius_t current, const celsius_t target) { const uint8_t red = pel_intensity(start, current, target); if (red != old_intensity) { old_intensity = red; pel_set_rgb(red, 0, 255); } } #endif #if HAS_HEATED_CHAMBER void PrinterEventLEDs::onChamberHeating(const celsius_t start, const celsius_t current, const celsius_t target) { const uint8_t green = pel_intensity(start, current, target); if (green != old_intensity) { old_intensity = green; pel_set_rgb(255, green, 255); } } #endif #endif // PRINTER_EVENT_LEDS
2301_81045437/Marlin
Marlin/src/feature/leds/printer_event_leds.cpp
C++
agpl-3.0
2,770
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * feature/leds/printer_event_leds.h - LED color changing based on printer status */ #include "leds.h" #include "../../inc/MarlinConfig.h" class PrinterEventLEDs { private: static uint8_t old_intensity; #if HAS_LEDS_OFF_FLAG static bool leds_off_after_print; #endif static void set_done() { TERN(LED_COLOR_PRESETS, leds.set_default(), leds.set_off()); } public: #if HAS_TEMP_HOTEND static LEDColor onHotendHeatingStart() { old_intensity = 0; return leds.get_color(); } static void onHotendHeating(const celsius_t start, const celsius_t current, const celsius_t target); #endif #if HAS_HEATED_BED static LEDColor onBedHeatingStart() { old_intensity = 127; return leds.get_color(); } static void onBedHeating(const celsius_t start, const celsius_t current, const celsius_t target); #endif #if HAS_HEATED_CHAMBER static LEDColor onChamberHeatingStart() { old_intensity = 127; return leds.get_color(); } static void onChamberHeating(const celsius_t start, const celsius_t current, const celsius_t target); #endif #if HAS_TEMP_HOTEND || HAS_HEATED_BED || HAS_HEATED_CHAMBER static void onHeatingDone() { leds.set_white(); } static void onPIDTuningDone(LEDColor c) { leds.set_color(c); } #endif #if HAS_MEDIA static void onPrintCompleted() { leds.set_green(); #if HAS_LEDS_OFF_FLAG leds_off_after_print = true; #else safe_delay(2000); set_done(); #endif } static void onResumeAfterWait() { #if HAS_LEDS_OFF_FLAG if (leds_off_after_print) { set_done(); leds_off_after_print = false; } #endif } #endif // HAS_MEDIA }; extern PrinterEventLEDs printerEventLEDs;
2301_81045437/Marlin
Marlin/src/feature/leds/printer_event_leds.h
C++
agpl-3.0
2,634
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * Marlin RGB LED general support */ #include "../../inc/MarlinConfig.h" #if ENABLED(TEMP_STAT_LEDS) #include "tempstat.h" #include "../../module/temperature.h" void handle_status_leds() { static int8_t old_red = -1; // Invalid value to force LED initialization static millis_t next_status_led_update_ms = 0; if (ELAPSED(millis(), next_status_led_update_ms)) { next_status_led_update_ms += 500; // Update every 0.5s celsius_t max_temp = TERN0(HAS_HEATED_BED, _MAX(thermalManager.degTargetBed(), thermalManager.wholeDegBed())); HOTEND_LOOP() max_temp = _MAX(max_temp, thermalManager.wholeDegHotend(e), thermalManager.degTargetHotend(e)); const int8_t new_red = (max_temp > 55) ? HIGH : (max_temp < 54 || old_red < 0) ? LOW : old_red; if (new_red != old_red) { old_red = new_red; #if PIN_EXISTS(STAT_LED_RED) WRITE(STAT_LED_RED_PIN, new_red); #endif #if PIN_EXISTS(STAT_LED_BLUE) WRITE(STAT_LED_BLUE_PIN, !new_red); #endif } } } #endif // TEMP_STAT_LEDS
2301_81045437/Marlin
Marlin/src/feature/leds/tempstat.cpp
C++
agpl-3.0
1,910
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * Marlin general RGB LED support */ void handle_status_leds();
2301_81045437/Marlin
Marlin/src/feature/leds/tempstat.h
C
agpl-3.0
946
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * This module is off by default, but can be enabled to facilitate the display of * extra debug information during code development. * * Just connect up 5V and GND to give it power, then connect up the pins assigned * in Configuration_adv.h. For example, on the Re-ARM you could use: * * #define MAX7219_CLK_PIN 77 * #define MAX7219_DIN_PIN 78 * #define MAX7219_LOAD_PIN 79 * * send() is called automatically at startup, and then there are a number of * support functions available to control the LEDs in the 8x8 grid. */ #include "../inc/MarlinConfigPre.h" #if ENABLED(MAX7219_DEBUG) #define MAX7219_ERRORS // Requires ~400 bytes of flash #include "max7219.h" #include "../module/planner.h" #include "../module/stepper.h" #include "../MarlinCore.h" #include "../HAL/shared/Delay.h" #if ENABLED(MAX7219_SIDE_BY_SIDE) && MAX7219_NUMBER_UNITS > 1 #define HAS_SIDE_BY_SIDE 1 #endif #define _ROT ((MAX7219_ROTATE + 360) % 360) #if _ROT == 0 || _ROT == 180 #define MAX7219_X_LEDS TERN(HAS_SIDE_BY_SIDE, 8, MAX7219_LINES) #define MAX7219_Y_LEDS TERN(HAS_SIDE_BY_SIDE, MAX7219_LINES, 8) #elif _ROT == 90 || _ROT == 270 #define MAX7219_X_LEDS TERN(HAS_SIDE_BY_SIDE, MAX7219_LINES, 8) #define MAX7219_Y_LEDS TERN(HAS_SIDE_BY_SIDE, 8, MAX7219_LINES) #else #error "MAX7219_ROTATE must be a multiple of +/- 90°." #endif #ifdef MAX7219_DEBUG_PROFILE CodeProfiler::Mode CodeProfiler::mode = ACCUMULATE_AVERAGE; uint8_t CodeProfiler::instance_count = 0; uint32_t CodeProfiler::last_calc_time = micros(); uint8_t CodeProfiler::time_fraction = 0; uint32_t CodeProfiler::total_time = 0; uint16_t CodeProfiler::call_count = 0; #endif #if defined(MAX7219_DEBUG_PLANNER_HEAD) && defined(MAX7219_DEBUG_PLANNER_TAIL) && MAX7219_DEBUG_PLANNER_HEAD == MAX7219_DEBUG_PLANNER_TAIL static int16_t last_head_cnt = 0xF, last_tail_cnt = 0xF; #else #ifdef MAX7219_DEBUG_PLANNER_HEAD static int16_t last_head_cnt = 0x1; #endif #ifdef MAX7219_DEBUG_PLANNER_TAIL static int16_t last_tail_cnt = 0x1; #endif #endif #ifdef MAX7219_DEBUG_PLANNER_QUEUE static int16_t last_depth = 0; #endif #ifdef MAX7219_DEBUG_PROFILE static uint8_t last_time_fraction = 0; #endif #ifdef MAX7219_DEBUG_MULTISTEPPING static uint8_t last_multistepping = 0; #endif Max7219 max7219; uint8_t Max7219::led_line[MAX7219_LINES]; // = { 0 }; uint8_t Max7219::suspended; // = 0; #define LINE_REG(Q) (max7219_reg_digit0 + ((Q) & 0x7)) #if (_ROT == 0 || _ROT == 270) == DISABLED(MAX7219_REVERSE_EACH) #define _LED_BIT(Q) (7 - ((Q) & 0x7)) #else #define _LED_BIT(Q) ((Q) & 0x7) #endif #if _ROT == 0 || _ROT == 180 #define LED_BIT(X,Y) _LED_BIT(X) #else #define LED_BIT(X,Y) _LED_BIT(Y) #endif #if _ROT == 0 || _ROT == 90 #define _LED_IND(P,Q) (_LED_TOP(P) + ((Q) & 0x7)) #else #define _LED_IND(P,Q) (_LED_TOP(P) + (7 - ((Q) & 0x7))) #endif #if HAS_SIDE_BY_SIDE #if (_ROT == 0 || _ROT == 90) == DISABLED(MAX7219_REVERSE_ORDER) #define _LED_TOP(Q) ((MAX7219_NUMBER_UNITS - 1 - ((Q) >> 3)) << 3) #else #define _LED_TOP(Q) ((Q) & ~0x7) #endif #if _ROT == 0 || _ROT == 180 #define LED_IND(X,Y) _LED_IND(Y,Y) #elif _ROT == 90 || _ROT == 270 #define LED_IND(X,Y) _LED_IND(X,X) #endif #else #if (_ROT == 0 || _ROT == 270) == DISABLED(MAX7219_REVERSE_ORDER) #define _LED_TOP(Q) ((Q) & ~0x7) #else #define _LED_TOP(Q) ((MAX7219_NUMBER_UNITS - 1 - ((Q) >> 3)) << 3) #endif #if _ROT == 0 || _ROT == 180 #define LED_IND(X,Y) _LED_IND(X,Y) #elif _ROT == 90 || _ROT == 270 #define LED_IND(X,Y) _LED_IND(Y,X) #endif #endif #define XOR_7219(X,Y) do{ led_line[LED_IND(X,Y)] ^= _BV(LED_BIT(X,Y)); }while(0) #define SET_7219(X,Y) do{ led_line[LED_IND(X,Y)] |= _BV(LED_BIT(X,Y)); }while(0) #define CLR_7219(X,Y) do{ led_line[LED_IND(X,Y)] &= ~_BV(LED_BIT(X,Y)); }while(0) #define BIT_7219(X,Y) TEST(led_line[LED_IND(X,Y)], LED_BIT(X,Y)) #ifdef CPU_32_BIT #define SIG_DELAY() DELAY_US(1) // Approximate a 1µs delay on 32-bit ARM #undef CRITICAL_SECTION_START #undef CRITICAL_SECTION_END #define CRITICAL_SECTION_START() NOOP #define CRITICAL_SECTION_END() NOOP #else #define SIG_DELAY() DELAY_NS(250) #endif void Max7219::error(FSTR_P const func, const int32_t v1, const int32_t v2/*=-1*/) { #if ENABLED(MAX7219_ERRORS) SERIAL_ECHO(F("??? Max7219::"), func, C('('), v1); if (v2 > 0) SERIAL_ECHOPGM(", ", v2); SERIAL_CHAR(')'); SERIAL_EOL(); #else UNUSED(func); UNUSED(v1); UNUSED(v2); #endif } /** * Flip the lowest n_bytes of the supplied bits: * flipped(x, 1) flips the low 8 bits of x. * flipped(x, 2) flips the low 16 bits of x. * flipped(x, 3) flips the low 24 bits of x. * flipped(x, 4) flips the low 32 bits of x. */ inline uint32_t flipped(const uint32_t bits, const uint8_t n_bytes) { uint32_t mask = 1, outbits = 0; for (uint8_t b = 0; b < n_bytes * 8; ++b) { outbits <<= 1; if (bits & mask) outbits |= 1; mask <<= 1; } return outbits; } void Max7219::noop() { CRITICAL_SECTION_START(); SIG_DELAY(); WRITE(MAX7219_DIN_PIN, LOW); for (uint8_t i = 16; i--;) { SIG_DELAY(); WRITE(MAX7219_CLK_PIN, LOW); SIG_DELAY(); SIG_DELAY(); WRITE(MAX7219_CLK_PIN, HIGH); SIG_DELAY(); } CRITICAL_SECTION_END(); } void Max7219::putbyte(uint8_t data) { CRITICAL_SECTION_START(); for (uint8_t i = 8; i--;) { SIG_DELAY(); WRITE(MAX7219_CLK_PIN, LOW); // tick SIG_DELAY(); WRITE(MAX7219_DIN_PIN, (data & 0x80) ? HIGH : LOW); // send 1 or 0 based on data bit SIG_DELAY(); WRITE(MAX7219_CLK_PIN, HIGH); // tock SIG_DELAY(); data <<= 1; } CRITICAL_SECTION_END(); } void Max7219::pulse_load() { SIG_DELAY(); WRITE(MAX7219_LOAD_PIN, LOW); // tell the chip to load the data SIG_DELAY(); WRITE(MAX7219_LOAD_PIN, HIGH); SIG_DELAY(); } void Max7219::send(const uint8_t reg, const uint8_t data) { SIG_DELAY(); CRITICAL_SECTION_START(); SIG_DELAY(); putbyte(reg); // specify register SIG_DELAY(); putbyte(data); // put data CRITICAL_SECTION_END(); } // Send out a single native row of bits to just one unit void Max7219::refresh_unit_line(const uint8_t line) { if (suspended) return; #if MAX7219_NUMBER_UNITS == 1 send(LINE_REG(line), led_line[line]); #else for (uint8_t u = MAX7219_NUMBER_UNITS; u--;) if (u == (line >> 3)) send(LINE_REG(line), led_line[line]); else noop(); #endif pulse_load(); } // Send out a single native row of bits to all units void Max7219::refresh_line(const uint8_t line) { if (suspended) return; #if MAX7219_NUMBER_UNITS == 1 refresh_unit_line(line); #else for (uint8_t u = MAX7219_NUMBER_UNITS; u--;) send(LINE_REG(line), led_line[(u << 3) | (line & 0x7)]); #endif pulse_load(); } void Max7219::set(const uint8_t line, const uint8_t bits) { led_line[line] = bits; refresh_unit_line(line); } #if ENABLED(MAX7219_NUMERIC) // Draw an integer with optional leading zeros and optional decimal point void Max7219::print(const uint8_t start, int16_t value, uint8_t size, const bool leadzero=false, bool dec=false) { if (suspended) return; constexpr uint8_t led_numeral[10] = { 0x7E, 0x60, 0x6D, 0x79, 0x63, 0x5B, 0x5F, 0x70, 0x7F, 0x7A }, led_decimal = 0x80, led_minus = 0x01; bool blank = false, neg = value < 0; if (neg) value *= -1; while (size--) { const bool minus = neg && blank; if (minus) neg = false; send( max7219_reg_digit0 + start + size, minus ? led_minus : blank ? 0x00 : led_numeral[value % 10] | (dec ? led_decimal : 0x00) ); pulse_load(); // tell the chips to load the clocked out data value /= 10; if (!value && !leadzero) blank = true; dec = false; } } // Draw a float with a decimal point and optional digits void Max7219::print(const uint8_t start, const_float_t value, const uint8_t pre_size, const uint8_t post_size, const bool leadzero=false) { if (pre_size) print(start, value, pre_size, leadzero, !!post_size); if (post_size) { const int16_t after = ABS(value) * (10 ^ post_size); print(start + pre_size, after, post_size, true); } } #endif // MAX7219_NUMERIC // Modify a single LED bit and send the changed line void Max7219::led_set(const uint8_t x, const uint8_t y, const bool on, uint8_t * const rcm/*=nullptr*/) { if (x >= MAX7219_X_LEDS || y >= MAX7219_Y_LEDS) return error(F("led_set"), x, y); if (BIT_7219(x, y) == on) return; XOR_7219(x, y); refresh_unit_line(LED_IND(x, y)); if (rcm != nullptr) *rcm |= _BV(LED_IND(x, y) & 0x07); } void Max7219::led_on(const uint8_t x, const uint8_t y, uint8_t * const rcm/*=nullptr*/) { if (x >= MAX7219_X_LEDS || y >= MAX7219_Y_LEDS) return error(F("led_on"), x, y); led_set(x, y, true, rcm); } void Max7219::led_off(const uint8_t x, const uint8_t y, uint8_t * const rcm/*=nullptr*/) { if (x >= MAX7219_X_LEDS || y >= MAX7219_Y_LEDS) return error(F("led_off"), x, y); led_set(x, y, false, rcm); } void Max7219::led_toggle(const uint8_t x, const uint8_t y, uint8_t * const rcm/*=nullptr*/) { if (x >= MAX7219_X_LEDS || y >= MAX7219_Y_LEDS) return error(F("led_toggle"), x, y); led_set(x, y, !BIT_7219(x, y), rcm); } void Max7219::send_row(const uint8_t row) { if (suspended) return; #if _ROT == 0 || _ROT == 180 // Native Lines are horizontal too #if MAX7219_X_LEDS <= 8 refresh_unit_line(LED_IND(0, row)); // A single unit line #else refresh_line(LED_IND(0, row)); // Same line, all units #endif #else // Native lines are vertical UNUSED(row); refresh(); // Actually a column #endif } void Max7219::send_column(const uint8_t col) { if (suspended) return; #if _ROT == 90 || _ROT == 270 // Native Lines are vertical too #if MAX7219_Y_LEDS <= 8 refresh_unit_line(LED_IND(col, 0)); // A single unit line #else refresh_line(LED_IND(col, 0)); // Same line, all units #endif #else // Native lines are horizontal UNUSED(col); refresh(); // Actually a row #endif } void Max7219::clear() { ZERO(led_line); refresh(); } void Max7219::fill() { memset(led_line, 0xFF, sizeof(led_line)); refresh(); } void Max7219::clear_row(const uint8_t row) { if (row >= MAX7219_Y_LEDS) return error(F("clear_row"), row); for (uint8_t x = 0; x < MAX7219_X_LEDS; ++x) CLR_7219(x, row); send_row(row); } void Max7219::clear_column(const uint8_t col) { if (col >= MAX7219_X_LEDS) return error(F("set_column"), col); for (uint8_t y = 0; y < MAX7219_Y_LEDS; ++y) CLR_7219(col, y); send_column(col); } /** * Plot the low order bits of val to the specified row of the matrix. * With 4 Max7219 units in the chain, it's possible to set 32 bits at * once with a single call to the function (if rotated 90° or 270°). */ void Max7219::set_row(const uint8_t row, const uint32_t val) { if (row >= MAX7219_Y_LEDS) return error(F("set_row"), row); uint32_t mask = _BV32(MAX7219_X_LEDS - 1); for (uint8_t x = 0; x < MAX7219_X_LEDS; ++x) { if (val & mask) SET_7219(x, row); else CLR_7219(x, row); mask >>= 1; } send_row(row); } /** * Plot the low order bits of val to the specified column of the matrix. * With 4 Max7219 units in the chain, it's possible to set 32 bits at * once with a single call to the function (if rotated 0° or 180°). */ void Max7219::set_column(const uint8_t col, const uint32_t val) { if (col >= MAX7219_X_LEDS) return error(F("set_column"), col); uint32_t mask = _BV32(MAX7219_Y_LEDS - 1); for (uint8_t y = 0; y < MAX7219_Y_LEDS; ++y) { if (val & mask) SET_7219(col, y); else CLR_7219(col, y); mask >>= 1; } send_column(col); } void Max7219::set_rows_16bits(const uint8_t y, uint32_t val) { #if MAX7219_X_LEDS == 8 if (y > MAX7219_Y_LEDS - 2) return error(F("set_rows_16bits"), y, val); set_row(y + 1, val); val >>= 8; set_row(y + 0, val); #else // at least 16 bits on each row if (y > MAX7219_Y_LEDS - 1) return error(F("set_rows_16bits"), y, val); set_row(y, val); #endif } void Max7219::set_rows_32bits(const uint8_t y, uint32_t val) { #if MAX7219_X_LEDS == 8 if (y > MAX7219_Y_LEDS - 4) return error(F("set_rows_32bits"), y, val); set_row(y + 3, val); val >>= 8; set_row(y + 2, val); val >>= 8; set_row(y + 1, val); val >>= 8; set_row(y + 0, val); #elif MAX7219_X_LEDS == 16 if (y > MAX7219_Y_LEDS - 2) return error(F("set_rows_32bits"), y, val); set_row(y + 1, val); val >>= 16; set_row(y + 0, val); #else // at least 24 bits on each row. In the 3 matrix case, just display the low 24 bits if (y > MAX7219_Y_LEDS - 1) return error(F("set_rows_32bits"), y, val); set_row(y, val); #endif } void Max7219::set_columns_16bits(const uint8_t x, uint32_t val) { #if MAX7219_Y_LEDS == 8 if (x > MAX7219_X_LEDS - 2) return error(F("set_columns_16bits"), x, val); set_column(x + 0, val); val >>= 8; set_column(x + 1, val); #else // at least 16 bits in each column if (x > MAX7219_X_LEDS - 1) return error(F("set_columns_16bits"), x, val); set_column(x, val); #endif } void Max7219::set_columns_32bits(const uint8_t x, uint32_t val) { #if MAX7219_Y_LEDS == 8 if (x > MAX7219_X_LEDS - 4) return error(F("set_rows_32bits"), x, val); set_column(x + 3, val); val >>= 8; set_column(x + 2, val); val >>= 8; set_column(x + 1, val); val >>= 8; set_column(x + 0, val); #elif MAX7219_Y_LEDS == 16 if (x > MAX7219_X_LEDS - 2) return error(F("set_rows_32bits"), x, val); set_column(x + 1, val); val >>= 16; set_column(x + 0, val); #else // at least 24 bits on each row. In the 3 matrix case, just display the low 24 bits if (x > MAX7219_X_LEDS - 1) return error(F("set_rows_32bits"), x, val); set_column(x, val); #endif } // Initialize the Max7219 void Max7219::register_setup() { for (uint8_t i = 0; i < MAX7219_NUMBER_UNITS; ++i) send(max7219_reg_scanLimit, 0x07); pulse_load(); // Tell the chips to load the clocked out data for (uint8_t i = 0; i < MAX7219_NUMBER_UNITS; ++i) send(max7219_reg_decodeMode, 0x00); // Using an led matrix (not digits) pulse_load(); // Tell the chips to load the clocked out data for (uint8_t i = 0; i < MAX7219_NUMBER_UNITS; ++i) send(max7219_reg_shutdown, 0x01); // Not in shutdown mode pulse_load(); // Tell the chips to load the clocked out data for (uint8_t i = 0; i < MAX7219_NUMBER_UNITS; ++i) send(max7219_reg_displayTest, 0x00); // No display test pulse_load(); // Tell the chips to load the clocked out data for (uint8_t i = 0; i < MAX7219_NUMBER_UNITS; ++i) send(max7219_reg_intensity, 0x01 & 0x0F); // The first 0x0F is the value you can set // Range: 0x00 to 0x0F pulse_load(); // Tell the chips to load the clocked out data } #if MAX7219_INIT_TEST uint8_t test_mode = 0; millis_t next_patt_ms; bool patt_on; #if MAX7219_INIT_TEST == 2 #define MAX7219_LEDS (MAX7219_X_LEDS * MAX7219_Y_LEDS) constexpr millis_t pattern_delay = 4; int8_t spiralx, spiraly, spiral_dir; uvalue_t(MAX7219_LEDS) spiral_count; void Max7219::test_pattern() { constexpr int8_t way[][2] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; led_set(spiralx, spiraly, patt_on); const int8_t x = spiralx + way[spiral_dir][0], y = spiraly + way[spiral_dir][1]; if (!WITHIN(x, 0, MAX7219_X_LEDS - 1) || !WITHIN(y, 0, MAX7219_Y_LEDS - 1) || BIT_7219(x, y) == patt_on) spiral_dir = (spiral_dir + 1) & 0x3; spiralx += way[spiral_dir][0]; spiraly += way[spiral_dir][1]; if (!spiral_count--) { if (!patt_on) test_mode = 0; else { spiral_count = MAX7219_LEDS; spiralx = spiraly = spiral_dir = 0; patt_on = false; } } } #else constexpr millis_t pattern_delay = 20; int8_t sweep_count, sweepx, sweep_dir; void Max7219::test_pattern() { set_column(sweepx, patt_on ? 0xFFFFFFFF : 0x00000000); sweepx += sweep_dir; if (!WITHIN(sweepx, 0, MAX7219_X_LEDS - 1)) { if (!patt_on) { sweep_dir *= -1; sweepx += sweep_dir; } else sweepx -= MAX7219_X_LEDS * sweep_dir; patt_on ^= true; next_patt_ms += 100; if (++test_mode > 4) test_mode = 0; } } #endif void Max7219::run_test_pattern() { const millis_t ms = millis(); if (PENDING(ms, next_patt_ms)) return; next_patt_ms = ms + pattern_delay; test_pattern(); } void Max7219::start_test_pattern() { clear(); test_mode = 1; patt_on = true; #if MAX7219_INIT_TEST == 2 spiralx = spiraly = spiral_dir = 0; spiral_count = MAX7219_LEDS; #else sweep_dir = 1; sweepx = 0; sweep_count = MAX7219_X_LEDS; #endif } #endif // MAX7219_INIT_TEST void Max7219::init() { SET_OUTPUT(MAX7219_DIN_PIN); SET_OUTPUT(MAX7219_CLK_PIN); OUT_WRITE(MAX7219_LOAD_PIN, HIGH); delay(1); register_setup(); clear(); #if MAX7219_INIT_TEST start_test_pattern(); #endif #ifdef MAX7219_REINIT_ON_POWERUP #if defined(MAX7219_DEBUG_PLANNER_HEAD) && defined(MAX7219_DEBUG_PLANNER_TAIL) && MAX7219_DEBUG_PLANNER_HEAD == MAX7219_DEBUG_PLANNER_TAIL last_head_cnt = 0xF; last_tail_cnt = 0xF; #else #ifdef MAX7219_DEBUG_PLANNER_HEAD last_head_cnt = 0x1; #endif #ifdef MAX7219_DEBUG_PLANNER_TAIL last_tail_cnt = 0x1; #endif #endif #ifdef MAX7219_DEBUG_PLANNER_QUEUE last_depth = 0; #endif #ifdef MAX7219_DEBUG_PROFILE last_time_fraction = 0; #endif #ifdef MAX7219_DEBUG_MULTISTEPPING last_multistepping = 0; #endif #endif } /** * This code demonstrates some simple debugging using a single 8x8 LED Matrix. If your feature could * benefit from matrix display, add its code here. Very little processing is required, so the 7219 is * ideal for debugging when realtime feedback is important but serial output can't be used. */ // Apply changes to update a marker void Max7219::mark16(const uint8_t pos, const uint8_t v1, const uint8_t v2, uint8_t * const rcm/*=nullptr*/) { #if MAX7219_X_LEDS > 8 // At least 16 LEDs on the X-Axis. Use single line. led_off(v1 & 0xF, pos, rcm); led_on(v2 & 0xF, pos, rcm); #elif MAX7219_Y_LEDS > 8 // At least 16 LEDs on the Y-Axis. Use a single column. led_off(pos, v1 & 0xF, rcm); led_on(pos, v2 & 0xF, rcm); #else // Single 8x8 LED matrix. Use two lines to get 16 LEDs. led_off(v1 & 0x7, pos + (v1 >= 8), rcm); led_on(v2 & 0x7, pos + (v2 >= 8), rcm); #endif } // Apply changes to update a tail-to-head range void Max7219::range16(const uint8_t y, const uint8_t ot, const uint8_t nt, const uint8_t oh, const uint8_t nh, uint8_t * const rcm/*=nullptr*/) { #if MAX7219_X_LEDS > 8 // At least 16 LEDs on the X-Axis. Use single line. if (ot != nt) for (uint8_t n = ot & 0xF; n != (nt & 0xF) && n != (nh & 0xF); n = (n + 1) & 0xF) led_off(n & 0xF, y, rcm); if (oh != nh) for (uint8_t n = (oh + 1) & 0xF; n != ((nh + 1) & 0xF); n = (n + 1) & 0xF) led_on(n & 0xF, y, rcm); #elif MAX7219_Y_LEDS > 8 // At least 16 LEDs on the Y-Axis. Use a single column. if (ot != nt) for (uint8_t n = ot & 0xF; n != (nt & 0xF) && n != (nh & 0xF); n = (n + 1) & 0xF) led_off(y, n & 0xF, rcm); if (oh != nh) for (uint8_t n = (oh + 1) & 0xF; n != ((nh + 1) & 0xF); n = (n + 1) & 0xF) led_on(y, n & 0xF, rcm); #else // Single 8x8 LED matrix. Use two lines to get 16 LEDs. if (ot != nt) for (uint8_t n = ot & 0xF; n != (nt & 0xF) && n != (nh & 0xF); n = (n + 1) & 0xF) led_off(n & 0x7, y + (n >= 8), rcm); if (oh != nh) for (uint8_t n = (oh + 1) & 0xF; n != ((nh + 1) & 0xF); n = (n + 1) & 0xF) led_on(n & 0x7, y + (n >= 8), rcm); #endif } // Apply changes to update a quantity void Max7219::quantity(const uint8_t pos, const uint8_t ov, const uint8_t nv, uint8_t * const rcm/*=nullptr*/) { for (uint8_t i = _MIN(nv, ov); i < _MAX(nv, ov); i++) led_set( #if MAX7219_X_LEDS >= MAX7219_Y_LEDS i, pos // Single matrix or multiple matrices in Landscape #else pos, i // Multiple matrices in Portrait #endif , nv >= ov , rcm ); } void Max7219::quantity16(const uint8_t pos, const uint8_t ov, const uint8_t nv, uint8_t * const rcm/*=nullptr*/) { for (uint8_t i = _MIN(nv, ov); i < _MAX(nv, ov); i++) led_set( #if MAX7219_X_LEDS > 8 // At least 16 LEDs on the X-Axis. Use single line. i, pos #elif MAX7219_Y_LEDS > 8 // At least 16 LEDs on the Y-Axis. Use a single column. pos, i #else // Single 8x8 LED matrix. Use two lines to get 16 LEDs. i >> 1, pos + (i & 1) #endif , nv >= ov , rcm ); } void Max7219::idle_tasks() { #define MAX7219_USE_HEAD (defined(MAX7219_DEBUG_PLANNER_HEAD) || defined(MAX7219_DEBUG_PLANNER_QUEUE)) #define MAX7219_USE_TAIL (defined(MAX7219_DEBUG_PLANNER_TAIL) || defined(MAX7219_DEBUG_PLANNER_QUEUE)) #if MAX7219_USE_HEAD || MAX7219_USE_TAIL CRITICAL_SECTION_START(); #if MAX7219_USE_HEAD const uint8_t head = planner.block_buffer_head; #endif #if MAX7219_USE_TAIL const uint8_t tail = planner.block_buffer_tail; #endif CRITICAL_SECTION_END(); #endif #if ENABLED(MAX7219_DEBUG_PRINTER_ALIVE) static uint8_t refresh_cnt; // = 0 constexpr uint16_t refresh_limit = 5; static millis_t next_blink = 0; const millis_t ms = millis(); const bool do_blink = ELAPSED(ms, next_blink); #else static uint16_t refresh_cnt; // = 0 constexpr bool do_blink = true; constexpr uint16_t refresh_limit = 50000; #endif // Some Max7219 units are vulnerable to electrical noise, especially // with long wires next to high current wires. If the display becomes // corrupted, this will fix it within a couple seconds. if (do_blink && ++refresh_cnt >= refresh_limit) { refresh_cnt = 0; register_setup(); } #if MAX7219_INIT_TEST if (test_mode) { run_test_pattern(); return; } #endif // suspend updates and record which lines have changed for batching later suspended++; uint8_t row_change_mask = 0x00; #if ENABLED(MAX7219_DEBUG_PRINTER_ALIVE) if (do_blink) { led_toggle(MAX7219_X_LEDS - 1, MAX7219_Y_LEDS - 1, &row_change_mask); next_blink = ms + 1000; } #endif #if defined(MAX7219_DEBUG_PLANNER_HEAD) && defined(MAX7219_DEBUG_PLANNER_TAIL) && MAX7219_DEBUG_PLANNER_HEAD == MAX7219_DEBUG_PLANNER_TAIL if (last_head_cnt != head || last_tail_cnt != tail) { range16(MAX7219_DEBUG_PLANNER_HEAD, last_tail_cnt, tail, last_head_cnt, head, &row_change_mask); last_head_cnt = head; last_tail_cnt = tail; } #else #ifdef MAX7219_DEBUG_PLANNER_HEAD if (last_head_cnt != head) { mark16(MAX7219_DEBUG_PLANNER_HEAD, last_head_cnt, head, &row_change_mask); last_head_cnt = head; } #endif #ifdef MAX7219_DEBUG_PLANNER_TAIL if (last_tail_cnt != tail) { mark16(MAX7219_DEBUG_PLANNER_TAIL, last_tail_cnt, tail, &row_change_mask); last_tail_cnt = tail; } #endif #endif #ifdef MAX7219_DEBUG_PLANNER_QUEUE static int16_t last_depth = 0; const int16_t current_depth = BLOCK_MOD(head - tail + (BLOCK_BUFFER_SIZE)) & 0xF; if (current_depth != last_depth) { quantity16(MAX7219_DEBUG_PLANNER_QUEUE, last_depth, current_depth, &row_change_mask); last_depth = current_depth; } #endif #ifdef MAX7219_DEBUG_PROFILE const uint8_t current_time_fraction = (uint16_t(CodeProfiler::get_time_fraction()) * MAX7219_NUMBER_UNITS + 8) / 16; if (current_time_fraction != last_time_fraction) { quantity(MAX7219_DEBUG_PROFILE, last_time_fraction, current_time_fraction, &row_change_mask); last_time_fraction = current_time_fraction; } #endif #ifdef MAX7219_DEBUG_MULTISTEPPING static uint8_t last_multistepping = 0; const uint8_t multistepping = Stepper::steps_per_isr; if (multistepping != last_multistepping) { static uint8_t log2_old = 0; uint8_t log2_new = 0; for (uint8_t val = multistepping; val > 1; val >>= 1) log2_new++; mark16(MAX7219_DEBUG_MULTISTEPPING, log2_old, log2_new, &row_change_mask); last_multistepping = multistepping; log2_old = log2_new; } #endif #ifdef MAX7219_DEBUG_SLOWDOWN static uint8_t last_slowdown_count = 0; const uint8_t slowdown_count = Planner::slowdown_count; if (slowdown_count != last_slowdown_count) { mark16(MAX7219_DEBUG_SLOWDOWN, last_slowdown_count, slowdown_count, &row_change_mask); last_slowdown_count = slowdown_count; } #endif // batch line updates suspended--; if (!suspended) for (uint8_t i = 0; i < 8; ++i) if (row_change_mask & _BV(i)) refresh_line(i); // After resume() automatically do a refresh() if (suspended == 0x80) { suspended = 0; refresh(); } } #endif // MAX7219_DEBUG
2301_81045437/Marlin
Marlin/src/feature/max7219.cpp
C++
agpl-3.0
26,498
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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 /** * This module is off by default, but can be enabled to facilitate the display of * extra debug information during code development. * * Just connect up 5V and GND to give it power, then connect up the pins assigned * in Configuration_adv.h. For example, on the Re-ARM you could use: * * #define MAX7219_CLK_PIN 77 * #define MAX7219_DIN_PIN 78 * #define MAX7219_LOAD_PIN 79 * * max7219.init() is called automatically at startup, and then there are a number of * support functions available to control the LEDs in the 8x8 grid. * * If you are using the Max7219 matrix for firmware debug purposes in time sensitive * areas of the code, please be aware that the orientation (rotation) of the display can * affect the speed. The Max7219 can update a single column fairly fast. It is much * faster to do a Max7219_Set_Column() with a rotation of 90 or 270 degrees than to do * a Max7219_Set_Row(). The opposite is true for rotations of 0 or 180 degrees. */ #include "../inc/MarlinConfig.h" #ifndef MAX7219_ROTATE #define MAX7219_ROTATE 0 #endif #ifndef MAX7219_NUMBER_UNITS #define MAX7219_NUMBER_UNITS 1 #endif #define MAX7219_LINES (8 * (MAX7219_NUMBER_UNITS)) // // MAX7219 registers // #define max7219_reg_noop 0x00 #define max7219_reg_digit0 0x01 #define max7219_reg_digit1 0x02 #define max7219_reg_digit2 0x03 #define max7219_reg_digit3 0x04 #define max7219_reg_digit4 0x05 #define max7219_reg_digit5 0x06 #define max7219_reg_digit6 0x07 #define max7219_reg_digit7 0x08 #define max7219_reg_decodeMode 0x09 #define max7219_reg_intensity 0x0A #define max7219_reg_scanLimit 0x0B #define max7219_reg_shutdown 0x0C #define max7219_reg_displayTest 0x0F #ifdef MAX7219_DEBUG_PROFILE // This class sums up the amount of time for which its instances exist. // By default there is one instantiated for the duration of the idle() // function. But an instance can be created in any code block to measure // the time spent from the point of instantiation until the CPU leaves // block. Be careful about having multiple instances of CodeProfiler as // it does not guard against double counting. In general mixing ISR and // non-ISR use will require critical sections but note that mode setting // is atomic so the total or average times can safely be read if you set // mode to FREEZE first. class CodeProfiler { public: enum Mode : uint8_t { ACCUMULATE_AVERAGE, ACCUMULATE_TOTAL, FREEZE }; private: static Mode mode; static uint8_t instance_count; static uint32_t last_calc_time; static uint32_t total_time; static uint8_t time_fraction; static uint16_t call_count; uint32_t start_time; public: CodeProfiler() : start_time(micros()) { instance_count++; } ~CodeProfiler() { instance_count--; if (mode == FREEZE) return; call_count++; const uint32_t now = micros(); total_time += now - start_time; if (mode == ACCUMULATE_TOTAL) return; // update time_fraction every hundred milliseconds if (instance_count == 0 && ELAPSED(now, last_calc_time + 100000)) { time_fraction = total_time * 128 / (now - last_calc_time); last_calc_time = now; total_time = 0; } } static void set_mode(Mode _mode) { mode = _mode; } static void reset() { time_fraction = 0; last_calc_time = micros(); total_time = 0; call_count = 0; } // returns fraction of total time which was measured, scaled from 0 to 128 static uint8_t get_time_fraction() { return time_fraction; } // returns total time in microseconds static uint32_t get_total_time() { return total_time; } static uint16_t get_call_count() { return call_count; } }; #endif class Max7219 { public: static uint8_t led_line[MAX7219_LINES]; Max7219() {} static void init(); static void register_setup(); static void putbyte(uint8_t data); static void pulse_load(); // Set a single register (e.g., a whole native row) static void send(const uint8_t reg, const uint8_t data); // Refresh all units static void refresh() { for (uint8_t i = 0; i < 8; i++) refresh_line(i); } // Suspend / resume updates to the LED unit // Use these methods to speed up multiple changes // or to apply updates from interrupt context. static void suspend() { suspended++; } static void resume() { suspended--; suspended |= 0x80; } // Update a single native line on all units static void refresh_line(const uint8_t line); // Update a single native line on just one unit static void refresh_unit_line(const uint8_t line); #if ENABLED(MAX7219_NUMERIC) // Draw an integer with optional leading zeros and optional decimal point void print(const uint8_t start, int16_t value, uint8_t size, const bool leadzero=false, bool dec=false); // Draw a float with a decimal point and optional digits void print(const uint8_t start, const_float_t value, const uint8_t pre_size, const uint8_t post_size, const bool leadzero=false); #endif // Set a single LED by XY coordinate static void led_set(const uint8_t x, const uint8_t y, const bool on, uint8_t * const rcm=nullptr); static void led_on(const uint8_t x, const uint8_t y, uint8_t * const rcm=nullptr); static void led_off(const uint8_t x, const uint8_t y, uint8_t * const rcm=nullptr); static void led_toggle(const uint8_t x, const uint8_t y, uint8_t * const rcm=nullptr); // Set all LEDs in a single column static void set_column(const uint8_t col, const uint32_t val); static void clear_column(const uint8_t col); // Set all LEDs in a single row static void set_row(const uint8_t row, const uint32_t val); static void clear_row(const uint8_t row); // 16 and 32 bit versions of Row and Column functions // Multiple rows and columns will be used to display the value if // the array of matrix LED's is too narrow to accomplish the goal static void set_rows_16bits(const uint8_t y, uint32_t val); static void set_rows_32bits(const uint8_t y, uint32_t val); static void set_columns_16bits(const uint8_t x, uint32_t val); static void set_columns_32bits(const uint8_t x, uint32_t val); // Quickly clear the whole matrix static void clear(); // Quickly fill the whole matrix static void fill(); // Apply custom code to update the matrix static void idle_tasks(); private: static uint8_t suspended; static void error(FSTR_P const func, const int32_t v1, const int32_t v2=-1); static void noop(); static void set(const uint8_t line, const uint8_t bits); static void send_row(const uint8_t row); static void send_column(const uint8_t col); static void mark16(const uint8_t y, const uint8_t v1, const uint8_t v2, uint8_t * const rcm=nullptr); static void range16(const uint8_t y, const uint8_t ot, const uint8_t nt, const uint8_t oh, const uint8_t nh, uint8_t * const rcm=nullptr); static void quantity(const uint8_t y, const uint8_t ov, const uint8_t nv, uint8_t * const rcm=nullptr); static void quantity16(const uint8_t y, const uint8_t ov, const uint8_t nv, uint8_t * const rcm=nullptr); #if MAX7219_INIT_TEST static void test_pattern(); static void run_test_pattern(); static void start_test_pattern(); #endif }; extern Max7219 max7219;
2301_81045437/Marlin
Marlin/src/feature/max7219.h
C++
agpl-3.0
8,218
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * MeatPack G-code Compression * * Algorithm & Implementation: Scott Mudge - mail@scottmudge.com * Date: Dec. 2020 * * Character Frequencies from ~30 MB of comment-stripped G-code: * '1' -> 4451136 '4' -> 1353273 '\n' -> 1087683 '-' -> 90242 * '0' -> 4253577 '9' -> 1352147 'G' -> 1075806 'Z' -> 34109 * ' ' -> 3053297 '3' -> 1262929 'X' -> 975742 'M' -> 11879 * '.' -> 3035310 '5' -> 1189871 'E' -> 965275 'S' -> 9910 * '2' -> 1523296 '6' -> 1127900 'Y' -> 965274 * '8' -> 1366812 '7' -> 1112908 'F' -> 99416 * * When space is omitted the letter 'E' is used in its place */ #include "../inc/MarlinConfig.h" #if HAS_MEATPACK #include "meatpack.h" #define MeatPack_ProtocolVersion "PV01" //#define MP_DEBUG #define DEBUG_OUT ENABLED(MP_DEBUG) #include "../core/debug_out.h" // The 15 most-common characters used in G-code, ~90-95% of all G-code uses these characters // Stored in SRAM for performance. uint8_t meatPackLookupTable[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', ' ', '\n', 'G', 'X', '\0' // Unused. 0b1111 indicates a literal character }; #if ENABLED(MP_DEBUG) uint8_t chars_decoded = 0; // Log the first 64 bytes after each reset #endif void MeatPack::reset_state() { state = 0; cmd_is_next = false; second_char = 0; cmd_count = full_char_count = char_out_count = 0; TERN_(MP_DEBUG, chars_decoded = 0); } /** * Unpack one or two characters from a packed byte into a buffer. * Return flags indicating whether any literal bytes follow. */ uint8_t MeatPack::unpack_chars(const uint8_t pk, uint8_t* __restrict const chars_out) { uint8_t out = 0; // If lower nybble is 1111, the higher nybble is unused, and next char is full. if ((pk & kFirstNotPacked) == kFirstNotPacked) out = kFirstCharIsLiteral; else { const uint8_t chr = pk & 0x0F; chars_out[0] = meatPackLookupTable[chr]; // Set the first char } // Check if upper nybble is 1111... if so, we don't need the second char. if ((pk & kSecondNotPacked) == kSecondNotPacked) out |= kSecondCharIsLiteral; else { const uint8_t chr = (pk >> 4) & 0x0F; chars_out[1] = meatPackLookupTable[chr]; // Set the second char } return out; } /** * Interpret a single (non-command) character * according to the current MeatPack state. */ void MeatPack::handle_rx_char_inner(const uint8_t c) { if (TEST(state, MPConfig_Bit_Active)) { // Is MeatPack active? if (!full_char_count) { // No literal characters to fetch? uint8_t buf[2] = { 0, 0 }; const uint8_t res = unpack_chars(c, buf); // Decode the byte into one or two characters. if (res & kFirstCharIsLiteral) { // The 1st character couldn't be packed. ++full_char_count; // So the next stream byte is a full character. if (res & kSecondCharIsLiteral) ++full_char_count; // The 2nd character couldn't be packed. Another stream byte is a full character. else second_char = buf[1]; // Retain the unpacked second character. } else { handle_output_char(buf[0]); // Send the unpacked first character out. if (buf[0] != '\n') { // After a newline the next char won't be set if (res & kSecondCharIsLiteral) ++full_char_count; // The 2nd character couldn't be packed. The next stream byte is a full character. else handle_output_char(buf[1]); // Send the unpacked second character out. } } } else { handle_output_char(c); // Pass through the character that couldn't be packed... if (second_char) { handle_output_char(second_char); // ...and send an unpacked 2nd character, if set. second_char = 0; } --full_char_count; // One literal character was consumed } } else // Packing not enabled, just copy character to output handle_output_char(c); } /** * Buffer a single output character which will be picked up in * GCodeQueue::get_serial_commands via calls to get_result_char */ void MeatPack::handle_output_char(const uint8_t c) { char_out_buf[char_out_count++] = c; #if ENABLED(MP_DEBUG) if (chars_decoded < 1024) { ++chars_decoded; DEBUG_ECHOLNPGM("RB: ", C(c)); } #endif } /** * Process a MeatPack command byte to update the state. * Report the new state to serial. */ void MeatPack::handle_command(const MeatPack_Command c) { switch (c) { case MPCommand_QueryConfig: break; case MPCommand_EnablePacking: SBI(state, MPConfig_Bit_Active); DEBUG_ECHOLNPGM("[MPDBG] ENA REC"); break; case MPCommand_DisablePacking: CBI(state, MPConfig_Bit_Active); DEBUG_ECHOLNPGM("[MPDBG] DIS REC"); break; case MPCommand_ResetAll: reset_state(); DEBUG_ECHOLNPGM("[MPDBG] RESET REC"); break; case MPCommand_EnableNoSpaces: SBI(state, MPConfig_Bit_NoSpaces); meatPackLookupTable[kSpaceCharIdx] = kSpaceCharReplace; DEBUG_ECHOLNPGM("[MPDBG] ENA NSP"); break; case MPCommand_DisableNoSpaces: CBI(state, MPConfig_Bit_NoSpaces); meatPackLookupTable[kSpaceCharIdx] = ' '; DEBUG_ECHOLNPGM("[MPDBG] DIS NSP"); break; default: DEBUG_ECHOLNPGM("[MPDBG] UNK CMD REC"); } report_state(); } void MeatPack::report_state() { // NOTE: if any configuration vars are added below, the outgoing sync text for host plugin // should not contain the "PV' substring, as this is used to indicate protocol version SERIAL_ECHOPGM("[MP] " MeatPack_ProtocolVersion " "); serialprint_onoff(TEST(state, MPConfig_Bit_Active)); SERIAL_ECHO(TEST(state, MPConfig_Bit_NoSpaces) ? F(" NSP\n") : F(" ESP\n")); } /** * Interpret a single character received from serial * according to the current meatpack state. */ void MeatPack::handle_rx_char(const uint8_t c, const serial_index_t serial_ind) { if (c == kCommandByte) { // A command (0xFF) byte? if (cmd_count) { // In fact, two in a row? cmd_is_next = true; // Then a MeatPack command follows cmd_count = 0; } else ++cmd_count; // cmd_count = 1 // One command byte received so far... return; } if (cmd_is_next) { // Were two command bytes received? PORT_REDIRECT(SERIAL_PORTMASK(serial_ind)); handle_command((MeatPack_Command)c); // Then the byte is a MeatPack command cmd_is_next = false; return; } if (cmd_count) { // Only a single 0xFF was received handle_rx_char_inner(kCommandByte); // A single 0xFF is passed on literally so it can be interpreted as kFirstNotPacked|kSecondNotPacked cmd_count = 0; } handle_rx_char_inner(c); // Other characters are passed on for MeatPack decoding } uint8_t MeatPack::get_result_char(char * const __restrict out) { uint8_t res = 0; if (char_out_count) { res = char_out_count; char_out_count = 0; for (uint8_t i = 0; i < res; ++i) out[i] = (char)char_out_buf[i]; } return res; } #endif // HAS_MEATPACK
2301_81045437/Marlin
Marlin/src/feature/meatpack.cpp
C++
agpl-3.0
8,317
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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/>. * */ /** * MeatPack G-code Compression * * Algorithm & Implementation: Scott Mudge - mail@scottmudge.com * Date: Dec. 2020 * * Specifically optimized for 3D printing G-Code, this is a zero-cost data compression method * which packs ~180-190% more data into the same amount of bytes going to the CNC controller. * As a majority of G-Code can be represented by a restricted alphabet, I performed histogram * analysis on a wide variety of 3D printing G-code samples, and found ~93% of all G-code could * be represented by the same 15-character alphabet. * * This allowed me to design a system of packing 2 8-bit characters into a single byte, assuming * they fall within this limited 15-character alphabet. Using a 4-bit lookup table, these 8-bit * characters can be represented by a 4-bit index. * * Combined with some logic to allow commingling of full-width characters outside of this 15- * character alphabet (at the cost of an extra 8-bits per full-width character), and by stripping * out unnecessary comments, the end result is G-code which is roughly half the original size. * * Why did I do this? I noticed micro-stuttering and other data-bottleneck issues while printing * objects with high curvature, especially at high speeds. There is also the issue of the limited * baud rate provided by Prusa's Atmega2560-based boards, over the USB serial connection. So soft- * ware like OctoPrint would also suffer this same micro-stuttering and poor print quality issue. * */ #pragma once #include <stdint.h> #include "../core/serial_hook.h" /** * Commands sent to MeatPack to control its behavior. * They are sent by first sending 2x MeatPack_CommandByte (0xFF) in sequence, * followed by one of the command bytes below. * Provided that 0xFF is an exceedingly rare character that is virtually never * present in G-code naturally, it is safe to assume 2 in sequence should never * happen naturally, and so it is used as a signal here. * * 0xFF *IS* used in "packed" G-code (used to denote that the next 2 characters are * full-width), however 2 in a row will never occur, as the next 2 bytes will always * some non-0xFF character. */ enum MeatPack_Command : uint8_t { MPCommand_None = 0, MPCommand_EnablePacking = 0xFB, MPCommand_DisablePacking = 0xFA, MPCommand_ResetAll = 0xF9, MPCommand_QueryConfig = 0xF8, MPCommand_EnableNoSpaces = 0xF7, MPCommand_DisableNoSpaces = 0xF6 }; enum MeatPack_ConfigStateBits : uint8_t { MPConfig_Bit_Active = 0, MPConfig_Bit_NoSpaces = 1 }; class MeatPack { // Utility definitions static const uint8_t kCommandByte = 0b11111111, kFirstNotPacked = 0b00001111, kSecondNotPacked = 0b11110000, kFirstCharIsLiteral = 0b00000001, kSecondCharIsLiteral = 0b00000010; static const uint8_t kSpaceCharIdx = 11; static const char kSpaceCharReplace = 'E'; bool cmd_is_next; // A command is pending uint8_t state; // Configuration state uint8_t second_char; // Buffers a character if dealing with out-of-sequence pairs uint8_t cmd_count, // Counter of command bytes received (need 2) full_char_count, // Counter for full-width characters to be received char_out_count; // Stores number of characters to be read out. uint8_t char_out_buf[2]; // Output buffer for caching up to 2 characters public: // Pass in a character rx'd by SD card or serial. Automatically parses command/ctrl sequences, // and will control state internally. void handle_rx_char(const uint8_t c, const serial_index_t serial_ind); /** * After passing in rx'd char using above method, call this to get characters out. * Can return from 0 to 2 characters at once. * @param out [in] Output pointer for unpacked/processed data. * @return Number of characters returned. Range from 0 to 2. */ uint8_t get_result_char(char * const __restrict out); void reset_state(); void report_state(); uint8_t unpack_chars(const uint8_t pk, uint8_t* __restrict const chars_out); void handle_command(const MeatPack_Command c); void handle_output_char(const uint8_t c); void handle_rx_char_inner(const uint8_t c); MeatPack() : cmd_is_next(false), state(0), second_char(0), cmd_count(0), full_char_count(0), char_out_count(0) {} }; // Implement the MeatPack serial class so it's transparent to rest of the code template <typename SerialT> struct MeatpackSerial : public SerialBase <MeatpackSerial < SerialT >> { typedef SerialBase< MeatpackSerial<SerialT> > BaseClassT; SerialT & out; MeatPack meatpack; char serialBuffer[2]; uint8_t charCount; uint8_t readIndex; NO_INLINE void write(uint8_t c) { out.write(c); } void flush() { out.flush(); } void begin(long br) { out.begin(br); readIndex = 0; } void end() { out.end(); } void msgDone() { out.msgDone(); } // Existing instances implement Arduino's operator bool, so use that if it's available bool connected() { return Private::HasMember_connected<SerialT>::value ? CALL_IF_EXISTS(bool, &out, connected) : (bool)out; } void flushTX() { CALL_IF_EXISTS(void, &out, flushTX); } SerialFeature features(serial_index_t index) const { return SerialFeature::MeatPack | CALL_IF_EXISTS(SerialFeature, &out, features, index); } int available(serial_index_t index) { if (charCount) return charCount; // The buffer still has data if (out.available(index) <= 0) return 0; // No data to read // Don't read in read method, instead do it here, so we can make progress in the read method const int r = out.read(index); if (r == -1) return 0; // This is an error from the underlying serial code meatpack.handle_rx_char((uint8_t)r, index); charCount = meatpack.get_result_char(serialBuffer); readIndex = 0; return charCount; } int readImpl(const serial_index_t index) { // Not enough char to make progress? if (charCount == 0 && available(index) == 0) return -1; charCount--; return serialBuffer[readIndex++]; } int read(serial_index_t index) { return readImpl(index); } int available() { return available(0); } int read() { return readImpl(0); } MeatpackSerial(const bool e, SerialT & out) : BaseClassT(e), out(out) {} };
2301_81045437/Marlin
Marlin/src/feature/meatpack.h
C++
agpl-3.0
7,383
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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(MIXING_EXTRUDER) #include "mixing.h" Mixer mixer; #ifdef MIXER_NORMALIZER_DEBUG #include "../core/serial.h" #endif // Used up to Planner level uint_fast8_t Mixer::selected_vtool = 0; float Mixer::collector[MIXING_STEPPERS]; // mix proportion. 0.0 = off, otherwise <= COLOR_A_MASK. mixer_comp_t Mixer::color[NR_MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS]; // Used in Stepper int_fast8_t Mixer::runner = 0; mixer_comp_t Mixer::s_color[MIXING_STEPPERS]; mixer_accu_t Mixer::accu[MIXING_STEPPERS] = { 0 }; #if ANY(HAS_DUAL_MIXING, GRADIENT_MIX) mixer_perc_t Mixer::mix[MIXING_STEPPERS]; #endif void Mixer::normalize(const uint8_t tool_index) { float cmax = 0; #ifdef MIXER_NORMALIZER_DEBUG float csum = 0; #endif MIXER_STEPPER_LOOP(i) { const float v = collector[i]; NOLESS(cmax, v); #ifdef MIXER_NORMALIZER_DEBUG csum += v; #endif } #ifdef MIXER_NORMALIZER_DEBUG SERIAL_ECHOPGM("Mixer: Old relation : [ "); MIXER_STEPPER_LOOP(i) SERIAL_ECHO(collector[i] / csum, C(' ')); SERIAL_ECHOLNPGM("]"); #endif // Scale all values so their maximum is COLOR_A_MASK const float scale = float(COLOR_A_MASK) / cmax; MIXER_STEPPER_LOOP(i) color[tool_index][i] = collector[i] * scale; #ifdef MIXER_NORMALIZER_DEBUG csum = 0; SERIAL_ECHOPGM("Mixer: Normalize to : [ "); MIXER_STEPPER_LOOP(i) { SERIAL_ECHO(uint16_t(color[tool_index][i]), C(' ')); csum += color[tool_index][i]; } SERIAL_ECHOLNPGM("]"); SERIAL_ECHOPGM("Mixer: New relation : [ "); MIXER_STEPPER_LOOP(i) SERIAL_ECHO(p_float_t(uint16_t(color[tool_index][i]) / csum, 3), C(' ')); SERIAL_ECHOLNPGM("]"); #endif TERN_(GRADIENT_MIX, refresh_gradient()); } void Mixer::reset_vtools() { // Virtual Tools 0, 1, 2, 3 = Filament 1, 2, 3, 4, etc. // Every virtual tool gets a pure filament for (uint8_t t = 0; t < _MIN(MIXING_VIRTUAL_TOOLS, MIXING_STEPPERS); ++t) MIXER_STEPPER_LOOP(i) color[t][i] = (t == i) ? COLOR_A_MASK : 0; // Remaining virtual tools are 100% filament 1 #if MIXING_VIRTUAL_TOOLS > MIXING_STEPPERS for (uint8_t t = MIXING_STEPPERS; t < MIXING_VIRTUAL_TOOLS; ++t) MIXER_STEPPER_LOOP(i) color[t][i] = (i == 0) ? COLOR_A_MASK : 0; #endif // MIXING_PRESETS: Set a variety of obvious mixes as presets #if ENABLED(MIXING_PRESETS) && WITHIN(MIXING_STEPPERS, 2, 3) #if MIXING_STEPPERS == 2 if (MIXING_VIRTUAL_TOOLS > 2) { collector[0] = 1; collector[1] = 1; mixer.normalize(2); } // 1:1 if (MIXING_VIRTUAL_TOOLS > 3) { collector[0] = 3; mixer.normalize(3); } // 3:1 if (MIXING_VIRTUAL_TOOLS > 4) { collector[0] = 1; collector[1] = 3; mixer.normalize(4); } // 1:3 if (MIXING_VIRTUAL_TOOLS > 5) { collector[1] = 2; mixer.normalize(5); } // 1:2 if (MIXING_VIRTUAL_TOOLS > 6) { collector[0] = 2; collector[1] = 1; mixer.normalize(6); } // 2:1 if (MIXING_VIRTUAL_TOOLS > 7) { collector[0] = 3; collector[1] = 2; mixer.normalize(7); } // 3:2 #else if (MIXING_VIRTUAL_TOOLS > 3) { collector[0] = 1; collector[1] = 1; collector[2] = 1; mixer.normalize(3); } // 1:1:1 if (MIXING_VIRTUAL_TOOLS > 4) { collector[1] = 3; collector[2] = 0; mixer.normalize(4); } // 1:3:0 if (MIXING_VIRTUAL_TOOLS > 5) { collector[0] = 0; collector[2] = 1; mixer.normalize(5); } // 0:3:1 if (MIXING_VIRTUAL_TOOLS > 6) { collector[1] = 1; mixer.normalize(6); } // 0:1:1 if (MIXING_VIRTUAL_TOOLS > 7) { collector[0] = 1; collector[2] = 0; mixer.normalize(7); } // 1:1:0 #endif ZERO(collector); #endif } // called at boot void Mixer::init() { ZERO(collector); reset_vtools(); #if HAS_MIXER_SYNC_CHANNEL // AUTORETRACT_TOOL gets the same amount of all filaments MIXER_STEPPER_LOOP(i) color[MIXER_AUTORETRACT_TOOL][i] = COLOR_A_MASK; #endif #if ANY(HAS_DUAL_MIXING, GRADIENT_MIX) update_mix_from_vtool(); #endif TERN_(GRADIENT_MIX, update_gradient_for_planner_z()); } void Mixer::refresh_collector(const float proportion/*=1.0*/, const uint8_t t/*=selected_vtool*/, float (&c)[MIXING_STEPPERS]/*=collector*/) { float csum = 0, cmax = 0; MIXER_STEPPER_LOOP(i) { const float v = color[t][i]; cmax = _MAX(cmax, v); csum += v; } //SERIAL_ECHOPGM("Mixer::refresh_collector(", proportion, ", ", t, ") cmax=", cmax, " csum=", csum, " color"); const float inv_prop = proportion / csum; MIXER_STEPPER_LOOP(i) { c[i] = color[t][i] * inv_prop; //SERIAL_ECHOPGM(" [", t, "][", i, "] = ", color[t][i], " (", c[i], ") "); } //SERIAL_EOL(); } #if ENABLED(GRADIENT_MIX) #include "../module/motion.h" #include "../module/planner.h" gradient_t Mixer::gradient = { false, // enabled {0}, // color (array) 0, 0, // start_z, end_z 0, 1, // start_vtool, end_vtool {0}, {0} // start_mix[], end_mix[] OPTARG(GRADIENT_VTOOL, -1) // vtool_index }; float Mixer::prev_z; // = 0 void Mixer::update_gradient_for_z(const_float_t z) { if (z == prev_z) return; prev_z = z; const float slice = gradient.end_z - gradient.start_z; float pct = (z - gradient.start_z) / slice; NOLESS(pct, 0.0f); NOMORE(pct, 1.0f); MIXER_STEPPER_LOOP(i) { const mixer_perc_t sm = gradient.start_mix[i]; mix[i] = sm + (gradient.end_mix[i] - sm) * pct; } copy_mix_to_color(gradient.color); } void Mixer::update_gradient_for_planner_z() { #if ENABLED(DELTA) get_cartesian_from_steppers(); update_gradient_for_z(cartes.z); #else update_gradient_for_z(planner.get_axis_position_mm(Z_AXIS)); #endif } #endif // GRADIENT_MIX #endif // MIXING_EXTRUDER
2301_81045437/Marlin
Marlin/src/feature/mixing.cpp
C++
agpl-3.0
6,810
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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 MIXER_NORMALIZER_DEBUG #ifndef __AVR__ // || HAS_DUAL_MIXING // Use 16-bit (or fastest) data for the integer mix factors typedef uint_fast16_t mixer_comp_t; typedef uint_fast16_t mixer_accu_t; #define COLOR_A_MASK 0x8000 #define COLOR_MASK 0x7FFF #else // Use 8-bit data for the integer mix factors // Exactness is sacrificed for speed #define MIXER_ACCU_SIGNED typedef uint8_t mixer_comp_t; typedef int8_t mixer_accu_t; #define COLOR_A_MASK 0x80 #define COLOR_MASK 0x7F #endif typedef int8_t mixer_perc_t; enum MixTool { FIRST_USER_VIRTUAL_TOOL = 0 , LAST_USER_VIRTUAL_TOOL = MIXING_VIRTUAL_TOOLS - 1 , NR_USER_VIRTUAL_TOOLS , MIXER_DIRECT_SET_TOOL = NR_USER_VIRTUAL_TOOLS #if HAS_MIXER_SYNC_CHANNEL , MIXER_AUTORETRACT_TOOL #endif , NR_MIXING_VIRTUAL_TOOLS }; #define MAX_VTOOLS TERN(HAS_MIXER_SYNC_CHANNEL, 254, 255) static_assert(NR_MIXING_VIRTUAL_TOOLS <= MAX_VTOOLS, "MIXING_VIRTUAL_TOOLS must be <= " STRINGIFY(MAX_VTOOLS) "!"); #define MIXER_STEPPER_LOOP(VAR) for (uint_fast8_t VAR = 0; VAR < MIXING_STEPPERS; VAR++) #if ENABLED(GRADIENT_MIX) typedef struct { bool enabled; // This gradient is enabled mixer_comp_t color[MIXING_STEPPERS]; // The current gradient color float start_z, end_z; // Region for gradient int8_t start_vtool, end_vtool; // Start and end virtual tools mixer_perc_t start_mix[MIXING_STEPPERS], // Start and end mixes from those tools end_mix[MIXING_STEPPERS]; #if ENABLED(GRADIENT_VTOOL) int8_t vtool_index; // Use this virtual tool number as index #endif } gradient_t; #endif /** * @brief Mixer class * @details Contains data and behaviors for a Mixing Extruder */ class Mixer { public: static float collector[MIXING_STEPPERS]; // M163 components, also editable from LCD static void init(); // Populate colors at boot time static void reset_vtools(); static void refresh_collector(const float proportion=1.0, const uint8_t t=selected_vtool, float (&c)[MIXING_STEPPERS]=collector); // Used up to Planner level FORCE_INLINE static void set_collector(const uint8_t c, const float f) { collector[c] = _MAX(f, 0.0f); } static void normalize(const uint8_t tool_index); FORCE_INLINE static void normalize() { normalize(selected_vtool); } FORCE_INLINE static uint8_t get_current_vtool() { return selected_vtool; } FORCE_INLINE static void T(const uint_fast8_t c) { selected_vtool = c; TERN_(GRADIENT_VTOOL, refresh_gradient()); TERN_(HAS_DUAL_MIXING, update_mix_from_vtool()); } // Used when dealing with blocks FORCE_INLINE static void populate_block(mixer_comp_t (&b_color)[MIXING_STEPPERS]) { #if ENABLED(GRADIENT_MIX) if (gradient.enabled) { MIXER_STEPPER_LOOP(i) b_color[i] = gradient.color[i]; return; } #endif MIXER_STEPPER_LOOP(i) b_color[i] = color[selected_vtool][i]; } FORCE_INLINE static void stepper_setup(mixer_comp_t (&b_color)[MIXING_STEPPERS]) { MIXER_STEPPER_LOOP(i) s_color[i] = b_color[i]; } #if ANY(HAS_DUAL_MIXING, GRADIENT_MIX) static mixer_perc_t mix[MIXING_STEPPERS]; // Scratch array for the Mix in proportion to 100 static void copy_mix_to_color(mixer_comp_t (&tcolor)[MIXING_STEPPERS]) { // Scale each component to the largest one in terms of COLOR_A_MASK // So the largest component will be COLOR_A_MASK and the other will be in proportion to it const float scale = (COLOR_A_MASK) * RECIPROCAL(_MAX( LIST_N(MIXING_STEPPERS, mix[0], mix[1], mix[2], mix[3], mix[4], mix[5]) )); // Scale all values so their maximum is COLOR_A_MASK MIXER_STEPPER_LOOP(i) tcolor[i] = mix[i] * scale; #ifdef MIXER_NORMALIZER_DEBUG SERIAL_ECHOLN( F("Mix [ "), LIST_N(MIXING_STEPPERS, mix[0], mix[1], mix[2], mix[3], mix[4], mix[5]), F(" ] to Color [ "), LIST_N(MIXING_STEPPERS, tcolor[0], tcolor[1], tcolor[2], tcolor[3], tcolor[4], tcolor[5]), F(" ]") ); #endif } static void update_mix_from_vtool(const uint8_t j=selected_vtool) { float ctot = 0; MIXER_STEPPER_LOOP(i) ctot += color[j][i]; MIXER_STEPPER_LOOP(i) mix[i] = mixer_perc_t(100.0f * color[j][i] / ctot + 0.5f); #ifdef MIXER_NORMALIZER_DEBUG SERIAL_ECHOLN(F("V-tool "), j, F(" [ "), LIST_N(MIXING_STEPPERS, color[j][0], color[j][1], color[j][2], color[j][3], color[j][4], color[j][5]), F(" ] to Mix [ "), LIST_N(MIXING_STEPPERS, mix[0], mix[1], mix[2], mix[3], mix[4], mix[5]), F(" ]") ); #endif } #endif // HAS_DUAL_MIXING || GRADIENT_MIX #if HAS_DUAL_MIXING // Update the virtual tool from an edited mix static void update_vtool_from_mix() { copy_mix_to_color(color[selected_vtool]); TERN_(GRADIENT_MIX, refresh_gradient()); // MIXER_STEPPER_LOOP(i) collector[i] = mix[i]; // normalize(); } #endif // HAS_DUAL_MIXING #if ENABLED(GRADIENT_MIX) static gradient_t gradient; static float prev_z; // Update the current mix from the gradient for a given Z static void update_gradient_for_z(const_float_t z); static void update_gradient_for_planner_z(); static void gradient_control(const_float_t z) { if (gradient.enabled) { if (z >= gradient.end_z) T(gradient.end_vtool); else update_gradient_for_z(z); } } static void update_mix_from_gradient() { float ctot = 0; MIXER_STEPPER_LOOP(i) ctot += gradient.color[i]; MIXER_STEPPER_LOOP(i) mix[i] = (mixer_perc_t)CEIL(100.0f * gradient.color[i] / ctot); #ifdef MIXER_NORMALIZER_DEBUG SERIAL_ECHOLN( F("Gradient [ "), LIST_N(MIXING_STEPPERS, gradient.color[0], gradient.color[1], gradient.color[2], gradient.color[3], gradient.color[4], gradient.color[5]), F(" ] to Mix [ "), LIST_N(MIXING_STEPPERS, mix[0], mix[1], mix[2], mix[3], mix[4], mix[5]), F(" ]") ); #endif } // Refresh the gradient after a change static void refresh_gradient() { #if ENABLED(GRADIENT_VTOOL) const bool is_grd = (gradient.vtool_index == -1 || selected_vtool == (uint8_t)gradient.vtool_index); #else constexpr bool is_grd = true; #endif gradient.enabled = is_grd && gradient.start_vtool != gradient.end_vtool && gradient.start_z < gradient.end_z; if (gradient.enabled) { mixer_perc_t mix_bak[MIXING_STEPPERS]; COPY(mix_bak, mix); update_mix_from_vtool(gradient.start_vtool); COPY(gradient.start_mix, mix); update_mix_from_vtool(gradient.end_vtool); COPY(gradient.end_mix, mix); update_gradient_for_planner_z(); COPY(mix, mix_bak); prev_z = -1; } } #endif // GRADIENT_MIX // Used in Stepper FORCE_INLINE static uint8_t get_stepper() { return runner; } FORCE_INLINE static uint8_t get_next_stepper() { for (;;) { if (--runner < 0) runner = MIXING_STEPPERS - 1; accu[runner] += s_color[runner]; if (TERN(MIXER_ACCU_SIGNED, accu[runner] < 0, accu[runner] & COLOR_A_MASK)) { accu[runner] &= COLOR_MASK; return runner; } } } private: // Used up to Planner level static uint_fast8_t selected_vtool; static mixer_comp_t color[NR_MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS]; // Used in Stepper static int_fast8_t runner; static mixer_comp_t s_color[MIXING_STEPPERS]; static mixer_accu_t accu[MIXING_STEPPERS]; }; extern Mixer mixer;
2301_81045437/Marlin
Marlin/src/feature/mixing.h
C++
agpl-3.0
8,544
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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_PRUSA_MMU1 #include "../../MarlinCore.h" #include "../../module/planner.h" #include "../../module/stepper.h" void mmu_init() { SET_OUTPUT(E_MUX0_PIN); SET_OUTPUT(E_MUX1_PIN); SET_OUTPUT(E_MUX2_PIN); } void select_multiplexed_stepper(const uint8_t e) { planner.synchronize(); stepper.disable_e_steppers(); WRITE(E_MUX0_PIN, TEST(e, 0) ? HIGH : LOW); WRITE(E_MUX1_PIN, TEST(e, 1) ? HIGH : LOW); WRITE(E_MUX2_PIN, TEST(e, 2) ? HIGH : LOW); safe_delay(100); } #endif // HAS_PRUSA_MMU1
2301_81045437/Marlin
Marlin/src/feature/mmu/mmu.cpp
C++
agpl-3.0
1,411
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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 mmu_init(); void select_multiplexed_stepper(const uint8_t e);
2301_81045437/Marlin
Marlin/src/feature/mmu/mmu.h
C
agpl-3.0
943
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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_PRUSA_MMU2 #include "mmu2.h" #include "../../lcd/menu/menu_mmu2.h" MMU2 mmu2; #include "../../gcode/gcode.h" #include "../../lcd/marlinui.h" #include "../../libs/buzzer.h" #include "../../libs/nozzle.h" #include "../../module/temperature.h" #include "../../module/planner.h" #include "../../module/stepper.h" #include "../../MarlinCore.h" #if ENABLED(HOST_PROMPT_SUPPORT) #include "../../feature/host_actions.h" #endif #if ENABLED(EXTENSIBLE_UI) #include "../../lcd/extui/ui_api.h" #endif #define DEBUG_OUT ENABLED(MMU2_DEBUG) #include "../../core/debug_out.h" #define MMU_TODELAY 100 #define MMU_TIMEOUT 10 #define MMU_CMD_TIMEOUT 45000UL // 45s timeout for mmu commands (except P0) #define MMU_P0_TIMEOUT 3000UL // Timeout for P0 command: 3seconds #define MMU2_SEND(S) tx_str(F(S "\n")) #define MMU2_RECV(S) rx_str(F(S "\n")) #if ENABLED(MMU_EXTRUDER_SENSOR) uint8_t mmu_idl_sens = 0; static bool mmu_loading_flag = false; #endif #define MMU_CMD_NONE 0 #define MMU_CMD_T0 0x10 // up to supported filaments #define MMU_CMD_L0 0x20 // up to supported filaments #define MMU_CMD_C0 0x30 #define MMU_CMD_U0 0x40 #define MMU_CMD_E0 0x50 // up to supported filaments #define MMU_CMD_R0 0x60 #define MMU_CMD_F0 0x70 // up to supported filaments #define MMU_REQUIRED_FW_BUILDNR TERN(MMU2_MODE_12V, 132, 126) #define MMU2_NO_TOOL 99 #define MMU_BAUD 115200 bool MMU2::_enabled, MMU2::ready; #if HAS_PRUSA_MMU2S bool MMU2::mmu2s_triggered; #endif uint8_t MMU2::cmd, MMU2::cmd_arg, MMU2::last_cmd, MMU2::extruder; int8_t MMU2::state = 0; volatile int8_t MMU2::finda = 1; volatile bool MMU2::finda_runout_valid; millis_t MMU2::prev_request, MMU2::prev_P0_request; char MMU2::rx_buffer[MMU_RX_SIZE], MMU2::tx_buffer[MMU_TX_SIZE]; struct E_Step { float extrude; //!< extrude distance in mm feedRate_t feedRate; //!< feed rate in mm/s }; inline void unscaled_mmu2_e_move(const float &dist, const feedRate_t fr_mm_s, const bool sync=true) { current_position.e += dist / planner.e_factor[active_extruder]; line_to_current_position(fr_mm_s); if (sync) planner.synchronize(); } MMU2::MMU2() { rx_buffer[0] = '\0'; } void MMU2::init() { set_runout_valid(false); #if PIN_EXISTS(MMU2_RST) WRITE(MMU2_RST_PIN, HIGH); SET_OUTPUT(MMU2_RST_PIN); #endif MMU2_SERIAL.begin(MMU_BAUD); extruder = MMU2_NO_TOOL; safe_delay(10); reset(); rx_buffer[0] = '\0'; state = -1; } void MMU2::reset() { DEBUG_ECHOLNPGM("MMU <= reset"); #if PIN_EXISTS(MMU2_RST) WRITE(MMU2_RST_PIN, LOW); safe_delay(20); WRITE(MMU2_RST_PIN, HIGH); #else MMU2_SEND("X0"); // Send soft reset #endif } int8_t MMU2::get_current_tool() { return extruder == MMU2_NO_TOOL ? -1 : extruder; } #if ANY(HAS_PRUSA_MMU2S, MMU_EXTRUDER_SENSOR) #define FILAMENT_PRESENT() (READ(FIL_RUNOUT1_PIN) != FIL_RUNOUT1_STATE) #else #define FILAMENT_PRESENT() true #endif void mmu2_attn_buzz(const bool two=false) { BUZZ(200, 404); if (two) { BUZZ(10, 0); BUZZ(200, 404); } } // Avoiding sscanf significantly reduces build size void MMU2::mmu_loop() { switch (state) { case 0: break; case -1: if (rx_start()) { prev_P0_request = millis(); // Initialize finda sensor timeout DEBUG_ECHOLNPGM("MMU => 'start'"); DEBUG_ECHOLNPGM("MMU <= 'S1'"); MMU2_SEND("S1"); // Read Version state = -2; } else if (ELAPSED(millis(), prev_request + 30000)) { // 30sec after reset disable MMU SERIAL_ECHOLNPGM("MMU not responding - DISABLED"); state = 0; } break; case -2: if (rx_ok()) { const uint16_t version = uint16_t(strtoul(rx_buffer, nullptr, 10)); DEBUG_ECHOLNPGM("MMU => ", version, "\nMMU <= 'S2'"); MMU2_SEND("S2"); // Read Build Number state = -3; } break; case -3: if (rx_ok()) { const uint16_t buildnr = uint16_t(strtoul(rx_buffer, nullptr, 10)); DEBUG_ECHOLNPGM("MMU => ", buildnr); check_version(buildnr); #if ENABLED(MMU2_MODE_12V) DEBUG_ECHOLNPGM("MMU <= 'M1'"); MMU2_SEND("M1"); // Stealth Mode state = -5; #else DEBUG_ECHOLNPGM("MMU <= 'P0'"); MMU2_SEND("P0"); // Read FINDA state = -4; #endif } break; #if ENABLED(MMU2_MODE_12V) case -5: // response to M1 if (rx_ok()) { DEBUG_ECHOLNPGM("MMU => ok"); DEBUG_ECHOLNPGM("MMU <= 'P0'"); MMU2_SEND("P0"); // Read FINDA state = -4; } break; #endif case -4: if (rx_ok()) { const uint8_t findex = uint8_t(rx_buffer[0] - '0'); if (findex <= 1) finda = findex; DEBUG_ECHOLNPGM("MMU => ", finda, "\nMMU - ENABLED"); _enabled = true; state = 1; TERN_(HAS_PRUSA_MMU2S, mmu2s_triggered = false); } break; case 1: if (cmd) { if (WITHIN(cmd, MMU_CMD_T0, MMU_CMD_T0 + EXTRUDERS - 1)) { // tool change const int filament = cmd - MMU_CMD_T0; DEBUG_ECHOLNPGM("MMU <= T", filament); tx_printf(F("T%d\n"), filament); TERN_(MMU_EXTRUDER_SENSOR, mmu_idl_sens = 1); // enable idler sensor, if any state = 3; // wait for response } else if (WITHIN(cmd, MMU_CMD_L0, MMU_CMD_L0 + EXTRUDERS - 1)) { // load const int filament = cmd - MMU_CMD_L0; DEBUG_ECHOLNPGM("MMU <= L", filament); tx_printf(F("L%d\n"), filament); state = 3; // wait for response } else if (cmd == MMU_CMD_C0) { // continue loading DEBUG_ECHOLNPGM("MMU <= 'C0'"); MMU2_SEND("C0"); state = 3; // wait for response } else if (cmd == MMU_CMD_U0) { // unload current DEBUG_ECHOLNPGM("MMU <= 'U0'"); MMU2_SEND("U0"); state = 3; // wait for response } else if (WITHIN(cmd, MMU_CMD_E0, MMU_CMD_E0 + EXTRUDERS - 1)) { // eject filament const int filament = cmd - MMU_CMD_E0; DEBUG_ECHOLNPGM("MMU <= E", filament); tx_printf(F("E%d\n"), filament); state = 3; // wait for response } else if (cmd == MMU_CMD_R0) { // recover after eject DEBUG_ECHOLNPGM("MMU <= 'R0'"); MMU2_SEND("R0"); state = 3; // wait for response } else if (WITHIN(cmd, MMU_CMD_F0, MMU_CMD_F0 + EXTRUDERS - 1)) { // filament type const int filament = cmd - MMU_CMD_F0; DEBUG_ECHOLNPGM("MMU <= F", filament, " ", cmd_arg); tx_printf(F("F%d %d\n"), filament, cmd_arg); state = 3; // wait for response } last_cmd = cmd; cmd = MMU_CMD_NONE; } else if (ELAPSED(millis(), prev_P0_request + 300)) { MMU2_SEND("P0"); // Read FINDA state = 2; // wait for response } TERN_(HAS_PRUSA_MMU2S, check_filament()); break; case 2: // response to command P0 if (rx_ok()) { const uint8_t findex = uint8_t(rx_buffer[0] - '0'); if (findex <= 1) finda = findex; // This is super annoying. Only activate if necessary //if (finda_runout_valid) DEBUG_ECHOLNPGM("MMU <= 'P0'\nMMU => ", p_float_t(finda, 6)); if (!finda && finda_runout_valid) filament_runout(); if (cmd == MMU_CMD_NONE) ready = true; state = 1; } else if (ELAPSED(millis(), prev_request + MMU_P0_TIMEOUT)) // Resend request after timeout (3s) state = 1; TERN_(HAS_PRUSA_MMU2S, check_filament()); break; case 3: // response to mmu commands #if ENABLED(MMU_EXTRUDER_SENSOR) if (mmu_idl_sens) { if (FILAMENT_PRESENT() && mmu_loading_flag) { DEBUG_ECHOLNPGM("MMU <= 'A'"); MMU2_SEND("A"); // send 'abort' request mmu_idl_sens = 0; DEBUG_ECHOLNPGM("MMU IDLER_SENSOR = 0 - ABORT"); } } #endif if (rx_ok()) { #if HAS_PRUSA_MMU2S // Respond to C0 MMU command in MMU2S model const bool keep_trying = !mmu2s_triggered && last_cmd == MMU_CMD_C0; if (keep_trying) { // MMU ok received but filament sensor not triggered, retrying... DEBUG_ECHOLNPGM("MMU => 'ok' (no filament in gears)"); DEBUG_ECHOLNPGM("MMU <= 'C0' (keep trying)"); MMU2_SEND("C0"); } #else constexpr bool keep_trying = false; #endif if (!keep_trying) { DEBUG_ECHOLNPGM("MMU => 'ok'"); ready = true; state = 1; last_cmd = MMU_CMD_NONE; } } else if (ELAPSED(millis(), prev_request + MMU_CMD_TIMEOUT)) { // resend request after timeout if (last_cmd) { DEBUG_ECHOLNPGM("MMU retry"); cmd = last_cmd; last_cmd = MMU_CMD_NONE; } state = 1; } TERN_(HAS_PRUSA_MMU2S, check_filament()); break; } } /** * Check if MMU was started */ bool MMU2::rx_start() { // check for start message return MMU2_RECV("start"); } /** * Check if the data received ends with the given string. */ bool MMU2::rx_str(FSTR_P fstr) { PGM_P pstr = FTOP(fstr); uint8_t i = strlen(rx_buffer); while (MMU2_SERIAL.available()) { rx_buffer[i++] = MMU2_SERIAL.read(); if (i == sizeof(rx_buffer) - 1) { DEBUG_ECHOLNPGM("rx buffer overrun"); break; } } rx_buffer[i] = '\0'; uint8_t len = strlen_P(pstr); if (i < len) return false; pstr += len; while (len--) { char c0 = pgm_read_byte(pstr--), c1 = rx_buffer[i--]; if (c0 == c1) continue; if (c0 == '\r' && c1 == '\n') continue; // match cr as lf if (c0 == '\n' && c1 == '\r') continue; // match lf as cr return false; } return true; } /** * Transfer data to MMU, no argument */ void MMU2::tx_str(FSTR_P fstr) { clear_rx_buffer(); PGM_P pstr = FTOP(fstr); while (const char c = pgm_read_byte(pstr)) { MMU2_SERIAL.write(c); pstr++; } prev_request = millis(); } /** * Transfer data to MMU, single argument */ void MMU2::tx_printf(FSTR_P format, int argument = -1) { clear_rx_buffer(); const uint8_t len = sprintf_P(tx_buffer, FTOP(format), argument); for (uint8_t i = 0; i < len; ++i) MMU2_SERIAL.write(tx_buffer[i]); prev_request = millis(); } /** * Transfer data to MMU, two arguments */ void MMU2::tx_printf(FSTR_P format, int argument1, int argument2) { clear_rx_buffer(); const uint8_t len = sprintf_P(tx_buffer, FTOP(format), argument1, argument2); for (uint8_t i = 0; i < len; ++i) MMU2_SERIAL.write(tx_buffer[i]); prev_request = millis(); } /** * Empty the rx buffer */ void MMU2::clear_rx_buffer() { while (MMU2_SERIAL.available()) MMU2_SERIAL.read(); rx_buffer[0] = '\0'; } /** * Check if we received 'ok' from MMU */ bool MMU2::rx_ok() { if (MMU2_RECV("ok")) { prev_P0_request = millis(); return true; } return false; } /** * Check if MMU has compatible firmware */ void MMU2::check_version(const uint16_t buildnr) { if (buildnr < MMU_REQUIRED_FW_BUILDNR) { SERIAL_ERROR_MSG("Invalid MMU2 firmware. Version >= " STRINGIFY(MMU_REQUIRED_FW_BUILDNR) " required."); kill(GET_TEXT_F(MSG_KILL_MMU2_FIRMWARE)); } } static void mmu2_not_responding() { LCD_MESSAGE(MSG_MMU2_NOT_RESPONDING); BUZZ(100, 659); BUZZ(200, 698); BUZZ(100, 659); BUZZ(300, 440); BUZZ(100, 659); } inline void beep_bad_cmd() { BUZZ(400, 40); } #if HAS_PRUSA_MMU2S /** * Load filament until the sensor at the gears is triggered * and give up after a number of attempts set with MMU2_C0_RETRY. * Each try has a timeout before returning a fail state. */ bool MMU2::load_to_gears() { command(MMU_CMD_C0); manage_response(true, true); for (uint8_t i = 0; i < MMU2_C0_RETRY; ++i) { // Keep loading until filament reaches gears if (mmu2s_triggered) break; command(MMU_CMD_C0); manage_response(true, true); check_filament(); } const bool success = mmu2s_triggered && can_load(); if (!success) mmu2_not_responding(); return success; } /** * Handle tool change */ void MMU2::tool_change(const uint8_t index) { if (!_enabled) return; set_runout_valid(false); if (index != extruder) { if (ENABLED(MMU_IR_UNLOAD_MOVE) && FILAMENT_PRESENT()) { DEBUG_ECHOLNPGM("Unloading\n"); while (FILAMENT_PRESENT()) // Filament present? Keep unloading. unscaled_mmu2_e_move(-0.25, MMM_TO_MMS(120)); // 0.25mm is a guessed value. Adjust to preference. } stepper.disable_extruder(); ui.status_printf(0, GET_TEXT_F(MSG_MMU2_LOADING_FILAMENT), int(index + 1)); command(MMU_CMD_T0 + index); manage_response(true, true); if (load_to_gears()) { extruder = index; // filament change is finished active_extruder = 0; stepper.enable_extruder(); SERIAL_ECHO_MSG(STR_ACTIVE_EXTRUDER, extruder); } ui.reset_status(); } set_runout_valid(true); } /** * Handle special T?/Tx/Tc commands * * T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically * Tx Same as T?, except nozzle doesn't have to be preheated. Tc must be placed after extruder nozzle is preheated to finish filament load. * Tc Load to nozzle after filament was prepared by Tx and extruder nozzle is already heated. */ void MMU2::tool_change(const char *special) { if (!_enabled) return; set_runout_valid(false); switch (*special) { case '?': { #if ENABLED(MMU2_MENUS) const uint8_t index = mmu2_choose_filament(); while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(100); load_to_nozzle(index); #else beep_bad_cmd(); #endif } break; case 'x': { #if ENABLED(MMU2_MENUS) planner.synchronize(); const uint8_t index = mmu2_choose_filament(); stepper.disable_extruder(); command(MMU_CMD_T0 + index); manage_response(true, true); if (load_to_gears()) { mmu_loop(); stepper.enable_extruder(); extruder = index; active_extruder = 0; } #else beep_bad_cmd(); #endif } break; case 'c': { while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(100); load_to_nozzle_sequence(); } break; } set_runout_valid(true); } #elif ENABLED(MMU_EXTRUDER_SENSOR) /** * Handle tool change */ void MMU2::tool_change(const uint8_t index) { if (!_enabled) return; set_runout_valid(false); if (index != extruder) { stepper.disable_extruder(); if (FILAMENT_PRESENT()) { DEBUG_ECHOLNPGM("Unloading\n"); mmu_loading_flag = false; command(MMU_CMD_U0); manage_response(true, true); } ui.status_printf(0, GET_TEXT_F(MSG_MMU2_LOADING_FILAMENT), int(index + 1)); mmu_loading_flag = true; command(MMU_CMD_T0 + index); manage_response(true, true); mmu_continue_loading(); //command(MMU_CMD_C0); extruder = index; active_extruder = 0; stepper.enable_extruder(); SERIAL_ECHO_MSG(STR_ACTIVE_EXTRUDER, extruder); ui.reset_status(); } set_runout_valid(true); } /** * Handle special T?/Tx/Tc commands * * T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically * Tx Same as T?, except nozzle doesn't have to be preheated. Tc must be placed after extruder nozzle is preheated to finish filament load. * Tc Load to nozzle after filament was prepared by Tx and extruder nozzle is already heated. */ void MMU2::tool_change(const char *special) { if (!_enabled) return; set_runout_valid(false); switch (*special) { case '?': { DEBUG_ECHOLNPGM("case ?\n"); #if ENABLED(MMU2_MENUS) uint8_t index = mmu2_choose_filament(); while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(100); load_to_nozzle(index); #else beep_bad_cmd(); #endif } break; case 'x': { DEBUG_ECHOLNPGM("case x\n"); #if ENABLED(MMU2_MENUS) planner.synchronize(); uint8_t index = mmu2_choose_filament(); stepper.disable_extruder(); command(MMU_CMD_T0 + index); manage_response(true, true); mmu_continue_loading(); command(MMU_CMD_C0); mmu_loop(); stepper.enable_extruder(); extruder = index; active_extruder = 0; #else beep_bad_cmd(); #endif } break; case 'c': { DEBUG_ECHOLNPGM("case c\n"); while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(100); load_to_nozzle_sequence(); } break; } set_runout_valid(true); } void MMU2::mmu_continue_loading() { // Try to load the filament a limited number of times bool fil_present = 0; for (uint8_t i = 0; i < MMU_LOADING_ATTEMPTS_NR; i++) { DEBUG_ECHOLNPGM("Load attempt #", i + 1); // Done as soon as filament is present fil_present = FILAMENT_PRESENT(); if (fil_present) break; // Attempt to load the filament, 1mm at a time, for 3s command(MMU_CMD_C0); stepper.enable_extruder(); const millis_t expire_ms = millis() + 3000; do { current_position.e += 1; line_to_current_position(MMU_LOAD_FEEDRATE); planner.synchronize(); // When (T0 rx->ok) load is ready, but in fact it did not load // successfully or an overload created pressure in the extruder. // Send (C0) to load more and move E_AXIS a little to release pressure. if ((fil_present = FILAMENT_PRESENT())) MMU2_SEND("A"); } while (!fil_present && PENDING(millis(), expire_ms)); stepper.disable_extruder(); manage_response(true, true); } // Was the filament still missing in the last check? if (!fil_present) { DEBUG_ECHOLNPGM("Filament never reached sensor, runout"); filament_runout(); } mmu_idl_sens = 0; } #else // !HAS_PRUSA_MMU2S && !MMU_EXTRUDER_SENSOR /** * Handle tool change */ void MMU2::tool_change(const uint8_t index) { if (!_enabled) return; set_runout_valid(false); if (index != extruder) { stepper.disable_extruder(); ui.status_printf(0, GET_TEXT_F(MSG_MMU2_LOADING_FILAMENT), int(index + 1)); command(MMU_CMD_T0 + index); manage_response(true, true); command(MMU_CMD_C0); extruder = index; // Filament change is finished active_extruder = 0; stepper.enable_extruder(); SERIAL_ECHO_MSG(STR_ACTIVE_EXTRUDER, extruder); ui.reset_status(); } set_runout_valid(true); } /** * Handle special T?/Tx/Tc commands * * T? Gcode to extrude shouldn't have to follow, load to extruder wheels is done automatically * Tx Same as T?, except nozzle doesn't have to be preheated. Tc must be placed after extruder nozzle is preheated to finish filament load. * Tc Load to nozzle after filament was prepared by Tx and extruder nozzle is already heated. */ void MMU2::tool_change(const char *special) { if (!_enabled) return; set_runout_valid(false); switch (*special) { case '?': { DEBUG_ECHOLNPGM("case ?\n"); #if ENABLED(MMU2_MENUS) uint8_t index = mmu2_choose_filament(); while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(100); load_to_nozzle(index); #else beep_bad_cmd(); #endif } break; case 'x': { DEBUG_ECHOLNPGM("case x\n"); #if ENABLED(MMU2_MENUS) planner.synchronize(); uint8_t index = mmu2_choose_filament(); stepper.disable_extruder(); command(MMU_CMD_T0 + index); manage_response(true, true); command(MMU_CMD_C0); mmu_loop(); stepper.enable_extruder(); extruder = index; active_extruder = 0; #else beep_bad_cmd(); #endif } break; case 'c': { DEBUG_ECHOLNPGM("case c\n"); while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(100); load_to_nozzle_sequence(); } break; } set_runout_valid(true); } #endif // HAS_PRUSA_MMU2S /** * Set next command */ void MMU2::command(const uint8_t mmu_cmd) { if (!_enabled) return; cmd = mmu_cmd; ready = false; } /** * Wait for response from MMU */ bool MMU2::get_response() { while (cmd != MMU_CMD_NONE) idle(); while (!ready) { idle(); if (state != 3) break; } const bool ret = ready; ready = false; return ret; } /** * Wait for response and deal with timeout if necessary */ void MMU2::manage_response(const bool move_axes, const bool turn_off_nozzle) { constexpr xyz_pos_t park_point = NOZZLE_PARK_POINT; bool response = false, mmu_print_saved = false; xyz_pos_t resume_position; celsius_t resume_hotend_temp = thermalManager.degTargetHotend(active_extruder); KEEPALIVE_STATE(PAUSED_FOR_USER); while (!response) { response = get_response(); // wait for "ok" from mmu if (!response) { // No "ok" was received in reserved time frame, user will fix the issue on mmu unit if (!mmu_print_saved) { // First occurrence. Save current position, park print head, disable nozzle heater. planner.synchronize(); mmu_print_saved = true; SERIAL_ECHOLNPGM("MMU not responding"); resume_hotend_temp = thermalManager.degTargetHotend(active_extruder); resume_position = current_position; if (move_axes && all_axes_homed()) nozzle.park(0, park_point); if (turn_off_nozzle) thermalManager.setTargetHotend(0, active_extruder); mmu2_not_responding(); } } else if (mmu_print_saved) { SERIAL_ECHOLNPGM("\nMMU starts responding"); if (turn_off_nozzle && resume_hotend_temp) { thermalManager.setTargetHotend(resume_hotend_temp, active_extruder); LCD_MESSAGE(MSG_HEATING); ERR_BUZZ(); while (!thermalManager.wait_for_hotend(active_extruder, false)) safe_delay(1000); } LCD_MESSAGE(MSG_MMU2_RESUMING); mmu2_attn_buzz(true); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" if (move_axes && all_axes_homed()) { // Move XY to starting position, then Z do_blocking_move_to_xy(resume_position, feedRate_t(NOZZLE_PARK_XY_FEEDRATE)); // Move Z_AXIS to saved position do_blocking_move_to_z(resume_position.z, feedRate_t(NOZZLE_PARK_Z_FEEDRATE)); } #pragma GCC diagnostic pop } } } void MMU2::set_filament_type(const uint8_t index, const uint8_t filamentType) { if (!_enabled) return; cmd_arg = filamentType; command(MMU_CMD_F0 + index); manage_response(true, true); } void MMU2::filament_runout() { queue.inject(F(MMU2_FILAMENT_RUNOUT_SCRIPT)); planner.synchronize(); } #if HAS_PRUSA_MMU2S void MMU2::check_filament() { const bool present = FILAMENT_PRESENT(); if (cmd == MMU_CMD_NONE && last_cmd == MMU_CMD_C0) { if (present && !mmu2s_triggered) { DEBUG_ECHOLNPGM("MMU <= 'A'"); MMU2_SEND("A"); } // Slowly spin the extruder during C0 else { while (planner.movesplanned() < 3) unscaled_mmu2_e_move(0.25, MMM_TO_MMS(120), false); } } mmu2s_triggered = present; } bool MMU2::can_load() { static const E_Step can_load_sequence[] PROGMEM = { MMU2_CAN_LOAD_SEQUENCE }, can_load_increment_sequence[] PROGMEM = { MMU2_CAN_LOAD_INCREMENT_SEQUENCE }; execute_extruder_sequence(can_load_sequence, COUNT(can_load_sequence)); int filament_detected_count = 0; const int steps = (MMU2_CAN_LOAD_RETRACT) / (MMU2_CAN_LOAD_INCREMENT); DEBUG_ECHOLNPGM("MMU can_load:"); for (uint8_t i = 0; i < steps; ++i) { execute_extruder_sequence(can_load_increment_sequence, COUNT(can_load_increment_sequence)); check_filament(); // Don't trust the idle function DEBUG_CHAR(mmu2s_triggered ? 'O' : 'o'); if (mmu2s_triggered) ++filament_detected_count; } if (filament_detected_count <= steps - (MMU2_CAN_LOAD_DEVIATION) / (MMU2_CAN_LOAD_INCREMENT)) { DEBUG_ECHOLNPGM(" failed."); return false; } DEBUG_ECHOLNPGM(" succeeded."); return true; } #endif // Load filament into MMU2 void MMU2::load_to_feeder(const uint8_t index) { if (!_enabled) return; command(MMU_CMD_L0 + index); manage_response(false, false); mmu2_attn_buzz(); } /** * Switch material and load to nozzle */ bool MMU2::load_to_nozzle(const uint8_t index) { if (!_enabled) return false; if (thermalManager.tooColdToExtrude(active_extruder)) { mmu2_attn_buzz(); LCD_ALERTMESSAGE(MSG_HOTEND_TOO_COLD); return false; } if (TERN0(MMU_IR_UNLOAD_MOVE, index != extruder) && FILAMENT_PRESENT()) { DEBUG_ECHOLNPGM("Unloading\n"); ramming_sequence(); // Unloading instructions from printer side when operating LCD while (FILAMENT_PRESENT()) // Filament present? Keep unloading. unscaled_mmu2_e_move(-0.25, MMM_TO_MMS(120)); // 0.25mm is a guessed value. Adjust to preference. } stepper.disable_extruder(); command(MMU_CMD_T0 + index); manage_response(true, true); const bool success = load_to_gears(); if (success) { mmu_loop(); extruder = index; active_extruder = 0; load_to_nozzle_sequence(); mmu2_attn_buzz(); } return success; } bool MMU2::eject_filament(const uint8_t index, const bool recover) { if (!_enabled) return false; if (thermalManager.tooColdToExtrude(active_extruder)) { mmu2_attn_buzz(); LCD_ALERTMESSAGE(MSG_HOTEND_TOO_COLD); return false; } LCD_MESSAGE(MSG_MMU2_EJECTING_FILAMENT); unscaled_mmu2_e_move(-(MMU2_FILAMENTCHANGE_EJECT_FEED), MMM_TO_MMS(2500)); command(MMU_CMD_E0 + index); manage_response(false, false); if (recover) { LCD_MESSAGE(MSG_MMU2_REMOVE_AND_CLICK); mmu2_attn_buzz(); TERN_(HOST_PROMPT_SUPPORT, hostui.continue_prompt(GET_TEXT_F(MSG_MMU2_EJECT_RECOVER))); TERN_(EXTENSIBLE_UI, ExtUI::onUserConfirmRequired(GET_TEXT_F(MSG_MMU2_EJECT_RECOVER))); TERN_(HAS_RESUME_CONTINUE, wait_for_user_response()); mmu2_attn_buzz(); command(MMU_CMD_R0); manage_response(false, false); } ui.reset_status(); // no active tool extruder = MMU2_NO_TOOL; set_runout_valid(false); mmu2_attn_buzz(); stepper.disable_extruder(); return true; } /** * Unload from hotend and retract to MMU */ bool MMU2::unload() { if (!_enabled) return false; if (thermalManager.tooColdToExtrude(active_extruder)) { mmu2_attn_buzz(); LCD_ALERTMESSAGE(MSG_HOTEND_TOO_COLD); return false; } // Unload sequence to optimize shape of the tip of the unloaded filament ramming_sequence(); command(MMU_CMD_U0); manage_response(false, true); mmu2_attn_buzz(); // no active tool extruder = MMU2_NO_TOOL; set_runout_valid(false); return true; } void MMU2::ramming_sequence() { static const E_Step sequence[] PROGMEM = { MMU2_RAMMING_SEQUENCE }; execute_extruder_sequence(sequence, COUNT(sequence)); } void MMU2::load_to_nozzle_sequence() { static const E_Step sequence[] PROGMEM = { MMU2_LOAD_TO_NOZZLE_SEQUENCE }; execute_extruder_sequence(sequence, COUNT(sequence)); } void MMU2::execute_extruder_sequence(const E_Step * sequence, int steps) { planner.synchronize(); const E_Step *step = sequence; for (uint8_t i = 0; i < steps; ++i) { const float es = pgm_read_float(&(step->extrude)); const feedRate_t fr_mm_m = pgm_read_float(&(step->feedRate)); DEBUG_ECHO_MSG("E step ", es, "/", fr_mm_m); unscaled_mmu2_e_move(es, MMM_TO_MMS(fr_mm_m)); step++; } stepper.disable_extruder(); } #endif // HAS_PRUSA_MMU2
2301_81045437/Marlin
Marlin/src/feature/mmu/mmu2.cpp
C++
agpl-3.0
29,499
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../../inc/MarlinConfig.h" #if HAS_FILAMENT_SENSOR #include "../runout.h" #endif #if SERIAL_USB #define MMU_RX_SIZE 256 #define MMU_TX_SIZE 256 #else #define MMU_RX_SIZE 16 #define MMU_TX_SIZE 16 #endif struct E_Step; class MMU2 { public: MMU2(); static void init(); static void reset(); static bool enabled() { return _enabled; } static void mmu_loop(); static void tool_change(const uint8_t index); static void tool_change(const char *special); static int8_t get_current_tool(); static void set_filament_type(const uint8_t index, const uint8_t type); static bool unload(); static void load_to_feeder(const uint8_t index); static bool load_to_nozzle(const uint8_t index); static bool eject_filament(const uint8_t index, const bool recover); private: static bool rx_str(FSTR_P fstr); static void tx_str(FSTR_P fstr); static void tx_printf(FSTR_P ffmt, const int argument); static void tx_printf(FSTR_P ffmt, const int argument1, const int argument2); static void clear_rx_buffer(); static bool rx_ok(); static bool rx_start(); static void check_version(const uint16_t buildnr); static void command(const uint8_t cmd); static bool get_response(); static void manage_response(const bool move_axes, const bool turn_off_nozzle); static void execute_extruder_sequence(const E_Step * sequence, int steps); static void ramming_sequence(); static void load_to_nozzle_sequence(); static void filament_runout(); #if HAS_PRUSA_MMU2S static bool mmu2s_triggered; static void check_filament(); static bool can_load(); static bool load_to_gears(); #else FORCE_INLINE static bool load_to_gears() { return true; } #endif #if ENABLED(MMU_EXTRUDER_SENSOR) #define MMU_LOAD_FEEDRATE 19.02f // (mm/s) static void mmu_continue_loading(); #endif static bool _enabled, ready; static uint8_t cmd, cmd_arg, last_cmd, extruder; static int8_t state; static volatile int8_t finda; static volatile bool finda_runout_valid; static millis_t prev_request, prev_P0_request; static char rx_buffer[MMU_RX_SIZE], tx_buffer[MMU_TX_SIZE]; static void set_runout_valid(const bool valid) { finda_runout_valid = valid; #if HAS_FILAMENT_SENSOR if (valid) runout.reset(); #endif } }; extern MMU2 mmu2;
2301_81045437/Marlin
Marlin/src/feature/mmu/mmu2.h
C++
agpl-3.0
3,204
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../../inc/MarlinConfigPre.h" #if ENABLED(PASSWORD_FEATURE) #include "password.h" #include "../../gcode/gcode.h" #include "../../core/serial.h" Password password; // public: bool Password::is_set, Password::is_locked, Password::did_first_run; // = false uint32_t Password::value, Password::value_entry; // // Authenticate user with password. // Called from Setup, after SD Prinitng Stops/Aborts, and M510 // void Password::lock_machine() { is_locked = true; TERN_(HAS_MARLINUI_MENU, authenticate_user(ui.status_screen, screen_password_entry)); } // // Authentication check // void Password::authentication_check() { if (value_entry == value) { is_locked = false; did_first_run = true; } else { is_locked = true; SERIAL_ECHOLNPGM(STR_WRONG_PASSWORD); } TERN_(HAS_MARLINUI_MENU, authentication_done()); } #endif // PASSWORD_FEATURE
2301_81045437/Marlin
Marlin/src/feature/password/password.cpp
C++
agpl-3.0
1,743
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../../lcd/marlinui.h" class Password { public: static bool is_set, is_locked, did_first_run; static uint32_t value, value_entry; Password() {} static void lock_machine(); static void authentication_check(); #if HAS_MARLINUI_MENU static void access_menu_password(); static void authentication_done(); static void media_gatekeeper(); private: static void authenticate_user(const screenFunc_t, const screenFunc_t); static void menu_password(); static void menu_password_entry(); static void screen_password_entry(); static void screen_set_password(); static void start_over(); static void digit_entered(); static void set_password_done(const bool with_set=true); static void menu_password_report(); static void remove_password(); #endif }; extern Password password;
2301_81045437/Marlin
Marlin/src/feature/password/password.h
C++
agpl-3.0
1,727
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * feature/pause.cpp - Pause feature support functions * This may be combined with related G-codes if features are consolidated. * * Note: Calls to ui.pause_show_message are passed to either ExtUI or MarlinUI. */ #include "../inc/MarlinConfigPre.h" #if ENABLED(ADVANCED_PAUSE_FEATURE) //#define DEBUG_PAUSE_RESUME #include "../MarlinCore.h" #include "../gcode/gcode.h" #include "../module/motion.h" #include "../module/planner.h" #include "../module/printcounter.h" #include "../module/temperature.h" #if HAS_EXTRUDERS #include "../module/stepper.h" #endif #if ENABLED(AUTO_BED_LEVELING_UBL) #include "bedlevel/bedlevel.h" #endif #if ENABLED(FWRETRACT) #include "fwretract.h" #endif #if HAS_FILAMENT_SENSOR #include "runout.h" #endif #if ENABLED(HOST_ACTION_COMMANDS) #include "host_actions.h" #endif #if ENABLED(EXTENSIBLE_UI) #include "../lcd/extui/ui_api.h" #endif #include "../lcd/marlinui.h" #if HAS_SOUND #include "../libs/buzzer.h" #endif #if ENABLED(POWER_LOSS_RECOVERY) #include "powerloss.h" #endif #include "../libs/nozzle.h" #include "pause.h" #define DEBUG_OUT ENABLED(DEBUG_PAUSE_RESUME) #include "../core/debug_out.h" // private: static xyze_pos_t resume_position; #if M600_PURGE_MORE_RESUMABLE PauseMenuResponse pause_menu_response; PauseMode pause_mode = PAUSE_MODE_PAUSE_PRINT; #endif #if ENABLED(CONFIGURE_FILAMENT_CHANGE) fil_change_settings_t fc_settings[EXTRUDERS]; #endif #if HAS_MEDIA #include "../sd/cardreader.h" #endif #if ENABLED(EMERGENCY_PARSER) #define _PMSG(L) L##_M108 #else #define _PMSG(L) L##_LCD #endif #if HAS_SOUND static void impatient_beep(const int8_t max_beep_count, const bool restart=false) { if (TERN0(HAS_MARLINUI_MENU, pause_mode == PAUSE_MODE_PAUSE_PRINT)) return; static millis_t next_buzz = 0; static int8_t runout_beep = 0; if (restart) next_buzz = runout_beep = 0; const bool always = max_beep_count < 0; const millis_t ms = millis(); if (ELAPSED(ms, next_buzz)) { if (always || runout_beep < max_beep_count + 5) { // Only beep as long as we're supposed to next_buzz = ms + ((always || runout_beep < max_beep_count) ? 1000 : 500); BUZZ(50, 880 - (runout_beep & 1) * 220); runout_beep++; } } } inline void first_impatient_beep(const int8_t max_beep_count) { impatient_beep(max_beep_count, true); } #else inline void impatient_beep(const int8_t, const bool=false) {} inline void first_impatient_beep(const int8_t) {} #endif /** * Ensure a safe temperature for extrusion * * - Fail if the TARGET temperature is too low * - Display LCD placard with temperature status * - Return when heating is done or aborted * * Returns 'true' if heating was completed, 'false' for abort */ static bool ensure_safe_temperature(const bool wait=true, const PauseMode mode=PAUSE_MODE_SAME) { DEBUG_SECTION(est, "ensure_safe_temperature", true); DEBUG_ECHOLNPGM("... wait:", wait, " mode:", mode); #if ENABLED(PREVENT_COLD_EXTRUSION) if (!DEBUGGING(DRYRUN) && thermalManager.targetTooColdToExtrude(active_extruder)) thermalManager.setTargetHotend(thermalManager.extrude_min_temp, active_extruder); #endif ui.pause_show_message(PAUSE_MESSAGE_HEATING, mode); if (wait) return thermalManager.wait_for_hotend(active_extruder); // Allow interruption by Emergency Parser M108 wait_for_heatup = TERN1(PREVENT_COLD_EXTRUSION, !thermalManager.allow_cold_extrude); while (wait_for_heatup && ABS(thermalManager.wholeDegHotend(active_extruder) - thermalManager.degTargetHotend(active_extruder)) > (TEMP_WINDOW)) idle(); wait_for_heatup = false; #if ENABLED(PREVENT_COLD_EXTRUSION) // A user can cancel wait-for-heating with M108 if (!DEBUGGING(DRYRUN) && thermalManager.targetTooColdToExtrude(active_extruder)) { SERIAL_ECHO_MSG(STR_ERR_HOTEND_TOO_COLD); return false; } #endif return true; } /** * Load filament into the hotend * * - Fail if the a safe temperature was not reached * - If pausing for confirmation, wait for a click or M108 * - Show "wait for load" placard * - Load and purge filament * - Show "Purge more" / "Continue" menu * - Return when "Continue" is selected * * Returns 'true' if load was completed, 'false' for abort */ bool load_filament(const_float_t slow_load_length/*=0*/, const_float_t fast_load_length/*=0*/, const_float_t purge_length/*=0*/, const int8_t max_beep_count/*=0*/, const bool show_lcd/*=false*/, const bool pause_for_user/*=false*/, const PauseMode mode/*=PAUSE_MODE_PAUSE_PRINT*/ DXC_ARGS ) { DEBUG_SECTION(lf, "load_filament", true); DEBUG_ECHOLNPGM("... slowlen:", slow_load_length, " fastlen:", fast_load_length, " purgelen:", purge_length, " maxbeep:", max_beep_count, " showlcd:", show_lcd, " pauseforuser:", pause_for_user, " pausemode:", mode DXC_SAY); if (!ensure_safe_temperature(false, mode)) { if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_STATUS, mode); return false; } if (pause_for_user) { if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_INSERT, mode); SERIAL_ECHO_MSG(_PMSG(STR_FILAMENT_CHANGE_INSERT)); first_impatient_beep(max_beep_count); KEEPALIVE_STATE(PAUSED_FOR_USER); wait_for_user = true; // LCD click or M108 will clear this TERN_(EXTENSIBLE_UI, ExtUI::onUserConfirmRequired(GET_TEXT_F(MSG_FILAMENTLOAD))); #if ENABLED(HOST_PROMPT_SUPPORT) const char tool = '0' + TERN0(MULTI_FILAMENT_SENSOR, active_extruder); hostui.prompt_do(PROMPT_USER_CONTINUE, F("Load Filament T"), tool, FPSTR(CONTINUE_STR)); #endif while (wait_for_user) { impatient_beep(max_beep_count); #if ALL(FILAMENT_CHANGE_RESUME_ON_INSERT, FILAMENT_RUNOUT_SENSOR) #if MULTI_FILAMENT_SENSOR #define _CASE_INSERTED(N) case N-1: if (READ(FIL_RUNOUT##N##_PIN) != FIL_RUNOUT##N##_STATE) wait_for_user = false; break; switch (active_extruder) { REPEAT_1(NUM_RUNOUT_SENSORS, _CASE_INSERTED) } #else if (READ(FIL_RUNOUT_PIN) != FIL_RUNOUT_STATE) wait_for_user = false; #endif #endif idle_no_sleep(); } } if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_LOAD, mode); #if ENABLED(DUAL_X_CARRIAGE) const int8_t saved_ext = active_extruder; const bool saved_ext_dup_mode = extruder_duplication_enabled; set_duplication_enabled(false, DXC_ext); #endif TERN_(BELTPRINTER, do_blocking_move_to_xy(0.00, 50.00)); TERN_(MPCTEMP, MPC::e_paused = true); // Slow Load filament if (slow_load_length) unscaled_e_move(slow_load_length, FILAMENT_CHANGE_SLOW_LOAD_FEEDRATE); // Fast Load Filament if (fast_load_length) { #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0 const float saved_acceleration = planner.settings.retract_acceleration; planner.settings.retract_acceleration = FILAMENT_CHANGE_FAST_LOAD_ACCEL; #endif unscaled_e_move(fast_load_length, FILAMENT_CHANGE_FAST_LOAD_FEEDRATE); #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0 planner.settings.retract_acceleration = saved_acceleration; #endif } #if ENABLED(DUAL_X_CARRIAGE) // Tie the two extruders movement back together. set_duplication_enabled(saved_ext_dup_mode, saved_ext); #endif #if ENABLED(ADVANCED_PAUSE_CONTINUOUS_PURGE) if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_PURGE); TERN_(EXTENSIBLE_UI, ExtUI::onUserConfirmRequired(GET_TEXT_F(MSG_FILAMENT_CHANGE_PURGE))); TERN_(HOST_PROMPT_SUPPORT, hostui.continue_prompt(GET_TEXT_F(MSG_FILAMENT_CHANGE_PURGE))); wait_for_user = true; // A click or M108 breaks the purge_length loop for (float purge_count = purge_length; purge_count > 0 && wait_for_user; --purge_count) unscaled_e_move(1, ADVANCED_PAUSE_PURGE_FEEDRATE); wait_for_user = false; #else do { if (purge_length > 0) { // "Wait for filament purge" if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_PURGE); // Extrude filament to get into hotend unscaled_e_move(purge_length, ADVANCED_PAUSE_PURGE_FEEDRATE); } TERN_(HOST_PROMPT_SUPPORT, hostui.filament_load_prompt()); // Initiate another host prompt. #if M600_PURGE_MORE_RESUMABLE if (show_lcd) { // Show "Purge More" / "Resume" menu and wait for reply KEEPALIVE_STATE(PAUSED_FOR_USER); wait_for_user = false; #if ANY(HAS_MARLINUI_MENU, EXTENSIBLE_UI) ui.pause_show_message(PAUSE_MESSAGE_OPTION); // MarlinUI and MKS UI also set PAUSE_RESPONSE_WAIT_FOR #else pause_menu_response = PAUSE_RESPONSE_WAIT_FOR; #endif while (pause_menu_response == PAUSE_RESPONSE_WAIT_FOR) idle_no_sleep(); } #endif // Keep looping if "Purge More" was selected } while (TERN0(M600_PURGE_MORE_RESUMABLE, pause_menu_response == PAUSE_RESPONSE_EXTRUDE_MORE)); #endif TERN_(MPCTEMP, MPC::e_paused = false); TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_end()); return true; } /** * Disabling E steppers for manual filament change should be fine * as long as users don't spin the E motor ridiculously fast and * send current back to their board, potentially frying it. */ inline void disable_active_extruder() { #if HAS_EXTRUDERS stepper.DISABLE_EXTRUDER(active_extruder); safe_delay(100); #endif } /** * Unload filament from the hotend * * - Fail if the a safe temperature was not reached * - Show "wait for unload" placard * - Retract, pause, then unload filament * - Disable E stepper (on most machines) * * Returns 'true' if unload was completed, 'false' for abort */ bool unload_filament(const_float_t unload_length, const bool show_lcd/*=false*/, const PauseMode mode/*=PAUSE_MODE_PAUSE_PRINT*/ #if ALL(FILAMENT_UNLOAD_ALL_EXTRUDERS, MIXING_EXTRUDER) , const_float_t mix_multiplier/*=1.0*/ #endif ) { DEBUG_SECTION(uf, "unload_filament", true); DEBUG_ECHOLNPGM("... unloadlen:", unload_length, " showlcd:", show_lcd, " mode:", mode #if ALL(FILAMENT_UNLOAD_ALL_EXTRUDERS, MIXING_EXTRUDER) , " mixmult:", mix_multiplier #endif ); #if !ALL(FILAMENT_UNLOAD_ALL_EXTRUDERS, MIXING_EXTRUDER) constexpr float mix_multiplier = 1.0f; #endif if (!ensure_safe_temperature(false, mode)) { if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_STATUS); return false; } if (show_lcd) ui.pause_show_message(PAUSE_MESSAGE_UNLOAD, mode); // Retract filament unscaled_e_move(-(FILAMENT_UNLOAD_PURGE_RETRACT) * mix_multiplier, (PAUSE_PARK_RETRACT_FEEDRATE) * mix_multiplier); // Wait for filament to cool safe_delay(FILAMENT_UNLOAD_PURGE_DELAY); // Quickly purge unscaled_e_move((FILAMENT_UNLOAD_PURGE_RETRACT + FILAMENT_UNLOAD_PURGE_LENGTH) * mix_multiplier, (FILAMENT_UNLOAD_PURGE_FEEDRATE) * mix_multiplier); // Unload filament #if FILAMENT_CHANGE_UNLOAD_ACCEL > 0 const float saved_acceleration = planner.settings.retract_acceleration; planner.settings.retract_acceleration = FILAMENT_CHANGE_UNLOAD_ACCEL; #endif unscaled_e_move(unload_length * mix_multiplier, (FILAMENT_CHANGE_UNLOAD_FEEDRATE) * mix_multiplier); #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0 planner.settings.retract_acceleration = saved_acceleration; #endif // Disable the Extruder for manual change disable_active_extruder(); return true; } // public: /** * Pause procedure * * - Abort if already paused * - Send host action for pause, if configured * - Abort if TARGET temperature is too low * - Display "wait for start of filament change" (if a length was specified) * - Initial retract, if current temperature is hot enough * - Park the nozzle at the given position * - Call unload_filament (if a length was specified) * * Return 'true' if pause was completed, 'false' for abort */ uint8_t did_pause_print = 0; bool pause_print(const_float_t retract, const xyz_pos_t &park_point, const bool show_lcd/*=false*/, const_float_t unload_length/*=0*/ DXC_ARGS) { DEBUG_SECTION(pp, "pause_print", true); DEBUG_ECHOLNPGM("... park.x:", park_point.x, " y:", park_point.y, " z:", park_point.z, " unloadlen:", unload_length, " showlcd:", show_lcd DXC_SAY); if (did_pause_print) return false; // already paused #if ENABLED(HOST_ACTION_COMMANDS) #ifdef ACTION_ON_PAUSED hostui.paused(); #elif defined(ACTION_ON_PAUSE) hostui.pause(); #endif #endif TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_open(PROMPT_INFO, F("Pause"), FPSTR(DISMISS_STR))); // Indicate that the printer is paused ++did_pause_print; // Pause the print job and timer #if HAS_MEDIA const bool was_sd_printing = IS_SD_PRINTING(); if (was_sd_printing) { card.pauseSDPrint(); ++did_pause_print; // Indicate SD pause also } #endif print_job_timer.pause(); // Save current position resume_position = current_position; // Will the nozzle be parking? const bool do_park = !axes_should_home(); #if ENABLED(POWER_LOSS_RECOVERY) // Save PLR info in case the power goes out while parked const float park_raise = do_park ? nozzle.park_mode_0_height(park_point.z) - current_position.z : POWER_LOSS_ZRAISE; if (was_sd_printing && recovery.enabled) recovery.save(true, park_raise, do_park); #endif // Wait for buffered blocks to complete planner.synchronize(); #if ALL(ADVANCED_PAUSE_FANS_PAUSE, HAS_FAN) thermalManager.set_fans_paused(true); #endif // Initial retract before move to filament change position if (retract && thermalManager.hotEnoughToExtrude(active_extruder)) { DEBUG_ECHOLNPGM("... retract:", retract); #if ENABLED(AUTO_BED_LEVELING_UBL) const bool leveling_was_enabled = planner.leveling_active; // save leveling state set_bed_leveling_enabled(false); // turn off leveling #endif unscaled_e_move(retract, PAUSE_PARK_RETRACT_FEEDRATE); TERN_(AUTO_BED_LEVELING_UBL, set_bed_leveling_enabled(leveling_was_enabled)); // restore leveling } // If axes don't need to home then the nozzle can park if (do_park) nozzle.park(0, park_point); // Park the nozzle by doing a Minimum Z Raise followed by an XY Move if (!do_park) LCD_MESSAGE(MSG_PARK_FAILED); #if ENABLED(DUAL_X_CARRIAGE) const int8_t saved_ext = active_extruder; const bool saved_ext_dup_mode = extruder_duplication_enabled; set_duplication_enabled(false, DXC_ext); #endif // Unload the filament, if specified if (unload_length) unload_filament(unload_length, show_lcd, PAUSE_MODE_CHANGE_FILAMENT); TERN_(DUAL_X_CARRIAGE, set_duplication_enabled(saved_ext_dup_mode, saved_ext)); // Disable the Extruder for manual change disable_active_extruder(); return true; } /** * For Paused Print: * - Show "Press button (or M108) to resume" * * For Filament Change: * - Show "Insert filament and press button to continue" * * - Wait for a click before returning * - Heaters can time out and must reheat before continuing * * Used by M125 and M600 */ void show_continue_prompt(const bool is_reload) { DEBUG_SECTION(scp, "pause_print", true); DEBUG_ECHOLNPGM("... is_reload:", is_reload); ui.pause_show_message(is_reload ? PAUSE_MESSAGE_INSERT : PAUSE_MESSAGE_WAITING); SERIAL_ECHO_START(); SERIAL_ECHO(is_reload ? F(_PMSG(STR_FILAMENT_CHANGE_INSERT) "\n") : F(_PMSG(STR_FILAMENT_CHANGE_WAIT) "\n")); } void wait_for_confirmation(const bool is_reload/*=false*/, const int8_t max_beep_count/*=0*/ DXC_ARGS) { DEBUG_SECTION(wfc, "wait_for_confirmation", true); DEBUG_ECHOLNPGM("... is_reload:", is_reload, " maxbeep:", max_beep_count DXC_SAY); bool nozzle_timed_out = false; show_continue_prompt(is_reload); first_impatient_beep(max_beep_count); // Start the heater idle timers const millis_t nozzle_timeout = SEC_TO_MS(PAUSE_PARK_NOZZLE_TIMEOUT); HOTEND_LOOP() thermalManager.heater_idle[e].start(nozzle_timeout); #if ENABLED(DUAL_X_CARRIAGE) const int8_t saved_ext = active_extruder; const bool saved_ext_dup_mode = extruder_duplication_enabled; set_duplication_enabled(false, DXC_ext); #endif // Wait for filament insert by user and press button KEEPALIVE_STATE(PAUSED_FOR_USER); TERN_(HOST_PROMPT_SUPPORT, hostui.continue_prompt(GET_TEXT_F(MSG_NOZZLE_PARKED))); TERN_(EXTENSIBLE_UI, ExtUI::onUserConfirmRequired(GET_TEXT_F(MSG_NOZZLE_PARKED))); wait_for_user = true; // LCD click or M108 will clear this while (wait_for_user) { impatient_beep(max_beep_count); // If the nozzle has timed out... if (!nozzle_timed_out) HOTEND_LOOP() nozzle_timed_out |= thermalManager.heater_idle[e].timed_out; // Wait for the user to press the button to re-heat the nozzle, then // re-heat the nozzle, re-show the continue prompt, restart idle timers, start over if (nozzle_timed_out) { ui.pause_show_message(PAUSE_MESSAGE_HEAT); SERIAL_ECHO_MSG(_PMSG(STR_FILAMENT_CHANGE_HEAT)); TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_do(PROMPT_USER_CONTINUE, GET_TEXT_F(MSG_HEATER_TIMEOUT), GET_TEXT_F(MSG_REHEAT))); #if ENABLED(TOUCH_UI_FTDI_EVE) ExtUI::onUserConfirmRequired(GET_TEXT_F(MSG_FTDI_HEATER_TIMEOUT)); #elif ENABLED(EXTENSIBLE_UI) ExtUI::onUserConfirmRequired(GET_TEXT_F(MSG_HEATER_TIMEOUT)); #endif TERN_(HAS_RESUME_CONTINUE, wait_for_user_response(0, true)); // Wait for LCD click or M108 TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_do(PROMPT_INFO, GET_TEXT_F(MSG_REHEATING))); LCD_MESSAGE(MSG_REHEATING); // Re-enable the heaters if they timed out HOTEND_LOOP() thermalManager.reset_hotend_idle_timer(e); // Wait for the heaters to reach the target temperatures ensure_safe_temperature(false); // Show the prompt to continue show_continue_prompt(is_reload); // Start the heater idle timers const millis_t nozzle_timeout = SEC_TO_MS(PAUSE_PARK_NOZZLE_TIMEOUT); HOTEND_LOOP() thermalManager.heater_idle[e].start(nozzle_timeout); TERN_(HOST_PROMPT_SUPPORT, hostui.continue_prompt(GET_TEXT_F(MSG_REHEATDONE))); #if ENABLED(EXTENSIBLE_UI) ExtUI::onUserConfirmRequired(GET_TEXT_F(MSG_REHEATDONE)); #else LCD_MESSAGE(MSG_REHEATDONE); #endif IF_DISABLED(PAUSE_REHEAT_FAST_RESUME, wait_for_user = true); nozzle_timed_out = false; first_impatient_beep(max_beep_count); } idle_no_sleep(); } TERN_(DUAL_X_CARRIAGE, set_duplication_enabled(saved_ext_dup_mode, saved_ext)); } /** * Resume or Start print procedure * * - If not paused, do nothing and return * - Reset heater idle timers * - Load filament if specified, but only if: * - a nozzle timed out, or * - the nozzle is already heated. * - Display "wait for print to resume" * - Retract to prevent oozing * - Move the nozzle back to resume_position * - Unretract * - Re-prime the nozzle... * - FWRETRACT: Recover/prime from the prior G10. * - !FWRETRACT: Retract by resume_position.e, if negative. * Not sure how this logic comes into use. * - Sync the planner E to resume_position.e * - Send host action for resume, if configured * - Resume the current SD print job, if any */ void resume_print(const_float_t slow_load_length/*=0*/, const_float_t fast_load_length/*=0*/, const_float_t purge_length/*=ADVANCED_PAUSE_PURGE_LENGTH*/, const int8_t max_beep_count/*=0*/, const celsius_t targetTemp/*=0*/ DXC_ARGS) { DEBUG_SECTION(rp, "resume_print", true); DEBUG_ECHOLNPGM("... slowlen:", slow_load_length, " fastlen:", fast_load_length, " purgelen:", purge_length, " maxbeep:", max_beep_count, " targetTemp:", targetTemp DXC_SAY); /* SERIAL_ECHOLNPGM( "start of resume_print()\ndual_x_carriage_mode:", dual_x_carriage_mode, "\nextruder_duplication_enabled:", extruder_duplication_enabled, "\nactive_extruder:", active_extruder, "\n" ); //*/ if (!did_pause_print) return; // Re-enable the heaters if they timed out bool nozzle_timed_out = false; HOTEND_LOOP() { nozzle_timed_out |= thermalManager.heater_idle[e].timed_out; thermalManager.reset_hotend_idle_timer(e); } if (targetTemp > thermalManager.degTargetHotend(active_extruder)) thermalManager.setTargetHotend(targetTemp, active_extruder); // Load the new filament load_filament(slow_load_length, fast_load_length, purge_length, max_beep_count, true, nozzle_timed_out, PAUSE_MODE_SAME DXC_PASS); if (targetTemp > 0) { thermalManager.setTargetHotend(targetTemp, active_extruder); thermalManager.wait_for_hotend(active_extruder, false); } ui.pause_show_message(PAUSE_MESSAGE_RESUME); // Check Temperature before moving hotend ensure_safe_temperature(DISABLED(BELTPRINTER)); // Retract to prevent oozing unscaled_e_move(-(PAUSE_PARK_RETRACT_LENGTH), feedRate_t(PAUSE_PARK_RETRACT_FEEDRATE)); if (!axes_should_home()) { // Move XY back to saved position destination.set(resume_position.x, resume_position.y, current_position.z, current_position.e); prepare_internal_move_to_destination(NOZZLE_PARK_XY_FEEDRATE); // Move Z back to saved position destination.z = resume_position.z; prepare_internal_move_to_destination(NOZZLE_PARK_Z_FEEDRATE); } #if ENABLED(AUTO_BED_LEVELING_UBL) const bool leveling_was_enabled = planner.leveling_active; // save leveling state set_bed_leveling_enabled(false); // turn off leveling #endif // Unretract unscaled_e_move(PAUSE_PARK_RETRACT_LENGTH, feedRate_t(PAUSE_PARK_RETRACT_FEEDRATE)); TERN_(AUTO_BED_LEVELING_UBL, set_bed_leveling_enabled(leveling_was_enabled)); // restore leveling // Intelligent resuming #if ENABLED(FWRETRACT) // If retracted before goto pause if (fwretract.retracted[active_extruder]) unscaled_e_move(-fwretract.settings.retract_length, fwretract.settings.retract_feedrate_mm_s); #endif // If resume_position is negative if (resume_position.e < 0) unscaled_e_move(resume_position.e, feedRate_t(PAUSE_PARK_RETRACT_FEEDRATE)); #ifdef ADVANCED_PAUSE_RESUME_PRIME if (ADVANCED_PAUSE_RESUME_PRIME != 0) unscaled_e_move(ADVANCED_PAUSE_RESUME_PRIME, feedRate_t(ADVANCED_PAUSE_PURGE_FEEDRATE)); #endif // Now all extrusion positions are resumed and ready to be confirmed // Set extruder to saved position planner.set_e_position_mm((destination.e = current_position.e = resume_position.e)); ui.pause_show_message(PAUSE_MESSAGE_STATUS); #ifdef ACTION_ON_RESUMED hostui.resumed(); #elif defined(ACTION_ON_RESUME) hostui.resume(); #endif --did_pause_print; TERN_(HOST_PROMPT_SUPPORT, hostui.prompt_open(PROMPT_INFO, F("Resuming"), FPSTR(DISMISS_STR))); // Resume the print job timer if it was running if (print_job_timer.isPaused()) print_job_timer.start(); #if HAS_MEDIA if (did_pause_print) { --did_pause_print; card.startOrResumeFilePrinting(); // Write PLR now to update the z axis value TERN_(POWER_LOSS_RECOVERY, if (recovery.enabled) recovery.save(true)); } #endif #if ENABLED(ADVANCED_PAUSE_FANS_PAUSE) && HAS_FAN thermalManager.set_fans_paused(false); #endif TERN_(HAS_FILAMENT_SENSOR, runout.reset()); ui.reset_status(); ui.return_to_status(); } #endif // ADVANCED_PAUSE_FEATURE
2301_81045437/Marlin
Marlin/src/feature/pause.cpp
C++
agpl-3.0
24,339
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * feature/pause.h - Pause feature support functions * This may be combined with related G-codes if features are consolidated. */ #include "../inc/MarlinConfigPre.h" #if ENABLED(ADVANCED_PAUSE_FEATURE) #include "../libs/nozzle.h" enum PauseMode : char { PAUSE_MODE_SAME, PAUSE_MODE_PAUSE_PRINT, PAUSE_MODE_CHANGE_FILAMENT, PAUSE_MODE_LOAD_FILAMENT, PAUSE_MODE_UNLOAD_FILAMENT }; enum PauseMessage : char { PAUSE_MESSAGE_PARKING, PAUSE_MESSAGE_CHANGING, PAUSE_MESSAGE_WAITING, PAUSE_MESSAGE_INSERT, PAUSE_MESSAGE_LOAD, PAUSE_MESSAGE_UNLOAD, PAUSE_MESSAGE_PURGE, PAUSE_MESSAGE_OPTION, PAUSE_MESSAGE_RESUME, PAUSE_MESSAGE_HEAT, PAUSE_MESSAGE_HEATING, PAUSE_MESSAGE_STATUS, PAUSE_MESSAGE_COUNT }; #if M600_PURGE_MORE_RESUMABLE // Input methods can Purge More, Resume, or request input enum PauseMenuResponse : char { PAUSE_RESPONSE_WAIT_FOR, PAUSE_RESPONSE_EXTRUDE_MORE, PAUSE_RESPONSE_RESUME_PRINT }; extern PauseMenuResponse pause_menu_response; extern PauseMode pause_mode; #endif typedef struct FilamentChangeSettings { #if ENABLED(CONFIGURE_FILAMENT_CHANGE) float load_length, unload_length; #else static constexpr float load_length = FILAMENT_CHANGE_FAST_LOAD_LENGTH, unload_length = FILAMENT_CHANGE_UNLOAD_LENGTH; #endif } fil_change_settings_t; #if ENABLED(CONFIGURE_FILAMENT_CHANGE) extern fil_change_settings_t fc_settings[EXTRUDERS]; #else constexpr fil_change_settings_t fc_settings[EXTRUDERS]; #endif extern uint8_t did_pause_print; #define DXC_PARAMS OPTARG(DUAL_X_CARRIAGE, const int8_t DXC_ext=-1) #define DXC_ARGS OPTARG(DUAL_X_CARRIAGE, const int8_t DXC_ext) #define DXC_PASS OPTARG(DUAL_X_CARRIAGE, DXC_ext) #define DXC_SAY OPTARG(DUAL_X_CARRIAGE, " dxc:", int(DXC_ext)) // Pause the print. If unload_length is set, do a Filament Unload bool pause_print( const_float_t retract, // (mm) Retraction length const xyz_pos_t &park_point, // Parking XY Position and Z Raise const bool show_lcd=false, // Set LCD status messages? const_float_t unload_length=0 // (mm) Filament Change Unload Length - 0 to skip DXC_PARAMS // Dual-X-Carriage extruder index ); void wait_for_confirmation( const bool is_reload=false, // Reload Filament? (otherwise Resume Print) const int8_t max_beep_count=0 // Beep alert for attention DXC_PARAMS // Dual-X-Carriage extruder index ); void resume_print( const_float_t slow_load_length=0, // (mm) Slow Load Length for finishing move const_float_t fast_load_length=0, // (mm) Fast Load Length for initial move const_float_t purge_length=ADVANCED_PAUSE_PURGE_LENGTH, // (mm) Purge length const int8_t max_beep_count=0, // Beep alert for attention const celsius_t targetTemp=0 // (°C) A target temperature for the hotend DXC_PARAMS // Dual-X-Carriage extruder index ); bool load_filament( const_float_t slow_load_length=0, // (mm) Slow Load Length for finishing move const_float_t fast_load_length=0, // (mm) Fast Load Length for initial move const_float_t purge_length=0, // (mm) Purge length const int8_t max_beep_count=0, // Beep alert for attention const bool show_lcd=false, // Set LCD status messages? const bool pause_for_user=false, // Pause for user before returning? const PauseMode mode=PAUSE_MODE_PAUSE_PRINT // Pause Mode to apply DXC_PARAMS // Dual-X-Carriage extruder index ); bool unload_filament( const_float_t unload_length, // (mm) Filament Unload Length - 0 to skip const bool show_lcd=false, // Set LCD status messages? const PauseMode mode=PAUSE_MODE_PAUSE_PRINT // Pause Mode to apply #if ALL(FILAMENT_UNLOAD_ALL_EXTRUDERS, MIXING_EXTRUDER) , const_float_t mix_multiplier=1.0f // Extrusion multiplier (for a Mixing Extruder) #endif ); #else // !ADVANCED_PAUSE_FEATURE constexpr uint8_t did_pause_print = 0; #endif // !ADVANCED_PAUSE_FEATURE
2301_81045437/Marlin
Marlin/src/feature/pause.h
C++
agpl-3.0
5,563
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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/>. * */ /** * power.cpp - power control */ #include "../inc/MarlinConfigPre.h" #if ANY(PSU_CONTROL, AUTO_POWER_CONTROL) #include "power.h" #include "../module/planner.h" #include "../module/stepper/indirection.h" // for restore_stepper_drivers #include "../module/temperature.h" #include "../MarlinCore.h" #if ENABLED(MAX7219_REINIT_ON_POWERUP) #include "max7219.h" #endif #if ENABLED(PS_OFF_SOUND) #include "../libs/buzzer.h" #endif #if defined(PSU_POWERUP_GCODE) || defined(PSU_POWEROFF_GCODE) #include "../gcode/gcode.h" #endif Power powerManager; bool Power::psu_on; #if ENABLED(AUTO_POWER_CONTROL) #include "../module/stepper.h" #include "../module/temperature.h" #if ALL(USE_CONTROLLER_FAN, AUTO_POWER_CONTROLLERFAN) #include "controllerfan.h" #endif #if ANY(LASER_FEATURE, SPINDLE_FEATURE) #include "spindle_laser.h" #endif millis_t Power::lastPowerOn; #endif #if PSU_TRACK_STATE_MS millis_t Power::last_state_change_ms = 0; #endif /** * Initialize pins & state for the power manager. * */ void Power::init() { psu_on = ENABLED(PSU_DEFAULT_OFF); // Set opposite state to get full power_off/on TERN(PSU_DEFAULT_OFF, power_off(), power_on()); } /** * Power on if the power is currently off. * Restores stepper drivers and processes any PSU_POWERUP_GCODE. * */ void Power::power_on() { #if ENABLED(AUTO_POWER_CONTROL) const millis_t now = millis(); lastPowerOn = now + !now; #endif if (psu_on) return; #if ANY(POWER_OFF_TIMER, POWER_OFF_WAIT_FOR_COOLDOWN) cancelAutoPowerOff(); #endif OUT_WRITE(PS_ON_PIN, PSU_ACTIVE_STATE); #if ENABLED(PSU_OFF_REDUNDANT) OUT_WRITE(PS_ON1_PIN, TERN_(PSU_OFF_REDUNDANT_INVERTED, !)PSU_ACTIVE_STATE); #endif TERN_(PSU_TRACK_STATE_MS, last_state_change_ms = millis()); psu_on = true; safe_delay(PSU_POWERUP_DELAY); restore_stepper_drivers(); TERN_(MAX7219_REINIT_ON_POWERUP, max7219.init()); TERN_(HAS_TRINAMIC_CONFIG, safe_delay(PSU_POWERUP_DELAY)); #ifdef PSU_POWERUP_GCODE gcode.process_subcommands_now(F(PSU_POWERUP_GCODE)); #endif } /** * Power off if the power is currently on. * Processes any PSU_POWEROFF_GCODE and makes a PS_OFF_SOUND if enabled. */ void Power::power_off() { TERN_(HAS_SUICIDE, suicide()); if (!psu_on) return; SERIAL_ECHOLNPGM(STR_POWEROFF); #ifdef PSU_POWEROFF_GCODE gcode.process_subcommands_now(F(PSU_POWEROFF_GCODE)); #endif #if ENABLED(PS_OFF_SOUND) BUZZ(1000, 659); #endif OUT_WRITE(PS_ON_PIN, !PSU_ACTIVE_STATE); #if ENABLED(PSU_OFF_REDUNDANT) OUT_WRITE(PS_ON1_PIN, IF_DISABLED(PSU_OFF_REDUNDANT_INVERTED, !)PSU_ACTIVE_STATE); #endif TERN_(PSU_TRACK_STATE_MS, last_state_change_ms = millis()); psu_on = false; #if ANY(POWER_OFF_TIMER, POWER_OFF_WAIT_FOR_COOLDOWN) cancelAutoPowerOff(); #endif } #if ANY(AUTO_POWER_CONTROL, POWER_OFF_WAIT_FOR_COOLDOWN) bool Power::is_cooling_needed() { #if HAS_HOTEND && AUTO_POWER_E_TEMP HOTEND_LOOP() if (thermalManager.degHotend(e) >= (AUTO_POWER_E_TEMP)) return true; #endif #if HAS_HEATED_CHAMBER && AUTO_POWER_CHAMBER_TEMP if (thermalManager.degChamber() >= (AUTO_POWER_CHAMBER_TEMP)) return true; #endif #if HAS_COOLER && AUTO_POWER_COOLER_TEMP if (thermalManager.degCooler() >= (AUTO_POWER_COOLER_TEMP)) return true; #endif return false; } #endif #if ANY(POWER_OFF_TIMER, POWER_OFF_WAIT_FOR_COOLDOWN) #if ENABLED(POWER_OFF_TIMER) millis_t Power::power_off_time = 0; void Power::setPowerOffTimer(const millis_t delay_ms) { power_off_time = millis() + delay_ms; } #endif #if ENABLED(POWER_OFF_WAIT_FOR_COOLDOWN) bool Power::power_off_on_cooldown = false; void Power::setPowerOffOnCooldown(const bool ena) { power_off_on_cooldown = ena; } #endif void Power::cancelAutoPowerOff() { TERN_(POWER_OFF_TIMER, power_off_time = 0); TERN_(POWER_OFF_WAIT_FOR_COOLDOWN, power_off_on_cooldown = false); } void Power::checkAutoPowerOff() { if (TERN1(POWER_OFF_TIMER, !power_off_time) && TERN1(POWER_OFF_WAIT_FOR_COOLDOWN, !power_off_on_cooldown)) return; if (TERN0(POWER_OFF_WAIT_FOR_COOLDOWN, power_off_on_cooldown && is_cooling_needed())) return; if (TERN0(POWER_OFF_TIMER, power_off_time && PENDING(millis(), power_off_time))) return; power_off(); } #endif // POWER_OFF_TIMER || POWER_OFF_WAIT_FOR_COOLDOWN #if ENABLED(AUTO_POWER_CONTROL) #ifndef POWER_TIMEOUT #define POWER_TIMEOUT 0 #endif /** * Check all conditions that would signal power needing to be on. * * @returns bool if power is needed */ bool Power::is_power_needed() { // If any of the stepper drivers are enabled... if (stepper.axis_enabled.bits) return true; if (printJobOngoing() || printingIsPaused()) return true; #if ENABLED(AUTO_POWER_FANS) FANS_LOOP(i) if (thermalManager.fan_speed[i]) return true; #endif #if ENABLED(AUTO_POWER_E_FANS) HOTEND_LOOP() if (thermalManager.autofan_speed[e]) return true; #endif #if ALL(USE_CONTROLLER_FAN, AUTO_POWER_CONTROLLERFAN) if (controllerFan.state()) return true; #endif #if ANY(LASER_FEATURE, SPINDLE_FEATURE) if (TERN0(AUTO_POWER_SPINDLE_LASER, cutter.enabled())) return true; #endif if (TERN0(AUTO_POWER_CHAMBER_FAN, thermalManager.chamberfan_speed)) return true; if (TERN0(AUTO_POWER_COOLER_FAN, thermalManager.coolerfan_speed)) return true; #if HAS_HOTEND HOTEND_LOOP() if (thermalManager.degTargetHotend(e) > 0 || thermalManager.temp_hotend[e].soft_pwm_amount > 0) return true; #endif if (TERN0(HAS_HEATED_BED, thermalManager.degTargetBed() > 0 || thermalManager.temp_bed.soft_pwm_amount > 0)) return true; return is_cooling_needed(); } /** * Check if we should power off automatically (POWER_TIMEOUT elapsed, !is_power_needed). * * @param pause pause the 'timer' */ void Power::check(const bool pause) { static millis_t nextPowerCheck = 0; const millis_t now = millis(); #if POWER_TIMEOUT > 0 static bool _pause = false; if (pause != _pause) { lastPowerOn = now + !now; _pause = pause; } if (pause) return; #endif if (ELAPSED(now, nextPowerCheck)) { nextPowerCheck = now + 2500UL; if (is_power_needed()) power_on(); else if (!lastPowerOn || (POWER_TIMEOUT > 0 && ELAPSED(now, lastPowerOn + SEC_TO_MS(POWER_TIMEOUT)))) power_off(); } } #if POWER_OFF_DELAY > 0 /** * Power off with a delay. Power off is triggered by check() after the delay. */ void Power::power_off_soon() { lastPowerOn = millis() - SEC_TO_MS(POWER_TIMEOUT) + SEC_TO_MS(POWER_OFF_DELAY); } #endif #endif // AUTO_POWER_CONTROL #endif // PSU_CONTROL || AUTO_POWER_CONTROL
2301_81045437/Marlin
Marlin/src/feature/power.cpp
C++
agpl-3.0
7,715
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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 /** * power.h - power control */ #if PIN_EXISTS(PS_ON_EDM) || (PIN_EXISTS(PS_ON1_EDM) && ENABLED(PSU_OFF_REDUNDANT)) #define PSU_TRACK_STATE_MS 1 #endif #if ANY(AUTO_POWER_CONTROL, POWER_OFF_TIMER, PSU_TRACK_STATE_MS) #include "../core/millis_t.h" #endif class Power { public: static bool psu_on; static void init(); static void power_on(); static void power_off(); #if PSU_TRACK_STATE_MS static millis_t last_state_change_ms; #endif #if ANY(POWER_OFF_TIMER, POWER_OFF_WAIT_FOR_COOLDOWN) #if ENABLED(POWER_OFF_TIMER) static millis_t power_off_time; static void setPowerOffTimer(const millis_t delay_ms); #endif #if ENABLED(POWER_OFF_WAIT_FOR_COOLDOWN) static bool power_off_on_cooldown; static void setPowerOffOnCooldown(const bool ena); #endif static void cancelAutoPowerOff(); static void checkAutoPowerOff(); #endif #if ENABLED(AUTO_POWER_CONTROL) && POWER_OFF_DELAY > 0 static void power_off_soon(); #else static void power_off_soon() { power_off(); } #endif #if ENABLED(AUTO_POWER_CONTROL) static void check(const bool pause); private: static millis_t lastPowerOn; static bool is_power_needed(); static bool is_cooling_needed(); #elif ENABLED(POWER_OFF_WAIT_FOR_COOLDOWN) private: static bool is_cooling_needed(); #endif }; extern Power powerManager;
2301_81045437/Marlin
Marlin/src/feature/power.h
C++
agpl-3.0
2,341
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfigPre.h" #if HAS_POWER_MONITOR #include "power_monitor.h" #if HAS_MARLINUI_MENU #include "../lcd/marlinui.h" #include "../lcd/lcdprint.h" #endif #include "../libs/numtostr.h" uint8_t PowerMonitor::flags; // = 0 #if ENABLED(POWER_MONITOR_CURRENT) pm_lpf_t<PowerMonitor::amps_adc_scale, PM_K_VALUE, PM_K_SCALE> PowerMonitor::amps; #endif #if ENABLED(POWER_MONITOR_VOLTAGE) pm_lpf_t<PowerMonitor::volts_adc_scale, PM_K_VALUE, PM_K_SCALE> PowerMonitor::volts; #endif millis_t PowerMonitor::display_item_ms; uint8_t PowerMonitor::display_item; PowerMonitor power_monitor; // Single instance - this calls the constructor #if HAS_MARLINUI_U8GLIB #if ENABLED(POWER_MONITOR_CURRENT) void PowerMonitor::draw_current() { const float amps = getAmps(); lcd_put_u8str(amps < 100 ? ftostr31ns(amps) : ui16tostr4rj((uint16_t)amps)); lcd_put_u8str(F("A")); } #endif #if ENABLED(POWER_MONITOR_VOLTAGE) void PowerMonitor::draw_voltage() { const float volts = getVolts(); lcd_put_u8str(volts < 100 ? ftostr31ns(volts) : ui16tostr4rj((uint16_t)volts)); lcd_put_u8str(F("V")); } #endif #if HAS_POWER_MONITOR_WATTS void PowerMonitor::draw_power() { const float power = getPower(); lcd_put_u8str(power < 100 ? ftostr31ns(power) : ui16tostr4rj((uint16_t)power)); lcd_put_u8str(F("W")); } #endif #endif // HAS_MARLINUI_U8GLIB #endif // HAS_POWER_MONITOR
2301_81045437/Marlin
Marlin/src/feature/power_monitor.cpp
C++
agpl-3.0
2,330
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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 PM_SAMPLE_RANGE HAL_ADC_RANGE #define PM_K_VALUE 6 #define PM_K_SCALE 6 template <const float & SCALE, int K_VALUE, int K_SCALE> struct pm_lpf_t { uint32_t filter_buf; float value; void add_sample(const uint16_t sample) { filter_buf += (uint32_t(sample) << K_SCALE) - (filter_buf >> K_VALUE); } void capture() { value = filter_buf * (SCALE * (1.0f / (1UL << (PM_K_VALUE + PM_K_SCALE)))); } void reset(uint16_t reset_value = 0) { filter_buf = uint32_t(reset_value) << (K_VALUE + K_SCALE); capture(); } }; class PowerMonitor { private: #if ENABLED(POWER_MONITOR_CURRENT) static constexpr float amps_adc_scale = (float(ADC_VREF_MV) / 1000.0f) / (POWER_MONITOR_VOLTS_PER_AMP * PM_SAMPLE_RANGE); static pm_lpf_t<amps_adc_scale, PM_K_VALUE, PM_K_SCALE> amps; #endif #if ENABLED(POWER_MONITOR_VOLTAGE) static constexpr float volts_adc_scale = (float(ADC_VREF_MV) / 1000.0f) / (POWER_MONITOR_VOLTS_PER_VOLT * PM_SAMPLE_RANGE); static pm_lpf_t<volts_adc_scale, PM_K_VALUE, PM_K_SCALE> volts; #endif public: static uint8_t flags; // M430 flags to display current static millis_t display_item_ms; static uint8_t display_item; PowerMonitor() { reset(); } enum PM_Display_Bit : uint8_t { PM_DISP_BIT_I, // Current display enable bit PM_DISP_BIT_V, // Voltage display enable bit PM_DISP_BIT_P // Power display enable bit }; #if ENABLED(POWER_MONITOR_CURRENT) FORCE_INLINE static float getAmps() { return amps.value + (POWER_MONITOR_CURRENT_OFFSET); } void add_current_sample(const uint16_t value) { amps.add_sample(value); } #endif #if ENABLED(POWER_MONITOR_VOLTAGE) FORCE_INLINE static float getVolts() { return volts.value + (POWER_MONITOR_VOLTAGE_OFFSET); } void add_voltage_sample(const uint16_t value) { volts.add_sample(value); } #else FORCE_INLINE static float getVolts() { return POWER_MONITOR_FIXED_VOLTAGE; } #endif #if HAS_POWER_MONITOR_WATTS FORCE_INLINE static float getPower() { return getAmps() * getVolts(); } #endif #if HAS_WIRED_LCD #if HAS_MARLINUI_U8GLIB && DISABLED(LIGHTWEIGHT_UI) FORCE_INLINE static bool display_enabled() { return flags != 0x00; } #endif #if ENABLED(POWER_MONITOR_CURRENT) static void draw_current(); FORCE_INLINE static bool current_display_enabled() { return TEST(flags, PM_DISP_BIT_I); } FORCE_INLINE static void set_current_display(const bool b) { SET_BIT_TO(flags, PM_DISP_BIT_I, b); } FORCE_INLINE static void toggle_current_display() { TBI(flags, PM_DISP_BIT_I); } #endif #if ENABLED(POWER_MONITOR_VOLTAGE) static void draw_voltage(); FORCE_INLINE static bool voltage_display_enabled() { return TEST(flags, PM_DISP_BIT_V); } FORCE_INLINE static void set_voltage_display(const bool b) { SET_BIT_TO(flags, PM_DISP_BIT_V, b); } FORCE_INLINE static void toggle_voltage_display() { TBI(flags, PM_DISP_BIT_V); } #endif #if HAS_POWER_MONITOR_WATTS static void draw_power(); FORCE_INLINE static bool power_display_enabled() { return TEST(flags, PM_DISP_BIT_P); } FORCE_INLINE static void set_power_display(const bool b) { SET_BIT_TO(flags, PM_DISP_BIT_P, b); } FORCE_INLINE static void toggle_power_display() { TBI(flags, PM_DISP_BIT_P); } #endif #endif static void reset() { flags = 0x00; #if ENABLED(POWER_MONITOR_CURRENT) amps.reset(); #endif #if ENABLED(POWER_MONITOR_VOLTAGE) volts.reset(); #endif #if HAS_MEDIA display_item_ms = 0; display_item = 0; #endif } static void capture_values() { #if ENABLED(POWER_MONITOR_CURRENT) amps.capture(); #endif #if ENABLED(POWER_MONITOR_VOLTAGE) volts.capture(); #endif } }; extern PowerMonitor power_monitor;
2301_81045437/Marlin
Marlin/src/feature/power_monitor.h
C++
agpl-3.0
4,744
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * feature/powerloss.cpp - Resume an SD print after power-loss */ #include "../inc/MarlinConfigPre.h" #if ENABLED(POWER_LOSS_RECOVERY) #include "powerloss.h" #include "../core/macros.h" #if ENABLED(EXTENSIBLE_UI) #include "../lcd/extui/ui_api.h" #endif bool PrintJobRecovery::enabled; // Initialized by settings.load() #if HAS_PLR_BED_THRESHOLD celsius_t PrintJobRecovery::bed_temp_threshold; // Initialized by settings.load() #endif MediaFile PrintJobRecovery::file; job_recovery_info_t PrintJobRecovery::info; const char PrintJobRecovery::filename[5] = "/PLR"; uint8_t PrintJobRecovery::queue_index_r; uint32_t PrintJobRecovery::cmd_sdpos, // = 0 PrintJobRecovery::sdpos[BUFSIZE]; #if HAS_PLR_UI_FLAG bool PrintJobRecovery::ui_flag_resume; // = false #endif #include "../sd/cardreader.h" #include "../lcd/marlinui.h" #include "../gcode/queue.h" #include "../gcode/gcode.h" #include "../module/motion.h" #include "../module/planner.h" #include "../module/printcounter.h" #include "../module/temperature.h" #include "../core/serial.h" #if HOMING_Z_WITH_PROBE #include "../module/probe.h" #endif #if ENABLED(FWRETRACT) #include "fwretract.h" #endif #define DEBUG_OUT ENABLED(DEBUG_POWER_LOSS_RECOVERY) #include "../core/debug_out.h" PrintJobRecovery recovery; #if DISABLED(BACKUP_POWER_SUPPLY) #undef POWER_LOSS_RETRACT_LEN // No retract at outage without backup power #endif #ifndef POWER_LOSS_RETRACT_LEN #define POWER_LOSS_RETRACT_LEN 0 #endif #ifndef POWER_LOSS_PURGE_LEN #define POWER_LOSS_PURGE_LEN 0 #endif // Allow power-loss recovery to be aborted #define PLR_CAN_ABORT #define PROCESS_SUBCOMMANDS_NOW(cmd) do{ \ if (TERN0(PLR_CAN_ABORT, card.flag.abort_sd_printing)) return; \ gcode.process_subcommands_now(cmd); \ }while(0) /** * Clear the recovery info */ void PrintJobRecovery::init() { memset(&info, 0, sizeof(info)); } /** * Enable or disable then call changed() */ void PrintJobRecovery::enable(const bool onoff) { enabled = onoff; changed(); } /** * The enabled state was changed: * - Enabled: Purge the job recovery file * - Disabled: Write the job recovery file */ void PrintJobRecovery::changed() { if (!enabled) purge(); else if (IS_SD_PRINTING()) save(true); TERN_(EXTENSIBLE_UI, ExtUI::onSetPowerLoss(enabled)); } /** * Check for Print Job Recovery during setup() * * If a saved state exists send 'M1000 S' to initiate job recovery. */ bool PrintJobRecovery::check() { //if (!card.isMounted()) card.mount(); bool success = false; if (card.isMounted()) { load(); success = valid(); if (!success) cancel(); else queue.inject(F("M1000S")); } return success; } /** * Delete the recovery file and clear the recovery data */ void PrintJobRecovery::purge() { init(); card.removeJobRecoveryFile(); } /** * Load the recovery data, if it exists */ void PrintJobRecovery::load() { if (exists()) { open(true); (void)file.read(&info, sizeof(info)); close(); } debug(F("Load")); } /** * Set info fields that won't change */ void PrintJobRecovery::prepare() { card.getAbsFilenameInCWD(info.sd_filename); // SD filename cmd_sdpos = 0; } /** * Save the current machine state to the power-loss recovery file */ void PrintJobRecovery::save(const bool force/*=false*/, const float zraise/*=POWER_LOSS_ZRAISE*/, const bool raised/*=false*/) { // We don't check IS_SD_PRINTING here so a save may occur during a pause #if SAVE_INFO_INTERVAL_MS > 0 static millis_t next_save_ms; // = 0 millis_t ms = millis(); #endif #ifndef POWER_LOSS_MIN_Z_CHANGE #define POWER_LOSS_MIN_Z_CHANGE 0.05 // Vase-mode-friendly out of the box #endif // Did Z change since the last call? if (force #if DISABLED(SAVE_EACH_CMD_MODE) // Always save state when enabled #if SAVE_INFO_INTERVAL_MS > 0 // Save if interval is elapsed || ELAPSED(ms, next_save_ms) #endif // Save if Z is above the last-saved position by some minimum height || current_position.z > info.current_position.z + POWER_LOSS_MIN_Z_CHANGE #endif ) { #if SAVE_INFO_INTERVAL_MS > 0 next_save_ms = ms + SAVE_INFO_INTERVAL_MS; #endif // Set Head and Foot to matching non-zero values if (!++info.valid_head) ++info.valid_head; // non-zero in sequence //if (!IS_SD_PRINTING()) info.valid_head = 0; info.valid_foot = info.valid_head; // Machine state // info.sdpos and info.current_position are pre-filled from the Stepper ISR info.feedrate = uint16_t(MMS_TO_MMM(feedrate_mm_s)); info.zraise = zraise; info.flag.raised = raised; // Was Z raised before power-off? TERN_(GCODE_REPEAT_MARKERS, info.stored_repeat = repeat); TERN_(HAS_HOME_OFFSET, info.home_offset = home_offset); TERN_(HAS_WORKSPACE_OFFSET, info.workspace_offset = workspace_offset); E_TERN_(info.active_extruder = active_extruder); #if DISABLED(NO_VOLUMETRICS) info.flag.volumetric_enabled = parser.volumetric_enabled; #if HAS_MULTI_EXTRUDER EXTRUDER_LOOP() info.filament_size[e] = planner.filament_size[e]; #else if (parser.volumetric_enabled) info.filament_size[0] = planner.filament_size[active_extruder]; #endif #endif #if HAS_HOTEND HOTEND_LOOP() info.target_temperature[e] = thermalManager.degTargetHotend(e); #endif TERN_(HAS_HEATED_BED, info.target_temperature_bed = thermalManager.degTargetBed()); TERN_(HAS_HEATED_CHAMBER, info.target_temperature_chamber = thermalManager.degTargetChamber()); TERN_(HAS_FAN, COPY(info.fan_speed, thermalManager.fan_speed)); #if HAS_LEVELING info.flag.leveling = planner.leveling_active; info.fade = TERN0(ENABLE_LEVELING_FADE_HEIGHT, planner.z_fade_height); #endif TERN_(GRADIENT_MIX, memcpy(&info.gradient, &mixer.gradient, sizeof(info.gradient))); #if ENABLED(FWRETRACT) COPY(info.retract, fwretract.current_retract); info.retract_hop = fwretract.current_hop; #endif // Elapsed print job time info.print_job_elapsed = print_job_timer.duration(); // Relative axis modes info.axis_relative = gcode.axis_relative; // Misc. Marlin flags info.flag.dryrun = !!(marlin_debug_flags & MARLIN_DEBUG_DRYRUN); info.flag.allow_cold_extrusion = TERN0(PREVENT_COLD_EXTRUSION, thermalManager.allow_cold_extrude); write(); } } #if PIN_EXISTS(POWER_LOSS) #if ENABLED(BACKUP_POWER_SUPPLY) void PrintJobRecovery::retract_and_lift(const_float_t zraise) { #if POWER_LOSS_RETRACT_LEN || POWER_LOSS_ZRAISE gcode.set_relative_mode(true); // Use relative coordinates #if POWER_LOSS_RETRACT_LEN // Retract filament now gcode.process_subcommands_now(F("G1 F3000 E-" STRINGIFY(POWER_LOSS_RETRACT_LEN))); #endif #if POWER_LOSS_ZRAISE // Raise the Z axis now if (zraise) gcode.process_subcommands_now(TS(F("G0Z"), p_float_t(zraise, 3))); #else UNUSED(zraise); #endif //gcode.axis_relative = info.axis_relative; planner.synchronize(); #endif } #endif #endif // POWER_LOSS_PIN #if PIN_EXISTS(POWER_LOSS) || ENABLED(DEBUG_POWER_LOSS_RECOVERY) /** * An outage was detected by a sensor pin. * - If not SD printing, let the machine turn off on its own with no "KILL" screen * - Disable all heaters first to save energy * - Save the recovery data for the current instant * - If backup power is available Retract E and Raise Z * - Go to the KILL screen */ void PrintJobRecovery::_outage(TERN_(DEBUG_POWER_LOSS_RECOVERY, const bool simulated/*=false*/)) { #if ENABLED(BACKUP_POWER_SUPPLY) static bool lock = false; if (lock) return; // No re-entrance from idle() during retract_and_lift() lock = true; #endif #if POWER_LOSS_ZRAISE // Get the limited Z-raise to do now or on resume const float zraise = _MAX(0, _MIN(current_position.z + POWER_LOSS_ZRAISE, Z_MAX_POS - 1) - current_position.z); #else constexpr float zraise = 0; #endif // Save the current position, distance that Z was (or should be) raised, // and a flag whether the raise was already done here. if (IS_SD_PRINTING()) save(true, zraise, ENABLED(BACKUP_POWER_SUPPLY)); // Tell the LCD about the outage, even though it is about to die TERN_(EXTENSIBLE_UI, ExtUI::onPowerLoss()); // Disable all heaters to reduce power loss thermalManager.disable_all_heaters(); #if ENABLED(BACKUP_POWER_SUPPLY) // Do a hard-stop of the steppers (with possibly a loud thud) quickstop_stepper(); // With backup power a retract and raise can be done now retract_and_lift(zraise); #endif if (TERN0(DEBUG_POWER_LOSS_RECOVERY, simulated)) { card.fileHasFinished(); current_position.reset(); sync_plan_position(); } else kill(GET_TEXT_F(MSG_OUTAGE_RECOVERY)); } #endif // POWER_LOSS_PIN || DEBUG_POWER_LOSS_RECOVERY /** * Save the recovery info the recovery file */ void PrintJobRecovery::write() { debug(F("Write")); open(false); file.seekSet(0); const int16_t ret = file.write(&info, sizeof(info)); if (ret == -1) DEBUG_ECHOLNPGM("Power-loss file write failed."); if (!file.close()) DEBUG_ECHOLNPGM("Power-loss file close failed."); } /** * Resume the saved print job */ void PrintJobRecovery::resume() { // Get these fields before any moves because stepper.cpp overwrites them const xyze_pos_t resume_pos = info.current_position; const uint32_t resume_sdpos = info.sdpos; // Apply the dry-run flag if enabled if (info.flag.dryrun) marlin_debug_flags |= MARLIN_DEBUG_DRYRUN; #if ENABLED(DEBUG_POWER_LOSS_RECOVERY) struct OnExit { uint8_t old_flags; OnExit() { old_flags = marlin_debug_flags; marlin_debug_flags |= MARLIN_DEBUG_ECHO; } ~OnExit() { marlin_debug_flags = old_flags; } } on_exit; #endif // Restore cold extrusion permission TERN_(PREVENT_COLD_EXTRUSION, thermalManager.allow_cold_extrude = info.flag.allow_cold_extrusion); #if HAS_LEVELING // Make sure leveling is off before any G92 and G28 PROCESS_SUBCOMMANDS_NOW(F("M420S0")); #endif #if HAS_HEATED_CHAMBER // Restore the chamber temperature const celsius_t ct = info.target_temperature_chamber; if (ct) PROCESS_SUBCOMMANDS_NOW(TS(F("M191S"), ct)); #endif #if HAS_HEATED_BED // Restore the bed temperature const celsius_t bt = info.target_temperature_bed; if (bt) PROCESS_SUBCOMMANDS_NOW(TS(F("M190S"), bt)); #endif // Heat hotend enough to soften material #if HAS_HOTEND HOTEND_LOOP() { const celsius_t et = _MAX(info.target_temperature[e], 180); if (et) { TERN_(HAS_MULTI_HOTEND, PROCESS_SUBCOMMANDS_NOW(TS('T', e, 'S'))); PROCESS_SUBCOMMANDS_NOW(TS(F("M109S"), et)); } } #endif // Interpret the saved Z according to flags const float z_print = resume_pos.z, z_raised = z_print + info.zraise; // // Home the axes that can safely be homed, and // establish the current position as best we can. // PROCESS_SUBCOMMANDS_NOW(F("G92.9E0")); // Reset E to 0 #if Z_HOME_TO_MAX float z_now = z_raised; // If Z homing goes to max then just move back to the "raised" position PROCESS_SUBCOMMANDS_NOW(TS( F( "G28R0\n" // Home all axes (no raise) "G1F1200Z") // Move Z down to (raised) height , p_float_t(z_now, 3) )); #elif DISABLED(BELTPRINTER) #if ENABLED(POWER_LOSS_RECOVER_ZHOME) && defined(POWER_LOSS_ZHOME_POS) #define HOMING_Z_DOWN 1 #endif float z_now = info.flag.raised ? z_raised : z_print; #if !HOMING_Z_DOWN // Set Z to the real position PROCESS_SUBCOMMANDS_NOW(TS(F("G92.9Z"), p_float_t(z_now, 3))); #endif // Does Z need to be raised now? It should be raised before homing XY. if (z_raised > z_now) { z_now = z_raised; PROCESS_SUBCOMMANDS_NOW(TS(F("G1F600Z"), p_float_t(z_now, 3))); } // Home XY with no Z raise PROCESS_SUBCOMMANDS_NOW(F("G28R0XY")); // No raise during G28 #endif #if HOMING_Z_DOWN // Move to a safe XY position and home Z while avoiding the print. const xy_pos_t p = xy_pos_t(POWER_LOSS_ZHOME_POS) TERN_(HOMING_Z_WITH_PROBE, - probe.offset_xy); PROCESS_SUBCOMMANDS_NOW(TS(F("G1F1000X"), p_float_t(p.x, 3), 'Y', p_float_t(p.y, 3), F("\nG28HZ"))); #endif // Mark all axes as having been homed (no effect on current_position) set_all_homed(); #if HAS_LEVELING // Restore Z fade and possibly re-enable bed leveling compensation. // Leveling may already be enabled due to the ENABLE_LEVELING_AFTER_G28 option. // TODO: Add a G28 parameter to leave leveling disabled. PROCESS_SUBCOMMANDS_NOW(TS(F("M420S"), '0' + (char)info.flag.leveling, 'Z', p_float_t(info.fade, 1))); #if !HOMING_Z_DOWN // The physical Z was adjusted at power-off so undo the M420S1 correction to Z with G92.9. PROCESS_SUBCOMMANDS_NOW(TS(F("G92.9Z"), p_float_t(z_now, 1))); #endif #endif #if ENABLED(POWER_LOSS_RECOVER_ZHOME) // Z was homed down to the bed, so move up to the raised height. z_now = z_raised; PROCESS_SUBCOMMANDS_NOW(TS(F("G1F600Z"), p_float_t(z_now, 3))); #endif // Recover volumetric extrusion state #if DISABLED(NO_VOLUMETRICS) #if HAS_MULTI_EXTRUDER EXTRUDER_LOOP() PROCESS_SUBCOMMANDS_NOW(TS(F("M200T"), e, F("D"), p_float_t(info.filament_size[e], 3))); if (!info.flag.volumetric_enabled) PROCESS_SUBCOMMANDS_NOW(TS(F("M200D0T"), info.active_extruder)); #else if (info.flag.volumetric_enabled) PROCESS_SUBCOMMANDS_NOW(TS(F("M200D"), p_float_t(info.filament_size[0], 3))); #endif #endif // Restore all hotend temperatures #if HAS_HOTEND HOTEND_LOOP() { const celsius_t et = info.target_temperature[e]; if (et) { TERN_(HAS_MULTI_HOTEND, PROCESS_SUBCOMMANDS_NOW(TS('T', e, 'S'))); PROCESS_SUBCOMMANDS_NOW(TS(F("M109S"), et)); } } #endif // Restore the previously active tool (with no_move) #if HAS_MULTI_EXTRUDER || HAS_MULTI_HOTEND PROCESS_SUBCOMMANDS_NOW(TS('T', info.active_extruder, 'S')); #endif // Restore print cooling fan speeds #if HAS_FAN FANS_LOOP(i) { const int f = info.fan_speed[i]; if (f) PROCESS_SUBCOMMANDS_NOW(TS(F("M106P"), i, 'S', f)); } #endif // Restore retract and hop state from an active `G10` command #if ENABLED(FWRETRACT) EXTRUDER_LOOP() { if (info.retract[e] != 0.0) { fwretract.current_retract[e] = info.retract[e]; fwretract.retracted.set(e); } } fwretract.current_hop = info.retract_hop; #endif #if ENABLED(GRADIENT_MIX) memcpy(&mixer.gradient, &info.gradient, sizeof(info.gradient)); #endif // Un-retract if there was a retract at outage #if ENABLED(BACKUP_POWER_SUPPLY) && POWER_LOSS_RETRACT_LEN > 0 PROCESS_SUBCOMMANDS_NOW(F("G1F3000E" STRINGIFY(POWER_LOSS_RETRACT_LEN))); #endif // Additional purge on resume if configured #if POWER_LOSS_PURGE_LEN PROCESS_SUBCOMMANDS_NOW(TS(F("G1F3000E"), (POWER_LOSS_PURGE_LEN) + (POWER_LOSS_RETRACT_LEN))); #endif #if ENABLED(NOZZLE_CLEAN_FEATURE) PROCESS_SUBCOMMANDS_NOW(F("G12")); #endif // Move back over to the saved XY PROCESS_SUBCOMMANDS_NOW(TS( F("G1F3000X"), p_float_t(resume_pos.x, 3), 'Y', p_float_t(resume_pos.y, 3) )); // Move back down to the saved Z for printing PROCESS_SUBCOMMANDS_NOW(TS(F("G1F600Z"), p_float_t(z_print, 3))); // Restore the feedrate PROCESS_SUBCOMMANDS_NOW(TS(F("G1F"), info.feedrate)); // Restore E position with G92.9 PROCESS_SUBCOMMANDS_NOW(TS(F("G92.9E"), p_float_t(resume_pos.e, 3))); TERN_(GCODE_REPEAT_MARKERS, repeat = info.stored_repeat); TERN_(HAS_HOME_OFFSET, home_offset = info.home_offset); TERN_(HAS_WORKSPACE_OFFSET, workspace_offset = info.workspace_offset); // Relative axis modes gcode.axis_relative = info.axis_relative; // Continue to apply PLR when a file is resumed! enable(true); // Resume the SD file from the last position PROCESS_SUBCOMMANDS_NOW(MString<MAX_CMD_SIZE>(F("M23 "), info.sd_filename)); PROCESS_SUBCOMMANDS_NOW(TS(F("M24S"), resume_sdpos, 'T', info.print_job_elapsed)); } #if ENABLED(DEBUG_POWER_LOSS_RECOVERY) void PrintJobRecovery::debug(FSTR_P const prefix) { DEBUG_ECHOLN(prefix, F(" Job Recovery Info...\nvalid_head:"), info.valid_head, F(" valid_foot:"), info.valid_foot); if (info.valid_head) { if (info.valid_head == info.valid_foot) { DEBUG_ECHOPGM("current_position: "); LOOP_LOGICAL_AXES(i) { if (i) DEBUG_CHAR(','); DEBUG_ECHO(info.current_position[i]); } DEBUG_EOL(); DEBUG_ECHOLNPGM("feedrate: ", info.feedrate); DEBUG_ECHOLNPGM("zraise: ", info.zraise, " ", info.flag.raised ? "(before)" : ""); #if ENABLED(GCODE_REPEAT_MARKERS) const uint8_t ind = info.stored_repeat.count(); DEBUG_ECHOLNPGM("repeat markers: ", ind); for (uint8_t i = ind; i--;) DEBUG_ECHOLNPGM("...", i, " sdpos: ", info.stored_repeat.get_marker_sdpos(i), " count: ", info.stored_repeat.get_marker_counter(i)); #endif #if HAS_HOME_OFFSET DEBUG_ECHOPGM("home_offset: "); LOOP_NUM_AXES(i) { if (i) DEBUG_CHAR(','); DEBUG_ECHO(info.home_offset[i]); } DEBUG_EOL(); #endif #if HAS_WORKSPACE_OFFSET DEBUG_ECHOPGM("workspace_offset: "); LOOP_NUM_AXES(i) { if (i) DEBUG_CHAR(','); DEBUG_ECHO(info.workspace_offset[i]); } DEBUG_EOL(); #endif #if HAS_MULTI_EXTRUDER DEBUG_ECHOLNPGM("active_extruder: ", info.active_extruder); #endif #if DISABLED(NO_VOLUMETRICS) DEBUG_ECHOPGM("filament_size:"); EXTRUDER_LOOP() DEBUG_ECHOLNPGM(" ", info.filament_size[e]); DEBUG_EOL(); #endif #if HAS_HOTEND DEBUG_ECHOPGM("target_temperature: "); HOTEND_LOOP() { DEBUG_ECHO(info.target_temperature[e]); if (e < HOTENDS - 1) DEBUG_CHAR(','); } DEBUG_EOL(); #endif #if HAS_HEATED_BED DEBUG_ECHOLNPGM("target_temperature_bed: ", info.target_temperature_bed); #endif #if HAS_HEATED_CHAMBER DEBUG_ECHOLNPGM("target_temperature_chamber: ", info.target_temperature_chamber); #endif #if HAS_FAN DEBUG_ECHOPGM("fan_speed: "); FANS_LOOP(i) { DEBUG_ECHO(info.fan_speed[i]); if (i < FAN_COUNT - 1) DEBUG_CHAR(','); } DEBUG_EOL(); #endif #if HAS_LEVELING DEBUG_ECHOLNPGM("leveling: ", info.flag.leveling ? "ON" : "OFF", " fade: ", info.fade); #endif #if ENABLED(FWRETRACT) DEBUG_ECHOPGM("retract: "); EXTRUDER_LOOP() { DEBUG_ECHO(info.retract[e]); if (e < EXTRUDERS - 1) DEBUG_CHAR(','); } DEBUG_EOL(); DEBUG_ECHOLNPGM("retract_hop: ", info.retract_hop); #endif // Mixing extruder and gradient #if ALL(MIXING_EXTRUDER, GRADIENT_MIX) DEBUG_ECHOLNPGM("gradient: ", info.gradient.enabled ? "ON" : "OFF"); #endif DEBUG_ECHOLNPGM("sd_filename: ", info.sd_filename); DEBUG_ECHOLNPGM("sdpos: ", info.sdpos); DEBUG_ECHOLNPGM("print_job_elapsed: ", info.print_job_elapsed); DEBUG_ECHOPGM("axis_relative:"); if (TEST(info.axis_relative, REL_X)) DEBUG_ECHOPGM(" REL_X"); if (TEST(info.axis_relative, REL_Y)) DEBUG_ECHOPGM(" REL_Y"); if (TEST(info.axis_relative, REL_Z)) DEBUG_ECHOPGM(" REL_Z"); if (TEST(info.axis_relative, REL_E)) DEBUG_ECHOPGM(" REL_E"); if (TEST(info.axis_relative, E_MODE_ABS)) DEBUG_ECHOPGM(" E_MODE_ABS"); if (TEST(info.axis_relative, E_MODE_REL)) DEBUG_ECHOPGM(" E_MODE_REL"); DEBUG_EOL(); DEBUG_ECHOLNPGM("flag.dryrun: ", AS_DIGIT(info.flag.dryrun)); DEBUG_ECHOLNPGM("flag.allow_cold_extrusion: ", AS_DIGIT(info.flag.allow_cold_extrusion)); #if DISABLED(NO_VOLUMETRICS) DEBUG_ECHOLNPGM("flag.volumetric_enabled: ", AS_DIGIT(info.flag.volumetric_enabled)); #endif } else DEBUG_ECHOLNPGM("INVALID DATA"); } DEBUG_ECHOLNPGM("---"); } #endif // DEBUG_POWER_LOSS_RECOVERY #endif // POWER_LOSS_RECOVERY
2301_81045437/Marlin
Marlin/src/feature/powerloss.cpp
C++
agpl-3.0
21,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/>. * */ #pragma once /** * feature/powerloss.h - Resume an SD print after power-loss */ #include "../sd/cardreader.h" #include "../gcode/gcode.h" #include "../inc/MarlinConfig.h" #if ENABLED(GCODE_REPEAT_MARKERS) #include "../feature/repeat.h" #endif #if ENABLED(MIXING_EXTRUDER) #include "../feature/mixing.h" #endif #if !defined(POWER_LOSS_STATE) && PIN_EXISTS(POWER_LOSS) #define POWER_LOSS_STATE HIGH #endif #if DISABLED(BACKUP_POWER_SUPPLY) #undef POWER_LOSS_ZRAISE // No Z raise at outage without backup power #endif #ifndef POWER_LOSS_ZRAISE #define POWER_LOSS_ZRAISE 2 // Default Z-raise on outage or resume #endif //#define DEBUG_POWER_LOSS_RECOVERY //#define SAVE_EACH_CMD_MODE //#define SAVE_INFO_INTERVAL_MS 0 typedef struct { uint8_t valid_head; // Machine state xyze_pos_t current_position; uint16_t feedrate; float zraise; // Repeat information #if ENABLED(GCODE_REPEAT_MARKERS) Repeat stored_repeat; #endif #if HAS_HOME_OFFSET xyz_pos_t home_offset; #endif #if HAS_WORKSPACE_OFFSET xyz_pos_t workspace_offset; #endif #if HAS_MULTI_EXTRUDER uint8_t active_extruder; #endif #if DISABLED(NO_VOLUMETRICS) float filament_size[EXTRUDERS]; #endif #if HAS_HOTEND celsius_t target_temperature[HOTENDS]; #endif #if HAS_HEATED_BED celsius_t target_temperature_bed; #endif #if HAS_HEATED_CHAMBER celsius_t target_temperature_chamber; #endif #if HAS_FAN uint8_t fan_speed[FAN_COUNT]; #endif #if HAS_LEVELING float fade; #endif #if ENABLED(FWRETRACT) float retract[EXTRUDERS], retract_hop; #endif // Mixing extruder and gradient #if ENABLED(MIXING_EXTRUDER) //uint_fast8_t selected_vtool; //mixer_comp_t color[NR_MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS]; #if ENABLED(GRADIENT_MIX) gradient_t gradient; #endif #endif // SD Filename and position char sd_filename[MAXPATHNAMELENGTH]; volatile uint32_t sdpos; // Job elapsed time millis_t print_job_elapsed; // Relative axis modes relative_t axis_relative; // Misc. Marlin flags struct { bool raised:1; // Raised before saved bool dryrun:1; // M111 S8 bool allow_cold_extrusion:1; // M302 P1 #if HAS_LEVELING bool leveling:1; // M420 S #endif #if DISABLED(NO_VOLUMETRICS) bool volumetric_enabled:1; // M200 S D #endif } flag; uint8_t valid_foot; bool valid() { return valid_head && valid_head == valid_foot; } } job_recovery_info_t; class PrintJobRecovery { public: static const char filename[5]; static MediaFile file; static job_recovery_info_t info; static uint8_t queue_index_r; //!< Queue index of the active command static uint32_t cmd_sdpos, //!< SD position of the next command sdpos[BUFSIZE]; //!< SD positions of queued commands #if HAS_PLR_UI_FLAG static bool ui_flag_resume; //!< Flag the UI to show a dialog to Resume (M1000) or Cancel (M1000C) #endif static void init(); static void prepare(); static void setup() { #if PIN_EXISTS(OUTAGECON) OUT_WRITE(OUTAGECON_PIN, HIGH); #endif #if PIN_EXISTS(POWER_LOSS) #if ENABLED(POWER_LOSS_PULLUP) SET_INPUT_PULLUP(POWER_LOSS_PIN); #elif ENABLED(POWER_LOSS_PULLDOWN) SET_INPUT_PULLDOWN(POWER_LOSS_PIN); #else SET_INPUT(POWER_LOSS_PIN); #endif #endif } // Track each command's file offsets static uint32_t command_sdpos() { return sdpos[queue_index_r]; } static void commit_sdpos(const uint8_t index_w) { sdpos[index_w] = cmd_sdpos; } static bool enabled; static void enable(const bool onoff); static void changed(); #if HAS_PLR_BED_THRESHOLD static celsius_t bed_temp_threshold; #endif static bool exists() { return card.jobRecoverFileExists(); } static void open(const bool read) { card.openJobRecoveryFile(read); } static void close() { file.close(); } static bool check(); static void resume(); static void purge(); static void cancel() { purge(); } static void load(); static void save(const bool force=ENABLED(SAVE_EACH_CMD_MODE), const float zraise=POWER_LOSS_ZRAISE, const bool raised=false); #if PIN_EXISTS(POWER_LOSS) static void outage() { static constexpr uint8_t OUTAGE_THRESHOLD = 3; static uint8_t outage_counter = 0; if (enabled && READ(POWER_LOSS_PIN) == POWER_LOSS_STATE) { outage_counter++; if (outage_counter >= OUTAGE_THRESHOLD) _outage(); } else outage_counter = 0; } #endif // The referenced file exists static bool interrupted_file_exists() { return card.fileExists(info.sd_filename); } static bool valid() { return info.valid() && interrupted_file_exists(); } #if ENABLED(DEBUG_POWER_LOSS_RECOVERY) static void debug(FSTR_P const prefix); #else static void debug(FSTR_P const) {} #endif private: static void write(); #if ENABLED(BACKUP_POWER_SUPPLY) static void retract_and_lift(const_float_t zraise); #endif #if PIN_EXISTS(POWER_LOSS) || ENABLED(DEBUG_POWER_LOSS_RECOVERY) friend class GcodeSuite; static void _outage(TERN_(DEBUG_POWER_LOSS_RECOVERY, const bool simulated=false)); #endif }; extern PrintJobRecovery recovery;
2301_81045437/Marlin
Marlin/src/feature/powerloss.h
C++
agpl-3.0
6,324
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfigPre.h" #if HAS_PTC //#define DEBUG_PTC // Print extra debug output with 'M871' #include "probe_temp_comp.h" #include <math.h> #include "../module/temperature.h" ProbeTempComp ptc; #if ENABLED(PTC_PROBE) constexpr int16_t z_offsets_probe_default[PTC_PROBE_COUNT] = PTC_PROBE_ZOFFS; int16_t ProbeTempComp::z_offsets_probe[PTC_PROBE_COUNT] = PTC_PROBE_ZOFFS; #endif #if ENABLED(PTC_BED) constexpr int16_t z_offsets_bed_default[PTC_BED_COUNT] = PTC_BED_ZOFFS; int16_t ProbeTempComp::z_offsets_bed[PTC_BED_COUNT] = PTC_BED_ZOFFS; #endif #if ENABLED(PTC_HOTEND) constexpr int16_t z_offsets_hotend_default[PTC_HOTEND_COUNT] = PTC_HOTEND_ZOFFS; int16_t ProbeTempComp::z_offsets_hotend[PTC_HOTEND_COUNT] = PTC_HOTEND_ZOFFS; #endif int16_t *ProbeTempComp::sensor_z_offsets[TSI_COUNT] = { #if ENABLED(PTC_PROBE) ProbeTempComp::z_offsets_probe, #endif #if ENABLED(PTC_BED) ProbeTempComp::z_offsets_bed, #endif #if ENABLED(PTC_HOTEND) ProbeTempComp::z_offsets_hotend, #endif }; constexpr temp_calib_t ProbeTempComp::cali_info[TSI_COUNT]; uint8_t ProbeTempComp::calib_idx; // = 0 float ProbeTempComp::init_measurement; // = 0.0 bool ProbeTempComp::enabled = true; void ProbeTempComp::reset() { TERN_(PTC_PROBE, for (uint8_t i = 0; i < PTC_PROBE_COUNT; ++i) z_offsets_probe[i] = z_offsets_probe_default[i]); TERN_(PTC_BED, for (uint8_t i = 0; i < PTC_BED_COUNT; ++i) z_offsets_bed[i] = z_offsets_bed_default[i]); TERN_(PTC_HOTEND, for (uint8_t i = 0; i < PTC_HOTEND_COUNT; ++i) z_offsets_hotend[i] = z_offsets_hotend_default[i]); } void ProbeTempComp::clear_offsets(const TempSensorID tsi) { for (uint8_t i = 0; i < cali_info[tsi].measurements; ++i) sensor_z_offsets[tsi][i] = 0; calib_idx = 0; } bool ProbeTempComp::set_offset(const TempSensorID tsi, const uint8_t idx, const int16_t offset) { if (idx >= cali_info[tsi].measurements) return false; sensor_z_offsets[tsi][idx] = offset; return true; } void ProbeTempComp::print_offsets() { for (uint8_t s = 0; s < TSI_COUNT; ++s) { celsius_t temp = cali_info[s].start_temp; for (int16_t i = -1; i < cali_info[s].measurements; ++i) { SERIAL_ECHOLN( TERN_(PTC_BED, s == TSI_BED ? F("Bed") :) TERN_(PTC_HOTEND, s == TSI_EXT ? F("Extruder") :) F("Probe"), F(" temp: "), temp, F("C; Offset: "), i < 0 ? 0.0f : sensor_z_offsets[s][i], F(" um") ); temp += cali_info[s].temp_resolution; } } #if ENABLED(DEBUG_PTC) float meas[4] = { 0, 0, 0, 0 }; compensate_measurement(TSI_PROBE, 27.5, meas[0]); compensate_measurement(TSI_PROBE, 32.5, meas[1]); compensate_measurement(TSI_PROBE, 77.5, meas[2]); compensate_measurement(TSI_PROBE, 82.5, meas[3]); SERIAL_ECHOLNPGM("DEBUG_PTC 27.5:", meas[0], " 32.5:", meas[1], " 77.5:", meas[2], " 82.5:", meas[3]); #endif } void ProbeTempComp::prepare_new_calibration(const_float_t init_meas_z) { calib_idx = 0; init_measurement = init_meas_z; } void ProbeTempComp::push_back_new_measurement(const TempSensorID tsi, const_float_t meas_z) { if (calib_idx >= cali_info[tsi].measurements) return; sensor_z_offsets[tsi][calib_idx++] = static_cast<int16_t>((meas_z - init_measurement) * 1000.0f); } bool ProbeTempComp::finish_calibration(const TempSensorID tsi) { if (!calib_idx) { SERIAL_ECHOLNPGM("!No measurements."); clear_offsets(tsi); return false; } const uint8_t measurements = cali_info[tsi].measurements; const celsius_t start_temp = cali_info[tsi].start_temp, res_temp = cali_info[tsi].temp_resolution; int16_t * const data = sensor_z_offsets[tsi]; // Extrapolate float k, d; if (calib_idx < measurements) { SERIAL_ECHOLNPGM("Got ", calib_idx, " measurements. "); if (linear_regression(tsi, k, d)) { SERIAL_ECHOPGM("Applying linear extrapolation"); for (; calib_idx < measurements; ++calib_idx) { const celsius_float_t temp = start_temp + float(calib_idx + 1) * res_temp; data[calib_idx] = static_cast<int16_t>(k * temp + d); } } else { // Simply use the last measured value for higher temperatures SERIAL_ECHOPGM("Failed to extrapolate"); const int16_t last_val = data[calib_idx-1]; for (; calib_idx < measurements; ++calib_idx) data[calib_idx] = last_val; } SERIAL_ECHOLNPGM(" for higher temperatures."); } // Sanity check for (calib_idx = 0; calib_idx < measurements; ++calib_idx) { // Restrict the max. offset if (ABS(data[calib_idx]) > 2000) { SERIAL_ECHOLNPGM("!Invalid Z-offset detected (0-2)."); clear_offsets(tsi); return false; } // Restrict the max. offset difference between two probings if (calib_idx > 0 && ABS(data[calib_idx - 1] - data[calib_idx]) > 800) { SERIAL_ECHOLNPGM("!Invalid Z-offset between two probings detected (0-0.8)."); clear_offsets(tsi); return false; } } return true; } void ProbeTempComp::apply_compensation(float &meas_z) { if (!enabled) return; TERN_(PTC_BED, compensate_measurement(TSI_BED, thermalManager.degBed(), meas_z)); TERN_(PTC_PROBE, compensate_measurement(TSI_PROBE, thermalManager.degProbe(), meas_z)); TERN_(PTC_HOTEND, compensate_measurement(TSI_EXT, thermalManager.degHotend(0), meas_z)); } void ProbeTempComp::compensate_measurement(const TempSensorID tsi, const celsius_t temp, float &meas_z) { const uint8_t measurements = cali_info[tsi].measurements; const celsius_t start_temp = cali_info[tsi].start_temp, res_temp = cali_info[tsi].temp_resolution, end_temp = start_temp + measurements * res_temp; const int16_t * const data = sensor_z_offsets[tsi]; // Given a data index, return { celsius, zoffset } in the form { x, y } auto tpoint = [&](uint8_t i) -> xy_float_t { return xy_float_t({ static_cast<float>(start_temp) + i * res_temp, i ? static_cast<float>(data[i - 1]) : 0.0f }); }; // Interpolate Z based on a temperature being within a given range auto linear_interp = [](const_float_t x, xy_float_t p1, xy_float_t p2) { // zoffs1 + zoffset_per_toffset * toffset return p1.y + (p2.y - p1.y) / (p2.x - p1.x) * (x - p1.x); }; // offset in µm float offset = 0.0f; #if PTC_LINEAR_EXTRAPOLATION if (temp < start_temp) offset = linear_interp(temp, tpoint(0), tpoint(PTC_LINEAR_EXTRAPOLATION)); else if (temp >= end_temp) offset = linear_interp(temp, tpoint(measurements - PTC_LINEAR_EXTRAPOLATION), tpoint(measurements)); #else if (temp < start_temp) offset = 0.0f; else if (temp >= end_temp) offset = static_cast<float>(data[measurements - 1]); #endif else { // Linear interpolation const int8_t idx = static_cast<int8_t>((temp - start_temp) / res_temp); offset = linear_interp(temp, tpoint(idx), tpoint(idx + 1)); } // convert offset to mm and apply it meas_z -= offset / 1000.0f; } bool ProbeTempComp::linear_regression(const TempSensorID tsi, float &k, float &d) { if (!WITHIN(calib_idx, 1, cali_info[tsi].measurements)) return false; const celsius_t start_temp = cali_info[tsi].start_temp, res_temp = cali_info[tsi].temp_resolution; const int16_t * const data = sensor_z_offsets[tsi]; float sum_x = start_temp, sum_x2 = sq(start_temp), sum_xy = 0, sum_y = 0; float xi = static_cast<float>(start_temp); for (uint8_t i = 0; i < calib_idx; ++i) { const float yi = static_cast<float>(data[i]); xi += res_temp; sum_x += xi; sum_x2 += sq(xi); sum_xy += xi * yi; sum_y += yi; } const float denom = static_cast<float>(calib_idx + 1) * sum_x2 - sq(sum_x); if (fabs(denom) <= 10e-5) { // Singularity - unable to solve k = d = 0.0; return false; } k = (static_cast<float>(calib_idx + 1) * sum_xy - sum_x * sum_y) / denom; d = (sum_y - k * sum_x) / static_cast<float>(calib_idx + 1); return true; } #endif // HAS_PTC
2301_81045437/Marlin
Marlin/src/feature/probe_temp_comp.cpp
C++
agpl-3.0
8,890
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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 TempSensorID : uint8_t { #if ENABLED(PTC_PROBE) TSI_PROBE, #endif #if ENABLED(PTC_BED) TSI_BED, #endif #if ENABLED(PTC_HOTEND) TSI_EXT, #endif TSI_COUNT }; typedef struct { uint8_t measurements; // Max. number of measurements to be stored (35 - 80°C) celsius_t temp_resolution, // Resolution in °C between measurements start_temp; // Base measurement; z-offset == 0 } temp_calib_t; /** * Probe temperature compensation implementation. * Z-probes like the P.I.N.D.A V2 allow for compensation of * measurement errors/shifts due to changed temperature. */ class ProbeTempComp { public: static constexpr temp_calib_t cali_info[TSI_COUNT] = { #if ENABLED(PTC_PROBE) { PTC_PROBE_COUNT, PTC_PROBE_RES, PTC_PROBE_START }, // Probe #endif #if ENABLED(PTC_BED) { PTC_BED_COUNT, PTC_BED_RES, PTC_BED_START }, // Bed #endif #if ENABLED(PTC_HOTEND) { PTC_HOTEND_COUNT, PTC_HOTEND_RES, PTC_HOTEND_START }, // Extruder #endif }; static int16_t *sensor_z_offsets[TSI_COUNT]; #if ENABLED(PTC_PROBE) static int16_t z_offsets_probe[PTC_PROBE_COUNT]; // (µm) #endif #if ENABLED(PTC_BED) static int16_t z_offsets_bed[PTC_BED_COUNT]; // (µm) #endif #if ENABLED(PTC_HOTEND) static int16_t z_offsets_hotend[PTC_HOTEND_COUNT]; // (µm) #endif static void reset_index() { calib_idx = 0; }; static uint8_t get_index() { return calib_idx; } static void reset(); static void clear_all_offsets() { TERN_(PTC_PROBE, clear_offsets(TSI_PROBE)); TERN_(PTC_BED, clear_offsets(TSI_BED)); TERN_(PTC_HOTEND, clear_offsets(TSI_EXT)); } static bool set_offset(const TempSensorID tsi, const uint8_t idx, const int16_t offset); static void print_offsets(); static void prepare_new_calibration(const_float_t init_meas_z); static void push_back_new_measurement(const TempSensorID tsi, const_float_t meas_z); static bool finish_calibration(const TempSensorID tsi); static void set_enabled(const bool ena) { enabled = ena; } // Apply all temperature compensation adjustments static void apply_compensation(float &meas_z); private: static uint8_t calib_idx; static bool enabled; static void clear_offsets(const TempSensorID tsi); /** * Base value. Temperature compensation values will be deltas * to this value, set at first probe. */ static float init_measurement; /** * Fit a linear function in measured temperature offsets * to allow generating values of higher temperatures. */ static bool linear_regression(const TempSensorID tsi, float &k, float &d); static void compensate_measurement(const TempSensorID tsi, const celsius_t temp, float &meas_z); }; extern ProbeTempComp ptc;
2301_81045437/Marlin
Marlin/src/feature/probe_temp_comp.h
C++
agpl-3.0
3,785
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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(GCODE_REPEAT_MARKERS) //#define DEBUG_GCODE_REPEAT_MARKERS #include "repeat.h" #include "../gcode/gcode.h" #include "../sd/cardreader.h" #define DEBUG_OUT ENABLED(DEBUG_GCODE_REPEAT_MARKERS) #include "../core/debug_out.h" repeat_marker_t Repeat::marker[MAX_REPEAT_NESTING]; uint8_t Repeat::index; void Repeat::add_marker(const uint32_t sdpos, const uint16_t count) { if (index >= MAX_REPEAT_NESTING) SERIAL_ECHO_MSG("!Too many markers."); else { marker[index].sdpos = sdpos; marker[index].counter = count ? count - 1 : -1; index++; DEBUG_ECHOLNPGM("Add Marker ", index, " at ", sdpos, " (", count, ")"); } } void Repeat::loop() { if (!index) // No marker? SERIAL_ECHO_MSG("!No marker set."); // Inform the user. else { const uint8_t ind = index - 1; // Active marker's index if (!marker[ind].counter) { // Did its counter run out? DEBUG_ECHOLNPGM("Pass Marker ", index); index--; // Carry on. Previous marker on the next 'M808'. } else { card.setIndex(marker[ind].sdpos); // Loop back to the marker. if (marker[ind].counter > 0) // Ignore a negative (or zero) counter. --marker[ind].counter; // Decrement the counter. If zero this 'M808' will be skipped next time. DEBUG_ECHOLNPGM("Goto Marker ", index, " at ", marker[ind].sdpos, " (", marker[ind].counter, ")"); } } } void Repeat::cancel() { for (uint8_t i = 0; i < index; ++i) marker[i].counter = 0; } void Repeat::early_parse_M808(char * const cmd) { if (is_command_M808(cmd)) { DEBUG_ECHOLNPGM("Parsing \"", cmd, "\""); parser.parse(cmd); if (parser.seen('L')) add_marker(card.getIndex(), parser.value_ushort()); else Repeat::loop(); } } #endif // GCODE_REPEAT_MARKERS
2301_81045437/Marlin
Marlin/src/feature/repeat.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 #include "../inc/MarlinConfigPre.h" #include "../gcode/parser.h" #include <stdint.h> #define MAX_REPEAT_NESTING 10 typedef struct { uint32_t sdpos; // The repeat file position int16_t counter; // The counter for looping } repeat_marker_t; class Repeat { private: static repeat_marker_t marker[MAX_REPEAT_NESTING]; static uint8_t index; public: static void reset() { index = 0; } static bool is_active() { for (uint8_t i = 0; i < index; ++i) if (marker[i].counter) return true; return false; } static bool is_command_M808(char * const cmd) { return cmd[0] == 'M' && cmd[1] == '8' && cmd[2] == '0' && cmd[3] == '8' && !NUMERIC(cmd[4]); } static void early_parse_M808(char * const cmd); static void add_marker(const uint32_t sdpos, const uint16_t count); static void loop(); static void cancel(); static uint8_t count() { return index; } static int16_t get_marker_counter(const uint8_t i) { return marker[i].counter; } static uint32_t get_marker_sdpos(const uint8_t i) { return marker[i].sdpos; } }; extern Repeat repeat;
2301_81045437/Marlin
Marlin/src/feature/repeat.h
C++
agpl-3.0
1,941
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * feature/runout.cpp - Runout sensor support */ #include "../inc/MarlinConfigPre.h" #if HAS_FILAMENT_SENSOR #include "runout.h" FilamentMonitor runout; bool FilamentMonitorBase::enabled = true, FilamentMonitorBase::filament_ran_out; // = false #if ENABLED(HOST_ACTION_COMMANDS) bool FilamentMonitorBase::host_handling; // = false #endif #if ENABLED(TOOLCHANGE_MIGRATION_FEATURE) #include "../module/tool_change.h" #define DEBUG_OUT ENABLED(DEBUG_TOOLCHANGE_MIGRATION_FEATURE) #include "../core/debug_out.h" #endif #if HAS_FILAMENT_RUNOUT_DISTANCE float RunoutResponseDelayed::runout_distance_mm = FILAMENT_RUNOUT_DISTANCE_MM; countdown_t RunoutResponseDelayed::mm_countdown; #if ENABLED(FILAMENT_MOTION_SENSOR) uint8_t FilamentSensorEncoder::motion_detected; #endif #else int8_t RunoutResponseDebounced::runout_count[NUM_RUNOUT_SENSORS]; // = 0 #endif // // Filament Runout event handler // #include "../MarlinCore.h" #include "../feature/pause.h" #include "../gcode/queue.h" #if ENABLED(HOST_ACTION_COMMANDS) #include "host_actions.h" #endif #if ENABLED(EXTENSIBLE_UI) #include "../lcd/extui/ui_api.h" #endif void event_filament_runout(const uint8_t extruder) { if (did_pause_print) return; // Action already in progress. Purge triggered repeated runout. #if ENABLED(TOOLCHANGE_MIGRATION_FEATURE) if (migration.in_progress) { DEBUG_ECHOLNPGM("Migration Already In Progress"); return; // Action already in progress. Purge triggered repeated runout. } if (migration.automode) { DEBUG_ECHOLNPGM("Migration Starting"); if (extruder_migration()) return; } #endif TERN_(EXTENSIBLE_UI, ExtUI::onFilamentRunout(ExtUI::getTool(extruder))); #if ANY(HOST_PROMPT_SUPPORT, HOST_ACTION_COMMANDS, MULTI_FILAMENT_SENSOR) const char tool = '0' + TERN0(MULTI_FILAMENT_SENSOR, extruder); #endif //action:out_of_filament #if ENABLED(HOST_PROMPT_SUPPORT) hostui.prompt_do(PROMPT_FILAMENT_RUNOUT, F("FilamentRunout T"), tool); //action:out_of_filament #endif const bool run_runout_script = !runout.host_handling; #if ENABLED(HOST_ACTION_COMMANDS) const bool park_or_pause = (false #ifdef FILAMENT_RUNOUT_SCRIPT || strstr(FILAMENT_RUNOUT_SCRIPT, "M600") || strstr(FILAMENT_RUNOUT_SCRIPT, "M125") || TERN0(ADVANCED_PAUSE_FEATURE, strstr(FILAMENT_RUNOUT_SCRIPT, "M25")) #endif ); if (run_runout_script && park_or_pause) { hostui.paused(false); } else { // Legacy Repetier command for use until newer version supports standard dialog // To be removed later when pause command also triggers dialog #ifdef ACTION_ON_FILAMENT_RUNOUT hostui.action(F(ACTION_ON_FILAMENT_RUNOUT " T"), false); SERIAL_CHAR(tool); SERIAL_EOL(); #endif hostui.pause(false); } SERIAL_ECHOPGM(" " ACTION_REASON_ON_FILAMENT_RUNOUT " "); SERIAL_CHAR(tool); SERIAL_EOL(); #endif // HOST_ACTION_COMMANDS #ifdef FILAMENT_RUNOUT_SCRIPT if (run_runout_script) { #if MULTI_FILAMENT_SENSOR MString<strlen(FILAMENT_RUNOUT_SCRIPT)> script; script.setf(F(FILAMENT_RUNOUT_SCRIPT), C(tool)); #if ENABLED(FILAMENT_RUNOUT_SENSOR_DEBUG) SERIAL_ECHOLNPGM("Runout Command: ", &script); #endif queue.inject(&script); #else #if ENABLED(FILAMENT_RUNOUT_SENSOR_DEBUG) SERIAL_ECHOPGM("Runout Command: "); SERIAL_ECHOLNPGM(FILAMENT_RUNOUT_SCRIPT); #endif queue.inject(F(FILAMENT_RUNOUT_SCRIPT)); #endif } #endif } #endif // HAS_FILAMENT_SENSOR
2301_81045437/Marlin
Marlin/src/feature/runout.cpp
C++
agpl-3.0
4,522
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * feature/runout.h - Runout sensor support */ #include "../sd/cardreader.h" #include "../module/printcounter.h" #include "../module/planner.h" #include "../module/stepper.h" // for block_t #include "../gcode/queue.h" #include "../feature/pause.h" // for did_pause_print #include "../MarlinCore.h" // for printingIsActive() #include "../inc/MarlinConfig.h" #if ENABLED(EXTENSIBLE_UI) #include "../lcd/extui/ui_api.h" #endif //#define FILAMENT_RUNOUT_SENSOR_DEBUG #ifndef FILAMENT_RUNOUT_THRESHOLD #define FILAMENT_RUNOUT_THRESHOLD 5 #endif #if ENABLED(FILAMENT_MOTION_SENSOR) #define HAS_FILAMENT_MOTION 1 #endif #if DISABLED(FILAMENT_MOTION_SENSOR) || ENABLED(FILAMENT_SWITCH_AND_MOTION) #define HAS_FILAMENT_SWITCH 1 #endif typedef Flags< #if NUM_MOTION_SENSORS > NUM_RUNOUT_SENSORS NUM_MOTION_SENSORS #else NUM_RUNOUT_SENSORS #endif > runout_flags_t; void event_filament_runout(const uint8_t extruder); inline bool should_monitor_runout() { return did_pause_print || printingIsActive(); } template<class RESPONSE_T, class SENSOR_T> class TFilamentMonitor; class FilamentSensor; class RunoutResponseDelayed; class RunoutResponseDebounced; /********************************* TEMPLATE SPECIALIZATION *********************************/ typedef TFilamentMonitor< TERN(HAS_FILAMENT_RUNOUT_DISTANCE, RunoutResponseDelayed, RunoutResponseDebounced), FilamentSensor > FilamentMonitor; extern FilamentMonitor runout; /*******************************************************************************************/ class FilamentMonitorBase { public: static bool enabled, filament_ran_out; #if ENABLED(HOST_ACTION_COMMANDS) static bool host_handling; #else static constexpr bool host_handling = false; #endif }; template<class RESPONSE_T, class SENSOR_T> class TFilamentMonitor : public FilamentMonitorBase { private: typedef RESPONSE_T response_t; typedef SENSOR_T sensor_t; static response_t response; static sensor_t sensor; public: static void setup() { sensor.setup(); reset(); } static void reset() { filament_ran_out = false; response.reset(); } // Call this method when filament is present, // so the response can reset its counter. static void filament_present(const uint8_t extruder) { response.filament_present(extruder); } #if ENABLED(FILAMENT_SWITCH_AND_MOTION) static void filament_motion_present(const uint8_t extruder) { response.filament_motion_present(extruder); } #endif #if HAS_FILAMENT_RUNOUT_DISTANCE static float& runout_distance() { return response.runout_distance_mm; } static void set_runout_distance(const_float_t mm) { response.runout_distance_mm = mm; } #endif // Handle a block completion. RunoutResponseDelayed uses this to // add up the length of filament moved while the filament is out. static void block_completed(const block_t * const b) { if (enabled) { response.block_completed(b); sensor.block_completed(b); } } // Give the response a chance to update its counter. static void run() { if (enabled && !filament_ran_out && should_monitor_runout()) { TERN_(HAS_FILAMENT_RUNOUT_DISTANCE, cli()); // Prevent RunoutResponseDelayed::block_completed from accumulating here response.run(); sensor.run(); const runout_flags_t runout_flags = response.has_run_out(); TERN_(HAS_FILAMENT_RUNOUT_DISTANCE, sei()); #if MULTI_FILAMENT_SENSOR #if ENABLED(WATCH_ALL_RUNOUT_SENSORS) const bool ran_out = bool(runout_flags); // any sensor triggers uint8_t extruder = 0; if (ran_out) while (!runout_flags.test(extruder)) extruder++; #else const bool ran_out = runout_flags[active_extruder]; // suppress non active extruders uint8_t extruder = active_extruder; #endif #else const bool ran_out = bool(runout_flags); uint8_t extruder = active_extruder; #endif if (ran_out) { #if ENABLED(FILAMENT_RUNOUT_SENSOR_DEBUG) SERIAL_ECHOPGM("Runout Sensors: "); for (uint8_t i = 0; i < 8; ++i) SERIAL_CHAR('0' + char(runout_flags[i])); SERIAL_ECHOLNPGM(" -> ", extruder, " RUN OUT"); #endif filament_ran_out = true; event_filament_runout(extruder); planner.synchronize(); } } } }; /*************************** FILAMENT PRESENCE SENSORS ***************************/ class FilamentSensorBase { protected: /** * Called by FilamentSensorSwitch::run when filament is detected. * Called by FilamentSensorEncoder::block_completed when motion is detected. */ static void filament_present(const uint8_t extruder) { runout.filament_present(extruder); // ...which calls response.filament_present(extruder) } #if ENABLED(FILAMENT_SWITCH_AND_MOTION) static void filament_motion_present(const uint8_t extruder) { runout.filament_motion_present(extruder); // ...which calls response.filament_motion_present(extruder) } #endif public: static void setup() { #define _INIT_RUNOUT_PIN(P,S,U,D) do{ if (ENABLED(U)) SET_INPUT_PULLUP(P); else if (ENABLED(D)) SET_INPUT_PULLDOWN(P); else SET_INPUT(P); }while(0); #define INIT_RUNOUT_PIN(N) _INIT_RUNOUT_PIN(FIL_RUNOUT##N##_PIN, FIL_RUNOUT##N##_STATE, FIL_RUNOUT##N##_PULLUP, FIL_RUNOUT##N##_PULLDOWN); REPEAT_1(NUM_RUNOUT_SENSORS, INIT_RUNOUT_PIN) #undef INIT_RUNOUT_PIN #if ENABLED(FILAMENT_SWITCH_AND_MOTION) #define INIT_MOTION_PIN(N) _INIT_RUNOUT_PIN(FIL_MOTION##N##_PIN, FIL_MOTION##N##_STATE, FIL_MOTION##N##_PULLUP, FIL_MOTION##N##_PULLDOWN); REPEAT_1(NUM_MOTION_SENSORS, INIT_MOTION_PIN) #undef INIT_MOTION_PIN #endif #undef _INIT_RUNOUT_PIN } // Return a bitmask of runout pin states static uint8_t poll_runout_pins() { #define _OR_RUNOUT(N) | (READ(FIL_RUNOUT##N##_PIN) ? _BV((N) - 1) : 0) return (0 REPEAT_1(NUM_RUNOUT_SENSORS, _OR_RUNOUT)); #undef _OR_RUNOUT } // Return a bitmask of runout flag states (1 bits always indicates runout) static uint8_t poll_runout_states() { #define _INVERT_BIT(N) | (FIL_RUNOUT##N##_STATE ? 0 : _BV(N - 1)) return poll_runout_pins() ^ uint8_t(0 REPEAT_1(NUM_RUNOUT_SENSORS, _INVERT_BIT)); #undef _INVERT_BIT } #if ENABLED(FILAMENT_SWITCH_AND_MOTION) // Return a bitmask of motion pin states static uint8_t poll_motion_pins() { #define _OR_MOTION(N) | (READ(FIL_MOTION##N##_PIN) ? _BV((N) - 1) : 0) return (0 REPEAT_1(NUM_MOTION_SENSORS, _OR_MOTION)); #undef _OR_MOTION } // Return a bitmask of motion flag states (1 bits always indicates runout) static uint8_t poll_motion_states() { #define _OR_MOTION(N) | (FIL_MOTION##N##_STATE ? 0 : _BV(N - 1)) return poll_motion_pins() ^ uint8_t(0 REPEAT_1(NUM_MOTION_SENSORS, _OR_MOTION)); #undef _OR_MOTION } #endif }; #if HAS_FILAMENT_MOTION /** * This sensor uses a magnetic encoder disc and a Hall effect * sensor (or a slotted disc and optical sensor). The state * will toggle between 0 and 1 on filament movement. It can detect * filament runout and stripouts or jams. */ class FilamentSensorEncoder : public FilamentSensorBase { private: static uint8_t motion_detected; static void poll_motion_sensor() { static uint8_t old_state; const uint8_t new_state = TERN(FILAMENT_SWITCH_AND_MOTION, poll_motion_pins, poll_runout_pins)(), change = old_state ^ new_state; old_state = new_state; #if ENABLED(FILAMENT_RUNOUT_SENSOR_DEBUG) if (change) { SERIAL_ECHOPGM("Motion detected:"); for (uint8_t e = 0; e < TERN(FILAMENT_SWITCH_AND_MOTION, NUM_MOTION_SENSORS, NUM_RUNOUT_SENSORS); ++e) if (TEST(change, e)) SERIAL_CHAR(' ', '0' + e); SERIAL_EOL(); } #endif motion_detected |= change; } public: static void block_completed(const block_t * const b) { // If the sensor wheel has moved since the last call to // this method reset the runout counter for the extruder. if (TEST(motion_detected, b->extruder)) TERN(FILAMENT_SWITCH_AND_MOTION, filament_motion_present, filament_present)(b->extruder); // Clear motion triggers for next block motion_detected = 0; } static void run() { poll_motion_sensor(); } }; #endif // HAS_FILAMENT_MOTION #if HAS_FILAMENT_SWITCH /** * This is a simple endstop switch in the path of the filament. * It can detect filament runout, but not stripouts or jams. */ class FilamentSensorSwitch : public FilamentSensorBase { private: static bool poll_runout_state(const uint8_t extruder) { const uint8_t runout_states = poll_runout_states(); #if MULTI_FILAMENT_SENSOR if ( !TERN0(DUAL_X_CARRIAGE, idex_is_duplicating()) && !TERN0(MULTI_NOZZLE_DUPLICATION, extruder_duplication_enabled) ) return TEST(runout_states, extruder); // A specific extruder ran out #else UNUSED(extruder); #endif return !!runout_states; // Any extruder ran out } public: static void block_completed(const block_t * const) {} static void run() { for (uint8_t s = 0; s < NUM_RUNOUT_SENSORS; ++s) { const bool out = poll_runout_state(s); if (!out) filament_present(s); #if ENABLED(FILAMENT_RUNOUT_SENSOR_DEBUG) static uint8_t was_out; // = 0 if (out != TEST(was_out, s)) { TBI(was_out, s); SERIAL_ECHOLN(F("Filament Sensor "), AS_DIGIT(s), out ? F(" OUT") : F(" IN")); } #endif } } }; #endif // HAS_FILAMENT_SWITCH /** * This is a simple endstop switch in the path of the filament. * It can detect filament runout, but not stripouts or jams. */ class FilamentSensor : public FilamentSensorBase { private: TERN_(HAS_FILAMENT_MOTION, static FilamentSensorEncoder encoder_sensor); TERN_(HAS_FILAMENT_SWITCH, static FilamentSensorSwitch switch_sensor); public: static void block_completed(const block_t * const b) { TERN_(HAS_FILAMENT_MOTION, encoder_sensor.block_completed(b)); TERN_(HAS_FILAMENT_SWITCH, switch_sensor.block_completed(b)); } static void run() { TERN_(HAS_FILAMENT_MOTION, encoder_sensor.run()); TERN_(HAS_FILAMENT_SWITCH, switch_sensor.run()); } }; /********************************* RESPONSE TYPE *********************************/ #if HAS_FILAMENT_RUNOUT_DISTANCE typedef struct { float runout[NUM_RUNOUT_SENSORS]; Flags<NUM_RUNOUT_SENSORS> runout_reset; // Reset runout later #if ENABLED(FILAMENT_SWITCH_AND_MOTION) float motion[NUM_MOTION_SENSORS]; Flags<NUM_MOTION_SENSORS> motion_reset; // Reset motion later #endif } countdown_t; // RunoutResponseDelayed triggers a runout event only if the length // of filament specified by FILAMENT_RUNOUT_DISTANCE_MM has been fed // during a runout condition. class RunoutResponseDelayed { private: static countdown_t mm_countdown; public: static float runout_distance_mm; static void reset() { for (uint8_t i = 0; i < NUM_RUNOUT_SENSORS; ++i) filament_present(i); #if ENABLED(FILAMENT_SWITCH_AND_MOTION) for (uint8_t i = 0; i < NUM_MOTION_SENSORS; ++i) filament_motion_present(i); #endif } static void run() { #if ENABLED(FILAMENT_RUNOUT_SENSOR_DEBUG) static millis_t t = 0; const millis_t ms = millis(); if (ELAPSED(ms, t)) { t = millis() + 1000UL; for (uint8_t i = 0; i < NUM_RUNOUT_SENSORS; ++i) SERIAL_ECHO(i ? F(", ") : F("Runout remaining mm: "), mm_countdown.runout[i]); #if ENABLED(FILAMENT_SWITCH_AND_MOTION) for (uint8_t i = 0; i < NUM_MOTION_SENSORS; ++i) SERIAL_ECHO(i ? F(", ") : F("Motion remaining mm: "), mm_countdown.motion[i]); #endif SERIAL_EOL(); } #endif } static runout_flags_t has_run_out() { runout_flags_t runout_flags{0}; for (uint8_t i = 0; i < NUM_RUNOUT_SENSORS; ++i) if (mm_countdown.runout[i] < 0) runout_flags.set(i); #if ENABLED(FILAMENT_SWITCH_AND_MOTION) for (uint8_t i = 0; i < NUM_MOTION_SENSORS; ++i) if (mm_countdown.motion[i] < 0) runout_flags.set(i); #endif return runout_flags; } static void filament_present(const uint8_t extruder) { if (mm_countdown.runout[extruder] < runout_distance_mm || did_pause_print) { // Reset runout only if it is smaller than runout_distance or printing is paused. // On Bowden systems retract may be larger than runout_distance_mm, so if retract // was added leave it in place, or the following unretract will cause runout event. mm_countdown.runout[extruder] = runout_distance_mm; mm_countdown.runout_reset.clear(extruder); } else { // If runout is larger than runout distance, we cannot reset right now, as Bowden and retract // distance larger than runout_distance_mm leads to negative runout right after unretract. // But we cannot ignore filament_present event. After unretract, runout will become smaller // than runout_distance_mm and should be reset after that. So activate delayed reset. mm_countdown.runout_reset.set(extruder); } } #if ENABLED(FILAMENT_SWITCH_AND_MOTION) static void filament_motion_present(const uint8_t extruder) { // Same logic as filament_present if (mm_countdown.motion[extruder] < runout_distance_mm || did_pause_print) { mm_countdown.motion[extruder] = runout_distance_mm; mm_countdown.motion_reset.clear(extruder); } else mm_countdown.motion_reset.set(extruder); } #endif static void block_completed(const block_t * const b) { const int32_t esteps = b->steps.e; if (!esteps) return; // No calculation unless paused or printing if (!should_monitor_runout()) return; // No need to ignore retract/unretract movement since they complement each other const uint8_t e = b->extruder; const float mm = (b->direction_bits.e ? esteps : -esteps) * planner.mm_per_step[E_AXIS_N(e)]; if (e < NUM_RUNOUT_SENSORS) { mm_countdown.runout[e] -= mm; if (mm_countdown.runout_reset[e]) filament_present(e); // Reset pending. Try to reset. } #if ENABLED(FILAMENT_SWITCH_AND_MOTION) if (e < NUM_MOTION_SENSORS) { mm_countdown.motion[e] -= mm; if (mm_countdown.motion_reset[e]) filament_motion_present(e); // Reset pending. Try to reset. } #endif } }; #else // !HAS_FILAMENT_RUNOUT_DISTANCE // RunoutResponseDebounced triggers a runout event after a runout // condition has been detected runout_threshold times in a row. class RunoutResponseDebounced { private: static constexpr int8_t runout_threshold = FILAMENT_RUNOUT_THRESHOLD; static int8_t runout_count[NUM_RUNOUT_SENSORS]; public: static void reset() { for (uint8_t i = 0; i < NUM_RUNOUT_SENSORS; ++i) filament_present(i); } static void run() { for (uint8_t i = 0; i < NUM_RUNOUT_SENSORS; ++i) if (runout_count[i] >= 0) runout_count[i]--; } static runout_flags_t has_run_out() { runout_flags_t runout_flags{0}; for (uint8_t i = 0; i < NUM_RUNOUT_SENSORS; ++i) if (runout_count[i] < 0) runout_flags.set(i); return runout_flags; } static void block_completed(const block_t * const) { } static void filament_present(const uint8_t extruder) { runout_count[extruder] = runout_threshold; } }; #endif // !HAS_FILAMENT_RUNOUT_DISTANCE
2301_81045437/Marlin
Marlin/src/feature/runout.h
C++
agpl-3.0
17,399
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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 ANY(EXT_SOLENOID, MANUAL_SOLENOID_CONTROL) #include "solenoid.h" #include "../module/motion.h" // for active_extruder #include "../module/tool_change.h" // for parking_extruder_set_parked // Used primarily with MANUAL_SOLENOID_CONTROL static void set_solenoid(const uint8_t num, const uint8_t state) { #define _SOL_CASE(N) case N: TERN_(HAS_SOLENOID_##N, OUT_WRITE(SOL##N##_PIN, state)); break; switch (num) { REPEAT(8, _SOL_CASE) default: SERIAL_ECHO_MSG(STR_INVALID_SOLENOID); break; } #if ENABLED(PARKING_EXTRUDER) if (state == LOW && active_extruder == num) // If active extruder's solenoid is disabled, carriage is considered parked parking_extruder_set_parked(true); #endif } // PARKING_EXTRUDER options alter the default behavior of solenoids to ensure compliance of M380-381 void enable_solenoid(const uint8_t num) { set_solenoid(num, TERN1(PARKING_EXTRUDER, PE_MAGNET_ON_STATE)); } void disable_solenoid(const uint8_t num) { set_solenoid(num, TERN0(PARKING_EXTRUDER, !PE_MAGNET_ON_STATE)); } void disable_all_solenoids() { #define _SOL_DISABLE(N) TERN_(HAS_SOLENOID_##N, disable_solenoid(N)); REPEAT(8, _SOL_DISABLE) } #endif // EXT_SOLENOID || MANUAL_SOLENOID_CONTROL
2301_81045437/Marlin
Marlin/src/feature/solenoid.cpp
C++
agpl-3.0
2,120
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once void disable_all_solenoids(); void enable_solenoid(const uint8_t num); void disable_solenoid(const uint8_t num);
2301_81045437/Marlin
Marlin/src/feature/solenoid.h
C
agpl-3.0
989
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * feature/spindle_laser.cpp */ #include "../inc/MarlinConfig.h" #if HAS_CUTTER #include "spindle_laser.h" #if ENABLED(SPINDLE_SERVO) #include "../module/servo.h" #endif #if ENABLED(I2C_AMMETER) #include "../feature/ammeter.h" #endif SpindleLaser cutter; bool SpindleLaser::enable_state; // Virtual enable state, controls enable pin if present and or apply power if > 0 uint8_t SpindleLaser::power, // Actual power output 0-255 ocr or "0 = off" > 0 = "on" SpindleLaser::last_power_applied; // = 0 // Basic power state tracking #if ENABLED(LASER_FEATURE) cutter_test_pulse_t SpindleLaser::testPulse = 50; // (ms) Test fire pulse default duration uint8_t SpindleLaser::last_block_power; // = 0 // Track power changes for dynamic inline power feedRate_t SpindleLaser::feedrate_mm_m = 1500, SpindleLaser::last_feedrate_mm_m; // = 0 // (mm/min) Track feedrate changes for dynamic power #endif bool SpindleLaser::isReadyForUI = false; // Ready to apply power setting from the UI to OCR CutterMode SpindleLaser::cutter_mode = CUTTER_MODE_STANDARD; // Default is standard mode constexpr cutter_cpower_t SpindleLaser::power_floor; cutter_power_t SpindleLaser::menuPower = 0, // Power value via LCD menu in PWM, PERCENT, or RPM based on configured format set by CUTTER_POWER_UNIT. SpindleLaser::unitPower = 0; // Unit power is in PWM, PERCENT, or RPM based on CUTTER_POWER_UNIT. cutter_frequency_t SpindleLaser::frequency; // PWM frequency setting; range: 2K - 50K #define SPINDLE_LASER_PWM_OFF TERN(SPINDLE_LASER_PWM_INVERT, 255, 0) /** * Init the cutter to a safe OFF state */ void SpindleLaser::init() { #if ENABLED(SPINDLE_SERVO) servo[SPINDLE_SERVO_NR].move(SPINDLE_SERVO_MIN); #elif PIN_EXISTS(SPINDLE_LASER_ENA) OUT_WRITE(SPINDLE_LASER_ENA_PIN, !SPINDLE_LASER_ACTIVE_STATE); // Init spindle to off #endif #if ENABLED(SPINDLE_CHANGE_DIR) OUT_WRITE(SPINDLE_DIR_PIN, SPINDLE_INVERT_DIR); // Init rotation to clockwise (M3) #endif #if ENABLED(HAL_CAN_SET_PWM_FREQ) && SPINDLE_LASER_FREQUENCY frequency = SPINDLE_LASER_FREQUENCY; hal.set_pwm_frequency(pin_t(SPINDLE_LASER_PWM_PIN), SPINDLE_LASER_FREQUENCY); #endif #if ENABLED(SPINDLE_LASER_USE_PWM) SET_PWM(SPINDLE_LASER_PWM_PIN); hal.set_pwm_duty(pin_t(SPINDLE_LASER_PWM_PIN), SPINDLE_LASER_PWM_OFF); // Set to lowest speed #endif #if ENABLED(AIR_EVACUATION) OUT_WRITE(AIR_EVACUATION_PIN, !AIR_EVACUATION_ACTIVE); // Init Vacuum/Blower OFF #endif #if ENABLED(AIR_ASSIST) OUT_WRITE(AIR_ASSIST_PIN, !AIR_ASSIST_ACTIVE); // Init Air Assist OFF #endif TERN_(I2C_AMMETER, ammeter.init()); // Init I2C Ammeter } #if ENABLED(SPINDLE_LASER_USE_PWM) /** * Set the cutter PWM directly to the given ocr value * * @param ocr Power value */ void SpindleLaser::_set_ocr(const uint8_t ocr) { #if ENABLED(HAL_CAN_SET_PWM_FREQ) && SPINDLE_LASER_FREQUENCY hal.set_pwm_frequency(pin_t(SPINDLE_LASER_PWM_PIN), frequency); #endif hal.set_pwm_duty(pin_t(SPINDLE_LASER_PWM_PIN), ocr ^ SPINDLE_LASER_PWM_OFF); } void SpindleLaser::set_ocr(const uint8_t ocr) { #if PIN_EXISTS(SPINDLE_LASER_ENA) WRITE(SPINDLE_LASER_ENA_PIN, SPINDLE_LASER_ACTIVE_STATE); // Cutter ON #endif _set_ocr(ocr); } void SpindleLaser::ocr_off() { #if PIN_EXISTS(SPINDLE_LASER_ENA) WRITE(SPINDLE_LASER_ENA_PIN, !SPINDLE_LASER_ACTIVE_STATE); // Cutter OFF #endif _set_ocr(0); } #endif // SPINDLE_LASER_USE_PWM /** * Apply power for Laser or Spindle * * Apply cutter power value for PWM, Servo, and on/off pin. * * @param opwr Power value. Range 0 to MAX. */ void SpindleLaser::apply_power(const uint8_t opwr) { if (enabled() || opwr == 0) { // 0 check allows us to disable where no ENA pin exists // Test and set the last power used to improve performance if (opwr == last_power_applied) return; last_power_applied = opwr; // Handle PWM driven or just simple on/off #if ENABLED(SPINDLE_LASER_USE_PWM) if (CUTTER_UNIT_IS(RPM) && unitPower == 0) ocr_off(); else if (ENABLED(CUTTER_POWER_RELATIVE) || enabled() || opwr == 0) { set_ocr(opwr); isReadyForUI = true; } else ocr_off(); #elif ENABLED(SPINDLE_SERVO) servo[SPINDLE_SERVO_NR].move(opwr); #else WRITE(SPINDLE_LASER_ENA_PIN, enabled() ? SPINDLE_LASER_ACTIVE_STATE : !SPINDLE_LASER_ACTIVE_STATE); isReadyForUI = true; #endif } else { #if PIN_EXISTS(SPINDLE_LASER_ENA) WRITE(SPINDLE_LASER_ENA_PIN, !SPINDLE_LASER_ACTIVE_STATE); #endif isReadyForUI = false; // Only used for UI display updates. TERN_(SPINDLE_LASER_USE_PWM, ocr_off()); } } #if ENABLED(SPINDLE_CHANGE_DIR) /** * Set the spindle direction and apply immediately * Stop on direction change if SPINDLE_STOP_ON_DIR_CHANGE is enabled */ void SpindleLaser::set_reverse(const bool reverse) { const bool dir_state = (reverse == SPINDLE_INVERT_DIR); // Forward (M3) HIGH when not inverted if (TERN0(SPINDLE_STOP_ON_DIR_CHANGE, enabled()) && READ(SPINDLE_DIR_PIN) != dir_state) disable(); WRITE(SPINDLE_DIR_PIN, dir_state); } #endif #if ENABLED(AIR_EVACUATION) // Enable / disable Cutter Vacuum or Laser Blower motor void SpindleLaser::air_evac_enable() { WRITE(AIR_EVACUATION_PIN, AIR_EVACUATION_ACTIVE); } // Turn ON void SpindleLaser::air_evac_disable() { WRITE(AIR_EVACUATION_PIN, !AIR_EVACUATION_ACTIVE); } // Turn OFF void SpindleLaser::air_evac_toggle() { TOGGLE(AIR_EVACUATION_PIN); } // Toggle state #endif #if ENABLED(AIR_ASSIST) // Enable / disable air assist void SpindleLaser::air_assist_enable() { WRITE(AIR_ASSIST_PIN, AIR_ASSIST_ACTIVE); } // Turn ON void SpindleLaser::air_assist_disable() { WRITE(AIR_ASSIST_PIN, !AIR_ASSIST_ACTIVE); } // Turn OFF void SpindleLaser::air_assist_toggle() { TOGGLE(AIR_ASSIST_PIN); } // Toggle state #endif #endif // HAS_CUTTER
2301_81045437/Marlin
Marlin/src/feature/spindle_laser.cpp
C++
agpl-3.0
7,232
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * feature/spindle_laser.h * Support for Laser Power or Spindle Power & Direction */ #include "../inc/MarlinConfig.h" #include "spindle_laser_types.h" #include "../libs/buzzer.h" // Inline laser power #include "../module/planner.h" #define PCT_TO_PWM(X) ((X) * 255 / 100) #define PCT_TO_SERVO(X) ((X) * 180 / 100) // Laser/Cutter operation mode enum CutterMode : int8_t { CUTTER_MODE_ERROR = -1, CUTTER_MODE_STANDARD, // M3 power is applied directly and waits for planner moves to sync. CUTTER_MODE_CONTINUOUS, // M3 or G1/2/3 move power is controlled within planner blocks, set with 'M3 I', cleared with 'M5 I'. CUTTER_MODE_DYNAMIC // M4 laser power is proportional to the feed rate, set with 'M4 I', cleared with 'M5 I'. }; class SpindleLaser { public: static CutterMode cutter_mode; static constexpr uint8_t pct_to_ocr(const_float_t pct) { return uint8_t(PCT_TO_PWM(pct)); } // cpower = configured values (e.g., SPEED_POWER_MAX) // Convert configured power range to a percentage static constexpr cutter_cpower_t power_floor = TERN(CUTTER_POWER_RELATIVE, SPEED_POWER_MIN, 0); static constexpr uint8_t cpwr_to_pct(const cutter_cpower_t cpwr) { return cpwr ? round(100.0f * (cpwr - power_floor) / (SPEED_POWER_MAX - power_floor)) : 0; } // Convert config defines from RPM to %, angle or PWM when in Spindle mode // and convert from PERCENT to PWM when in Laser mode static constexpr cutter_power_t cpwr_to_upwr(const cutter_cpower_t cpwr) { // STARTUP power to Unit power return ( #if ENABLED(SPINDLE_FEATURE) // Spindle configured define values are in RPM #if CUTTER_UNIT_IS(RPM) cpwr // to same #elif CUTTER_UNIT_IS(PERCENT) cpwr_to_pct(cpwr) // to Percent #elif CUTTER_UNIT_IS(SERVO) PCT_TO_SERVO(cpwr_to_pct(cpwr)) // to SERVO angle #else PCT_TO_PWM(cpwr_to_pct(cpwr)) // to PWM #endif #else // Laser configured define values are in Percent #if CUTTER_UNIT_IS(PWM255) PCT_TO_PWM(cpwr) // to PWM #else cpwr // to same #endif #endif ); } static constexpr cutter_power_t mpower_min() { return cpwr_to_upwr(SPEED_POWER_MIN); } static constexpr cutter_power_t mpower_max() { return cpwr_to_upwr(SPEED_POWER_MAX); } #if ENABLED(LASER_FEATURE) static cutter_test_pulse_t testPulse; // (ms) Test fire pulse duration static uint8_t last_block_power; // Track power changes for dynamic power static feedRate_t feedrate_mm_m, last_feedrate_mm_m; // (mm/min) Track feedrate changes for dynamic power static bool laser_feedrate_changed() { const bool changed = last_feedrate_mm_m != feedrate_mm_m; if (changed) last_feedrate_mm_m = feedrate_mm_m; return changed; } #endif static bool isReadyForUI; // Ready to apply power setting from the UI to OCR static bool enable_state; static uint8_t power, last_power_applied; // Basic power state tracking static cutter_frequency_t frequency; // Set PWM frequency; range: 2K-50K static cutter_power_t menuPower, // Power as set via LCD menu in PWM, Percentage or RPM unitPower; // Power as displayed status in PWM, Percentage or RPM static void init(); #if ENABLED(HAL_CAN_SET_PWM_FREQ) && SPINDLE_LASER_FREQUENCY static void refresh_frequency() { hal.set_pwm_frequency(pin_t(SPINDLE_LASER_PWM_PIN), frequency); } #endif // Modifying this function should update everywhere static bool enabled(const cutter_power_t opwr) { return opwr > 0; } static bool enabled() { return enable_state; } static void apply_power(const uint8_t inpow); FORCE_INLINE static void refresh() { apply_power(power); } #if ENABLED(SPINDLE_LASER_USE_PWM) private: static void _set_ocr(const uint8_t ocr); public: static void set_ocr(const uint8_t ocr); static void ocr_off(); /** * Update output for power->OCR translation */ static uint8_t upower_to_ocr(const cutter_power_t upwr) { return uint8_t( #if CUTTER_UNIT_IS(PWM255) upwr #elif CUTTER_UNIT_IS(PERCENT) pct_to_ocr(upwr) #else pct_to_ocr(cpwr_to_pct(upwr)) #endif ); } #endif // SPINDLE_LASER_USE_PWM /** * Correct power to configured range */ static cutter_power_t power_to_range(const cutter_power_t pwr, const uint8_t pwrUnit=_CUTTER_POWER(CUTTER_POWER_UNIT)) { static constexpr float min_pct = TERN(CUTTER_POWER_RELATIVE, 0, TERN(SPINDLE_FEATURE, round(100.0f * (SPEED_POWER_MIN) / (SPEED_POWER_MAX)), SPEED_POWER_MIN)), max_pct = TERN(SPINDLE_FEATURE, 100, SPEED_POWER_MAX); if (pwr <= 0) return 0; cutter_power_t upwr; switch (pwrUnit) { case _CUTTER_POWER_PWM255: { // PWM const uint8_t pmin = pct_to_ocr(min_pct), pmax = pct_to_ocr(max_pct); upwr = cutter_power_t(constrain(pwr, pmin, pmax)); } break; case _CUTTER_POWER_PERCENT: // Percent upwr = cutter_power_t(constrain(pwr, min_pct, max_pct)); break; case _CUTTER_POWER_RPM: // Calculate OCR value upwr = cutter_power_t(constrain(pwr, SPEED_POWER_MIN, SPEED_POWER_MAX)); break; default: break; } return upwr; } /** * Enable Laser or Spindle output. * It's important to prevent changing the power output value during inline cutter operation. * Inline power is adjusted in the planner to support LASER_TRAP_POWER and CUTTER_MODE_DYNAMIC mode. * * This method accepts one of the following control states: * * - For CUTTER_MODE_STANDARD the cutter power is either full on/off or ocr-based and it will apply * SPEED_POWER_STARTUP if no value is assigned. * * - For CUTTER_MODE_CONTINUOUS inline and power remains where last set and the cutter output enable flag is set. * * - CUTTER_MODE_DYNAMIC is also inline-based and it just sets the enable output flag. * * - For CUTTER_MODE_ERROR set the output enable_state flag directly and set power to 0 for any mode. * This mode allows a global power shutdown action to occur. */ static void set_enabled(bool enable) { switch (cutter_mode) { case CUTTER_MODE_STANDARD: apply_power(enable ? TERN(SPINDLE_LASER_USE_PWM, (power ?: (unitPower ? upower_to_ocr(cpwr_to_upwr(SPEED_POWER_STARTUP)) : 0)), 255) : 0); break; case CUTTER_MODE_CONTINUOUS: case CUTTER_MODE_DYNAMIC: TERN_(LASER_FEATURE, set_inline_enabled(enable)); break; case CUTTER_MODE_ERROR: // Error mode, no enable and kill power. enable = false; apply_power(0); } #if PIN_EXISTS(SPINDLE_LASER_ENA) WRITE(SPINDLE_LASER_ENA_PIN, enable ? SPINDLE_LASER_ACTIVE_STATE : !SPINDLE_LASER_ACTIVE_STATE); #endif enable_state = enable; } static void disable() { isReadyForUI = false; set_enabled(false); } // Wait for spindle/laser to startup or shutdown static void power_delay(const bool on) { safe_delay(on ? SPINDLE_LASER_POWERUP_DELAY : SPINDLE_LASER_POWERDOWN_DELAY); } #if ENABLED(SPINDLE_CHANGE_DIR) static void set_reverse(const bool reverse); static bool is_reverse() { return READ(SPINDLE_DIR_PIN) == SPINDLE_INVERT_DIR; } #else static void set_reverse(const bool) {} static bool is_reverse() { return false; } #endif #if ENABLED(AIR_EVACUATION) static void air_evac_enable(); // Turn On Cutter Vacuum or Laser Blower motor static void air_evac_disable(); // Turn Off Cutter Vacuum or Laser Blower motor static void air_evac_toggle(); // Toggle Cutter Vacuum or Laser Blower motor static bool air_evac_state() { // Get current state return (READ(AIR_EVACUATION_PIN) == AIR_EVACUATION_ACTIVE); } #endif #if ENABLED(AIR_ASSIST) static void air_assist_enable(); // Turn on air assist static void air_assist_disable(); // Turn off air assist static void air_assist_toggle(); // Toggle air assist static bool air_assist_state() { // Get current state return (READ(AIR_ASSIST_PIN) == AIR_ASSIST_ACTIVE); } #endif #if HAS_MARLINUI_MENU #if ENABLED(SPINDLE_FEATURE) static void enable_with_dir(const bool reverse) { isReadyForUI = true; const uint8_t ocr = TERN(SPINDLE_LASER_USE_PWM, upower_to_ocr(menuPower), 255); if (menuPower) power = ocr; else menuPower = cpwr_to_upwr(SPEED_POWER_STARTUP); unitPower = menuPower; set_reverse(reverse); set_enabled(true); } FORCE_INLINE static void enable_forward() { enable_with_dir(false); } FORCE_INLINE static void enable_reverse() { enable_with_dir(true); } FORCE_INLINE static void enable_same_dir() { enable_with_dir(is_reverse()); } #endif // SPINDLE_FEATURE #if ENABLED(SPINDLE_LASER_USE_PWM) static void update_from_mpower() { if (isReadyForUI) power = upower_to_ocr(menuPower); unitPower = menuPower; } #endif #if ENABLED(LASER_FEATURE) // Toggle the laser on/off with menuPower. Apply SPEED_POWER_STARTUP if it was 0 on entry. static void menu_set_enabled(const bool state) { set_enabled(state); if (state) { if (!menuPower) menuPower = cpwr_to_upwr(SPEED_POWER_STARTUP); power = TERN(SPINDLE_LASER_USE_PWM, upower_to_ocr(menuPower), 255); apply_power(power); } else apply_power(0); } /** * Test fire the laser using the testPulse ms duration * Also fires with any PWM power that was previous set * If not set defaults to 80% power */ static void test_fire_pulse() { BUZZ(30, 3000); cutter_mode = CUTTER_MODE_STANDARD; // Menu needs standard mode. menu_set_enabled(true); // Laser On delay(testPulse); // Delay for time set by user in pulse ms menu screen. menu_set_enabled(false); // Laser Off } #endif // LASER_FEATURE #endif // HAS_MARLINUI_MENU #if ENABLED(LASER_FEATURE) // Dynamic mode rate calculation static uint8_t calc_dynamic_power() { if (feedrate_mm_m > 65535) return 255; // Too fast, go always on uint16_t rate = uint16_t(feedrate_mm_m); // 16 bits from the G-code parser float input rate >>= 8; // Take the G-code input e.g. F40000 and shift off the lower bits to get an OCR value from 1-255 return uint8_t(rate); } // Inline modes of all other functions; all enable planner inline power control static void set_inline_enabled(const bool enable) { planner.laser_inline.status.isEnabled = enable; } // Set the power for subsequent movement blocks static void inline_power(const cutter_power_t cpwr) { TERN(SPINDLE_LASER_USE_PWM, power = planner.laser_inline.power = cpwr, planner.laser_inline.power = cpwr > 0 ? 255 : 0); } #endif // LASER_FEATURE static void kill() { disable(); } }; extern SpindleLaser cutter;
2301_81045437/Marlin
Marlin/src/feature/spindle_laser.h
C++
agpl-3.0
12,219
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * feature/spindle_laser_types.h * Support for Laser Power or Spindle Power & Direction */ #include "../inc/MarlinConfigPre.h" #define MSG_CUTTER(M) _MSG_CUTTER(M) #ifndef SPEED_POWER_INTERCEPT #define SPEED_POWER_INTERCEPT 0 #endif #if ENABLED(SPINDLE_FEATURE) #define _MSG_CUTTER(M) MSG_SPINDLE_##M #ifndef SPEED_POWER_MIN #define SPEED_POWER_MIN 5000 #endif #ifndef SPEED_POWER_MAX #define SPEED_POWER_MAX 30000 #endif #ifndef SPEED_POWER_STARTUP #define SPEED_POWER_STARTUP 25000 #endif #else #define _MSG_CUTTER(M) MSG_LASER_##M #ifndef SPEED_POWER_MIN #define SPEED_POWER_MIN 0 #endif #ifndef SPEED_POWER_MAX #define SPEED_POWER_MAX 255 #endif #ifndef SPEED_POWER_STARTUP #define SPEED_POWER_STARTUP 255 #endif #endif typedef uvalue_t(SPEED_POWER_MAX) cutter_cpower_t; #if CUTTER_UNIT_IS(RPM) && SPEED_POWER_MAX > 255 typedef uint16_t cutter_power_t; #define CUTTER_MENU_POWER_TYPE uint16_5 #define cutter_power2str ui16tostr5rj #else typedef uint8_t cutter_power_t; #if CUTTER_UNIT_IS(PERCENT) #define CUTTER_MENU_POWER_TYPE percent_3 #define cutter_power2str pcttostrpctrj #else #define CUTTER_MENU_POWER_TYPE uint8 #define cutter_power2str ui8tostr3rj #endif #endif typedef uint16_t cutter_frequency_t; #if ENABLED(LASER_FEATURE) typedef uint16_t cutter_test_pulse_t; #define CUTTER_MENU_PULSE_TYPE uint16_3 #define CUTTER_MENU_FREQUENCY_TYPE uint16_5 #endif
2301_81045437/Marlin
Marlin/src/feature/spindle_laser_types.h
C
agpl-3.0
2,394
/** * 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" #include "../lcd/marlinui.h" #if HAS_DRIVER_SAFE_POWER_PROTECT #include "stepper_driver_safety.h" static uint32_t axis_plug_backward = 0; void stepper_driver_backward_error(FSTR_P const fstr) { SERIAL_ERROR_START(); SERIAL_ECHOLN(fstr, F(" driver is backward!")); ui.status_printf(2, F(S_FMT S_FMT), FTOP(fstr), GET_TEXT_F(MSG_DRIVER_BACKWARD)); } void stepper_driver_backward_check() { OUT_WRITE(SAFE_POWER_PIN, LOW); #define _TEST_BACKWARD(AXIS, BIT) do { \ SET_INPUT(AXIS##_ENABLE_PIN); \ OUT_WRITE(AXIS##_STEP_PIN, false); \ delay(20); \ if (READ(AXIS##_ENABLE_PIN) == LOW) { \ SBI(axis_plug_backward, BIT); \ stepper_driver_backward_error(F(STRINGIFY(AXIS))); \ } \ }while(0) #define TEST_BACKWARD(AXIS, BIT) TERN_(HAS_##AXIS##_ENABLE, _TEST_BACKWARD(AXIS, BIT)) TEST_BACKWARD(X, 0); TEST_BACKWARD(X2, 1); TEST_BACKWARD(Y, 2); TEST_BACKWARD(Y2, 3); TEST_BACKWARD(Z, 4); TEST_BACKWARD(Z2, 5); TEST_BACKWARD(Z3, 6); TEST_BACKWARD(Z4, 7); TEST_BACKWARD(I, 8); TEST_BACKWARD(J, 9); TEST_BACKWARD(K, 10); TEST_BACKWARD(U, 11); TEST_BACKWARD(V, 12); TEST_BACKWARD(W, 13); TEST_BACKWARD(E0, 14); TEST_BACKWARD(E1, 15); TEST_BACKWARD(E2, 16); TEST_BACKWARD(E3, 17); TEST_BACKWARD(E4, 18); TEST_BACKWARD(E5, 19); TEST_BACKWARD(E6, 20); TEST_BACKWARD(E7, 21); if (!axis_plug_backward) WRITE(SAFE_POWER_PIN, HIGH); } void stepper_driver_backward_report() { if (!axis_plug_backward) return; auto _report_if_backward = [](FSTR_P const axis, uint8_t bit) { if (TEST(axis_plug_backward, bit)) stepper_driver_backward_error(axis); }; #define REPORT_BACKWARD(axis, bit) TERN_(HAS_##axis##_ENABLE, _report_if_backward(F(STRINGIFY(axis)), bit)) REPORT_BACKWARD(X, 0); REPORT_BACKWARD(X2, 1); REPORT_BACKWARD(Y, 2); REPORT_BACKWARD(Y2, 3); REPORT_BACKWARD(Z, 4); REPORT_BACKWARD(Z2, 5); REPORT_BACKWARD(Z3, 6); REPORT_BACKWARD(Z4, 7); REPORT_BACKWARD(I, 8); REPORT_BACKWARD(J, 9); REPORT_BACKWARD(K, 10); REPORT_BACKWARD(U, 11); REPORT_BACKWARD(V, 12); REPORT_BACKWARD(W, 13); REPORT_BACKWARD(E0, 14); REPORT_BACKWARD(E1, 15); REPORT_BACKWARD(E2, 16); REPORT_BACKWARD(E3, 17); REPORT_BACKWARD(E4, 18); REPORT_BACKWARD(E5, 19); REPORT_BACKWARD(E6, 20); REPORT_BACKWARD(E7, 21); } #endif // HAS_DRIVER_SAFE_POWER_PROTECT
2301_81045437/Marlin
Marlin/src/feature/stepper_driver_safety.cpp
C++
agpl-3.0
3,334
/** * 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" void stepper_driver_backward_check(); void stepper_driver_backward_report();
2301_81045437/Marlin
Marlin/src/feature/stepper_driver_safety.h
C
agpl-3.0
990
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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_TRINAMIC_CONFIG #include "tmc_util.h" #include "../MarlinCore.h" #include "../module/stepper/indirection.h" #include "../module/printcounter.h" #include "../libs/duration_t.h" #include "../gcode/gcode.h" #if ENABLED(TMC_DEBUG) #include "../libs/hex_print.h" #if ENABLED(MONITOR_DRIVER_STATUS) static uint16_t report_tmc_status_interval; // = 0 #endif #endif /** * Check for over temperature or short to ground error flags. * Report and log warning of overtemperature condition. * Reduce driver current in a persistent otpw condition. * Keep track of otpw counter so we don't reduce current on a single instance, * and so we don't repeatedly report warning before the condition is cleared. */ #if ENABLED(MONITOR_DRIVER_STATUS) struct TMC_driver_data { uint32_t drv_status; bool is_otpw:1, is_ot:1, is_s2g:1, is_error:1 #if ENABLED(TMC_DEBUG) , is_stall:1 , is_stealth:1 , is_standstill:1 #if HAS_STALLGUARD , sg_result_reasonable:1 #endif #endif ; #if ENABLED(TMC_DEBUG) #if HAS_TMCX1X0 || HAS_TMC220x uint8_t cs_actual; #endif #if HAS_STALLGUARD uint16_t sg_result; #endif #endif }; #if HAS_TMCX1X0 #if ENABLED(TMC_DEBUG) static uint32_t get_pwm_scale(TMC2130Stepper &st) { return st.PWM_SCALE(); } #endif static TMC_driver_data get_driver_data(TMC2130Stepper &st) { constexpr uint8_t OT_bp = 25, OTPW_bp = 26; constexpr uint32_t S2G_bm = 0x18000000; #if ENABLED(TMC_DEBUG) constexpr uint16_t SG_RESULT_bm = 0x3FF; // 0:9 constexpr uint8_t STEALTH_bp = 14; constexpr uint32_t CS_ACTUAL_bm = 0x1F0000; // 16:20 constexpr uint8_t STALL_GUARD_bp = 24; constexpr uint8_t STST_bp = 31; #endif TMC_driver_data data; const auto ds = data.drv_status = st.DRV_STATUS(); #ifdef __AVR__ // 8-bit optimization saves up to 70 bytes of PROGMEM per axis uint8_t spart; #if ENABLED(TMC_DEBUG) data.sg_result = ds & SG_RESULT_bm; spart = ds >> 8; data.is_stealth = TEST(spart, STEALTH_bp - 8); spart = ds >> 16; data.cs_actual = spart & (CS_ACTUAL_bm >> 16); #endif spart = ds >> 24; data.is_ot = TEST(spart, OT_bp - 24); data.is_otpw = TEST(spart, OTPW_bp - 24); data.is_s2g = !!(spart & (S2G_bm >> 24)); #if ENABLED(TMC_DEBUG) data.is_stall = TEST(spart, STALL_GUARD_bp - 24); data.is_standstill = TEST(spart, STST_bp - 24); data.sg_result_reasonable = !data.is_standstill; // sg_result has no reasonable meaning while standstill #endif #else // !__AVR__ data.is_ot = TEST(ds, OT_bp); data.is_otpw = TEST(ds, OTPW_bp); data.is_s2g = !!(ds & S2G_bm); #if ENABLED(TMC_DEBUG) constexpr uint8_t CS_ACTUAL_sb = 16; data.sg_result = ds & SG_RESULT_bm; data.is_stealth = TEST(ds, STEALTH_bp); data.cs_actual = (ds & CS_ACTUAL_bm) >> CS_ACTUAL_sb; data.is_stall = TEST(ds, STALL_GUARD_bp); data.is_standstill = TEST(ds, STST_bp); data.sg_result_reasonable = !data.is_standstill; // sg_result has no reasonable meaning while standstill #endif #endif // !__AVR__ return data; } #endif // HAS_TMCX1X0 #if HAS_TMC220x #if ENABLED(TMC_DEBUG) static uint32_t get_pwm_scale(TMC2208Stepper &st) { return st.pwm_scale_sum(); } #endif static TMC_driver_data get_driver_data(TMC2208Stepper &st) { constexpr uint8_t OTPW_bp = 0, OT_bp = 1; constexpr uint8_t S2G_bm = 0b111100; // 2..5 TMC_driver_data data; const auto ds = data.drv_status = st.DRV_STATUS(); data.is_otpw = TEST(ds, OTPW_bp); data.is_ot = TEST(ds, OT_bp); data.is_s2g = !!(ds & S2G_bm); #if ENABLED(TMC_DEBUG) constexpr uint32_t CS_ACTUAL_bm = 0x1F0000; // 16:20 constexpr uint8_t STEALTH_bp = 30, STST_bp = 31; #ifdef __AVR__ // 8-bit optimization saves up to 12 bytes of PROGMEM per axis uint8_t spart = ds >> 16; data.cs_actual = spart & (CS_ACTUAL_bm >> 16); spart = ds >> 24; data.is_stealth = TEST(spart, STEALTH_bp - 24); data.is_standstill = TEST(spart, STST_bp - 24); #else constexpr uint8_t CS_ACTUAL_sb = 16; data.cs_actual = (ds & CS_ACTUAL_bm) >> CS_ACTUAL_sb; data.is_stealth = TEST(ds, STEALTH_bp); data.is_standstill = TEST(ds, STST_bp); #endif TERN_(HAS_STALLGUARD, data.sg_result_reasonable = false); #endif return data; } #endif // TMC2208 || TMC2209 #if HAS_DRIVER(TMC2660) #if ENABLED(TMC_DEBUG) static uint32_t get_pwm_scale(TMC2660Stepper) { return 0; } #endif static TMC_driver_data get_driver_data(TMC2660Stepper &st) { constexpr uint8_t OT_bp = 1, OTPW_bp = 2; constexpr uint8_t S2G_bm = 0b11000; TMC_driver_data data; const auto ds = data.drv_status = st.DRVSTATUS(); uint8_t spart = ds & 0xFF; data.is_otpw = TEST(spart, OTPW_bp); data.is_ot = TEST(spart, OT_bp); data.is_s2g = !!(ds & S2G_bm); #if ENABLED(TMC_DEBUG) constexpr uint8_t STALL_GUARD_bp = 0; constexpr uint8_t STST_bp = 7, SG_RESULT_sp = 10; constexpr uint32_t SG_RESULT_bm = 0xFFC00; // 10:19 data.is_stall = TEST(spart, STALL_GUARD_bp); data.is_standstill = TEST(spart, STST_bp); data.sg_result = (ds & SG_RESULT_bm) >> SG_RESULT_sp; data.sg_result_reasonable = true; #endif return data; } #endif // TMC2660 #if ENABLED(STOP_ON_ERROR) void report_driver_error(const TMC_driver_data &data) { SERIAL_ECHOPGM(" driver error detected: 0x"); SERIAL_PRINTLN(data.drv_status, PrintBase::Hex); if (data.is_ot) SERIAL_ECHOLNPGM("overtemperature"); if (data.is_s2g) SERIAL_ECHOLNPGM("coil short circuit"); TERN_(TMC_DEBUG, tmc_report_all()); kill(F("Driver error")); } #endif template<typename TMC> void report_driver_otpw(TMC &st) { MString<13> timestamp; duration_t elapsed = print_job_timer.duration(); const bool has_days = (elapsed.value > 60*60*24L); (void)elapsed.toDigital(&timestamp, has_days); TSS('\n', timestamp, F(": ")).echo(); st.printLabel(); SString<50>(F(" driver overtemperature warning! ("), st.getMilliamps(), F("mA)")).echoln(); } template<typename TMC> void report_polled_driver_data(TMC &st, const TMC_driver_data &data) { const uint32_t pwm_scale = get_pwm_scale(st); st.printLabel(); SString<60> report(':', pwm_scale); #if ENABLED(TMC_DEBUG) #if HAS_TMCX1X0 || HAS_TMC220x report.append('/', data.cs_actual); #endif #if HAS_STALLGUARD report += '/'; if (data.sg_result_reasonable) report += data.sg_result; else report += '-'; #endif #endif report += '|'; if (st.error_count) report += 'E'; // Error if (data.is_ot) report += 'O'; // Over-temperature if (data.is_otpw) report += 'W'; // over-temperature pre-Warning #if ENABLED(TMC_DEBUG) if (data.is_stall) report += 'G'; // stallGuard if (data.is_stealth) report += 'T'; // stealthChop if (data.is_standstill) report += 'I'; // standstIll #endif if (st.flag_otpw) report += 'F'; // otpw Flag report += '|'; if (st.otpw_count > 0) report += st.otpw_count; report += '\t'; report.echo(); } #if CURRENT_STEP_DOWN > 0 template<typename TMC> void step_current_down(TMC &st) { if (st.isEnabled()) { const uint16_t I_rms = st.getMilliamps() - (CURRENT_STEP_DOWN); if (I_rms > 50) { st.rms_current(I_rms); #if ENABLED(REPORT_CURRENT_CHANGE) st.printLabel(); SERIAL_ECHOLNPGM(" current decreased to ", I_rms); #endif } } } #else #define step_current_down(...) #endif template<typename TMC> bool monitor_tmc_driver(TMC &st, const bool need_update_error_counters, const bool need_debug_reporting) { TMC_driver_data data = get_driver_data(st); if (data.drv_status == 0xFFFFFFFF || data.drv_status == 0x0) return false; bool should_step_down = false; if (need_update_error_counters) { if (data.is_ot | data.is_s2g) st.error_count++; else if (st.error_count > 0) st.error_count--; #if ENABLED(STOP_ON_ERROR) if (st.error_count >= 10) { SERIAL_EOL(); st.printLabel(); report_driver_error(data); } #endif // Report if a warning was triggered if (data.is_otpw && st.otpw_count == 0) report_driver_otpw(st); #if CURRENT_STEP_DOWN > 0 // Decrease current if is_otpw is true and driver is enabled and there's been more than 4 warnings if (data.is_otpw && st.otpw_count > 4 && st.isEnabled()) should_step_down = true; #endif if (data.is_otpw) { st.otpw_count++; st.flag_otpw = true; } else if (st.otpw_count > 0) st.otpw_count = 0; } #if ENABLED(TMC_DEBUG) if (need_debug_reporting) report_polled_driver_data(st, data); #endif return should_step_down; } void monitor_tmc_drivers() { const millis_t ms = millis(); // Poll TMC drivers at the configured interval static millis_t next_poll = 0; const bool need_update_error_counters = ELAPSED(ms, next_poll); if (need_update_error_counters) next_poll = ms + MONITOR_DRIVER_STATUS_INTERVAL_MS; // Also poll at intervals for debugging #if ENABLED(TMC_DEBUG) static millis_t next_debug_reporting = 0; const bool need_debug_reporting = report_tmc_status_interval && ELAPSED(ms, next_debug_reporting); if (need_debug_reporting) next_debug_reporting = ms + report_tmc_status_interval; #else constexpr bool need_debug_reporting = false; #endif if (need_update_error_counters || need_debug_reporting) { #if AXIS_IS_TMC(X) || AXIS_IS_TMC(X2) { bool result = false; #if AXIS_IS_TMC(X) if (monitor_tmc_driver(stepperX, need_update_error_counters, need_debug_reporting)) result = true; #endif #if AXIS_IS_TMC(X2) if (monitor_tmc_driver(stepperX2, need_update_error_counters, need_debug_reporting)) result = true; #endif if (result) { #if AXIS_IS_TMC(X) step_current_down(stepperX); #endif #if AXIS_IS_TMC(X2) step_current_down(stepperX2); #endif } } #endif #if AXIS_IS_TMC(Y) || AXIS_IS_TMC(Y2) { bool result = false; #if AXIS_IS_TMC(Y) if (monitor_tmc_driver(stepperY, need_update_error_counters, need_debug_reporting)) result = true; #endif #if AXIS_IS_TMC(Y2) if (monitor_tmc_driver(stepperY2, need_update_error_counters, need_debug_reporting)) result = true; #endif if (result) { #if AXIS_IS_TMC(Y) step_current_down(stepperY); #endif #if AXIS_IS_TMC(Y2) step_current_down(stepperY2); #endif } } #endif #if AXIS_IS_TMC(Z) || AXIS_IS_TMC(Z2) || AXIS_IS_TMC(Z3) || AXIS_IS_TMC(Z4) { bool result = false; #if AXIS_IS_TMC(Z) if (monitor_tmc_driver(stepperZ, need_update_error_counters, need_debug_reporting)) result = true; #endif #if AXIS_IS_TMC(Z2) if (monitor_tmc_driver(stepperZ2, need_update_error_counters, need_debug_reporting)) result = true; #endif #if AXIS_IS_TMC(Z3) if (monitor_tmc_driver(stepperZ3, need_update_error_counters, need_debug_reporting)) result = true; #endif #if AXIS_IS_TMC(Z4) if (monitor_tmc_driver(stepperZ4, need_update_error_counters, need_debug_reporting)) result = true; #endif if (result) { #if AXIS_IS_TMC(Z) step_current_down(stepperZ); #endif #if AXIS_IS_TMC(Z2) step_current_down(stepperZ2); #endif #if AXIS_IS_TMC(Z3) step_current_down(stepperZ3); #endif #if AXIS_IS_TMC(Z4) step_current_down(stepperZ4); #endif } } #endif #if AXIS_IS_TMC(I) if (monitor_tmc_driver(stepperI, need_update_error_counters, need_debug_reporting)) step_current_down(stepperI); #endif #if AXIS_IS_TMC(J) if (monitor_tmc_driver(stepperJ, need_update_error_counters, need_debug_reporting)) step_current_down(stepperJ); #endif #if AXIS_IS_TMC(K) if (monitor_tmc_driver(stepperK, need_update_error_counters, need_debug_reporting)) step_current_down(stepperK); #endif #if AXIS_IS_TMC(U) if (monitor_tmc_driver(stepperU, need_update_error_counters, need_debug_reporting)) step_current_down(stepperU); #endif #if AXIS_IS_TMC(V) if (monitor_tmc_driver(stepperV, need_update_error_counters, need_debug_reporting)) step_current_down(stepperV); #endif #if AXIS_IS_TMC(W) if (monitor_tmc_driver(stepperW, need_update_error_counters, need_debug_reporting)) step_current_down(stepperW); #endif #if AXIS_IS_TMC(E0) (void)monitor_tmc_driver(stepperE0, need_update_error_counters, need_debug_reporting); #endif #if AXIS_IS_TMC(E1) (void)monitor_tmc_driver(stepperE1, need_update_error_counters, need_debug_reporting); #endif #if AXIS_IS_TMC(E2) (void)monitor_tmc_driver(stepperE2, need_update_error_counters, need_debug_reporting); #endif #if AXIS_IS_TMC(E3) (void)monitor_tmc_driver(stepperE3, need_update_error_counters, need_debug_reporting); #endif #if AXIS_IS_TMC(E4) (void)monitor_tmc_driver(stepperE4, need_update_error_counters, need_debug_reporting); #endif #if AXIS_IS_TMC(E5) (void)monitor_tmc_driver(stepperE5, need_update_error_counters, need_debug_reporting); #endif #if AXIS_IS_TMC(E6) (void)monitor_tmc_driver(stepperE6, need_update_error_counters, need_debug_reporting); #endif #if AXIS_IS_TMC(E7) (void)monitor_tmc_driver(stepperE7, need_update_error_counters, need_debug_reporting); #endif if (TERN0(TMC_DEBUG, need_debug_reporting)) SERIAL_EOL(); } } #endif // MONITOR_DRIVER_STATUS #if ENABLED(TMC_DEBUG) /** * M122 [S<0|1>] [Pnnn] Enable periodic status reports */ #if ENABLED(MONITOR_DRIVER_STATUS) void tmc_set_report_interval(const uint16_t update_interval) { if ((report_tmc_status_interval = update_interval)) SERIAL_ECHOLNPGM("axis:pwm_scale" TERN_(HAS_STEALTHCHOP, "/curr_scale") TERN_(HAS_STALLGUARD, "/mech_load") "|flags|warncount" ); } #endif enum TMC_debug_enum : char { TMC_CODES, TMC_UART_ADDR, TMC_ENABLED, TMC_CURRENT, TMC_RMS_CURRENT, TMC_MAX_CURRENT, TMC_IRUN, TMC_IHOLD, TMC_GLOBAL_SCALER, TMC_CS_ACTUAL, TMC_PWM_SCALE, TMC_PWM_SCALE_SUM, TMC_PWM_SCALE_AUTO, TMC_PWM_OFS_AUTO, TMC_PWM_GRAD_AUTO, TMC_VSENSE, TMC_STEALTHCHOP, TMC_MICROSTEPS, TMC_TSTEP, TMC_TPWMTHRS, TMC_TPWMTHRS_MMS, TMC_OTPW, TMC_OTPW_TRIGGERED, TMC_TOFF, TMC_TBL, TMC_HEND, TMC_HSTRT, TMC_SGT, TMC_MSCNT, TMC_INTERPOLATE }; enum TMC_drv_status_enum : char { TMC_DRV_CODES, TMC_STST, TMC_OLB, TMC_OLA, TMC_S2GB, TMC_S2GA, TMC_DRV_OTPW, TMC_OT, TMC_STALLGUARD, TMC_DRV_CS_ACTUAL, TMC_FSACTIVE, TMC_SG_RESULT, TMC_DRV_STATUS_HEX, TMC_T157, TMC_T150, TMC_T143, TMC_T120, TMC_STEALTH, TMC_S2VSB, TMC_S2VSA }; enum TMC_get_registers_enum : char { TMC_AXIS_CODES, TMC_GET_GCONF, TMC_GET_IHOLD_IRUN, TMC_GET_GSTAT, TMC_GET_IOIN, TMC_GET_TPOWERDOWN, TMC_GET_TSTEP, TMC_GET_TPWMTHRS, TMC_GET_TCOOLTHRS, TMC_GET_THIGH, TMC_GET_CHOPCONF, TMC_GET_COOLCONF, TMC_GET_PWMCONF, TMC_GET_PWM_SCALE, TMC_GET_DRV_STATUS, TMC_GET_DRVCONF, TMC_GET_DRVCTRL, TMC_GET_DRVSTATUS, TMC_GET_SGCSCONF, TMC_GET_SMARTEN }; template<class TMC> static void print_vsense(TMC &st) { SERIAL_ECHO(st.vsense() ? F("1=.18") : F("0=.325")); } #if HAS_DRIVER(TMC2130) || HAS_DRIVER(TMC5130) static void _tmc_status(TMC2130Stepper &st, const TMC_debug_enum i) { switch (i) { case TMC_PWM_SCALE: SERIAL_ECHO(st.PWM_SCALE()); break; case TMC_SGT: SERIAL_ECHO(st.sgt()); break; case TMC_STEALTHCHOP: serialprint_truefalse(st.en_pwm_mode()); break; case TMC_INTERPOLATE: serialprint_truefalse(st.intpol()); break; default: break; } } #endif #if HAS_TMCX1X0 static void _tmc_parse_drv_status(TMC2130Stepper &st, const TMC_drv_status_enum i) { switch (i) { case TMC_STALLGUARD: if (st.stallguard()) SERIAL_CHAR('*'); break; case TMC_SG_RESULT: SERIAL_ECHO(st.sg_result()); break; case TMC_FSACTIVE: if (st.fsactive()) SERIAL_CHAR('*'); break; case TMC_DRV_CS_ACTUAL: SERIAL_ECHO(st.cs_actual()); break; default: break; } } #endif #if HAS_DRIVER(TMC2160) || HAS_DRIVER(TMC5160) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void print_vsense(TMCMarlin<TMC2160Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &) { } template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void print_vsense(TMCMarlin<TMC5160Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &) { } static void _tmc_status(TMC2160Stepper &st, const TMC_debug_enum i) { switch (i) { case TMC_PWM_SCALE: SERIAL_ECHO(st.PWM_SCALE()); break; case TMC_SGT: SERIAL_ECHO(st.sgt()); break; case TMC_STEALTHCHOP: serialprint_truefalse(st.en_pwm_mode()); break; case TMC_GLOBAL_SCALER: { const uint16_t value = st.GLOBAL_SCALER(); SERIAL_ECHO(value ?: 256); SERIAL_ECHOPGM("/256"); } break; case TMC_INTERPOLATE: serialprint_truefalse(st.intpol()); break; default: break; } } #endif #if HAS_TMC220x static void _tmc_status(TMC2208Stepper &st, const TMC_debug_enum i) { switch (i) { case TMC_PWM_SCALE_SUM: SERIAL_ECHO(st.pwm_scale_sum()); break; case TMC_PWM_SCALE_AUTO: SERIAL_ECHO(st.pwm_scale_auto()); break; case TMC_PWM_OFS_AUTO: SERIAL_ECHO(st.pwm_ofs_auto()); break; case TMC_PWM_GRAD_AUTO: SERIAL_ECHO(st.pwm_grad_auto()); break; case TMC_STEALTHCHOP: serialprint_truefalse(st.stealth()); break; case TMC_INTERPOLATE: serialprint_truefalse(st.intpol()); break; default: break; } } #if HAS_DRIVER(TMC2209) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> static void _tmc_status(TMCMarlin<TMC2209Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const TMC_debug_enum i) { switch (i) { case TMC_SGT: SERIAL_ECHO(st.SGTHRS()); break; case TMC_UART_ADDR: SERIAL_ECHO(st.get_address()); break; default: TMC2208Stepper *parent = &st; _tmc_status(*parent, i); break; } } #endif static void _tmc_parse_drv_status(TMC2208Stepper &st, const TMC_drv_status_enum i) { switch (i) { case TMC_T157: if (st.t157()) SERIAL_CHAR('*'); break; case TMC_T150: if (st.t150()) SERIAL_CHAR('*'); break; case TMC_T143: if (st.t143()) SERIAL_CHAR('*'); break; case TMC_T120: if (st.t120()) SERIAL_CHAR('*'); break; case TMC_S2VSA: if (st.s2vsa()) SERIAL_CHAR('*'); break; case TMC_S2VSB: if (st.s2vsb()) SERIAL_CHAR('*'); break; case TMC_DRV_CS_ACTUAL: SERIAL_ECHO(st.cs_actual()); break; default: break; } } #if HAS_DRIVER(TMC2209) static void _tmc_parse_drv_status(TMC2209Stepper &st, const TMC_drv_status_enum i) { switch (i) { case TMC_SG_RESULT: SERIAL_ECHO(st.SG_RESULT()); break; default: _tmc_parse_drv_status(static_cast<TMC2208Stepper &>(st), i); break; } } #endif #endif #if HAS_DRIVER(TMC2660) static void _tmc_parse_drv_status(TMC2660Stepper, const TMC_drv_status_enum) { } static void _tmc_status(TMC2660Stepper &st, const TMC_debug_enum i) { switch (i) { case TMC_INTERPOLATE: serialprint_truefalse(st.intpol()); break; default: break; } } #endif template <typename TMC> static void tmc_status(TMC &st, const TMC_debug_enum i) { SERIAL_CHAR('\t'); switch (i) { case TMC_CODES: st.printLabel(); break; case TMC_ENABLED: serialprint_truefalse(st.isEnabled()); break; case TMC_CURRENT: SERIAL_ECHO(st.getMilliamps()); break; case TMC_RMS_CURRENT: SERIAL_ECHO(st.rms_current()); break; case TMC_MAX_CURRENT: SERIAL_ECHO(p_float_t(st.rms_current() * 1.41, 0)); break; case TMC_IRUN: SERIAL_ECHO(st.irun()); SERIAL_ECHOPGM("/31"); break; case TMC_IHOLD: SERIAL_ECHO(st.ihold()); SERIAL_ECHOPGM("/31"); break; case TMC_CS_ACTUAL: SERIAL_ECHO(st.cs_actual()); SERIAL_ECHOPGM("/31"); break; case TMC_VSENSE: print_vsense(st); break; case TMC_MICROSTEPS: SERIAL_ECHO(st.microsteps()); break; case TMC_TSTEP: { const uint32_t tstep_value = st.TSTEP(); if (tstep_value != 0xFFFFF) SERIAL_ECHO(tstep_value); else SERIAL_ECHOPGM("max"); } break; #if ENABLED(HYBRID_THRESHOLD) case TMC_TPWMTHRS: SERIAL_ECHO(uint32_t(st.TPWMTHRS())); break; case TMC_TPWMTHRS_MMS: { const uint32_t tpwmthrs_val = st.get_pwm_thrs(); if (tpwmthrs_val) SERIAL_ECHO(tpwmthrs_val); else SERIAL_CHAR('-'); } break; #endif case TMC_OTPW: serialprint_truefalse(st.otpw()); break; #if ENABLED(MONITOR_DRIVER_STATUS) case TMC_OTPW_TRIGGERED: serialprint_truefalse(st.getOTPW()); break; #endif case TMC_TOFF: SERIAL_ECHO(st.toff()); break; case TMC_TBL: SERIAL_ECHO(st.blank_time()); break; case TMC_HEND: SERIAL_ECHO(st.hysteresis_end()); break; case TMC_HSTRT: SERIAL_ECHO(st.hysteresis_start()); break; case TMC_MSCNT: SERIAL_ECHO(st.get_microstep_counter()); break; default: _tmc_status(st, i); break; } } #if HAS_DRIVER(TMC2660) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_status(TMCMarlin<TMC2660Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const TMC_debug_enum i) { SERIAL_CHAR('\t'); switch (i) { case TMC_CODES: st.printLabel(); break; case TMC_ENABLED: serialprint_truefalse(st.isEnabled()); break; case TMC_CURRENT: SERIAL_ECHO(st.getMilliamps()); break; case TMC_RMS_CURRENT: SERIAL_ECHO(st.rms_current()); break; case TMC_MAX_CURRENT: SERIAL_ECHO(p_float_t(st.rms_current() * 1.41, 0)); break; case TMC_IRUN: SERIAL_ECHO(st.cs()); SERIAL_ECHOPGM("/31"); break; case TMC_VSENSE: SERIAL_ECHO(st.vsense() ? F("1=.165") : F("0=.310")); break; case TMC_MICROSTEPS: SERIAL_ECHO(st.microsteps()); break; //case TMC_OTPW: serialprint_truefalse(st.otpw()); break; //case TMC_OTPW_TRIGGERED: serialprint_truefalse(st.getOTPW()); break; case TMC_SGT: SERIAL_ECHO(st.sgt()); break; case TMC_TOFF: SERIAL_ECHO(st.toff()); break; case TMC_TBL: SERIAL_ECHO(st.blank_time()); break; case TMC_HEND: SERIAL_ECHO(st.hysteresis_end()); break; case TMC_HSTRT: SERIAL_ECHO(st.hysteresis_start()); break; default: break; } } #endif template <typename TMC> static void tmc_parse_drv_status(TMC &st, const TMC_drv_status_enum i) { SERIAL_CHAR('\t'); switch (i) { case TMC_DRV_CODES: st.printLabel(); break; case TMC_STST: if (!st.stst()) SERIAL_CHAR('*'); break; case TMC_OLB: if (st.olb()) SERIAL_CHAR('*'); break; case TMC_OLA: if (st.ola()) SERIAL_CHAR('*'); break; case TMC_S2GB: if (st.s2gb()) SERIAL_CHAR('*'); break; case TMC_S2GA: if (st.s2ga()) SERIAL_CHAR('*'); break; case TMC_DRV_OTPW: if (st.otpw()) SERIAL_CHAR('*'); break; case TMC_OT: if (st.ot()) SERIAL_CHAR('*'); break; case TMC_DRV_STATUS_HEX: { const uint32_t drv_status = st.DRV_STATUS(); SERIAL_CHAR('\t'); st.printLabel(); SERIAL_CHAR('\t'); print_hex_long(drv_status, ':', true); if (drv_status == 0xFFFFFFFF || drv_status == 0) SERIAL_ECHOPGM("\t Bad response!"); SERIAL_EOL(); break; } default: _tmc_parse_drv_status(st, i); break; } } static void tmc_debug_loop(const TMC_debug_enum n OPTARGS_LOGICAL(const bool)) { if (TERN0(HAS_X_AXIS, x)) { #if AXIS_IS_TMC(X) tmc_status(stepperX, n); #endif #if AXIS_IS_TMC(X2) tmc_status(stepperX2, n); #endif } if (TERN0(HAS_Y_AXIS, y)) { #if AXIS_IS_TMC(Y) tmc_status(stepperY, n); #endif #if AXIS_IS_TMC(Y2) tmc_status(stepperY2, n); #endif } if (TERN0(HAS_Z_AXIS, z)) { #if AXIS_IS_TMC(Z) tmc_status(stepperZ, n); #endif #if AXIS_IS_TMC(Z2) tmc_status(stepperZ2, n); #endif #if AXIS_IS_TMC(Z3) tmc_status(stepperZ3, n); #endif #if AXIS_IS_TMC(Z4) tmc_status(stepperZ4, n); #endif } #if AXIS_IS_TMC(I) if (i) tmc_status(stepperI, n); #endif #if AXIS_IS_TMC(J) if (j) tmc_status(stepperJ, n); #endif #if AXIS_IS_TMC(K) if (k) tmc_status(stepperK, n); #endif #if AXIS_IS_TMC(U) if (u) tmc_status(stepperU, n); #endif #if AXIS_IS_TMC(V) if (v) tmc_status(stepperV, n); #endif #if AXIS_IS_TMC(W) if (w) tmc_status(stepperW, n); #endif if (TERN0(HAS_EXTRUDERS, e)) { #if AXIS_IS_TMC(E0) tmc_status(stepperE0, n); #endif #if AXIS_IS_TMC(E1) tmc_status(stepperE1, n); #endif #if AXIS_IS_TMC(E2) tmc_status(stepperE2, n); #endif #if AXIS_IS_TMC(E3) tmc_status(stepperE3, n); #endif #if AXIS_IS_TMC(E4) tmc_status(stepperE4, n); #endif #if AXIS_IS_TMC(E5) tmc_status(stepperE5, n); #endif #if AXIS_IS_TMC(E6) tmc_status(stepperE6, n); #endif #if AXIS_IS_TMC(E7) tmc_status(stepperE7, n); #endif } SERIAL_EOL(); } static void drv_status_loop(const TMC_drv_status_enum n OPTARGS_LOGICAL(const bool)) { if (TERN0(HAS_X_AXIS, x)) { #if AXIS_IS_TMC(X) tmc_parse_drv_status(stepperX, n); #endif #if AXIS_IS_TMC(X2) tmc_parse_drv_status(stepperX2, n); #endif } if (TERN0(HAS_Y_AXIS, y)) { #if AXIS_IS_TMC(Y) tmc_parse_drv_status(stepperY, n); #endif #if AXIS_IS_TMC(Y2) tmc_parse_drv_status(stepperY2, n); #endif } if (TERN0(HAS_Z_AXIS, z)) { #if AXIS_IS_TMC(Z) tmc_parse_drv_status(stepperZ, n); #endif #if AXIS_IS_TMC(Z2) tmc_parse_drv_status(stepperZ2, n); #endif #if AXIS_IS_TMC(Z3) tmc_parse_drv_status(stepperZ3, n); #endif #if AXIS_IS_TMC(Z4) tmc_parse_drv_status(stepperZ4, n); #endif } #if AXIS_IS_TMC(I) if (i) tmc_parse_drv_status(stepperI, n); #endif #if AXIS_IS_TMC(J) if (j) tmc_parse_drv_status(stepperJ, n); #endif #if AXIS_IS_TMC(K) if (k) tmc_parse_drv_status(stepperK, n); #endif #if AXIS_IS_TMC(U) if (u) tmc_parse_drv_status(stepperU, n); #endif #if AXIS_IS_TMC(V) if (v) tmc_parse_drv_status(stepperV, n); #endif #if AXIS_IS_TMC(W) if (w) tmc_parse_drv_status(stepperW, n); #endif if (TERN0(HAS_EXTRUDERS, e)) { #if AXIS_IS_TMC(E0) tmc_parse_drv_status(stepperE0, n); #endif #if AXIS_IS_TMC(E1) tmc_parse_drv_status(stepperE1, n); #endif #if AXIS_IS_TMC(E2) tmc_parse_drv_status(stepperE2, n); #endif #if AXIS_IS_TMC(E3) tmc_parse_drv_status(stepperE3, n); #endif #if AXIS_IS_TMC(E4) tmc_parse_drv_status(stepperE4, n); #endif #if AXIS_IS_TMC(E5) tmc_parse_drv_status(stepperE5, n); #endif #if AXIS_IS_TMC(E6) tmc_parse_drv_status(stepperE6, n); #endif #if AXIS_IS_TMC(E7) tmc_parse_drv_status(stepperE7, n); #endif } SERIAL_EOL(); } /** * M122 report functions */ void tmc_report_all(LOGICAL_AXIS_ARGS(const bool)) { #define TMC_REPORT(LABEL, ITEM) do{ SERIAL_ECHOPGM(LABEL); tmc_debug_loop(ITEM OPTARGS_LOGICAL()); }while(0) #define DRV_REPORT(LABEL, ITEM) do{ SERIAL_ECHOPGM(LABEL); drv_status_loop(ITEM OPTARGS_LOGICAL()); }while(0) TMC_REPORT("\t", TMC_CODES); #if HAS_DRIVER(TMC2209) TMC_REPORT("Address\t", TMC_UART_ADDR); #endif TMC_REPORT("Enabled\t", TMC_ENABLED); TMC_REPORT("Set current", TMC_CURRENT); TMC_REPORT("RMS current", TMC_RMS_CURRENT); TMC_REPORT("MAX current", TMC_MAX_CURRENT); TMC_REPORT("Run current", TMC_IRUN); TMC_REPORT("Hold current", TMC_IHOLD); #if HAS_DRIVER(TMC2160) || HAS_DRIVER(TMC5160) TMC_REPORT("Global scaler", TMC_GLOBAL_SCALER); #endif TMC_REPORT("CS actual", TMC_CS_ACTUAL); TMC_REPORT("PWM scale", TMC_PWM_SCALE); #if HAS_DRIVER(TMC2130) || HAS_DRIVER(TMC2224) || HAS_DRIVER(TMC2660) || HAS_TMC220x TMC_REPORT("vsense\t", TMC_VSENSE); #endif TMC_REPORT("stealthChop", TMC_STEALTHCHOP); TMC_REPORT("msteps\t", TMC_MICROSTEPS); TMC_REPORT("interp\t", TMC_INTERPOLATE); TMC_REPORT("tstep\t", TMC_TSTEP); TMC_REPORT("PWM thresh.", TMC_TPWMTHRS); TMC_REPORT("[mm/s]\t", TMC_TPWMTHRS_MMS); TMC_REPORT("OT prewarn", TMC_OTPW); #if ENABLED(MONITOR_DRIVER_STATUS) TMC_REPORT("triggered\n OTP\t", TMC_OTPW_TRIGGERED); #endif #if HAS_TMC220x TMC_REPORT("pwm scale sum", TMC_PWM_SCALE_SUM); TMC_REPORT("pwm scale auto", TMC_PWM_SCALE_AUTO); TMC_REPORT("pwm offset auto", TMC_PWM_OFS_AUTO); TMC_REPORT("pwm grad auto", TMC_PWM_GRAD_AUTO); #endif TMC_REPORT("off time", TMC_TOFF); TMC_REPORT("blank time", TMC_TBL); TMC_REPORT("hysteresis\n -end\t", TMC_HEND); TMC_REPORT(" -start\t", TMC_HSTRT); TMC_REPORT("Stallguard thrs", TMC_SGT); TMC_REPORT("uStep count", TMC_MSCNT); DRV_REPORT("DRVSTATUS", TMC_DRV_CODES); #if HAS_TMCX1X0 || HAS_TMC220x DRV_REPORT("sg_result", TMC_SG_RESULT); #endif #if HAS_TMCX1X0 DRV_REPORT("stallguard", TMC_STALLGUARD); DRV_REPORT("fsactive", TMC_FSACTIVE); #endif DRV_REPORT("stst\t", TMC_STST); DRV_REPORT("olb\t", TMC_OLB); DRV_REPORT("ola\t", TMC_OLA); DRV_REPORT("s2gb\t", TMC_S2GB); DRV_REPORT("s2ga\t", TMC_S2GA); DRV_REPORT("otpw\t", TMC_DRV_OTPW); DRV_REPORT("ot\t", TMC_OT); #if HAS_TMC220x DRV_REPORT("157C\t", TMC_T157); DRV_REPORT("150C\t", TMC_T150); DRV_REPORT("143C\t", TMC_T143); DRV_REPORT("120C\t", TMC_T120); DRV_REPORT("s2vsa\t", TMC_S2VSA); DRV_REPORT("s2vsb\t", TMC_S2VSB); #endif DRV_REPORT("Driver registers:\n",TMC_DRV_STATUS_HEX); SERIAL_EOL(); } #define PRINT_TMC_REGISTER(REG_CASE) case TMC_GET_##REG_CASE: print_hex_long(st.REG_CASE(), ':'); break #if HAS_TMCX1X0 static void tmc_get_ic_registers(TMC2130Stepper &st, const TMC_get_registers_enum i) { switch (i) { PRINT_TMC_REGISTER(TCOOLTHRS); PRINT_TMC_REGISTER(THIGH); PRINT_TMC_REGISTER(COOLCONF); default: SERIAL_CHAR('\t'); break; } } #endif #if HAS_TMC220x static void tmc_get_ic_registers(TMC2208Stepper, const TMC_get_registers_enum) { SERIAL_CHAR('\t'); } #endif #if HAS_TRINAMIC_CONFIG template<class TMC> static void tmc_get_registers(TMC &st, const TMC_get_registers_enum i) { switch (i) { case TMC_AXIS_CODES: SERIAL_CHAR('\t'); st.printLabel(); break; PRINT_TMC_REGISTER(GCONF); PRINT_TMC_REGISTER(IHOLD_IRUN); PRINT_TMC_REGISTER(GSTAT); PRINT_TMC_REGISTER(IOIN); PRINT_TMC_REGISTER(TPOWERDOWN); PRINT_TMC_REGISTER(TSTEP); PRINT_TMC_REGISTER(TPWMTHRS); PRINT_TMC_REGISTER(CHOPCONF); PRINT_TMC_REGISTER(PWMCONF); PRINT_TMC_REGISTER(PWM_SCALE); PRINT_TMC_REGISTER(DRV_STATUS); default: tmc_get_ic_registers(st, i); break; } SERIAL_CHAR('\t'); } #endif #if HAS_DRIVER(TMC2660) template <char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> static void tmc_get_registers(TMCMarlin<TMC2660Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const TMC_get_registers_enum i) { switch (i) { case TMC_AXIS_CODES: SERIAL_CHAR('\t'); st.printLabel(); break; PRINT_TMC_REGISTER(DRVCONF); PRINT_TMC_REGISTER(DRVCTRL); PRINT_TMC_REGISTER(CHOPCONF); PRINT_TMC_REGISTER(DRVSTATUS); PRINT_TMC_REGISTER(SGCSCONF); PRINT_TMC_REGISTER(SMARTEN); default: SERIAL_CHAR('\t'); break; } SERIAL_CHAR('\t'); } #endif static void tmc_get_registers(TMC_get_registers_enum n OPTARGS_LOGICAL(const bool)) { if (TERN0(HAS_X_AXIS, x)) { #if AXIS_IS_TMC(X) tmc_get_registers(stepperX, n); #endif #if AXIS_IS_TMC(X2) tmc_get_registers(stepperX2, n); #endif } if (TERN0(HAS_Y_AXIS, y)) { #if AXIS_IS_TMC(Y) tmc_get_registers(stepperY, n); #endif #if AXIS_IS_TMC(Y2) tmc_get_registers(stepperY2, n); #endif } if (TERN0(HAS_Z_AXIS, z)) { #if AXIS_IS_TMC(Z) tmc_get_registers(stepperZ, n); #endif #if AXIS_IS_TMC(Z2) tmc_get_registers(stepperZ2, n); #endif #if AXIS_IS_TMC(Z3) tmc_get_registers(stepperZ3, n); #endif #if AXIS_IS_TMC(Z4) tmc_get_registers(stepperZ4, n); #endif } #if AXIS_IS_TMC(I) if (i) tmc_get_registers(stepperI, n); #endif #if AXIS_IS_TMC(J) if (j) tmc_get_registers(stepperJ, n); #endif #if AXIS_IS_TMC(K) if (k) tmc_get_registers(stepperK, n); #endif #if AXIS_IS_TMC(U) if (u) tmc_get_registers(stepperU, n); #endif #if AXIS_IS_TMC(V) if (v) tmc_get_registers(stepperV, n); #endif #if AXIS_IS_TMC(W) if (w) tmc_get_registers(stepperW, n); #endif if (TERN0(HAS_EXTRUDERS, e)) { #if AXIS_IS_TMC(E0) tmc_get_registers(stepperE0, n); #endif #if AXIS_IS_TMC(E1) tmc_get_registers(stepperE1, n); #endif #if AXIS_IS_TMC(E2) tmc_get_registers(stepperE2, n); #endif #if AXIS_IS_TMC(E3) tmc_get_registers(stepperE3, n); #endif #if AXIS_IS_TMC(E4) tmc_get_registers(stepperE4, n); #endif #if AXIS_IS_TMC(E5) tmc_get_registers(stepperE5, n); #endif #if AXIS_IS_TMC(E6) tmc_get_registers(stepperE6, n); #endif #if AXIS_IS_TMC(E7) tmc_get_registers(stepperE7, n); #endif } SERIAL_EOL(); } void tmc_get_registers(LOGICAL_AXIS_ARGS(bool)) { #define _TMC_GET_REG(LABEL, ITEM) do{ SERIAL_ECHOPGM(LABEL); tmc_get_registers(ITEM OPTARGS_LOGICAL()); }while(0) #define TMC_GET_REG(NAME, TABS) _TMC_GET_REG(STRINGIFY(NAME) TABS, TMC_GET_##NAME) _TMC_GET_REG("\t", TMC_AXIS_CODES); TMC_GET_REG(GCONF, "\t\t"); TMC_GET_REG(IHOLD_IRUN, "\t"); TMC_GET_REG(GSTAT, "\t\t"); TMC_GET_REG(IOIN, "\t\t"); TMC_GET_REG(TPOWERDOWN, "\t"); TMC_GET_REG(TSTEP, "\t\t"); TMC_GET_REG(TPWMTHRS, "\t"); TMC_GET_REG(TCOOLTHRS, "\t"); TMC_GET_REG(THIGH, "\t\t"); TMC_GET_REG(CHOPCONF, "\t"); TMC_GET_REG(COOLCONF, "\t"); TMC_GET_REG(PWMCONF, "\t"); TMC_GET_REG(PWM_SCALE, "\t"); TMC_GET_REG(DRV_STATUS, "\t"); } #endif // TMC_DEBUG #if USE_SENSORLESS bool tmc_enable_stallguard(TMC2130Stepper &st) { const bool stealthchop_was_enabled = st.en_pwm_mode(); st.TCOOLTHRS(0xFFFFF); st.en_pwm_mode(false); st.diag1_stall(true); return stealthchop_was_enabled; } void tmc_disable_stallguard(TMC2130Stepper &st, const bool restore_stealth) { st.TCOOLTHRS(0); st.en_pwm_mode(restore_stealth); st.diag1_stall(false); } bool tmc_enable_stallguard(TMC2209Stepper &st) { const bool stealthchop_was_enabled = !st.en_spreadCycle(); st.TCOOLTHRS(0xFFFFF); st.en_spreadCycle(false); return stealthchop_was_enabled; } void tmc_disable_stallguard(TMC2209Stepper &st, const bool restore_stealth) { st.en_spreadCycle(!restore_stealth); st.TCOOLTHRS(0); } bool tmc_enable_stallguard(TMC2660Stepper) { // TODO return false; } void tmc_disable_stallguard(TMC2660Stepper, const bool) {}; #endif // USE_SENSORLESS template<typename TMC> static bool test_connection(TMC &st) { SERIAL_ECHOPGM("Testing "); st.printLabel(); SERIAL_ECHOPGM(" connection... "); const uint8_t test_result = st.test_connection(); if (test_result > 0) SERIAL_ECHOPGM("Error: All "); FSTR_P stat; switch (test_result) { default: case 0: stat = F("OK"); break; case 1: stat = F("HIGH"); break; case 2: stat = F("LOW"); break; } SERIAL_ECHOLN(stat); return test_result; } void test_tmc_connection(LOGICAL_AXIS_ARGS(const bool)) { uint8_t axis_connection = 0; if (TERN0(HAS_X_AXIS, x)) { #if AXIS_IS_TMC(X) axis_connection += test_connection(stepperX); #endif #if AXIS_IS_TMC(X2) axis_connection += test_connection(stepperX2); #endif } if (TERN0(HAS_Y_AXIS, y)) { #if AXIS_IS_TMC(Y) axis_connection += test_connection(stepperY); #endif #if AXIS_IS_TMC(Y2) axis_connection += test_connection(stepperY2); #endif } if (TERN0(HAS_Z_AXIS, z)) { #if AXIS_IS_TMC(Z) axis_connection += test_connection(stepperZ); #endif #if AXIS_IS_TMC(Z2) axis_connection += test_connection(stepperZ2); #endif #if AXIS_IS_TMC(Z3) axis_connection += test_connection(stepperZ3); #endif #if AXIS_IS_TMC(Z4) axis_connection += test_connection(stepperZ4); #endif } #if AXIS_IS_TMC(I) if (i) axis_connection += test_connection(stepperI); #endif #if AXIS_IS_TMC(J) if (j) axis_connection += test_connection(stepperJ); #endif #if AXIS_IS_TMC(K) if (k) axis_connection += test_connection(stepperK); #endif #if AXIS_IS_TMC(U) if (u) axis_connection += test_connection(stepperU); #endif #if AXIS_IS_TMC(V) if (v) axis_connection += test_connection(stepperV); #endif #if AXIS_IS_TMC(W) if (w) axis_connection += test_connection(stepperW); #endif if (TERN0(HAS_EXTRUDERS, e)) { #if AXIS_IS_TMC(E0) axis_connection += test_connection(stepperE0); #endif #if AXIS_IS_TMC(E1) axis_connection += test_connection(stepperE1); #endif #if AXIS_IS_TMC(E2) axis_connection += test_connection(stepperE2); #endif #if AXIS_IS_TMC(E3) axis_connection += test_connection(stepperE3); #endif #if AXIS_IS_TMC(E4) axis_connection += test_connection(stepperE4); #endif #if AXIS_IS_TMC(E5) axis_connection += test_connection(stepperE5); #endif #if AXIS_IS_TMC(E6) axis_connection += test_connection(stepperE6); #endif #if AXIS_IS_TMC(E7) axis_connection += test_connection(stepperE7); #endif } if (axis_connection) LCD_MESSAGE(MSG_ERROR_TMC); } #endif // HAS_TRINAMIC_CONFIG #if HAS_TMC_SPI #define SET_CS_PIN(st) OUT_WRITE(st##_CS_PIN, HIGH) void tmc_init_cs_pins() { #if AXIS_HAS_SPI(X) SET_CS_PIN(X); #endif #if AXIS_HAS_SPI(Y) SET_CS_PIN(Y); #endif #if AXIS_HAS_SPI(Z) SET_CS_PIN(Z); #endif #if AXIS_HAS_SPI(X2) SET_CS_PIN(X2); #endif #if AXIS_HAS_SPI(Y2) SET_CS_PIN(Y2); #endif #if AXIS_HAS_SPI(Z2) SET_CS_PIN(Z2); #endif #if AXIS_HAS_SPI(Z3) SET_CS_PIN(Z3); #endif #if AXIS_HAS_SPI(Z4) SET_CS_PIN(Z4); #endif #if AXIS_HAS_SPI(I) SET_CS_PIN(I); #endif #if AXIS_HAS_SPI(J) SET_CS_PIN(J); #endif #if AXIS_HAS_SPI(K) SET_CS_PIN(K); #endif #if AXIS_HAS_SPI(U) SET_CS_PIN(U); #endif #if AXIS_HAS_SPI(V) SET_CS_PIN(V); #endif #if AXIS_HAS_SPI(W) SET_CS_PIN(W); #endif #if AXIS_HAS_SPI(E0) SET_CS_PIN(E0); #endif #if AXIS_HAS_SPI(E1) SET_CS_PIN(E1); #endif #if AXIS_HAS_SPI(E2) SET_CS_PIN(E2); #endif #if AXIS_HAS_SPI(E3) SET_CS_PIN(E3); #endif #if AXIS_HAS_SPI(E4) SET_CS_PIN(E4); #endif #if AXIS_HAS_SPI(E5) SET_CS_PIN(E5); #endif #if AXIS_HAS_SPI(E6) SET_CS_PIN(E6); #endif #if AXIS_HAS_SPI(E7) SET_CS_PIN(E7); #endif } #endif // HAS_TMC_SPI
2301_81045437/Marlin
Marlin/src/feature/tmc_util.cpp
C++
agpl-3.0
43,282
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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 "../lcd/marlinui.h" #if HAS_TRINAMIC_CONFIG #include <TMCStepper.h> #include "../module/planner.h" #define CHOPPER_DEFAULT_12V { 3, -1, 1 } #define CHOPPER_DEFAULT_19V { 4, 1, 1 } #define CHOPPER_DEFAULT_24V { 4, 2, 1 } #define CHOPPER_DEFAULT_36V { 5, 2, 4 } #define CHOPPER_PRUSAMK3_24V { 3, -2, 6 } #define CHOPPER_MARLIN_119 { 5, 2, 3 } #define CHOPPER_09STEP_24V { 3, -1, 5 } #if ENABLED(MONITOR_DRIVER_STATUS) && !defined(MONITOR_DRIVER_STATUS_INTERVAL_MS) #define MONITOR_DRIVER_STATUS_INTERVAL_MS 500U #endif constexpr uint16_t _tmc_thrs(const uint16_t msteps, const uint32_t thrs, const uint32_t spmm) { return 12650000UL * msteps / (256 * thrs * spmm); } typedef struct { uint8_t toff; int8_t hend; uint8_t hstrt; } chopper_timing_t; template<char AXIS_LETTER, char DRIVER_ID> class TMCStorage { protected: // Only a child class has access to constructor => Don't create on its own! "Poor man's abstract class" TMCStorage() {} public: uint16_t val_mA = 0; #if ENABLED(MONITOR_DRIVER_STATUS) uint8_t otpw_count = 0, error_count = 0; bool flag_otpw = false; bool getOTPW() { return flag_otpw; } void clear_otpw() { flag_otpw = 0; } #endif uint16_t getMilliamps() { return val_mA; } void printLabel() { SERIAL_CHAR(AXIS_LETTER); if (DRIVER_ID > '0') SERIAL_CHAR(DRIVER_ID); } struct { OPTCODE(HAS_STEALTHCHOP, bool stealthChop_enabled = false) OPTCODE(HYBRID_THRESHOLD, uint8_t hybrid_thrs = 0) OPTCODE(USE_SENSORLESS, int16_t homing_thrs = 0) } stored; }; template<class TMC, char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> class TMCMarlin : public TMC, public TMCStorage<AXIS_LETTER, DRIVER_ID> { public: TMCMarlin(const uint16_t cs_pin, const float RS) : TMC(cs_pin, RS) {} TMCMarlin(const uint16_t cs_pin, const float RS, const uint8_t axis_chain_index) : TMC(cs_pin, RS, axis_chain_index) {} TMCMarlin(const uint16_t CS, const float RS, const uint16_t pinMOSI, const uint16_t pinMISO, const uint16_t pinSCK) : TMC(CS, RS, pinMOSI, pinMISO, pinSCK) {} TMCMarlin(const uint16_t CS, const float RS, const uint16_t pinMOSI, const uint16_t pinMISO, const uint16_t pinSCK, const uint8_t axis_chain_index) : TMC(CS, RS, pinMOSI, pinMISO, pinSCK, axis_chain_index) {} uint16_t rms_current() { return TMC::rms_current(); } void rms_current(uint16_t mA) { this->val_mA = mA; TMC::rms_current(mA); } void rms_current(const uint16_t mA, const float mult) { this->val_mA = mA; TMC::rms_current(mA, mult); } uint16_t get_microstep_counter() { return TMC::MSCNT(); } #if HAS_STEALTHCHOP bool get_stealthChop() { return this->en_pwm_mode(); } bool get_stored_stealthChop() { return this->stored.stealthChop_enabled; } void refresh_stepping_mode() { this->en_pwm_mode(this->stored.stealthChop_enabled); } void set_stealthChop(const bool stch) { this->stored.stealthChop_enabled = stch; refresh_stepping_mode(); } bool toggle_stepping_mode() { set_stealthChop(!this->stored.stealthChop_enabled); return get_stealthChop(); } #endif void set_chopper_times(const chopper_timing_t &ct) { TMC::toff(ct.toff); TMC::hysteresis_end(ct.hend); TMC::hysteresis_start(ct.hstrt); } #if ENABLED(HYBRID_THRESHOLD) uint32_t get_pwm_thrs() { return _tmc_thrs(this->microsteps(), this->TPWMTHRS(), planner.settings.axis_steps_per_mm[AXIS_ID]); } void set_pwm_thrs(const uint32_t thrs) { TMC::TPWMTHRS(_tmc_thrs(this->microsteps(), thrs, planner.settings.axis_steps_per_mm[AXIS_ID])); TERN_(HAS_MARLINUI_MENU, this->stored.hybrid_thrs = thrs); } #endif #if USE_SENSORLESS int16_t homing_threshold() { return TMC::sgt(); } void homing_threshold(int16_t sgt_val) { sgt_val = (int16_t)constrain(sgt_val, sgt_min, sgt_max); TMC::sgt(sgt_val); TERN_(HAS_MARLINUI_MENU, this->stored.homing_thrs = sgt_val); } #if ENABLED(SPI_ENDSTOPS) bool test_stall_status(); #endif #endif void refresh_stepper_current() { rms_current(this->val_mA); } #if ENABLED(HYBRID_THRESHOLD) void refresh_hybrid_thrs() { set_pwm_thrs(this->stored.hybrid_thrs); } #endif #if USE_SENSORLESS void refresh_homing_thrs() { homing_threshold(this->stored.homing_thrs); } #endif static constexpr int8_t sgt_min = -64, sgt_max = 63; }; template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> class TMCMarlin<TMC2208Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> : public TMC2208Stepper, public TMCStorage<AXIS_LETTER, DRIVER_ID> { public: TMCMarlin(Stream * SerialPort, const float RS, const uint8_t) : TMC2208Stepper(SerialPort, RS) {} TMCMarlin(Stream * SerialPort, const float RS, uint8_t addr, const uint16_t mul_pin1, const uint16_t mul_pin2) : TMC2208Stepper(SerialPort, RS, addr, mul_pin1, mul_pin2) {} TMCMarlin(const uint16_t RX, const uint16_t TX, const float RS, const uint8_t) : TMC2208Stepper(RX, TX, RS) {} uint16_t rms_current() { return TMC2208Stepper::rms_current(); } void rms_current(const uint16_t mA) { this->val_mA = mA; TMC2208Stepper::rms_current(mA); } void rms_current(const uint16_t mA, const float mult) { this->val_mA = mA; TMC2208Stepper::rms_current(mA, mult); } uint16_t get_microstep_counter() { return TMC2208Stepper::MSCNT(); } #if HAS_STEALTHCHOP bool get_stealthChop() { return !this->en_spreadCycle(); } bool get_stored_stealthChop() { return this->stored.stealthChop_enabled; } void refresh_stepping_mode() { this->en_spreadCycle(!this->stored.stealthChop_enabled); } void set_stealthChop(const bool stch) { this->stored.stealthChop_enabled = stch; refresh_stepping_mode(); } bool toggle_stepping_mode() { set_stealthChop(!this->stored.stealthChop_enabled); return get_stealthChop(); } #endif void set_chopper_times(const chopper_timing_t &ct) { TMC2208Stepper::toff(ct.toff); TMC2208Stepper::hysteresis_end(ct.hend); TMC2208Stepper::hysteresis_start(ct.hstrt); } #if ENABLED(HYBRID_THRESHOLD) uint32_t get_pwm_thrs() { return _tmc_thrs(this->microsteps(), this->TPWMTHRS(), planner.settings.axis_steps_per_mm[AXIS_ID]); } void set_pwm_thrs(const uint32_t thrs) { TMC2208Stepper::TPWMTHRS(_tmc_thrs(this->microsteps(), thrs, planner.settings.axis_steps_per_mm[AXIS_ID])); TERN_(HAS_MARLINUI_MENU, this->stored.hybrid_thrs = thrs); } #endif void refresh_stepper_current() { rms_current(this->val_mA); } #if ENABLED(HYBRID_THRESHOLD) void refresh_hybrid_thrs() { set_pwm_thrs(this->stored.hybrid_thrs); } #endif }; template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> class TMCMarlin<TMC2209Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> : public TMC2209Stepper, public TMCStorage<AXIS_LETTER, DRIVER_ID> { public: TMCMarlin(Stream * SerialPort, const float RS, const uint8_t addr) : TMC2209Stepper(SerialPort, RS, addr) {} TMCMarlin(const uint16_t RX, const uint16_t TX, const float RS, const uint8_t addr) : TMC2209Stepper(RX, TX, RS, addr) {} uint8_t get_address() { return slave_address; } uint16_t rms_current() { return TMC2209Stepper::rms_current(); } void rms_current(const uint16_t mA) { this->val_mA = mA; TMC2209Stepper::rms_current(mA); } void rms_current(const uint16_t mA, const float mult) { this->val_mA = mA; TMC2209Stepper::rms_current(mA, mult); } uint16_t get_microstep_counter() { return TMC2209Stepper::MSCNT(); } #if HAS_STEALTHCHOP bool get_stealthChop() { return !this->en_spreadCycle(); } bool get_stored_stealthChop() { return this->stored.stealthChop_enabled; } void refresh_stepping_mode() { this->en_spreadCycle(!this->stored.stealthChop_enabled); } void set_stealthChop(const bool stch) { this->stored.stealthChop_enabled = stch; refresh_stepping_mode(); } bool toggle_stepping_mode() { set_stealthChop(!this->stored.stealthChop_enabled); return get_stealthChop(); } #endif void set_chopper_times(const chopper_timing_t &ct) { TMC2209Stepper::toff(ct.toff); TMC2209Stepper::hysteresis_end(ct.hend); TMC2209Stepper::hysteresis_start(ct.hstrt); } #if ENABLED(HYBRID_THRESHOLD) uint32_t get_pwm_thrs() { return _tmc_thrs(this->microsteps(), this->TPWMTHRS(), planner.settings.axis_steps_per_mm[AXIS_ID]); } void set_pwm_thrs(const uint32_t thrs) { TMC2209Stepper::TPWMTHRS(_tmc_thrs(this->microsteps(), thrs, planner.settings.axis_steps_per_mm[AXIS_ID])); TERN_(HAS_MARLINUI_MENU, this->stored.hybrid_thrs = thrs); } #endif #if USE_SENSORLESS int16_t homing_threshold() { return TMC2209Stepper::SGTHRS(); } void homing_threshold(int16_t sgt_val) { sgt_val = (int16_t)constrain(sgt_val, sgt_min, sgt_max); TMC2209Stepper::SGTHRS(sgt_val); TERN_(HAS_MARLINUI_MENU, this->stored.homing_thrs = sgt_val); } #endif void refresh_stepper_current() { rms_current(this->val_mA); } #if ENABLED(HYBRID_THRESHOLD) void refresh_hybrid_thrs() { set_pwm_thrs(this->stored.hybrid_thrs); } #endif #if USE_SENSORLESS void refresh_homing_thrs() { homing_threshold(this->stored.homing_thrs); } #endif static constexpr uint8_t sgt_min = 0, sgt_max = 255; }; template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> class TMCMarlin<TMC2660Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> : public TMC2660Stepper, public TMCStorage<AXIS_LETTER, DRIVER_ID> { public: TMCMarlin(const uint16_t cs_pin, const float RS, const uint8_t) : TMC2660Stepper(cs_pin, RS) {} TMCMarlin(const uint16_t CS, const float RS, const uint16_t pinMOSI, const uint16_t pinMISO, const uint16_t pinSCK, const uint8_t) : TMC2660Stepper(CS, RS, pinMOSI, pinMISO, pinSCK) {} uint16_t rms_current() { return TMC2660Stepper::rms_current(); } void rms_current(const uint16_t mA) { this->val_mA = mA; TMC2660Stepper::rms_current(mA); } uint16_t get_microstep_counter() { return TMC2660Stepper::mstep(); } void set_chopper_times(const chopper_timing_t &ct) { TMC2660Stepper::toff(ct.toff); TMC2660Stepper::hysteresis_end(ct.hend); TMC2660Stepper::hysteresis_start(ct.hstrt); } #if USE_SENSORLESS int16_t homing_threshold() { return TMC2660Stepper::sgt(); } void homing_threshold(int16_t sgt_val) { sgt_val = (int16_t)constrain(sgt_val, sgt_min, sgt_max); TMC2660Stepper::sgt(sgt_val); TERN_(HAS_MARLINUI_MENU, this->stored.homing_thrs = sgt_val); } #endif void refresh_stepper_current() { rms_current(this->val_mA); } #if USE_SENSORLESS void refresh_homing_thrs() { homing_threshold(this->stored.homing_thrs); } #endif static constexpr int8_t sgt_min = -64, sgt_max = 63; }; void monitor_tmc_drivers(); void test_tmc_connection(LOGICAL_AXIS_DECL(const bool, true)); #if ENABLED(TMC_DEBUG) #if ENABLED(MONITOR_DRIVER_STATUS) void tmc_set_report_interval(const uint16_t update_interval); #endif void tmc_report_all(LOGICAL_AXIS_DECL(const bool, true)); void tmc_get_registers(LOGICAL_AXIS_ARGS(const bool)); #endif /** * TMC2130-specific sensorless homing using stallGuard2. * stallGuard2 only works when in spreadCycle mode. * spreadCycle and stealthChop are mutually-exclusive. * * Defined here because of limitations with templates and headers. */ #if USE_SENSORLESS // Track enabled status of stealthChop and only re-enable where applicable struct sensorless_t { bool NUM_AXIS_ARGS_() x2, y2, z2, z3, z4; }; #if ENABLED(IMPROVE_HOMING_RELIABILITY) extern millis_t sg_guard_period; constexpr uint16_t default_sg_guard_duration = 400; #endif bool tmc_enable_stallguard(TMC2130Stepper &st); void tmc_disable_stallguard(TMC2130Stepper &st, const bool restore_stealth); bool tmc_enable_stallguard(TMC2209Stepper &st); void tmc_disable_stallguard(TMC2209Stepper &st, const bool restore_stealth); bool tmc_enable_stallguard(TMC2660Stepper); void tmc_disable_stallguard(TMC2660Stepper, const bool); #if ENABLED(SPI_ENDSTOPS) template<class TMC, char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> bool TMCMarlin<TMC, AXIS_LETTER, DRIVER_ID, AXIS_ID>::test_stall_status() { this->switchCSpin(LOW); // read stallGuard flag from TMC library, will handle HW and SW SPI TMC2130_n::DRV_STATUS_t drv_status{0}; drv_status.sr = this->DRV_STATUS(); this->switchCSpin(HIGH); return drv_status.stallGuard; } #endif // SPI_ENDSTOPS #endif // USE_SENSORLESS #endif // HAS_TRINAMIC_CONFIG #if HAS_TMC_SPI void tmc_init_cs_pins(); #endif
2301_81045437/Marlin
Marlin/src/feature/tmc_util.h
C++
agpl-3.0
14,217
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfigPre.h" #if ENABLED(ASSISTED_TRAMMING) #include "tramming.h" #define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) #include "../core/debug_out.h" #define _TRAM_NAME_DEF(N) PGMSTR(point_name_##N, TRAMMING_POINT_NAME_##N); #define _TRAM_NAME_ITEM(N) point_name_##N REPEAT_1(_NR_TRAM_NAMES, _TRAM_NAME_DEF) PGM_P const tramming_point_name[] PROGMEM = { REPLIST_1(_NR_TRAM_NAMES, _TRAM_NAME_ITEM) }; #ifdef ASSISTED_TRAMMING_WAIT_POSITION // Move to the defined wait position void move_to_tramming_wait_pos() { constexpr xyz_pos_t wait_pos = ASSISTED_TRAMMING_WAIT_POSITION; if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Moving away"); do_blocking_move_to(wait_pos, XY_PROBE_FEEDRATE_MM_S); } #endif #endif // ASSISTED_TRAMMING
2301_81045437/Marlin
Marlin/src/feature/tramming.cpp
C++
agpl-3.0
1,634
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfig.h" #include "../module/probe.h" #if !WITHIN(TRAMMING_SCREW_THREAD, 30, 51) || TRAMMING_SCREW_THREAD % 10 > 1 #error "TRAMMING_SCREW_THREAD must be equal to 30, 31, 40, 41, 50, or 51." #endif constexpr xy_pos_t tramming_points[] = TRAMMING_POINT_XY; #define G35_PROBE_COUNT COUNT(tramming_points) static_assert(WITHIN(G35_PROBE_COUNT, 3, 9), "TRAMMING_POINT_XY requires between 3 and 9 XY positions."); #ifdef TRAMMING_POINT_NAME_9 #define _NR_TRAM_NAMES 9 #elif defined(TRAMMING_POINT_NAME_8) #define _NR_TRAM_NAMES 8 #elif defined(TRAMMING_POINT_NAME_7) #define _NR_TRAM_NAMES 7 #elif defined(TRAMMING_POINT_NAME_6) #define _NR_TRAM_NAMES 6 #elif defined(TRAMMING_POINT_NAME_5) #define _NR_TRAM_NAMES 5 #elif defined(TRAMMING_POINT_NAME_4) #define _NR_TRAM_NAMES 4 #elif defined(TRAMMING_POINT_NAME_3) #define _NR_TRAM_NAMES 3 #else #define _NR_TRAM_NAMES 0 #endif static_assert(_NR_TRAM_NAMES >= G35_PROBE_COUNT, "Define enough TRAMMING_POINT_NAME_s for all TRAMMING_POINT_XY entries."); #define _TRAM_NAME_PTR(N) point_name_##N[] extern const char REPLIST_1(_NR_TRAM_NAMES, _TRAM_NAME_PTR); #define _CHECK_TRAM_POINT(N) static_assert(Probe::build_time::can_reach(tramming_points[N]), "TRAMMING_POINT_XY point " STRINGIFY(N) " is not reachable with the default NOZZLE_TO_PROBE offset and PROBING_MARGIN."); REPEAT(_NR_TRAM_NAMES, _CHECK_TRAM_POINT) #undef _CHECK_TRAM_POINT extern PGM_P const tramming_point_name[]; #ifdef ASSISTED_TRAMMING_WAIT_POSITION void move_to_tramming_wait_pos(); #else inline void move_to_tramming_wait_pos() {} #endif
2301_81045437/Marlin
Marlin/src/feature/tramming.h
C++
agpl-3.0
2,484
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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(EXPERIMENTAL_I2CBUS) #include "twibus.h" #include <Wire.h> #include "../libs/hex_print.h" TWIBus i2c; TWIBus::TWIBus() { #if I2C_SLAVE_ADDRESS == 0 #if PINS_EXIST(I2C_SCL, I2C_SDA) && DISABLED(SOFT_I2C_EEPROM) Wire.setSDA(pin_t(I2C_SDA_PIN)); Wire.setSCL(pin_t(I2C_SCL_PIN)); #endif Wire.begin(); // No address joins the BUS as the master #else Wire.begin(I2C_SLAVE_ADDRESS); // Join the bus as a slave #endif reset(); } void TWIBus::reset() { buffer_s = 0; buffer[0] = 0x00; } void TWIBus::address(const uint8_t adr) { if (!WITHIN(adr, 8, 127)) SERIAL_ECHO_MSG("Bad I2C address (8-127)"); addr = adr; debug(F("address"), adr); } void TWIBus::addbyte(const char c) { if (buffer_s >= COUNT(buffer)) return; buffer[buffer_s++] = c; debug(F("addbyte"), c); } void TWIBus::addbytes(char src[], uint8_t bytes) { debug(F("addbytes"), bytes); while (bytes--) addbyte(*src++); } void TWIBus::addstring(char str[]) { debug(F("addstring"), str); while (char c = *str++) addbyte(c); } void TWIBus::send() { debug(F("send"), addr); Wire.beginTransmission(I2C_ADDRESS(addr)); Wire.write(buffer, buffer_s); Wire.endTransmission(); reset(); } // static void TWIBus::echoprefix(uint8_t bytes, FSTR_P const pref, uint8_t adr) { SERIAL_ECHO_START(); SERIAL_ECHO(pref, F(": from:"), adr, F(" bytes:"), bytes, F(" data:")); } // static void TWIBus::echodata(uint8_t bytes, FSTR_P const pref, uint8_t adr, const uint8_t style/*=0*/) { union TwoBytesToInt16 { uint8_t bytes[2]; int16_t integervalue; }; TwoBytesToInt16 ConversionUnion; echoprefix(bytes, pref, adr); while (bytes-- && Wire.available()) { int value = Wire.read(); switch (style) { // Style 1, HEX DUMP case 1: SERIAL_CHAR(hex_nybble((value & 0xF0) >> 4)); SERIAL_CHAR(hex_nybble(value & 0x0F)); if (bytes) SERIAL_CHAR(' '); break; // Style 2, signed two byte integer (int16) case 2: if (bytes == 1) ConversionUnion.bytes[1] = (uint8_t)value; else if (bytes == 0) { ConversionUnion.bytes[0] = (uint8_t)value; // Output value in base 10 (standard decimal) SERIAL_ECHO(ConversionUnion.integervalue); } break; // Style 3, unsigned byte, base 10 (uint8) case 3: SERIAL_ECHO(value); if (bytes) SERIAL_CHAR(' '); break; // Default style (zero), raw serial output default: // This can cause issues with some serial consoles, Pronterface is an example where things go wrong SERIAL_CHAR(value); break; } } SERIAL_EOL(); } void TWIBus::echobuffer(FSTR_P const prefix, uint8_t adr) { echoprefix(buffer_s, prefix, adr); for (uint8_t i = 0; i < buffer_s; ++i) SERIAL_CHAR(buffer[i]); SERIAL_EOL(); } bool TWIBus::request(const uint8_t bytes) { if (!addr) return false; debug(F("request"), bytes); // requestFrom() is a blocking function if (Wire.requestFrom(I2C_ADDRESS(addr), bytes) == 0) { debug(F("request fail"), I2C_ADDRESS(addr)); return false; } return true; } void TWIBus::relay(const uint8_t bytes, const uint8_t style/*=0*/) { debug(F("relay"), bytes); if (request(bytes)) echodata(bytes, F("i2c-reply"), addr, style); } uint8_t TWIBus::capture(char *dst, const uint8_t bytes) { reset(); uint8_t count = 0; while (count < bytes && Wire.available()) dst[count++] = Wire.read(); debug(F("capture"), count); return count; } // static void TWIBus::flush() { while (Wire.available()) Wire.read(); } #if I2C_SLAVE_ADDRESS > 0 void TWIBus::receive(uint8_t bytes) { debug(F("receive"), bytes); echodata(bytes, F("i2c-receive"), 0); } void TWIBus::reply(char str[]/*=nullptr*/) { debug(F("reply"), str); if (str) { reset(); addstring(str); } Wire.write(buffer, buffer_s); reset(); } void i2c_on_receive(int bytes) { // just echo all bytes received to serial i2c.receive(bytes); } void i2c_on_request() { // just send dummy data for now i2c.reply("Hello World!\n"); } #endif #if ENABLED(DEBUG_TWIBUS) // static void TWIBus::prefix(FSTR_P const func) { SERIAL_ECHOPGM("TWIBus::", func, ": "); } void TWIBus::debug(FSTR_P const func, uint32_t adr) { if (DEBUGGING(INFO)) { prefix(func); SERIAL_ECHOLN(adr); } } void TWIBus::debug(FSTR_P const func, char c) { if (DEBUGGING(INFO)) { prefix(func); SERIAL_ECHOLN(c); } } void TWIBus::debug(FSTR_P const func, char str[]) { if (DEBUGGING(INFO)) { prefix(func); SERIAL_ECHOLN(str); } } #endif #endif // EXPERIMENTAL_I2CBUS
2301_81045437/Marlin
Marlin/src/feature/twibus.cpp
C++
agpl-3.0
5,635
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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" #include <Wire.h> // Print debug messages with M111 S2 (Uses 236 bytes of PROGMEM) //#define DEBUG_TWIBUS typedef void (*twiReceiveFunc_t)(int bytes); typedef void (*twiRequestFunc_t)(); /** * For a light i2c protocol that runs on two boards running Marlin see: * See https://github.com/MarlinFirmware/Marlin/issues/4776#issuecomment-246262879 */ #if I2C_SLAVE_ADDRESS > 0 void i2c_on_receive(int bytes); // Demo i2c onReceive handler void i2c_on_request(); // Demo i2c onRequest handler #endif #define TWIBUS_BUFFER_SIZE 32 /** * TWIBUS class * * This class implements a wrapper around the two wire (I2C) bus, allowing * Marlin to send and request data from any slave device on the bus. * * The two main consumers of this class are M260 and M261. M260 provides a way * to send an I2C packet to a device (no repeated starts) by caching up to 32 * bytes in a buffer and then sending the buffer. * M261 requests data from a device. The received data is relayed to serial out * for the host to interpret. * * For more information see * - https://marlinfw.org/docs/gcode/M260.html * - https://marlinfw.org/docs/gcode/M261.html */ class TWIBus { private: /** * @brief Number of bytes on buffer * @description Number of bytes in the buffer waiting to be flushed to the bus */ uint8_t buffer_s = 0; /** * @brief Internal buffer * @details A fixed buffer. TWI commands can be no longer than this. */ uint8_t buffer[TWIBUS_BUFFER_SIZE]; public: /** * @brief Target device address * @description The target device address. Persists until changed. */ uint8_t addr = 0; /** * @brief Class constructor * @details Initialize the TWI bus and clear the buffer */ TWIBus(); /** * @brief Reset the buffer * @details Set the buffer to a known-empty state */ void reset(); /** * @brief Send the buffer data to the bus * @details Flush the buffer to the target address */ void send(); /** * @brief Add one byte to the buffer * @details Add a byte to the end of the buffer. * Silently fails if the buffer is full. * * @param c a data byte */ void addbyte(const char c); /** * @brief Add some bytes to the buffer * @details Add bytes to the end of the buffer. * Concatenates at the buffer size. * * @param src source data address * @param bytes the number of bytes to add */ void addbytes(char src[], uint8_t bytes); /** * @brief Add a null-terminated string to the buffer * @details Add bytes to the end of the buffer up to a nul. * Concatenates at the buffer size. * * @param str source string address */ void addstring(char str[]); /** * @brief Set the target slave address * @details The target slave address for sending the full packet * * @param adr 7-bit integer address */ void address(const uint8_t adr); /** * @brief Prefix for echo to serial * @details Echo a label, length, address, and "data:" * * @param bytes the number of bytes to request */ static void echoprefix(uint8_t bytes, FSTR_P const prefix, uint8_t adr); /** * @brief Echo data on the bus to serial * @details Echo some number of bytes from the bus * to serial in a parser-friendly format. * * @param bytes the number of bytes to request * @param style Output format for the bytes, 0 = Raw byte [default], 1 = Hex characters, 2 = uint16_t */ static void echodata(uint8_t bytes, FSTR_P const prefix, uint8_t adr, const uint8_t style=0); /** * @brief Echo data in the buffer to serial * @details Echo the entire buffer to serial * to serial in a parser-friendly format. * * @param bytes the number of bytes to request */ void echobuffer(FSTR_P const prefix, uint8_t adr); /** * @brief Request data from the slave device and wait. * @details Request a number of bytes from a slave device. * Wait for the data to arrive, and return true * on success. * * @param bytes the number of bytes to request * @return status of the request: true=success, false=fail */ bool request(const uint8_t bytes); /** * @brief Capture data from the bus into the buffer. * @details Capture data after a request has succeeded. * * @param bytes the number of bytes to request * @return the number of bytes captured to the buffer */ uint8_t capture(char *dst, const uint8_t bytes); /** * @brief Flush the i2c bus. * @details Get all bytes on the bus and throw them away. */ static void flush(); /** * @brief Request data from the slave device, echo to serial. * @details Request a number of bytes from a slave device and output * the returned data to serial in a parser-friendly format. * @style Output format for the bytes, 0 = raw byte [default], 1 = Hex characters, 2 = uint16_t * * @param bytes the number of bytes to request */ void relay(const uint8_t bytes, const uint8_t style=0); #if I2C_SLAVE_ADDRESS > 0 /** * @brief Register a slave receive handler * @details Set a handler to receive data addressed to us * * @param handler A function to handle receiving bytes */ inline void onReceive(const twiReceiveFunc_t handler) { Wire.onReceive(handler); } /** * @brief Register a slave request handler * @details Set a handler to send data requested from us * * @param handler A function to handle receiving bytes */ inline void onRequest(const twiRequestFunc_t handler) { Wire.onRequest(handler); } /** * @brief Default handler to receive * @details Receive bytes sent to our slave address * and simply echo them to serial. */ void receive(uint8_t bytes); /** * @brief Send a reply to the bus * @details Send the buffer and clear it. * If a string is passed, write it into the buffer first. */ void reply(char str[]=nullptr); inline void reply(const char str[]) { reply((char*)str); } #endif #if ENABLED(DEBUG_TWIBUS) /** * @brief Prints a debug message * @details Prints a simple debug message "TWIBus::function: value" */ static void prefix(FSTR_P const func); static void debug(FSTR_P const func, uint32_t adr); static void debug(FSTR_P const func, char c); static void debug(FSTR_P const func, char adr[]); #else static void debug(FSTR_P const, uint32_t) {} static void debug(FSTR_P const, char) {} static void debug(FSTR_P const, char[]) {} #endif static void debug(FSTR_P const func, uint8_t v) { debug(func, (uint32_t)v); } }; extern TWIBus i2c;
2301_81045437/Marlin
Marlin/src/feature/twibus.h
C++
agpl-3.0
7,981
/** * 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(X_AXIS_TWIST_COMPENSATION) #include "x_twist.h" #include "../module/probe.h" XATC xatc; bool XATC::enabled; float XATC::spacing, XATC::start; xatc_array_t XATC::z_offset; // Initialized by settings.load() void XATC::reset() { constexpr float xzo[] = XATC_Z_OFFSETS; static_assert(COUNT(xzo) == XATC_MAX_POINTS, "XATC_Z_OFFSETS is the wrong size."); COPY(z_offset, xzo); start = probe.min_x(); spacing = (probe.max_x() - start) / (XATC_MAX_POINTS - 1); enabled = true; } void XATC::print_points() { SERIAL_ECHOLNPGM(" X-Twist Correction:"); for (uint8_t x = 0; x < XATC_MAX_POINTS; ++x) { SERIAL_CHAR(' '); if (!isnan(z_offset[x])) serial_offset(z_offset[x]); else for (uint8_t i = 0; i < 6; ++i) SERIAL_CHAR(i ? '=' : ' '); } SERIAL_EOL(); } float lerp(const_float_t t, const_float_t a, const_float_t b) { return a + t * (b - a); } float XATC::compensation(const xy_pos_t &raw) { if (!enabled) return 0; if (NEAR_ZERO(spacing)) return 0; float t = (raw.x - start) / spacing; const int i = constrain(FLOOR(t), 0, XATC_MAX_POINTS - 2); t -= i; return lerp(t, z_offset[i], z_offset[i + 1]); } #endif // X_AXIS_TWIST_COMPENSATION
2301_81045437/Marlin
Marlin/src/feature/x_twist.cpp
C++
agpl-3.0
2,098
/** * 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" typedef float xatc_array_t[XATC_MAX_POINTS]; class XATC { static bool enabled; public: static float spacing, start; static xatc_array_t z_offset; static void reset(); static void set_enabled(const bool ena) { enabled = ena; } static float compensation(const xy_pos_t &raw); static void print_points(); }; extern XATC xatc;
2301_81045437/Marlin
Marlin/src/feature/x_twist.h
C++
agpl-3.0
1,253
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * feature/z_stepper_align.cpp */ #include "../inc/MarlinConfigPre.h" #if ENABLED(Z_STEPPER_AUTO_ALIGN) #include "z_stepper_align.h" #include "../module/probe.h" ZStepperAlign z_stepper_align; xy_pos_t ZStepperAlign::xy[NUM_Z_STEPPERS]; #if HAS_Z_STEPPER_ALIGN_STEPPER_XY xy_pos_t ZStepperAlign::stepper_xy[NUM_Z_STEPPERS]; #endif void ZStepperAlign::reset_to_default() { #ifdef Z_STEPPER_ALIGN_XY constexpr xy_pos_t xy_init[] = Z_STEPPER_ALIGN_XY; static_assert(COUNT(xy_init) == NUM_Z_STEPPERS, "Z_STEPPER_ALIGN_XY requires " #if NUM_Z_STEPPERS == 4 "four {X,Y} entries (Z, Z2, Z3, and Z4)." #elif NUM_Z_STEPPERS == 3 "three {X,Y} entries (Z, Z2, and Z3)." #else "two {X,Y} entries (Z and Z2)." #endif ); #define VALIDATE_ALIGN_POINT(N) static_assert(N >= NUM_Z_STEPPERS || Probe::build_time::can_reach(xy_init[N]), \ "Z_STEPPER_ALIGN_XY point " STRINGIFY(N) " is not reachable with the default NOZZLE_TO_PROBE offset and PROBING_MARGIN.") VALIDATE_ALIGN_POINT(0); VALIDATE_ALIGN_POINT(1); VALIDATE_ALIGN_POINT(2); VALIDATE_ALIGN_POINT(3); #else // !Z_STEPPER_ALIGN_XY const xy_pos_t xy_init[] = { #if NUM_Z_STEPPERS >= 3 // First probe point... #if !Z_STEPPERS_ORIENTATION { probe.min_x(), probe.min_y() }, // SW #elif Z_STEPPERS_ORIENTATION == 1 { probe.min_x(), probe.max_y() }, // NW #elif Z_STEPPERS_ORIENTATION == 2 { probe.max_x(), probe.max_y() }, // NE #elif Z_STEPPERS_ORIENTATION == 3 { probe.max_x(), probe.min_y() }, // SE #else #error "Z_STEPPERS_ORIENTATION must be from 0 to 3 (first point SW, NW, NE, SE)." #endif #if NUM_Z_STEPPERS == 4 // 3 more points... #if !Z_STEPPERS_ORIENTATION { probe.min_x(), probe.max_y() }, { probe.max_x(), probe.max_y() }, { probe.max_x(), probe.min_y() } // SW #elif Z_STEPPERS_ORIENTATION == 1 { probe.max_x(), probe.max_y() }, { probe.max_x(), probe.min_y() }, { probe.min_x(), probe.min_y() } // NW #elif Z_STEPPERS_ORIENTATION == 2 { probe.max_x(), probe.min_y() }, { probe.min_x(), probe.min_y() }, { probe.min_x(), probe.max_y() } // NE #elif Z_STEPPERS_ORIENTATION == 3 { probe.min_x(), probe.min_y() }, { probe.min_x(), probe.max_y() }, { probe.max_x(), probe.max_y() } // SE #endif #elif !Z_STEPPERS_ORIENTATION // or 2 more points... { probe.max_x(), probe.min_y() }, { X_CENTER, probe.max_y() } // SW #elif Z_STEPPERS_ORIENTATION == 1 { probe.min_x(), probe.min_y() }, { probe.max_x(), Y_CENTER } // NW #elif Z_STEPPERS_ORIENTATION == 2 { probe.min_x(), probe.max_y() }, { X_CENTER, probe.min_y() } // NE #elif Z_STEPPERS_ORIENTATION == 3 { probe.max_x(), probe.max_y() }, { probe.min_x(), Y_CENTER } // SE #endif #elif Z_STEPPERS_ORIENTATION { X_CENTER, probe.min_y() }, { X_CENTER, probe.max_y() } #else { probe.min_x(), Y_CENTER }, { probe.max_x(), Y_CENTER } #endif }; #endif // !Z_STEPPER_ALIGN_XY COPY(xy, xy_init); #if HAS_Z_STEPPER_ALIGN_STEPPER_XY constexpr xy_pos_t stepper_xy_init[] = Z_STEPPER_ALIGN_STEPPER_XY; static_assert( COUNT(stepper_xy_init) == NUM_Z_STEPPERS, "Z_STEPPER_ALIGN_STEPPER_XY requires " #if NUM_Z_STEPPERS == 4 "four {X,Y} entries (Z, Z2, Z3, and Z4)." #elif NUM_Z_STEPPERS == 3 "three {X,Y} entries (Z, Z2, and Z3)." #endif ); COPY(stepper_xy, stepper_xy_init); #endif } #endif // Z_STEPPER_AUTO_ALIGN
2301_81045437/Marlin
Marlin/src/feature/z_stepper_align.cpp
C++
agpl-3.0
4,581
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * feature/z_stepper_align.h */ #include "../inc/MarlinConfig.h" class ZStepperAlign { public: static xy_pos_t xy[NUM_Z_STEPPERS]; #if HAS_Z_STEPPER_ALIGN_STEPPER_XY static xy_pos_t stepper_xy[NUM_Z_STEPPERS]; #endif static void reset_to_default(); }; extern ZStepperAlign z_stepper_align;
2301_81045437/Marlin
Marlin/src/feature/z_stepper_align.h
C++
agpl-3.0
1,198
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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/>. * */ /** * G26 Mesh Validation Tool * * G26 is a Mesh Validation Tool intended to provide support for the Marlin Unified Bed Leveling System. * In order to fully utilize and benefit from the Marlin Unified Bed Leveling System an accurate Mesh must * be defined. G29 is designed to allow the user to quickly validate the correctness of her Mesh. It will * first heat the bed and nozzle. It will then print lines and circles along the Mesh Cell boundaries and * the intersections of those lines (respectively). * * This action allows the user to immediately see where the Mesh is properly defined and where it needs to * be edited. The command will generate the Mesh lines closest to the nozzle's starting position. Alternatively * the user can specify the X and Y position of interest with command parameters. This allows the user to * focus on a particular area of the Mesh where attention is needed. * * B # Bed Set the Bed Temperature. If not specified, a default of 60 C. will be assumed. * * C Current When searching for Mesh Intersection points to draw, use the current nozzle location * as the base for any distance comparison. * * D Disable Disable the Unified Bed Leveling System. In the normal case the user is invoking this * command to see how well a Mesh as been adjusted to match a print surface. In order to do * this the Unified Bed Leveling System is turned on by the G26 command. The D parameter * alters the command's normal behavior and disables the Unified Bed Leveling System even if * it is on. * * H # Hotend Set the Nozzle Temperature. If not specified, a default of 205 C. will be assumed. * * I # Preset Heat the Nozzle and Bed based on a Material Preset (if material presets are defined). * * F # Filament Used to specify the diameter of the filament being used. If not specified * 1.75mm filament is assumed. If you are not getting acceptable results by using the * 'correct' numbers, you can scale this number up or down a little bit to change the amount * of filament that is being extruded during the printing of the various lines on the bed. * * K Keep-On Keep the heaters turned on at the end of the command. * * L # Layer Layer height. (Height of nozzle above bed) If not specified .20mm will be used. * * O # Ooooze How much your nozzle will Ooooze filament while getting in position to print. This * is over kill, but using this parameter will let you get the very first 'circle' perfect * so you have a trophy to peel off of the bed and hang up to show how perfectly you have your * Mesh calibrated. If not specified, a filament length of .3mm is assumed. * * P # Prime Prime the nozzle with specified length of filament. If this parameter is not * given, no prime action will take place. If the parameter specifies an amount, that much * will be purged before continuing. If no amount is specified the command will start * purging filament until the user provides an LCD Click and then it will continue with * printing the Mesh. You can carefully remove the spent filament with a needle nose * pliers while holding the LCD Click wheel in a depressed state. If you do not have * an LCD, you must specify a value if you use P. * * Q # Multiplier Retraction Multiplier. (Normally not needed.) During G26 retraction will use the length * specified by this parameter (1mm by default). Recover will be 1.2x the retract distance. * * R # Repeat Prints the number of patterns given as a parameter, starting at the current location. * If a parameter isn't given, every point will be printed unless G26 is interrupted. * This works the same way that the UBL G29 P4 R parameter works. * * NOTE: If you do not have an LCD, you -must- specify R. This is to ensure that you are * aware that there's some risk associated with printing without the ability to abort in * cases where mesh point Z value may be inaccurate. As above, if you do not include a * parameter, every point will be printed. * * S # Nozzle Used to control the size of nozzle diameter. If not specified, a .4mm nozzle is assumed. * * U # Random Randomize the order that the circles are drawn on the bed. The search for the closest * un-drawn circle is still done. But the distance to the location for each circle has a * random number of the specified size added to it. Specifying S50 will give an interesting * deviation from the normal behavior on a 10 x 10 Mesh. * * X # X Coord. Specify the starting location of the drawing activity. * * Y # Y Coord. Specify the starting location of the drawing activity. */ #include "../../inc/MarlinConfig.h" #if ENABLED(G26_MESH_VALIDATION) #define G26_OK false #define G26_ERR true #include "../../gcode/gcode.h" #include "../../feature/bedlevel/bedlevel.h" #include "../../MarlinCore.h" #include "../../module/planner.h" #include "../../module/motion.h" #include "../../module/tool_change.h" #include "../../module/temperature.h" #include "../../lcd/marlinui.h" #if ENABLED(EXTENSIBLE_UI) #include "../../lcd/extui/ui_api.h" #endif #if ENABLED(UBL_HILBERT_CURVE) #include "../../feature/bedlevel/hilbert_curve.h" #endif #define EXTRUSION_MULTIPLIER 1.0 #define PRIME_LENGTH 10.0 #define OOZE_AMOUNT 0.3 #define INTERSECTION_CIRCLE_RADIUS 5 #define CROSSHAIRS_SIZE 3 #ifndef G26_RETRACT_MULTIPLIER #define G26_RETRACT_MULTIPLIER 1.0 // x 1mm #endif #ifndef G26_XY_FEEDRATE #define G26_XY_FEEDRATE (PLANNER_XY_FEEDRATE() / 3.0) #endif #ifndef G26_XY_FEEDRATE_TRAVEL #define G26_XY_FEEDRATE_TRAVEL (PLANNER_XY_FEEDRATE() / 1.5) #endif #if CROSSHAIRS_SIZE >= INTERSECTION_CIRCLE_RADIUS #error "CROSSHAIRS_SIZE must be less than INTERSECTION_CIRCLE_RADIUS." #endif #define G26_OK false #define G26_ERR true #if ENABLED(ARC_SUPPORT) void plan_arc(const xyze_pos_t&, const ab_float_t&, const bool, const uint8_t); #endif constexpr float g26_e_axis_feedrate = 0.025; static MeshFlags circle_flags; float g26_random_deviation = 0.0; #if HAS_MARLINUI_MENU /** * If the LCD is clicked, cancel, wait for release, return true */ bool user_canceled() { if (!ui.button_pressed()) return false; // Return if the button isn't pressed LCD_MESSAGE_MAX(MSG_G26_CANCELED); ui.quick_feedback(); ui.wait_for_release(); return true; } #endif void move_to(const_float_t rx, const_float_t ry, const_float_t z, const_float_t e_delta) { static float last_z = -999.99; const xy_pos_t dest = { rx, ry }; const bool has_xy_component = dest != current_position, // Check if X or Y is involved in the movement. has_e_component = e_delta != 0.0; if (z != last_z) { last_z = z; destination.set(current_position.x, current_position.y, z, current_position.e); const feedRate_t fr_mm_s = planner.settings.max_feedrate_mm_s[Z_AXIS] * 0.5f; // Use half of the Z_AXIS max feed rate prepare_internal_move_to_destination(fr_mm_s); } // If X or Y in combination with E is involved do a 'normal' move. // If X or Y with no E is involved do a 'fast' move // Otherwise retract/recover/hop. destination = dest; destination.e += e_delta; const feedRate_t fr_mm_s = has_xy_component ? (has_e_component ? feedRate_t(G26_XY_FEEDRATE) : feedRate_t(G26_XY_FEEDRATE_TRAVEL)) : planner.settings.max_feedrate_mm_s[E_AXIS] * 0.666f; prepare_internal_move_to_destination(fr_mm_s); } void move_to(const xyz_pos_t &where, const_float_t de) { move_to(where.x, where.y, where.z, de); } typedef struct { float extrusion_multiplier = EXTRUSION_MULTIPLIER, retraction_multiplier = G26_RETRACT_MULTIPLIER, layer_height = MESH_TEST_LAYER_HEIGHT, prime_length = PRIME_LENGTH; celsius_t bed_temp = MESH_TEST_BED_TEMP, hotend_temp = MESH_TEST_HOTEND_TEMP; float nozzle = MESH_TEST_NOZZLE_SIZE, filament_diameter = DEFAULT_NOMINAL_FILAMENT_DIA, ooze_amount; // 'O' ... OOZE_AMOUNT bool continue_with_closest, // 'C' keep_heaters_on; // 'K' xy_pos_t xy_pos; // = { 0, 0 } int8_t prime_flag = 0; bool g26_retracted = false; // Track the retracted state during G26 so mismatched // retracts/recovers don't result in a bad state. void retract_filament(const xyz_pos_t &where) { if (!g26_retracted) { // Only retract if we are not already retracted! g26_retracted = true; move_to(where, -1.0f * retraction_multiplier); } } // TODO: Parameterize the Z lift with a define void retract_lift_move(const xyz_pos_t &s) { retract_filament(destination); move_to(current_position.x, current_position.y, current_position.z + 0.5f, 0.0f); // Z lift to minimize scraping move_to(s.x, s.y, s.z + 0.5f, 0.0f); // Get to the starting point with no extrusion while lifted } void recover_filament(const xyz_pos_t &where) { if (g26_retracted) { // Only un-retract if we are retracted. move_to(where, 1.2f * retraction_multiplier); g26_retracted = false; } } /** * print_line_from_here_to_there() takes two cartesian coordinates and draws a line from one * to the other. But there are really three sets of coordinates involved. The first coordinate * is the present location of the nozzle. We don't necessarily want to print from this location. * We first need to move the nozzle to the start of line segment where we want to print. Once * there, we can use the two coordinates supplied to draw the line. * * Note: Although we assume the first set of coordinates is the start of the line and the second * set of coordinates is the end of the line, it does not always work out that way. This function * optimizes the movement to minimize the travel distance before it can start printing. This saves * a lot of time and eliminates a lot of nonsensical movement of the nozzle. However, it does * cause a lot of very little short retracement of th nozzle when it draws the very first line * segment of a 'circle'. The time this requires is very short and is easily saved by the other * cases where the optimization comes into play. */ void print_line_from_here_to_there(const xyz_pos_t &s, const xyz_pos_t &e) { // Distances to the start / end of the line xy_float_t svec = current_position - s, evec = current_position - e; const float dist_start = HYPOT2(svec.x, svec.y), dist_end = HYPOT2(evec.x, evec.y), line_length = HYPOT(e.x - s.x, e.y - s.y); // If the end point of the line is closer to the nozzle, flip the direction, // moving from the end to the start. On very small lines the optimization isn't worth it. if (dist_end < dist_start && (INTERSECTION_CIRCLE_RADIUS) < ABS(line_length)) return print_line_from_here_to_there(e, s); // Decide whether to retract & lift if (dist_start > 2.0) retract_lift_move(s); move_to(s, 0.0); // Get to the starting point with no extrusion / un-Z lift const float e_pos_delta = line_length * g26_e_axis_feedrate * extrusion_multiplier; recover_filament(destination); move_to(e, e_pos_delta); // Get to the ending point with an appropriate amount of extrusion } void connect_neighbor_with_line(const xy_int8_t &p1, int8_t dx, int8_t dy) { xy_int8_t p2; p2.x = p1.x + dx; p2.y = p1.y + dy; if (p2.x < 0 || p2.x >= (GRID_MAX_POINTS_X)) return; if (p2.y < 0 || p2.y >= (GRID_MAX_POINTS_Y)) return; if (circle_flags.marked(p1.x, p1.y) && circle_flags.marked(p2.x, p2.y)) { xyz_pos_t s, e; s.x = bedlevel.get_mesh_x(p1.x) + (INTERSECTION_CIRCLE_RADIUS - (CROSSHAIRS_SIZE)) * dx; e.x = bedlevel.get_mesh_x(p2.x) - (INTERSECTION_CIRCLE_RADIUS - (CROSSHAIRS_SIZE)) * dx; s.y = bedlevel.get_mesh_y(p1.y) + (INTERSECTION_CIRCLE_RADIUS - (CROSSHAIRS_SIZE)) * dy; e.y = bedlevel.get_mesh_y(p2.y) - (INTERSECTION_CIRCLE_RADIUS - (CROSSHAIRS_SIZE)) * dy; s.z = e.z = layer_height; #if HAS_ENDSTOPS LIMIT(s.y, Y_MIN_POS + 1, Y_MAX_POS - 1); LIMIT(e.y, Y_MIN_POS + 1, Y_MAX_POS - 1); LIMIT(s.x, X_MIN_POS + 1, X_MAX_POS - 1); LIMIT(e.x, X_MIN_POS + 1, X_MAX_POS - 1); #endif if (position_is_reachable(s) && position_is_reachable(e)) print_line_from_here_to_there(s, e); } } /** * Turn on the bed and nozzle heat and * wait for them to get up to temperature. */ bool turn_on_heaters() { SERIAL_ECHOLNPGM("Waiting for heatup."); #if HAS_HEATED_BED if (bed_temp > 25) { LCD_MESSAGE_MAX(MSG_G26_HEATING_BED); ui.quick_feedback(); TERN_(HAS_MARLINUI_MENU, ui.capture()); thermalManager.setTargetBed(bed_temp); // Wait for the temperature to stabilize if (!thermalManager.wait_for_bed(true OPTARG(G26_CLICK_CAN_CANCEL, true))) return G26_ERR; } #else UNUSED(bed_temp); #endif // HAS_HEATED_BED // Start heating the active nozzle LCD_MESSAGE_MAX(MSG_G26_HEATING_NOZZLE); ui.quick_feedback(); thermalManager.setTargetHotend(hotend_temp, active_extruder); // Wait for the temperature to stabilize if (!thermalManager.wait_for_hotend(active_extruder, true OPTARG(G26_CLICK_CAN_CANCEL, true))) return G26_ERR; ui.reset_status(); ui.completion_feedback(); return G26_OK; } /** * Prime the nozzle if needed. Return true on error. */ bool prime_nozzle() { const feedRate_t fr_slow_e = planner.settings.max_feedrate_mm_s[E_AXIS] / 15.0f; #if HAS_MARLINUI_MENU && !HAS_TOUCH_BUTTONS // ui.button_pressed issue with touchscreen #if ENABLED(PREVENT_LENGTHY_EXTRUDE) float Total_Prime = 0.0; #endif if (prime_flag == -1) { // The user wants to control how much filament gets purged ui.capture(); LCD_MESSAGE_MAX(MSG_G26_MANUAL_PRIME); ui.chirp(); destination = current_position; recover_filament(destination); // Make sure G26 doesn't think the filament is retracted(). while (!ui.button_pressed()) { ui.chirp(); destination.e += 0.25; #if ENABLED(PREVENT_LENGTHY_EXTRUDE) Total_Prime += 0.25; if (Total_Prime >= EXTRUDE_MAXLENGTH) { ui.release(); return G26_ERR; } #endif prepare_internal_move_to_destination(fr_slow_e); destination = current_position; planner.synchronize(); // Without this synchronize, the purge is more consistent, // but because the planner has a buffer, we won't be able // to stop as quickly. So we put up with the less smooth // action to give the user a more responsive 'Stop'. } ui.wait_for_release(); LCD_MESSAGE_MAX(MSG_G26_PRIME_DONE); ui.quick_feedback(); ui.release(); } else #endif { LCD_MESSAGE_MAX(MSG_G26_FIXED_LENGTH); ui.quick_feedback(); destination = current_position; destination.e += prime_length; prepare_internal_move_to_destination(fr_slow_e); destination.e -= prime_length; retract_filament(destination); } return G26_OK; } /** * Find the nearest point at which to print a circle */ mesh_index_pair find_closest_circle_to_print(const xy_pos_t &pos) { mesh_index_pair out_point; out_point.pos = -1; #if ENABLED(UBL_HILBERT_CURVE) auto test_func = [](uint8_t i, uint8_t j, void *data) -> bool { if (!circle_flags.marked(i, j)) { mesh_index_pair *out_point = (mesh_index_pair*)data; out_point->pos.set(i, j); // Save its data return true; } return false; }; hilbert_curve::search_from_closest(pos, test_func, &out_point); #else float closest = 99999.99; GRID_LOOP(i, j) { if (!circle_flags.marked(i, j)) { // We found a circle that needs to be printed const xy_pos_t m = { bedlevel.get_mesh_x(i), bedlevel.get_mesh_y(j) }; // Get the distance to this intersection float f = (pos - m).magnitude(); // It is possible that we are being called with the values // to let us find the closest circle to the start position. // But if this is not the case, add a small weighting to the // distance calculation to help it choose a better place to continue. f += (xy_pos - m).magnitude() / 15.0f; // Add the specified amount of Random Noise to our search if (g26_random_deviation > 1.0) f += random(0.0, g26_random_deviation); if (f < closest) { closest = f; // Found a closer un-printed location out_point.pos.set(i, j); // Save its data out_point.distance = closest; } } } #endif circle_flags.mark(out_point); // Mark this location as done. return out_point; } } g26_helper_t; /** * G26: Mesh Validation Pattern generation. * * Used to interactively edit the mesh by placing the * nozzle in a problem area and doing a G29 P4 R command. * * Parameters: * * B Bed Temperature * C Continue from the Closest mesh point * D Disable leveling before starting * F Filament diameter * H Hotend Temperature * K Keep heaters on when completed * L Layer Height * O Ooze extrusion length * P Prime length * Q Retraction multiplier * R Repetitions (number of grid points) * S Nozzle Size (diameter) in mm * T Tool index to change to, if included * U Random deviation (50 if no value given) * X X position * Y Y position */ void GcodeSuite::G26() { SERIAL_ECHOLNPGM("G26 starting..."); // Don't allow Mesh Validation without homing first, // or if the parameter parsing did not go OK, abort if (homing_needed_error()) return; #if HAS_TOOLCHANGE // Change the tool first, if specified if (parser.seenval('T')) tool_change(parser.value_int()); #endif g26_helper_t g26; g26.ooze_amount = parser.linearval('O', OOZE_AMOUNT); g26.continue_with_closest = parser.boolval('C'); g26.keep_heaters_on = parser.boolval('K'); // Accept 'I' if temperature presets are defined #if HAS_PREHEAT const uint8_t preset_index = parser.seenval('I') ? _MIN(parser.value_byte(), PREHEAT_COUNT - 1) + 1 : 0; #endif #if HAS_HEATED_BED // Get a temperature from 'I' or 'B' celsius_t bedtemp = 0; // Use the 'I' index if temperature presets are defined #if HAS_PREHEAT if (preset_index) bedtemp = ui.material_preset[preset_index - 1].bed_temp; #endif // Look for 'B' Bed Temperature if (parser.seenval('B')) bedtemp = parser.value_celsius(); if (bedtemp) { if (!WITHIN(bedtemp, 40, BED_MAX_TARGET)) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Specified bed temperature not plausible (40-", BED_MAX_TARGET, "C).")); return; } g26.bed_temp = bedtemp; } #endif // HAS_HEATED_BED if (parser.seenval('L')) { g26.layer_height = parser.value_linear_units(); if (!WITHIN(g26.layer_height, 0.0, 2.0)) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Specified layer height not plausible.")); return; } } if (parser.seen('Q')) { if (parser.has_value()) { g26.retraction_multiplier = parser.value_float(); if (!WITHIN(g26.retraction_multiplier, 0.05, 15.0)) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Specified Retraction Multiplier not plausible.")); return; } } else { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Retraction Multiplier must be specified.")); return; } } if (parser.seenval('S')) { g26.nozzle = parser.value_float(); if (!WITHIN(g26.nozzle, 0.1, 2.0)) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Specified nozzle size not plausible.")); return; } } if (parser.seen('P')) { if (!parser.has_value()) { #if HAS_MARLINUI_MENU g26.prime_flag = -1; #else SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Prime length must be specified when not using an LCD.")); return; #endif } else { g26.prime_flag++; g26.prime_length = parser.value_linear_units(); if (!WITHIN(g26.prime_length, 0.0, 25.0)) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Specified prime length not plausible.")); return; } } } if (parser.seenval('F')) { g26.filament_diameter = parser.value_linear_units(); if (!WITHIN(g26.filament_diameter, 1.0, 4.0)) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Specified filament size not plausible.")); return; } } g26.extrusion_multiplier *= sq(1.75) / sq(g26.filament_diameter); // If we aren't using 1.75mm filament, we need to // scale up or down the length needed to get the // same volume of filament g26.extrusion_multiplier *= g26.filament_diameter * sq(g26.nozzle) / sq(0.3); // Scale up by nozzle size // Get a temperature from 'I' or 'H' celsius_t noztemp = 0; // Accept 'I' if temperature presets are defined #if HAS_PREHEAT if (preset_index) noztemp = ui.material_preset[preset_index - 1].hotend_temp; #endif // Look for 'H' Hotend Temperature if (parser.seenval('H')) noztemp = parser.value_celsius(); // If any preset or temperature was specified if (noztemp) { if (!WITHIN(noztemp, 165, thermalManager.hotend_max_target(active_extruder))) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Specified nozzle temperature not plausible.")); return; } g26.hotend_temp = noztemp; } // 'U' to Randomize and optionally set circle deviation if (parser.seen('U')) { randomSeed(millis()); // This setting will persist for the next G26 g26_random_deviation = parser.has_value() ? parser.value_float() : 50.0; } // Get repeat from 'R', otherwise do one full circuit grid_count_t g26_repeats; #if HAS_MARLINUI_MENU g26_repeats = parser.intval('R', GRID_MAX_POINTS + 1); #else if (parser.seen('R')) g26_repeats = parser.has_value() ? parser.value_int() : GRID_MAX_POINTS + 1; else { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("(R)epeat must be specified when not using an LCD.")); return; } #endif if (g26_repeats < 1) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("(R)epeat value not plausible; must be at least 1.")); return; } // Set a position with 'X' and/or 'Y'. Default: current_position g26.xy_pos.set(parser.seenval('X') ? RAW_X_POSITION(parser.value_linear_units()) : current_position.x, parser.seenval('Y') ? RAW_Y_POSITION(parser.value_linear_units()) : current_position.y); if (!position_is_reachable(g26.xy_pos)) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Specified X,Y coordinate out of bounds.")); return; } /** * Wait until all parameters are verified before altering the state! */ set_bed_leveling_enabled(!parser.seen_test('D')); do_z_clearance(Z_CLEARANCE_BETWEEN_PROBES); #if DISABLED(NO_VOLUMETRICS) bool volumetric_was_enabled = parser.volumetric_enabled; parser.volumetric_enabled = false; planner.calculate_volumetric_multipliers(); #endif if (g26.turn_on_heaters() != G26_OK) goto LEAVE; current_position.e = 0.0; sync_plan_position_e(); if (g26.prime_flag && g26.prime_nozzle() != G26_OK) goto LEAVE; /** * Bed is preheated * * Nozzle is at temperature * * Filament is primed! * * It's "Show Time" !!! */ circle_flags.reset(); // Move nozzle to the specified height for the first layer destination = current_position; destination.z = g26.layer_height; move_to(destination, 0.0); move_to(destination, g26.ooze_amount); TERN_(HAS_MARLINUI_MENU, ui.capture()); #if DISABLED(ARC_SUPPORT) /** * Pre-generate radius offset values at 30 degree intervals to reduce CPU load. */ #define A_INT 30 #define _ANGS (360 / A_INT) #define A_CNT (_ANGS / 2) #define _IND(A) ((A + _ANGS * 8) % _ANGS) #define _COS(A) (trig_table[_IND(A) % A_CNT] * (_IND(A) >= A_CNT ? -1 : 1)) #define _SIN(A) (-_COS((A + A_CNT / 2) % _ANGS)) #if A_CNT & 1 #error "A_CNT must be a positive value. Please change A_INT." #endif float trig_table[A_CNT]; for (uint8_t i = 0; i < A_CNT; ++i) trig_table[i] = INTERSECTION_CIRCLE_RADIUS * cos(RADIANS(i * A_INT)); #endif // !ARC_SUPPORT mesh_index_pair location; TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location.pos, ExtUI::G26_START)); do { // Find the nearest confluence location = g26.find_closest_circle_to_print(g26.continue_with_closest ? xy_pos_t(current_position) : g26.xy_pos); if (location.valid()) { TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location.pos, ExtUI::G26_POINT_START)); const xy_pos_t circle = { bedlevel.get_mesh_x(location.pos.a), bedlevel.get_mesh_y(location.pos.b) }; // If this mesh location is outside the printable radius, skip it. if (!position_is_reachable(circle)) continue; // Determine where to start and end the circle, // which is always drawn counter-clockwise. const xy_int8_t st = location; const bool f = st.y == 0, r = st.x >= (GRID_MAX_POINTS_X) - 1, b = st.y >= (GRID_MAX_POINTS_Y) - 1; #if ENABLED(ARC_SUPPORT) #define ARC_LENGTH(quarters) (INTERSECTION_CIRCLE_RADIUS * M_PI * (quarters) / 2) #define INTERSECTION_CIRCLE_DIAM ((INTERSECTION_CIRCLE_RADIUS) * 2) xy_float_t e = { circle.x + INTERSECTION_CIRCLE_RADIUS, circle.y }; xyz_float_t s = e; // Figure out where to start and end the arc - we always print counterclockwise float arc_length = ARC_LENGTH(4); if (st.x == 0) { // left edge if (!f) { s.x = circle.x; s.y -= INTERSECTION_CIRCLE_RADIUS; } if (!b) { e.x = circle.x; e.y += INTERSECTION_CIRCLE_RADIUS; } arc_length = (f || b) ? ARC_LENGTH(1) : ARC_LENGTH(2); } else if (r) { // right edge if (b) s.set(circle.x - (INTERSECTION_CIRCLE_RADIUS), circle.y); else s.set(circle.x, circle.y + INTERSECTION_CIRCLE_RADIUS); if (f) e.set(circle.x - (INTERSECTION_CIRCLE_RADIUS), circle.y); else e.set(circle.x, circle.y - (INTERSECTION_CIRCLE_RADIUS)); arc_length = (f || b) ? ARC_LENGTH(1) : ARC_LENGTH(2); } else if (f) { e.x -= INTERSECTION_CIRCLE_DIAM; arc_length = ARC_LENGTH(2); } else if (b) { s.x -= INTERSECTION_CIRCLE_DIAM; arc_length = ARC_LENGTH(2); } const ab_float_t arc_offset = circle - s; const xy_float_t dist = current_position - s; // Distance from the start of the actual circle const float dist_start = HYPOT2(dist.x, dist.y); const xyze_pos_t endpoint = { e.x, e.y, g26.layer_height, current_position.e + (arc_length * g26_e_axis_feedrate * g26.extrusion_multiplier) }; if (dist_start > 2.0) { s.z = g26.layer_height + 0.5f; g26.retract_lift_move(s); } s.z = g26.layer_height; move_to(s, 0.0); // Get to the starting point with no extrusion / un-Z lift g26.recover_filament(destination); { REMEMBER(fr, feedrate_mm_s, PLANNER_XY_FEEDRATE() * 0.1f); plan_arc(endpoint, arc_offset, false, 0); // Draw a counter-clockwise arc destination = current_position; } if (TERN0(HAS_MARLINUI_MENU, user_canceled())) goto LEAVE; // Check if the user wants to stop the Mesh Validation #else // !ARC_SUPPORT int8_t start_ind = -2, end_ind = 9; // Assume a full circle (from 5:00 to 5:00) if (st.x == 0) { // Left edge? Just right half. start_ind = f ? 0 : -3; // 03:00 to 12:00 for front-left end_ind = b ? 0 : 2; // 06:00 to 03:00 for back-left } else if (r) { // Right edge? Just left half. start_ind = b ? 6 : 3; // 12:00 to 09:00 for front-right end_ind = f ? 5 : 8; // 09:00 to 06:00 for back-right } else if (f) { // Front edge? Just back half. start_ind = 0; // 03:00 end_ind = 5; // 09:00 } else if (b) { // Back edge? Just front half. start_ind = 6; // 09:00 end_ind = 11; // 03:00 } for (int8_t ind = start_ind; ind <= end_ind; ind++) { if (TERN0(HAS_MARLINUI_MENU, user_canceled())) goto LEAVE; // Check if the user wants to stop the Mesh Validation xyz_float_t p = { circle.x + _COS(ind ), circle.y + _SIN(ind ), g26.layer_height }, q = { circle.x + _COS(ind + 1), circle.y + _SIN(ind + 1), g26.layer_height }; #if IS_KINEMATIC // Check to make sure this segment is entirely on the bed, skip if not. if (!position_is_reachable(p) || !position_is_reachable(q)) continue; #elif HAS_ENDSTOPS LIMIT(p.x, X_MIN_POS + 1, X_MAX_POS - 1); // Prevent hitting the endstops LIMIT(p.y, Y_MIN_POS + 1, Y_MAX_POS - 1); LIMIT(q.x, X_MIN_POS + 1, X_MAX_POS - 1); LIMIT(q.y, Y_MIN_POS + 1, Y_MAX_POS - 1); #endif g26.print_line_from_here_to_there(p, q); SERIAL_FLUSH(); // Prevent host M105 buffer overrun. } #endif // !ARC_SUPPORT g26.connect_neighbor_with_line(location.pos, -1, 0); g26.connect_neighbor_with_line(location.pos, 1, 0); g26.connect_neighbor_with_line(location.pos, 0, -1); g26.connect_neighbor_with_line(location.pos, 0, 1); planner.synchronize(); TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location.pos, ExtUI::G26_POINT_FINISH)); if (TERN0(HAS_MARLINUI_MENU, user_canceled())) goto LEAVE; } SERIAL_FLUSH(); // Prevent host M105 buffer overrun. } while (--g26_repeats && location.valid()); LEAVE: LCD_MESSAGE_MIN(MSG_G26_LEAVING); TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(location, ExtUI::G26_FINISH)); g26.retract_filament(destination); destination.z = Z_CLEARANCE_BETWEEN_PROBES; move_to(destination, 0); // Raise the nozzle #if DISABLED(NO_VOLUMETRICS) parser.volumetric_enabled = volumetric_was_enabled; planner.calculate_volumetric_multipliers(); #endif TERN_(HAS_MARLINUI_MENU, ui.release()); // Give back control of the LCD if (!g26.keep_heaters_on) { TERN_(HAS_HEATED_BED, thermalManager.setTargetBed(0)); thermalManager.setTargetHotend(active_extruder, 0); } } #endif // G26_MESH_VALIDATION
2301_81045437/Marlin
Marlin/src/gcode/bedlevel/G26.cpp
C++
agpl-3.0
32,743
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../../inc/MarlinConfig.h" #if ENABLED(ASSISTED_TRAMMING) #include "../gcode.h" #include "../../module/planner.h" #include "../../module/probe.h" #include "../../feature/bedlevel/bedlevel.h" #if ENABLED(BLTOUCH) #include "../../feature/bltouch.h" #endif #define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) #include "../../core/debug_out.h" // // Define tramming point names. // #include "../../feature/tramming.h" /** * G35: Read bed corners to help adjust bed screws * * S<screw_thread> * * Screw thread: 30 - Clockwise M3 * 31 - Counter-Clockwise M3 * 40 - Clockwise M4 * 41 - Counter-Clockwise M4 * 50 - Clockwise M5 * 51 - Counter-Clockwise M5 **/ void GcodeSuite::G35() { DEBUG_SECTION(log_G35, "G35", DEBUGGING(LEVELING)); if (DEBUGGING(LEVELING)) log_machine_info(); float z_measured[G35_PROBE_COUNT] = { 0 }; const uint8_t screw_thread = parser.byteval('S', TRAMMING_SCREW_THREAD); if (!WITHIN(screw_thread, 30, 51) || screw_thread % 10 > 1) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("(S)crew thread must be 30, 31, 40, 41, 50, or 51.")); return; } // Wait for planner moves to finish! planner.synchronize(); // Disable the leveling matrix before auto-aligning #if HAS_LEVELING #if ENABLED(RESTORE_LEVELING_AFTER_G35) const bool leveling_was_active = planner.leveling_active; #endif set_bed_leveling_enabled(false); #endif TERN_(CNC_WORKSPACE_PLANES, workspace_plane = PLANE_XY); probe.use_probing_tool(); // Disable duplication mode on homing TERN_(HAS_DUPLICATION_MODE, set_duplication_enabled(false)); // Home only Z axis when X and Y is trusted, otherwise all axes, if needed before this procedure if (!all_axes_trusted()) process_subcommands_now(F("G28Z")); bool err_break = false; // Probe all positions for (uint8_t i = 0; i < G35_PROBE_COUNT; ++i) { const float z_probed_height = probe.probe_at_point(tramming_points[i], PROBE_PT_RAISE); if (isnan(z_probed_height)) { SERIAL_ECHOLN( F("G35 failed at point "), i + 1, F(" ("), FPSTR(pgm_read_ptr(&tramming_point_name[i])), C(')'), FPSTR(SP_X_STR), tramming_points[i].x, FPSTR(SP_Y_STR), tramming_points[i].y ); err_break = true; break; } if (DEBUGGING(LEVELING)) { DEBUG_ECHOLN( F("Probing point "), i + 1, F(" ("), FPSTR(pgm_read_ptr(&tramming_point_name[i])), C(')'), FPSTR(SP_X_STR), tramming_points[i].x, FPSTR(SP_Y_STR), tramming_points[i].y, FPSTR(SP_Z_STR), z_probed_height ); } z_measured[i] = z_probed_height; } if (!err_break) { const float threads_factor[] = { 0.5, 0.7, 0.8 }; // Calculate adjusts for (uint8_t i = 1; i < G35_PROBE_COUNT; ++i) { const float diff = z_measured[0] - z_measured[i], adjust = ABS(diff) < 0.001f ? 0 : diff / threads_factor[(screw_thread - 30) / 10]; const int full_turns = trunc(adjust); const float decimal_part = adjust - float(full_turns); const int minutes = trunc(decimal_part * 60.0f); SERIAL_ECHOPGM("Turn "); SERIAL_ECHOPGM_P((char *)pgm_read_ptr(&tramming_point_name[i])); SERIAL_ECHOPGM(" ", (screw_thread & 1) == (adjust > 0) ? "CCW" : "CW", " by ", ABS(full_turns), " turns"); if (minutes) SERIAL_ECHOPGM(" and ", ABS(minutes), " minutes"); if (ENABLED(REPORT_TRAMMING_MM)) SERIAL_ECHOPGM(" (", -diff, "mm)"); SERIAL_EOL(); } } else SERIAL_ECHOLNPGM("G35 aborted."); // Restore the active tool after homing probe.use_probing_tool(false); #if ALL(HAS_LEVELING, RESTORE_LEVELING_AFTER_G35) set_bed_leveling_enabled(leveling_was_active); #endif // Stow the probe, as the last call to probe.probe_at_point(...) left // the probe deployed if it was successful. probe.stow(); move_to_tramming_wait_pos(); // After this operation the Z position needs correction set_axis_never_homed(Z_AXIS); } #endif // ASSISTED_TRAMMING
2301_81045437/Marlin
Marlin/src/gcode/bedlevel/G35.cpp
C++
agpl-3.0
4,922
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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_MESH #include "../gcode.h" #include "../../MarlinCore.h" // for IsRunning() #include "../../module/motion.h" #include "../../module/probe.h" // for probe.offset #include "../../feature/bedlevel/bedlevel.h" /** * G42: Move X & Y axes to mesh coordinates (I & J) */ void GcodeSuite::G42() { if (MOTION_CONDITIONS) { const bool hasI = parser.seenval('I'); const int8_t ix = hasI ? parser.value_int() : 0; const bool hasJ = parser.seenval('J'); const int8_t iy = hasJ ? parser.value_int() : 0; if ((hasI && !WITHIN(ix, 0, GRID_MAX_POINTS_X - 1)) || (hasJ && !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1))) { SERIAL_ECHOLNPGM(STR_ERR_MESH_XY); return; } // Move to current_position, as modified by I, J, P parameters destination = current_position; if (hasI) destination.x = bedlevel.get_mesh_x(ix); if (hasJ) destination.y = bedlevel.get_mesh_y(iy); #if HAS_PROBE_XY_OFFSET if (parser.boolval('P')) { if (hasI) destination.x -= probe.offset_xy.x; if (hasJ) destination.y -= probe.offset_xy.y; } #endif const feedRate_t fval = parser.linearval('F'), fr_mm_s = MMM_TO_MMS(fval > 0 ? fval : 0.0f); // SCARA kinematic has "safe" XY raw moves #if IS_SCARA prepare_internal_fast_move_to_destination(fr_mm_s); #else prepare_internal_move_to_destination(fr_mm_s); #endif } } #endif // HAS_MESH
2301_81045437/Marlin
Marlin/src/gcode/bedlevel/G42.cpp
C++
agpl-3.0
2,338
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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 "../gcode.h" #include "../../feature/bedlevel/bedlevel.h" #include "../../module/planner.h" #include "../../module/probe.h" #if ENABLED(EEPROM_SETTINGS) #include "../../module/settings.h" #endif #if ENABLED(EXTENSIBLE_UI) #include "../../lcd/extui/ui_api.h" #endif //#define M420_C_USE_MEAN /** * M420: Enable/Disable Bed Leveling and/or set the Z fade height. * * S[bool] Turns leveling on or off * Z[height] Sets the Z fade height (0 or none to disable) * V[bool] Verbose - Print the leveling grid * * With AUTO_BED_LEVELING_UBL only: * * L[index] Load UBL mesh from index (0 is default) * T[map] 0:Human-readable 1:CSV 2:"LCD" 4:Compact * * With mesh-based leveling only: * * C Center mesh on the mean of the lowest and highest * * With MARLIN_DEV_MODE: * S2 Create a simple random mesh and enable */ void GcodeSuite::M420() { const bool seen_S = parser.seen('S'), to_enable = seen_S ? parser.value_bool() : planner.leveling_active; #if ENABLED(MARLIN_DEV_MODE) if (parser.intval('S') == 2) { const float x_min = probe.min_x(), x_max = probe.max_x(), y_min = probe.min_y(), y_max = probe.max_y(); #if ENABLED(AUTO_BED_LEVELING_BILINEAR) xy_pos_t start, spacing; start.set(x_min, y_min); spacing.set((x_max - x_min) / (GRID_MAX_CELLS_X), (y_max - y_min) / (GRID_MAX_CELLS_Y)); bedlevel.set_grid(spacing, start); #endif GRID_LOOP(x, y) { bedlevel.z_values[x][y] = 0.001 * random(-200, 200); TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, bedlevel.z_values[x][y])); } TERN_(AUTO_BED_LEVELING_BILINEAR, bedlevel.refresh_bed_level()); SERIAL_ECHOPGM("Simulated " STRINGIFY(GRID_MAX_POINTS_X) "x" STRINGIFY(GRID_MAX_POINTS_Y) " mesh "); SERIAL_ECHOPGM(" (", x_min); SERIAL_CHAR(','); SERIAL_ECHO(y_min); SERIAL_ECHOPGM(")-(", x_max); SERIAL_CHAR(','); SERIAL_ECHO(y_max); SERIAL_ECHOLNPGM(")"); } #endif xyz_pos_t oldpos = current_position; // If disabling leveling do it right away // (Don't disable for just M420 or M420 V) if (seen_S && !to_enable) set_bed_leveling_enabled(false); #if ENABLED(AUTO_BED_LEVELING_UBL) // L to load a mesh from the EEPROM if (parser.seen('L')) { set_bed_leveling_enabled(false); #if ENABLED(EEPROM_SETTINGS) const int8_t storage_slot = parser.has_value() ? parser.value_int() : bedlevel.storage_slot; const int16_t a = settings.calc_num_meshes(); if (!a) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("EEPROM storage not available.")); return; } if (!WITHIN(storage_slot, 0, a - 1)) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Invalid storage slot. Use 0 to ", a - 1)); return; } settings.load_mesh(storage_slot); bedlevel.storage_slot = storage_slot; #else SERIAL_ECHOLNPGM(GCODE_ERR_MSG("EEPROM storage not available.")); return; #endif } // L or V display the map info if (parser.seen("LV")) { bedlevel.display_map(parser.byteval('T')); SERIAL_ECHOPGM("Mesh is "); if (!bedlevel.mesh_is_valid()) SERIAL_ECHOPGM("in"); SERIAL_ECHOLNPGM("valid\nStorage slot: ", bedlevel.storage_slot); } #endif // AUTO_BED_LEVELING_UBL const bool seenV = parser.seen_test('V'); #if HAS_MESH if (leveling_is_valid()) { // Subtract the given value or the mean from all mesh values if (parser.seen('C')) { const float cval = parser.value_float(); #if ENABLED(AUTO_BED_LEVELING_UBL) set_bed_leveling_enabled(false); bedlevel.adjust_mesh_to_mean(true, cval); #else #if ENABLED(M420_C_USE_MEAN) // Get the sum and average of all mesh values float mesh_sum = 0; GRID_LOOP(x, y) mesh_sum += bedlevel.z_values[x][y]; const float zmean = mesh_sum / float(GRID_MAX_POINTS); #else // midrange // Find the low and high mesh values. float lo_val = 100, hi_val = -100; GRID_LOOP(x, y) { const float z = bedlevel.z_values[x][y]; NOMORE(lo_val, z); NOLESS(hi_val, z); } // Get the midrange plus C value. (The median may be better.) const float zmean = (lo_val + hi_val) / 2.0 + cval; #endif // If not very close to 0, adjust the mesh if (!NEAR_ZERO(zmean)) { set_bed_leveling_enabled(false); // Subtract the mean from all values GRID_LOOP(x, y) { bedlevel.z_values[x][y] -= zmean; TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, bedlevel.z_values[x][y])); } TERN_(AUTO_BED_LEVELING_BILINEAR, bedlevel.refresh_bed_level()); } #endif } } else if (to_enable || seenV) { SERIAL_ECHO_MSG("Invalid mesh."); goto EXIT_M420; } #endif // HAS_MESH // V to print the matrix or mesh if (seenV) { #if ABL_PLANAR planner.bed_level_matrix.debug(F("Bed Level Correction Matrix:")); #else if (leveling_is_valid()) { #if ENABLED(AUTO_BED_LEVELING_BILINEAR) bedlevel.print_leveling_grid(); #elif ENABLED(MESH_BED_LEVELING) SERIAL_ECHOLNPGM("Mesh Bed Level data:"); bedlevel.report_mesh(); #endif } #endif } #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) if (parser.seen('Z')) set_z_fade_height(parser.value_linear_units(), false); #endif // Enable leveling if specified, or if previously active set_bed_leveling_enabled(to_enable); #if HAS_MESH EXIT_M420: #endif // Error if leveling failed to enable or reenable if (to_enable && !planner.leveling_active) SERIAL_ERROR_MSG(STR_ERR_M420_FAILED); SERIAL_ECHO_START(); SERIAL_ECHOPGM("Bed Leveling "); serialprintln_onoff(planner.leveling_active); #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) SERIAL_ECHO_START(); SERIAL_ECHOPGM("Fade Height "); if (planner.z_fade_height > 0.0) SERIAL_ECHOLN(planner.z_fade_height); else SERIAL_ECHOLNPGM(STR_OFF); #endif // Report change in position if (oldpos != current_position) report_current_position(); } void GcodeSuite::M420_report(const bool forReplay/*=true*/) { TERN_(MARLIN_SMALL_BUILD, return); report_heading_etc(forReplay, F( TERN(MESH_BED_LEVELING, "Mesh Bed Leveling", TERN(AUTO_BED_LEVELING_UBL, "Unified Bed Leveling", "Auto Bed Leveling")) )); SERIAL_ECHO( F(" M420 S"), planner.leveling_active #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) , FPSTR(SP_Z_STR), LINEAR_UNIT(planner.z_fade_height) #endif , F(" ; Leveling ") ); serialprintln_onoff(planner.leveling_active); } #endif // HAS_LEVELING
2301_81045437/Marlin
Marlin/src/gcode/bedlevel/M420.cpp
C++
agpl-3.0
7,876
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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/>. * */ /** * G29.cpp - Auto Bed Leveling */ #include "../../../inc/MarlinConfig.h" #if HAS_ABL_NOT_UBL #include "../../gcode.h" #include "../../../feature/bedlevel/bedlevel.h" #include "../../../module/motion.h" #include "../../../module/planner.h" #include "../../../module/probe.h" #include "../../queue.h" #if ENABLED(AUTO_BED_LEVELING_LINEAR) #include "../../../libs/least_squares_fit.h" #endif #if ABL_PLANAR #include "../../../libs/vector_3.h" #endif #if ENABLED(BD_SENSOR_PROBE_NO_STOP) #include "../../../feature/bedlevel/bdl/bdl.h" #endif #include "../../../lcd/marlinui.h" #if ENABLED(EXTENSIBLE_UI) #include "../../../lcd/extui/ui_api.h" #elif ENABLED(DWIN_CREALITY_LCD) #include "../../../lcd/e3v2/creality/dwin.h" #endif #define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) #include "../../../core/debug_out.h" #if ABL_USES_GRID #if ENABLED(PROBE_Y_FIRST) #define PR_OUTER_VAR abl.meshCount.x #define PR_OUTER_SIZE abl.grid_points.x #define PR_INNER_VAR abl.meshCount.y #define PR_INNER_SIZE abl.grid_points.y #else #define PR_OUTER_VAR abl.meshCount.y #define PR_OUTER_SIZE abl.grid_points.y #define PR_INNER_VAR abl.meshCount.x #define PR_INNER_SIZE abl.grid_points.x #endif #endif static void pre_g29_return(const bool retry, const bool did) { if (!retry) { TERN_(FULL_REPORT_TO_HOST_FEATURE, set_and_report_grblstate(M_IDLE, false)); } if (did) { TERN_(DWIN_CREALITY_LCD, dwinLevelingDone()); TERN_(EXTENSIBLE_UI, ExtUI::onLevelingDone()); } } #define G29_RETURN(retry, did) do{ \ pre_g29_return(TERN0(G29_RETRY_AND_RECOVER, retry), did); \ return TERN_(G29_RETRY_AND_RECOVER, retry); \ }while(0) // For manual probing values persist over multiple G29 class G29_State { public: int verbose_level; xy_pos_t probePos; float measured_z; bool dryrun, reenable; #if ANY(PROBE_MANUALLY, AUTO_BED_LEVELING_LINEAR) int abl_probe_index; #endif #if ENABLED(AUTO_BED_LEVELING_LINEAR) grid_count_t abl_points; #elif ENABLED(AUTO_BED_LEVELING_3POINT) static constexpr grid_count_t abl_points = 3; #elif ABL_USES_GRID static constexpr grid_count_t abl_points = GRID_MAX_POINTS; #endif #if ABL_USES_GRID xy_int8_t meshCount; xy_pos_t probe_position_lf, probe_position_rb; xy_float_t gridSpacing; // = { 0.0f, 0.0f } #if ENABLED(AUTO_BED_LEVELING_LINEAR) bool topography_map; xy_uint8_t grid_points; #else // Bilinear static constexpr xy_uint8_t grid_points = { GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y }; #endif #if ENABLED(AUTO_BED_LEVELING_BILINEAR) float Z_offset; bed_mesh_t z_values; #endif #if ENABLED(AUTO_BED_LEVELING_LINEAR) int indexIntoAB[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y]; float eqnAMatrix[GRID_MAX_POINTS * 3], // "A" matrix of the linear system of equations eqnBVector[GRID_MAX_POINTS], // "B" vector of Z points mean; #endif #endif }; #if ABL_USES_GRID && ANY(AUTO_BED_LEVELING_3POINT, AUTO_BED_LEVELING_BILINEAR) constexpr xy_uint8_t G29_State::grid_points; constexpr grid_count_t G29_State::abl_points; #endif /** * G29: Detailed Z probe, probes the bed at 3 or more points. * Will fail if the printer has not been homed with G28. * * Enhanced G29 Auto Bed Leveling Probe Routine * * O Auto-level only if needed * * D Dry-Run mode. Just evaluate the bed Topology - Don't apply * or alter the bed level data. Useful to check the topology * after a first run of G29. * * J Jettison current bed leveling data * * V Set the verbose level (0-4). Example: "G29 V3" * * Parameters With LINEAR leveling only: * * P Set the size of the grid that will be probed (P x P points). * Example: "G29 P4" * * X Set the X size of the grid that will be probed (X x Y points). * Example: "G29 X7 Y5" * * Y Set the Y size of the grid that will be probed (X x Y points). * * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report. * This is useful for manual bed leveling and finding flaws in the bed (to * assist with part placement). * Not supported by non-linear delta printer bed leveling. * * Parameters With LINEAR and BILINEAR leveling only: * * S Set the XY travel speed between probe points (in units/min) * * H Set bounds to a centered square H x H units in size * * -or- * * F Set the Front limit of the probing grid * B Set the Back limit of the probing grid * L Set the Left limit of the probing grid * R Set the Right limit of the probing grid * * Parameters with DEBUG_LEVELING_FEATURE only: * * C Make a totally fake grid with no actual probing. * For use in testing when no probing is possible. * * Parameters with BILINEAR leveling only: * * Z Supply an additional Z probe offset * * Extra parameters with PROBE_MANUALLY: * * To do manual probing simply repeat G29 until the procedure is complete. * The first G29 accepts parameters. 'G29 Q' for status, 'G29 A' to abort. * * Q Query leveling and G29 state * * A Abort current leveling procedure * * Extra parameters with BILINEAR only: * * W Write a mesh point. (If G29 is idle.) * I X index for mesh point * J Y index for mesh point * X X for mesh point, overrides I * Y Y for mesh point, overrides J * Z Z for mesh point. Otherwise, raw current Z. * * Without PROBE_MANUALLY: * * E By default G29 will engage the Z probe, test the bed, then disengage. * Include "E" to engage/disengage the Z probe for each sample. * There's no extra effect if you have a fixed Z probe. */ G29_TYPE GcodeSuite::G29() { DEBUG_SECTION(log_G29, "G29", DEBUGGING(LEVELING)); // Leveling state is persistent when done manually with multiple G29 commands TERN_(PROBE_MANUALLY, static) G29_State abl; // Keep powered steppers from timing out reset_stepper_timeout(); // Q = Query leveling and G29 state const bool seenQ = ANY(DEBUG_LEVELING_FEATURE, PROBE_MANUALLY) && parser.seen_test('Q'); // G29 Q is also available if debugging #if ENABLED(DEBUG_LEVELING_FEATURE) if (seenQ || DEBUGGING(LEVELING)) log_machine_info(); if (DISABLED(PROBE_MANUALLY) && seenQ) G29_RETURN(false, false); #endif // A = Abort manual probing // C<bool> = Generate fake probe points (DEBUG_LEVELING_FEATURE) const bool seenA = TERN0(PROBE_MANUALLY, parser.seen_test('A')), no_action = seenA || seenQ, faux = ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(PROBE_MANUALLY) ? parser.boolval('C') : no_action; // O = Don't level if leveling is already active if (!no_action && planner.leveling_active && parser.boolval('O')) { if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("> Auto-level not needed, skip"); G29_RETURN(false, false); } // Send 'N' to force homing before G29 (internal only) if (parser.seen_test('N')) process_subcommands_now(TERN(CAN_SET_LEVELING_AFTER_G28, F("G28L0"), FPSTR(G28_STR))); // Don't allow auto-leveling without homing first if (homing_needed_error()) G29_RETURN(false, false); // 3-point leveling gets points from the probe class #if ENABLED(AUTO_BED_LEVELING_3POINT) vector_3 points[3]; probe.get_three_points(points); #endif // Storage for ABL Linear results #if ENABLED(AUTO_BED_LEVELING_LINEAR) struct linear_fit_data lsf_results; #endif // Set and report "probing" state to host TERN_(FULL_REPORT_TO_HOST_FEATURE, set_and_report_grblstate(M_PROBE, false)); /** * On the initial G29 fetch command parameters. */ if (!g29_in_progress) { probe.use_probing_tool(); #if ANY(PROBE_MANUALLY, AUTO_BED_LEVELING_LINEAR) abl.abl_probe_index = -1; #endif abl.reenable = planner.leveling_active; #if ENABLED(AUTO_BED_LEVELING_BILINEAR) const bool seen_w = parser.seen_test('W'); if (seen_w) { if (!leveling_is_valid()) { SERIAL_ERROR_MSG("No bilinear grid"); G29_RETURN(false, false); } const float rz = parser.seenval('Z') ? RAW_Z_POSITION(parser.value_linear_units()) : current_position.z; if (!WITHIN(rz, -10, 10)) { SERIAL_ERROR_MSG("Bad Z value"); G29_RETURN(false, false); } const float rx = RAW_X_POSITION(parser.linearval('X', NAN)), ry = RAW_Y_POSITION(parser.linearval('Y', NAN)); int8_t i = parser.byteval('I', -1), j = parser.byteval('J', -1); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" if (!isnan(rx) && !isnan(ry)) { // Get nearest i / j from rx / ry i = (rx - bedlevel.grid_start.x) / bedlevel.grid_spacing.x + 0.5f; j = (ry - bedlevel.grid_start.y) / bedlevel.grid_spacing.y + 0.5f; LIMIT(i, 0, (GRID_MAX_POINTS_X) - 1); LIMIT(j, 0, (GRID_MAX_POINTS_Y) - 1); } #pragma GCC diagnostic pop if (WITHIN(i, 0, (GRID_MAX_POINTS_X) - 1) && WITHIN(j, 0, (GRID_MAX_POINTS_Y) - 1)) { set_bed_leveling_enabled(false); bedlevel.z_values[i][j] = rz; bedlevel.refresh_bed_level(); TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(i, j, rz)); if (abl.reenable) { set_bed_leveling_enabled(true); report_current_position(); } } G29_RETURN(false, false); } // parser.seen_test('W') #else constexpr bool seen_w = false; #endif // Jettison bed leveling data if (!seen_w && parser.seen_test('J')) { reset_bed_level(); G29_RETURN(false, false); } abl.verbose_level = parser.intval('V'); if (!WITHIN(abl.verbose_level, 0, 4)) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("(V)erbose level implausible (0-4).")); G29_RETURN(false, false); } abl.dryrun = parser.boolval('D') || TERN0(PROBE_MANUALLY, no_action); #if ENABLED(AUTO_BED_LEVELING_LINEAR) incremental_LSF_reset(&lsf_results); abl.topography_map = abl.verbose_level > 2 || parser.boolval('T'); // X and Y specify points in each direction, overriding the default // These values may be saved with the completed mesh abl.grid_points.set( parser.byteval('X', GRID_MAX_POINTS_X), parser.byteval('Y', GRID_MAX_POINTS_Y) ); if (parser.seenval('P')) abl.grid_points.x = abl.grid_points.y = parser.value_int(); if (!WITHIN(abl.grid_points.x, 2, GRID_MAX_POINTS_X)) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Probe points (X) implausible (2-" STRINGIFY(GRID_MAX_POINTS_X) ").")); G29_RETURN(false, false); } if (!WITHIN(abl.grid_points.y, 2, GRID_MAX_POINTS_Y)) { SERIAL_ECHOLNPGM(GCODE_ERR_MSG("Probe points (Y) implausible (2-" STRINGIFY(GRID_MAX_POINTS_Y) ").")); G29_RETURN(false, false); } abl.abl_points = abl.grid_points.x * abl.grid_points.y; abl.mean = 0; #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) abl.Z_offset = parser.linearval('Z'); #endif #if ABL_USES_GRID xy_probe_feedrate_mm_s = MMM_TO_MMS(parser.linearval('S', XY_PROBE_FEEDRATE)); const float x_min = probe.min_x(), x_max = probe.max_x(), y_min = probe.min_y(), y_max = probe.max_y(); if (parser.seen('H')) { const int16_t size = (int16_t)parser.value_linear_units(); abl.probe_position_lf.set(_MAX((X_CENTER) - size / 2, x_min), _MAX((Y_CENTER) - size / 2, y_min)); abl.probe_position_rb.set(_MIN(abl.probe_position_lf.x + size, x_max), _MIN(abl.probe_position_lf.y + size, y_max)); } else { abl.probe_position_lf.set(parser.linearval('L', x_min), parser.linearval('F', y_min)); abl.probe_position_rb.set(parser.linearval('R', x_max), parser.linearval('B', y_max)); } if (!probe.good_bounds(abl.probe_position_lf, abl.probe_position_rb)) { if (DEBUGGING(LEVELING)) { DEBUG_ECHOLNPGM("G29 L", abl.probe_position_lf.x, " R", abl.probe_position_rb.x, " F", abl.probe_position_lf.y, " B", abl.probe_position_rb.y); } SERIAL_ECHOLNPGM(GCODE_ERR_MSG(" (L,R,F,B) out of bounds.")); G29_RETURN(false, false); } // Probe at the points of a lattice grid abl.gridSpacing.set((abl.probe_position_rb.x - abl.probe_position_lf.x) / (abl.grid_points.x - 1), (abl.probe_position_rb.y - abl.probe_position_lf.y) / (abl.grid_points.y - 1)); #endif // ABL_USES_GRID if (abl.verbose_level > 0) { SERIAL_ECHOPGM("G29 Auto Bed Leveling"); if (abl.dryrun) SERIAL_ECHOPGM(" (DRYRUN)"); SERIAL_EOL(); } planner.synchronize(); #if ENABLED(AUTO_BED_LEVELING_3POINT) if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("> 3-point Leveling"); points[0].z = points[1].z = points[2].z = 0; // Probe at 3 arbitrary points #endif TERN_(EXTENSIBLE_UI, ExtUI::onLevelingStart()); if (!faux) { remember_feedrate_scaling_off(); #if ENABLED(PREHEAT_BEFORE_LEVELING) if (!abl.dryrun) probe.preheat_for_probing(LEVELING_NOZZLE_TEMP, TERN(EXTENSIBLE_UI, ExtUI::getLevelingBedTemp(), LEVELING_BED_TEMP) ); #endif } // 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 // Disable auto bed leveling during G29. // Be formal so G29 can be done successively without G28. if (!no_action) set_bed_leveling_enabled(false); // Deploy certain probes before starting probing #if ENABLED(BLTOUCH) || ALL(HAS_Z_SERVO_PROBE, Z_SERVO_INTERMEDIATE_STOW) do_z_clearance(Z_CLEARANCE_DEPLOY_PROBE); #elif HAS_BED_PROBE if (probe.deploy()) { // (returns true on deploy failure) set_bed_leveling_enabled(abl.reenable); G29_RETURN(false, true); } #endif #if ENABLED(AUTO_BED_LEVELING_BILINEAR) if (!abl.dryrun && (abl.gridSpacing != bedlevel.grid_spacing || abl.probe_position_lf != bedlevel.grid_start)) { reset_bed_level(); // Reset grid to 0.0 or "not probed". (Also disables ABL) abl.reenable = false; // Can't re-enable (on error) until the new grid is written } // Pre-populate local Z values from the stored mesh TERN_(IS_KINEMATIC, COPY(abl.z_values, bedlevel.z_values)); #endif } // !g29_in_progress #if ENABLED(PROBE_MANUALLY) // For manual probing, get the next index to probe now. // On the first probe this will be incremented to 0. if (!no_action) { ++abl.abl_probe_index; g29_in_progress = true; } // Abort current G29 procedure, go back to idle state if (seenA && g29_in_progress) { SERIAL_ECHOLNPGM("Manual G29 aborted"); SET_SOFT_ENDSTOP_LOOSE(false); set_bed_leveling_enabled(abl.reenable); g29_in_progress = false; TERN_(LCD_BED_LEVELING, ui.wait_for_move = false); } // Query G29 status if (abl.verbose_level || seenQ) { SERIAL_ECHOPGM("Manual G29 "); if (g29_in_progress) SERIAL_ECHOLNPGM("point ", _MIN(abl.abl_probe_index + 1, abl.abl_points), " of ", abl.abl_points); else SERIAL_ECHOLNPGM("idle"); } // For 'A' or 'Q' exit with success state if (no_action) G29_RETURN(false, true); if (abl.abl_probe_index == 0) { // For the initial G29 S2 save software endstop state SET_SOFT_ENDSTOP_LOOSE(true); // Move close to the bed before the first point do_blocking_move_to_z(0); } else { #if ANY(AUTO_BED_LEVELING_LINEAR, AUTO_BED_LEVELING_3POINT) const uint16_t index = abl.abl_probe_index - 1; #endif // For G29 after adjusting Z. // Save the previous Z before going to the next point abl.measured_z = current_position.z; #if ENABLED(AUTO_BED_LEVELING_LINEAR) abl.mean += abl.measured_z; abl.eqnBVector[index] = abl.measured_z; abl.eqnAMatrix[index + 0 * abl.abl_points] = abl.probePos.x; abl.eqnAMatrix[index + 1 * abl.abl_points] = abl.probePos.y; abl.eqnAMatrix[index + 2 * abl.abl_points] = 1; incremental_LSF(&lsf_results, abl.probePos, abl.measured_z); #elif ENABLED(AUTO_BED_LEVELING_3POINT) points[index].z = abl.measured_z; #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) const float newz = abl.measured_z + abl.Z_offset; abl.z_values[abl.meshCount.x][abl.meshCount.y] = newz; TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(abl.meshCount, newz)); if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM_P(PSTR("Save X"), abl.meshCount.x, SP_Y_STR, abl.meshCount.y, SP_Z_STR, abl.measured_z + abl.Z_offset); #endif } // // If there's another point to sample, move there with optional lift. // #if ABL_USES_GRID // Skip any unreachable points while (abl.abl_probe_index < abl.abl_points) { // Set abl.meshCount.x, abl.meshCount.y based on abl.abl_probe_index, with zig-zag PR_OUTER_VAR = abl.abl_probe_index / PR_INNER_SIZE; PR_INNER_VAR = abl.abl_probe_index - (PR_OUTER_VAR * PR_INNER_SIZE); // Probe in reverse order for every other row/column const bool zig = (PR_OUTER_VAR & 1); // != ((PR_OUTER_SIZE) & 1); if (zig) PR_INNER_VAR = (PR_INNER_SIZE - 1) - PR_INNER_VAR; abl.probePos = abl.probe_position_lf + abl.gridSpacing * abl.meshCount.asFloat(); TERN_(AUTO_BED_LEVELING_LINEAR, abl.indexIntoAB[abl.meshCount.x][abl.meshCount.y] = abl.abl_probe_index); // Keep looping till a reachable point is found if (position_is_reachable(abl.probePos)) break; ++abl.abl_probe_index; } // Is there a next point to move to? if (abl.abl_probe_index < abl.abl_points) { _manual_goto_xy(abl.probePos); // Can be used here too! // Disable software endstops to allow manual adjustment // If G29 is not completed, they will not be re-enabled SET_SOFT_ENDSTOP_LOOSE(true); G29_RETURN(false, true); } else { // Leveling done! Fall through to G29 finishing code below SERIAL_ECHOLNPGM("Grid probing done."); // Re-enable software endstops, if needed SET_SOFT_ENDSTOP_LOOSE(false); } #elif ENABLED(AUTO_BED_LEVELING_3POINT) // Probe at 3 arbitrary points if (abl.abl_probe_index < abl.abl_points) { abl.probePos = xy_pos_t(points[abl.abl_probe_index]); _manual_goto_xy(abl.probePos); // Disable software endstops to allow manual adjustment // If G29 is not completed, they will not be re-enabled SET_SOFT_ENDSTOP_LOOSE(true); G29_RETURN(false, true); } else { SERIAL_ECHOLNPGM("3-point probing done."); // Re-enable software endstops, if needed SET_SOFT_ENDSTOP_LOOSE(false); if (!abl.dryrun) { vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal(); if (planeNormal.z < 0) planeNormal *= -1; planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal); // Can't re-enable (on error) until the new grid is written abl.reenable = false; } } #endif // AUTO_BED_LEVELING_3POINT #else // !PROBE_MANUALLY { const ProbePtRaise raise_after = parser.boolval('E') ? PROBE_PT_STOW : PROBE_PT_RAISE; abl.measured_z = 0; #if ABL_USES_GRID bool zig = PR_OUTER_SIZE & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION // Outer loop is X with PROBE_Y_FIRST enabled // Outer loop is Y with PROBE_Y_FIRST disabled for (PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_SIZE && !isnan(abl.measured_z); PR_OUTER_VAR++) { int8_t inStart, inStop, inInc; if (zig) { // Zig away from origin inStart = 0; // Left or front inStop = PR_INNER_SIZE; // Right or back inInc = 1; // Zig right } else { // Zag towards origin inStart = PR_INNER_SIZE - 1; // Right or back inStop = -1; // Left or front inInc = -1; // Zag left } zig ^= true; // zag // An index to print current state grid_count_t pt_index = (PR_OUTER_VAR) * (PR_INNER_SIZE) + 1; // Inner loop is Y with PROBE_Y_FIRST enabled // Inner loop is X with PROBE_Y_FIRST disabled for (PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; pt_index++, PR_INNER_VAR += inInc) { abl.probePos = abl.probe_position_lf + abl.gridSpacing * abl.meshCount.asFloat(); TERN_(AUTO_BED_LEVELING_LINEAR, abl.indexIntoAB[abl.meshCount.x][abl.meshCount.y] = ++abl.abl_probe_index); // 0... // Avoid probing outside the round or hexagonal area if (TERN0(IS_KINEMATIC, !probe.can_reach(abl.probePos))) continue; if (abl.verbose_level) SERIAL_ECHOLNPGM("Probing mesh point ", pt_index, "/", abl.abl_points, "."); TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " %i/%i"), GET_TEXT_F(MSG_PROBING_POINT), int(pt_index), int(abl.abl_points))); #if ENABLED(BD_SENSOR_PROBE_NO_STOP) if (PR_INNER_VAR == inStart) { char tmp_1[32]; // move to the start point of new line abl.measured_z = faux ? 0.001f * random(-100, 101) : probe.probe_at_point(abl.probePos, raise_after, abl.verbose_level); // Go to the end of the row/column ... and back up by one // TODO: Why not just use... PR_INNER_VAR = inStop - inInc for (PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc); PR_INNER_VAR -= inInc; // Get the coordinate of the resulting grid point abl.probePos = abl.probe_position_lf + abl.gridSpacing * abl.meshCount.asFloat(); // Coordinate that puts the probe at the grid point abl.probePos -= probe.offset_xy; // Put a G1 move into the buffer // TODO: Instead of G1, we can just add the move directly to the planner... // { // destination = current_position; destination = abl.probePos; // REMEMBER(fr, feedrate_mm_s, XY_PROBE_FEEDRATE_MM_S); // prepare_line_to_destination(); // } sprintf_P(tmp_1, PSTR("G1X%d.%d Y%d.%d F%d"), int(abl.probePos.x), int(abl.probePos.x * 10) % 10, int(abl.probePos.y), int(abl.probePos.y * 10) % 10, XY_PROBE_FEEDRATE ); gcode.process_subcommands_now(tmp_1); if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("destX: ", abl.probePos.x, " Y:", abl.probePos.y); // Reset the inner counter back to the start PR_INNER_VAR = inStart; // Get the coordinate of the start of the row/column abl.probePos = abl.probe_position_lf + abl.gridSpacing * abl.meshCount.asFloat(); } // Wait around until the real axis position reaches the comparison point // TODO: Use NEAR() because float is imprecise constexpr AxisEnum axis = TERN(PROBE_Y_FIRST, Y_AXIS, X_AXIS); const float cmp = abl.probePos[axis] - probe.offset_xy[axis]; float pos; for (;;) { pos = planner.get_axis_position_mm(axis); if (inInc > 0 ? (pos >= cmp) : (pos <= cmp)) break; idle_no_sleep(); } //if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM_P(axis == Y_AXIS ? PSTR("Y=") : PSTR("X=", pos); safe_delay(4); abl.measured_z = current_position.z - bdl.read(); if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("x_cur ", planner.get_axis_position_mm(X_AXIS), " z ", abl.measured_z); #else // !BD_SENSOR_PROBE_NO_STOP abl.measured_z = faux ? 0.001f * random(-100, 101) : probe.probe_at_point(abl.probePos, raise_after, abl.verbose_level); #endif if (isnan(abl.measured_z)) { set_bed_leveling_enabled(abl.reenable); break; // Breaks out of both loops } #if ENABLED(AUTO_BED_LEVELING_LINEAR) abl.mean += abl.measured_z; abl.eqnBVector[abl.abl_probe_index] = abl.measured_z; abl.eqnAMatrix[abl.abl_probe_index + 0 * abl.abl_points] = abl.probePos.x; abl.eqnAMatrix[abl.abl_probe_index + 1 * abl.abl_points] = abl.probePos.y; abl.eqnAMatrix[abl.abl_probe_index + 2 * abl.abl_points] = 1; incremental_LSF(&lsf_results, abl.probePos, abl.measured_z); #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) const float z = abl.measured_z + abl.Z_offset; abl.z_values[abl.meshCount.x][abl.meshCount.y] = z; TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(abl.meshCount, z)); #endif abl.reenable = false; // Don't re-enable after modifying the mesh idle_no_sleep(); } // inner } // outer #elif ENABLED(AUTO_BED_LEVELING_3POINT) // Probe at 3 arbitrary points for (uint8_t i = 0; i < 3; ++i) { if (abl.verbose_level) SERIAL_ECHOLNPGM("Probing point ", i + 1, "/3."); TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " %i/3"), GET_TEXT_F(MSG_PROBING_POINT), int(i + 1))); // Retain the last probe position abl.probePos = xy_pos_t(points[i]); abl.measured_z = faux ? 0.001 * random(-100, 101) : probe.probe_at_point(abl.probePos, raise_after, abl.verbose_level); if (isnan(abl.measured_z)) { set_bed_leveling_enabled(abl.reenable); break; } points[i].z = abl.measured_z; } if (!abl.dryrun && !isnan(abl.measured_z)) { vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal(); if (planeNormal.z < 0) planeNormal *= -1; planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal); // Can't re-enable (on error) until the new grid is written abl.reenable = false; } #endif // AUTO_BED_LEVELING_3POINT TERN_(HAS_STATUS_MESSAGE, ui.reset_status()); // Stow the probe. No raise for FIX_MOUNTED_PROBE. if (probe.stow()) { set_bed_leveling_enabled(abl.reenable); abl.measured_z = NAN; } } #endif // !PROBE_MANUALLY // // G29 Finishing Code // // Unless this is a dry run, auto bed leveling will // definitely be enabled after this point. // // If code above wants to continue leveling, it should // return or loop before this point. // if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position); #if ENABLED(PROBE_MANUALLY) g29_in_progress = false; TERN_(LCD_BED_LEVELING, ui.wait_for_move = false); #endif // Calculate leveling, print reports, correct the position if (!isnan(abl.measured_z)) { #if ENABLED(AUTO_BED_LEVELING_BILINEAR) if (abl.dryrun) bedlevel.print_leveling_grid(&abl.z_values); else { bedlevel.set_grid(abl.gridSpacing, abl.probe_position_lf); COPY(bedlevel.z_values, abl.z_values); TERN_(IS_KINEMATIC, bedlevel.extrapolate_unprobed_bed_level()); bedlevel.refresh_bed_level(); bedlevel.print_leveling_grid(); } #elif ENABLED(AUTO_BED_LEVELING_LINEAR) // For LINEAR leveling calculate matrix, print reports, correct the position /** * solve the plane equation ax + by + d = z * A is the matrix with rows [x y 1] for all the probed points * B is the vector of the Z positions * the normal vector to the plane is formed by the coefficients of the * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0 * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z */ struct { float a, b, d; } plane_equation_coefficients; finish_incremental_LSF(&lsf_results); plane_equation_coefficients.a = -lsf_results.A; // We should be able to eliminate the '-' on these three lines and down below plane_equation_coefficients.b = -lsf_results.B; // but that is not yet tested. plane_equation_coefficients.d = -lsf_results.D; abl.mean /= abl.abl_points; if (abl.verbose_level) { SERIAL_ECHOPGM("Eqn coefficients: a: ", p_float_t(plane_equation_coefficients.a, 8), " b: ", p_float_t(plane_equation_coefficients.b, 8), " d: ", p_float_t(plane_equation_coefficients.d, 8)); if (abl.verbose_level > 2) SERIAL_ECHOPGM("\nMean of sampled points: ", p_float_t(abl.mean, 8)); SERIAL_EOL(); } // Create the matrix but don't correct the position yet if (!abl.dryrun) planner.bed_level_matrix = matrix_3x3::create_look_at( vector_3(-plane_equation_coefficients.a, -plane_equation_coefficients.b, 1) // We can eliminate the '-' here and up above ); // Show the Topography map if enabled if (abl.topography_map) { float min_diff = 999; auto print_topo_map = [&](FSTR_P const title, const bool get_min) { SERIAL_ECHO(title); for (int8_t yy = abl.grid_points.y - 1; yy >= 0; yy--) { for (uint8_t xx = 0; xx < abl.grid_points.x; ++xx) { const int ind = abl.indexIntoAB[xx][yy]; xyz_float_t tmp = { abl.eqnAMatrix[ind + 0 * abl.abl_points], abl.eqnAMatrix[ind + 1 * abl.abl_points], 0 }; planner.bed_level_matrix.apply_rotation_xyz(tmp.x, tmp.y, tmp.z); if (get_min) NOMORE(min_diff, abl.eqnBVector[ind] - tmp.z); const float subval = get_min ? abl.mean : tmp.z + min_diff, diff = abl.eqnBVector[ind] - subval; SERIAL_CHAR(' '); if (diff >= 0.0) SERIAL_CHAR('+'); // Include + for column alignment SERIAL_ECHO(p_float_t(diff, 5)); } // xx SERIAL_EOL(); } // yy SERIAL_EOL(); }; print_topo_map(F("\nBed Height Topography:\n" " +--- BACK --+\n" " | |\n" " L | (+) | R\n" " E | | I\n" " F | (-) N (+) | G\n" " T | | H\n" " | (-) | T\n" " | |\n" " O-- FRONT --+\n" " (0,0)\n"), true); if (abl.verbose_level > 3) print_topo_map(F("\nCorrected Bed Height vs. Bed Topology:\n"), false); } // abl.topography_map #endif // AUTO_BED_LEVELING_LINEAR #if ABL_PLANAR // For LINEAR and 3POINT leveling correct the current position if (abl.verbose_level > 0) planner.bed_level_matrix.debug(F("\n\nBed Level Correction Matrix:")); if (!abl.dryrun) { // // Correct the current XYZ position based on the tilted plane. // if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position); xyze_pos_t converted = current_position; planner.force_unapply_leveling(converted); // use conversion machinery // Use the last measured distance to the bed, if possible if ( NEAR(current_position.x, abl.probePos.x - probe.offset_xy.x) && NEAR(current_position.y, abl.probePos.y - probe.offset_xy.y) ) { const float simple_z = current_position.z - abl.measured_z; if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Probed Z", simple_z, " Matrix Z", converted.z, " Discrepancy ", simple_z - converted.z); converted.z = simple_z; } // The rotated XY and corrected Z are now current_position current_position = converted; if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position); abl.reenable = true; } // Auto Bed Leveling is complete! Enable if possible. if (abl.reenable) { planner.leveling_active = true; sync_plan_position(); } #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) // Auto Bed Leveling is complete! Enable if possible. if (!abl.dryrun || abl.reenable) set_bed_leveling_enabled(true); #endif } // !isnan(abl.measured_z) // Restore state after probing if (!faux) restore_feedrate_and_scaling(); TERN_(HAS_BED_PROBE, probe.move_z_after_probing()); #ifdef EVENT_GCODE_AFTER_G29 if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Z Probe End Script: ", EVENT_GCODE_AFTER_G29); planner.synchronize(); process_subcommands_now(F(EVENT_GCODE_AFTER_G29)); #endif probe.use_probing_tool(false); report_current_position(); G29_RETURN(isnan(abl.measured_z), true); } #endif // HAS_ABL_NOT_UBL
2301_81045437/Marlin
Marlin/src/gcode/bedlevel/abl/G29.cpp
C++
agpl-3.0
35,337
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General 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/>. * */ /** * M421.cpp - Auto Bed Leveling */ #include "../../../inc/MarlinConfig.h" #if ENABLED(AUTO_BED_LEVELING_BILINEAR) #include "../../gcode.h" #include "../../../feature/bedlevel/bedlevel.h" #if ENABLED(EXTENSIBLE_UI) #include "../../../lcd/extui/ui_api.h" #endif /** * M421: Set one or more Mesh Bed Leveling Z coordinates * * Usage: * M421 I<xindex> J<yindex> Z<linear> * M421 I<xindex> J<yindex> Q<offset> * * - If I is omitted, set the entire row * - If J is omitted, set the entire column * - If both I and J are omitted, set all */ void GcodeSuite::M421() { int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1); const bool hasZ = parser.seenval('Z'), hasQ = !hasZ && parser.seenval('Q'); if (hasZ || hasQ) { if (WITHIN(ix, -1, GRID_MAX_POINTS_X - 1) && WITHIN(iy, -1, GRID_MAX_POINTS_Y - 1)) { const float zval = parser.value_linear_units(); uint8_t sx = ix >= 0 ? ix : 0, ex = ix >= 0 ? ix : GRID_MAX_POINTS_X - 1, sy = iy >= 0 ? iy : 0, ey = iy >= 0 ? iy : GRID_MAX_POINTS_Y - 1; for (uint8_t x = sx; x <= ex; ++x) { for (uint8_t y = sy; y <= ey; ++y) { bedlevel.z_values[x][y] = zval + (hasQ ? bedlevel.z_values[x][y] : 0); TERN_(EXTENSIBLE_UI, ExtUI::onMeshUpdate(x, y, bedlevel.z_values[x][y])); } } bedlevel.refresh_bed_level(); } else SERIAL_ERROR_MSG(STR_ERR_MESH_XY); } else SERIAL_ERROR_MSG(STR_ERR_M421_PARAMETERS); } #endif // AUTO_BED_LEVELING_BILINEAR
2301_81045437/Marlin
Marlin/src/gcode/bedlevel/abl/M421.cpp
C++
agpl-3.0
2,398