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(SPI_FLASH) #include "W25Qxx.h" W25QXXFlash W25QXX; #ifndef NC #define NC -1 #endif MarlinSPI W25QXXFlash::mySPI(SPI_FLASH_MOSI_PIN, SPI_FLASH_MISO_PIN, SPI_FLASH_SCK_PIN, NC); #define SPI_FLASH_CS_H() OUT_WRITE(SPI_FLASH_CS_PIN, HIGH) #define SPI_FLASH_CS_L() OUT_WRITE(SPI_FLASH_CS_PIN, LOW) bool flash_dma_mode = true; void W25QXXFlash::init(uint8_t spiRate) { OUT_WRITE(SPI_FLASH_CS_PIN, HIGH); /** * STM32F1 APB2 = 72MHz, APB1 = 36MHz, max SPI speed of this MCU if 18Mhz * STM32F1 has 3 SPI ports, SPI1 in APB2, SPI2/SPI3 in APB1 * so the minimum prescale of SPI1 is DIV4, SPI2/SPI3 is DIV2 */ #ifndef SPI_CLOCK_MAX #if SPI_DEVICE == 1 #define SPI_CLOCK_MAX SPI_CLOCK_DIV4 #else #define SPI_CLOCK_MAX SPI_CLOCK_DIV2 #endif #endif uint8_t clock; switch (spiRate) { case SPI_FULL_SPEED: clock = SPI_CLOCK_MAX; break; case SPI_HALF_SPEED: clock = SPI_CLOCK_DIV4; break; case SPI_QUARTER_SPEED: clock = SPI_CLOCK_DIV8; break; case SPI_EIGHTH_SPEED: clock = SPI_CLOCK_DIV16; break; case SPI_SPEED_5: clock = SPI_CLOCK_DIV32; break; case SPI_SPEED_6: clock = SPI_CLOCK_DIV64; break; default: clock = SPI_CLOCK_DIV2;// Default from the SPI library } mySPI.setClockDivider(clock); mySPI.setBitOrder(MSBFIRST); mySPI.setDataMode(SPI_MODE0); mySPI.begin(); } /** * @brief Receive a single byte from the SPI port. * * @return Byte received */ uint8_t W25QXXFlash::spi_flash_Rec() { const uint8_t returnByte = mySPI.transfer(0xFF); return returnByte; } uint8_t W25QXXFlash::spi_flash_read_write_byte(uint8_t data) { const uint8_t returnByte = mySPI.transfer(data); return returnByte; } /** * @brief Receive a number of bytes from the SPI port to a buffer * * @param buf Pointer to starting address of buffer to write to. * @param nbyte Number of bytes to receive. * @return Nothing * * @details Uses DMA */ void W25QXXFlash::spi_flash_Read(uint8_t *buf, uint16_t nbyte) { mySPI.dmaTransfer(0, const_cast<uint8_t*>(buf), nbyte); } /** * @brief Send a single byte on SPI port * * @param b Byte to send * * @details */ void W25QXXFlash::spi_flash_Send(uint8_t b) { mySPI.transfer(b); } /** * @brief Write token and then write from 512 byte buffer to SPI (for SD card) * * @param buf Pointer with buffer start address * @return Nothing * * @details Use DMA */ void W25QXXFlash::spi_flash_SendBlock(uint8_t token, const uint8_t *buf) { mySPI.transfer(token); mySPI.dmaSend(const_cast<uint8_t*>(buf), 512); } uint16_t W25QXXFlash::W25QXX_ReadID(void) { uint16_t Temp = 0; SPI_FLASH_CS_L(); spi_flash_Send(0x90); spi_flash_Send(0x00); spi_flash_Send(0x00); spi_flash_Send(0x00); Temp |= spi_flash_Rec() << 8; Temp |= spi_flash_Rec(); SPI_FLASH_CS_H(); return Temp; } void W25QXXFlash::SPI_FLASH_WriteEnable() { // Select the FLASH: Chip Select low SPI_FLASH_CS_L(); // Send "Write Enable" instruction spi_flash_Send(W25X_WriteEnable); // Deselect the FLASH: Chip Select high SPI_FLASH_CS_H(); } /******************************************************************************* * Function Name : SPI_FLASH_WaitForWriteEnd * Description : Polls the status of the Write In Progress (WIP) flag in the * FLASH's status register and loop until write operation has * completed. * Input : None * Output : None * Return : None *******************************************************************************/ void W25QXXFlash::SPI_FLASH_WaitForWriteEnd() { uint8_t FLASH_Status = 0; // Select the FLASH: Chip Select low SPI_FLASH_CS_L(); // Send "Read Status Register" instruction spi_flash_Send(W25X_ReadStatusReg); // Loop as long as the memory is busy with a write cycle do /* Send a dummy byte to generate the clock needed by the FLASH and put the value of the status register in FLASH_Status variable */ FLASH_Status = spi_flash_Rec(); while ((FLASH_Status & WIP_Flag) == 0x01); // Write in progress // Deselect the FLASH: Chip Select high SPI_FLASH_CS_H(); } void W25QXXFlash::SPI_FLASH_SectorErase(uint32_t SectorAddr) { // Send write enable instruction SPI_FLASH_WriteEnable(); // Sector Erase // Select the FLASH: Chip Select low SPI_FLASH_CS_L(); // Send Sector Erase instruction spi_flash_Send(W25X_SectorErase); // Send SectorAddr high nybble address byte spi_flash_Send((SectorAddr & 0xFF0000) >> 16); // Send SectorAddr medium nybble address byte spi_flash_Send((SectorAddr & 0xFF00) >> 8); // Send SectorAddr low nybble address byte spi_flash_Send(SectorAddr & 0xFF); // Deselect the FLASH: Chip Select high SPI_FLASH_CS_H(); // Wait the end of Flash writing SPI_FLASH_WaitForWriteEnd(); } void W25QXXFlash::SPI_FLASH_BlockErase(uint32_t BlockAddr) { SPI_FLASH_WriteEnable(); SPI_FLASH_CS_L(); // Send Sector Erase instruction spi_flash_Send(W25X_BlockErase); // Send SectorAddr high nybble address byte spi_flash_Send((BlockAddr & 0xFF0000) >> 16); // Send SectorAddr medium nybble address byte spi_flash_Send((BlockAddr & 0xFF00) >> 8); // Send SectorAddr low nybble address byte spi_flash_Send(BlockAddr & 0xFF); SPI_FLASH_CS_H(); SPI_FLASH_WaitForWriteEnd(); } /******************************************************************************* * Function Name : SPI_FLASH_BulkErase * Description : Erases the entire FLASH. * Input : None * Output : None * Return : None *******************************************************************************/ void W25QXXFlash::SPI_FLASH_BulkErase() { // Send write enable instruction SPI_FLASH_WriteEnable(); // Bulk Erase // Select the FLASH: Chip Select low SPI_FLASH_CS_L(); // Send Bulk Erase instruction spi_flash_Send(W25X_ChipErase); // Deselect the FLASH: Chip Select high SPI_FLASH_CS_H(); // Wait the end of Flash writing SPI_FLASH_WaitForWriteEnd(); } /******************************************************************************* * Function Name : SPI_FLASH_PageWrite * Description : Writes more than one byte to the FLASH with a single WRITE * cycle(Page WRITE sequence). The number of byte can't exceed * the FLASH page size. * Input : - pBuffer : pointer to the buffer containing the data to be * written to the FLASH. * - WriteAddr : FLASH's internal address to write to. * - NumByteToWrite : number of bytes to write to the FLASH, * must be equal or less than "SPI_FLASH_PageSize" value. * Output : None * Return : None *******************************************************************************/ void W25QXXFlash::SPI_FLASH_PageWrite(uint8_t *pBuffer, uint32_t WriteAddr, uint16_t NumByteToWrite) { // Enable the write access to the FLASH SPI_FLASH_WriteEnable(); // Select the FLASH: Chip Select low SPI_FLASH_CS_L(); // Send "Write to Memory " instruction spi_flash_Send(W25X_PageProgram); // Send WriteAddr high nybble address byte to write to spi_flash_Send((WriteAddr & 0xFF0000) >> 16); // Send WriteAddr medium nybble address byte to write to spi_flash_Send((WriteAddr & 0xFF00) >> 8); // Send WriteAddr low nybble address byte to write to spi_flash_Send(WriteAddr & 0xFF); NOMORE(NumByteToWrite, SPI_FLASH_PerWritePageSize); // While there is data to be written on the FLASH while (NumByteToWrite--) { // Send the current byte spi_flash_Send(*pBuffer); // Point on the next byte to be written pBuffer++; } // Deselect the FLASH: Chip Select high SPI_FLASH_CS_H(); // Wait the end of Flash writing SPI_FLASH_WaitForWriteEnd(); } /******************************************************************************* * Function Name : SPI_FLASH_BufferWrite * Description : Writes block of data to the FLASH. In this function, the * number of WRITE cycles are reduced, using Page WRITE sequence. * Input : - pBuffer : pointer to the buffer containing the data to be * written to the FLASH. * - WriteAddr : FLASH's internal address to write to. * - NumByteToWrite : number of bytes to write to the FLASH. * Output : None * Return : None *******************************************************************************/ void W25QXXFlash::SPI_FLASH_BufferWrite(uint8_t *pBuffer, uint32_t WriteAddr, uint16_t NumByteToWrite) { uint8_t NumOfPage = 0, NumOfSingle = 0, Addr = 0, count = 0, temp = 0; Addr = WriteAddr % SPI_FLASH_PageSize; count = SPI_FLASH_PageSize - Addr; NumOfPage = NumByteToWrite / SPI_FLASH_PageSize; NumOfSingle = NumByteToWrite % SPI_FLASH_PageSize; if (Addr == 0) { // WriteAddr is SPI_FLASH_PageSize aligned if (NumOfPage == 0) { // NumByteToWrite < SPI_FLASH_PageSize SPI_FLASH_PageWrite(pBuffer, WriteAddr, NumByteToWrite); } else { // NumByteToWrite > SPI_FLASH_PageSize while (NumOfPage--) { SPI_FLASH_PageWrite(pBuffer, WriteAddr, SPI_FLASH_PageSize); WriteAddr += SPI_FLASH_PageSize; pBuffer += SPI_FLASH_PageSize; } SPI_FLASH_PageWrite(pBuffer, WriteAddr, NumOfSingle); } } else { // WriteAddr is not SPI_FLASH_PageSize aligned if (NumOfPage == 0) { // NumByteToWrite < SPI_FLASH_PageSize if (NumOfSingle > count) { // (NumByteToWrite + WriteAddr) > SPI_FLASH_PageSize temp = NumOfSingle - count; SPI_FLASH_PageWrite(pBuffer, WriteAddr, count); WriteAddr += count; pBuffer += count; SPI_FLASH_PageWrite(pBuffer, WriteAddr, temp); } else SPI_FLASH_PageWrite(pBuffer, WriteAddr, NumByteToWrite); } else { // NumByteToWrite > SPI_FLASH_PageSize NumByteToWrite -= count; NumOfPage = NumByteToWrite / SPI_FLASH_PageSize; NumOfSingle = NumByteToWrite % SPI_FLASH_PageSize; SPI_FLASH_PageWrite(pBuffer, WriteAddr, count); WriteAddr += count; pBuffer += count; while (NumOfPage--) { SPI_FLASH_PageWrite(pBuffer, WriteAddr, SPI_FLASH_PageSize); WriteAddr += SPI_FLASH_PageSize; pBuffer += SPI_FLASH_PageSize; } if (NumOfSingle != 0) SPI_FLASH_PageWrite(pBuffer, WriteAddr, NumOfSingle); } } } /******************************************************************************* * Function Name : SPI_FLASH_BufferRead * Description : Reads a block of data from the FLASH. * Input : - pBuffer : pointer to the buffer that receives the data read * from the FLASH. * - ReadAddr : FLASH's internal address to read from. * - NumByteToRead : number of bytes to read from the FLASH. * Output : None * Return : None *******************************************************************************/ void W25QXXFlash::SPI_FLASH_BufferRead(uint8_t *pBuffer, uint32_t ReadAddr, uint16_t NumByteToRead) { // Select the FLASH: Chip Select low SPI_FLASH_CS_L(); // Send "Read from Memory " instruction spi_flash_Send(W25X_ReadData); // Send ReadAddr high nybble address byte to read from spi_flash_Send((ReadAddr & 0xFF0000) >> 16); // Send ReadAddr medium nybble address byte to read from spi_flash_Send((ReadAddr & 0xFF00) >> 8); // Send ReadAddr low nybble address byte to read from spi_flash_Send(ReadAddr & 0xFF); if (NumByteToRead <= 32 || !flash_dma_mode) { while (NumByteToRead--) { // While there is data to be read // Read a byte from the FLASH *pBuffer = spi_flash_Rec(); // Point to the next location where the byte read will be saved pBuffer++; } } else spi_flash_Read(pBuffer, NumByteToRead); SPI_FLASH_CS_H(); } #endif // SPI_FLASH
2301_81045437/Marlin
Marlin/src/libs/W25Qxx.cpp
C++
agpl-3.0
12,854
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include <stdint.h> #include HAL_PATH(.., MarlinSPI.h) #define W25X_WriteEnable 0x06 #define W25X_WriteDisable 0x04 #define W25X_ReadStatusReg 0x05 #define W25X_WriteStatusReg 0x01 #define W25X_ReadData 0x03 #define W25X_FastReadData 0x0B #define W25X_FastReadDual 0x3B #define W25X_PageProgram 0x02 #define W25X_BlockErase 0xD8 #define W25X_SectorErase 0x20 #define W25X_ChipErase 0xC7 #define W25X_PowerDown 0xB9 #define W25X_ReleasePowerDown 0xAB #define W25X_DeviceID 0xAB #define W25X_ManufactDeviceID 0x90 #define W25X_JedecDeviceID 0x9F #define WIP_Flag 0x01 /* Write In Progress (WIP) flag */ #define Dummy_Byte 0xA5 #define SPI_FLASH_SectorSize 4096 #define SPI_FLASH_PageSize 256 #define SPI_FLASH_PerWritePageSize 256 class W25QXXFlash { private: static MarlinSPI mySPI; public: void init(uint8_t spiRate); static uint8_t spi_flash_Rec(); static uint8_t spi_flash_read_write_byte(uint8_t data); static void spi_flash_Read(uint8_t *buf, uint16_t nbyte); static void spi_flash_Send(uint8_t b); static void spi_flash_SendBlock(uint8_t token, const uint8_t *buf); static uint16_t W25QXX_ReadID(void); static void SPI_FLASH_WriteEnable(); static void SPI_FLASH_WaitForWriteEnd(); static void SPI_FLASH_SectorErase(uint32_t SectorAddr); static void SPI_FLASH_BlockErase(uint32_t BlockAddr); static void SPI_FLASH_BulkErase(); static void SPI_FLASH_PageWrite(uint8_t *pBuffer, uint32_t WriteAddr, uint16_t NumByteToWrite); static void SPI_FLASH_BufferWrite(uint8_t *pBuffer, uint32_t WriteAddr, uint16_t NumByteToWrite); static void SPI_FLASH_BufferRead(uint8_t *pBuffer, uint32_t ReadAddr, uint16_t NumByteToRead); }; extern W25QXXFlash W25QXX;
2301_81045437/Marlin
Marlin/src/libs/W25Qxx.h
C++
agpl-3.0
2,717
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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" template <typename Helper> struct AutoReporter { millis_t next_report_ms; uint8_t report_interval; #if HAS_MULTI_SERIAL SerialMask report_port_mask; AutoReporter() : report_port_mask(SerialMask::All) {} #endif inline void set_interval(uint8_t seconds, const uint8_t limit=60) { report_interval = _MIN(seconds, limit); next_report_ms = millis() + SEC_TO_MS(seconds); } inline void tick() { if (!report_interval) return; const millis_t ms = millis(); if (ELAPSED(ms, next_report_ms)) { next_report_ms = ms + SEC_TO_MS(report_interval); PORT_REDIRECT(report_port_mask); Helper::report(); PORT_RESTORE(); } } };
2301_81045437/Marlin
Marlin/src/libs/autoreport.h
C++
agpl-3.0
1,592
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../core/serial.h" /** * bresenham_t.h - Bresenham algorithm template * * An array of values / counters that tick together */ #define FORCE_INLINE __attribute__((always_inline)) inline #define __O3 __attribute__((optimize("O3"))) template <uint8_t uid, uint8_t size> struct BresenhamCfg { static constexpr uint8_t UID = uid, SIZE = size; }; template<typename T, typename Cfg> class Bresenham { private: static constexpr T signtest = -1; static_assert(signtest < 0, "Bresenham type must be signed!"); public: static T divisor, value[Cfg::SIZE], dir[Cfg::SIZE], dividend[Cfg::SIZE], counter[Cfg::SIZE]; // Default: Instantiate all items with the identical parameters Bresenham(const T &inDivisor=1, const int8_t &inDir=1, const T &inDividend=1, const T &inValue=0) { for (uint8_t i = 0; i < Cfg::SIZE; i++) init(i, inDivisor, inDir, inDividend, inValue); } // Instantiate all items with the same divisor Bresenham(const T &inDivisor, const int8_t (&inDir)[Cfg::SIZE], const T (&inDividend)[Cfg::SIZE], const T (&inValue)[Cfg::SIZE]={0}) { init(inDivisor, inDir, inDividend, inValue); } // Instantiate all items with the same divisor and direction Bresenham(const T &inDivisor, const int8_t &inDir, const T (&inDividend)[Cfg::SIZE], const T (&inValue)[Cfg::SIZE]={0}) { init(inDivisor, inDir, inDividend, inValue); } // Init all items with the same parameters FORCE_INLINE static void init(const uint8_t index, const T &inDivisor=1, const int8_t &inDir=1, const T &inDividend=1, const T &inValue=0) { divisor = inDivisor; dir[index] = inDir; dividend[index] = inDividend; value[index] = inValue; prime(index); } // Init all items with the same divisor FORCE_INLINE static void init(const T &inDivisor, const int8_t (&inDir)[Cfg::SIZE], const T (&inDividend)[Cfg::SIZE], const T (&inValue)[Cfg::SIZE]={0}) { divisor = inDivisor; for (uint8_t i = 0; i < Cfg::SIZE; i++) { dir[i] = inDir[i]; dividend[i] = inDividend[i]; value[i] = inValue[i]; } prime(); } // Init all items with the same divisor and direction FORCE_INLINE static void init(const T &inDivisor, const int8_t &inDir, const T (&inDividend)[Cfg::SIZE], const T (&inValue)[Cfg::SIZE]={0}) { divisor = inDivisor; for (uint8_t i = 0; i < Cfg::SIZE; i++) { dir[i] = inDir; dividend[i] = inDividend[i]; value[i] = inValue[i]; } prime(); } // Reinit item with new dir, dividend, value keeping the same divisor FORCE_INLINE static void reinit(const uint8_t index, const int8_t &inDir=1, const T &inDividend=1, const T &inValue=0) { dir[index] = inDir; dividend[index] = inDividend; value[index] = inValue; prime(); } FORCE_INLINE static void prime(const uint8_t index) { counter[index] = -(divisor / 2); } FORCE_INLINE static void prime() { for (uint8_t i = 0; i < Cfg::SIZE; i++) prime(i); } FORCE_INLINE static void back(const uint8_t index) { counter[index] -= divisor; } FORCE_INLINE static bool tick1(const uint8_t index) { counter[index] += dividend[index]; return counter[index] > 0; } FORCE_INLINE static void tick(const uint8_t index) { if (tick1(index)) { value[index] += dir[index]; back(index); } } FORCE_INLINE static void tick1() __O3 { for (uint8_t i = 0; i < Cfg::SIZE; i++) (void)tick1(i); } FORCE_INLINE static void tick() __O3 { for (uint8_t i = 0; i < Cfg::SIZE; i++) (void)tick(i); } static void report(const uint8_t index) { if (index < Cfg::SIZE) { SERIAL_ECHOPGM("bresenham ", index, " : (", dividend[index], "/", divisor, ") "); if (counter[index] >= 0) SERIAL_CHAR(' '); if (labs(counter[index]) < 100) { SERIAL_CHAR(' '); if (labs(counter[index]) < 10) SERIAL_CHAR(' '); } SERIAL_ECHO(counter[index]); SERIAL_ECHOLNPGM(" ... ", value[index]); } } static void report() { for (uint8_t i = 0; i < Cfg::SIZE; i++) report(i); } };
2301_81045437/Marlin
Marlin/src/libs/bresenham.h
C++
agpl-3.0
4,902
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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_BEEPER #include "buzzer.h" #include "../module/temperature.h" #include "../lcd/marlinui.h" #if ENABLED(EXTENSIBLE_UI) #include "../lcd/extui/ui_api.h" #endif Buzzer::state_t Buzzer::state; CircularQueue<tone_t, TONE_QUEUE_LENGTH> Buzzer::buffer; Buzzer buzzer; /** * @brief Add a tone to the queue * @details Adds a tone_t structure to the ring buffer, will block IO if the * queue is full waiting for one slot to get available. * * @param duration Duration of the tone in milliseconds * @param frequency Frequency of the tone in hertz */ void Buzzer::tone(const uint16_t duration, const uint16_t frequency/*=0*/) { if (!ui.sound_on) return; while (buffer.isFull()) { tick(); thermalManager.task(); } tone_t tone = { duration, frequency }; buffer.enqueue(tone); } void Buzzer::tick() { if (!ui.sound_on) return; const millis_t now = millis(); if (!state.endtime) { if (buffer.isEmpty()) return; state.tone = buffer.dequeue(); state.endtime = now + state.tone.duration; if (state.tone.frequency > 0) { #if ENABLED(EXTENSIBLE_UI) && DISABLED(EXTUI_LOCAL_BEEPER) CRITICAL_SECTION_START(); ExtUI::onPlayTone(state.tone.frequency, state.tone.duration); CRITICAL_SECTION_END(); #elif ENABLED(SPEAKER) CRITICAL_SECTION_START(); ::tone(BEEPER_PIN, state.tone.frequency, state.tone.duration); CRITICAL_SECTION_END(); #else on(); #endif } } else if (ELAPSED(now, state.endtime)) reset(); } #endif // HAS_BEEPER
2301_81045437/Marlin
Marlin/src/libs/buzzer.cpp
C++
agpl-3.0
2,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/>. * */ #pragma once #include "../inc/MarlinConfig.h" #if HAS_BEEPER #include "circularqueue.h" #ifndef TONE_QUEUE_LENGTH #define TONE_QUEUE_LENGTH 4 #endif /** * @brief Tone structure * @details Simple abstraction of a tone based on a duration and a frequency. */ struct tone_t { uint16_t duration; uint16_t frequency; }; /** * @brief Buzzer class */ class Buzzer { public: typedef struct { tone_t tone; uint32_t endtime; } state_t; private: static state_t state; protected: static CircularQueue<tone_t, TONE_QUEUE_LENGTH> buffer; /** * @brief Inverts the state of a digital PIN * @details This will invert the current state of an digital IO pin. */ FORCE_INLINE static void invert() { TOGGLE(BEEPER_PIN); } /** * @brief Resets the state of the class * @details Brings the class state to a known one. */ static void reset() { off(); state.endtime = 0; } public: /** * @brief Init Buzzer */ static void init() { SET_OUTPUT(BEEPER_PIN); reset(); } /** * @brief Turn on a digital PIN * @details Alias of digitalWrite(PIN, HIGH) using FastIO */ FORCE_INLINE static void on() { WRITE(BEEPER_PIN, HIGH); } /** * @brief Turn off a digital PIN * @details Alias of digitalWrite(PIN, LOW) using FastIO */ FORCE_INLINE static void off() { WRITE(BEEPER_PIN, LOW); } static void click(const uint16_t duration) { on(); delay(duration); off(); } /** * @brief Add a tone to the queue * @details Adds a tone_t structure to the ring buffer, will block IO if the * queue is full waiting for one slot to get available. * * @param duration Duration of the tone in milliseconds * @param frequency Frequency of the tone in hertz */ static void tone(const uint16_t duration, const uint16_t frequency=0); /** * @brief Tick function * @details This function should be called at loop, it will take care of * playing the tones in the queue. */ static void tick(); }; // Provide a buzzer instance extern Buzzer buzzer; // Buzz directly via the BEEPER pin tone queue #define BUZZ(V...) buzzer.tone(V) #elif USE_MARLINUI_BUZZER // Use MarlinUI for a buzzer on the LCD #define BUZZ(V...) ui.buzz(V) #else // No buzz capability #define BUZZ(...) NOOP #endif #define ERR_BUZZ() BUZZ(400, 40) #define OKAY_BUZZ() do{ BUZZ(100, 659); BUZZ(10); BUZZ(100, 698); }while(0) #define DONE_BUZZ(ok) do{ if (ok) OKAY_BUZZ(); else ERR_BUZZ(); }while(0)
2301_81045437/Marlin
Marlin/src/libs/buzzer.h
C++
agpl-3.0
3,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 <stdint.h> /** * @brief Circular Queue class * @details Implementation of the classic ring buffer data structure */ template<typename T, uint8_t N> class CircularQueue { private: /** * @brief Buffer structure * @details This structure consolidates all the overhead required to handle * a circular queue such as the pointers and the buffer vector. */ struct buffer_t { uint8_t head; uint8_t tail; uint8_t count; uint8_t size; T queue[N]; } buffer; public: /** * @brief Class constructor * @details This class requires two template parameters, T defines the type * of item this queue will handle and N defines the maximum number of * items that can be stored on the queue. */ CircularQueue<T, N>() { buffer.size = N; buffer.count = buffer.head = buffer.tail = 0; } /** * @brief Removes and returns a item from the queue * @details Removes the oldest item on the queue, pointed to by the * buffer_t head field. The item is returned to the caller. * @return type T item */ T dequeue() { if (isEmpty()) return T(); uint8_t index = buffer.head; --buffer.count; if (++buffer.head == buffer.size) buffer.head = 0; return buffer.queue[index]; } /** * @brief Adds an item to the queue * @details Adds an item to the queue on the location pointed by the buffer_t * tail variable. Returns false if no queue space is available. * @param item Item to be added to the queue * @return true if the operation was successful */ bool enqueue(T const &item) { if (isFull()) return false; buffer.queue[buffer.tail] = item; ++buffer.count; if (++buffer.tail == buffer.size) buffer.tail = 0; return true; } /** * @brief Checks if the queue has no items * @details Returns true if there are no items on the queue, false otherwise. * @return true if queue is empty */ bool isEmpty() { return buffer.count == 0; } /** * @brief Checks if the queue is full * @details Returns true if the queue is full, false otherwise. * @return true if queue is full */ bool isFull() { return buffer.count == buffer.size; } /** * @brief Gets the queue size * @details Returns the maximum number of items a queue can have. * @return the queue size */ uint8_t size() { return buffer.size; } /** * @brief Gets the next item from the queue without removing it * @details Returns the next item in the queue without removing it * or updating the pointers. * @return first item in the queue */ T peek() { return buffer.queue[buffer.head]; } /** * @brief Gets the number of items on the queue * @details Returns the current number of items stored on the queue. * @return number of items in the queue */ uint8_t count() { return buffer.count; } };
2301_81045437/Marlin
Marlin/src/libs/circularqueue.h
C++
agpl-3.0
3,994
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 "crc16.h" void crc16(uint16_t *crc, const void * const data, uint16_t cnt) { uint8_t *ptr = (uint8_t *)data; while (cnt--) { *crc = (uint16_t)(*crc ^ (uint16_t)(((uint16_t)*ptr++) << 8)); for (uint8_t i = 0; i < 8; i++) *crc = (uint16_t)((*crc & 0x8000) ? ((uint16_t)(*crc << 1) ^ 0x1021) : (*crc << 1)); } }
2301_81045437/Marlin
Marlin/src/libs/crc16.cpp
C++
agpl-3.0
1,202
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include <stdint.h> void crc16(uint16_t *crc, const void * const data, uint16_t cnt);
2301_81045437/Marlin
Marlin/src/libs/crc16.h
C
agpl-3.0
963
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 "../HAL/shared/Marduino.h" struct duration_t { /** * @brief Duration is stored in seconds */ uint32_t value; /** * @brief Constructor */ duration_t() : duration_t(0) {}; /** * @brief Constructor * * @param seconds The number of seconds */ duration_t(uint32_t const &seconds) { this->value = seconds; } /** * @brief Equality comparison * @details Overloads the equality comparison operator * * @param value The number of seconds to compare to * @return True if both durations are equal */ bool operator==(const uint32_t &value) const { return (this->value == value); } /** * @brief Inequality comparison * @details Overloads the inequality comparison operator * * @param value The number of seconds to compare to * @return False if both durations are equal */ bool operator!=(const uint32_t &value) const { return ! this->operator==(value); } /** * @brief Format the duration as years * @return The number of years */ inline uint8_t year() const { return this->day() / 365; } /** * @brief Format the duration as days * @return The number of days */ inline uint16_t day() const { return this->hour() / 24; } /** * @brief Format the duration as hours * @return The number of hours */ inline uint32_t hour() const { return this->minute() / 60; } /** * @brief Format the duration as minutes * @return The number of minutes */ inline uint32_t minute() const { return this->second() / 60; } /** * @brief Format the duration as seconds * @return The number of seconds */ inline uint32_t second() const { return this->value; } #pragma GCC diagnostic push #if GCC_VERSION <= 50000 #pragma GCC diagnostic ignored "-Wformat-overflow" #endif /** * @brief Format the duration as a string * @details String will be formatted using a "full" representation of duration * * @param buffer The array pointed to must be able to accommodate 22 bytes * (21 for the string, 1 more for the terminating nul) * @param dense Whether to skip spaces in the resulting string * * Output examples: * 123456789012345678901 (strlen) * 135y 364d 23h 59m 59s * 364d 23h 59m 59s * 23h 59m 59s * 59m 59s * 59s */ char* toString(char * const buffer) const { const uint16_t y = this->year(), d = this->day() % 365, h = this->hour() % 24, m = this->minute() % 60, s = this->second() % 60; if (y) sprintf_P(buffer, PSTR("%iy %id %ih %im %is"), y, d, h, m, s); else if (d) sprintf_P(buffer, PSTR("%id %ih %im %is"), d, h, m, s); else if (h) sprintf_P(buffer, PSTR("%ih %im %is"), h, m, s); else if (m) sprintf_P(buffer, PSTR("%im %is"), m, s); else sprintf_P(buffer, PSTR("%is"), s); return buffer; } /** * @brief Format the duration as a compact string * @details String will be formatted using a "full" representation of duration * * @param buffer The array pointed to must be able to accommodate 18 bytes * (17 for the string, 1 more for the terminating nul) * @param dense Whether to skip spaces in the resulting string * * Output examples: * 12345678901234567 (strlen) * 135y364d23h59m59s * 364d23h59m59s * 23h59m59s * 59m59s * 59s */ char* toCompactString(char * const buffer) const { const uint16_t y = this->year(), d = this->day() % 365, h = this->hour() % 24, m = this->minute() % 60, s = this->second() % 60; if (y) sprintf_P(buffer, PSTR("%iy%id%ih%im%is"), y, d, h, m, s); else if (d) sprintf_P(buffer, PSTR("%id%ih%im%is"), d, h, m, s); else if (h) sprintf_P(buffer, PSTR("%ih%im%is"), h, m, s); else if (m) sprintf_P(buffer, PSTR("%im%is"), m, s); else sprintf_P(buffer, PSTR("%is"), s); return buffer; } /** * @brief Format the duration as a string * @details String will be formatted using a "digital" representation of duration * * @param buffer The array pointed to must be able to accommodate 10 bytes * @return length of the formatted string (without terminating nul) * * Output examples: * 123456789 (strlen) * 12'34 * 99:59 * 123:45 * 1d 12:33 * 9999d 12:33 */ uint8_t toDigital(char *buffer, bool with_days=false) const { const uint16_t h = uint16_t(this->hour()), m = uint16_t(this->minute() % 60UL); if (with_days) { const uint16_t d = this->day(); sprintf_P(buffer, PSTR("%hud %02hu:%02hu"), d, h % 24, m); // 1d 23:45 return strlen_P(buffer); } else if (!h) { const uint16_t s = uint16_t(this->second() % 60UL); sprintf_P(buffer, PSTR("%02hu'%02hu"), m, s); // 12'34 return 5; } else if (h < 100) { sprintf_P(buffer, PSTR("%02hu:%02hu"), h, m); // 12:34 return 5; } else { sprintf_P(buffer, PSTR("%hu:%02hu"), h, m); // 123:45 return 6; } } #pragma GCC diagnostic pop };
2301_81045437/Marlin
Marlin/src/libs/duration_t.h
C
agpl-3.0
6,110
/** * libs/heatshrink/heatshrink_common.h */ #pragma once #define HEATSHRINK_AUTHOR "Scott Vokes <vokes.s@gmail.com>" #define HEATSHRINK_URL "github.com/atomicobject/heatshrink" /* Version 0.4.1 */ #define HEATSHRINK_VERSION_MAJOR 0 #define HEATSHRINK_VERSION_MINOR 4 #define HEATSHRINK_VERSION_PATCH 1 #define HEATSHRINK_MIN_WINDOW_BITS 4 #define HEATSHRINK_MAX_WINDOW_BITS 15 #define HEATSHRINK_MIN_LOOKAHEAD_BITS 3 #define HEATSHRINK_LITERAL_MARKER 0x01 #define HEATSHRINK_BACKREF_MARKER 0x00
2301_81045437/Marlin
Marlin/src/libs/heatshrink/heatshrink_common.h
C
agpl-3.0
503
/** * libs/heatshrink/heatshrink_config.h */ #pragma once // Should functionality assuming dynamic allocation be used? #ifndef HEATSHRINK_DYNAMIC_ALLOC //#define HEATSHRINK_DYNAMIC_ALLOC 1 #endif #if HEATSHRINK_DYNAMIC_ALLOC // Optional replacement of malloc/free #define HEATSHRINK_MALLOC(SZ) malloc(SZ) #define HEATSHRINK_FREE(P, SZ) free(P) #else // Required parameters for static configuration #define HEATSHRINK_STATIC_INPUT_BUFFER_SIZE 32 #define HEATSHRINK_STATIC_WINDOW_BITS 8 #define HEATSHRINK_STATIC_LOOKAHEAD_BITS 4 #endif // Turn on logging for debugging #define HEATSHRINK_DEBUGGING_LOGS 0 // Use indexing for faster compression. (This requires additional space.) #define HEATSHRINK_USE_INDEX 1
2301_81045437/Marlin
Marlin/src/libs/heatshrink/heatshrink_config.h
C
agpl-3.0
731
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../../inc/MarlinConfigPre.h" #if ENABLED(BINARY_FILE_TRANSFER) /** * libs/heatshrink/heatshrink_decoder.cpp */ #include "heatshrink_decoder.h" #include <stdlib.h> #include <string.h> #pragma GCC optimize ("O3") /* States for the polling state machine. */ typedef enum { HSDS_TAG_BIT, /* tag bit */ HSDS_YIELD_LITERAL, /* ready to yield literal byte */ HSDS_BACKREF_INDEX_MSB, /* most significant byte of index */ HSDS_BACKREF_INDEX_LSB, /* least significant byte of index */ HSDS_BACKREF_COUNT_MSB, /* most significant byte of count */ HSDS_BACKREF_COUNT_LSB, /* least significant byte of count */ HSDS_YIELD_BACKREF /* ready to yield back-reference */ } HSD_state; #if HEATSHRINK_DEBUGGING_LOGS #include <stdio.h> #include <ctype.h> #include <assert.h> #define LOG(...) fprintf(stderr, __VA_ARGS__) #define ASSERT(X) assert(X) static const char *state_names[] = { "tag_bit", "yield_literal", "backref_index_msb", "backref_index_lsb", "backref_count_msb", "backref_count_lsb", "yield_backref" }; #else #define LOG(...) /* no-op */ #define ASSERT(X) /* no-op */ #endif typedef struct { uint8_t *buf; /* output buffer */ size_t buf_size; /* buffer size */ size_t *output_size; /* bytes pushed to buffer, so far */ } output_info; #define NO_BITS ((uint16_t)-1) /* Forward references. */ static uint16_t get_bits(heatshrink_decoder *hsd, uint8_t count); static void push_byte(heatshrink_decoder *hsd, output_info *oi, uint8_t byte); #if HEATSHRINK_DYNAMIC_ALLOC heatshrink_decoder *heatshrink_decoder_alloc(uint16_t input_buffer_size, uint8_t window_sz2, uint8_t lookahead_sz2) { if ((window_sz2 < HEATSHRINK_MIN_WINDOW_BITS) || (window_sz2 > HEATSHRINK_MAX_WINDOW_BITS) || (input_buffer_size == 0) || (lookahead_sz2 < HEATSHRINK_MIN_LOOKAHEAD_BITS) || (lookahead_sz2 >= window_sz2)) { return nullptr; } size_t buffers_sz = (1 << window_sz2) + input_buffer_size; size_t sz = sizeof(heatshrink_decoder) + buffers_sz; heatshrink_decoder *hsd = HEATSHRINK_MALLOC(sz); if (!hsd) return nullptr; hsd->input_buffer_size = input_buffer_size; hsd->window_sz2 = window_sz2; hsd->lookahead_sz2 = lookahead_sz2; heatshrink_decoder_reset(hsd); LOG("-- allocated decoder with buffer size of %zu (%zu + %u + %u)\n", sz, sizeof(heatshrink_decoder), (1 << window_sz2), input_buffer_size); return hsd; } void heatshrink_decoder_free(heatshrink_decoder *hsd) { size_t buffers_sz = (1 << hsd->window_sz2) + hsd->input_buffer_size; size_t sz = sizeof(heatshrink_decoder) + buffers_sz; HEATSHRINK_FREE(hsd, sz); (void)sz; /* may not be used by free */ } #endif void heatshrink_decoder_reset(heatshrink_decoder *hsd) { size_t buf_sz = 1 << HEATSHRINK_DECODER_WINDOW_BITS(hsd); size_t input_sz = HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(hsd); memset(hsd->buffers, 0, buf_sz + input_sz); hsd->state = HSDS_TAG_BIT; hsd->input_size = 0; hsd->input_index = 0; hsd->bit_index = 0x00; hsd->current_byte = 0x00; hsd->output_count = 0; hsd->output_index = 0; hsd->head_index = 0; } /* Copy SIZE bytes into the decoder's input buffer, if it will fit. */ HSD_sink_res heatshrink_decoder_sink(heatshrink_decoder *hsd, uint8_t *in_buf, size_t size, size_t *input_size) { if (!hsd || !in_buf || !input_size) return HSDR_SINK_ERROR_NULL; size_t rem = HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(hsd) - hsd->input_size; if (rem == 0) { *input_size = 0; return HSDR_SINK_FULL; } size = rem < size ? rem : size; LOG("-- sinking %zd bytes\n", size); /* copy into input buffer (at head of buffers) */ memcpy(&hsd->buffers[hsd->input_size], in_buf, size); hsd->input_size += size; *input_size = size; return HSDR_SINK_OK; } /***************** * Decompression * *****************/ #define BACKREF_COUNT_BITS(HSD) (HEATSHRINK_DECODER_LOOKAHEAD_BITS(HSD)) #define BACKREF_INDEX_BITS(HSD) (HEATSHRINK_DECODER_WINDOW_BITS(HSD)) // States static HSD_state st_tag_bit(heatshrink_decoder *hsd); static HSD_state st_yield_literal(heatshrink_decoder *hsd, output_info *oi); static HSD_state st_backref_index_msb(heatshrink_decoder *hsd); static HSD_state st_backref_index_lsb(heatshrink_decoder *hsd); static HSD_state st_backref_count_msb(heatshrink_decoder *hsd); static HSD_state st_backref_count_lsb(heatshrink_decoder *hsd); static HSD_state st_yield_backref(heatshrink_decoder *hsd, output_info *oi); HSD_poll_res heatshrink_decoder_poll(heatshrink_decoder *hsd, uint8_t *out_buf, size_t out_buf_size, size_t *output_size) { if (!hsd || !out_buf || !output_size) return HSDR_POLL_ERROR_NULL; *output_size = 0; output_info oi; oi.buf = out_buf; oi.buf_size = out_buf_size; oi.output_size = output_size; while (1) { LOG("-- poll, state is %d (%s), input_size %d\n", hsd->state, state_names[hsd->state], hsd->input_size); uint8_t in_state = hsd->state; switch (in_state) { case HSDS_TAG_BIT: hsd->state = st_tag_bit(hsd); break; case HSDS_YIELD_LITERAL: hsd->state = st_yield_literal(hsd, &oi); break; case HSDS_BACKREF_INDEX_MSB: hsd->state = st_backref_index_msb(hsd); break; case HSDS_BACKREF_INDEX_LSB: hsd->state = st_backref_index_lsb(hsd); break; case HSDS_BACKREF_COUNT_MSB: hsd->state = st_backref_count_msb(hsd); break; case HSDS_BACKREF_COUNT_LSB: hsd->state = st_backref_count_lsb(hsd); break; case HSDS_YIELD_BACKREF: hsd->state = st_yield_backref(hsd, &oi); break; default: return HSDR_POLL_ERROR_UNKNOWN; } // If the current state cannot advance, check if input or output // buffer are exhausted. if (hsd->state == in_state) return (*output_size == out_buf_size) ? HSDR_POLL_MORE : HSDR_POLL_EMPTY; } } static HSD_state st_tag_bit(heatshrink_decoder *hsd) { uint32_t bits = get_bits(hsd, 1); // get tag bit if (bits == NO_BITS) return HSDS_TAG_BIT; else if (bits) return HSDS_YIELD_LITERAL; else if (HEATSHRINK_DECODER_WINDOW_BITS(hsd) > 8) return HSDS_BACKREF_INDEX_MSB; else { hsd->output_index = 0; return HSDS_BACKREF_INDEX_LSB; } } static HSD_state st_yield_literal(heatshrink_decoder *hsd, output_info *oi) { /* Emit a repeated section from the window buffer, and add it (again) * to the window buffer. (Note that the repetition can include * itself.)*/ if (*oi->output_size < oi->buf_size) { uint16_t byte = get_bits(hsd, 8); if (byte == NO_BITS) { return HSDS_YIELD_LITERAL; } /* out of input */ uint8_t *buf = &hsd->buffers[HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(hsd)]; uint16_t mask = (1 << HEATSHRINK_DECODER_WINDOW_BITS(hsd)) - 1; uint8_t c = byte & 0xFF; LOG("-- emitting literal byte 0x%02x ('%c')\n", c, isprint(c) ? c : '.'); buf[hsd->head_index++ & mask] = c; push_byte(hsd, oi, c); return HSDS_TAG_BIT; } return HSDS_YIELD_LITERAL; } static HSD_state st_backref_index_msb(heatshrink_decoder *hsd) { uint8_t bit_ct = BACKREF_INDEX_BITS(hsd); ASSERT(bit_ct > 8); uint16_t bits = get_bits(hsd, bit_ct - 8); LOG("-- backref index (msb), got 0x%04x (+1)\n", bits); if (bits == NO_BITS) { return HSDS_BACKREF_INDEX_MSB; } hsd->output_index = bits << 8; return HSDS_BACKREF_INDEX_LSB; } static HSD_state st_backref_index_lsb(heatshrink_decoder *hsd) { uint8_t bit_ct = BACKREF_INDEX_BITS(hsd); uint16_t bits = get_bits(hsd, bit_ct < 8 ? bit_ct : 8); LOG("-- backref index (lsb), got 0x%04x (+1)\n", bits); if (bits == NO_BITS) { return HSDS_BACKREF_INDEX_LSB; } hsd->output_index |= bits; hsd->output_index++; uint8_t br_bit_ct = BACKREF_COUNT_BITS(hsd); hsd->output_count = 0; return (br_bit_ct > 8) ? HSDS_BACKREF_COUNT_MSB : HSDS_BACKREF_COUNT_LSB; } static HSD_state st_backref_count_msb(heatshrink_decoder *hsd) { uint8_t br_bit_ct = BACKREF_COUNT_BITS(hsd); ASSERT(br_bit_ct > 8); uint16_t bits = get_bits(hsd, br_bit_ct - 8); LOG("-- backref count (msb), got 0x%04x (+1)\n", bits); if (bits == NO_BITS) { return HSDS_BACKREF_COUNT_MSB; } hsd->output_count = bits << 8; return HSDS_BACKREF_COUNT_LSB; } static HSD_state st_backref_count_lsb(heatshrink_decoder *hsd) { uint8_t br_bit_ct = BACKREF_COUNT_BITS(hsd); uint16_t bits = get_bits(hsd, br_bit_ct < 8 ? br_bit_ct : 8); LOG("-- backref count (lsb), got 0x%04x (+1)\n", bits); if (bits == NO_BITS) { return HSDS_BACKREF_COUNT_LSB; } hsd->output_count |= bits; hsd->output_count++; return HSDS_YIELD_BACKREF; } static HSD_state st_yield_backref(heatshrink_decoder *hsd, output_info *oi) { size_t count = oi->buf_size - *oi->output_size; if (count > 0) { size_t i = 0; if (hsd->output_count < count) count = hsd->output_count; uint8_t *buf = &hsd->buffers[HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(hsd)]; uint16_t mask = (1 << HEATSHRINK_DECODER_WINDOW_BITS(hsd)) - 1; uint16_t neg_offset = hsd->output_index; LOG("-- emitting %zu bytes from -%u bytes back\n", count, neg_offset); ASSERT(neg_offset <= mask + 1); ASSERT(count <= (size_t)(1 << BACKREF_COUNT_BITS(hsd))); for (i = 0; i < count; i++) { uint8_t c = buf[(hsd->head_index - neg_offset) & mask]; push_byte(hsd, oi, c); buf[hsd->head_index & mask] = c; hsd->head_index++; LOG(" -- ++ 0x%02x\n", c); } hsd->output_count -= count; if (hsd->output_count == 0) { return HSDS_TAG_BIT; } } return HSDS_YIELD_BACKREF; } /* Get the next COUNT bits from the input buffer, saving incremental progress. * Returns NO_BITS on end of input, or if more than 15 bits are requested. */ static uint16_t get_bits(heatshrink_decoder *hsd, uint8_t count) { uint16_t accumulator = 0; int i = 0; if (count > 15) return NO_BITS; LOG("-- popping %u bit(s)\n", count); /* If we aren't able to get COUNT bits, suspend immediately, because we * don't track how many bits of COUNT we've accumulated before suspend. */ if (hsd->input_size == 0 && hsd->bit_index < (1 << (count - 1))) return NO_BITS; for (i = 0; i < count; i++) { if (hsd->bit_index == 0x00) { if (hsd->input_size == 0) { LOG(" -- out of bits, suspending w/ accumulator of %u (0x%02x)\n", accumulator, accumulator); return NO_BITS; } hsd->current_byte = hsd->buffers[hsd->input_index++]; LOG(" -- pulled byte 0x%02x\n", hsd->current_byte); if (hsd->input_index == hsd->input_size) { hsd->input_index = 0; /* input is exhausted */ hsd->input_size = 0; } hsd->bit_index = 0x80; } accumulator <<= 1; if (hsd->current_byte & hsd->bit_index) { accumulator |= 0x01; if (0) { LOG(" -- got 1, accumulator 0x%04x, bit_index 0x%02x\n", accumulator, hsd->bit_index); } } else if (0) { LOG(" -- got 0, accumulator 0x%04x, bit_index 0x%02x\n", accumulator, hsd->bit_index); } hsd->bit_index >>= 1; } if (count > 1) LOG(" -- accumulated %08x\n", accumulator); return accumulator; } HSD_finish_res heatshrink_decoder_finish(heatshrink_decoder *hsd) { if (!hsd) return HSDR_FINISH_ERROR_NULL; switch (hsd->state) { case HSDS_TAG_BIT: return hsd->input_size == 0 ? HSDR_FINISH_DONE : HSDR_FINISH_MORE; /* If we want to finish with no input, but are in these states, it's * because the 0-bit padding to the last byte looks like a backref * marker bit followed by all 0s for index and count bits. */ case HSDS_BACKREF_INDEX_LSB: case HSDS_BACKREF_INDEX_MSB: case HSDS_BACKREF_COUNT_LSB: case HSDS_BACKREF_COUNT_MSB: return hsd->input_size == 0 ? HSDR_FINISH_DONE : HSDR_FINISH_MORE; /* If the output stream is padded with 0xFFs (possibly due to being in * flash memory), also explicitly check the input size rather than * uselessly returning MORE but yielding 0 bytes when polling. */ case HSDS_YIELD_LITERAL: return hsd->input_size == 0 ? HSDR_FINISH_DONE : HSDR_FINISH_MORE; default: return HSDR_FINISH_MORE; } } static void push_byte(heatshrink_decoder *hsd, output_info *oi, uint8_t byte) { LOG(" -- pushing byte: 0x%02x ('%c')\n", byte, isprint(byte) ? byte : '.'); oi->buf[(*oi->output_size)++] = byte; (void)hsd; } #endif // BINARY_FILE_TRANSFER
2301_81045437/Marlin
Marlin/src/libs/heatshrink/heatshrink_decoder.cpp
C++
agpl-3.0
13,353
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * libs/heatshrink/heatshrink_decoder.h */ #pragma once #include "heatshrink_common.h" #include "heatshrink_config.h" #include <stdint.h> #include <stddef.h> typedef enum { HSDR_SINK_OK, /* data sunk, ready to poll */ HSDR_SINK_FULL, /* out of space in internal buffer */ HSDR_SINK_ERROR_NULL=-1, /* NULL argument */ } HSD_sink_res; typedef enum { HSDR_POLL_EMPTY, /* input exhausted */ HSDR_POLL_MORE, /* more data remaining, call again w/ fresh output buffer */ HSDR_POLL_ERROR_NULL=-1, /* NULL arguments */ HSDR_POLL_ERROR_UNKNOWN=-2, } HSD_poll_res; typedef enum { HSDR_FINISH_DONE, /* output is done */ HSDR_FINISH_MORE, /* more output remains */ HSDR_FINISH_ERROR_NULL=-1, /* NULL arguments */ } HSD_finish_res; #if HEATSHRINK_DYNAMIC_ALLOC #define HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(BUF) \ ((BUF)->input_buffer_size) #define HEATSHRINK_DECODER_WINDOW_BITS(BUF) \ ((BUF)->window_sz2) #define HEATSHRINK_DECODER_LOOKAHEAD_BITS(BUF) \ ((BUF)->lookahead_sz2) #else #define HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(_) \ HEATSHRINK_STATIC_INPUT_BUFFER_SIZE #define HEATSHRINK_DECODER_WINDOW_BITS(_) \ (HEATSHRINK_STATIC_WINDOW_BITS) #define HEATSHRINK_DECODER_LOOKAHEAD_BITS(BUF) \ (HEATSHRINK_STATIC_LOOKAHEAD_BITS) #endif typedef struct { uint16_t input_size; /* bytes in input buffer */ uint16_t input_index; /* offset to next unprocessed input byte */ uint16_t output_count; /* how many bytes to output */ uint16_t output_index; /* index for bytes to output */ uint16_t head_index; /* head of window buffer */ uint8_t state; /* current state machine node */ uint8_t current_byte; /* current byte of input */ uint8_t bit_index; /* current bit index */ #if HEATSHRINK_DYNAMIC_ALLOC /* Fields that are only used if dynamically allocated. */ uint8_t window_sz2; /* window buffer bits */ uint8_t lookahead_sz2; /* lookahead bits */ uint16_t input_buffer_size; /* input buffer size */ /* Input buffer, then expansion window buffer */ uint8_t buffers[]; #else /* Input buffer, then expansion window buffer */ uint8_t buffers[(1 << HEATSHRINK_DECODER_WINDOW_BITS(_)) + HEATSHRINK_DECODER_INPUT_BUFFER_SIZE(_)]; #endif } heatshrink_decoder; #if HEATSHRINK_DYNAMIC_ALLOC /* Allocate a decoder with an input buffer of INPUT_BUFFER_SIZE bytes, * an expansion buffer size of 2^WINDOW_SZ2, and a lookahead * size of 2^lookahead_sz2. (The window buffer and lookahead sizes * must match the settings used when the data was compressed.) * Returns NULL on error. */ heatshrink_decoder *heatshrink_decoder_alloc(uint16_t input_buffer_size, uint8_t expansion_buffer_sz2, uint8_t lookahead_sz2); /* Free a decoder. */ void heatshrink_decoder_free(heatshrink_decoder *hsd); #endif /* Reset a decoder. */ void heatshrink_decoder_reset(heatshrink_decoder *hsd); /* Sink at most SIZE bytes from IN_BUF into the decoder. *INPUT_SIZE is set to * indicate how many bytes were actually sunk (in case a buffer was filled). */ HSD_sink_res heatshrink_decoder_sink(heatshrink_decoder *hsd, uint8_t *in_buf, size_t size, size_t *input_size); /* Poll for output from the decoder, copying at most OUT_BUF_SIZE bytes into * OUT_BUF (setting *OUTPUT_SIZE to the actual amount copied). */ HSD_poll_res heatshrink_decoder_poll(heatshrink_decoder *hsd, uint8_t *out_buf, size_t out_buf_size, size_t *output_size); /* Notify the dencoder that the input stream is finished. * If the return value is HSDR_FINISH_MORE, there is still more output, so * call heatshrink_decoder_poll and repeat. */ HSD_finish_res heatshrink_decoder_finish(heatshrink_decoder *hsd);
2301_81045437/Marlin
Marlin/src/libs/heatshrink/heatshrink_decoder.h
C
agpl-3.0
4,624
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 NEED_HEX_PRINT #include "hex_print.h" #include "../core/serial.h" static char _hex[] = "0x00000000"; // 0:adr32 2:long 4:adr16 6:word 8:byte inline void __hex_byte(const uint8_t b, const uint8_t o=8) { _hex[o + 0] = hex_nybble(b >> 4); _hex[o + 1] = hex_nybble(b); } inline void __hex_word(const uint16_t w, const uint8_t o=6) { __hex_byte(w >> 8, o + 0); __hex_byte(w , o + 2); } inline void __hex_long(const uint32_t w) { __hex_word(w >> 16, 2); __hex_word(w , 6); } char* hex_byte(const uint8_t b) { __hex_byte(b); return &_hex[8]; } char* _hex_word(const uint16_t w) { __hex_word(w); return &_hex[6]; } char* _hex_long(const uint32_t l) { __hex_long(l); return &_hex[2]; } char* hex_address(const void * const a) { #ifdef CPU_32_BIT (void)_hex_long((uintptr_t)a); return _hex; #else _hex[4] = '0'; _hex[5] = 'x'; (void)_hex_word((uintptr_t)a); return &_hex[4]; #endif } void print_hex_nybble(const uint8_t n) { SERIAL_CHAR(hex_nybble(n)); } void print_hex_byte(const uint8_t b) { SERIAL_ECHO(hex_byte(b)); } void print_hex_word(const uint16_t w) { SERIAL_ECHO(_hex_word(w)); } void print_hex_address(const void * const w) { SERIAL_ECHO(hex_address(w)); } void print_hex_long(const uint32_t w, const char delimiter/*='\0'*/, const bool prefix/*=false*/) { if (prefix) SERIAL_ECHOPGM("0x"); for (int B = 24; B >= 8; B -= 8) { print_hex_byte(w >> B); if (delimiter) SERIAL_CHAR(delimiter); } print_hex_byte(w); } #endif // NEED_HEX_PRINT
2301_81045437/Marlin
Marlin/src/libs/hex_print.cpp
C++
agpl-3.0
2,441
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include <stdint.h> // // Utility functions to create and print hex strings as nybble, byte, and word. // constexpr char hex_nybble(const uint8_t n) { return (n & 0xF) + ((n & 0xF) < 10 ? '0' : 'A' - 10); } char* _hex_word(const uint16_t w); char* _hex_long(const uint32_t l); char* hex_byte(const uint8_t b); template<typename T> char* hex_word(T w) { return _hex_word((uint16_t)w); } template<typename T> char* hex_long(T w) { return _hex_long((uint32_t)w); } char* hex_address(const void * const w); void print_hex_nybble(const uint8_t n); void print_hex_byte(const uint8_t b); void print_hex_word(const uint16_t w); void print_hex_address(const void * const w); void print_hex_long(const uint32_t w, const char delimiter='\0', const bool prefix=false);
2301_81045437/Marlin
Marlin/src/libs/hex_print.h
C++
agpl-3.0
1,640
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * Least Squares Best Fit by Roxy and Ed Williams * * This algorithm is high speed and has a very small code footprint. * Its results are identical to both the Iterative Least-Squares published * earlier by Roxy and the QR_SOLVE solution. If used in place of QR_SOLVE * it saves roughly 10K of program memory. It also does not require all of * coordinates to be present during the calculations. Each point can be * probed and then discarded. */ #include "../inc/MarlinConfig.h" #if NEED_LSF #include "least_squares_fit.h" #include <math.h> int finish_incremental_LSF(struct linear_fit_data *lsf) { const float N = lsf->N; if (N == 0.0) return 1; const float RN = 1.0f / N, xbar = lsf->xbar * RN, ybar = lsf->ybar * RN, zbar = lsf->zbar * RN, x2bar = lsf->x2bar * RN - sq(xbar), y2bar = lsf->y2bar * RN - sq(ybar), xybar = lsf->xybar * RN - xbar * ybar, yzbar = lsf->yzbar * RN - ybar * zbar, xzbar = lsf->xzbar * RN - xbar * zbar, DD = x2bar * y2bar - sq(xybar); if (ABS(DD) <= 1e-10 * (lsf->max_absx + lsf->max_absy)) return 1; lsf->A = (yzbar * xybar - xzbar * y2bar) / DD; lsf->B = (xzbar * xybar - yzbar * x2bar) / DD; lsf->D = -(zbar + lsf->A * xbar + lsf->B * ybar); return 0; } #endif // NEED_LSF
2301_81045437/Marlin
Marlin/src/libs/least_squares_fit.cpp
C++
agpl-3.0
2,240
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 /** * Incremental Least Squares Best Fit By Roxy and Ed Williams * * This algorithm is high speed and has a very small code footprint. * Its results are identical to both the Iterative Least-Squares published * earlier by Roxy and the QR_SOLVE solution. If used in place of QR_SOLVE * it saves roughly 10K of program memory. And even better... the data * fed into the algorithm does not need to all be present at the same time. * A point can be probed and its values fed into the algorithm and then discarded. */ #include "../inc/MarlinConfig.h" #include <math.h> struct linear_fit_data { float xbar, ybar, zbar, x2bar, y2bar, xybar, xzbar, yzbar, max_absx, max_absy, A, B, D, N; }; inline void incremental_LSF_reset(struct linear_fit_data *lsf) { memset(lsf, 0, sizeof(linear_fit_data)); } inline void incremental_WLSF(struct linear_fit_data *lsf, const_float_t x, const_float_t y, const_float_t z, const_float_t w) { // weight each accumulator by factor w, including the "number" of samples // (analogous to calling inc_LSF twice with same values to weight it by 2X) const float wx = w * x, wy = w * y, wz = w * z; lsf->xbar += wx; lsf->ybar += wy; lsf->zbar += wz; lsf->x2bar += wx * x; lsf->y2bar += wy * y; lsf->xybar += wx * y; lsf->xzbar += wx * z; lsf->yzbar += wy * z; lsf->N += w; lsf->max_absx = _MAX(ABS(wx), lsf->max_absx); lsf->max_absy = _MAX(ABS(wy), lsf->max_absy); } inline void incremental_WLSF(struct linear_fit_data *lsf, const xy_pos_t &pos, const_float_t z, const_float_t w) { incremental_WLSF(lsf, pos.x, pos.y, z, w); } inline void incremental_LSF(struct linear_fit_data *lsf, const_float_t x, const_float_t y, const_float_t z) { lsf->xbar += x; lsf->ybar += y; lsf->zbar += z; lsf->x2bar += sq(x); lsf->y2bar += sq(y); lsf->xybar += x * y; lsf->xzbar += x * z; lsf->yzbar += y * z; lsf->max_absx = _MAX(ABS(x), lsf->max_absx); lsf->max_absy = _MAX(ABS(y), lsf->max_absy); lsf->N += 1.0; } inline void incremental_LSF(struct linear_fit_data *lsf, const xy_pos_t &pos, const_float_t z) { incremental_LSF(lsf, pos.x, pos.y, z); } int finish_incremental_LSF(struct linear_fit_data *);
2301_81045437/Marlin
Marlin/src/libs/least_squares_fit.h
C
agpl-3.0
3,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 ANY(NOZZLE_CLEAN_FEATURE, NOZZLE_PARK_FEATURE) #include "nozzle.h" Nozzle nozzle; #include "../MarlinCore.h" #include "../module/motion.h" #if NOZZLE_CLEAN_MIN_TEMP > 20 #include "../module/temperature.h" #endif #if ENABLED(NOZZLE_CLEAN_FEATURE) #if ENABLED(NOZZLE_CLEAN_PATTERN_LINE) /** * @brief Stroke clean pattern * @details Wipes the nozzle back and forth in a linear movement * * @param start xyz_pos_t defining the starting point * @param end xyz_pos_t defining the ending point * @param strokes number of strokes to execute */ void Nozzle::stroke(const xyz_pos_t &start, const xyz_pos_t &end, const uint8_t strokes) { #if ENABLED(NOZZLE_CLEAN_GOBACK) const xyz_pos_t oldpos = current_position; #endif // Move to the starting point #if ENABLED(NOZZLE_CLEAN_NO_Z) #if ENABLED(NOZZLE_CLEAN_NO_Y) do_blocking_move_to_x(start.x); #else do_blocking_move_to_xy(start); #endif #else do_blocking_move_to(start); #endif // Start the stroke pattern for (uint8_t i = 0; i < strokes >> 1; ++i) { #if ENABLED(NOZZLE_CLEAN_NO_Y) do_blocking_move_to_x(end.x); do_blocking_move_to_x(start.x); #else do_blocking_move_to_xy(end); do_blocking_move_to_xy(start); #endif } TERN_(NOZZLE_CLEAN_GOBACK, do_blocking_move_to(oldpos)); } #endif #if ENABLED(NOZZLE_CLEAN_PATTERN_ZIGZAG) /** * @brief Zig-zag clean pattern * @details Apply a zig-zag cleaning pattern * * @param start xyz_pos_t defining the starting point * @param end xyz_pos_t defining the ending point * @param strokes number of strokes to execute * @param objects number of triangles to do */ void Nozzle::zigzag(const xyz_pos_t &start, const xyz_pos_t &end, const uint8_t strokes, const uint8_t objects) { const xy_pos_t diff = end - start; if (!diff.x || !diff.y) return; #if ENABLED(NOZZLE_CLEAN_GOBACK) const xyz_pos_t back = current_position; #endif #if ENABLED(NOZZLE_CLEAN_NO_Z) do_blocking_move_to_xy(start); #else do_blocking_move_to(start); #endif const uint8_t zigs = objects << 1; const bool horiz = ABS(diff.x) >= ABS(diff.y); // Do a horizontal wipe? const float P = (horiz ? diff.x : diff.y) / zigs; // Period of each zig / zag const xyz_pos_t *side; for (uint8_t j = 0; j < strokes; ++j) { for (int8_t i = 0; i < zigs; i++) { side = (i & 1) ? &end : &start; if (horiz) do_blocking_move_to_xy(start.x + i * P, side->y); else do_blocking_move_to_xy(side->x, start.y + i * P); } for (int8_t i = zigs; i >= 0; i--) { side = (i & 1) ? &end : &start; if (horiz) do_blocking_move_to_xy(start.x + i * P, side->y); else do_blocking_move_to_xy(side->x, start.y + i * P); } } TERN_(NOZZLE_CLEAN_GOBACK, do_blocking_move_to(back)); } #endif #if ENABLED(NOZZLE_CLEAN_PATTERN_CIRCLE) /** * @brief Circular clean pattern * @details Apply a circular cleaning pattern * * @param start xyz_pos_t defining the middle of circle * @param strokes number of strokes to execute * @param radius radius of circle */ void Nozzle::circle(const xyz_pos_t &start, const xyz_pos_t &middle, const uint8_t strokes, const_float_t radius) { if (strokes == 0) return; #if ENABLED(NOZZLE_CLEAN_GOBACK) const xyz_pos_t back = current_position; #endif TERN(NOZZLE_CLEAN_NO_Z, do_blocking_move_to_xy, do_blocking_move_to)(start); for (uint8_t s = 0; s < strokes; ++s) for (uint8_t i = 0; i < NOZZLE_CLEAN_CIRCLE_FN; ++i) do_blocking_move_to_xy( middle.x + sin((RADIANS(360) / NOZZLE_CLEAN_CIRCLE_FN) * i) * radius, middle.y + cos((RADIANS(360) / NOZZLE_CLEAN_CIRCLE_FN) * i) * radius ); // Let's be safe do_blocking_move_to_xy(start); TERN_(NOZZLE_CLEAN_GOBACK, do_blocking_move_to(back)); } #endif /** * @brief Clean the nozzle * @details Starts the selected clean procedure pattern * * @param pattern one of the available patterns * @param argument depends on the cleaning pattern */ void Nozzle::clean(const uint8_t pattern, const uint8_t strokes, const_float_t radius, const uint8_t objects, const uint8_t cleans) { xyz_pos_t start[HOTENDS] = NOZZLE_CLEAN_START_POINT, end[HOTENDS] = NOZZLE_CLEAN_END_POINT; #if ENABLED(NOZZLE_CLEAN_PATTERN_CIRCLE) xyz_pos_t middle[HOTENDS] = NOZZLE_CLEAN_CIRCLE_MIDDLE; #endif const uint8_t arrPos = ANY(SINGLENOZZLE, MIXING_EXTRUDER) ? 0 : active_extruder; switch (pattern) { #if DISABLED(NOZZLE_CLEAN_PATTERN_LINE) case 0: SERIAL_ECHOLNPGM("Pattern ", F("LINE"), " not enabled."); return; #endif #if DISABLED(NOZZLE_CLEAN_PATTERN_ZIGZAG) case 1: SERIAL_ECHOLNPGM("Pattern ", F("ZIGZAG"), " not enabled."); return; #endif #if DISABLED(NOZZLE_CLEAN_PATTERN_CIRCLE) case 2: SERIAL_ECHOLNPGM("Pattern ", F("CIRCULAR"), " not enabled."); return; #endif } #if NOZZLE_CLEAN_MIN_TEMP > 20 if (thermalManager.degTargetHotend(arrPos) < NOZZLE_CLEAN_MIN_TEMP) { #if ENABLED(NOZZLE_CLEAN_HEATUP) SERIAL_ECHOLNPGM("Nozzle too Cold - Heating"); thermalManager.setTargetHotend(NOZZLE_CLEAN_MIN_TEMP, arrPos); thermalManager.wait_for_hotend(arrPos); #else SERIAL_ECHOLNPGM("Nozzle too cold - Skipping wipe"); return; #endif } #endif #if HAS_SOFTWARE_ENDSTOPS #define LIMIT_AXIS(A) do{ \ LIMIT( start[arrPos].A, soft_endstop.min.A, soft_endstop.max.A); \ LIMIT( end[arrPos].A, soft_endstop.min.A, soft_endstop.max.A); \ TERN_(NOZZLE_CLEAN_PATTERN_CIRCLE, LIMIT(middle[arrPos].A, soft_endstop.min.A, soft_endstop.max.A)); \ }while(0) if (soft_endstop.enabled()) { LIMIT_AXIS(x); LIMIT_AXIS(y); LIMIT_AXIS(z); #if ENABLED(NOZZLE_CLEAN_PATTERN_CIRCLE) if (pattern == 2 && !(WITHIN(middle[arrPos].x, soft_endstop.min.x + radius, soft_endstop.max.x - radius) && WITHIN(middle[arrPos].y, soft_endstop.min.y + radius, soft_endstop.max.y - radius)) ) { SERIAL_ECHOLNPGM("Warning: Radius Out of Range"); return; } #endif } #endif #if ENABLED(NOZZLE_CLEAN_PATTERN_CIRCLE) if (pattern == 2 && !(cleans & (_BV(X_AXIS) | _BV(Y_AXIS)))) { SERIAL_ECHOLNPGM("Warning: Clean Circle requires XY"); return; } #endif if (TERN1(NOZZLE_CLEAN_PATTERN_CIRCLE, pattern != 2)) { if (!TEST(cleans, X_AXIS)) start[arrPos].x = end[arrPos].x = current_position.x; if (!TEST(cleans, Y_AXIS)) start[arrPos].y = end[arrPos].y = current_position.y; } if (!TEST(cleans, Z_AXIS)) start[arrPos].z = end[arrPos].z = current_position.z; switch (pattern) { // no default clause as pattern is already validated #if ENABLED(NOZZLE_CLEAN_PATTERN_LINE) case 0: stroke(start[arrPos], end[arrPos], strokes); break; #endif #if ENABLED(NOZZLE_CLEAN_PATTERN_ZIGZAG) case 1: zigzag(start[arrPos], end[arrPos], strokes, objects); break; #endif #if ENABLED(NOZZLE_CLEAN_PATTERN_CIRCLE) case 2: circle(start[arrPos], middle[arrPos], strokes, radius); break; #endif } } #endif // NOZZLE_CLEAN_FEATURE #if ENABLED(NOZZLE_PARK_FEATURE) #if HAS_Z_AXIS float Nozzle::park_mode_0_height(const_float_t park_z) { // Apply a minimum raise, if specified. Use park.z as a minimum height instead. return _MAX(park_z, // Minimum height over 0 based on input _MIN(Z_MAX_POS, // Maximum height is fixed #ifdef NOZZLE_PARK_Z_RAISE_MIN NOZZLE_PARK_Z_RAISE_MIN + // Minimum raise... #endif current_position.z // ...over current position ) ); } #endif // HAS_Z_AXIS void Nozzle::park(const uint8_t z_action, const xyz_pos_t &park/*=NOZZLE_PARK_POINT*/) { #if HAS_Z_AXIS constexpr feedRate_t fr_z = NOZZLE_PARK_Z_FEEDRATE; switch (z_action) { case 1: // Go to Z-park height do_blocking_move_to_z(park.z, fr_z); break; case 2: // Raise by Z-park height do_blocking_move_to_z(_MIN(current_position.z + park.z, Z_MAX_POS), fr_z); break; case 3: { // Raise by NOZZLE_PARK_Z_RAISE_MIN, bypass XY-park position do_blocking_move_to_z(park_mode_0_height(0), fr_z); goto SKIP_XY_MOVE; } break; case 4: // Skip Z raise, go to XY position break; default: // Raise by NOZZLE_PARK_Z_RAISE_MIN, use park.z as a minimum height do_blocking_move_to_z(park_mode_0_height(park.z), fr_z); break; } #endif // HAS_Z_AXIS { #ifndef NOZZLE_PARK_MOVE #define NOZZLE_PARK_MOVE 0 #endif constexpr feedRate_t fr_xy = NOZZLE_PARK_XY_FEEDRATE; switch (NOZZLE_PARK_MOVE) { case 0: do_blocking_move_to_xy(park, fr_xy); break; case 1: do_blocking_move_to_x(park.x, fr_xy); break; case 2: do_blocking_move_to_y(park.y, fr_xy); break; case 3: do_blocking_move_to_x(park.x, fr_xy); do_blocking_move_to_y(park.y, fr_xy); break; case 4: do_blocking_move_to_y(park.y, fr_xy); do_blocking_move_to_x(park.x, fr_xy); break; } } SKIP_XY_MOVE: report_current_position(); } #endif // NOZZLE_PARK_FEATURE #endif // NOZZLE_CLEAN_FEATURE || NOZZLE_PARK_FEATURE
2301_81045437/Marlin
Marlin/src/libs/nozzle.cpp
C++
agpl-3.0
10,951
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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" /** * @brief Nozzle class * * @todo: Do not ignore the end.z value and allow XYZ movements */ class Nozzle { private: #if ENABLED(NOZZLE_CLEAN_FEATURE) /** * @brief Stroke clean pattern * @details Wipes the nozzle back and forth in a linear movement * * @param start xyz_pos_t defining the starting point * @param end xyz_pos_t defining the ending point * @param strokes number of strokes to execute */ static void stroke(const xyz_pos_t &start, const xyz_pos_t &end, const uint8_t strokes) __Os; /** * @brief Zig-zag clean pattern * @details Apply a zig-zag cleaning pattern * * @param start xyz_pos_t defining the starting point * @param end xyz_pos_t defining the ending point * @param strokes number of strokes to execute * @param objects number of objects to create */ static void zigzag(const xyz_pos_t &start, const xyz_pos_t &end, const uint8_t strokes, const uint8_t objects) __Os; /** * @brief Circular clean pattern * @details Apply a circular cleaning pattern * * @param start xyz_pos_t defining the middle of circle * @param strokes number of strokes to execute * @param radius radius of circle */ static void circle(const xyz_pos_t &start, const xyz_pos_t &middle, const uint8_t strokes, const_float_t radius) __Os; #endif // NOZZLE_CLEAN_FEATURE public: #if ENABLED(NOZZLE_CLEAN_FEATURE) /** * @brief Clean the nozzle * @details Starts the selected clean procedure pattern * * @param pattern one of the available patterns * @param argument depends on the cleaning pattern */ static void clean(const uint8_t pattern, const uint8_t strokes, const_float_t radius, const uint8_t objects, const uint8_t cleans) __Os; #endif // NOZZLE_CLEAN_FEATURE #if ENABLED(NOZZLE_PARK_FEATURE) static float park_mode_0_height(const_float_t park_z) __Os; static void park(const uint8_t z_action, const xyz_pos_t &park=NOZZLE_PARK_POINT) __Os; #endif }; extern Nozzle nozzle;
2301_81045437/Marlin
Marlin/src/libs/nozzle.h
C++
agpl-3.0
2,994
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 "numtostr.h" #include "../inc/MarlinConfigPre.h" #include "../core/utility.h" constexpr char DIGIT(const uint8_t n) { return '0' + n; } template <typename T1, typename T2> constexpr char DIGIMOD(const T1 n, const T2 f) { return DIGIT((n / f) % 10); } template <typename T1, typename T2> constexpr char RJDIGIT(const T1 n, const T2 f) { return (n >= (T1)f ? DIGIMOD(n, f) : ' '); } template <typename T> constexpr char MINUSOR(T &n, const char alt) { return (n >= 0) ? alt : (n = -n) ? '-' : '-'; } constexpr long INTFLOAT(const float V, const int N) { return long((V * 10.0f * pow(10.0f, N) + (V < 0.0f ? -5.0f : 5.0f)) / 10.0f); } constexpr long UINTFLOAT(const float V, const int N) { return INTFLOAT(V < 0.0f ? -V : V, N); } char conv[9] = { 0 }; // Format uint8_t (0-100) as rj string with __3% / _23% / 123% format const char* pcttostrpctrj(const uint8_t i) { conv[4] = RJDIGIT(i, 100); conv[5] = RJDIGIT(i, 10); conv[6] = DIGIMOD(i, 1); conv[7] = '%'; return &conv[4]; } // Convert uint8_t (0-255) to a percentage, format as above const char* ui8tostr4pctrj(const uint8_t i) { return pcttostrpctrj(ui8_to_percent(i)); } // Convert unsigned 8bit int to string with __3 / _23 / 123 format const char* ui8tostr3rj(const uint8_t i) { conv[5] = RJDIGIT(i, 100); conv[6] = RJDIGIT(i, 10); conv[7] = DIGIMOD(i, 1); return &conv[5]; } // Convert uint8_t to string with 12 format const char* ui8tostr2(const uint8_t i) { conv[6] = DIGIMOD(i, 10); conv[7] = DIGIMOD(i, 1); return &conv[6]; } // Convert signed 8bit int to rj string with __3 / _23 / 123 / -_3 / -23 format const char* i8tostr3rj(const int8_t x) { int xx = x; conv[5] = MINUSOR(xx, RJDIGIT(xx, 100)); conv[6] = RJDIGIT(xx, 10); conv[7] = DIGIMOD(xx, 1); return &conv[5]; } #if HAS_PRINT_PROGRESS_PERMYRIAD // Convert unsigned 16-bit permyriad to percent with 100 / 23.4 / 3.45 format const char* permyriadtostr4(const uint16_t xx) { if (xx >= 10000) return " 100"; // space to keep 4-width alignment else if (xx >= 1000) { conv[4] = DIGIMOD(xx, 1000); conv[5] = DIGIMOD(xx, 100); conv[6] = '.'; conv[7] = DIGIMOD(xx, 10); return &conv[4]; } else { conv[4] = DIGIMOD(xx, 100); conv[5] = '.'; conv[6] = DIGIMOD(xx, 10); conv[7] = RJDIGIT(xx, 1); return &conv[4]; } } #endif // Convert unsigned 16bit int to right-justified string inline const char* ui16tostrXrj(const uint16_t xx, const int index) { switch (index) { case 0 ... 3: conv[3] = RJDIGIT(xx, 10000); case 4: conv[4] = RJDIGIT(xx, 1000); case 5: conv[5] = RJDIGIT(xx, 100); case 6: conv[6] = RJDIGIT(xx, 10); } conv[7] = DIGIMOD(xx, 1); return &conv[index]; } // Convert unsigned 16bit int to string with 12345 format const char* ui16tostr5rj(const uint16_t xx) { return ui16tostrXrj(xx, 8 - 5); } // Convert unsigned 16bit int to string with 1234 format const char* ui16tostr4rj(const uint16_t xx) { return ui16tostrXrj(xx, 8 - 4); } // Convert unsigned 16bit int to string with 123 format const char* ui16tostr3rj(const uint16_t xx) { return ui16tostrXrj(xx, 8 - 3); } // Convert signed 16bit int to rj string with 123 or -12 format const char* i16tostr3rj(const int16_t x) { int xx = x; conv[5] = MINUSOR(xx, RJDIGIT(xx, 100)); conv[6] = RJDIGIT(xx, 10); conv[7] = DIGIMOD(xx, 1); return &conv[5]; } // Convert unsigned 16bit int to lj string with 123 format const char* i16tostr3left(const int16_t i) { char *str = &conv[7]; *str = DIGIMOD(i, 1); if (i >= 10) { *(--str) = DIGIMOD(i, 10); if (i >= 100) *(--str) = DIGIMOD(i, 100); } return str; } // Convert signed 16bit int to rj string with 1234, _123, -123, _-12, or __-1 format const char* i16tostr4signrj(const int16_t i) { const bool neg = i < 0; const int ii = neg ? -i : i; if (i >= 1000) { conv[4] = DIGIMOD(ii, 1000); conv[5] = DIGIMOD(ii, 100); conv[6] = DIGIMOD(ii, 10); } else if (ii >= 100) { conv[4] = neg ? '-' : ' '; conv[5] = DIGIMOD(ii, 100); conv[6] = DIGIMOD(ii, 10); } else { conv[4] = ' '; conv[5] = ' '; if (ii >= 10) { conv[5] = neg ? '-' : ' '; conv[6] = DIGIMOD(ii, 10); } else { conv[6] = neg ? '-' : ' '; } } conv[7] = DIGIMOD(ii, 1); return &conv[4]; } // Convert unsigned float to string with 1.1 format const char* ftostr11ns(const_float_t f) { const long i = UINTFLOAT(f, 1); conv[5] = DIGIMOD(i, 10); conv[6] = '.'; conv[7] = DIGIMOD(i, 1); return &conv[5]; } // Convert unsigned float to string with 1.23 format const char* ftostr12ns(const_float_t f) { const long i = UINTFLOAT(f, 2); conv[4] = DIGIMOD(i, 100); conv[5] = '.'; conv[6] = DIGIMOD(i, 10); conv[7] = DIGIMOD(i, 1); return &conv[4]; } // Convert unsigned float to string with 12.3 format const char* ftostr31ns(const_float_t f) { const long i = UINTFLOAT(f, 1); conv[4] = DIGIMOD(i, 100); conv[5] = DIGIMOD(i, 10); conv[6] = '.'; conv[7] = DIGIMOD(i, 1); return &conv[4]; } // Convert unsigned float to string with 123.4 format const char* ftostr41ns(const_float_t f) { const long i = UINTFLOAT(f, 1); conv[3] = DIGIMOD(i, 1000); conv[4] = DIGIMOD(i, 100); conv[5] = DIGIMOD(i, 10); conv[6] = '.'; conv[7] = DIGIMOD(i, 1); return &conv[3]; } // Convert float to fixed-length string with 12.34 / _2.34 / -2.34 or -23.45 / 123.45 format const char* ftostr42_52(const_float_t f) { if (f <= -10 || f >= 100) return ftostr52(f); // -23.45 / 123.45 long i = INTFLOAT(f, 2); conv[3] = (f >= 0 && f < 10) ? ' ' : MINUSOR(i, DIGIMOD(i, 1000)); conv[4] = DIGIMOD(i, 100); conv[5] = '.'; conv[6] = DIGIMOD(i, 10); conv[7] = DIGIMOD(i, 1); return &conv[3]; } // Convert float to fixed-length string with 023.45 / -23.45 format const char* ftostr52(const_float_t f) { long i = INTFLOAT(f, 2); conv[2] = MINUSOR(i, DIGIMOD(i, 10000)); conv[3] = DIGIMOD(i, 1000); conv[4] = DIGIMOD(i, 100); conv[5] = '.'; conv[6] = DIGIMOD(i, 10); conv[7] = DIGIMOD(i, 1); return &conv[2]; } // Convert float to fixed-length string with 12.345 / _2.345 / -2.345 or -23.45 / 123.45 format const char* ftostr53_63(const_float_t f) { if (f <= -10 || f >= 100) return ftostr63(f); // -23.456 / 123.456 long i = INTFLOAT(f, 3); conv[2] = (f >= 0 && f < 10) ? ' ' : MINUSOR(i, DIGIMOD(i, 10000)); conv[3] = DIGIMOD(i, 1000); conv[4] = '.'; conv[5] = DIGIMOD(i, 100); conv[6] = DIGIMOD(i, 10); conv[7] = DIGIMOD(i, 1); return &conv[2]; } // Convert float to fixed-length string with 023.456 / -23.456 format const char* ftostr63(const_float_t f) { long i = INTFLOAT(f, 3); conv[1] = MINUSOR(i, DIGIMOD(i, 100000)); conv[2] = DIGIMOD(i, 10000); conv[3] = DIGIMOD(i, 1000); conv[4] = '.'; conv[5] = DIGIMOD(i, 100); conv[6] = DIGIMOD(i, 10); conv[7] = DIGIMOD(i, 1); return &conv[1]; } #if ENABLED(LCD_DECIMAL_SMALL_XY) // Convert float to rj string with 1234, _123, -123, _-12, 12.3, _1.2, or -1.2 format const char* ftostr4sign(const_float_t f) { const int i = INTFLOAT(f, 1); if (!WITHIN(i, -99, 999)) return i16tostr4signrj((int)f); const bool neg = i < 0; const int ii = neg ? -i : i; conv[4] = neg ? '-' : (ii >= 100 ? DIGIMOD(ii, 100) : ' '); conv[5] = DIGIMOD(ii, 10); conv[6] = '.'; conv[7] = DIGIMOD(ii, 1); return &conv[4]; } #endif // // Convert float to fixed-length string with +/- and a single decimal place // inline const char* ftostrX1sign(const_float_t f, const int index) { long i = INTFLOAT(f, 1); conv[index] = MINUSOR(i, '+'); switch (index + 1) { case 1: conv[1] = DIGIMOD(i, 100000); case 2: conv[2] = DIGIMOD(i, 10000); case 3: conv[3] = DIGIMOD(i, 1000); case 4: conv[4] = DIGIMOD(i, 100); } conv[5] = DIGIMOD(i, 10); conv[6] = '.'; conv[7] = DIGIMOD(i, 1); return &conv[index]; } // Convert float to fixed-length string with +12.3 / -12.3 format const char* ftostr31sign(const_float_t f) { return ftostrX1sign(f, 3); } // Convert float to fixed-length string with +123.4 / -123.4 format const char* ftostr41sign(const_float_t f) { return ftostrX1sign(f, 2); } // Convert float to fixed-length string with +1234.5 / +1234.5 format const char* ftostr51sign(const_float_t f) { return ftostrX1sign(f, 1); } // // Convert float to string with +/ /- and 3 decimal places // inline const char* ftostrX3sign(const_float_t f, const int index, char plus/*=' '*/) { long i = INTFLOAT(f, 3); conv[index] = i ? MINUSOR(i, plus) : ' '; switch (index + 1) { case 1: conv[1] = DIGIMOD(i, 100000); case 2: conv[2] = DIGIMOD(i, 10000); } conv[3] = DIGIMOD(i, 1000); conv[4] = '.'; conv[5] = DIGIMOD(i, 100); conv[6] = DIGIMOD(i, 10); conv[7] = DIGIMOD(i, 1); return &conv[index]; } // Convert float to string (6 chars) with -1.234 / _0.000 / +1.234 format const char* ftostr43sign(const_float_t f, char plus/*=' '*/) { return ftostrX3sign(f, 2, plus); } // Convert float to string (7 chars) with -12.345 / _00.000 / +12.345 format const char* ftostr53sign(const_float_t f, char plus/*=' '*/) { return ftostrX3sign(f, 1, plus); } // Convert float to string (7 chars) with -1.2345 / _0.0000 / +1.2345 format const char* ftostr54sign(const_float_t f, char plus/*=' '*/) { long i = INTFLOAT(f, 4); conv[1] = i ? MINUSOR(i, plus) : ' '; conv[2] = DIGIMOD(i, 10000); conv[3] = '.'; conv[4] = DIGIMOD(i, 1000); conv[5] = DIGIMOD(i, 100); conv[6] = DIGIMOD(i, 10); conv[7] = DIGIMOD(i, 1); return &conv[1]; } // Convert unsigned float to rj string with 12345 format const char* ftostr5rj(const_float_t f) { const long i = UINTFLOAT(f, 0); return ui16tostr5rj(i); } // Convert signed float to string with +123.45 format const char* ftostr52sign(const_float_t f) { long i = INTFLOAT(f, 2); conv[1] = MINUSOR(i, '+'); conv[2] = DIGIMOD(i, 10000); conv[3] = DIGIMOD(i, 1000); conv[4] = DIGIMOD(i, 100); conv[5] = '.'; conv[6] = DIGIMOD(i, 10); conv[7] = DIGIMOD(i, 1); return &conv[1]; } // Convert unsigned float to string with a single digit precision inline const char* ftostrX1rj(const_float_t f, const int index=1) { const long i = UINTFLOAT(f, 1); switch (index) { case 0: conv[0] = RJDIGIT(i, 1000000); case 1: conv[1] = RJDIGIT(i, 100000); case 2: conv[2] = RJDIGIT(i, 10000); case 3: conv[3] = RJDIGIT(i, 1000); case 4: conv[4] = RJDIGIT(i, 100); } conv[5] = DIGIMOD(i, 10); conv[6] = '.'; conv[7] = DIGIMOD(i, 1); return &conv[index]; } // Convert unsigned float to string with _2.3 / 12.3 format const char* ftostr31rj(const_float_t f) { return ftostrX1rj(f, 7 - 3); } // Convert unsigned float to string with __3.4 / _23.4 / 123.4 format const char* ftostr41rj(const_float_t f) { return ftostrX1rj(f, 7 - 4); } // Convert unsigned float to string with ___4.5 / __34.5 / _234.5 / 1234.5 format const char* ftostr51rj(const_float_t f) { return ftostrX1rj(f, 7 - 5); } // Convert unsigned float to string with ____5.6 / ___45.6 / __345.6 / _2345.6 / 12345.6 format const char* ftostr61rj(const_float_t f) { return ftostrX1rj(f, 7 - 6); } // Convert unsigned float to string with two digit precision inline const char* ftostrX2rj(const_float_t f, const int index=1) { const long i = UINTFLOAT(f, 2); switch (index) { case 0: conv[0] = RJDIGIT(i, 1000000); case 1: conv[1] = RJDIGIT(i, 100000); case 2: conv[2] = RJDIGIT(i, 10000); case 3: conv[3] = RJDIGIT(i, 1000); case 4: conv[4] = RJDIGIT(i, 100); } conv[5] = '.'; conv[6] = DIGIMOD(i, 10); conv[7] = DIGIMOD(i, 1); return &conv[index]; } // Convert unsigned float to string with 1.23 format const char* ftostr32rj(const_float_t f) { return ftostrX2rj(f, 4); } // Convert unsigned float to string with _2.34, 12.34 format const char* ftostr42rj(const_float_t f) { return ftostrX2rj(f, 3); } // Convert unsigned float to string with __3.45, _23.45, 123.45 format const char* ftostr52rj(const_float_t f) { return ftostrX2rj(f, 2); } // Convert unsigned float to string with ___4.56, __34.56, _234.56, 1234.56 format const char* ftostr62rj(const_float_t f) { return ftostrX2rj(f, 1); } // Convert unsigned float to string with ____5.67, ___45.67, __345.67, _2345.67, 12345.67 format const char* ftostr72rj(const_float_t f) { return ftostrX2rj(f, 0); } // Convert float to space-padded string with -_23.4_ format const char* ftostr52sp(const_float_t f) { long i = INTFLOAT(f, 2); uint8_t dig; conv[1] = MINUSOR(i, ' '); conv[2] = RJDIGIT(i, 10000); conv[3] = RJDIGIT(i, 1000); conv[4] = DIGIMOD(i, 100); if ((dig = i % 10)) { // Second digit after decimal point? conv[5] = '.'; conv[6] = DIGIMOD(i, 10); conv[7] = DIGIT(dig); } else { if ((dig = (i / 10) % 10)) { // First digit after decimal point? conv[5] = '.'; conv[6] = DIGIT(dig); } else // Nothing after decimal point conv[5] = conv[6] = ' '; conv[7] = ' '; } return &conv[1]; } // Convert unsigned 16bit int to string 1, 12, 123 format, capped at 999 const char* utostr3(const uint16_t x) { return i16tostr3left(_MIN(x, 999U)); } // Convert float to space-padded string with 1.23, 12.34, 123.45 format const char* ftostr52sprj(const_float_t f) { long i = INTFLOAT(f, 2); LIMIT(i, -99999, 99999); // cap to -999.99 - 999.99 range if (WITHIN(i, -999, 999)) { // -9.99 - 9.99 range conv[1] = conv[2] = ' '; // default to ' ' for smaller numbers conv[3] = MINUSOR(i, ' '); } else if (WITHIN(i, -9999, 9999)) { // -99.99 - 99.99 range conv[1] = ' '; conv[2] = MINUSOR(i, ' '); conv[3] = DIGIMOD(i, 1000); } else { // -999.99 - 999.99 range conv[1] = MINUSOR(i, ' '); conv[2] = DIGIMOD(i, 10000); conv[3] = DIGIMOD(i, 1000); } conv[4] = DIGIMOD(i, 100); // always convert last 3 digits conv[5] = '.'; conv[6] = DIGIMOD(i, 10); conv[7] = DIGIMOD(i, 1); return &conv[1]; }
2301_81045437/Marlin
Marlin/src/libs/numtostr.cpp
C++
agpl-3.0
14,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/>. * */ #pragma once #include "../inc/MarlinConfigPre.h" #include "../core/types.h" // Format uint8_t (0-100) as rj string with 123% / _12% / __1% format const char* pcttostrpctrj(const uint8_t i); // Convert uint8_t (0-255) to a percentage, format as above const char* ui8tostr4pctrj(const uint8_t i); // Convert uint8_t to string with 12 format const char* ui8tostr2(const uint8_t x); // Convert uint8_t to string with 123 format const char* ui8tostr3rj(const uint8_t i); // Convert int8_t to string with 123 format const char* i8tostr3rj(const int8_t x); #if HAS_PRINT_PROGRESS_PERMYRIAD // Convert 16-bit unsigned permyriad value to percent: _100 / __23 / 23.4 / 3.45 const char* permyriadtostr4(const uint16_t xx); #endif // Convert uint16_t to string with 12345 format const char* ui16tostr5rj(const uint16_t x); // Convert uint16_t to string with 1234 format const char* ui16tostr4rj(const uint16_t x); // Convert uint16_t to string with 123 format const char* ui16tostr3rj(const uint16_t x); // Convert int16_t to string with 123 format const char* i16tostr3rj(const int16_t x); // Convert signed int to lj string with 123 format const char* i16tostr3left(const int16_t xx); // Convert signed int to rj string with _123, -123, _-12, or __-1 format const char* i16tostr4signrj(const int16_t x); // Convert unsigned float to string with 1.2 format const char* ftostr11ns(const_float_t x); // Convert unsigned float to string with 1.23 format const char* ftostr12ns(const_float_t x); // Convert unsigned float to string with 12.3 format const char* ftostr31ns(const_float_t x); // Convert unsigned float to string with 123.4 format const char* ftostr41ns(const_float_t x); // Convert signed float to fixed-length string with 12.34 / _2.34 / -2.34 or -23.45 / 123.45 format const char* ftostr42_52(const_float_t x); // Convert signed float to fixed-length string with 023.45 / -23.45 format const char* ftostr52(const_float_t x); // Convert signed float to fixed-length string with 12.345 / -2.345 or 023.456 / -23.456 format const char* ftostr53_63(const_float_t x); // Convert signed float to fixed-length string with 023.456 / -23.456 format const char* ftostr63(const_float_t x); // Convert signed float to fixed-length string with +12.3 / -12.3 format const char* ftostr31sign(const_float_t x); // Convert signed float to fixed-length string with +123.4 / -123.4 format const char* ftostr41sign(const_float_t x); // Convert signed float to fixed-length string with +1234.5 / +1234.5 format const char* ftostr51sign(const_float_t x); // Convert signed float to string (6 digit) with -1.234 / _0.000 / +1.234 format const char* ftostr43sign(const_float_t x, char plus=' '); // Convert signed float to string (7 chars) with -12.345 / _00.000 / +12.345 format const char* ftostr53sign(const_float_t x, char plus=' '); // Convert signed float to string (5 digit) with -1.2345 / _0.0000 / +1.2345 format const char* ftostr54sign(const_float_t x, char plus=' '); // Convert unsigned float to rj string with 12345 format const char* ftostr5rj(const_float_t x); // Convert signed float to fixed-length string with +12.3 / -12.3 format const char* ftostr31sign(const_float_t x); // Convert signed float to fixed-length string with +123.4 / -123.4 format const char* ftostr41sign(const_float_t x); // Convert signed float to fixed-length string with +1234.5 format const char* ftostr51sign(const_float_t x); // Convert signed float to space-padded string with -_23.4_ format const char* ftostr52sp(const_float_t x); // Convert signed float to string with +123.45 format const char* ftostr52sign(const_float_t x); // Convert unsigned float to string with _2.3 / 12.3 format const char* ftostr31rj(const_float_t x); // Convert unsigned float to string with __3.4 / _23.4 / 123.4 format const char* ftostr41rj(const_float_t x); // Convert unsigned float to string with ___4.5 / __34.5 / _234.5 / 1234.5 format const char* ftostr51rj(const_float_t x); // Convert unsigned float to string with ____5.6 / ___45.6 / __345.6 / _2345.6 / 12345.6 format const char* ftostr61rj(const_float_t x); // Convert unsigned float to string with 1.23 format const char* ftostr32rj(const_float_t f); // Convert unsigned float to string with _2.34, 12.34 format const char* ftostr42rj(const_float_t f); // Convert unsigned float to string with __3.45, _23.45, 123.45 format const char* ftostr52rj(const_float_t f); // Convert unsigned float to string with ___4.56, __34.56, _234.56, 1234.56 format const char* ftostr62rj(const_float_t f); // Convert unsigned float to string with ____5.67, ___45.67, __345.67, _2345.67, 12345.67 format const char* ftostr72rj(const_float_t x); // Convert signed float to rj string with 123 or -12 format FORCE_INLINE const char* ftostr3rj(const_float_t x) { return i16tostr3rj(int16_t(x + (x < 0 ? -0.5f : 0.5f))); } #if ENABLED(LCD_DECIMAL_SMALL_XY) // Convert signed float to rj string with 1234, _123, 12.3, _1.2, -123, _-12, or -1.2 format const char* ftostr4sign(const_float_t fx); #else // Convert signed float to rj string with 1234, _123, -123, __12, _-12, ___1, or __-1 format FORCE_INLINE const char* ftostr4sign(const_float_t x) { return i16tostr4signrj(int16_t(x + (x < 0 ? -0.5f : 0.5f))); } #endif // Convert unsigned int to string 1, 12, 123 format, capped at 999 const char* utostr3(const uint16_t x); // Convert signed float to space-padded string with 1.23, 12.34, 123.45 format const char* ftostr52sprj(const_float_t f);
2301_81045437/Marlin
Marlin/src/libs/numtostr.h
C
agpl-3.0
6,361
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 "softspi.h" #include <stdint.h> template<uint8_t MisoPin, uint8_t MosiPin, uint8_t SckPin> class SPIclass { static SoftSPI<MisoPin, MosiPin, SckPin> softSPI; public: FORCE_INLINE static void init() { softSPI.begin(); } FORCE_INLINE static void send(uint8_t data) { softSPI.send(data); } FORCE_INLINE static uint8_t receive() { return softSPI.receive(); } }; // Hardware SPI template<> class SPIclass<SD_MISO_PIN, SD_MOSI_PIN, SD_SCK_PIN> { public: FORCE_INLINE static void init() { OUT_WRITE(SD_SCK_PIN, LOW); OUT_WRITE(SD_MOSI_PIN, HIGH); SET_INPUT_PULLUP(SD_MISO_PIN); } FORCE_INLINE static uint8_t receive() { #if defined(__AVR__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) || defined(__IMXRT1062__) SPDR = 0; for (;!TEST(SPSR, SPIF);); return SPDR; #else return spiRec(); #endif } };
2301_81045437/Marlin
Marlin/src/libs/private_spi.h
C++
agpl-3.0
1,812
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // // Based on https://github.com/niteris/ArduinoSoftSpi // #include "../HAL/shared/Marduino.h" // CORE_TEENSY #define nop __asm__ volatile ("nop") // NOP for timing #ifdef __arm__ #ifdef CORE_TEENSY /** * Read pin value * @param[in] pin Arduino pin number * @return value read */ FORCE_INLINE static bool fastDigitalRead(uint8_t pin) { return *portInputRegister(pin); } /** * Set pin value * @param[in] pin Arduino pin number * @param[in] level value to write */ FORCE_INLINE static void fastDigitalWrite(uint8_t pin, bool value) { if (value) *portSetRegister(pin) = 1; else *portClearRegister(pin) = 1; } #else // !CORE_TEENSY /** * Read pin value * @param[in] pin Arduino pin number * @return value read */ FORCE_INLINE static bool fastDigitalRead(uint8_t pin) { return digitalRead(pin); } /** * Set pin value * @param[in] pin Arduino pin number * @param[in] level value to write */ FORCE_INLINE static void fastDigitalWrite(uint8_t pin, bool value) { digitalWrite(pin, value); } #endif // !CORE_TEENSY inline void fastDigitalToggle(uint8_t pin) { fastDigitalWrite(pin, !fastDigitalRead(pin)); } inline void fastPinMode(uint8_t pin, bool mode) { pinMode(pin, mode); } #else // !__arm__ #include <avr/io.h> #include <util/atomic.h> /** * @class pin_map_t * @brief struct for mapping digital pins */ struct pin_map_t { volatile uint8_t* ddr; /**< address of DDR for this pin */ volatile uint8_t* pin; /**< address of PIN for this pin */ volatile uint8_t* port; /**< address of PORT for this pin */ uint8_t bit; /**< bit number for this pin */ }; #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega168P__) || defined(__AVR_ATmega328P__) // 168 and 328 Arduinos const static pin_map_t pinMap[] = { {&DDRD, &PIND, &PORTD, 0}, // D0 0 {&DDRD, &PIND, &PORTD, 1}, // D1 1 {&DDRD, &PIND, &PORTD, 2}, // D2 2 {&DDRD, &PIND, &PORTD, 3}, // D3 3 {&DDRD, &PIND, &PORTD, 4}, // D4 4 {&DDRD, &PIND, &PORTD, 5}, // D5 5 {&DDRD, &PIND, &PORTD, 6}, // D6 6 {&DDRD, &PIND, &PORTD, 7}, // D7 7 {&DDRB, &PINB, &PORTB, 0}, // B0 8 {&DDRB, &PINB, &PORTB, 1}, // B1 9 {&DDRB, &PINB, &PORTB, 2}, // B2 10 {&DDRB, &PINB, &PORTB, 3}, // B3 11 {&DDRB, &PINB, &PORTB, 4}, // B4 12 {&DDRB, &PINB, &PORTB, 5}, // B5 13 {&DDRC, &PINC, &PORTC, 0}, // C0 14 {&DDRC, &PINC, &PORTC, 1}, // C1 15 {&DDRC, &PINC, &PORTC, 2}, // C2 16 {&DDRC, &PINC, &PORTC, 3}, // C3 17 {&DDRC, &PINC, &PORTC, 4}, // C4 18 {&DDRC, &PINC, &PORTC, 5} // C5 19 }; #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) // Mega static const pin_map_t pinMap[] = { {&DDRE, &PINE, &PORTE, 0}, // E0 0 {&DDRE, &PINE, &PORTE, 1}, // E1 1 {&DDRE, &PINE, &PORTE, 4}, // E4 2 {&DDRE, &PINE, &PORTE, 5}, // E5 3 {&DDRG, &PING, &PORTG, 5}, // G5 4 {&DDRE, &PINE, &PORTE, 3}, // E3 5 {&DDRH, &PINH, &PORTH, 3}, // H3 6 {&DDRH, &PINH, &PORTH, 4}, // H4 7 {&DDRH, &PINH, &PORTH, 5}, // H5 8 {&DDRH, &PINH, &PORTH, 6}, // H6 9 {&DDRB, &PINB, &PORTB, 4}, // B4 10 {&DDRB, &PINB, &PORTB, 5}, // B5 11 {&DDRB, &PINB, &PORTB, 6}, // B6 12 {&DDRB, &PINB, &PORTB, 7}, // B7 13 {&DDRJ, &PINJ, &PORTJ, 1}, // J1 14 {&DDRJ, &PINJ, &PORTJ, 0}, // J0 15 {&DDRH, &PINH, &PORTH, 1}, // H1 16 {&DDRH, &PINH, &PORTH, 0}, // H0 17 {&DDRD, &PIND, &PORTD, 3}, // D3 18 {&DDRD, &PIND, &PORTD, 2}, // D2 19 {&DDRD, &PIND, &PORTD, 1}, // D1 20 {&DDRD, &PIND, &PORTD, 0}, // D0 21 {&DDRA, &PINA, &PORTA, 0}, // A0 22 {&DDRA, &PINA, &PORTA, 1}, // A1 23 {&DDRA, &PINA, &PORTA, 2}, // A2 24 {&DDRA, &PINA, &PORTA, 3}, // A3 25 {&DDRA, &PINA, &PORTA, 4}, // A4 26 {&DDRA, &PINA, &PORTA, 5}, // A5 27 {&DDRA, &PINA, &PORTA, 6}, // A6 28 {&DDRA, &PINA, &PORTA, 7}, // A7 29 {&DDRC, &PINC, &PORTC, 7}, // C7 30 {&DDRC, &PINC, &PORTC, 6}, // C6 31 {&DDRC, &PINC, &PORTC, 5}, // C5 32 {&DDRC, &PINC, &PORTC, 4}, // C4 33 {&DDRC, &PINC, &PORTC, 3}, // C3 34 {&DDRC, &PINC, &PORTC, 2}, // C2 35 {&DDRC, &PINC, &PORTC, 1}, // C1 36 {&DDRC, &PINC, &PORTC, 0}, // C0 37 {&DDRD, &PIND, &PORTD, 7}, // D7 38 {&DDRG, &PING, &PORTG, 2}, // G2 39 {&DDRG, &PING, &PORTG, 1}, // G1 40 {&DDRG, &PING, &PORTG, 0}, // G0 41 {&DDRL, &PINL, &PORTL, 7}, // L7 42 {&DDRL, &PINL, &PORTL, 6}, // L6 43 {&DDRL, &PINL, &PORTL, 5}, // L5 44 {&DDRL, &PINL, &PORTL, 4}, // L4 45 {&DDRL, &PINL, &PORTL, 3}, // L3 46 {&DDRL, &PINL, &PORTL, 2}, // L2 47 {&DDRL, &PINL, &PORTL, 1}, // L1 48 {&DDRL, &PINL, &PORTL, 0}, // L0 49 {&DDRB, &PINB, &PORTB, 3}, // B3 50 {&DDRB, &PINB, &PORTB, 2}, // B2 51 {&DDRB, &PINB, &PORTB, 1}, // B1 52 {&DDRB, &PINB, &PORTB, 0}, // B0 53 {&DDRF, &PINF, &PORTF, 0}, // F0 54 {&DDRF, &PINF, &PORTF, 1}, // F1 55 {&DDRF, &PINF, &PORTF, 2}, // F2 56 {&DDRF, &PINF, &PORTF, 3}, // F3 57 {&DDRF, &PINF, &PORTF, 4}, // F4 58 {&DDRF, &PINF, &PORTF, 5}, // F5 59 {&DDRF, &PINF, &PORTF, 6}, // F6 60 {&DDRF, &PINF, &PORTF, 7}, // F7 61 {&DDRK, &PINK, &PORTK, 0}, // K0 62 {&DDRK, &PINK, &PORTK, 1}, // K1 63 {&DDRK, &PINK, &PORTK, 2}, // K2 64 {&DDRK, &PINK, &PORTK, 3}, // K3 65 {&DDRK, &PINK, &PORTK, 4}, // K4 66 {&DDRK, &PINK, &PORTK, 5}, // K5 67 {&DDRK, &PINK, &PORTK, 6}, // K6 68 {&DDRK, &PINK, &PORTK, 7}, // K7 69 // pins_MIGHTYBOARD_REVE.h {&DDRG, &PING, &PORTG, 4}, // G4 70 {&DDRG, &PING, &PORTG, 3}, // G3 71 {&DDRJ, &PINJ, &PORTJ, 2}, // J2 72 {&DDRJ, &PINJ, &PORTJ, 3}, // J3 73 {&DDRJ, &PINJ, &PORTJ, 7}, // J7 74 {&DDRJ, &PINJ, &PORTJ, 4}, // J4 75 {&DDRJ, &PINJ, &PORTJ, 5}, // J5 76 {&DDRJ, &PINJ, &PORTJ, 6}, // J6 77 {&DDRE, &PINE, &PORTE, 2}, // E2 78 {&DDRE, &PINE, &PORTE, 6} // E6 79 }; #elif defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega1284__) \ || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) \ || defined(__AVR_ATmega64__) || defined(__AVR_ATmega32__) \ || defined(__AVR_ATmega324__) || defined(__AVR_ATmega16__) #ifdef VARIANT_MIGHTY // Mighty Layout static const pin_map_t pinMap[] = { {&DDRB, &PINB, &PORTB, 0}, // B0 0 {&DDRB, &PINB, &PORTB, 1}, // B1 1 {&DDRB, &PINB, &PORTB, 2}, // B2 2 {&DDRB, &PINB, &PORTB, 3}, // B3 3 {&DDRB, &PINB, &PORTB, 4}, // B4 4 {&DDRB, &PINB, &PORTB, 5}, // B5 5 {&DDRB, &PINB, &PORTB, 6}, // B6 6 {&DDRB, &PINB, &PORTB, 7}, // B7 7 {&DDRD, &PIND, &PORTD, 0}, // D0 8 {&DDRD, &PIND, &PORTD, 1}, // D1 9 {&DDRD, &PIND, &PORTD, 2}, // D2 10 {&DDRD, &PIND, &PORTD, 3}, // D3 11 {&DDRD, &PIND, &PORTD, 4}, // D4 12 {&DDRD, &PIND, &PORTD, 5}, // D5 13 {&DDRD, &PIND, &PORTD, 6}, // D6 14 {&DDRD, &PIND, &PORTD, 7}, // D7 15 {&DDRC, &PINC, &PORTC, 0}, // C0 16 {&DDRC, &PINC, &PORTC, 1}, // C1 17 {&DDRC, &PINC, &PORTC, 2}, // C2 18 {&DDRC, &PINC, &PORTC, 3}, // C3 19 {&DDRC, &PINC, &PORTC, 4}, // C4 20 {&DDRC, &PINC, &PORTC, 5}, // C5 21 {&DDRC, &PINC, &PORTC, 6}, // C6 22 {&DDRC, &PINC, &PORTC, 7}, // C7 23 {&DDRA, &PINA, &PORTA, 0}, // A0 24 {&DDRA, &PINA, &PORTA, 1}, // A1 25 {&DDRA, &PINA, &PORTA, 2}, // A2 26 {&DDRA, &PINA, &PORTA, 3}, // A3 27 {&DDRA, &PINA, &PORTA, 4}, // A4 28 {&DDRA, &PINA, &PORTA, 5}, // A5 29 {&DDRA, &PINA, &PORTA, 6}, // A6 30 {&DDRA, &PINA, &PORTA, 7} // A7 31 }; #elif defined(VARIANT_BOBUINO) // Bobuino Layout static const pin_map_t pinMap[] = { {&DDRD, &PIND, &PORTD, 0}, // D0 0 {&DDRD, &PIND, &PORTD, 1}, // D1 1 {&DDRD, &PIND, &PORTD, 2}, // D2 2 {&DDRD, &PIND, &PORTD, 3}, // D3 3 {&DDRB, &PINB, &PORTB, 0}, // B0 4 {&DDRB, &PINB, &PORTB, 1}, // B1 5 {&DDRB, &PINB, &PORTB, 2}, // B2 6 {&DDRB, &PINB, &PORTB, 3}, // B3 7 {&DDRD, &PIND, &PORTD, 5}, // D5 8 {&DDRD, &PIND, &PORTD, 6}, // D6 9 {&DDRB, &PINB, &PORTB, 4}, // B4 10 {&DDRB, &PINB, &PORTB, 5}, // B5 11 {&DDRB, &PINB, &PORTB, 6}, // B6 12 {&DDRB, &PINB, &PORTB, 7}, // B7 13 {&DDRA, &PINA, &PORTA, 7}, // A7 14 {&DDRA, &PINA, &PORTA, 6}, // A6 15 {&DDRA, &PINA, &PORTA, 5}, // A5 16 {&DDRA, &PINA, &PORTA, 4}, // A4 17 {&DDRA, &PINA, &PORTA, 3}, // A3 18 {&DDRA, &PINA, &PORTA, 2}, // A2 19 {&DDRA, &PINA, &PORTA, 1}, // A1 20 {&DDRA, &PINA, &PORTA, 0}, // A0 21 {&DDRC, &PINC, &PORTC, 0}, // C0 22 {&DDRC, &PINC, &PORTC, 1}, // C1 23 {&DDRC, &PINC, &PORTC, 2}, // C2 24 {&DDRC, &PINC, &PORTC, 3}, // C3 25 {&DDRC, &PINC, &PORTC, 4}, // C4 26 {&DDRC, &PINC, &PORTC, 5}, // C5 27 {&DDRC, &PINC, &PORTC, 6}, // C6 28 {&DDRC, &PINC, &PORTC, 7}, // C7 29 {&DDRD, &PIND, &PORTD, 4}, // D4 30 {&DDRD, &PIND, &PORTD, 7} // D7 31 }; #elif defined(VARIANT_STANDARD) // Standard Layout static const pin_map_t pinMap[] = { {&DDRB, &PINB, &PORTB, 0}, // B0 0 {&DDRB, &PINB, &PORTB, 1}, // B1 1 {&DDRB, &PINB, &PORTB, 2}, // B2 2 {&DDRB, &PINB, &PORTB, 3}, // B3 3 {&DDRB, &PINB, &PORTB, 4}, // B4 4 {&DDRB, &PINB, &PORTB, 5}, // B5 5 {&DDRB, &PINB, &PORTB, 6}, // B6 6 {&DDRB, &PINB, &PORTB, 7}, // B7 7 {&DDRD, &PIND, &PORTD, 0}, // D0 8 {&DDRD, &PIND, &PORTD, 1}, // D1 9 {&DDRD, &PIND, &PORTD, 2}, // D2 10 {&DDRD, &PIND, &PORTD, 3}, // D3 11 {&DDRD, &PIND, &PORTD, 4}, // D4 12 {&DDRD, &PIND, &PORTD, 5}, // D5 13 {&DDRD, &PIND, &PORTD, 6}, // D6 14 {&DDRD, &PIND, &PORTD, 7}, // D7 15 {&DDRC, &PINC, &PORTC, 0}, // C0 16 {&DDRC, &PINC, &PORTC, 1}, // C1 17 {&DDRC, &PINC, &PORTC, 2}, // C2 18 {&DDRC, &PINC, &PORTC, 3}, // C3 19 {&DDRC, &PINC, &PORTC, 4}, // C4 20 {&DDRC, &PINC, &PORTC, 5}, // C5 21 {&DDRC, &PINC, &PORTC, 6}, // C6 22 {&DDRC, &PINC, &PORTC, 7}, // C7 23 {&DDRA, &PINA, &PORTA, 7}, // A7 24 {&DDRA, &PINA, &PORTA, 6}, // A6 25 {&DDRA, &PINA, &PORTA, 5}, // A5 26 {&DDRA, &PINA, &PORTA, 4}, // A4 27 {&DDRA, &PINA, &PORTA, 3}, // A3 28 {&DDRA, &PINA, &PORTA, 2}, // A2 29 {&DDRA, &PINA, &PORTA, 1}, // A1 30 {&DDRA, &PINA, &PORTA, 0} // A0 31 }; #else // !(VARIANT_MIGHTY || VARIANT_BOBUINO || VARIANT_STANDARD) #error Undefined variant 1284, 644, 324, 64, 32 #endif #elif defined(__AVR_ATmega32U4__) #ifdef CORE_TEENSY // Teensy 2.0 static const pin_map_t pinMap[] = { {&DDRB, &PINB, &PORTB, 0}, // B0 0 {&DDRB, &PINB, &PORTB, 1}, // B1 1 {&DDRB, &PINB, &PORTB, 2}, // B2 2 {&DDRB, &PINB, &PORTB, 3}, // B3 3 {&DDRB, &PINB, &PORTB, 7}, // B7 4 {&DDRD, &PIND, &PORTD, 0}, // D0 5 {&DDRD, &PIND, &PORTD, 1}, // D1 6 {&DDRD, &PIND, &PORTD, 2}, // D2 7 {&DDRD, &PIND, &PORTD, 3}, // D3 8 {&DDRC, &PINC, &PORTC, 6}, // C6 9 {&DDRC, &PINC, &PORTC, 7}, // C7 10 {&DDRD, &PIND, &PORTD, 6}, // D6 11 {&DDRD, &PIND, &PORTD, 7}, // D7 12 {&DDRB, &PINB, &PORTB, 4}, // B4 13 {&DDRB, &PINB, &PORTB, 5}, // B5 14 {&DDRB, &PINB, &PORTB, 6}, // B6 15 {&DDRF, &PINF, &PORTF, 7}, // F7 16 {&DDRF, &PINF, &PORTF, 6}, // F6 17 {&DDRF, &PINF, &PORTF, 5}, // F5 18 {&DDRF, &PINF, &PORTF, 4}, // F4 19 {&DDRF, &PINF, &PORTF, 1}, // F1 20 {&DDRF, &PINF, &PORTF, 0}, // F0 21 {&DDRD, &PIND, &PORTD, 4}, // D4 22 {&DDRD, &PIND, &PORTD, 5}, // D5 23 {&DDRE, &PINE, &PORTE, 6} // E6 24 }; #else // !CORE_TEENSY // Leonardo static const pin_map_t pinMap[] = { {&DDRD, &PIND, &PORTD, 2}, // D2 0 {&DDRD, &PIND, &PORTD, 3}, // D3 1 {&DDRD, &PIND, &PORTD, 1}, // D1 2 {&DDRD, &PIND, &PORTD, 0}, // D0 3 {&DDRD, &PIND, &PORTD, 4}, // D4 4 {&DDRC, &PINC, &PORTC, 6}, // C6 5 {&DDRD, &PIND, &PORTD, 7}, // D7 6 {&DDRE, &PINE, &PORTE, 6}, // E6 7 {&DDRB, &PINB, &PORTB, 4}, // B4 8 {&DDRB, &PINB, &PORTB, 5}, // B5 9 {&DDRB, &PINB, &PORTB, 6}, // B6 10 {&DDRB, &PINB, &PORTB, 7}, // B7 11 {&DDRD, &PIND, &PORTD, 6}, // D6 12 {&DDRC, &PINC, &PORTC, 7}, // C7 13 {&DDRB, &PINB, &PORTB, 3}, // B3 14 {&DDRB, &PINB, &PORTB, 1}, // B1 15 {&DDRB, &PINB, &PORTB, 2}, // B2 16 {&DDRB, &PINB, &PORTB, 0}, // B0 17 {&DDRF, &PINF, &PORTF, 7}, // F7 18 {&DDRF, &PINF, &PORTF, 6}, // F6 19 {&DDRF, &PINF, &PORTF, 5}, // F5 20 {&DDRF, &PINF, &PORTF, 4}, // F4 21 {&DDRF, &PINF, &PORTF, 1}, // F1 22 {&DDRF, &PINF, &PORTF, 0}, // F0 23 {&DDRD, &PIND, &PORTD, 4}, // D4 24 {&DDRD, &PIND, &PORTD, 7}, // D7 25 {&DDRB, &PINB, &PORTB, 4}, // B4 26 {&DDRB, &PINB, &PORTB, 5}, // B5 27 {&DDRB, &PINB, &PORTB, 6}, // B6 28 {&DDRD, &PIND, &PORTD, 6} // D6 29 }; #endif // !CORE_TEENSY #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) // Teensy++ 1.0 & 2.0 static const pin_map_t pinMap[] = { {&DDRD, &PIND, &PORTD, 0}, // D0 0 {&DDRD, &PIND, &PORTD, 1}, // D1 1 {&DDRD, &PIND, &PORTD, 2}, // D2 2 {&DDRD, &PIND, &PORTD, 3}, // D3 3 {&DDRD, &PIND, &PORTD, 4}, // D4 4 {&DDRD, &PIND, &PORTD, 5}, // D5 5 {&DDRD, &PIND, &PORTD, 6}, // D6 6 {&DDRD, &PIND, &PORTD, 7}, // D7 7 {&DDRE, &PINE, &PORTE, 0}, // E0 8 {&DDRE, &PINE, &PORTE, 1}, // E1 9 {&DDRC, &PINC, &PORTC, 0}, // C0 10 {&DDRC, &PINC, &PORTC, 1}, // C1 11 {&DDRC, &PINC, &PORTC, 2}, // C2 12 {&DDRC, &PINC, &PORTC, 3}, // C3 13 {&DDRC, &PINC, &PORTC, 4}, // C4 14 {&DDRC, &PINC, &PORTC, 5}, // C5 15 {&DDRC, &PINC, &PORTC, 6}, // C6 16 {&DDRC, &PINC, &PORTC, 7}, // C7 17 {&DDRE, &PINE, &PORTE, 6}, // E6 18 {&DDRE, &PINE, &PORTE, 7}, // E7 19 {&DDRB, &PINB, &PORTB, 0}, // B0 20 {&DDRB, &PINB, &PORTB, 1}, // B1 21 {&DDRB, &PINB, &PORTB, 2}, // B2 22 {&DDRB, &PINB, &PORTB, 3}, // B3 23 {&DDRB, &PINB, &PORTB, 4}, // B4 24 {&DDRB, &PINB, &PORTB, 5}, // B5 25 {&DDRB, &PINB, &PORTB, 6}, // B6 26 {&DDRB, &PINB, &PORTB, 7}, // B7 27 {&DDRA, &PINA, &PORTA, 0}, // A0 28 {&DDRA, &PINA, &PORTA, 1}, // A1 29 {&DDRA, &PINA, &PORTA, 2}, // A2 30 {&DDRA, &PINA, &PORTA, 3}, // A3 31 {&DDRA, &PINA, &PORTA, 4}, // A4 32 {&DDRA, &PINA, &PORTA, 5}, // A5 33 {&DDRA, &PINA, &PORTA, 6}, // A6 34 {&DDRA, &PINA, &PORTA, 7}, // A7 35 {&DDRE, &PINE, &PORTE, 4}, // E4 36 {&DDRE, &PINE, &PORTE, 5}, // E5 37 {&DDRF, &PINF, &PORTF, 0}, // F0 38 {&DDRF, &PINF, &PORTF, 1}, // F1 39 {&DDRF, &PINF, &PORTF, 2}, // F2 40 {&DDRF, &PINF, &PORTF, 3}, // F3 41 {&DDRF, &PINF, &PORTF, 4}, // F4 42 {&DDRF, &PINF, &PORTF, 5}, // F5 43 {&DDRF, &PINF, &PORTF, 6}, // F6 44 {&DDRF, &PINF, &PORTF, 7} // F7 45 }; #else // CPU type #error "Unknown CPU type for Software SPI" #endif // CPU type /** count of pins */ static constexpr uint8_t digitalPinCount = sizeof(pinMap) / sizeof(pin_map_t); /** generate bad pin number error */ void badPinNumber() __attribute__((error("Pin number is too large or not a constant"))); /** * Check for valid pin number * @param[in] pin Number of pin to be checked. */ FORCE_INLINE static void badPinCheck(const uint8_t pin) { if (!__builtin_constant_p(pin) || pin >= digitalPinCount) badPinNumber(); } /** * Fast write helper * @param[in] address I/O register address * @param[in] bit bit number to write * @param[in] level value for bit */ FORCE_INLINE static void fastBitWriteSafe(volatile uint8_t* address, uint8_t bit, bool level) { uint8_t oldSREG; if (address > (uint8_t*)0x5F) { oldSREG = SREG; cli(); } if (level) SBI(*address, bit); else CBI(*address, bit); if (address > (uint8_t*)0x5F) SREG = oldSREG; } /** * Read pin value * @param[in] pin Arduino pin number * @return value read */ FORCE_INLINE static bool fastDigitalRead(uint8_t pin) { badPinCheck(pin); return (*pinMap[pin].pin >> pinMap[pin].bit) & 1; } /** * Toggle a pin * @param[in] pin Arduino pin number * * If the pin is in output mode toggle the pin level. * If the pin is in input mode toggle the state of the 20K pullup. */ FORCE_INLINE static void fastDigitalToggle(uint8_t pin) { badPinCheck(pin); if (pinMap[pin].pin > (uint8_t*)0x5F) *pinMap[pin].pin = _BV(pinMap[pin].bit); // Must write bit to high address port else SBI(*pinMap[pin].pin, pinMap[pin].bit); // Compiles to sbi and PIN register will not be read } /** * Set pin value * @param[in] pin Arduino pin number * @param[in] level value to write */ FORCE_INLINE static void fastDigitalWrite(uint8_t pin, bool level) { badPinCheck(pin); fastBitWriteSafe(pinMap[pin].port, pinMap[pin].bit, level); } /** * Set pin mode * @param[in] pin Arduino pin number * @param[in] mode if true set output mode else input mode * * fastPinMode does not enable or disable the 20K pullup for input mode. */ FORCE_INLINE static void fastPinMode(uint8_t pin, bool mode) { badPinCheck(pin); fastBitWriteSafe(pinMap[pin].ddr, pinMap[pin].bit, mode); } #endif // !__arm__ /** * Set pin configuration * @param[in] pin Arduino pin number * @param[in] mode If true set output mode else input mode * @param[in] level If mode is output, set level high/low. * If mode is input, enable or disable the pin's 20K pullup. */ FORCE_INLINE static void fastPinConfig(uint8_t pin, bool mode, bool level) { fastPinMode(pin, mode); fastDigitalWrite(pin, level); } /** * @class DigitalPin * @brief Fast digital port I/O */ template<uint8_t PinNumber> class DigitalPin { public: /** Constructor */ DigitalPin() {} /** * Constructor * @param[in] pinMode if true set output mode else input mode. */ explicit DigitalPin(bool pinMode) { mode(pinMode); } /** * Constructor * @param[in] mode If true set output mode else input mode * @param[in] level If mode is output, set level high/low. * If mode is input, enable or disable the pin's 20K pullup. */ DigitalPin(bool mode, bool level) { config(mode, level); } /** * Assignment operator * @param[in] value If true set the pin's level high else set the * pin's level low. * * @return This DigitalPin instance. */ FORCE_INLINE DigitalPin & operator = (bool value) { write(value); return *this; } /** * Parentheses operator * @return Pin's level */ FORCE_INLINE operator bool () const { return read(); } /** * Set pin configuration * @param[in] mode If true set output mode else input mode * @param[in] level If mode is output, set level high/low. * If mode is input, enable or disable the pin's 20K pullup. */ FORCE_INLINE void config(bool mode, bool level) { fastPinConfig(PinNumber, mode, level); } /** * Set pin level high if output mode or enable 20K pullup if input mode. */ FORCE_INLINE void high() { write(true); } /** * Set pin level low if output mode or disable 20K pullup if input mode. */ FORCE_INLINE void low() { write(false); } /** * Set pin mode * @param[in] pinMode if true set output mode else input mode. * * mode() does not enable or disable the 20K pullup for input mode. */ FORCE_INLINE void mode(bool pinMode) { fastPinMode(PinNumber, pinMode); } /** @return Pin's level */ FORCE_INLINE bool read() const { return fastDigitalRead(PinNumber); } /** * Toggle a pin * If the pin is in output mode toggle the pin's level. * If the pin is in input mode toggle the state of the 20K pullup. */ FORCE_INLINE void toggle() { fastDigitalToggle(PinNumber); } /** * Write the pin's level. * @param[in] value If true set the pin's level high else set the * pin's level low. */ FORCE_INLINE void write(bool value) { fastDigitalWrite(PinNumber, value); } }; const bool MISO_MODE = false, // Pin Mode for MISO is input. MISO_LEVEL = false, // Pullups disabled for MISO are disabled. MOSI_MODE = true, // Pin Mode for MOSI is output. SCK_MODE = true; // Pin Mode for SCK is output. /** * @class SoftSPI * @brief Fast software SPI. */ template<uint8_t MisoPin, uint8_t MosiPin, uint8_t SckPin, uint8_t Mode = 0> class SoftSPI { public: /** Initialize SoftSPI pins. */ void begin() { fastPinConfig(MisoPin, MISO_MODE, MISO_LEVEL); fastPinConfig(MosiPin, MOSI_MODE, !MODE_CPHA(Mode)); fastPinConfig(SckPin, SCK_MODE, MODE_CPOL(Mode)); } /** * Soft SPI receive byte. * @return Data byte received. */ FORCE_INLINE uint8_t receive() { uint8_t data = 0; receiveBit(7, &data); receiveBit(6, &data); receiveBit(5, &data); receiveBit(4, &data); receiveBit(3, &data); receiveBit(2, &data); receiveBit(1, &data); receiveBit(0, &data); return data; } /** * Soft SPI send byte. * @param[in] data Data byte to send. */ FORCE_INLINE void send(uint8_t data) { sendBit(7, data); sendBit(6, data); sendBit(5, data); sendBit(4, data); sendBit(3, data); sendBit(2, data); sendBit(1, data); sendBit(0, data); } /** * Soft SPI transfer byte. * @param[in] txData Data byte to send. * @return Data byte received. */ FORCE_INLINE uint8_t transfer(uint8_t txData) { uint8_t rxData = 0; transferBit(7, &rxData, txData); transferBit(6, &rxData, txData); transferBit(5, &rxData, txData); transferBit(4, &rxData, txData); transferBit(3, &rxData, txData); transferBit(2, &rxData, txData); transferBit(1, &rxData, txData); transferBit(0, &rxData, txData); return rxData; } private: FORCE_INLINE bool MODE_CPHA(uint8_t mode) { return bool(mode & 1); } FORCE_INLINE bool MODE_CPOL(uint8_t mode) { return bool(mode & 2); } FORCE_INLINE void receiveBit(uint8_t bit, uint8_t *data) { if (MODE_CPHA(Mode)) fastDigitalWrite(SckPin, !MODE_CPOL(Mode)); nop; nop; fastDigitalWrite(SckPin, MODE_CPHA(Mode) ? MODE_CPOL(Mode) : !MODE_CPOL(Mode)); if (fastDigitalRead(MisoPin)) SBI(*data, bit); if (!MODE_CPHA(Mode)) fastDigitalWrite(SckPin, MODE_CPOL(Mode)); } FORCE_INLINE void sendBit(uint8_t bit, uint8_t data) { if (MODE_CPHA(Mode)) fastDigitalWrite(SckPin, !MODE_CPOL(Mode)); fastDigitalWrite(MosiPin, data & _BV(bit)); fastDigitalWrite(SckPin, MODE_CPHA(Mode) ? MODE_CPOL(Mode) : !MODE_CPOL(Mode)); nop; nop; if (!MODE_CPHA(Mode)) fastDigitalWrite(SckPin, MODE_CPOL(Mode)); } FORCE_INLINE void transferBit(uint8_t bit, uint8_t *rxData, uint8_t txData) { if (MODE_CPHA(Mode)) fastDigitalWrite(SckPin, !MODE_CPOL(Mode)); fastDigitalWrite(MosiPin, txData & _BV(bit)); fastDigitalWrite(SckPin, MODE_CPHA(Mode) ? MODE_CPOL(Mode) : !MODE_CPOL(Mode)); if (fastDigitalRead(MisoPin)) SBI(*rxData, bit); if (!MODE_CPHA(Mode)) fastDigitalWrite(SckPin, MODE_CPOL(Mode)); } };
2301_81045437/Marlin
Marlin/src/libs/softspi.h
C++
agpl-3.0
25,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/>. * */ #include "stopwatch.h" #include "../inc/MarlinConfig.h" #if ENABLED(EXTENSIBLE_UI) #include "../lcd/extui/ui_api.h" #endif Stopwatch::State Stopwatch::state; millis_t Stopwatch::accumulator; millis_t Stopwatch::startTimestamp; millis_t Stopwatch::stopTimestamp; bool Stopwatch::stop() { debug(F("stop")); if (isRunning() || isPaused()) { TERN_(EXTENSIBLE_UI, ExtUI::onPrintTimerStopped()); state = STOPPED; stopTimestamp = millis(); return true; } else return false; } bool Stopwatch::pause() { debug(F("pause")); if (isRunning()) { TERN_(EXTENSIBLE_UI, ExtUI::onPrintTimerPaused()); state = PAUSED; stopTimestamp = millis(); return true; } else return false; } bool Stopwatch::start() { debug(F("start")); TERN_(EXTENSIBLE_UI, ExtUI::onPrintTimerStarted()); if (!isRunning()) { if (isPaused()) accumulator = duration(); else reset(); state = RUNNING; startTimestamp = millis(); return true; } else return false; } void Stopwatch::resume(const millis_t with_time) { debug(F("resume")); reset(); if ((accumulator = with_time)) state = RUNNING; } void Stopwatch::reset() { debug(F("reset")); state = STOPPED; startTimestamp = 0; stopTimestamp = 0; accumulator = 0; } millis_t Stopwatch::duration() { return accumulator + MS_TO_SEC((isRunning() ? millis() : stopTimestamp) - startTimestamp); } #if ENABLED(DEBUG_STOPWATCH) void Stopwatch::debug(FSTR_P const func) { if (DEBUGGING(INFO)) SERIAL_ECHOLNPGM("Stopwatch::", func, "()"); } #endif
2301_81045437/Marlin
Marlin/src/libs/stopwatch.cpp
C++
agpl-3.0
2,426
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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" // Print debug messages with M111 S2 (Uses 156 bytes of PROGMEM) //#define DEBUG_STOPWATCH /** * @brief Stopwatch class * @details This class acts as a timer proving stopwatch functionality including * the ability to pause the running time counter. */ class Stopwatch { private: enum State : char { STOPPED, RUNNING, PAUSED }; static Stopwatch::State state; static millis_t accumulator; static millis_t startTimestamp; static millis_t stopTimestamp; public: /** * @brief Initialize the stopwatch */ FORCE_INLINE static void init() { reset(); } /** * @brief Stop the stopwatch * @details Stop the running timer, it will silently ignore the request if * no timer is currently running. * @return true on success */ static bool stop(); static bool abort() { return stop(); } // Alias by default /** * @brief Pause the stopwatch * @details Pause the running timer, it will silently ignore the request if * no timer is currently running. * @return true on success */ static bool pause(); /** * @brief Start the stopwatch * @details Start the timer, it will silently ignore the request if the * timer is already running. * @return true on success */ static bool start(); /** * @brief Resume the stopwatch * @details Resume a timer from a given duration */ static void resume(const millis_t with_time); /** * @brief Reset the stopwatch * @details Reset all settings to their default values. */ static void reset(); /** * @brief Check if the timer is running * @details Return true if the timer is currently running, false otherwise. * @return true if stopwatch is running */ FORCE_INLINE static bool isRunning() { return state == RUNNING; } /** * @brief Check if the timer is paused * @details Return true if the timer is currently paused, false otherwise. * @return true if stopwatch is paused */ FORCE_INLINE static bool isPaused() { return state == PAUSED; } /** * @brief Get the running time * @details Return the total number of seconds the timer has been running. * @return the delta since starting the stopwatch */ static millis_t duration(); #ifdef DEBUG_STOPWATCH /** * @brief Print a debug message * @details Print a simple debug message "Stopwatch::function" */ static void debug(FSTR_P const); #else static void debug(FSTR_P const) {} #endif };
2301_81045437/Marlin
Marlin/src/libs/stopwatch.h
C++
agpl-3.0
3,532
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * vector_3.cpp - Vector library for bed leveling * Copyright (c) 2012 Lars Brubaker. All right reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../inc/MarlinConfig.h" #if ABL_PLANAR || ENABLED(AUTO_BED_LEVELING_UBL) #include "vector_3.h" #include <math.h> /** * vector_3 */ vector_3 vector_3::cross(const vector_3 &left, const vector_3 &right) { return vector_3(left.y * right.z - left.z * right.y, // YZ cross left.z * right.x - left.x * right.z, // ZX cross left.x * right.y - left.y * right.x); // XY cross } vector_3 vector_3::get_normal() const { vector_3 normalized = *this; normalized.normalize(); return normalized; } float vector_3::magnitude() const { return SQRT(sq(x) + sq(y) + sq(z)); } void vector_3::normalize() { *this *= RSQRT(sq(x) + sq(y) + sq(z)); } // Apply a rotation to the matrix void vector_3::apply_rotation(const matrix_3x3 &matrix) { const float _x = x, _y = y, _z = z; *this = { matrix.vectors[0].x * _x + matrix.vectors[1].x * _y + matrix.vectors[2].x * _z, matrix.vectors[0].y * _x + matrix.vectors[1].y * _y + matrix.vectors[2].y * _z, matrix.vectors[0].z * _x + matrix.vectors[1].z * _y + matrix.vectors[2].z * _z }; } void vector_3::debug(FSTR_P const title) { SERIAL_ECHOLN(title, FPSTR(SP_X_STR), p_float_t(x, 6), FPSTR(SP_Y_STR), p_float_t(y, 6), FPSTR(SP_Z_STR), p_float_t(z, 6) ); } /** * matrix_3x3 */ void matrix_3x3::apply_rotation_xyz(float &_x, float &_y, float &_z) { vector_3 vec = vector_3(_x, _y, _z); vec.apply_rotation(*this); _x = vec.x; _y = vec.y; _z = vec.z; } // Reset to identity. No rotate or translate. void matrix_3x3::set_to_identity() { for (uint8_t i = 0; i < 3; ++i) for (uint8_t j = 0; j < 3; ++j) vectors[i][j] = float(i == j); } // Create a matrix from 3 vector_3 inputs matrix_3x3 matrix_3x3::create_from_rows(const vector_3 &row_0, const vector_3 &row_1, const vector_3 &row_2) { //row_0.debug(F("row_0")); //row_1.debug(F("row_1")); //row_2.debug(F("row_2")); matrix_3x3 new_matrix; new_matrix.vectors[0] = row_0; new_matrix.vectors[1] = row_1; new_matrix.vectors[2] = row_2; //new_matrix.debug(F("new_matrix")); return new_matrix; } // Create a matrix rotated to point towards a target matrix_3x3 matrix_3x3::create_look_at(const vector_3 &target) { const vector_3 z_row = target.get_normal(), x_row = vector_3(1, 0, -target.x / target.z).get_normal(), y_row = vector_3::cross(z_row, x_row).get_normal(); // x_row.debug(F("x_row")); // y_row.debug(F("y_row")); // z_row.debug(F("z_row")); // create the matrix already correctly transposed matrix_3x3 rot = matrix_3x3::create_from_rows(x_row, y_row, z_row); // rot.debug(F("rot")); return rot; } // Get a transposed copy of the matrix matrix_3x3 matrix_3x3::transpose(const matrix_3x3 &original) { matrix_3x3 new_matrix; for (uint8_t i = 0; i < 3; ++i) for (uint8_t j = 0; j < 3; ++j) new_matrix.vectors[i][j] = original.vectors[j][i]; return new_matrix; } void matrix_3x3::debug(FSTR_P const title) { if (title) SERIAL_ECHOLN(title); for (uint8_t i = 0; i < 3; ++i) { for (uint8_t j = 0; j < 3; ++j) { serial_offset(vectors[i][j], 2); SERIAL_CHAR(' '); } SERIAL_EOL(); } } #endif // HAS_ABL_OR_UBL
2301_81045437/Marlin
Marlin/src/libs/vector_3.cpp
C++
agpl-3.0
4,951
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 /** * vector_3.cpp - Vector library for bed leveling * Copyright (c) 2012 Lars Brubaker. All right reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../core/types.h" class matrix_3x3; struct vector_3 { union { struct { float x, y, z; }; float pos[3]; }; vector_3(const_float_t _x, const_float_t _y, const_float_t _z) : x(_x), y(_y), z(_z) {} vector_3(const xy_float_t &in) { TERN_(HAS_X_AXIS, x = in.x); TERN_(HAS_Y_AXIS, y = in.y); } vector_3(const xyz_float_t &in) { TERN_(HAS_X_AXIS, x = in.x); TERN_(HAS_Y_AXIS, y = in.y); TERN_(HAS_Z_AXIS, z = in.z); } vector_3(const xyze_float_t &in) { TERN_(HAS_X_AXIS, x = in.x); TERN_(HAS_Y_AXIS, y = in.y); TERN_(HAS_Z_AXIS, z = in.z); } vector_3() { x = y = z = 0; } // Factory method static vector_3 cross(const vector_3 &a, const vector_3 &b); // Modifiers void normalize(); void apply_rotation(const matrix_3x3 &matrix); // Accessors float magnitude() const; vector_3 get_normal() const; // Operators float& operator[](const int n) { return pos[n]; } const float& operator[](const int n) const { return pos[n]; } vector_3& operator*=(const float &v) { x *= v; y *= v; z *= v; return *this; } vector_3 operator+(const vector_3 &v) { return vector_3(x + v.x, y + v.y, z + v.z); } vector_3 operator-(const vector_3 &v) { return vector_3(x - v.x, y - v.y, z - v.z); } vector_3 operator*(const float &v) { return vector_3(x * v, y * v, z * v); } operator xy_float_t() { return xy_float_t({ TERN_(HAS_X_AXIS, x) OPTARG(HAS_Y_AXIS, y) }); } operator xyz_float_t() { return xyz_float_t({ TERN_(HAS_X_AXIS, x) OPTARG(HAS_Y_AXIS, y) OPTARG(HAS_Z_AXIS, z) }); } void debug(FSTR_P const title); }; struct matrix_3x3 { vector_3 vectors[3]; // Factory methods static matrix_3x3 create_from_rows(const vector_3 &row_0, const vector_3 &row_1, const vector_3 &row_2); static matrix_3x3 create_look_at(const vector_3 &target); static matrix_3x3 transpose(const matrix_3x3 &original); void set_to_identity(); void debug(FSTR_P const title); void apply_rotation_xyz(float &x, float &y, float &z); };
2301_81045437/Marlin
Marlin/src/libs/vector_3.h
C++
agpl-3.0
3,729
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * delta.cpp */ #include "../inc/MarlinConfig.h" #if ENABLED(DELTA) #include "delta.h" #include "motion.h" // For homing: #include "planner.h" #include "endstops.h" #include "../lcd/marlinui.h" #include "../MarlinCore.h" #if HAS_BED_PROBE #include "probe.h" #endif #if ENABLED(SENSORLESS_HOMING) #include "../feature/tmc_util.h" #include "stepper/indirection.h" #endif #define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) #include "../core/debug_out.h" // Initialized by settings.load() float delta_height; abc_float_t delta_endstop_adj{0}; float delta_radius, delta_diagonal_rod, segments_per_second; abc_float_t delta_tower_angle_trim; xy_float_t delta_tower[ABC]; abc_float_t delta_diagonal_rod_2_tower; float delta_clip_start_height = Z_MAX_POS; abc_float_t delta_diagonal_rod_trim; float delta_safe_distance_from_top(); void refresh_delta_clip_start_height() { delta_clip_start_height = TERN(HAS_SOFTWARE_ENDSTOPS, soft_endstop.max.z, DIFF_TERN(HAS_BED_PROBE, delta_height, probe.offset.z) ) - delta_safe_distance_from_top(); } /** * Recalculate factors used for delta kinematics whenever * settings have been changed (e.g., by M665). */ void recalc_delta_settings() { constexpr abc_float_t trt = DELTA_RADIUS_TRIM_TOWER; delta_tower[A_AXIS].set(cos(RADIANS(210 + delta_tower_angle_trim.a)) * (delta_radius + trt.a), // front left tower sin(RADIANS(210 + delta_tower_angle_trim.a)) * (delta_radius + trt.a)); delta_tower[B_AXIS].set(cos(RADIANS(330 + delta_tower_angle_trim.b)) * (delta_radius + trt.b), // front right tower sin(RADIANS(330 + delta_tower_angle_trim.b)) * (delta_radius + trt.b)); delta_tower[C_AXIS].set(cos(RADIANS( 90 + delta_tower_angle_trim.c)) * (delta_radius + trt.c), // back middle tower sin(RADIANS( 90 + delta_tower_angle_trim.c)) * (delta_radius + trt.c)); delta_diagonal_rod_2_tower.set(sq(delta_diagonal_rod + delta_diagonal_rod_trim.a), sq(delta_diagonal_rod + delta_diagonal_rod_trim.b), sq(delta_diagonal_rod + delta_diagonal_rod_trim.c)); update_software_endstops(Z_AXIS); set_all_unhomed(); } /** * Delta Inverse Kinematics * * Calculate the tower positions for a given machine * position, storing the result in the delta[] array. * * This is an expensive calculation, requiring 3 square * roots per segmented linear move, and strains the limits * of a Mega2560 with a Graphical Display. * * Suggested optimizations include: * * - Disable the home_offset (M206) and/or workspace_offset (G92) * features to remove up to 12 float additions. */ #define DELTA_DEBUG(VAR) do { \ SERIAL_ECHOLNPGM_P(PSTR("Cartesian X"), VAR.x, SP_Y_STR, VAR.y, SP_Z_STR, VAR.z); \ SERIAL_ECHOLNPGM_P(PSTR("Delta A"), delta.a, SP_B_STR, delta.b, SP_C_STR, delta.c); \ }while(0) void inverse_kinematics(const xyz_pos_t &raw) { #if HAS_HOTEND_OFFSET // Delta hotend offsets must be applied in Cartesian space with no "spoofing" xyz_pos_t pos = { raw.x - hotend_offset[active_extruder].x, raw.y - hotend_offset[active_extruder].y, raw.z }; DELTA_IK(pos); //DELTA_DEBUG(pos); #else DELTA_IK(raw); //DELTA_DEBUG(raw); #endif } /** * Calculate the highest Z position where the * effector has the full range of XY motion. */ float delta_safe_distance_from_top() { xyz_pos_t cartesian{0}; inverse_kinematics(cartesian); const float centered_extent = delta.a; cartesian.y = PRINTABLE_RADIUS; inverse_kinematics(cartesian); return ABS(centered_extent - delta.a); } /** * Delta Forward Kinematics * * See the Wikipedia article "Trilateration" * https://en.wikipedia.org/wiki/Trilateration * * Establish a new coordinate system in the plane of the * three carriage points. This system has its origin at * tower1, with tower2 on the X axis. Tower3 is in the X-Y * plane with a Z component of zero. * We will define unit vectors in this coordinate system * in our original coordinate system. Then when we calculate * the Xnew, Ynew and Znew values, we can translate back into * the original system by moving along those unit vectors * by the corresponding values. * * Variable names matched to Marlin, c-version, and avoid the * use of any vector library. * * by Andreas Hardtung 2016-06-07 * based on a Java function from "Delta Robot Kinematics V3" * by Steve Graves * * The result is stored in the cartes[] array. */ void forward_kinematics(const_float_t z1, const_float_t z2, const_float_t z3) { // Create a vector in old coordinates along x axis of new coordinate const float p12[3] = { delta_tower[B_AXIS].x - delta_tower[A_AXIS].x, delta_tower[B_AXIS].y - delta_tower[A_AXIS].y, z2 - z1 }, // Get the reciprocal of Magnitude of vector. d2 = sq(p12[0]) + sq(p12[1]) + sq(p12[2]), inv_d = RSQRT(d2), // Create unit vector by multiplying by the inverse of the magnitude. ex[3] = { p12[0] * inv_d, p12[1] * inv_d, p12[2] * inv_d }, // Get the vector from the origin of the new system to the third point. p13[3] = { delta_tower[C_AXIS].x - delta_tower[A_AXIS].x, delta_tower[C_AXIS].y - delta_tower[A_AXIS].y, z3 - z1 }, // Use the dot product to find the component of this vector on the X axis. i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2], // Create a vector along the x axis that represents the x component of p13. iex[3] = { ex[0] * i, ex[1] * i, ex[2] * i }; // Subtract the X component from the original vector leaving only Y. We use the // variable that will be the unit vector after we scale it. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] }; // The magnitude and the inverse of the magnitude of Y component const float j2 = sq(ey[0]) + sq(ey[1]) + sq(ey[2]), inv_j = RSQRT(j2); // Convert to a unit vector ey[0] *= inv_j; ey[1] *= inv_j; ey[2] *= inv_j; // The cross product of the unit x and y is the unit z // float[] ez = vectorCrossProd(ex, ey); const float ez[3] = { ex[1] * ey[2] - ex[2] * ey[1], ex[2] * ey[0] - ex[0] * ey[2], ex[0] * ey[1] - ex[1] * ey[0] }, // We now have the d, i and j values defined in Wikipedia. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew Xnew = (delta_diagonal_rod_2_tower.a - delta_diagonal_rod_2_tower.b + d2) * inv_d * 0.5, Ynew = ((delta_diagonal_rod_2_tower.a - delta_diagonal_rod_2_tower.c + sq(i) + j2) * 0.5 - i * Xnew) * inv_j, Znew = SQRT(delta_diagonal_rod_2_tower.a - HYPOT2(Xnew, Ynew)); // Start from the origin of the old coordinates and add vectors in the // old coords that represent the Xnew, Ynew and Znew to find the point // in the old system. cartes.set(delta_tower[A_AXIS].x + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew, delta_tower[A_AXIS].y + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew, z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew); } /** * A delta can only safely home all axes at the same time * This is like quick_home_xy() but for 3 towers. */ void home_delta() { DEBUG_SECTION(log_home_delta, "home_delta", DEBUGGING(LEVELING)); // Init the current position of all carriages to 0,0,0 current_position.reset(); destination.reset(); sync_plan_position(); // Disable stealthChop if used. Enable diag1 pin on driver. #if ENABLED(SENSORLESS_HOMING) TERN_(X_SENSORLESS, sensorless_t stealth_states_x = start_sensorless_homing_per_axis(X_AXIS)); TERN_(Y_SENSORLESS, sensorless_t stealth_states_y = start_sensorless_homing_per_axis(Y_AXIS)); TERN_(Z_SENSORLESS, sensorless_t stealth_states_z = start_sensorless_homing_per_axis(Z_AXIS)); TERN_(I_SENSORLESS, sensorless_t stealth_states_i = start_sensorless_homing_per_axis(I_AXIS)); TERN_(J_SENSORLESS, sensorless_t stealth_states_j = start_sensorless_homing_per_axis(J_AXIS)); TERN_(K_SENSORLESS, sensorless_t stealth_states_k = start_sensorless_homing_per_axis(K_AXIS)); TERN_(U_SENSORLESS, sensorless_t stealth_states_u = start_sensorless_homing_per_axis(U_AXIS)); TERN_(V_SENSORLESS, sensorless_t stealth_states_v = start_sensorless_homing_per_axis(V_AXIS)); TERN_(W_SENSORLESS, sensorless_t stealth_states_w = start_sensorless_homing_per_axis(W_AXIS)); #if SENSORLESS_STALLGUARD_DELAY safe_delay(SENSORLESS_STALLGUARD_DELAY); // Short delay needed to settle #endif #endif // Move all carriages together linearly until an endstop is hit. current_position.z = DIFF_TERN(USE_PROBE_FOR_Z_HOMING, delta_height + 10, probe.offset.z); line_to_current_position(homing_feedrate(Z_AXIS)); planner.synchronize(); TERN_(HAS_DELTA_SENSORLESS_PROBING, endstops.report_states()); // Re-enable stealthChop if used. Disable diag1 pin on driver. #if ENABLED(SENSORLESS_HOMING) && DISABLED(ENDSTOPS_ALWAYS_ON_DEFAULT) TERN_(X_SENSORLESS, end_sensorless_homing_per_axis(X_AXIS, stealth_states_x)); TERN_(Y_SENSORLESS, end_sensorless_homing_per_axis(Y_AXIS, stealth_states_y)); TERN_(Z_SENSORLESS, end_sensorless_homing_per_axis(Z_AXIS, stealth_states_z)); TERN_(I_SENSORLESS, end_sensorless_homing_per_axis(I_AXIS, stealth_states_i)); TERN_(J_SENSORLESS, end_sensorless_homing_per_axis(J_AXIS, stealth_states_j)); TERN_(K_SENSORLESS, end_sensorless_homing_per_axis(K_AXIS, stealth_states_k)); TERN_(U_SENSORLESS, end_sensorless_homing_per_axis(U_AXIS, stealth_states_u)); TERN_(V_SENSORLESS, end_sensorless_homing_per_axis(V_AXIS, stealth_states_v)); TERN_(W_SENSORLESS, end_sensorless_homing_per_axis(W_AXIS, stealth_states_w)); #if SENSORLESS_STALLGUARD_DELAY safe_delay(SENSORLESS_STALLGUARD_DELAY); // Short delay needed to settle #endif #endif endstops.validate_homing_move(); // At least one carriage has reached the top. // Now re-home each carriage separately. homeaxis(A_AXIS); homeaxis(B_AXIS); homeaxis(C_AXIS); // Set all carriages to their home positions // Do this here all at once for Delta, because // XYZ isn't ABC. Applying this per-tower would // give the impression that they are the same. LOOP_ABC(i) set_axis_is_at_home((AxisEnum)i); sync_plan_position(); #if DISABLED(DELTA_HOME_TO_SAFE_ZONE) && defined(HOMING_BACKOFF_POST_MM) constexpr xyz_float_t endstop_backoff = HOMING_BACKOFF_POST_MM; if (endstop_backoff.z) { current_position.z -= ABS(endstop_backoff.z) * Z_HOME_DIR; line_to_current_position(homing_feedrate(Z_AXIS)); } #endif } #endif // DELTA
2301_81045437/Marlin
Marlin/src/module/delta.cpp
C++
agpl-3.0
11,486
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 /** * delta.h - Delta-specific functions */ #include "../core/types.h" #include "../core/macros.h" extern float delta_height; extern abc_float_t delta_endstop_adj; extern float delta_radius, delta_diagonal_rod, segments_per_second; extern abc_float_t delta_tower_angle_trim; extern xy_float_t delta_tower[ABC]; extern abc_float_t delta_diagonal_rod_2_tower; extern float delta_clip_start_height; extern abc_float_t delta_diagonal_rod_trim; /** * Recalculate factors used for delta kinematics whenever * settings have been changed (e.g., by M665). */ void recalc_delta_settings(); /** * Get a safe radius for calibration */ #if HAS_DELTA_SENSORLESS_PROBING static constexpr float sensorless_radius_factor = 0.7f; #endif /** * Delta Inverse Kinematics * * Calculate the tower positions for a given machine * position, storing the result in the delta[] array. * * This is an expensive calculation, requiring 3 square * roots per segmented linear move, and strains the limits * of a Mega2560 with a Graphical Display. * * Suggested optimizations include: * * - Disable the home_offset (M206) and/or workspace_offset (G92) * features to remove up to 12 float additions. * * - Use a fast-inverse-sqrt function and add the reciprocal. * (see above) */ // Macro to obtain the Z position of an individual tower #define DELTA_Z(V,T) V.z + SQRT( \ delta_diagonal_rod_2_tower[T] - HYPOT2( \ delta_tower[T].x - V.x, \ delta_tower[T].y - V.y \ ) \ ) #define DELTA_IK(V) delta.set(DELTA_Z(V, A_AXIS), DELTA_Z(V, B_AXIS), DELTA_Z(V, C_AXIS)) void inverse_kinematics(const xyz_pos_t &raw); /** * Calculate the highest Z position where the * effector has the full range of XY motion. */ float delta_safe_distance_from_top(); void refresh_delta_clip_start_height(); /** * Delta Forward Kinematics * * See the Wikipedia article "Trilateration" * https://en.wikipedia.org/wiki/Trilateration * * Establish a new coordinate system in the plane of the * three carriage points. This system has its origin at * tower1, with tower2 on the X axis. Tower3 is in the X-Y * plane with a Z component of zero. * We will define unit vectors in this coordinate system * in our original coordinate system. Then when we calculate * the Xnew, Ynew and Znew values, we can translate back into * the original system by moving along those unit vectors * by the corresponding values. * * Variable names matched to Marlin, c-version, and avoid the * use of any vector library. * * by Andreas Hardtung 2016-06-07 * based on a Java function from "Delta Robot Kinematics V3" * by Steve Graves * * The result is stored in the cartes[] array. */ void forward_kinematics(const_float_t z1, const_float_t z2, const_float_t z3); FORCE_INLINE void forward_kinematics(const abc_float_t &point) { forward_kinematics(point.a, point.b, point.c); } void home_delta();
2301_81045437/Marlin
Marlin/src/module/delta.h
C
agpl-3.0
3,874
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * endstops.cpp - A singleton object to manage endstops */ #include "endstops.h" #include "stepper.h" #include "../sd/cardreader.h" #include "temperature.h" #include "../lcd/marlinui.h" #define DEBUG_OUT ALL(USE_SENSORLESS, DEBUG_LEVELING_FEATURE) #include "../core/debug_out.h" #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE) #include HAL_PATH(.., endstop_interrupts.h) #endif #if ENABLED(SD_ABORT_ON_ENDSTOP_HIT) #include "printcounter.h" // for print_job_timer #endif #if ENABLED(BLTOUCH) #include "../feature/bltouch.h" #endif #if ENABLED(JOYSTICK) #include "../feature/joystick.h" #endif #if ENABLED(FT_MOTION) #include "ft_motion.h" #endif #if HAS_BED_PROBE #include "probe.h" #endif Endstops endstops; // private: bool Endstops::enabled, Endstops::enabled_globally; // Initialized by settings.load() volatile Endstops::endstop_mask_t Endstops::hit_state; Endstops::endstop_mask_t Endstops::live_state = 0; #if ENABLED(BD_SENSOR) bool Endstops::bdp_state; // = false #if HOMING_Z_WITH_PROBE #define READ_ENDSTOP(P) ((P == TERN(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN, Z_MIN_PIN, Z_MIN_PROBE_PIN)) ? bdp_state : READ(P)) #else #define READ_ENDSTOP(P) READ(P) #endif #else #define READ_ENDSTOP(P) READ(P) #endif #if ENDSTOP_NOISE_THRESHOLD Endstops::endstop_mask_t Endstops::validated_live_state; uint8_t Endstops::endstop_poll_count; #endif #if HAS_BED_PROBE volatile bool Endstops::z_probe_enabled = false; #endif // Initialized by settings.load() #if ENABLED(X_DUAL_ENDSTOPS) float Endstops::x2_endstop_adj; #endif #if ENABLED(Y_DUAL_ENDSTOPS) float Endstops::y2_endstop_adj; #endif #if ENABLED(Z_MULTI_ENDSTOPS) float Endstops::z2_endstop_adj; #if NUM_Z_STEPPERS >= 3 float Endstops::z3_endstop_adj; #if NUM_Z_STEPPERS >= 4 float Endstops::z4_endstop_adj; #endif #endif #endif #if ENABLED(SPI_ENDSTOPS) Endstops::tmc_spi_homing_t Endstops::tmc_spi_homing; // = 0 #endif #if ENABLED(IMPROVE_HOMING_RELIABILITY) millis_t sg_guard_period; // = 0 #endif /** * Class and Instance Methods */ void Endstops::init() { #define _INIT_ENDSTOP(T,A,N) TERN(ENDSTOPPULLUP_##A##T, SET_INPUT_PULLUP, TERN(ENDSTOPPULLDOWN_##A##T, SET_INPUT_PULLDOWN, SET_INPUT))(A##N##_##T##_PIN) #if USE_X_MIN _INIT_ENDSTOP(MIN,X,); #endif #if USE_X_MAX _INIT_ENDSTOP(MAX,X,); #endif #if USE_X2_MIN _INIT_ENDSTOP(MIN,X,2); #endif #if USE_X2_MAX _INIT_ENDSTOP(MAX,X,2); #endif #if USE_Y_MIN _INIT_ENDSTOP(MIN,Y,); #endif #if USE_Y_MAX _INIT_ENDSTOP(MAX,Y,); #endif #if USE_Y2_MIN _INIT_ENDSTOP(MIN,Y,2); #endif #if USE_Y2_MAX _INIT_ENDSTOP(MAX,Y,2); #endif #if USE_Z_MIN _INIT_ENDSTOP(MIN,Z,); #endif #if USE_Z_MAX _INIT_ENDSTOP(MAX,Z,); #endif #if USE_Z2_MIN _INIT_ENDSTOP(MIN,Z,2); #endif #if USE_Z2_MAX _INIT_ENDSTOP(MAX,Z,2); #endif #if USE_Z3_MIN _INIT_ENDSTOP(MIN,Z,3); #endif #if USE_Z3_MAX _INIT_ENDSTOP(MAX,Z,3); #endif #if USE_Z4_MIN _INIT_ENDSTOP(MIN,Z,4); #endif #if USE_Z4_MAX _INIT_ENDSTOP(MAX,Z,4); #endif #if USE_I_MIN _INIT_ENDSTOP(MIN,I,); #endif #if USE_I_MAX _INIT_ENDSTOP(MAX,I,); #endif #if USE_J_MIN _INIT_ENDSTOP(MIN,J,); #endif #if USE_J_MAX _INIT_ENDSTOP(MAX,J,); #endif #if USE_K_MIN _INIT_ENDSTOP(MIN,K,); #endif #if USE_K_MAX _INIT_ENDSTOP(MAX,K,); #endif #if USE_U_MIN _INIT_ENDSTOP(MIN,U,); #endif #if USE_U_MAX _INIT_ENDSTOP(MAX,U,); #endif #if USE_V_MIN _INIT_ENDSTOP(MIN,V,); #endif #if USE_V_MAX _INIT_ENDSTOP(MAX,V,); #endif #if USE_W_MIN _INIT_ENDSTOP(MIN,W,); #endif #if USE_W_MAX _INIT_ENDSTOP(MAX,W,); #endif #if PIN_EXISTS(CALIBRATION) #if ENABLED(CALIBRATION_PIN_PULLUP) SET_INPUT_PULLUP(CALIBRATION_PIN); #elif ENABLED(CALIBRATION_PIN_PULLDOWN) SET_INPUT_PULLDOWN(CALIBRATION_PIN); #else SET_INPUT(CALIBRATION_PIN); #endif #endif #if USE_Z_MIN_PROBE #if ENABLED(ENDSTOPPULLUP_ZMIN_PROBE) SET_INPUT_PULLUP(Z_MIN_PROBE_PIN); #elif ENABLED(ENDSTOPPULLDOWN_ZMIN_PROBE) SET_INPUT_PULLDOWN(Z_MIN_PROBE_PIN); #else SET_INPUT(Z_MIN_PROBE_PIN); #endif #endif #if ENABLED(PROBE_ACTIVATION_SWITCH) SET_INPUT(PROBE_ACTIVATION_SWITCH_PIN); #endif TERN_(PROBE_TARE, probe.tare()); TERN_(ENDSTOP_INTERRUPTS_FEATURE, setup_endstop_interrupts()); // Enable endstops enable_globally(ENABLED(ENDSTOPS_ALWAYS_ON_DEFAULT)); } // Endstops::init // Called at ~1kHz from Temperature ISR: Poll endstop state if required void Endstops::poll() { TERN_(PINS_DEBUGGING, run_monitor()); // Report changes in endstop status #if DISABLED(ENDSTOP_INTERRUPTS_FEATURE) update(); #elif ENDSTOP_NOISE_THRESHOLD if (endstop_poll_count) update(); #endif } void Endstops::enable_globally(const bool onoff) { enabled_globally = enabled = onoff; resync(); } // Enable / disable endstop checking void Endstops::enable(const bool onoff) { enabled = onoff; resync(); } // Disable / Enable endstops based on ENSTOPS_ONLY_FOR_HOMING and global enable void Endstops::not_homing() { enabled = enabled_globally; } #if ENABLED(VALIDATE_HOMING_ENDSTOPS) // If the last move failed to trigger an endstop, call kill void Endstops::validate_homing_move() { if (trigger_state()) hit_on_purpose(); else kill(GET_TEXT_F(MSG_KILL_HOMING_FAILED)); } #endif // Enable / disable endstop z-probe checking #if HAS_BED_PROBE void Endstops::enable_z_probe(const bool onoff) { z_probe_enabled = onoff; #if PIN_EXISTS(PROBE_ENABLE) WRITE(PROBE_ENABLE_PIN, onoff); #endif resync(); } #endif // Get the stable endstop states when enabled void Endstops::resync() { if (!abort_enabled()) return; // If endstops/probes are disabled the loop below can hang // Wait for Temperature ISR to run at least once (runs at 1kHz) TERN(ENDSTOP_INTERRUPTS_FEATURE, update(), safe_delay(2)); while (TERN0(ENDSTOP_NOISE_THRESHOLD, endstop_poll_count)) safe_delay(1); } #if ENABLED(PINS_DEBUGGING) void Endstops::run_monitor() { if (!monitor_flag) return; static uint8_t monitor_count = 16; // offset this check from the others monitor_count += _BV(1); // 15 Hz monitor_count &= 0x7F; if (!monitor_count) monitor(); // report changes in endstop status } #endif void Endstops::event_handler() { static endstop_mask_t prev_hit_state; // = 0 if (hit_state == prev_hit_state) return; prev_hit_state = hit_state; if (hit_state) { #if HAS_STATUS_MESSAGE char NUM_AXIS_LIST_(chrX = ' ', chrY = ' ', chrZ = ' ', chrI = ' ', chrJ = ' ', chrK = ' ', chrU = ' ', chrV = ' ', chrW = ' ') chrP = ' '; #define _SET_STOP_CHAR(A,C) (chr## A = C) #else #define _SET_STOP_CHAR(A,C) NOOP #endif #define _ENDSTOP_HIT_ECHO(A,C) do{ \ SERIAL_ECHOPGM(" " STRINGIFY(A) ":", planner.triggered_position_mm(_AXIS(A))); _SET_STOP_CHAR(A,C); }while(0) #define _ENDSTOP_HIT_TEST(A,C) \ if (TERN0(HAS_##A##_MIN_STATE, TEST(hit_state, ES_ENUM(A,MIN))) || TERN0(HAS_##A##_MAX_STATE, TEST(hit_state, ES_ENUM(A,MAX)))) \ _ENDSTOP_HIT_ECHO(A,C) #define ENDSTOP_HIT_TEST_X() _ENDSTOP_HIT_TEST(X,'X') #define ENDSTOP_HIT_TEST_Y() _ENDSTOP_HIT_TEST(Y,'Y') #define ENDSTOP_HIT_TEST_Z() _ENDSTOP_HIT_TEST(Z,'Z') #define ENDSTOP_HIT_TEST_I() _ENDSTOP_HIT_TEST(I,'I') #define ENDSTOP_HIT_TEST_J() _ENDSTOP_HIT_TEST(J,'J') #define ENDSTOP_HIT_TEST_K() _ENDSTOP_HIT_TEST(K,'K') #define ENDSTOP_HIT_TEST_U() _ENDSTOP_HIT_TEST(U,'U') #define ENDSTOP_HIT_TEST_V() _ENDSTOP_HIT_TEST(V,'V') #define ENDSTOP_HIT_TEST_W() _ENDSTOP_HIT_TEST(W,'W') SERIAL_ECHO_START(); SERIAL_ECHOPGM(STR_ENDSTOPS_HIT); NUM_AXIS_CODE( ENDSTOP_HIT_TEST_X(), ENDSTOP_HIT_TEST_Y(), ENDSTOP_HIT_TEST_Z(), _ENDSTOP_HIT_TEST(I,'I'), _ENDSTOP_HIT_TEST(J,'J'), _ENDSTOP_HIT_TEST(K,'K'), _ENDSTOP_HIT_TEST(U,'U'), _ENDSTOP_HIT_TEST(V,'V'), _ENDSTOP_HIT_TEST(W,'W') ); #if USE_Z_MIN_PROBE #define P_AXIS Z_AXIS if (TEST(hit_state, Z_MIN_PROBE)) _ENDSTOP_HIT_ECHO(P, 'P'); #endif SERIAL_EOL(); TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT GANG_N_1(NUM_AXES, " %c") " %c"), GET_TEXT_F(MSG_LCD_ENDSTOPS), NUM_AXIS_LIST_(chrX, chrY, chrZ, chrI, chrJ, chrK, chrU, chrV, chrW) chrP ) ); #if ENABLED(SD_ABORT_ON_ENDSTOP_HIT) if (planner.abort_on_endstop_hit) { card.abortFilePrintNow(); quickstop_stepper(); thermalManager.disable_all_heaters(); #ifdef SD_ABORT_ON_ENDSTOP_HIT_GCODE queue.clear(); queue.inject(F(SD_ABORT_ON_ENDSTOP_HIT_GCODE)); #endif print_job_timer.stop(); } #endif } } #if NUM_AXES #pragma GCC diagnostic push #if GCC_VERSION <= 50000 #pragma GCC diagnostic ignored "-Wunused-function" #endif static void print_es_state(const bool is_hit, FSTR_P const flabel=nullptr) { if (flabel) SERIAL_ECHO(flabel); SERIAL_ECHOLN(F(": "), is_hit ? F(STR_ENDSTOP_HIT) : F(STR_ENDSTOP_OPEN)); } #pragma GCC diagnostic pop #endif void __O2 Endstops::report_states() { TERN_(BLTOUCH, bltouch._set_SW_mode()); SERIAL_ECHOLNPGM(STR_M119_REPORT); #define ES_REPORT(S) print_es_state(READ_ENDSTOP(S##_PIN) == S##_ENDSTOP_HIT_STATE, F(STR_##S)) #if USE_X_MIN ES_REPORT(X_MIN); #endif #if USE_X2_MIN ES_REPORT(X2_MIN); #endif #if USE_X_MAX ES_REPORT(X_MAX); #endif #if USE_X2_MAX ES_REPORT(X2_MAX); #endif #if USE_Y_MIN ES_REPORT(Y_MIN); #endif #if USE_Y2_MIN ES_REPORT(Y2_MIN); #endif #if USE_Y_MAX ES_REPORT(Y_MAX); #endif #if USE_Y2_MAX ES_REPORT(Y2_MAX); #endif #if USE_Z_MIN ES_REPORT(Z_MIN); #endif #if USE_Z2_MIN ES_REPORT(Z2_MIN); #endif #if USE_Z3_MIN ES_REPORT(Z3_MIN); #endif #if USE_Z4_MIN ES_REPORT(Z4_MIN); #endif #if USE_Z_MAX ES_REPORT(Z_MAX); #endif #if USE_Z2_MAX ES_REPORT(Z2_MAX); #endif #if USE_Z3_MAX ES_REPORT(Z3_MAX); #endif #if USE_Z4_MAX ES_REPORT(Z4_MAX); #endif #if USE_I_MIN ES_REPORT(I_MIN); #endif #if USE_I_MAX ES_REPORT(I_MAX); #endif #if USE_J_MIN ES_REPORT(J_MIN); #endif #if USE_J_MAX ES_REPORT(J_MAX); #endif #if USE_K_MIN ES_REPORT(K_MIN); #endif #if USE_K_MAX ES_REPORT(K_MAX); #endif #if USE_U_MIN ES_REPORT(U_MIN); #endif #if USE_U_MAX ES_REPORT(U_MAX); #endif #if USE_V_MIN ES_REPORT(V_MIN); #endif #if USE_V_MAX ES_REPORT(V_MAX); #endif #if USE_W_MIN ES_REPORT(W_MIN); #endif #if USE_W_MAX ES_REPORT(W_MAX); #endif #if ENABLED(PROBE_ACTIVATION_SWITCH) print_es_state(probe_switch_activated(), F(STR_PROBE_EN)); #endif #if USE_Z_MIN_PROBE print_es_state(PROBE_TRIGGERED(), F(STR_Z_PROBE)); #endif #if MULTI_FILAMENT_SENSOR #define _CASE_RUNOUT(N) case N: pin = FIL_RUNOUT##N##_PIN; state = FIL_RUNOUT##N##_STATE; break; for (uint8_t i = 1; i <= NUM_RUNOUT_SENSORS; ++i) { pin_t pin; uint8_t state; switch (i) { default: continue; REPEAT_1(NUM_RUNOUT_SENSORS, _CASE_RUNOUT) } SERIAL_ECHOPGM(STR_FILAMENT); if (i > 1) SERIAL_CHAR(' ', '0' + i); print_es_state(extDigitalRead(pin) != state); } #undef _CASE_RUNOUT #elif HAS_FILAMENT_SENSOR print_es_state(READ(FIL_RUNOUT1_PIN) != FIL_RUNOUT1_STATE, F(STR_FILAMENT)); #endif TERN_(BLTOUCH, bltouch._reset_SW_mode()); TERN_(JOYSTICK_DEBUG, joystick.report()); } // Endstops::report_states /** * Called from interrupt context by the Endstop ISR or Stepper ISR! * Read endstops to get their current states, register hits for all * axes moving in the direction of their endstops, and abort moves. */ void Endstops::update() { #if !ENDSTOP_NOISE_THRESHOLD // If not debouncing... if (!abort_enabled()) return; // ...and not enabled, exit. #endif // Macros to update / copy the live_state #define _ES_PIN(A,M) A##_##M##_PIN #define _ES_HIT(A,M) A##_##M##_ENDSTOP_HIT_STATE #define UPDATE_LIVE_STATE(AXIS, MINMAX) SET_BIT_TO(live_state, ES_ENUM(AXIS, MINMAX), (READ_ENDSTOP(_ES_PIN(AXIS, MINMAX)) == _ES_HIT(AXIS, MINMAX))) #define COPY_LIVE_STATE(SRC_BIT, DST_BIT) SET_BIT_TO(live_state, DST_BIT, TEST(live_state, SRC_BIT)) #if ENABLED(G38_PROBE_TARGET) // For G38 moves check the probe's pin for ALL movement if (G38_move) UPDATE_LIVE_STATE(Z, TERN(USE_Z_MIN_PROBE, MIN_PROBE, MIN)); #endif // With Dual X, endstops are only checked in the homing direction for the active extruder #define X_MIN_TEST() TERN1(DUAL_X_CARRIAGE, stepper.last_moved_extruder == 0) // Check min for the left carriage #define X_MAX_TEST() TERN1(DUAL_X_CARRIAGE, stepper.last_moved_extruder != 0) // Check max for the right carriage // Use HEAD for core axes, AXIS for others #if ANY(CORE_IS_XY, CORE_IS_XZ, MARKFORGED_XY, MARKFORGED_YX) #define X_AXIS_HEAD X_HEAD #else #define X_AXIS_HEAD X_AXIS #endif #if ANY(CORE_IS_XY, CORE_IS_YZ, MARKFORGED_XY, MARKFORGED_YX) #define Y_AXIS_HEAD Y_HEAD #else #define Y_AXIS_HEAD Y_AXIS #endif #if CORE_IS_XZ || CORE_IS_YZ #define Z_AXIS_HEAD Z_HEAD #else #define Z_AXIS_HEAD Z_AXIS #endif #define I_AXIS_HEAD I_AXIS #define J_AXIS_HEAD J_AXIS #define K_AXIS_HEAD K_AXIS #define U_AXIS_HEAD U_AXIS #define V_AXIS_HEAD V_AXIS #define W_AXIS_HEAD W_AXIS /** * Check and update endstops */ #if USE_X_MIN UPDATE_LIVE_STATE(X, MIN); #if ENABLED(X_DUAL_ENDSTOPS) #if USE_X2_MIN UPDATE_LIVE_STATE(X2, MIN); #else COPY_LIVE_STATE(X_MIN, X2_MIN); #endif #endif #endif #if USE_X_MAX UPDATE_LIVE_STATE(X, MAX); #if ENABLED(X_DUAL_ENDSTOPS) #if USE_X2_MAX UPDATE_LIVE_STATE(X2, MAX); #else COPY_LIVE_STATE(X_MAX, X2_MAX); #endif #endif #endif #if USE_Y_MIN UPDATE_LIVE_STATE(Y, MIN); #if ENABLED(Y_DUAL_ENDSTOPS) #if USE_Y2_MIN UPDATE_LIVE_STATE(Y2, MIN); #else COPY_LIVE_STATE(Y_MIN, Y2_MIN); #endif #endif #endif #if USE_Y_MAX UPDATE_LIVE_STATE(Y, MAX); #if ENABLED(Y_DUAL_ENDSTOPS) #if USE_Y2_MAX UPDATE_LIVE_STATE(Y2, MAX); #else COPY_LIVE_STATE(Y_MAX, Y2_MAX); #endif #endif #endif #if USE_Z_MIN && NONE(Z_SPI_SENSORLESS, Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) UPDATE_LIVE_STATE(Z, MIN); #endif #if USE_Z2_MIN UPDATE_LIVE_STATE(Z2, MIN); #elif HAS_Z2_MIN_STATE COPY_LIVE_STATE(Z_MIN, Z2_MIN); #endif #if USE_Z3_MIN UPDATE_LIVE_STATE(Z3, MIN); #elif HAS_Z3_MIN_STATE COPY_LIVE_STATE(Z_MIN, Z3_MIN); #endif #if USE_Z4_MIN UPDATE_LIVE_STATE(Z4, MIN); #elif HAS_Z4_MIN_STATE COPY_LIVE_STATE(Z_MIN, Z4_MIN); #endif #if HAS_REAL_BED_PROBE // When closing the gap check the enabled probe if (probe_switch_activated()) UPDATE_LIVE_STATE(Z, TERN(USE_Z_MIN_PROBE, MIN_PROBE, MIN)); #endif #if USE_Z_MAX UPDATE_LIVE_STATE(Z, MAX); #endif #if USE_Z2_MAX UPDATE_LIVE_STATE(Z2, MAX); #elif HAS_Z2_MAX_STATE COPY_LIVE_STATE(Z_MAX, Z2_MAX); #endif #if USE_Z3_MAX UPDATE_LIVE_STATE(Z3, MAX); #elif HAS_Z3_MAX_STATE COPY_LIVE_STATE(Z_MAX, Z3_MAX); #endif #if USE_Z4_MAX UPDATE_LIVE_STATE(Z4, MAX); #elif HAS_Z4_MAX_STATE COPY_LIVE_STATE(Z_MAX, Z4_MAX); #endif #if USE_I_MIN UPDATE_LIVE_STATE(I, MIN); #endif #if USE_I_MAX UPDATE_LIVE_STATE(I, MAX); #endif #if USE_J_MIN UPDATE_LIVE_STATE(J, MIN); #endif #if USE_J_MAX UPDATE_LIVE_STATE(J, MAX); #endif #if USE_K_MIN UPDATE_LIVE_STATE(K, MIN); #endif #if USE_K_MAX UPDATE_LIVE_STATE(K, MAX); #endif #if USE_U_MIN UPDATE_LIVE_STATE(U, MIN); #endif #if USE_U_MAX UPDATE_LIVE_STATE(U, MAX); #endif #if USE_V_MIN UPDATE_LIVE_STATE(V, MIN); #endif #if USE_V_MAX UPDATE_LIVE_STATE(V, MAX); #endif #if USE_W_MIN UPDATE_LIVE_STATE(W, MIN); #endif #if USE_W_MAX UPDATE_LIVE_STATE(W, MAX); #endif #if ENDSTOP_NOISE_THRESHOLD /** * Filtering out noise on endstops requires a delayed decision. Let's assume, due to noise, * that 50% of endstop signal samples are good and 50% are bad (assuming normal distribution * of random noise). Then the first sample has a 50% chance to be good or bad. The 2nd sample * also has a 50% chance to be good or bad. The chances of 2 samples both being bad becomes * 50% of 50%, or 25%. That was the previous implementation of Marlin endstop handling. It * reduces chances of bad readings in half, at the cost of 1 extra sample period, but chances * still exist. The only way to reduce them further is to increase the number of samples. * To reduce the chance to 1% (1/128th) requires 7 samples (adding 7ms of delay). */ static endstop_mask_t old_live_state; if (old_live_state != live_state) { endstop_poll_count = ENDSTOP_NOISE_THRESHOLD; old_live_state = live_state; } else if (endstop_poll_count && !--endstop_poll_count) validated_live_state = live_state; if (!abort_enabled()) return; #endif // Test the current status of an endstop #define TEST_ENDSTOP(ENDSTOP) (TEST(state(), ENDSTOP)) // Record endstop was hit #define _ENDSTOP_HIT(AXIS, MINMAX) SBI(hit_state, ES_ENUM(AXIS, MINMAX)) // Call the endstop triggered routine for single endstops #define PROCESS_ENDSTOP(AXIS, MINMAX) do { \ if (TEST_ENDSTOP(ES_ENUM(AXIS, MINMAX))) { \ _ENDSTOP_HIT(AXIS, MINMAX); \ planner.endstop_triggered(_AXIS(AXIS)); \ } \ }while(0) // Core Sensorless Homing needs to test an Extra Pin #define CORE_DIAG(QQ,A,MM) (CORE_IS_##QQ && A##_SENSORLESS && !A##_SPI_SENSORLESS && USE_##A##_##MM) #define PROCESS_CORE_ENDSTOP(A1,M1,A2,M2) do { \ if (TEST_ENDSTOP(ES_ENUM(A1,M1))) { \ _ENDSTOP_HIT(A2,M2); \ planner.endstop_triggered(_AXIS(A2)); \ } \ }while(0) // Call the endstop triggered routine for dual endstops #define PROCESS_DUAL_ENDSTOP(A, MINMAX) do { \ const byte dual_hit = TEST_ENDSTOP(ES_ENUM(A, MINMAX)) | (TEST_ENDSTOP(ES_ENUM(A##2, MINMAX)) << 1); \ if (dual_hit) { \ _ENDSTOP_HIT(A, MINMAX); \ /* if not performing home or if both endstops were triggered during homing... */ \ if (!stepper.separate_multi_axis || dual_hit == 0b11) \ planner.endstop_triggered(_AXIS(A)); \ } \ }while(0) #define PROCESS_TRIPLE_ENDSTOP(A, MINMAX) do { \ const byte triple_hit = TEST_ENDSTOP(ES_ENUM(A, MINMAX)) | (TEST_ENDSTOP(ES_ENUM(A##2, MINMAX)) << 1) | (TEST_ENDSTOP(ES_ENUM(A##3, MINMAX)) << 2); \ if (triple_hit) { \ _ENDSTOP_HIT(A, MINMAX); \ /* if not performing home or if both endstops were triggered during homing... */ \ if (!stepper.separate_multi_axis || triple_hit == 0b111) \ planner.endstop_triggered(_AXIS(A)); \ } \ }while(0) #define PROCESS_QUAD_ENDSTOP(A, MINMAX) do { \ const byte quad_hit = TEST_ENDSTOP(ES_ENUM(A, MINMAX)) | (TEST_ENDSTOP(ES_ENUM(A##2, MINMAX)) << 1) | (TEST_ENDSTOP(ES_ENUM(A##3, MINMAX)) << 2) | (TEST_ENDSTOP(ES_ENUM(A##4, MINMAX)) << 3); \ if (quad_hit) { \ _ENDSTOP_HIT(A, MINMAX); \ /* if not performing home or if both endstops were triggered during homing... */ \ if (!stepper.separate_multi_axis || quad_hit == 0b1111) \ planner.endstop_triggered(_AXIS(A)); \ } \ }while(0) #if ENABLED(X_DUAL_ENDSTOPS) #define PROCESS_ENDSTOP_X(MINMAX) PROCESS_DUAL_ENDSTOP(X, MINMAX) #else #define PROCESS_ENDSTOP_X(MINMAX) if (X_##MINMAX##_TEST()) PROCESS_ENDSTOP(X, MINMAX) #endif #if ENABLED(Y_DUAL_ENDSTOPS) #define PROCESS_ENDSTOP_Y(MINMAX) PROCESS_DUAL_ENDSTOP(Y, MINMAX) #else #define PROCESS_ENDSTOP_Y(MINMAX) PROCESS_ENDSTOP(Y, MINMAX) #endif #if DISABLED(Z_MULTI_ENDSTOPS) #define PROCESS_ENDSTOP_Z(MINMAX) PROCESS_ENDSTOP(Z, MINMAX) #elif NUM_Z_STEPPERS == 4 #define PROCESS_ENDSTOP_Z(MINMAX) PROCESS_QUAD_ENDSTOP(Z, MINMAX) #elif NUM_Z_STEPPERS == 3 #define PROCESS_ENDSTOP_Z(MINMAX) PROCESS_TRIPLE_ENDSTOP(Z, MINMAX) #else #define PROCESS_ENDSTOP_Z(MINMAX) PROCESS_DUAL_ENDSTOP(Z, MINMAX) #endif #if ENABLED(G38_PROBE_TARGET) // For G38 moves check the probe's pin for ALL movement if (G38_move && TEST_ENDSTOP(Z_MIN_PROBE) == TERN1(G38_PROBE_AWAY, (G38_move < 4))) { G38_did_trigger = true; #define _G38_SET(Q) | (stepper.axis_is_moving(_AXIS(Q)) << _AXIS(Q)) #define _G38_RESP(Q) if (moving[_AXIS(Q)]) { _ENDSTOP_HIT(Q, ENDSTOP); planner.endstop_triggered(_AXIS(Q)); } const Flags<NUM_AXES> moving = { uvalue_t(NUM_AXES)(0 MAIN_AXIS_MAP(_G38_SET)) }; MAIN_AXIS_MAP(_G38_RESP); } #endif // Signal, after validation, if an endstop limit is pressed or not #if HAS_X_AXIS #if ENABLED(FT_MOTION) const bool x_moving_pos = ftMotion.axis_moving_pos(X_AXIS_HEAD), x_moving_neg = ftMotion.axis_moving_neg(X_AXIS_HEAD); #define X_MOVE_TEST x_moving_pos || x_moving_neg #define X_NEG_DIR_TEST x_moving_neg #else #define X_MOVE_TEST stepper.axis_is_moving(X_AXIS) #define X_NEG_DIR_TEST !stepper.motor_direction(X_AXIS_HEAD) #endif if (X_MOVE_TEST) { if (X_NEG_DIR_TEST) { // -direction #if HAS_X_MIN_STATE PROCESS_ENDSTOP_X(MIN); #if CORE_DIAG(XY, Y, MIN) PROCESS_CORE_ENDSTOP(Y,MIN,X,MIN); #elif CORE_DIAG(XY, Y, MAX) PROCESS_CORE_ENDSTOP(Y,MAX,X,MIN); #elif CORE_DIAG(XZ, Z, MIN) PROCESS_CORE_ENDSTOP(Z,MIN,X,MIN); #elif CORE_DIAG(XZ, Z, MAX) PROCESS_CORE_ENDSTOP(Z,MAX,X,MIN); #endif #endif } else { // +direction #if HAS_X_MAX_STATE PROCESS_ENDSTOP_X(MAX); #if CORE_DIAG(XY, Y, MIN) PROCESS_CORE_ENDSTOP(Y,MIN,X,MAX); #elif CORE_DIAG(XY, Y, MAX) PROCESS_CORE_ENDSTOP(Y,MAX,X,MAX); #elif CORE_DIAG(XZ, Z, MIN) PROCESS_CORE_ENDSTOP(Z,MIN,X,MAX); #elif CORE_DIAG(XZ, Z, MAX) PROCESS_CORE_ENDSTOP(Z,MAX,X,MAX); #endif #endif } } #endif // HAS_X_AXIS #if HAS_Y_AXIS #if ENABLED(FT_MOTION) const bool y_moving_pos = ftMotion.axis_moving_pos(Y_AXIS_HEAD), y_moving_neg = ftMotion.axis_moving_neg(Y_AXIS_HEAD); #define Y_MOVE_TEST y_moving_pos || y_moving_neg #define Y_NEG_DIR_TEST y_moving_neg #else #define Y_MOVE_TEST stepper.axis_is_moving(Y_AXIS) #define Y_NEG_DIR_TEST !stepper.motor_direction(Y_AXIS_HEAD) #endif if (Y_MOVE_TEST) { if (Y_NEG_DIR_TEST) { // -direction #if HAS_Y_MIN_STATE PROCESS_ENDSTOP_Y(MIN); #if CORE_DIAG(XY, X, MIN) PROCESS_CORE_ENDSTOP(X,MIN,Y,MIN); #elif CORE_DIAG(XY, X, MAX) PROCESS_CORE_ENDSTOP(X,MAX,Y,MIN); #elif CORE_DIAG(YZ, Z, MIN) PROCESS_CORE_ENDSTOP(Z,MIN,Y,MIN); #elif CORE_DIAG(YZ, Z, MAX) PROCESS_CORE_ENDSTOP(Z,MAX,Y,MIN); #endif #endif } else { // +direction #if HAS_Y_MAX_STATE PROCESS_ENDSTOP_Y(MAX); #if CORE_DIAG(XY, X, MIN) PROCESS_CORE_ENDSTOP(X,MIN,Y,MAX); #elif CORE_DIAG(XY, X, MAX) PROCESS_CORE_ENDSTOP(X,MAX,Y,MAX); #elif CORE_DIAG(YZ, Z, MIN) PROCESS_CORE_ENDSTOP(Z,MIN,Y,MAX); #elif CORE_DIAG(YZ, Z, MAX) PROCESS_CORE_ENDSTOP(Z,MAX,Y,MAX); #endif #endif } } #endif // HAS_Y_AXIS #if HAS_Z_AXIS #if ENABLED(FT_MOTION) const bool z_moving_pos = ftMotion.axis_moving_pos(Z_AXIS_HEAD), z_moving_neg = ftMotion.axis_moving_neg(Z_AXIS_HEAD); #define Z_MOVE_TEST z_moving_pos || z_moving_neg #define Z_NEG_DIR_TEST z_moving_neg #else #define Z_MOVE_TEST stepper.axis_is_moving(Z_AXIS) #define Z_NEG_DIR_TEST !stepper.motor_direction(Z_AXIS_HEAD) #endif if (Z_MOVE_TEST) { if (Z_NEG_DIR_TEST) { // Z -direction. Gantry down, bed up. #if HAS_Z_MIN_STATE // If the Z_MIN_PIN is being used for the probe there's no // separate Z_MIN endstop. But a Z endstop could be wired // in series, so someone might find this useful. if ( TERN1(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN, z_probe_enabled) // When Z_MIN is the probe, the probe must be enabled && TERN1(USE_Z_MIN_PROBE, !z_probe_enabled) // When Z_MIN isn't the probe, Z MIN is ignored while probing ) { PROCESS_ENDSTOP_Z(MIN); #if CORE_DIAG(XZ, X, MIN) PROCESS_CORE_ENDSTOP(X,MIN,Z,MIN); #elif CORE_DIAG(XZ, X, MAX) PROCESS_CORE_ENDSTOP(X,MAX,Z,MIN); #elif CORE_DIAG(YZ, Y, MIN) PROCESS_CORE_ENDSTOP(Y,MIN,Z,MIN); #elif CORE_DIAG(YZ, Y, MAX) PROCESS_CORE_ENDSTOP(Y,MAX,Z,MIN); #endif } #endif // When closing the gap use the probe trigger state #if USE_Z_MIN_PROBE if (z_probe_enabled) PROCESS_ENDSTOP(Z, MIN_PROBE); #endif } else { // Z +direction. Gantry up, bed down. #if HAS_Z_MAX_STATE PROCESS_ENDSTOP_Z(MAX); #if CORE_DIAG(XZ, X, MIN) PROCESS_CORE_ENDSTOP(X,MIN,Z,MAX); #elif CORE_DIAG(XZ, X, MAX) PROCESS_CORE_ENDSTOP(X,MAX,Z,MAX); #elif CORE_DIAG(YZ, Y, MIN) PROCESS_CORE_ENDSTOP(Y,MIN,Z,MAX); #elif CORE_DIAG(YZ, Y, MAX) PROCESS_CORE_ENDSTOP(Y,MAX,Z,MAX); #endif #endif } } #endif // HAS_Z_AXIS #if HAS_I_AXIS // TODO: FT_Motion logic. if (stepper.axis_is_moving(I_AXIS)) { if (!stepper.motor_direction(I_AXIS_HEAD)) { // -direction #if HAS_I_MIN_STATE PROCESS_ENDSTOP(I, MIN); #endif } else { // +direction #if HAS_I_MAX_STATE PROCESS_ENDSTOP(I, MAX); #endif } } #endif // HAS_I_AXIS #if HAS_J_AXIS if (stepper.axis_is_moving(J_AXIS)) { if (!stepper.motor_direction(J_AXIS_HEAD)) { // -direction #if HAS_J_MIN_STATE PROCESS_ENDSTOP(J, MIN); #endif } else { // +direction #if HAS_J_MAX_STATE PROCESS_ENDSTOP(J, MAX); #endif } } #endif // HAS_J_AXIS #if HAS_K_AXIS if (stepper.axis_is_moving(K_AXIS)) { if (!stepper.motor_direction(K_AXIS_HEAD)) { // -direction #if HAS_K_MIN_STATE PROCESS_ENDSTOP(K, MIN); #endif } else { // +direction #if HAS_K_MAX_STATE PROCESS_ENDSTOP(K, MAX); #endif } } #endif // HAS_K_AXIS #if HAS_U_AXIS if (stepper.axis_is_moving(U_AXIS)) { if (!stepper.motor_direction(U_AXIS_HEAD)) { // -direction #if HAS_U_MIN_STATE PROCESS_ENDSTOP(U, MIN); #endif } else { // +direction #if HAS_U_MAX_STATE PROCESS_ENDSTOP(U, MAX); #endif } } #endif // HAS_U_AXIS #if HAS_V_AXIS if (stepper.axis_is_moving(V_AXIS)) { if (!stepper.motor_direction(V_AXIS_HEAD)) { // -direction #if HAS_V_MIN_STATE PROCESS_ENDSTOP(V, MIN); #endif } else { // +direction #if HAS_V_MAX_STATE PROCESS_ENDSTOP(V, MAX); #endif } } #endif // HAS_V_AXIS #if HAS_W_AXIS if (stepper.axis_is_moving(W_AXIS)) { if (!stepper.motor_direction(W_AXIS_HEAD)) { // -direction #if HAS_W_MIN_STATE PROCESS_ENDSTOP(W, MIN); #endif } else { // +direction #if HAS_W_MAX_STATE PROCESS_ENDSTOP(W, MAX); #endif } } #endif // HAS_W_AXIS } // Endstops::update() #if ENABLED(SPI_ENDSTOPS) // Called from idle() to read Trinamic stall states bool Endstops::tmc_spi_homing_check() { bool hit = false; #if X_SPI_SENSORLESS if (tmc_spi_homing.x) { #if ENABLED(DUAL_X_CARRIAGE) const bool ismin = X_MIN_TEST(); #endif const bool xhit = ( #if ENABLED(DUAL_X_CARRIAGE) ismin ? stepperX.test_stall_status() : stepperX2.test_stall_status() #else stepperX.test_stall_status() #if Y_SPI_SENSORLESS && ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX) || stepperY.test_stall_status() #elif Z_SPI_SENSORLESS && CORE_IS_XZ || stepperZ.test_stall_status() #endif #endif ); if (xhit) { SBI(live_state, TERN(DUAL_X_CARRIAGE, ismin ? X_MIN : X_MAX, X_ENDSTOP)); hit = true; } #if ENABLED(X_DUAL_ENDSTOPS) if (stepperX2.test_stall_status()) { SBI(live_state, X2_ENDSTOP); hit = true; } #endif } #endif #if Y_SPI_SENSORLESS if (tmc_spi_homing.y) { if (stepperY.test_stall_status() #if X_SPI_SENSORLESS && ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX) || stepperX.test_stall_status() #elif Z_SPI_SENSORLESS && CORE_IS_YZ || stepperZ.test_stall_status() #endif ) { SBI(live_state, Y_ENDSTOP); hit = true; } #if ENABLED(Y_DUAL_ENDSTOPS) if (stepperY2.test_stall_status()) { SBI(live_state, Y2_ENDSTOP); hit = true; } #endif } #endif #if Z_SPI_SENSORLESS if (tmc_spi_homing.z) { if (stepperZ.test_stall_status() #if X_SPI_SENSORLESS && CORE_IS_XZ || stepperX.test_stall_status() #elif Y_SPI_SENSORLESS && CORE_IS_YZ || stepperY.test_stall_status() #endif ) { SBI(live_state, Z_ENDSTOP); hit = true; } #if ENABLED(Z_MULTI_ENDSTOPS) if (stepperZ2.test_stall_status()) { SBI(live_state, Z2_ENDSTOP); hit = true; } #if NUM_Z_STEPPERS >= 3 if (stepperZ3.test_stall_status()) { SBI(live_state, Z3_ENDSTOP); hit = true; } #if NUM_Z_STEPPERS >= 4 if (stepperZ4.test_stall_status()) { SBI(live_state, Z4_ENDSTOP); hit = true; } #endif #endif #endif } #endif #if I_SPI_SENSORLESS if (tmc_spi_homing.i && stepperI.test_stall_status()) { SBI(live_state, I_ENDSTOP); hit = true; } #endif #if J_SPI_SENSORLESS if (tmc_spi_homing.j && stepperJ.test_stall_status()) { SBI(live_state, J_ENDSTOP); hit = true; } #endif #if K_SPI_SENSORLESS if (tmc_spi_homing.k && stepperK.test_stall_status()) { SBI(live_state, K_ENDSTOP); hit = true; } #endif #if U_SPI_SENSORLESS if (tmc_spi_homing.u && stepperU.test_stall_status()) { SBI(live_state, U_ENDSTOP); hit = true; } #endif #if V_SPI_SENSORLESS if (tmc_spi_homing.v && stepperV.test_stall_status()) { SBI(live_state, V_ENDSTOP); hit = true; } #endif #if W_SPI_SENSORLESS if (tmc_spi_homing.w && stepperW.test_stall_status()) { SBI(live_state, W_ENDSTOP); hit = true; } #endif if (TERN0(ENDSTOP_INTERRUPTS_FEATURE, hit)) update(); return hit; } void Endstops::clear_endstop_state() { TERN_(X_SPI_SENSORLESS, CBI(live_state, X_ENDSTOP)); #if ALL(X_SPI_SENSORLESS, X_DUAL_ENDSTOPS) CBI(live_state, X2_ENDSTOP); #endif TERN_(Y_SPI_SENSORLESS, CBI(live_state, Y_ENDSTOP)); #if ALL(Y_SPI_SENSORLESS, Y_DUAL_ENDSTOPS) CBI(live_state, Y2_ENDSTOP); #endif TERN_(Z_SPI_SENSORLESS, CBI(live_state, Z_ENDSTOP)); #if ALL(Z_SPI_SENSORLESS, Z_MULTI_ENDSTOPS) CBI(live_state, Z2_ENDSTOP); #if NUM_Z_STEPPERS >= 3 CBI(live_state, Z3_ENDSTOP); #if NUM_Z_STEPPERS >= 4 CBI(live_state, Z4_ENDSTOP); #endif #endif #endif TERN_(I_SPI_SENSORLESS, CBI(live_state, I_ENDSTOP)); TERN_(J_SPI_SENSORLESS, CBI(live_state, J_ENDSTOP)); TERN_(K_SPI_SENSORLESS, CBI(live_state, K_ENDSTOP)); TERN_(U_SPI_SENSORLESS, CBI(live_state, U_ENDSTOP)); TERN_(V_SPI_SENSORLESS, CBI(live_state, V_ENDSTOP)); TERN_(W_SPI_SENSORLESS, CBI(live_state, W_ENDSTOP)); } #endif // SPI_ENDSTOPS #if ENABLED(PINS_DEBUGGING) bool Endstops::monitor_flag = false; /** * Monitor Endstops and Z Probe for changes * * If a change is detected then the LED is toggled and * a message is sent out the serial port. * * Yes, we could miss a rapid back & forth change but * that won't matter because this is all manual. */ void Endstops::monitor() { static uint16_t old_live_state_local = 0; static uint8_t local_LED_status = 0; uint16_t live_state_local = 0; #define ES_GET_STATE(S) if (READ_ENDSTOP(S##_PIN)) SBI(live_state_local, S) #if USE_X_MIN ES_GET_STATE(X_MIN); #endif #if USE_X_MAX ES_GET_STATE(X_MAX); #endif #if USE_Y_MIN ES_GET_STATE(Y_MIN); #endif #if USE_Y_MAX ES_GET_STATE(Y_MAX); #endif #if USE_Z_MIN ES_GET_STATE(Z_MIN); #endif #if USE_Z_MAX ES_GET_STATE(Z_MAX); #endif #if USE_Z_MIN_PROBE ES_GET_STATE(Z_MIN_PROBE); #endif #if USE_X2_MIN ES_GET_STATE(X2_MIN); #endif #if USE_X2_MAX ES_GET_STATE(X2_MAX); #endif #if USE_Y2_MIN ES_GET_STATE(Y2_MIN); #endif #if USE_Y2_MAX ES_GET_STATE(Y2_MAX); #endif #if USE_Z2_MIN ES_GET_STATE(Z2_MIN); #endif #if USE_Z2_MAX ES_GET_STATE(Z2_MAX); #endif #if USE_Z3_MIN ES_GET_STATE(Z3_MIN); #endif #if USE_Z3_MAX ES_GET_STATE(Z3_MAX); #endif #if USE_Z4_MIN ES_GET_STATE(Z4_MIN); #endif #if USE_Z4_MAX ES_GET_STATE(Z4_MAX); #endif #if USE_I_MAX ES_GET_STATE(I_MAX); #endif #if USE_I_MIN ES_GET_STATE(I_MIN); #endif #if USE_J_MAX ES_GET_STATE(J_MAX); #endif #if USE_J_MIN ES_GET_STATE(J_MIN); #endif #if USE_K_MAX ES_GET_STATE(K_MAX); #endif #if USE_K_MIN ES_GET_STATE(K_MIN); #endif #if USE_U_MAX ES_GET_STATE(U_MAX); #endif #if USE_U_MIN ES_GET_STATE(U_MIN); #endif #if USE_V_MAX ES_GET_STATE(V_MAX); #endif #if USE_V_MIN ES_GET_STATE(V_MIN); #endif #if USE_W_MAX ES_GET_STATE(W_MAX); #endif #if USE_W_MIN ES_GET_STATE(W_MIN); #endif const uint16_t endstop_change = live_state_local ^ old_live_state_local; #define ES_REPORT_CHANGE(S) if (TEST(endstop_change, S)) SERIAL_ECHOPGM(" " STRINGIFY(S) ":", TEST(live_state_local, S)) if (endstop_change) { #if USE_X_MIN ES_REPORT_CHANGE(X_MIN); #endif #if USE_X_MAX ES_REPORT_CHANGE(X_MAX); #endif #if USE_Y_MIN ES_REPORT_CHANGE(Y_MIN); #endif #if USE_Y_MAX ES_REPORT_CHANGE(Y_MAX); #endif #if USE_Z_MIN ES_REPORT_CHANGE(Z_MIN); #endif #if USE_Z_MAX ES_REPORT_CHANGE(Z_MAX); #endif #if USE_Z_MIN_PROBE ES_REPORT_CHANGE(Z_MIN_PROBE); #endif #if USE_X2_MIN ES_REPORT_CHANGE(X2_MIN); #endif #if USE_X2_MAX ES_REPORT_CHANGE(X2_MAX); #endif #if USE_Y2_MIN ES_REPORT_CHANGE(Y2_MIN); #endif #if USE_Y2_MAX ES_REPORT_CHANGE(Y2_MAX); #endif #if USE_Z2_MIN ES_REPORT_CHANGE(Z2_MIN); #endif #if USE_Z2_MAX ES_REPORT_CHANGE(Z2_MAX); #endif #if USE_Z3_MIN ES_REPORT_CHANGE(Z3_MIN); #endif #if USE_Z3_MAX ES_REPORT_CHANGE(Z3_MAX); #endif #if USE_Z4_MIN ES_REPORT_CHANGE(Z4_MIN); #endif #if USE_Z4_MAX ES_REPORT_CHANGE(Z4_MAX); #endif #if USE_I_MIN ES_REPORT_CHANGE(I_MIN); #endif #if USE_I_MAX ES_REPORT_CHANGE(I_MAX); #endif #if USE_J_MIN ES_REPORT_CHANGE(J_MIN); #endif #if USE_J_MAX ES_REPORT_CHANGE(J_MAX); #endif #if USE_K_MIN ES_REPORT_CHANGE(K_MIN); #endif #if USE_K_MAX ES_REPORT_CHANGE(K_MAX); #endif #if USE_U_MIN ES_REPORT_CHANGE(U_MIN); #endif #if USE_U_MAX ES_REPORT_CHANGE(U_MAX); #endif #if USE_V_MIN ES_REPORT_CHANGE(V_MIN); #endif #if USE_V_MAX ES_REPORT_CHANGE(V_MAX); #endif #if USE_W_MIN ES_REPORT_CHANGE(W_MIN); #endif #if USE_W_MAX ES_REPORT_CHANGE(W_MAX); #endif SERIAL_ECHOLNPGM("\n"); hal.set_pwm_duty(pin_t(LED_PIN), local_LED_status); local_LED_status ^= 255; old_live_state_local = live_state_local; } } #endif // PINS_DEBUGGING #if USE_SENSORLESS /** * Change TMC driver currents to N##_CURRENT_HOME, saving the current configuration of each. */ void Endstops::set_z_sensorless_current(const bool onoff) { #if ENABLED(DELTA) && HAS_CURRENT_HOME(X) #define HAS_DELTA_X_CURRENT 1 #endif #if ENABLED(DELTA) && HAS_CURRENT_HOME(Y) #define HAS_DELTA_Y_CURRENT 1 #endif #if HAS_DELTA_X_CURRENT || HAS_DELTA_Y_CURRENT || HAS_CURRENT_HOME(Z) || HAS_CURRENT_HOME(Z2) || HAS_CURRENT_HOME(Z3) || HAS_CURRENT_HOME(Z4) #if HAS_DELTA_X_CURRENT static int16_t saved_current_X; #endif #if HAS_DELTA_Y_CURRENT static int16_t saved_current_Y; #endif #if HAS_CURRENT_HOME(Z) static int16_t saved_current_Z; #endif #if HAS_CURRENT_HOME(Z2) static int16_t saved_current_Z2; #endif #if HAS_CURRENT_HOME(Z3) static int16_t saved_current_Z3; #endif #if HAS_CURRENT_HOME(Z4) static int16_t saved_current_Z4; #endif #if ENABLED(DEBUG_LEVELING_FEATURE) auto debug_current = [](FSTR_P const s, const int16_t a, const int16_t b) { if (DEBUGGING(LEVELING)) { DEBUG_ECHOLN(s, F(" current: "), a, F(" -> "), b); } }; #else #define debug_current(...) #endif #define _SAVE_SET_CURRENT(A) \ saved_current_##A = stepper##A.getMilliamps(); \ stepper##A.rms_current(A##_CURRENT_HOME); \ debug_current(F(STR_##A), saved_current_##A, A##_CURRENT_HOME) #define _RESTORE_CURRENT(A) \ stepper##A.rms_current(saved_current_##A); \ debug_current(F(STR_##A), saved_current_##A, A##_CURRENT_HOME) if (onoff) { TERN_(HAS_DELTA_X_CURRENT, _SAVE_SET_CURRENT(X)); TERN_(HAS_DELTA_Y_CURRENT, _SAVE_SET_CURRENT(Y)); #if HAS_CURRENT_HOME(Z) _SAVE_SET_CURRENT(Z); #endif #if HAS_CURRENT_HOME(Z2) _SAVE_SET_CURRENT(Z2); #endif #if HAS_CURRENT_HOME(Z3) _SAVE_SET_CURRENT(Z3); #endif #if HAS_CURRENT_HOME(Z4) _SAVE_SET_CURRENT(Z4); #endif } else { TERN_(HAS_DELTA_X_CURRENT, _RESTORE_CURRENT(X)); TERN_(HAS_DELTA_Y_CURRENT, _RESTORE_CURRENT(Y)); #if HAS_CURRENT_HOME(Z) _RESTORE_CURRENT(Z); #endif #if HAS_CURRENT_HOME(Z2) _RESTORE_CURRENT(Z2); #endif #if HAS_CURRENT_HOME(Z3) _RESTORE_CURRENT(Z3); #endif #if HAS_CURRENT_HOME(Z4) _RESTORE_CURRENT(Z4); #endif } TERN_(IMPROVE_HOMING_RELIABILITY, planner.enable_stall_prevention(onoff)); #if SENSORLESS_STALLGUARD_DELAY safe_delay(SENSORLESS_STALLGUARD_DELAY); // Short delay needed to settle #endif #endif } #endif // USE_SENSORLESS
2301_81045437/Marlin
Marlin/src/module/endstops.cpp
C++
agpl-3.0
41,049
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 /** * endstops.h - manages endstops */ #include "../inc/MarlinConfig.h" #include <stdint.h> #define _ES_ENUM(A,M) A##_##M #define ES_ENUM(A,M) _ES_ENUM(A,M) #define _ES_ITEM(N) N, #define ES_ITEM(K,N) TERN(K,_ES_ITEM,_IF_1_ELSE)(N) #define _ESN_ITEM(K,A,M) ES_ITEM(K,ES_ENUM(A,M)) #define ES_MINMAX(A) ES_ITEM(HAS_##A##_MIN_STATE, ES_ENUM(A,MIN)) ES_ITEM(HAS_##A##_MAX_STATE, ES_ENUM(A,MAX)) #define HAS_CURRENT_HOME(N) ((N##_CURRENT_HOME > 0) && (N##_CURRENT_HOME != N##_CURRENT)) /** * Basic Endstop Flag Bits: * - Each axis with an endstop gets a flag for its homing direction. * (The use of "MIN" or "MAX" makes it easier to pair with similarly-named endstop pins.) * - Bed probes with a single pin get a Z_MIN_PROBE flag. This includes Sensorless Z Probe. * * Extended Flag Bits: * - Multi-stepper axes may have multi-endstops such as X2_MIN, Y2_MAX, etc. * - DELTA gets X_MAX, Y_MAX, and Z_MAX corresponding to its "A", "B", "C" towers. * - For DUAL_X_CARRIAGE the X axis has both X_MIN and X_MAX flags. * - The Z axis may have both MIN and MAX when homing to MAX and the probe is Z_MIN. * - DELTA Sensorless Probe uses X/Y/Z_MAX but sets the Z_MIN flag. * * Endstop Flag Bit Aliases: * - Each *_MIN or *_MAX flag is aliased to *_ENDSTOP. * - Z_MIN_PROBE is an alias to Z_MIN when the Z_MIN_PIN is being used as the probe pin. * - When homing with the probe Z_ENDSTOP is a Z_MIN_PROBE alias, otherwise a Z_MIN/MAX alias. */ enum EndstopEnum : char { // Common XYZ (ABC) endstops. ES_MINMAX(X) ES_MINMAX(Y) ES_MINMAX(Z) ES_MINMAX(I) ES_MINMAX(J) ES_MINMAX(K) ES_MINMAX(U) ES_MINMAX(V) ES_MINMAX(W) // Extra Endstops for XYZ ES_MINMAX(X2) ES_MINMAX(Y2) ES_MINMAX(Z2) ES_MINMAX(Z3) ES_MINMAX(Z4) // Bed Probe state is distinct or shared with Z_MIN (i.e., when the probe is the only Z endstop) ES_ITEM(HAS_Z_PROBE_STATE, Z_MIN_PROBE IF_DISABLED(USE_Z_MIN_PROBE, = Z_MIN)) // The total number of states NUM_ENDSTOP_STATES // Endstop aliases #if HAS_X_STATE , X_ENDSTOP = TERN(X_HOME_TO_MAX, X_MAX, X_MIN) #endif #if HAS_X2_STATE , X2_ENDSTOP = TERN(X_HOME_TO_MAX, X2_MAX, X2_MIN) #endif #if HAS_Y_STATE , Y_ENDSTOP = TERN(Y_HOME_TO_MAX, Y_MAX, Y_MIN) #endif #if HAS_Y2_STATE , Y2_ENDSTOP = TERN(Y_HOME_TO_MAX, Y2_MAX, Y2_MIN) #endif #if HOMING_Z_WITH_PROBE , Z_ENDSTOP = Z_MIN_PROBE // "Z" endstop alias when homing with the probe #elif HAS_Z_STATE , Z_ENDSTOP = TERN(Z_HOME_TO_MAX, Z_MAX, Z_MIN) #endif #if HAS_Z2_STATE , Z2_ENDSTOP = TERN(Z_HOME_TO_MAX, Z2_MAX, Z2_MIN) #endif #if HAS_Z3_STATE , Z3_ENDSTOP = TERN(Z_HOME_TO_MAX, Z3_MAX, Z3_MIN) #endif #if HAS_Z4_STATE , Z4_ENDSTOP = TERN(Z_HOME_TO_MAX, Z4_MAX, Z4_MIN) #endif #if HAS_I_STATE , I_ENDSTOP = TERN(I_HOME_TO_MAX, I_MAX, I_MIN) #endif #if HAS_J_STATE , J_ENDSTOP = TERN(J_HOME_TO_MAX, J_MAX, J_MIN) #endif #if HAS_K_STATE , K_ENDSTOP = TERN(K_HOME_TO_MAX, K_MAX, K_MIN) #endif #if HAS_U_STATE , U_ENDSTOP = TERN(U_HOME_TO_MAX, U_MAX, U_MIN) #endif #if HAS_V_STATE , V_ENDSTOP = TERN(V_HOME_TO_MAX, V_MAX, V_MIN) #endif #if HAS_W_STATE , W_ENDSTOP = TERN(W_HOME_TO_MAX, W_MAX, W_MIN) #endif }; #undef _ES_ITEM #undef ES_ITEM #undef _ESN_ITEM #undef ES_MINMAX class Endstops { public: typedef bits_t(NUM_ENDSTOP_STATES) endstop_mask_t; #if ENABLED(X_DUAL_ENDSTOPS) static float x2_endstop_adj; #endif #if ENABLED(Y_DUAL_ENDSTOPS) static float y2_endstop_adj; #endif #if ENABLED(Z_MULTI_ENDSTOPS) static float z2_endstop_adj; #endif #if ENABLED(Z_MULTI_ENDSTOPS) && NUM_Z_STEPPERS >= 3 static float z3_endstop_adj; #endif #if ENABLED(Z_MULTI_ENDSTOPS) && NUM_Z_STEPPERS >= 4 static float z4_endstop_adj; #endif private: static bool enabled, enabled_globally; static endstop_mask_t live_state; static volatile endstop_mask_t hit_state; // Use X_MIN, Y_MIN, Z_MIN and Z_MIN_PROBE as BIT index #if ENDSTOP_NOISE_THRESHOLD static endstop_mask_t validated_live_state; static uint8_t endstop_poll_count; // Countdown from threshold for polling #endif public: Endstops() {}; /** * Initialize the endstop pins */ static void init(); /** * Are endstops or the probe set to abort the move? */ FORCE_INLINE static bool abort_enabled() { return enabled || TERN0(HAS_BED_PROBE, z_probe_enabled); } static bool global_enabled() { return enabled_globally; } /** * Periodic call to poll endstops if required. Called from temperature ISR */ static void poll(); /** * Update endstops bits from the pins. Apply filtering to get a verified state. * If abort_enabled() and moving towards a triggered switch, abort the current move. * Called from ISR contexts. */ static void update(); #if ENABLED(BD_SENSOR) static bool bdp_state; static void bdp_state_update(const bool z_state) { bdp_state = z_state; } #endif /** * Get Endstop hit state. */ FORCE_INLINE static endstop_mask_t trigger_state() { return hit_state; } /** * Get current endstops state */ FORCE_INLINE static endstop_mask_t state() { return #if ENDSTOP_NOISE_THRESHOLD validated_live_state #else live_state #endif ; } static bool probe_switch_activated() { return (true #if ENABLED(PROBE_ACTIVATION_SWITCH) && READ(PROBE_ACTIVATION_SWITCH_PIN) == PROBE_ACTIVATION_SWITCH_STATE #endif ); } /** * Report endstop hits to serial. Called from loop(). */ static void event_handler(); /** * Report endstop states in response to M119 */ static void report_states(); // Enable / disable endstop checking globally static void enable_globally(const bool onoff=true); // Enable / disable endstop checking static void enable(const bool onoff=true); // Disable / Enable endstops based on ENSTOPS_ONLY_FOR_HOMING and global enable static void not_homing(); #if ENABLED(VALIDATE_HOMING_ENDSTOPS) // If the last move failed to trigger an endstop, call kill static void validate_homing_move(); #else FORCE_INLINE static void validate_homing_move() { hit_on_purpose(); } #endif // Clear endstops (i.e., they were hit intentionally) to suppress the report FORCE_INLINE static void hit_on_purpose() { hit_state = 0; } // Enable / disable endstop z-probe checking #if HAS_BED_PROBE static volatile bool z_probe_enabled; static void enable_z_probe(const bool onoff=true); #endif static void resync(); // Debugging of endstops #if ENABLED(PINS_DEBUGGING) static bool monitor_flag; static void monitor(); static void run_monitor(); #endif #if ENABLED(SPI_ENDSTOPS) typedef struct { union { bool any; struct { bool NUM_AXIS_LIST(x:1, y:1, z:1, i:1, j:1, k:1); }; }; } tmc_spi_homing_t; static tmc_spi_homing_t tmc_spi_homing; static void clear_endstop_state(); static bool tmc_spi_homing_check(); #endif public: // Basic functions for Sensorless Homing #if USE_SENSORLESS static void set_z_sensorless_current(const bool onoff); #endif }; extern Endstops endstops; /** * A class to save and change the endstop state, * then restore it when it goes out of scope. */ class TemporaryGlobalEndstopsState { bool saved; public: TemporaryGlobalEndstopsState(const bool enable) : saved(endstops.global_enabled()) { endstops.enable_globally(enable); } ~TemporaryGlobalEndstopsState() { endstops.enable_globally(saved); } };
2301_81045437/Marlin
Marlin/src/module/endstops.h
C++
agpl-3.0
8,724
/** * Marlin 3D Printer Firmware * Copyright (c) 2023 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../inc/MarlinConfig.h" #if ENABLED(FT_MOTION) #include "ft_motion.h" #include "stepper.h" // Access stepper block queue function and abort status. #include "endstops.h" FTMotion ftMotion; #if !HAS_X_AXIS static_assert(FTM_DEFAULT_MODE == ftMotionMode_ZV, "ftMotionMode_ZV requires at least one linear axis."); static_assert(FTM_DEFAULT_MODE == ftMotionMode_ZVD, "ftMotionMode_ZVD requires at least one linear axis."); static_assert(FTM_DEFAULT_MODE == ftMotionMode_ZVDD, "ftMotionMode_ZVD requires at least one linear axis."); static_assert(FTM_DEFAULT_MODE == ftMotionMode_ZVDDD, "ftMotionMode_ZVD requires at least one linear axis."); static_assert(FTM_DEFAULT_MODE == ftMotionMode_EI, "ftMotionMode_EI requires at least one linear axis."); static_assert(FTM_DEFAULT_MODE == ftMotionMode_2HEI, "ftMotionMode_2HEI requires at least one linear axis."); static_assert(FTM_DEFAULT_MODE == ftMotionMode_3HEI, "ftMotionMode_3HEI requires at least one linear axis."); static_assert(FTM_DEFAULT_MODE == ftMotionMode_MZV, "ftMotionMode_MZV requires at least one linear axis."); #endif #if !HAS_DYNAMIC_FREQ_MM static_assert(FTM_DEFAULT_DYNFREQ_MODE != dynFreqMode_Z_BASED, "dynFreqMode_Z_BASED requires a Z axis."); #endif #if !HAS_DYNAMIC_FREQ_G static_assert(FTM_DEFAULT_DYNFREQ_MODE != dynFreqMode_MASS_BASED, "dynFreqMode_MASS_BASED requires an X axis and an extruder."); #endif //----------------------------------------------------------------- // Variables. //----------------------------------------------------------------- // Public variables. ft_config_t FTMotion::cfg; bool FTMotion::busy; // = false ft_command_t FTMotion::stepperCmdBuff[FTM_STEPPERCMD_BUFF_SIZE] = {0U}; // Stepper commands buffer. int32_t FTMotion::stepperCmdBuff_produceIdx = 0, // Index of next stepper command write to the buffer. FTMotion::stepperCmdBuff_consumeIdx = 0; // Index of next stepper command read from the buffer. bool FTMotion::sts_stepperBusy = false; // The stepper buffer has items and is in use. millis_t FTMotion::axis_pos_move_end_ti[NUM_AXIS_ENUMS] = {0}, FTMotion::axis_neg_move_end_ti[NUM_AXIS_ENUMS] = {0}; // Private variables. // NOTE: These are sized for Ulendo FBS use. xyze_trajectory_t FTMotion::traj; // = {0.0f} Storage for fixed-time-based trajectory. xyze_trajectoryMod_t FTMotion::trajMod; // = {0.0f} Storage for fixed time trajectory window. bool FTMotion::blockProcRdy = false, // Indicates a block is ready to be processed. FTMotion::blockProcRdy_z1 = false, // Storage for the previous indicator. FTMotion::blockProcDn = false; // Indicates current block is done being processed. bool FTMotion::batchRdy = false; // Indicates a batch of the fixed time trajectory // has been generated, is now available in the upper - // half of traj.x[], y, z ... e vectors, and is ready to be // post processed, if applicable, then interpolated. bool FTMotion::batchRdyForInterp = false; // Indicates the batch is done being post processed, // if applicable, and is ready to be converted to step commands. bool FTMotion::runoutEna = false; // True if runout of the block hasn't been done and is allowed. bool FTMotion::blockDataIsRunout = false; // Indicates the last loaded block variables are for a runout. // Trapezoid data variables. xyze_pos_t FTMotion::startPosn, // (mm) Start position of block FTMotion::endPosn_prevBlock = { 0.0f }; // (mm) End position of previous block xyze_float_t FTMotion::ratio; // (ratio) Axis move ratio of block float FTMotion::accel_P, // Acceleration prime of block. [mm/sec/sec] FTMotion::decel_P, // Deceleration prime of block. [mm/sec/sec] FTMotion::F_P, // Feedrate prime of block. [mm/sec] FTMotion::f_s, // Starting feedrate of block. [mm/sec] FTMotion::s_1e, // Position after acceleration phase of block. FTMotion::s_2e; // Position after acceleration and coasting phase of block. uint32_t FTMotion::N1, // Number of data points in the acceleration phase. FTMotion::N2, // Number of data points in the coasting phase. FTMotion::N3; // Number of data points in the deceleration phase. uint32_t FTMotion::max_intervals; // Total number of data points that will be generated from block. // Make vector variables. uint32_t FTMotion::makeVector_idx = 0, // Index of fixed time trajectory generation of the overall block. FTMotion::makeVector_idx_z1 = 0, // Storage for the previously calculated index above. FTMotion::makeVector_batchIdx = 0; // Index of fixed time trajectory generation within the batch. // Interpolation variables. xyze_long_t FTMotion::steps = { 0 }; // Step count accumulator. uint32_t FTMotion::interpIdx = 0, // Index of current data point being interpolated. FTMotion::interpIdx_z1 = 0; // Storage for the previously calculated index above. // Shaping variables. #if HAS_X_AXIS FTMotion::shaping_t FTMotion::shaping = { 0, 0, x:{ false, { 0.0f }, { 0.0f }, { 0 } }, // d_zi, Ai, Ni #if HAS_Y_AXIS y:{ false, { 0.0f }, { 0.0f }, { 0 } } // d_zi, Ai, Ni #endif }; #endif #if HAS_EXTRUDERS // Linear advance variables. float FTMotion::e_raw_z1 = 0.0f; // (ms) Unit delay of raw extruder position. float FTMotion::e_advanced_z1 = 0.0f; // (ms) Unit delay of advanced extruder position. #endif constexpr uint32_t last_batchIdx = (FTM_WINDOW_SIZE) - (FTM_BATCH_SIZE); //----------------------------------------------------------------- // Function definitions. //----------------------------------------------------------------- // Public functions. static bool markBlockStart = false; // Sets controller states to begin processing a block. // Called by Stepper::ftMotion_blockQueueUpdate, invoked from the main loop. void FTMotion::startBlockProc() { blockProcRdy = true; blockProcDn = false; runoutEna = true; } // Move any free data points to the stepper buffer even if a full batch isn't ready. void FTMotion::runoutBlock() { if (!runoutEna) return; startPosn = endPosn_prevBlock; ratio.reset(); max_intervals = cfg.modeHasShaper() ? shaper_intervals : 0; if (max_intervals <= TERN(FTM_UNIFIED_BWS, FTM_BATCH_SIZE, min_max_intervals - (FTM_BATCH_SIZE))) max_intervals = min_max_intervals; max_intervals += ( #if ENABLED(FTM_UNIFIED_BWS) FTM_WINDOW_SIZE - makeVector_batchIdx #else FTM_WINDOW_SIZE - ((last_batchIdx < (FTM_BATCH_SIZE)) ? 0 : makeVector_batchIdx) #endif ); blockProcRdy = blockDataIsRunout = true; runoutEna = blockProcDn = false; } // Controller main, to be invoked from non-isr task. void FTMotion::loop() { if (!cfg.mode) return; /** * Handle block abort with the following sequence: * 1. Zero out commands in stepper ISR. * 2. Drain the motion buffer, stop processing until they are emptied. * 3. Reset all the states / memory. * 4. Signal ready for new block. */ if (stepper.abort_current_block) { if (sts_stepperBusy) return; // Wait until motion buffers are emptied reset(); blockProcDn = true; // Set queueing to look for next block. stepper.abort_current_block = false; // Abort finished. } // Planner processing and block conversion. if (!blockProcRdy) stepper.ftMotion_blockQueueUpdate(); if (blockProcRdy) { if (!blockProcRdy_z1) { // One-shot. if (!blockDataIsRunout) { loadBlockData(stepper.current_block); markBlockStart = true; } else blockDataIsRunout = false; } while (!blockProcDn && !batchRdy && (makeVector_idx - makeVector_idx_z1 < (FTM_POINTS_PER_LOOP))) makeVector(); } // FBS / post processing. if (batchRdy && !batchRdyForInterp) { // Call Ulendo FBS here. #if ENABLED(FTM_UNIFIED_BWS) trajMod = traj; // Move the window to traj #else // Copy the uncompensated vectors. #define TCOPY(A) memcpy(trajMod.A, traj.A, sizeof(trajMod.A)); LOGICAL_AXIS_MAP_LC(TCOPY); // Shift the time series back in the window #define TSHIFT(A) memcpy(traj.A, &traj.A[FTM_BATCH_SIZE], last_batchIdx * sizeof(traj.A[0])); LOGICAL_AXIS_MAP_LC(TSHIFT); #endif // ... data is ready in trajMod. batchRdyForInterp = true; batchRdy = false; // Clear so makeVector() can resume generating points. } // Interpolation. while (batchRdyForInterp && (stepperCmdBuffItems() < (FTM_STEPPERCMD_BUFF_SIZE) - (FTM_STEPS_PER_UNIT_TIME)) && (interpIdx - interpIdx_z1 < (FTM_STEPS_PER_LOOP)) ) { convertToSteps(interpIdx); if (++interpIdx == FTM_BATCH_SIZE) { batchRdyForInterp = false; interpIdx = 0; } } // Report busy status to planner. busy = (sts_stepperBusy || ((!blockProcDn && blockProcRdy) || batchRdy || batchRdyForInterp || runoutEna)); blockProcRdy_z1 = blockProcRdy; makeVector_idx_z1 = makeVector_idx; interpIdx_z1 = interpIdx; } #if HAS_X_AXIS // Refresh the gains used by shaping functions. // To be called on init or mode or zeta change. void FTMotion::Shaping::updateShapingA(float zeta[]/*=cfg.zeta*/, float vtol[]/*=cfg.vtol*/) { const float Kx = exp(-zeta[0] * M_PI / sqrt(1.0f - sq(zeta[0]))), Ky = exp(-zeta[1] * M_PI / sqrt(1.0f - sq(zeta[1]))), Kx2 = sq(Kx), Ky2 = sq(Ky); switch (cfg.mode) { case ftMotionMode_ZV: max_i = 1U; x.Ai[0] = 1.0f / (1.0f + Kx); x.Ai[1] = x.Ai[0] * Kx; y.Ai[0] = 1.0f / (1.0f + Ky); y.Ai[1] = y.Ai[0] * Ky; break; case ftMotionMode_ZVD: max_i = 2U; x.Ai[0] = 1.0f / (1.0f + 2.0f * Kx + Kx2); x.Ai[1] = x.Ai[0] * 2.0f * Kx; x.Ai[2] = x.Ai[0] * Kx2; y.Ai[0] = 1.0f / (1.0f + 2.0f * Ky + Ky2); y.Ai[1] = y.Ai[0] * 2.0f * Ky; y.Ai[2] = y.Ai[0] * Ky2; break; case ftMotionMode_ZVDD: max_i = 3U; x.Ai[0] = 1.0f / (1.0f + 3.0f * Kx + 3.0f * Kx2 + cu(Kx)); x.Ai[1] = x.Ai[0] * 3.0f * Kx; x.Ai[2] = x.Ai[0] * 3.0f * Kx2; x.Ai[3] = x.Ai[0] * cu(Kx); y.Ai[0] = 1.0f / (1.0f + 3.0f * Ky + 3.0f * Ky2 + cu(Ky)); y.Ai[1] = y.Ai[0] * 3.0f * Ky; y.Ai[2] = y.Ai[0] * 3.0f * Ky2; y.Ai[3] = y.Ai[0] * cu(Ky); break; case ftMotionMode_ZVDDD: max_i = 4U; x.Ai[0] = 1.0f / (1.0f + 4.0f * Kx + 6.0f * Kx2 + 4.0f * cu(Kx) + sq(Kx2)); x.Ai[1] = x.Ai[0] * 4.0f * Kx; x.Ai[2] = x.Ai[0] * 6.0f * Kx2; x.Ai[3] = x.Ai[0] * 4.0f * cu(Kx); x.Ai[4] = x.Ai[0] * sq(Kx2); y.Ai[0] = 1.0f / (1.0f + 4.0f * Ky + 6.0f * Ky2 + 4.0f * cu(Ky) + sq(Ky2)); y.Ai[1] = y.Ai[0] * 4.0f * Ky; y.Ai[2] = y.Ai[0] * 6.0f * Ky2; y.Ai[3] = y.Ai[0] * 4.0f * cu(Ky); y.Ai[4] = y.Ai[0] * sq(Ky2); break; case ftMotionMode_EI: { max_i = 2U; x.Ai[0] = 0.25f * (1.0f + vtol[0]); x.Ai[1] = 0.50f * (1.0f - vtol[0]) * Kx; x.Ai[2] = x.Ai[0] * Kx2; y.Ai[0] = 0.25f * (1.0f + vtol[1]); y.Ai[1] = 0.50f * (1.0f - vtol[1]) * Ky; y.Ai[2] = y.Ai[0] * Ky2; const float X_adj = 1.0f / (x.Ai[0] + x.Ai[1] + x.Ai[2]); const float Y_adj = 1.0f / (y.Ai[0] + y.Ai[1] + y.Ai[2]); for (uint32_t i = 0U; i < 3U; i++) { x.Ai[i] *= X_adj; y.Ai[i] *= Y_adj; } } break; case ftMotionMode_2HEI: { max_i = 3U; const float vtolx2 = sq(vtol[0]); const float X = pow(vtolx2 * (sqrt(1.0f - vtolx2) + 1.0f), 1.0f / 3.0f); x.Ai[0] = (3.0f * sq(X) + 2.0f * X + 3.0f * vtolx2) / (16.0f * X); x.Ai[1] = (0.5f - x.Ai[0]) * Kx; x.Ai[2] = x.Ai[1] * Kx; x.Ai[3] = x.Ai[0] * cu(Kx); const float vtoly2 = sq(vtol[1]); const float Y = pow(vtoly2 * (sqrt(1.0f - vtoly2) + 1.0f), 1.0f / 3.0f); y.Ai[0] = (3.0f * sq(Y) + 2.0f * Y + 3.0f * vtoly2) / (16.0f * Y); y.Ai[1] = (0.5f - y.Ai[0]) * Ky; y.Ai[2] = y.Ai[1] * Ky; y.Ai[3] = y.Ai[0] * cu(Ky); const float X_adj = 1.0f / (x.Ai[0] + x.Ai[1] + x.Ai[2] + x.Ai[3]); const float Y_adj = 1.0f / (y.Ai[0] + y.Ai[1] + y.Ai[2] + y.Ai[3]); for (uint32_t i = 0U; i < 4U; i++) { x.Ai[i] *= X_adj; y.Ai[i] *= Y_adj; } } break; case ftMotionMode_3HEI: { max_i = 4U; x.Ai[0] = 0.0625f * ( 1.0f + 3.0f * vtol[0] + 2.0f * sqrt( 2.0f * ( vtol[0] + 1.0f ) * vtol[0] ) ); x.Ai[1] = 0.25f * ( 1.0f - vtol[0] ) * Kx; x.Ai[2] = ( 0.5f * ( 1.0f + vtol[0] ) - 2.0f * x.Ai[0] ) * Kx2; x.Ai[3] = x.Ai[1] * Kx2; x.Ai[4] = x.Ai[0] * sq(Kx2); y.Ai[0] = 0.0625f * (1.0f + 3.0f * vtol[1] + 2.0f * sqrt(2.0f * (vtol[1] + 1.0f) * vtol[1])); y.Ai[1] = 0.25f * (1.0f - vtol[1]) * Ky; y.Ai[2] = (0.5f * (1.0f + vtol[1]) - 2.0f * y.Ai[0]) * Ky2; y.Ai[3] = y.Ai[1] * Ky2; y.Ai[4] = y.Ai[0] * sq(Ky2); const float X_adj = 1.0f / (x.Ai[0] + x.Ai[1] + x.Ai[2] + x.Ai[3] + x.Ai[4]); const float Y_adj = 1.0f / (y.Ai[0] + y.Ai[1] + y.Ai[2] + y.Ai[3] + y.Ai[4]); for (uint32_t i = 0U; i < 5U; i++) { x.Ai[i] *= X_adj; y.Ai[i] *= Y_adj; } } break; case ftMotionMode_MZV: { max_i = 2U; const float Bx = 1.4142135623730950488016887242097f * Kx; x.Ai[0] = 1.0f / (1.0f + Bx + Kx2); x.Ai[1] = x.Ai[0] * Bx; x.Ai[2] = x.Ai[0] * Kx2; const float By = 1.4142135623730950488016887242097f * Ky; y.Ai[0] = 1.0f / (1.0f + By + Ky2); y.Ai[1] = y.Ai[0] * By; y.Ai[2] = y.Ai[0] * Ky2; } break; default: ZERO(x.Ai); ZERO(y.Ai); max_i = 0; } } void FTMotion::updateShapingA(float zeta[]/*=cfg.zeta*/, float vtol[]/*=cfg.vtol*/) { shaping.updateShapingA(zeta, vtol); } // Refresh the indices used by shaping functions. // To be called when frequencies change. void FTMotion::AxisShaping::updateShapingN(const_float_t f, const_float_t df) { // Protections omitted for DBZ and for index exceeding array length. switch (cfg.mode) { case ftMotionMode_ZV: Ni[1] = round((0.5f / f / df) * (FTM_FS)); break; case ftMotionMode_ZVD: case ftMotionMode_EI: Ni[1] = round((0.5f / f / df) * (FTM_FS)); Ni[2] = Ni[1] + Ni[1]; break; case ftMotionMode_ZVDD: case ftMotionMode_2HEI: Ni[1] = round((0.5f / f / df) * (FTM_FS)); Ni[2] = Ni[1] + Ni[1]; Ni[3] = Ni[2] + Ni[1]; break; case ftMotionMode_ZVDDD: case ftMotionMode_3HEI: Ni[1] = round((0.5f / f / df) * (FTM_FS)); Ni[2] = Ni[1] + Ni[1]; Ni[3] = Ni[2] + Ni[1]; Ni[4] = Ni[3] + Ni[1]; break; case ftMotionMode_MZV: Ni[1] = round((0.375f / f / df) * (FTM_FS)); Ni[2] = Ni[1] + Ni[1]; break; default: ZERO(Ni); } } void FTMotion::updateShapingN(const_float_t xf OPTARG(HAS_Y_AXIS, const_float_t yf), float zeta[]/*=cfg.zeta*/) { const float xdf = sqrt(1.0f - sq(zeta[0])); shaping.x.updateShapingN(xf, xdf); #if HAS_Y_AXIS const float ydf = sqrt(1.0f - sq(zeta[1])); shaping.y.updateShapingN(yf, ydf); #endif } #endif // HAS_X_AXIS // Reset all trajectory processing variables. void FTMotion::reset() { stepperCmdBuff_produceIdx = stepperCmdBuff_consumeIdx = 0; traj.reset(); blockProcRdy = blockProcRdy_z1 = blockProcDn = false; batchRdy = batchRdyForInterp = false; runoutEna = false; endPosn_prevBlock.reset(); makeVector_idx = makeVector_idx_z1 = 0; makeVector_batchIdx = TERN(FTM_UNIFIED_BWS, 0, _MAX(last_batchIdx, FTM_BATCH_SIZE)); steps.reset(); interpIdx = interpIdx_z1 = 0; #if HAS_X_AXIS ZERO(shaping.x.d_zi); TERN_(HAS_Y_AXIS, ZERO(shaping.y.d_zi)); shaping.zi_idx = 0; #endif TERN_(HAS_EXTRUDERS, e_raw_z1 = e_advanced_z1 = 0.0f); ZERO(axis_pos_move_end_ti); ZERO(axis_neg_move_end_ti); } // Private functions. // Auxiliary function to get number of step commands in the buffer. int32_t FTMotion::stepperCmdBuffItems() { const int32_t udiff = stepperCmdBuff_produceIdx - stepperCmdBuff_consumeIdx; return (udiff < 0) ? udiff + (FTM_STEPPERCMD_BUFF_SIZE) : udiff; } // Initializes storage variables before startup. void FTMotion::init() { #if HAS_X_AXIS refreshShapingN(); updateShapingA(); #endif reset(); // Precautionary. } // Load / convert block data from planner to fixed-time control variables. void FTMotion::loadBlockData(block_t * const current_block) { const float totalLength = current_block->millimeters, oneOverLength = 1.0f / totalLength; startPosn = endPosn_prevBlock; const xyze_pos_t moveDist = LOGICAL_AXIS_ARRAY( current_block->steps.e * planner.mm_per_step[E_AXIS_N(current_block->extruder)] * (current_block->direction_bits.e ? 1 : -1), current_block->steps.x * planner.mm_per_step[X_AXIS] * (current_block->direction_bits.x ? 1 : -1), current_block->steps.y * planner.mm_per_step[Y_AXIS] * (current_block->direction_bits.y ? 1 : -1), current_block->steps.z * planner.mm_per_step[Z_AXIS] * (current_block->direction_bits.z ? 1 : -1), current_block->steps.i * planner.mm_per_step[I_AXIS] * (current_block->direction_bits.i ? 1 : -1), current_block->steps.j * planner.mm_per_step[J_AXIS] * (current_block->direction_bits.j ? 1 : -1), current_block->steps.k * planner.mm_per_step[K_AXIS] * (current_block->direction_bits.k ? 1 : -1), current_block->steps.u * planner.mm_per_step[U_AXIS] * (current_block->direction_bits.u ? 1 : -1), current_block->steps.v * planner.mm_per_step[V_AXIS] * (current_block->direction_bits.v ? 1 : -1), current_block->steps.w * planner.mm_per_step[W_AXIS] * (current_block->direction_bits.w ? 1 : -1) ); ratio = moveDist * oneOverLength; const float spm = totalLength / current_block->step_event_count; // (steps/mm) Distance for each step f_s = spm * current_block->initial_rate; // (steps/s) Start feedrate const float f_e = spm * current_block->final_rate; // (steps/s) End feedrate /* Keep for comprehension const float a = current_block->acceleration, // (mm/s^2) Same magnitude for acceleration or deceleration oneby2a = 1.0f / (2.0f * a), // (s/mm) Time to accelerate or decelerate one mm (i.e., oneby2a * 2 oneby2d = -oneby2a; // (s/mm) Time to accelerate or decelerate one mm (i.e., oneby2a * 2 const float fsSqByTwoA = sq(f_s) * oneby2a, // (mm) Distance to accelerate from start speed to nominal speed feSqByTwoD = sq(f_e) * oneby2d; // (mm) Distance to decelerate from nominal speed to end speed float F_n = current_block->nominal_speed; // (mm/s) Speed we hope to achieve, if possible const float fdiff = feSqByTwoD - fsSqByTwoA, // (mm) Coasting distance if nominal speed is reached odiff = oneby2a - oneby2d, // (i.e., oneby2a * 2) (mm/s) Change in speed for one second of acceleration ldiff = totalLength - fdiff; // (mm) Distance to travel if nominal speed is reached float T2 = (1.0f / F_n) * (ldiff - odiff * sq(F_n)); // (s) Coasting duration after nominal speed reached if (T2 < 0.0f) { T2 = 0.0f; F_n = SQRT(ldiff / odiff); // Clip by intersection if nominal speed can't be reached. } const float T1 = (F_n - f_s) / a, // (s) Accel Time = difference in feedrate over acceleration T3 = (F_n - f_e) / a; // (s) Decel Time = difference in feedrate over acceleration */ const float accel = current_block->acceleration, oneOverAccel = 1.0f / accel; float F_n = current_block->nominal_speed; const float ldiff = totalLength + 0.5f * oneOverAccel * (sq(f_s) + sq(f_e)); float T2 = ldiff / F_n - oneOverAccel * F_n; if (T2 < 0.0f) { T2 = 0.0f; F_n = SQRT(ldiff * accel); } const float T1 = (F_n - f_s) * oneOverAccel, T3 = (F_n - f_e) * oneOverAccel; N1 = CEIL(T1 * (FTM_FS)); // Accel datapoints based on Hz frequency N2 = CEIL(T2 * (FTM_FS)); // Coast N3 = CEIL(T3 * (FTM_FS)); // Decel const float T1_P = N1 * (FTM_TS), // (s) Accel datapoints x timestep resolution T2_P = N2 * (FTM_TS), // (s) Coast T3_P = N3 * (FTM_TS); // (s) Decel /** * Calculate the reachable feedrate at the end of the accel phase. * totalLength is the total distance to travel in mm * f_s : (mm/s) Starting feedrate * f_e : (mm/s) Ending feedrate * T1_P : (sec) Time spent accelerating * T2_P : (sec) Time spent coasting * T3_P : (sec) Time spent decelerating * f_s * T1_P : (mm) Distance traveled during the accel phase * f_e * T3_P : (mm) Distance traveled during the decel phase */ const float adist = f_s * T1_P; F_P = (2.0f * totalLength - adist - f_e * T3_P) / (T1_P + 2.0f * T2_P + T3_P); // (mm/s) Feedrate at the end of the accel phase // Calculate the acceleration and deceleration rates accel_P = N1 ? ((F_P - f_s) / T1_P) : 0.0f; decel_P = (f_e - F_P) / T3_P; // Calculate the distance traveled during the accel phase s_1e = adist + 0.5f * accel_P * sq(T1_P); // Calculate the distance traveled during the decel phase s_2e = s_1e + F_P * T2_P; // Accel + Coasting + Decel datapoints max_intervals = N1 + N2 + N3; endPosn_prevBlock += moveDist; millis_t move_end_ti = millis() + SEC_TO_MS(FTM_TS*(float)(max_intervals + num_samples_cmpnstr_settle() + (PROP_BATCHES+1)*FTM_BATCH_SIZE) + ((float)FTM_STEPPERCMD_BUFF_SIZE/(float)FTM_STEPPER_FS)); #if CORE_IS_XY if (moveDist.x > 0.f) axis_pos_move_end_ti[A_AXIS] = move_end_ti; if (moveDist.y > 0.f) axis_pos_move_end_ti[B_AXIS] = move_end_ti; if (moveDist.x + moveDist.y > 0.f) axis_pos_move_end_ti[X_HEAD] = move_end_ti; if (moveDist.x - moveDist.y > 0.f) axis_pos_move_end_ti[Y_HEAD] = move_end_ti; if (moveDist.x < 0.f) axis_neg_move_end_ti[A_AXIS] = move_end_ti; if (moveDist.y < 0.f) axis_neg_move_end_ti[B_AXIS] = move_end_ti; if (moveDist.x + moveDist.y < 0.f) axis_neg_move_end_ti[X_HEAD] = move_end_ti; if (moveDist.x - moveDist.y < 0.f) axis_neg_move_end_ti[Y_HEAD] = move_end_ti; #else if (moveDist.x > 0.f) axis_pos_move_end_ti[X_AXIS] = move_end_ti; if (moveDist.y > 0.f) axis_pos_move_end_ti[Y_AXIS] = move_end_ti; if (moveDist.x < 0.f) axis_neg_move_end_ti[X_AXIS] = move_end_ti; if (moveDist.y < 0.f) axis_neg_move_end_ti[Y_AXIS] = move_end_ti; #endif if (moveDist.z > 0.f) axis_pos_move_end_ti[Z_AXIS] = move_end_ti; if (moveDist.z < 0.f) axis_neg_move_end_ti[Z_AXIS] = move_end_ti; // if (moveDist.i > 0.f) axis_pos_move_end_ti[I_AXIS] = move_end_ti; // if (moveDist.i < 0.f) axis_neg_move_end_ti[I_AXIS] = move_end_ti; // if (moveDist.j > 0.f) axis_pos_move_end_ti[J_AXIS] = move_end_ti; // if (moveDist.j < 0.f) axis_neg_move_end_ti[J_AXIS] = move_end_ti; // if (moveDist.k > 0.f) axis_pos_move_end_ti[K_AXIS] = move_end_ti; // if (moveDist.k < 0.f) axis_neg_move_end_ti[K_AXIS] = move_end_ti; // if (moveDist.u > 0.f) axis_pos_move_end_ti[U_AXIS] = move_end_ti; // if (moveDist.u < 0.f) axis_neg_move_end_ti[U_AXIS] = move_end_ti; // . // . // . // If the endstop is already pressed, endstop interrupts won't invoke // endstop_triggered and the move will grind. So check here for a // triggered endstop, which shortly marks the block for discard. endstops.update(); } // Generate data points of the trajectory. void FTMotion::makeVector() { float accel_k = 0.0f; // (mm/s^2) Acceleration K factor float tau = (makeVector_idx + 1) * (FTM_TS); // (s) Time since start of block float dist = 0.0f; // (mm) Distance traveled if (makeVector_idx < N1) { // Acceleration phase dist = (f_s * tau) + (0.5f * accel_P * sq(tau)); // (mm) Distance traveled for acceleration phase since start of block accel_k = accel_P; // (mm/s^2) Acceleration K factor from Accel phase } else if (makeVector_idx < (N1 + N2)) { // Coasting phase dist = s_1e + F_P * (tau - N1 * (FTM_TS)); // (mm) Distance traveled for coasting phase since start of block } else { // Deceleration phase tau -= (N1 + N2) * (FTM_TS); // (s) Time since start of decel phase dist = s_2e + F_P * tau + 0.5f * decel_P * sq(tau); // (mm) Distance traveled for deceleration phase since start of block accel_k = decel_P; // (mm/s^2) Acceleration K factor from Decel phase } #define _FTM_TRAJ(A) traj.A[makeVector_batchIdx] = startPosn.A + ratio.A * dist; LOGICAL_AXIS_MAP_LC(_FTM_TRAJ); #if HAS_EXTRUDERS if (cfg.linearAdvEna) { float dedt_adj = (traj.e[makeVector_batchIdx] - e_raw_z1) * (FTM_FS); if (ratio.e > 0.0f) dedt_adj += accel_k * cfg.linearAdvK; e_raw_z1 = traj.e[makeVector_batchIdx]; e_advanced_z1 += dedt_adj * (FTM_TS); traj.e[makeVector_batchIdx] = e_advanced_z1; } #endif // Update shaping parameters if needed. switch (cfg.dynFreqMode) { #if HAS_DYNAMIC_FREQ_MM case dynFreqMode_Z_BASED: if (traj.z[makeVector_batchIdx] != 0.0f) { // Only update if Z changed. const float xf = cfg.baseFreq[X_AXIS] + cfg.dynFreqK[X_AXIS] * traj.z[makeVector_batchIdx] OPTARG(HAS_Y_AXIS, yf = cfg.baseFreq[Y_AXIS] + cfg.dynFreqK[Y_AXIS] * traj.z[makeVector_batchIdx]); updateShapingN(_MAX(xf, FTM_MIN_SHAPE_FREQ) OPTARG(HAS_Y_AXIS, _MAX(yf, FTM_MIN_SHAPE_FREQ))); } break; #endif #if HAS_DYNAMIC_FREQ_G case dynFreqMode_MASS_BASED: // Update constantly. The optimization done for Z value makes // less sense for E, as E is expected to constantly change. updateShapingN( cfg.baseFreq[X_AXIS] + cfg.dynFreqK[X_AXIS] * traj.e[makeVector_batchIdx] OPTARG(HAS_Y_AXIS, cfg.baseFreq[Y_AXIS] + cfg.dynFreqK[Y_AXIS] * traj.e[makeVector_batchIdx]) ); break; #endif default: break; } // Apply shaping if in mode. #if HAS_X_AXIS if (cfg.modeHasShaper()) { shaping.x.d_zi[shaping.zi_idx] = traj.x[makeVector_batchIdx]; traj.x[makeVector_batchIdx] *= shaping.x.Ai[0]; #if HAS_Y_AXIS shaping.y.d_zi[shaping.zi_idx] = traj.y[makeVector_batchIdx]; traj.y[makeVector_batchIdx] *= shaping.y.Ai[0]; #endif for (uint32_t i = 1U; i <= shaping.max_i; i++) { const uint32_t udiffx = shaping.zi_idx - shaping.x.Ni[i]; traj.x[makeVector_batchIdx] += shaping.x.Ai[i] * shaping.x.d_zi[shaping.x.Ni[i] > shaping.zi_idx ? (FTM_ZMAX) + udiffx : udiffx]; #if HAS_Y_AXIS const uint32_t udiffy = shaping.zi_idx - shaping.y.Ni[i]; traj.y[makeVector_batchIdx] += shaping.y.Ai[i] * shaping.y.d_zi[shaping.y.Ni[i] > shaping.zi_idx ? (FTM_ZMAX) + udiffy : udiffy]; #endif } if (++shaping.zi_idx == (FTM_ZMAX)) shaping.zi_idx = 0; } #endif // Filled up the queue with regular and shaped steps if (++makeVector_batchIdx == FTM_WINDOW_SIZE) { makeVector_batchIdx = last_batchIdx; batchRdy = true; } if (++makeVector_idx == max_intervals) { blockProcDn = true; blockProcRdy = false; makeVector_idx = 0; } } /** * Convert to steps * - Commands are written in a bitmask with step and dir as single bits. * - Tests for delta are moved outside the loop. * - Two functions are used for command computation with an array of function pointers. */ static void (*command_set[SUM_TERN(HAS_EXTRUDERS, NUM_AXES, 1)])(int32_t&, int32_t&, ft_command_t&, int32_t, int32_t); static void command_set_pos(int32_t &e, int32_t &s, ft_command_t &b, int32_t bd, int32_t bs) { if (e < FTM_CTS_COMPARE_VAL) return; s++; b |= bd | bs; e -= FTM_STEPS_PER_UNIT_TIME; } static void command_set_neg(int32_t &e, int32_t &s, ft_command_t &b, int32_t bd, int32_t bs) { if (e > -(FTM_CTS_COMPARE_VAL)) return; s--; b |= bs; e += FTM_STEPS_PER_UNIT_TIME; } // Interpolates single data point to stepper commands. void FTMotion::convertToSteps(const uint32_t idx) { xyze_long_t err_P = { 0 }; //#define STEPS_ROUNDING #if ENABLED(STEPS_ROUNDING) #define TOSTEPS(A,B) int32_t(trajMod.A[idx] * planner.settings.axis_steps_per_mm[B] + (trajMod.A[idx] < 0.0f ? -0.5f : 0.5f)) const xyze_long_t steps_tar = LOGICAL_AXIS_ARRAY( TOSTEPS(e, E_AXIS_N(current_block->extruder)), // May be eliminated if guaranteed positive. TOSTEPS(x, X_AXIS), TOSTEPS(y, Y_AXIS), TOSTEPS(z, Z_AXIS), TOSTEPS(i, I_AXIS), TOSTEPS(j, J_AXIS), TOSTEPS(k, K_AXIS), TOSTEPS(u, U_AXIS), TOSTEPS(v, V_AXIS), TOSTEPS(w, W_AXIS) ); xyze_long_t delta = steps_tar - steps; #else #define TOSTEPS(A,B) int32_t(trajMod.A[idx] * planner.settings.axis_steps_per_mm[B]) - steps.A xyze_long_t delta = LOGICAL_AXIS_ARRAY( TOSTEPS(e, E_AXIS_N(current_block->extruder)), TOSTEPS(x, X_AXIS), TOSTEPS(y, Y_AXIS), TOSTEPS(z, Z_AXIS), TOSTEPS(i, I_AXIS), TOSTEPS(j, J_AXIS), TOSTEPS(k, K_AXIS), TOSTEPS(u, U_AXIS), TOSTEPS(v, V_AXIS), TOSTEPS(w, W_AXIS) ); #endif #define _COMMAND_SET(AXIS) command_set[_AXIS(AXIS)] = delta[_AXIS(AXIS)] >= 0 ? command_set_pos : command_set_neg; LOGICAL_AXIS_MAP(_COMMAND_SET); for (uint32_t i = 0U; i < (FTM_STEPS_PER_UNIT_TIME); i++) { ft_command_t &cmd = stepperCmdBuff[stepperCmdBuff_produceIdx]; // Init all step/dir bits to 0 (defaulting to reverse/negative motion) cmd = 0; // Mark the start of a new block if (markBlockStart) { cmd = _BV(FT_BIT_START); markBlockStart = false; } // Accumulate the errors for all axes err_P += delta; // Set up step/dir bits for all axes #define _COMMAND_RUN(AXIS) command_set[_AXIS(AXIS)](err_P[_AXIS(AXIS)], steps[_AXIS(AXIS)], cmd, _BV(FT_BIT_DIR_##AXIS), _BV(FT_BIT_STEP_##AXIS)); LOGICAL_AXIS_MAP(_COMMAND_RUN); // Next circular buffer index if (++stepperCmdBuff_produceIdx == (FTM_STEPPERCMD_BUFF_SIZE)) stepperCmdBuff_produceIdx = 0; } // FTM_STEPS_PER_UNIT_TIME loop } #endif // FT_MOTION
2301_81045437/Marlin
Marlin/src/module/ft_motion.cpp
C++
agpl-3.0
32,328
/** * Marlin 3D Printer Firmware * Copyright (c) 2023 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../inc/MarlinConfigPre.h" // Access the top level configurations. #include "../module/planner.h" // Access block type from planner. #include "ft_types.h" #if HAS_X_AXIS && (HAS_Z_AXIS || HAS_EXTRUDERS) #define HAS_DYNAMIC_FREQ 1 #if HAS_Z_AXIS #define HAS_DYNAMIC_FREQ_MM 1 #endif #if HAS_EXTRUDERS #define HAS_DYNAMIC_FREQ_G 1 #endif #endif typedef struct FTConfig { ftMotionMode_t mode = FTM_DEFAULT_MODE; // Mode / active compensation mode configuration. bool modeHasShaper() { return WITHIN(mode, 10U, 19U); } #if HAS_X_AXIS float baseFreq[1 + ENABLED(HAS_Y_AXIS)] = // Base frequency. [Hz] { FTM_SHAPING_DEFAULT_X_FREQ OPTARG(HAS_Y_AXIS, FTM_SHAPING_DEFAULT_Y_FREQ) }; float zeta[1 + ENABLED(HAS_Y_AXIS)] = // Damping factor { FTM_SHAPING_ZETA_X OPTARG(HAS_Y_AXIS, FTM_SHAPING_ZETA_Y) }; float vtol[1 + ENABLED(HAS_Y_AXIS)] = // Vibration Level { FTM_SHAPING_V_TOL_X OPTARG(HAS_Y_AXIS, FTM_SHAPING_V_TOL_Y) }; #endif #if HAS_DYNAMIC_FREQ dynFreqMode_t dynFreqMode = FTM_DEFAULT_DYNFREQ_MODE; // Dynamic frequency mode configuration. float dynFreqK[1 + ENABLED(HAS_Y_AXIS)] = { 0.0f }; // Scaling / gain for dynamic frequency. [Hz/mm] or [Hz/g] #else static constexpr dynFreqMode_t dynFreqMode = dynFreqMode_DISABLED; #endif #if HAS_EXTRUDERS bool linearAdvEna = FTM_LINEAR_ADV_DEFAULT_ENA; // Linear advance enable configuration. float linearAdvK = FTM_LINEAR_ADV_DEFAULT_K; // Linear advance gain. #endif } ft_config_t; class FTMotion { public: // Public variables static ft_config_t cfg; static bool busy; static void set_defaults() { cfg.mode = FTM_DEFAULT_MODE; TERN_(HAS_X_AXIS, cfg.baseFreq[X_AXIS] = FTM_SHAPING_DEFAULT_X_FREQ); TERN_(HAS_Y_AXIS, cfg.baseFreq[Y_AXIS] = FTM_SHAPING_DEFAULT_Y_FREQ); TERN_(HAS_X_AXIS, cfg.zeta[X_AXIS] = FTM_SHAPING_ZETA_X); TERN_(HAS_Y_AXIS, cfg.zeta[Y_AXIS] = FTM_SHAPING_ZETA_Y); TERN_(HAS_X_AXIS, cfg.vtol[X_AXIS] = FTM_SHAPING_V_TOL_X); TERN_(HAS_Y_AXIS, cfg.vtol[Y_AXIS] = FTM_SHAPING_V_TOL_Y); #if HAS_DYNAMIC_FREQ cfg.dynFreqMode = FTM_DEFAULT_DYNFREQ_MODE; cfg.dynFreqK[X_AXIS] = TERN_(HAS_Y_AXIS, cfg.dynFreqK[Y_AXIS]) = 0.0f; #endif #if HAS_EXTRUDERS cfg.linearAdvEna = FTM_LINEAR_ADV_DEFAULT_ENA; cfg.linearAdvK = FTM_LINEAR_ADV_DEFAULT_K; #endif #if HAS_X_AXIS refreshShapingN(); updateShapingA(); #endif reset(); } static ft_command_t stepperCmdBuff[FTM_STEPPERCMD_BUFF_SIZE]; // Buffer of stepper commands. static int32_t stepperCmdBuff_produceIdx, // Index of next stepper command write to the buffer. stepperCmdBuff_consumeIdx; // Index of next stepper command read from the buffer. static bool sts_stepperBusy; // The stepper buffer has items and is in use. static millis_t axis_pos_move_end_ti[NUM_AXIS_ENUMS], axis_neg_move_end_ti[NUM_AXIS_ENUMS]; // Public methods static void init(); static void startBlockProc(); // Set controller states to begin processing a block. static bool getBlockProcDn() { return blockProcDn; } // Return true if the controller no longer needs the current block. static void runoutBlock(); // Move any free data points to the stepper buffer even if a full batch isn't ready. static void loop(); // Controller main, to be invoked from non-isr task. #if HAS_X_AXIS // Refresh the gains used by shaping functions. // To be called on init or mode or zeta change. static void updateShapingA(float zeta[]=cfg.zeta, float vtol[]=cfg.vtol); // Refresh the indices used by shaping functions. // To be called when frequencies change. static void updateShapingN(const_float_t xf OPTARG(HAS_Y_AXIS, const_float_t yf), float zeta[]=cfg.zeta); static void refreshShapingN() { updateShapingN(cfg.baseFreq[X_AXIS] OPTARG(HAS_Y_AXIS, cfg.baseFreq[Y_AXIS])); } #endif static void reset(); // Reset all states of the fixed time conversion to defaults. static bool axis_moving_pos(const AxisEnum axis) { return !ELAPSED(millis(), axis_pos_move_end_ti[axis]); } static bool axis_moving_neg(const AxisEnum axis) { return !ELAPSED(millis(), axis_neg_move_end_ti[axis]); } private: static xyze_trajectory_t traj; static xyze_trajectoryMod_t trajMod; static bool blockProcRdy, blockProcRdy_z1, blockProcDn; static bool batchRdy, batchRdyForInterp; static bool runoutEna; static bool blockDataIsRunout; // Trapezoid data variables. static xyze_pos_t startPosn, // (mm) Start position of block endPosn_prevBlock; // (mm) End position of previous block static xyze_float_t ratio; // (ratio) Axis move ratio of block static float accel_P, decel_P, F_P, f_s, s_1e, s_2e; static uint32_t N1, N2, N3; static uint32_t max_intervals; static constexpr uint32_t PROP_BATCHES = CEIL(FTM_WINDOW_SIZE/FTM_BATCH_SIZE) - 1; // Number of batches needed to propagate the current trajectory to the stepper. #define _DIVCEIL(A,B) (((A) + (B) - 1) / (B)) static constexpr uint32_t _ftm_ratio = TERN(FTM_UNIFIED_BWS, 2, _DIVCEIL(FTM_WINDOW_SIZE, FTM_BATCH_SIZE)), shaper_intervals = (FTM_BATCH_SIZE) * _DIVCEIL(FTM_ZMAX, FTM_BATCH_SIZE), min_max_intervals = (FTM_BATCH_SIZE) * _ftm_ratio; // Make vector variables. static uint32_t makeVector_idx, makeVector_idx_z1, makeVector_batchIdx; // Interpolation variables. static uint32_t interpIdx, interpIdx_z1; static xyze_long_t steps; // Shaping variables. #if HAS_X_AXIS typedef struct AxisShaping { bool ena = false; // Enabled indication. float d_zi[FTM_ZMAX] = { 0.0f }; // Data point delay vector. float Ai[5]; // Shaping gain vector. uint32_t Ni[5]; // Shaping time index vector. void updateShapingN(const_float_t f, const_float_t df); } axis_shaping_t; typedef struct Shaping { uint32_t zi_idx, // Index of storage in the data point delay vectors. max_i; // Vector length for the selected shaper. axis_shaping_t x; #if HAS_Y_AXIS axis_shaping_t y; #endif void updateShapingA(float zeta[]=cfg.zeta, float vtol[]=cfg.vtol); } shaping_t; static shaping_t shaping; // Shaping data #endif // HAS_X_AXIS // Linear advance variables. #if HAS_EXTRUDERS static float e_raw_z1, e_advanced_z1; #endif // Private methods static int32_t stepperCmdBuffItems(); static void loadBlockData(block_t *const current_block); static void makeVector(); static void convertToSteps(const uint32_t idx); FORCE_INLINE static int32_t num_samples_cmpnstr_settle() { return ( shaping.x.ena || shaping.y.ena ) ? FTM_ZMAX : 0; } }; // class FTMotion extern FTMotion ftMotion;
2301_81045437/Marlin
Marlin/src/module/ft_motion.h
C++
agpl-3.0
8,402
/** * Marlin 3D Printer Firmware * Copyright (c) 2023 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #include "../core/types.h" typedef enum FXDTICtrlMode : uint8_t { ftMotionMode_DISABLED = 0, // Standard Motion ftMotionMode_ENABLED = 1, // Time-Based Motion ftMotionMode_ZV = 10, // Zero Vibration ftMotionMode_ZVD = 11, // Zero Vibration and Derivative ftMotionMode_ZVDD = 12, // Zero Vibration, Derivative, and Double Derivative ftMotionMode_ZVDDD = 13, // Zero Vibration, Derivative, Double Derivative, and Triple Derivative ftMotionMode_EI = 14, // Extra-Intensive ftMotionMode_2HEI = 15, // 2-Hump Extra-Intensive ftMotionMode_3HEI = 16, // 3-Hump Extra-Intensive ftMotionMode_MZV = 17 // Mass-based Zero Vibration } ftMotionMode_t; enum dynFreqMode_t : uint8_t { dynFreqMode_DISABLED = 0, dynFreqMode_Z_BASED = 1, dynFreqMode_MASS_BASED = 2 }; #define IS_EI_MODE(N) WITHIN(N, ftMotionMode_EI, ftMotionMode_3HEI) typedef struct XYZEarray<float, FTM_WINDOW_SIZE> xyze_trajectory_t; typedef struct XYZEarray<float, FTM_BATCH_SIZE> xyze_trajectoryMod_t; // TODO: Convert ft_command_t to a struct with bitfields instead of using a primitive type enum { FT_BIT_START, LIST_N(DOUBLE(LOGICAL_AXES), FT_BIT_DIR_E, FT_BIT_STEP_E, FT_BIT_DIR_X, FT_BIT_STEP_X, FT_BIT_DIR_Y, FT_BIT_STEP_Y, FT_BIT_DIR_Z, FT_BIT_STEP_Z, FT_BIT_DIR_I, FT_BIT_STEP_I, FT_BIT_DIR_J, FT_BIT_STEP_J, FT_BIT_DIR_K, FT_BIT_STEP_K, FT_BIT_DIR_U, FT_BIT_STEP_U, FT_BIT_DIR_V, FT_BIT_STEP_V, FT_BIT_DIR_W, FT_BIT_STEP_W ), FT_BIT_COUNT }; typedef bits_t(FT_BIT_COUNT) ft_command_t;
2301_81045437/Marlin
Marlin/src/module/ft_types.h
C
agpl-3.0
2,447
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * motion.cpp */ #include "motion.h" #include "endstops.h" #include "stepper.h" #include "planner.h" #include "temperature.h" #include "../gcode/gcode.h" #include "../lcd/marlinui.h" #include "../inc/MarlinConfig.h" #if IS_SCARA #include "../libs/buzzer.h" #include "../lcd/marlinui.h" #endif #if ENABLED(POLAR) #include "polar.h" #endif #if HAS_BED_PROBE #include "probe.h" #endif #if HAS_LEVELING #include "../feature/bedlevel/bedlevel.h" #endif #if ENABLED(BLTOUCH) #include "../feature/bltouch.h" #endif #if HAS_FILAMENT_SENSOR #include "../feature/runout.h" #endif #if ENABLED(SENSORLESS_HOMING) #include "../feature/tmc_util.h" #endif #if ENABLED(FWRETRACT) #include "../feature/fwretract.h" #endif #if ENABLED(BABYSTEP_DISPLAY_TOTAL) #include "../feature/babystep.h" #endif #define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) #include "../core/debug_out.h" #if ENABLED(BD_SENSOR) #include "../feature/bedlevel/bdl/bdl.h" #endif // Relative Mode. Enable with G91, disable with G90. bool relative_mode; // = false; /** * Cartesian Current Position * Used to track the native machine position as moves are queued. * Used by 'line_to_current_position' to do a move after changing it. * Used by 'sync_plan_position' to update 'planner.position'. */ #ifdef Z_IDLE_HEIGHT #define Z_INIT_POS Z_IDLE_HEIGHT #else #define Z_INIT_POS Z_HOME_POS #endif xyze_pos_t current_position = LOGICAL_AXIS_ARRAY(0, X_HOME_POS, Y_HOME_POS, Z_INIT_POS, I_HOME_POS, J_HOME_POS, K_HOME_POS, U_HOME_POS, V_HOME_POS, W_HOME_POS); /** * Cartesian Destination * The destination for a move, filled in by G-code movement commands, * and expected by functions like 'prepare_line_to_destination'. * G-codes can set destination using 'get_destination_from_command' */ xyze_pos_t destination; // {0} // G60/G61 Position Save and Return #if SAVED_POSITIONS uint8_t saved_slots[(SAVED_POSITIONS + 7) >> 3]; xyze_pos_t stored_position[SAVED_POSITIONS]; #endif // The active extruder (tool). Set with T<extruder> command. #if HAS_MULTI_EXTRUDER uint8_t active_extruder = 0; // = 0 #endif #if ENABLED(LCD_SHOW_E_TOTAL) float e_move_accumulator; // = 0 #endif // Extruder offsets #if HAS_HOTEND_OFFSET xyz_pos_t hotend_offset[HOTENDS]; // Initialized by settings.load() void reset_hotend_offsets() { constexpr float tmp[XYZ][HOTENDS] = { HOTEND_OFFSET_X, HOTEND_OFFSET_Y, HOTEND_OFFSET_Z }; static_assert( !tmp[X_AXIS][0] && !tmp[Y_AXIS][0] && !tmp[Z_AXIS][0], "Offsets for the first hotend must be 0.0." ); // Transpose from [XYZ][HOTENDS] to [HOTENDS][XYZ] HOTEND_LOOP() LOOP_ABC(a) hotend_offset[e][a] = tmp[a][e]; TERN_(DUAL_X_CARRIAGE, hotend_offset[1].x = _MAX(X2_HOME_POS, X2_MAX_POS)); } #endif // The feedrate for the current move, often used as the default if // no other feedrate is specified. Overridden for special moves. // Set by the last G0 through G5 command's "F" parameter. // Functions that override this for custom moves *must always* restore it! #ifndef DEFAULT_FEEDRATE_MM_M #define DEFAULT_FEEDRATE_MM_M 4000 #endif feedRate_t feedrate_mm_s = MMM_TO_MMS(DEFAULT_FEEDRATE_MM_M); int16_t feedrate_percentage = 100; // Cartesian conversion result goes here: xyz_pos_t cartes; #if IS_KINEMATIC abce_pos_t delta; #if HAS_SCARA_OFFSET abc_pos_t scara_home_offset; #endif #if HAS_SOFTWARE_ENDSTOPS float delta_max_radius, delta_max_radius_2; #elif IS_SCARA constexpr float delta_max_radius = PRINTABLE_RADIUS, delta_max_radius_2 = sq(PRINTABLE_RADIUS); #elif ENABLED(POLAR) constexpr float delta_max_radius = PRINTABLE_RADIUS, delta_max_radius_2 = sq(PRINTABLE_RADIUS); #else // DELTA constexpr float delta_max_radius = PRINTABLE_RADIUS, delta_max_radius_2 = sq(PRINTABLE_RADIUS); #endif #endif /** * The workspace can be offset by some commands, or * these offsets may be omitted to save on computation. */ #if HAS_HOME_OFFSET // This offset is added to the configured home position. // Set by M206, M428, or menu item. Saved to EEPROM. xyz_pos_t home_offset{0}; #endif #if HAS_WORKSPACE_OFFSET // The above two are combined to save on computes xyz_pos_t workspace_offset{0}; #endif #if HAS_ABL_NOT_UBL feedRate_t xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_FEEDRATE); #endif /** * Output the current position to serial */ inline void report_more_positions() { stepper.report_positions(); TERN_(IS_SCARA, scara_report_positions()); TERN_(POLAR, polar_report_positions()); } // Report the logical position for a given machine position inline void report_logical_position(const xyze_pos_t &rpos) { const xyze_pos_t lpos = rpos.asLogical(); #if NUM_AXES SERIAL_ECHOPGM_P( LIST_N(DOUBLE(NUM_AXES), X_LBL, lpos.x, SP_Y_LBL, lpos.y, SP_Z_LBL, lpos.z, SP_I_LBL, lpos.i, SP_J_LBL, lpos.j, SP_K_LBL, lpos.k, SP_U_LBL, lpos.u, SP_V_LBL, lpos.v, SP_W_LBL, lpos.w ) ); #endif #if HAS_EXTRUDERS SERIAL_ECHOPGM_P(SP_E_LBL, lpos.e); #endif } // Report the real current position according to the steppers. // Forward kinematics and un-leveling are applied. void report_real_position() { get_cartesian_from_steppers(); xyze_pos_t npos = LOGICAL_AXIS_ARRAY( planner.get_axis_position_mm(E_AXIS), cartes.x, cartes.y, cartes.z, cartes.i, cartes.j, cartes.k, cartes.u, cartes.v, cartes.w ); TERN_(HAS_POSITION_MODIFIERS, planner.unapply_modifiers(npos, true)); report_logical_position(npos); report_more_positions(); } // Report the logical current position according to the most recent G-code command void report_current_position() { report_logical_position(current_position); report_more_positions(); } /** * Report the logical current position according to the most recent G-code command. * The planner.position always corresponds to the last G-code too. This makes M114 * suitable for debugging kinematics and leveling while avoiding planner sync that * definitively interrupts the printing flow. */ void report_current_position_projected() { report_logical_position(current_position); stepper.report_a_position(planner.position); } #if ENABLED(AUTO_REPORT_POSITION) AutoReporter<PositionReport> position_auto_reporter; #endif #if ANY(FULL_REPORT_TO_HOST_FEATURE, REALTIME_REPORTING_COMMANDS) M_StateEnum M_State_grbl = M_INIT; /** * Output the current grbl compatible state to serial while moving */ void report_current_grblstate_moving() { SERIAL_ECHOLNPGM("S_XYZ:", int(M_State_grbl)); } /** * Output the current position (processed) to serial while moving */ void report_current_position_moving() { get_cartesian_from_steppers(); const xyz_pos_t lpos = cartes.asLogical(); SERIAL_ECHOPGM_P( LIST_N(DOUBLE(NUM_AXES), X_LBL, lpos.x, SP_Y_LBL, lpos.y, SP_Z_LBL, lpos.z, SP_I_LBL, lpos.i, SP_J_LBL, lpos.j, SP_K_LBL, lpos.k, SP_U_LBL, lpos.u, SP_V_LBL, lpos.v, SP_W_LBL, lpos.w ) #if HAS_EXTRUDERS , SP_E_LBL, current_position.e #endif ); report_more_positions(); report_current_grblstate_moving(); } /** * Set a Grbl-compatible state from the current marlin_state */ M_StateEnum grbl_state_for_marlin_state() { switch (marlin_state) { case MF_INITIALIZING: return M_INIT; case MF_SD_COMPLETE: return M_ALARM; case MF_WAITING: return M_IDLE; case MF_STOPPED: return M_END; case MF_RUNNING: return M_RUNNING; case MF_PAUSED: return M_HOLD; case MF_KILLED: return M_ERROR; default: return M_IDLE; } } #endif #if IS_KINEMATIC bool position_is_reachable(const_float_t rx, const_float_t ry, const float inset/*=0*/) { bool can_reach; #if ENABLED(DELTA) can_reach = HYPOT2(rx, ry) <= sq(PRINTABLE_RADIUS - inset + fslop); #elif ENABLED(AXEL_TPARA) const float R2 = HYPOT2(rx - TPARA_OFFSET_X, ry - TPARA_OFFSET_Y); can_reach = ( R2 <= sq(L1 + L2) - inset #if MIDDLE_DEAD_ZONE_R > 0 && R2 >= sq(float(MIDDLE_DEAD_ZONE_R)) #endif ); #elif IS_SCARA const float R2 = HYPOT2(rx - SCARA_OFFSET_X, ry - SCARA_OFFSET_Y); can_reach = ( R2 <= sq(L1 + L2) - inset #if MIDDLE_DEAD_ZONE_R > 0 && R2 >= sq(float(MIDDLE_DEAD_ZONE_R)) #endif ); #elif ENABLED(POLARGRAPH) const float d1 = rx - (draw_area_min.x), d2 = (draw_area_max.x) - rx, y = ry - (draw_area_max.y), a = HYPOT(d1, y), b = HYPOT(d2, y); can_reach = ( a < polargraph_max_belt_len + 1 && b < polargraph_max_belt_len + 1 ); #elif ENABLED(POLAR) can_reach = HYPOT(rx, ry) <= PRINTABLE_RADIUS; #endif return can_reach; } #else // CARTESIAN // Return true if the given position is within the machine bounds. bool position_is_reachable(TERN_(HAS_X_AXIS, const_float_t rx) OPTARG(HAS_Y_AXIS, const_float_t ry)) { if (TERN0(HAS_Y_AXIS, !COORDINATE_OKAY(ry, Y_MIN_POS - fslop, Y_MAX_POS + fslop))) return false; #if ENABLED(DUAL_X_CARRIAGE) if (active_extruder) return COORDINATE_OKAY(rx, X2_MIN_POS - fslop, X2_MAX_POS + fslop); else return COORDINATE_OKAY(rx, X1_MIN_POS - fslop, X1_MAX_POS + fslop); #else if (TERN0(HAS_X_AXIS, !COORDINATE_OKAY(rx, X_MIN_POS - fslop, X_MAX_POS + fslop))) return false; return true; #endif } #endif // CARTESIAN void home_if_needed(const bool keeplev/*=false*/) { if (!all_axes_trusted()) gcode.home_all_axes(keeplev); } /** * Run out the planner buffer and re-sync the current * position from the last-updated stepper positions. */ void quickstop_stepper() { planner.quick_stop(); planner.synchronize(); set_current_from_steppers_for_axis(ALL_AXES_ENUM); sync_plan_position(); } #if ENABLED(REALTIME_REPORTING_COMMANDS) void quickpause_stepper() { planner.quick_pause(); //planner.synchronize(); } void quickresume_stepper() { planner.quick_resume(); //planner.synchronize(); } #endif /** * Set the planner/stepper positions directly from current_position with * no kinematic translation. Used for homing axes and cartesian/core syncing. */ void sync_plan_position() { if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position); planner.set_position_mm(current_position); } #if HAS_EXTRUDERS void sync_plan_position_e() { planner.set_e_position_mm(current_position.e); } #endif /** * Get the stepper positions in the cartes[] array. * Forward kinematics are applied for DELTA and SCARA. * * The result is in the current coordinate space with * leveling applied. The coordinates need to be run through * unapply_leveling to obtain the "ideal" coordinates * suitable for current_position, etc. */ void get_cartesian_from_steppers() { #if ENABLED(DELTA) forward_kinematics(planner.get_axis_positions_mm()); #elif IS_SCARA forward_kinematics( planner.get_axis_position_degrees(A_AXIS), planner.get_axis_position_degrees(B_AXIS) OPTARG(AXEL_TPARA, planner.get_axis_position_degrees(C_AXIS)) ); cartes.z = planner.get_axis_position_mm(Z_AXIS); #elif ENABLED(POLAR) forward_kinematics(planner.get_axis_position_mm(X_AXIS), planner.get_axis_position_degrees(B_AXIS)); cartes.z = planner.get_axis_position_mm(Z_AXIS); #else NUM_AXIS_CODE( cartes.x = planner.get_axis_position_mm(X_AXIS), cartes.y = planner.get_axis_position_mm(Y_AXIS), cartes.z = planner.get_axis_position_mm(Z_AXIS), cartes.i = planner.get_axis_position_mm(I_AXIS), cartes.j = planner.get_axis_position_mm(J_AXIS), cartes.k = planner.get_axis_position_mm(K_AXIS), cartes.u = planner.get_axis_position_mm(U_AXIS), cartes.v = planner.get_axis_position_mm(V_AXIS), cartes.w = planner.get_axis_position_mm(W_AXIS) ); #endif } /** * Set the current_position for an axis based on * the stepper positions, removing any leveling that * may have been applied. * * To prevent small shifts in axis position always call * sync_plan_position after updating axes with this. * * To keep hosts in sync, always call report_current_position * after updating the current_position. */ void set_current_from_steppers_for_axis(const AxisEnum axis) { get_cartesian_from_steppers(); xyze_pos_t pos = cartes; TERN_(HAS_EXTRUDERS, pos.e = planner.get_axis_position_mm(E_AXIS)); TERN_(HAS_POSITION_MODIFIERS, planner.unapply_modifiers(pos, true)); if (axis == ALL_AXES_ENUM) current_position = pos; else current_position[axis] = pos[axis]; } /** * Move the planner to the current position from wherever it last moved * (or from wherever it has been told it is located). */ void line_to_current_position(const_feedRate_t fr_mm_s/*=feedrate_mm_s*/) { planner.buffer_line(current_position, fr_mm_s); } #if HAS_EXTRUDERS void unscaled_e_move(const_float_t length, const_feedRate_t fr_mm_s) { TERN_(HAS_FILAMENT_SENSOR, runout.reset()); current_position.e += length / planner.e_factor[active_extruder]; line_to_current_position(fr_mm_s); planner.synchronize(); } #endif #if IS_KINEMATIC /** * Buffer a fast move without interpolation. Set current_position to destination */ void prepare_fast_move_to_destination(const_feedRate_t scaled_fr_mm_s/*=MMS_SCALED(feedrate_mm_s)*/) { if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_fast_move_to_destination", destination); #if UBL_SEGMENTED // UBL segmented line will do Z-only moves in single segment bedlevel.line_to_destination_segmented(scaled_fr_mm_s); #else if (current_position == destination) return; planner.buffer_line(destination, scaled_fr_mm_s); #endif current_position = destination; } #endif // IS_KINEMATIC /** * Do a fast or normal move to 'destination' with an optional FR. * - Move at normal speed regardless of feedrate percentage. * - Extrude the specified length regardless of flow percentage. */ void _internal_move_to_destination(const_feedRate_t fr_mm_s/*=0.0f*/ OPTARG(IS_KINEMATIC, const bool is_fast/*=false*/) ) { REMEMBER(fr, feedrate_mm_s); REMEMBER(pct, feedrate_percentage, 100); TERN_(HAS_EXTRUDERS, REMEMBER(fac, planner.e_factor[active_extruder], 1.0f)); if (fr_mm_s) feedrate_mm_s = fr_mm_s; if (TERN0(IS_KINEMATIC, is_fast)) TERN(IS_KINEMATIC, prepare_fast_move_to_destination(), NOOP); else prepare_line_to_destination(); } #if SECONDARY_AXES void secondary_axis_moves(SECONDARY_AXIS_ARGS(const_float_t), const_feedRate_t fr_mm_s) { auto move_one = [&](const AxisEnum a, const_float_t p) { const feedRate_t fr = fr_mm_s ?: homing_feedrate(a); current_position[a] = p; line_to_current_position(fr); }; SECONDARY_AXIS_CODE( move_one(I_AXIS, i), move_one(J_AXIS, j), move_one(K_AXIS, k), move_one(U_AXIS, u), move_one(V_AXIS, v), move_one(W_AXIS, w) ); } #endif /** * Plan a move to (X, Y, Z, [I, [J, [K...]]]) and set the current_position * Plan a move to (X, Y, Z, [I, [J, [K...]]]) with separation of Z from other components. * * - If Z is moving up, the Z move is done before XY, etc. * - If Z is moving down, the Z move is done after XY, etc. * - Delta may lower Z first to get into the free motion zone. * - Before returning, wait for the planner buffer to empty. */ void do_blocking_move_to(NUM_AXIS_ARGS_(const_float_t) const_feedRate_t fr_mm_s/*=0.0f*/) { DEBUG_SECTION(log_move, "do_blocking_move_to", DEBUGGING(LEVELING)); #if NUM_AXES if (DEBUGGING(LEVELING)) DEBUG_XYZ("> ", NUM_AXIS_ARGS()); #endif const feedRate_t xy_feedrate = fr_mm_s ?: feedRate_t(XY_PROBE_FEEDRATE_MM_S); #if HAS_Z_AXIS const feedRate_t z_feedrate = fr_mm_s ?: homing_feedrate(Z_AXIS); #endif #if IS_KINEMATIC && DISABLED(POLARGRAPH) // kinematic machines are expected to home to a point 1.5x their range? never reachable. if (!position_is_reachable(x, y)) return; destination = current_position; // sync destination at the start #endif #if ENABLED(DELTA) REMEMBER(fr, feedrate_mm_s, xy_feedrate); if (DEBUGGING(LEVELING)) DEBUG_POS("destination = current_position", destination); // when in the danger zone if (current_position.z > delta_clip_start_height) { if (z > delta_clip_start_height) { // staying in the danger zone destination.set(x, y, z); // move directly (uninterpolated) prepare_internal_fast_move_to_destination(); // set current_position from destination if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position); return; } destination.z = delta_clip_start_height; prepare_internal_fast_move_to_destination(); // set current_position from destination if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position); } if (z > current_position.z) { // raising? destination.z = z; prepare_internal_fast_move_to_destination(z_feedrate); // set current_position from destination if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position); } destination.set(x, y); prepare_internal_move_to_destination(); // set current_position from destination if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position); if (z < current_position.z) { // lowering? destination.z = z; prepare_internal_fast_move_to_destination(z_feedrate); // set current_position from destination if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position); } #if SECONDARY_AXES secondary_axis_moves(SECONDARY_AXIS_LIST(i, j, k, u, v, w), fr_mm_s); #endif #elif IS_SCARA // If Z needs to raise, do it before moving XY if (destination.z < z) { destination.z = z; prepare_internal_fast_move_to_destination(z_feedrate); } destination.set(x, y); prepare_internal_fast_move_to_destination(xy_feedrate); #if SECONDARY_AXES secondary_axis_moves(SECONDARY_AXIS_LIST(i, j, k, u, v, w), fr_mm_s); #endif // If Z needs to lower, do it after moving XY if (destination.z > z) { destination.z = z; prepare_internal_fast_move_to_destination(z_feedrate); } #else #if HAS_Z_AXIS // If Z needs to raise, do it before moving XY if (current_position.z < z) { current_position.z = z; line_to_current_position(z_feedrate); } #endif current_position.set(TERN_(HAS_X_AXIS, x) OPTARG(HAS_Y_AXIS, y)); line_to_current_position(xy_feedrate); #if SECONDARY_AXES secondary_axis_moves(SECONDARY_AXIS_LIST(i, j, k, u, v, w), fr_mm_s); #endif #if HAS_Z_AXIS // If Z needs to lower, do it after moving XY if (current_position.z > z) { current_position.z = z; line_to_current_position(z_feedrate); } #endif #endif planner.synchronize(); } void do_blocking_move_to(const xy_pos_t &raw, const_feedRate_t fr_mm_s/*=0.0f*/) { do_blocking_move_to(NUM_AXIS_LIST_(raw.x, raw.y, current_position.z, current_position.i, current_position.j, current_position.k, current_position.u, current_position.v, current_position.w) fr_mm_s); } void do_blocking_move_to(const xyz_pos_t &raw, const_feedRate_t fr_mm_s/*=0.0f*/) { do_blocking_move_to(NUM_AXIS_ELEM_(raw) fr_mm_s); } void do_blocking_move_to(const xyze_pos_t &raw, const_feedRate_t fr_mm_s/*=0.0f*/) { do_blocking_move_to(NUM_AXIS_ELEM_(raw) fr_mm_s); } #if HAS_X_AXIS void do_blocking_move_to_x(const_float_t rx, const_feedRate_t fr_mm_s/*=0.0*/) { if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("do_blocking_move_to_x(", rx, ", ", fr_mm_s, ")"); do_blocking_move_to( NUM_AXIS_LIST_(rx, current_position.y, current_position.z, current_position.i, current_position.j, current_position.k, current_position.u, current_position.v, current_position.w) fr_mm_s ); } #endif #if HAS_Y_AXIS void do_blocking_move_to_y(const_float_t ry, const_feedRate_t fr_mm_s/*=0.0*/) { if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("do_blocking_move_to_y(", ry, ", ", fr_mm_s, ")"); do_blocking_move_to( NUM_AXIS_LIST_(current_position.x, ry, current_position.z, current_position.i, current_position.j, current_position.k, current_position.u, current_position.v, current_position.w) fr_mm_s ); } void do_blocking_move_to_xy(const_float_t rx, const_float_t ry, const_feedRate_t fr_mm_s/*=0.0*/) { if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("do_blocking_move_to_xy(", rx, ", ", ry, ", ", fr_mm_s, ")"); do_blocking_move_to( NUM_AXIS_LIST_(rx, ry, current_position.z, current_position.i, current_position.j, current_position.k, current_position.u, current_position.v, current_position.w) fr_mm_s ); } void do_blocking_move_to_xy(const xy_pos_t &raw, const_feedRate_t fr_mm_s/*=0.0f*/) { do_blocking_move_to_xy(raw.x, raw.y, fr_mm_s); } #endif #if HAS_Z_AXIS void do_blocking_move_to_z(const_float_t rz, const_feedRate_t fr_mm_s/*=0.0*/) { if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("do_blocking_move_to_z(", rz, ", ", fr_mm_s, ")"); do_blocking_move_to_xy_z(current_position, rz, fr_mm_s); } void do_blocking_move_to_xy_z(const xy_pos_t &raw, const_float_t z, const_feedRate_t fr_mm_s/*=0.0f*/) { do_blocking_move_to( NUM_AXIS_LIST_(raw.x, raw.y, z, current_position.i, current_position.j, current_position.k, current_position.u, current_position.v, current_position.w) fr_mm_s ); } void do_z_clearance(const_float_t zclear, const bool with_probe/*=true*/, const bool lower_allowed/*=false*/) { UNUSED(with_probe); float zdest = zclear; TERN_(HAS_BED_PROBE, if (with_probe && probe.offset.z < 0) zdest -= probe.offset.z); NOMORE(zdest, Z_MAX_POS); if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("do_z_clearance(", zclear, " [", current_position.z, " to ", zdest, "], ", lower_allowed, ")"); if ((!lower_allowed && zdest < current_position.z) || zdest == current_position.z) return; do_blocking_move_to_z(zdest, TERN(HAS_BED_PROBE, z_probe_fast_mm_s, homing_feedrate(Z_AXIS))); } void do_z_clearance_by(const_float_t zclear) { if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("do_z_clearance_by(", zclear, ")"); do_z_clearance(current_position.z + zclear, false); } void do_move_after_z_homing() { DEBUG_SECTION(mzah, "do_move_after_z_homing", DEBUGGING(LEVELING)); #if defined(Z_AFTER_HOMING) || ALL(DWIN_LCD_PROUI, INDIVIDUAL_AXIS_HOMING_SUBMENU, MESH_BED_LEVELING) do_z_clearance(Z_POST_CLEARANCE, true, true); #elif ENABLED(USE_PROBE_FOR_Z_HOMING) probe.move_z_after_probing(); #endif } #endif #if HAS_I_AXIS void do_blocking_move_to_xyz_i(const xyze_pos_t &raw, const_float_t i, const_feedRate_t fr_mm_s/*=0.0f*/) { do_blocking_move_to( NUM_AXIS_LIST_(raw.x, raw.y, raw.z, i, raw.j, raw.k, raw.u, raw.v, raw.w) fr_mm_s ); } void do_blocking_move_to_i(const_float_t ri, const_feedRate_t fr_mm_s/*=0.0*/) { do_blocking_move_to_xyz_i(current_position, ri, fr_mm_s); } #endif #if HAS_J_AXIS void do_blocking_move_to_xyzi_j(const xyze_pos_t &raw, const_float_t j, const_feedRate_t fr_mm_s/*=0.0f*/) { do_blocking_move_to( NUM_AXIS_LIST_(raw.x, raw.y, raw.z, raw.i, j, raw.k, raw.u, raw.v, raw.w) fr_mm_s ); } void do_blocking_move_to_j(const_float_t rj, const_feedRate_t fr_mm_s/*=0.0*/) { do_blocking_move_to_xyzi_j(current_position, rj, fr_mm_s); } #endif #if HAS_K_AXIS void do_blocking_move_to_xyzij_k(const xyze_pos_t &raw, const_float_t k, const_feedRate_t fr_mm_s/*=0.0f*/) { do_blocking_move_to( NUM_AXIS_LIST_(raw.x, raw.y, raw.z, raw.i, raw.j, k, raw.u, raw.v, raw.w) fr_mm_s ); } void do_blocking_move_to_k(const_float_t rk, const_feedRate_t fr_mm_s/*=0.0*/) { do_blocking_move_to_xyzij_k(current_position, rk, fr_mm_s); } #endif #if HAS_U_AXIS void do_blocking_move_to_xyzijk_u(const xyze_pos_t &raw, const_float_t u, const_feedRate_t fr_mm_s/*=0.0f*/) { do_blocking_move_to( NUM_AXIS_LIST_(raw.x, raw.y, raw.z, raw.i, raw.j, raw.k, u, raw.v, raw.w) fr_mm_s ); } void do_blocking_move_to_u(const_float_t ru, const_feedRate_t fr_mm_s/*=0.0*/) { do_blocking_move_to_xyzijk_u(current_position, ru, fr_mm_s); } #endif #if HAS_V_AXIS void do_blocking_move_to_xyzijku_v(const xyze_pos_t &raw, const_float_t v, const_feedRate_t fr_mm_s/*=0.0f*/) { do_blocking_move_to( NUM_AXIS_LIST_(raw.x, raw.y, raw.z, raw.i, raw.j, raw.k, raw.u, v, raw.w) fr_mm_s ); } void do_blocking_move_to_v(const_float_t rv, const_feedRate_t fr_mm_s/*=0.0*/) { do_blocking_move_to_xyzijku_v(current_position, rv, fr_mm_s); } #endif #if HAS_W_AXIS void do_blocking_move_to_xyzijkuv_w(const xyze_pos_t &raw, const_float_t w, const_feedRate_t fr_mm_s/*=0.0f*/) { do_blocking_move_to( NUM_AXIS_LIST_(raw.x, raw.y, raw.z, raw.i, raw.j, raw.k, raw.u, raw.v, w) fr_mm_s ); } void do_blocking_move_to_w(const_float_t rw, const_feedRate_t fr_mm_s/*=0.0*/) { do_blocking_move_to_xyzijkuv_w(current_position, rw, fr_mm_s); } #endif // // Prepare to do endstop or probe moves with custom feedrates. // - Save / restore current feedrate and multiplier // static float saved_feedrate_mm_s; static int16_t saved_feedrate_percentage; void remember_feedrate_scaling_off() { if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("remember_feedrate_scaling_off: fr=", feedrate_mm_s, " ", feedrate_percentage, "%"); saved_feedrate_mm_s = feedrate_mm_s; saved_feedrate_percentage = feedrate_percentage; feedrate_percentage = 100; } void restore_feedrate_and_scaling() { feedrate_mm_s = saved_feedrate_mm_s; feedrate_percentage = saved_feedrate_percentage; if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("restore_feedrate_and_scaling: fr=", feedrate_mm_s, " ", feedrate_percentage, "%"); } #if HAS_SOFTWARE_ENDSTOPS // Software Endstops are based on the configured limits. #define _AMIN(A) A##_MIN_POS #define _AMAX(A) A##_MAX_POS soft_endstops_t soft_endstop = { true, false, { MAPLIST(_AMIN, MAIN_AXIS_NAMES) }, { MAPLIST(_AMAX, MAIN_AXIS_NAMES) }, }; /** * Software endstops can be used to monitor the open end of * an axis that has a hardware endstop on the other end. Or * they can prevent axes from moving past endstops and grinding. * * To keep doing their job as the coordinate system changes, * the software endstop positions must be refreshed to remain * at the same positions relative to the machine. */ void update_software_endstops(const AxisEnum axis OPTARG(HAS_HOTEND_OFFSET, const uint8_t old_tool_index/*=0*/, const uint8_t new_tool_index/*=0*/) ) { #if ENABLED(DUAL_X_CARRIAGE) if (axis == X_AXIS) { // In Dual X mode hotend_offset[X] is T1's home position const float dual_max_x = _MAX(hotend_offset[1].x, X2_MAX_POS); if (new_tool_index != 0) { // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger) soft_endstop.min.x = X2_MIN_POS; soft_endstop.max.x = dual_max_x; } else if (idex_is_duplicating()) { // In Duplication Mode, T0 can move as far left as X1_MIN_POS // but not so far to the right that T1 would move past the end soft_endstop.min.x = X1_MIN_POS; soft_endstop.max.x = _MIN(X1_MAX_POS, dual_max_x - duplicate_extruder_x_offset); } else { // In other modes, T0 can move from X1_MIN_POS to X1_MAX_POS soft_endstop.min.x = X1_MIN_POS; soft_endstop.max.x = X1_MAX_POS; } } #elif ENABLED(DELTA) soft_endstop.min[axis] = base_min_pos(axis); soft_endstop.max[axis] = (axis == Z_AXIS) ? DIFF_TERN(USE_PROBE_FOR_Z_HOMING, delta_height, probe.offset.z) : base_home_pos(axis); switch (axis) { case X_AXIS: case Y_AXIS: // Get a minimum radius for clamping delta_max_radius = _MIN(ABS(_MAX(soft_endstop.min.x, soft_endstop.min.y)), soft_endstop.max.x, soft_endstop.max.y); delta_max_radius_2 = sq(delta_max_radius); break; case Z_AXIS: refresh_delta_clip_start_height(); default: break; } #elif HAS_HOTEND_OFFSET // Software endstops are relative to the tool 0 workspace, so // the movement limits must be shifted by the tool offset to // retain the same physical limit when other tools are selected. if (new_tool_index == old_tool_index || axis == Z_AXIS) { // The Z axis is "special" and shouldn't be modified const float offs = (axis == Z_AXIS) ? 0 : hotend_offset[active_extruder][axis]; soft_endstop.min[axis] = base_min_pos(axis) + offs; soft_endstop.max[axis] = base_max_pos(axis) + offs; } else { const float diff = hotend_offset[new_tool_index][axis] - hotend_offset[old_tool_index][axis]; soft_endstop.min[axis] += diff; soft_endstop.max[axis] += diff; } #else soft_endstop.min[axis] = base_min_pos(axis); soft_endstop.max[axis] = base_max_pos(axis); #endif if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Axis ", C(AXIS_CHAR(axis)), " min:", soft_endstop.min[axis], " max:", soft_endstop.max[axis]); } /** * Constrain the given coordinates to the software endstops. * * For DELTA/SCARA the XY constraint is based on the smallest * radius within the set software endstops. */ void apply_motion_limits(xyz_pos_t &target) { if (!soft_endstop._enabled) return; #if IS_KINEMATIC if (TERN0(DELTA, !all_axes_homed())) return; #if ALL(HAS_HOTEND_OFFSET, DELTA) // The effector center position will be the target minus the hotend offset. const xy_pos_t offs = hotend_offset[active_extruder]; #elif ENABLED(POLARGRAPH) // POLARGRAPH uses draw_area_* below... #elif ENABLED(POLAR) // For now, we don't limit POLAR #else // SCARA needs to consider the angle of the arm through the entire move, so for now use no tool offset. constexpr xy_pos_t offs{0}; #endif #if ENABLED(POLARGRAPH) LIMIT(target.x, draw_area_min.x, draw_area_max.x); LIMIT(target.y, draw_area_min.y, draw_area_max.y); #elif ENABLED(POLAR) // Motion limits are as same as cartesian limits. #else if (TERN1(IS_SCARA, axis_was_homed(X_AXIS) && axis_was_homed(Y_AXIS))) { const float dist_2 = HYPOT2(target.x - offs.x, target.y - offs.y); if (dist_2 > delta_max_radius_2) target *= float(delta_max_radius / SQRT(dist_2)); // 200 / 300 = 0.66 } #endif #else #if HAS_X_AXIS if (axis_was_homed(X_AXIS)) { #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MIN_SOFTWARE_ENDSTOP_X) NOLESS(target.x, soft_endstop.min.x); #endif #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MAX_SOFTWARE_ENDSTOP_X) NOMORE(target.x, soft_endstop.max.x); #endif } #endif #if HAS_Y_AXIS if (axis_was_homed(Y_AXIS)) { #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MIN_SOFTWARE_ENDSTOP_Y) NOLESS(target.y, soft_endstop.min.y); #endif #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MAX_SOFTWARE_ENDSTOP_Y) NOMORE(target.y, soft_endstop.max.y); #endif } #endif #endif #if HAS_Z_AXIS if (axis_was_homed(Z_AXIS)) { #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MIN_SOFTWARE_ENDSTOP_Z) NOLESS(target.z, soft_endstop.min.z); #endif #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MAX_SOFTWARE_ENDSTOP_Z) NOMORE(target.z, soft_endstop.max.z); #endif } #endif #if HAS_I_AXIS if (axis_was_homed(I_AXIS)) { #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MIN_SOFTWARE_ENDSTOP_I) NOLESS(target.i, soft_endstop.min.i); #endif #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MAX_SOFTWARE_ENDSTOP_I) NOMORE(target.i, soft_endstop.max.i); #endif } #endif #if HAS_J_AXIS if (axis_was_homed(J_AXIS)) { #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MIN_SOFTWARE_ENDSTOP_J) NOLESS(target.j, soft_endstop.min.j); #endif #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MAX_SOFTWARE_ENDSTOP_J) NOMORE(target.j, soft_endstop.max.j); #endif } #endif #if HAS_K_AXIS if (axis_was_homed(K_AXIS)) { #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MIN_SOFTWARE_ENDSTOP_K) NOLESS(target.k, soft_endstop.min.k); #endif #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MAX_SOFTWARE_ENDSTOP_K) NOMORE(target.k, soft_endstop.max.k); #endif } #endif #if HAS_U_AXIS if (axis_was_homed(U_AXIS)) { #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MIN_SOFTWARE_ENDSTOP_U) NOLESS(target.u, soft_endstop.min.u); #endif #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MAX_SOFTWARE_ENDSTOP_U) NOMORE(target.u, soft_endstop.max.u); #endif } #endif #if HAS_V_AXIS if (axis_was_homed(V_AXIS)) { #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MIN_SOFTWARE_ENDSTOP_V) NOLESS(target.v, soft_endstop.min.v); #endif #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MAX_SOFTWARE_ENDSTOP_V) NOMORE(target.v, soft_endstop.max.v); #endif } #endif #if HAS_W_AXIS if (axis_was_homed(W_AXIS)) { #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MIN_SOFTWARE_ENDSTOP_W) NOLESS(target.w, soft_endstop.min.w); #endif #if !HAS_SOFTWARE_ENDSTOPS || ENABLED(MAX_SOFTWARE_ENDSTOP_W) NOMORE(target.w, soft_endstop.max.w); #endif } #endif } #else // !HAS_SOFTWARE_ENDSTOPS soft_endstops_t soft_endstop; #endif // !HAS_SOFTWARE_ENDSTOPS FORCE_INLINE void segment_idle(millis_t &next_idle_ms) { const millis_t ms = millis(); if (ELAPSED(ms, next_idle_ms)) { next_idle_ms = ms + 200UL; return idle(); } thermalManager.task(); // Returns immediately on most calls } /** * Get distance from displacements along axes and, if required, update move type. */ float get_move_distance(const xyze_pos_t &diff OPTARG(HAS_ROTATIONAL_AXES, bool &is_cartesian_move)) { #if NUM_AXES if (!(NUM_AXIS_GANG(diff.x, || diff.y, /* skip z */, || diff.i, || diff.j, || diff.k, || diff.u, || diff.v, || diff.w))) return TERN0(HAS_Z_AXIS, ABS(diff.z)); #if ENABLED(ARTICULATED_ROBOT_ARM) // For articulated robots, interpreting feedrate like LinuxCNC would require inverse kinematics. As a workaround, pretend that motors sit on n mutually orthogonal // axes and assume that we could think of distance as magnitude of an n-vector in an n-dimensional Euclidian space. const float distance_sqr = NUM_AXIS_GANG( sq(diff.x), + sq(diff.y), + sq(diff.z), + sq(diff.i), + sq(diff.j), + sq(diff.k), + sq(diff.u), + sq(diff.v), + sq(diff.w) ); #elif ENABLED(FOAMCUTTER_XYUV) const float distance_sqr = ( #if HAS_J_AXIS _MAX(sq(diff.x) + sq(diff.y), sq(diff.i) + sq(diff.j)) // Special 5 axis kinematics. Return the larger of plane X/Y or I/J #else sq(diff.x) + sq(diff.y) // Foamcutter with only two axes (XY) #endif ); #else /** * Calculate distance for feedrate interpretation in accordance with NIST RS274NGC interpreter - version 3) and its default CANON_XYZ feed reference mode. * Assume: * - X, Y, Z are the primary linear axes; * - U, V, W are secondary linear axes; * - A, B, C are rotational axes. * * Then: * - dX, dY, dZ are the displacements of the primary linear axes; * - dU, dV, dW are the displacements of linear axes; * - dA, dB, dC are the displacements of rotational axes. * * The time it takes to execute a move command with feedrate F is t = D/F, * plus any time for acceleration and deceleration. * Here, D is the total distance, calculated as follows: * * D^2 = dX^2 + dY^2 + dZ^2 * if D^2 == 0 (none of XYZ move but any secondary linear axes move, whether other axes are moved or not): * D^2 = dU^2 + dV^2 + dW^2 * if D^2 == 0 (only rotational axes are moved): * D^2 = dA^2 + dB^2 + dC^2 */ float distance_sqr = XYZ_GANG(sq(diff.x), + sq(diff.y), + sq(diff.z)); #if SECONDARY_LINEAR_AXES if (UNEAR_ZERO(distance_sqr)) { // Move does not involve any primary linear axes (xyz) but might involve secondary linear axes distance_sqr = ( SECONDARY_AXIS_GANG( IF_DISABLED(AXIS4_ROTATES, + sq(diff.i)), IF_DISABLED(AXIS5_ROTATES, + sq(diff.j)), IF_DISABLED(AXIS6_ROTATES, + sq(diff.k)), IF_DISABLED(AXIS7_ROTATES, + sq(diff.u)), IF_DISABLED(AXIS8_ROTATES, + sq(diff.v)), IF_DISABLED(AXIS9_ROTATES, + sq(diff.w)) ) ); } #endif #if HAS_ROTATIONAL_AXES if (UNEAR_ZERO(distance_sqr)) { // Move involves no linear axes. Calculate angular distance in accordance with LinuxCNC distance_sqr = ROTATIONAL_AXIS_GANG(sq(diff.i), + sq(diff.j), + sq(diff.k), + sq(diff.u), + sq(diff.v), + sq(diff.w)); } if (!UNEAR_ZERO(distance_sqr)) { // Move involves rotational axes, not just the extruder is_cartesian_move = false; } #endif #endif return SQRT(distance_sqr); #else return 0; #endif } #if IS_KINEMATIC #if IS_SCARA /** * Before raising this value, use M665 S[seg_per_sec] to decrease * the number of segments-per-second. Default is 200. Some deltas * do better with 160 or lower. It would be good to know how many * segments-per-second are actually possible for SCARA on AVR. * * Longer segments result in less kinematic overhead * but may produce jagged lines. Try 0.5mm, 1.0mm, and 2.0mm * and compare the difference. */ #define SCARA_MIN_SEGMENT_LENGTH 0.5f #elif ENABLED(POLAR) #define POLAR_MIN_SEGMENT_LENGTH 0.5f #endif /** * Prepare a linear move in a DELTA or SCARA setup. * * Called from prepare_line_to_destination as the * default Delta/SCARA segmenter. * * This calls planner.buffer_line several times, adding * small incremental moves for DELTA or SCARA. * * For Unified Bed Leveling (Delta or Segmented Cartesian) * the bedlevel.line_to_destination_segmented method replaces this. * * For Auto Bed Leveling (Bilinear) with SEGMENT_LEVELED_MOVES * this is replaced by segmented_line_to_destination below. */ inline bool line_to_destination_kinematic() { // Get the top feedrate of the move in the XY plane const float scaled_fr_mm_s = MMS_SCALED(feedrate_mm_s); const xyze_float_t diff = destination - current_position; // If the move is only in Z/E don't split up the move if (!diff.x && !diff.y) { planner.buffer_line(destination, scaled_fr_mm_s); return false; // caller will update current_position } // Fail if attempting move outside printable radius if (!position_is_reachable(destination)) return true; // Get the linear distance in XYZ #if HAS_ROTATIONAL_AXES bool cartes_move = true; #endif float cartesian_mm = get_move_distance(diff OPTARG(HAS_ROTATIONAL_AXES, cartes_move)); // If the move is very short, check the E move distance TERN_(HAS_EXTRUDERS, if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = ABS(diff.e)); // No E move either? Game over. if (UNEAR_ZERO(cartesian_mm)) return true; // Minimum number of seconds to move the given distance const float seconds = cartesian_mm / ( #if ALL(HAS_ROTATIONAL_AXES, INCH_MODE_SUPPORT) cartes_move ? scaled_fr_mm_s : LINEAR_UNIT(scaled_fr_mm_s) #else scaled_fr_mm_s #endif ); // The number of segments-per-second times the duration // gives the number of segments uint16_t segments = segments_per_second * seconds; // For SCARA enforce a minimum segment size #if IS_SCARA NOMORE(segments, cartesian_mm * RECIPROCAL(SCARA_MIN_SEGMENT_LENGTH)); #elif ENABLED(POLAR) NOMORE(segments, cartesian_mm * RECIPROCAL(POLAR_MIN_SEGMENT_LENGTH)); #endif // At least one segment is required NOLESS(segments, 1U); // The approximate length of each segment const float inv_segments = 1.0f / float(segments); const xyze_float_t segment_distance = diff * inv_segments; // Add hints to help optimize the move PlannerHints hints(cartesian_mm * inv_segments); TERN_(HAS_ROTATIONAL_AXES, hints.cartesian_move = cartes_move); TERN_(FEEDRATE_SCALING, hints.inv_duration = scaled_fr_mm_s / hints.millimeters); /* SERIAL_ECHOPGM("mm=", cartesian_mm); SERIAL_ECHOPGM(" seconds=", seconds); SERIAL_ECHOPGM(" segments=", segments); SERIAL_ECHOPGM(" segment_mm=", hints.millimeters); SERIAL_EOL(); //*/ // Get the current position as starting point xyze_pos_t raw = current_position; // Calculate and execute the segments millis_t next_idle_ms = millis() + 200UL; while (--segments) { segment_idle(next_idle_ms); raw += segment_distance; if (!planner.buffer_line(raw, scaled_fr_mm_s, active_extruder, hints)) break; } // Ensure last segment arrives at target location. planner.buffer_line(destination, scaled_fr_mm_s, active_extruder, hints); return false; // caller will update current_position } #else // !IS_KINEMATIC #if ENABLED(SEGMENT_LEVELED_MOVES) && DISABLED(AUTO_BED_LEVELING_UBL) /** * Prepare a segmented move on a CARTESIAN setup. * * This calls planner.buffer_line several times, adding * small incremental moves. This allows the planner to * apply more detailed bed leveling to the full move. */ inline void segmented_line_to_destination(const_feedRate_t fr_mm_s, const float segment_size=LEVELED_SEGMENT_LENGTH) { const xyze_float_t diff = destination - current_position; // If the move is only in Z/E don't split up the move if (!diff.x && !diff.y) { planner.buffer_line(destination, fr_mm_s); return; } // Get the linear distance in XYZ #if HAS_ROTATIONAL_AXES bool cartes_move = true; #endif float cartesian_mm = get_move_distance(diff OPTARG(HAS_ROTATIONAL_AXES, cartes_move)); // If the move is very short, check the E move distance TERN_(HAS_EXTRUDERS, if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = ABS(diff.e)); // No E move either? Game over. if (UNEAR_ZERO(cartesian_mm)) return; // The length divided by the segment size // At least one segment is required uint16_t segments = cartesian_mm / segment_size; NOLESS(segments, 1U); // The approximate length of each segment const float inv_segments = 1.0f / float(segments); const xyze_float_t segment_distance = diff * inv_segments; // Add hints to help optimize the move PlannerHints hints(cartesian_mm * inv_segments); TERN_(HAS_ROTATIONAL_AXES, hints.cartesian_move = cartes_move); TERN_(FEEDRATE_SCALING, hints.inv_duration = scaled_fr_mm_s / hints.millimeters); //SERIAL_ECHOPGM("mm=", cartesian_mm); //SERIAL_ECHOLNPGM(" segments=", segments); //SERIAL_ECHOLNPGM(" segment_mm=", hints.millimeters); // Get the raw current position as starting point xyze_pos_t raw = current_position; // Calculate and execute the segments millis_t next_idle_ms = millis() + 200UL; while (--segments) { segment_idle(next_idle_ms); raw += segment_distance; if (!planner.buffer_line(raw, fr_mm_s, active_extruder, hints)) break; } // Since segment_distance is only approximate, // the final move must be to the exact destination. planner.buffer_line(destination, fr_mm_s, active_extruder, hints); } #endif // SEGMENT_LEVELED_MOVES && !AUTO_BED_LEVELING_UBL /** * Prepare a linear move in a Cartesian setup. * * When a mesh-based leveling system is active, moves are segmented * according to the configuration of the leveling system. * * Return true if 'current_position' was set to 'destination' */ inline bool line_to_destination_cartesian() { const float scaled_fr_mm_s = MMS_SCALED(feedrate_mm_s); #if HAS_MESH if (planner.leveling_active && planner.leveling_active_at_z(destination.z)) { #if ENABLED(AUTO_BED_LEVELING_UBL) #if UBL_SEGMENTED return bedlevel.line_to_destination_segmented(scaled_fr_mm_s); #else bedlevel.line_to_destination_cartesian(scaled_fr_mm_s, active_extruder); // UBL's motion routine needs to know about return true; // all moves, including Z-only moves. #endif #elif ENABLED(SEGMENT_LEVELED_MOVES) segmented_line_to_destination(scaled_fr_mm_s); return false; // caller will update current_position #else /** * For MBL and ABL-BILINEAR only segment moves when X or Y are involved. * Otherwise fall through to do a direct single move. */ if (xy_pos_t(current_position) != xy_pos_t(destination)) { #if ENABLED(MESH_BED_LEVELING) bedlevel.line_to_destination(scaled_fr_mm_s); #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) bedlevel.line_to_destination(scaled_fr_mm_s); #endif return true; } #endif } #endif // HAS_MESH planner.buffer_line(destination, scaled_fr_mm_s); return false; // caller will update current_position } #endif // !IS_KINEMATIC #if HAS_DUPLICATION_MODE bool extruder_duplication_enabled; #if ENABLED(MULTI_NOZZLE_DUPLICATION) uint8_t duplication_e_mask; // = 0 #endif #endif #if ENABLED(DUAL_X_CARRIAGE) DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE; float inactive_extruder_x = X2_MAX_POS, // Used in mode 0 & 1 duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // Used in mode 2 & 3 xyz_pos_t raised_parked_position; // Used in mode 1 bool active_extruder_parked = false; // Used in mode 1, 2 & 3 millis_t delayed_move_time = 0; // Used in mode 1 celsius_t duplicate_extruder_temp_offset = 0; // Used in mode 2 & 3 bool idex_mirrored_mode = false; // Used in mode 3 float x_home_pos(const uint8_t extruder) { if (extruder == 0) return X_HOME_POS; /** * In dual carriage mode the extruder offset provides an override of the * second X-carriage position when homed - otherwise X2_HOME_POS is used. * This allows soft recalibration of the second extruder home position * (with M218 T1 Xn) without firmware reflash. */ return hotend_offset[1].x > 0 ? hotend_offset[1].x : X2_HOME_POS; } void idex_set_mirrored_mode(const bool mirr) { idex_mirrored_mode = mirr; stepper.apply_directions(); } void set_duplication_enabled(const bool dupe, const int8_t tool_index/*=-1*/) { extruder_duplication_enabled = dupe; if (tool_index >= 0) active_extruder = tool_index; stepper.apply_directions(); } void idex_set_parked(const bool park/*=true*/) { delayed_move_time = 0; active_extruder_parked = park; if (park) raised_parked_position = current_position; // Remember current raised toolhead position for use by unpark } /** * Prepare a linear move in a dual X axis setup * * Return true if current_position[] was set to destination[] */ inline bool dual_x_carriage_unpark() { if (active_extruder_parked) { switch (dual_x_carriage_mode) { case DXC_FULL_CONTROL_MODE: break; case DXC_AUTO_PARK_MODE: { if (current_position.e == destination.e) { // This is a travel move (with no extrusion) // Skip it, but keep track of the current position // (so it can be used as the start of the next non-travel move) if (delayed_move_time != 0xFFFFFFFFUL) { current_position = destination; NOLESS(raised_parked_position.z, destination.z); delayed_move_time = millis() + 1000UL; return true; } } // // Un-park the active extruder // const feedRate_t fr_zfast = planner.settings.max_feedrate_mm_s[Z_AXIS]; // 1. Move to the raised parked XYZ. Presumably the tool is already at XY. xyze_pos_t raised = raised_parked_position; raised.e = current_position.e; if (planner.buffer_line(raised, fr_zfast)) { // 2. Move to the current native XY and raised Z. Presumably this is a null move. xyze_pos_t curpos = current_position; curpos.z = raised_parked_position.z; if (planner.buffer_line(curpos, PLANNER_XY_FEEDRATE())) { // 3. Lower Z back down line_to_current_position(fr_zfast); } } stepper.apply_directions(); idex_set_parked(false); if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("idex_set_parked(false)"); } break; case DXC_MIRRORED_MODE: case DXC_DUPLICATION_MODE: if (active_extruder == 0) { set_duplication_enabled(false); // Clear stale duplication state // Restore planner to parked head (T1) X position float x0_pos = current_position.x; xyze_pos_t pos_now = current_position; pos_now.x = inactive_extruder_x; planner.set_position_mm(pos_now); // Keep the same X or add the duplication X offset xyze_pos_t new_pos = pos_now; if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) new_pos.x = x0_pos + duplicate_extruder_x_offset; else new_pos.x = _MIN(X_BED_SIZE - x0_pos, X_MAX_POS); // Move duplicate extruder into the correct position if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Set planner X", inactive_extruder_x, " ... Line to X", new_pos.x); if (!planner.buffer_line(new_pos, planner.settings.max_feedrate_mm_s[X_AXIS], 1)) break; planner.synchronize(); sync_plan_position(); // Extra sync for good measure set_duplication_enabled(true); // Enable Duplication idex_set_parked(false); // No longer parked if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("set_duplication_enabled(true)\nidex_set_parked(false)"); } else if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Active extruder not 0"); break; } } return false; } #endif // DUAL_X_CARRIAGE /** * Prepare a single move and get ready for the next one * * This may result in several calls to planner.buffer_line to * do smaller moves for DELTA, SCARA, mesh moves, etc. * * Make sure current_position.e and destination.e are good * before calling or cold/lengthy extrusion may get missed. * * Before exit, current_position is set to destination. */ void prepare_line_to_destination() { apply_motion_limits(destination); #if ANY(PREVENT_COLD_EXTRUSION, PREVENT_LENGTHY_EXTRUDE) if (!DEBUGGING(DRYRUN) && destination.e != current_position.e) { bool ignore_e = thermalManager.tooColdToExtrude(active_extruder); if (ignore_e) SERIAL_ECHO_MSG(STR_ERR_COLD_EXTRUDE_STOP); #if ENABLED(PREVENT_LENGTHY_EXTRUDE) const float e_delta = ABS(destination.e - current_position.e) * planner.e_factor[active_extruder]; if (e_delta > (EXTRUDE_MAXLENGTH)) { #if ENABLED(MIXING_EXTRUDER) float collector[MIXING_STEPPERS]; mixer.refresh_collector(1.0, mixer.get_current_vtool(), collector); MIXER_STEPPER_LOOP(e) { if (e_delta * collector[e] > (EXTRUDE_MAXLENGTH)) { ignore_e = true; SERIAL_ECHO_MSG(STR_ERR_LONG_EXTRUDE_STOP); break; } } #else ignore_e = true; SERIAL_ECHO_MSG(STR_ERR_LONG_EXTRUDE_STOP); #endif } #endif if (ignore_e) { current_position.e = destination.e; // Behave as if the E move really took place planner.set_e_position_mm(destination.e); // Prevent the planner from complaining too } } #endif // PREVENT_COLD_EXTRUSION || PREVENT_LENGTHY_EXTRUDE if (TERN0(DUAL_X_CARRIAGE, dual_x_carriage_unpark())) return; if ( #if UBL_SEGMENTED #if IS_KINEMATIC // UBL using Kinematic / Cartesian cases as a workaround for now. bedlevel.line_to_destination_segmented(MMS_SCALED(feedrate_mm_s)) #else line_to_destination_cartesian() #endif #elif IS_KINEMATIC line_to_destination_kinematic() #else line_to_destination_cartesian() #endif ) return; current_position = destination; } #if HAS_ENDSTOPS main_axes_bits_t axes_homed, axes_trusted; // = 0 main_axes_bits_t axes_should_home(main_axes_bits_t axis_bits/*=main_axes_mask*/) { auto set_should = [](main_axes_bits_t &b, AxisEnum a) { if (TEST(b, a) && TERN(HOME_AFTER_DEACTIVATE, axis_is_trusted, axis_was_homed)(a)) CBI(b, a); }; // Clear test bits that are trusted NUM_AXIS_CODE( set_should(axis_bits, X_AXIS), set_should(axis_bits, Y_AXIS), set_should(axis_bits, Z_AXIS), set_should(axis_bits, I_AXIS), set_should(axis_bits, J_AXIS), set_should(axis_bits, K_AXIS), set_should(axis_bits, U_AXIS), set_should(axis_bits, V_AXIS), set_should(axis_bits, W_AXIS) ); return axis_bits; } bool homing_needed_error(main_axes_bits_t axis_bits/*=main_axes_mask*/) { if (!(axis_bits &= axes_should_home(axis_bits))) return false; char all_axes[] = STR_AXES_MAIN, need[NUM_AXES + 1]; uint8_t n = 0; LOOP_NUM_AXES(i) if (TEST(axis_bits, i)) need[n++] = all_axes[i]; need[n] = '\0'; SString<30> msg; msg.setf(GET_EN_TEXT_F(MSG_HOME_FIRST), need); SERIAL_ECHO_START(); msg.echoln(); msg.setf(GET_TEXT_F(MSG_HOME_FIRST), need); ui.set_status(msg); return true; } /** * Homing bump feedrate (mm/s) */ feedRate_t get_homing_bump_feedrate(const AxisEnum axis) { #if HOMING_Z_WITH_PROBE if (axis == Z_AXIS) return MMM_TO_MMS(Z_PROBE_FEEDRATE_SLOW); #endif static const uint8_t homing_bump_divisor[] PROGMEM = HOMING_BUMP_DIVISOR; uint8_t hbd = pgm_read_byte(&homing_bump_divisor[axis]); if (hbd < 1) { hbd = 10; SERIAL_ECHO_MSG("Warning: Homing Bump Divisor < 1"); } return homing_feedrate(axis) / float(hbd); } #if ENABLED(SENSORLESS_HOMING) /** * Set sensorless homing if the axis has it, accounting for Core Kinematics. */ sensorless_t start_sensorless_homing_per_axis(const AxisEnum axis) { sensorless_t stealth_states { false }; switch (axis) { default: break; #if X_SENSORLESS case X_AXIS: stealth_states.x = tmc_enable_stallguard(stepperX); TERN_(X2_SENSORLESS, stealth_states.x2 = tmc_enable_stallguard(stepperX2)); #if ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX) && Y_SENSORLESS stealth_states.y = tmc_enable_stallguard(stepperY); #elif CORE_IS_XZ && Z_SENSORLESS stealth_states.z = tmc_enable_stallguard(stepperZ); #endif break; #endif #if Y_SENSORLESS case Y_AXIS: stealth_states.y = tmc_enable_stallguard(stepperY); TERN_(Y2_SENSORLESS, stealth_states.y2 = tmc_enable_stallguard(stepperY2)); #if ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX) && X_SENSORLESS stealth_states.x = tmc_enable_stallguard(stepperX); #elif CORE_IS_YZ && Z_SENSORLESS stealth_states.z = tmc_enable_stallguard(stepperZ); #endif break; #endif #if Z_SENSORLESS case Z_AXIS: stealth_states.z = tmc_enable_stallguard(stepperZ); TERN_(Z2_SENSORLESS, stealth_states.z2 = tmc_enable_stallguard(stepperZ2)); TERN_(Z3_SENSORLESS, stealth_states.z3 = tmc_enable_stallguard(stepperZ3)); TERN_(Z4_SENSORLESS, stealth_states.z4 = tmc_enable_stallguard(stepperZ4)); #if CORE_IS_XZ && X_SENSORLESS stealth_states.x = tmc_enable_stallguard(stepperX); #elif CORE_IS_YZ && Y_SENSORLESS stealth_states.y = tmc_enable_stallguard(stepperY); #endif break; #endif #if I_SENSORLESS case I_AXIS: stealth_states.i = tmc_enable_stallguard(stepperI); break; #endif #if J_SENSORLESS case J_AXIS: stealth_states.j = tmc_enable_stallguard(stepperJ); break; #endif #if K_SENSORLESS case K_AXIS: stealth_states.k = tmc_enable_stallguard(stepperK); break; #endif #if U_SENSORLESS case U_AXIS: stealth_states.u = tmc_enable_stallguard(stepperU); break; #endif #if V_SENSORLESS case V_AXIS: stealth_states.v = tmc_enable_stallguard(stepperV); break; #endif #if W_SENSORLESS case W_AXIS: stealth_states.w = tmc_enable_stallguard(stepperW); break; #endif } switch (axis) { #if X_SPI_SENSORLESS case X_AXIS: endstops.tmc_spi_homing.x = true; break; #endif #if Y_SPI_SENSORLESS case Y_AXIS: endstops.tmc_spi_homing.y = true; break; #endif #if Z_SPI_SENSORLESS case Z_AXIS: endstops.tmc_spi_homing.z = true; break; #endif #if I_SPI_SENSORLESS case I_AXIS: endstops.tmc_spi_homing.i = true; break; #endif #if J_SPI_SENSORLESS case J_AXIS: endstops.tmc_spi_homing.j = true; break; #endif #if K_SPI_SENSORLESS case K_AXIS: endstops.tmc_spi_homing.k = true; break; #endif #if U_SPI_SENSORLESS case U_AXIS: endstops.tmc_spi_homing.u = true; break; #endif #if V_SPI_SENSORLESS case V_AXIS: endstops.tmc_spi_homing.v = true; break; #endif #if W_SPI_SENSORLESS case W_AXIS: endstops.tmc_spi_homing.w = true; break; #endif default: break; } TERN_(IMPROVE_HOMING_RELIABILITY, sg_guard_period = millis() + default_sg_guard_duration); return stealth_states; } void end_sensorless_homing_per_axis(const AxisEnum axis, sensorless_t enable_stealth) { switch (axis) { default: break; #if X_SENSORLESS case X_AXIS: tmc_disable_stallguard(stepperX, enable_stealth.x); TERN_(X2_SENSORLESS, tmc_disable_stallguard(stepperX2, enable_stealth.x2)); #if ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX) && Y_SENSORLESS tmc_disable_stallguard(stepperY, enable_stealth.y); #elif CORE_IS_XZ && Z_SENSORLESS tmc_disable_stallguard(stepperZ, enable_stealth.z); #endif break; #endif #if Y_SENSORLESS case Y_AXIS: tmc_disable_stallguard(stepperY, enable_stealth.y); TERN_(Y2_SENSORLESS, tmc_disable_stallguard(stepperY2, enable_stealth.y2)); #if ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX) && X_SENSORLESS tmc_disable_stallguard(stepperX, enable_stealth.x); #elif CORE_IS_YZ && Z_SENSORLESS tmc_disable_stallguard(stepperZ, enable_stealth.z); #endif break; #endif #if Z_SENSORLESS case Z_AXIS: tmc_disable_stallguard(stepperZ, enable_stealth.z); TERN_(Z2_SENSORLESS, tmc_disable_stallguard(stepperZ2, enable_stealth.z2)); TERN_(Z3_SENSORLESS, tmc_disable_stallguard(stepperZ3, enable_stealth.z3)); TERN_(Z4_SENSORLESS, tmc_disable_stallguard(stepperZ4, enable_stealth.z4)); #if CORE_IS_XZ && X_SENSORLESS tmc_disable_stallguard(stepperX, enable_stealth.x); #elif CORE_IS_YZ && Y_SENSORLESS tmc_disable_stallguard(stepperY, enable_stealth.y); #endif break; #endif #if I_SENSORLESS case I_AXIS: tmc_disable_stallguard(stepperI, enable_stealth.i); break; #endif #if J_SENSORLESS case J_AXIS: tmc_disable_stallguard(stepperJ, enable_stealth.j); break; #endif #if K_SENSORLESS case K_AXIS: tmc_disable_stallguard(stepperK, enable_stealth.k); break; #endif #if U_SENSORLESS case U_AXIS: tmc_disable_stallguard(stepperU, enable_stealth.u); break; #endif #if V_SENSORLESS case V_AXIS: tmc_disable_stallguard(stepperV, enable_stealth.v); break; #endif #if W_SENSORLESS case W_AXIS: tmc_disable_stallguard(stepperW, enable_stealth.w); break; #endif } switch (axis) { #if X_SPI_SENSORLESS case X_AXIS: endstops.tmc_spi_homing.x = false; break; #endif #if Y_SPI_SENSORLESS case Y_AXIS: endstops.tmc_spi_homing.y = false; break; #endif #if Z_SPI_SENSORLESS case Z_AXIS: endstops.tmc_spi_homing.z = false; break; #endif #if I_SPI_SENSORLESS case I_AXIS: endstops.tmc_spi_homing.i = false; break; #endif #if J_SPI_SENSORLESS case J_AXIS: endstops.tmc_spi_homing.j = false; break; #endif #if K_SPI_SENSORLESS case K_AXIS: endstops.tmc_spi_homing.k = false; break; #endif #if U_SPI_SENSORLESS case U_AXIS: endstops.tmc_spi_homing.u = false; break; #endif #if V_SPI_SENSORLESS case V_AXIS: endstops.tmc_spi_homing.v = false; break; #endif #if W_SPI_SENSORLESS case W_AXIS: endstops.tmc_spi_homing.w = false; break; #endif default: break; } } #endif // SENSORLESS_HOMING /** * Home an individual linear axis */ void do_homing_move(const AxisEnum axis, const float distance, const feedRate_t fr_mm_s=0.0, const bool final_approach=true) { DEBUG_SECTION(log_move, "do_homing_move", DEBUGGING(LEVELING)); const feedRate_t home_fr_mm_s = fr_mm_s ?: homing_feedrate(axis); if (DEBUGGING(LEVELING)) { DEBUG_ECHOPGM("...(", C(AXIS_CHAR(axis)), ", ", distance, ", "); if (fr_mm_s) DEBUG_ECHO(fr_mm_s); else DEBUG_ECHOPGM("[", home_fr_mm_s, "]"); DEBUG_ECHOLNPGM(")"); } // Only do some things when moving towards an endstop const int8_t axis_home_dir = TERN0(DUAL_X_CARRIAGE, axis == X_AXIS) ? TOOL_X_HOME_DIR(active_extruder) : home_dir(axis); const bool is_home_dir = (axis_home_dir > 0) == (distance > 0); #if ENABLED(SENSORLESS_HOMING) sensorless_t stealth_states; #endif if (is_home_dir) { if (TERN0(HOMING_Z_WITH_PROBE, axis == Z_AXIS)) { #if ALL(HAS_HEATED_BED, WAIT_FOR_BED_HEATER) // Wait for bed to heat back up between probing points thermalManager.wait_for_bed_heating(); #endif #if ALL(HAS_HOTEND, WAIT_FOR_HOTEND) // Wait for the hotend to heat back up between probing points thermalManager.wait_for_hotend_heating(active_extruder); #endif TERN_(HAS_QUIET_PROBING, if (final_approach) probe.set_probing_paused(true)); } // Disable stealthChop if used. Enable diag1 pin on driver. #if ENABLED(SENSORLESS_HOMING) stealth_states = start_sensorless_homing_per_axis(axis); #if SENSORLESS_STALLGUARD_DELAY safe_delay(SENSORLESS_STALLGUARD_DELAY); // Short delay needed to settle #endif #endif } #if ANY(MORGAN_SCARA, MP_SCARA) // Tell the planner the axis is at 0 current_position[axis] = 0; sync_plan_position(); current_position[axis] = distance; line_to_current_position(home_fr_mm_s); #else // Get the ABC or XYZ positions in mm abce_pos_t target = planner.get_axis_positions_mm(); target[axis] = 0; // Set the single homing axis to 0 planner.set_machine_position_mm(target); // Update the machine position #if HAS_DIST_MM_ARG const xyze_float_t cart_dist_mm{0}; #endif // Set delta/cartesian axes directly target[axis] = distance; // The move will be towards the endstop planner.buffer_segment(target OPTARG(HAS_DIST_MM_ARG, cart_dist_mm), home_fr_mm_s, active_extruder); #endif planner.synchronize(); if (is_home_dir) { #if HOMING_Z_WITH_PROBE && HAS_QUIET_PROBING if (axis == Z_AXIS && final_approach) probe.set_probing_paused(false); #endif endstops.validate_homing_move(); // Re-enable stealthChop if used. Disable diag1 pin on driver. #if ENABLED(SENSORLESS_HOMING) end_sensorless_homing_per_axis(axis, stealth_states); #if SENSORLESS_STALLGUARD_DELAY safe_delay(SENSORLESS_STALLGUARD_DELAY); // Short delay needed to settle #endif #endif } } /** * Set an axis to be unhomed. (Unless we are on a machine - e.g. a cheap Chinese CNC machine - * that has no endstops. Such machines should always be considered to be in a "known" and * "trusted" position). */ void set_axis_never_homed(const AxisEnum axis) { if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM(">>> set_axis_never_homed(", C(AXIS_CHAR(axis)), ")"); set_axis_untrusted(axis); set_axis_unhomed(axis); if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("<<< set_axis_never_homed(", C(AXIS_CHAR(axis)), ")"); TERN_(I2C_POSITION_ENCODERS, I2CPEM.unhomed(axis)); } #ifdef TMC_HOME_PHASE /** * Move the axis back to its home_phase if set and driver is capable (TMC) * * Improves homing repeatability by homing to stepper coil's nearest absolute * phase position. Trinamic drivers use a stepper phase table with 1024 values * spanning 4 full steps with 256 positions each (ergo, 1024 positions). */ void backout_to_tmc_homing_phase(const AxisEnum axis) { const xyz_long_t home_phase = TMC_HOME_PHASE; // check if home phase is disabled for this axis. if (home_phase[axis] < 0) return; int16_t phasePerUStep, // TMC µsteps(phase) per Marlin µsteps phaseCurrent, // The TMC µsteps(phase) count of the current position effectorBackoutDir, // Direction in which the effector mm coordinates move away from endstop. stepperBackoutDir; // Direction in which the TMC µstep count(phase) move away from endstop. #define PHASE_PER_MICROSTEP(N) (256 / _MAX(1, N##_MICROSTEPS)) switch (axis) { #ifdef X_MICROSTEPS case X_AXIS: phasePerUStep = PHASE_PER_MICROSTEP(X); phaseCurrent = stepperX.get_microstep_counter(); effectorBackoutDir = -(X_HOME_DIR); stepperBackoutDir = TERN_(INVERT_X_DIR, -)(-effectorBackoutDir); break; #endif #ifdef Y_MICROSTEPS case Y_AXIS: phasePerUStep = PHASE_PER_MICROSTEP(Y); phaseCurrent = stepperY.get_microstep_counter(); effectorBackoutDir = -(Y_HOME_DIR); stepperBackoutDir = TERN_(INVERT_Y_DIR, -)(-effectorBackoutDir); break; #endif #ifdef Z_MICROSTEPS case Z_AXIS: phasePerUStep = PHASE_PER_MICROSTEP(Z); phaseCurrent = stepperZ.get_microstep_counter(); effectorBackoutDir = -(Z_HOME_DIR); stepperBackoutDir = TERN_(INVERT_Z_DIR, -)(-effectorBackoutDir); break; #endif #ifdef I_MICROSTEPS case I_AXIS: phasePerUStep = PHASE_PER_MICROSTEP(I); phaseCurrent = stepperI.get_microstep_counter(); effectorBackoutDir = -(I_HOME_DIR); stepperBackoutDir = TERN_(INVERT_I_DIR, -)(-effectorBackoutDir); break; #endif #ifdef J_MICROSTEPS case J_AXIS: phasePerUStep = PHASE_PER_MICROSTEP(J); phaseCurrent = stepperJ.get_microstep_counter(); effectorBackoutDir = -(J_HOME_DIR); stepperBackoutDir = TERN_(INVERT_J_DIR, -)(-effectorBackoutDir); break; #endif #ifdef K_MICROSTEPS case K_AXIS: phasePerUStep = PHASE_PER_MICROSTEP(K); phaseCurrent = stepperK.get_microstep_counter(); effectorBackoutDir = -(K_HOME_DIR); stepperBackoutDir = TERN_(INVERT_K_DIR, -)(-effectorBackoutDir); break; #endif #ifdef U_MICROSTEPS case U_AXIS: phasePerUStep = PHASE_PER_MICROSTEP(U); phaseCurrent = stepperU.get_microstep_counter(); effectorBackoutDir = -(U_HOME_DIR); stepperBackoutDir = TERN_(INVERT_U_DIR, -)(-effectorBackoutDir); break; #endif #ifdef V_MICROSTEPS case V_AXIS: phasePerUStep = PHASE_PER_MICROSTEP(V); phaseCurrent = stepperV.get_microstep_counter(); effectorBackoutDir = -(V_HOME_DIR); stepperBackoutDir = TERN_(INVERT_V_DIR, -)(-effectorBackoutDir); break; #endif #ifdef W_MICROSTEPS case W_AXIS: phasePerUStep = PHASE_PER_MICROSTEP(W); phaseCurrent = stepperW.get_microstep_counter(); effectorBackoutDir = -(W_HOME_DIR); stepperBackoutDir = TERN_(INVERT_W_DIR, -)(-effectorBackoutDir); break; #endif default: return; } // Phase distance to nearest home phase position when moving in the backout direction from endstop(may be negative). int16_t phaseDelta = (home_phase[axis] - phaseCurrent) * stepperBackoutDir; // Check if home distance within endstop assumed repeatability noise of .05mm and warn. if (ABS(phaseDelta) * planner.mm_per_step[axis] / phasePerUStep < 0.05f) SERIAL_ECHOLNPGM("Selected home phase ", home_phase[axis], " too close to endstop trigger phase ", phaseCurrent, ". Pick a different phase for ", C(AXIS_CHAR(axis))); // Skip to next if target position is behind current. So it only moves away from endstop. if (phaseDelta < 0) phaseDelta += 1024; // Convert TMC µsteps(phase) to whole Marlin µsteps to effector backout direction to mm const float mmDelta = int16_t(phaseDelta / phasePerUStep) * effectorBackoutDir * planner.mm_per_step[axis]; // Optional debug messages if (DEBUGGING(LEVELING)) { DEBUG_ECHOLNPGM( "Endstop ", C(AXIS_CHAR(axis)), " hit at Phase:", phaseCurrent, " Delta:", phaseDelta, " Distance:", mmDelta ); } if (mmDelta != 0) { // Retrace by the amount computed in mmDelta. do_homing_move(axis, mmDelta, get_homing_bump_feedrate(axis)); } } #endif /** * Home an individual "raw axis" to its endstop. * This applies to XYZ on Cartesian and Core robots, and * to the individual ABC steppers on DELTA and SCARA. * * At the end of the procedure the axis is marked as * homed and the current position of that axis is updated. * Kinematic robots should wait till all axes are homed * before updating the current position. */ void homeaxis(const AxisEnum axis) { #if ANY(MORGAN_SCARA, MP_SCARA) // Only Z homing (with probe) is permitted if (axis != Z_AXIS) { BUZZ(100, 880); return; } #else #define _CAN_HOME(A) (axis == _AXIS(A) && (ANY(A##_SPI_SENSORLESS, HAS_##A##_STATE) || TERN0(HOMING_Z_WITH_PROBE, _AXIS(A) == Z_AXIS))) #define _ANDCANT(N) && !_CAN_HOME(N) if (true MAIN_AXIS_MAP(_ANDCANT)) return; #endif if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM(">>> homeaxis(", C(AXIS_CHAR(axis)), ")"); const int axis_home_dir = TERN0(DUAL_X_CARRIAGE, axis == X_AXIS) ? TOOL_X_HOME_DIR(active_extruder) : home_dir(axis); // // Homing Z with a probe? Raise Z (maybe) and deploy the Z probe. // if (TERN0(HOMING_Z_WITH_PROBE, axis == Z_AXIS && probe.deploy())) return; // Set flags for X, Y, Z motor locking #if HAS_EXTRA_ENDSTOPS switch (axis) { TERN_(X_DUAL_ENDSTOPS, case X_AXIS:) TERN_(Y_DUAL_ENDSTOPS, case Y_AXIS:) TERN_(Z_MULTI_ENDSTOPS, case Z_AXIS:) stepper.set_separate_multi_axis(true); default: break; } #endif // // Deploy BLTouch or tare the probe just before probing // #if HOMING_Z_WITH_PROBE if (axis == Z_AXIS) { if (TERN0(BLTOUCH, bltouch.deploy())) return; // BLTouch was deployed above, but get the alarm state. if (TERN0(PROBE_TARE, probe.tare())) return; TERN_(BD_SENSOR, bdl.config_state = BDS_HOMING_Z); } #endif // // Back away to prevent an early sensorless trigger // #if DISABLED(DELTA) && defined(SENSORLESS_BACKOFF_MM) const xyz_float_t backoff = SENSORLESS_BACKOFF_MM; if ((TERN0(X_SENSORLESS, axis == X_AXIS) || TERN0(Y_SENSORLESS, axis == Y_AXIS) || TERN0(Z_SENSORLESS, axis == Z_AXIS) || TERN0(I_SENSORLESS, axis == I_AXIS) || TERN0(J_SENSORLESS, axis == J_AXIS) || TERN0(K_SENSORLESS, axis == K_AXIS)) && backoff[axis]) { const float backoff_length = -ABS(backoff[axis]) * axis_home_dir; if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Sensorless backoff: ", backoff_length, "mm"); do_homing_move(axis, backoff_length, homing_feedrate(axis)); } #endif // // Back away to prevent opposite endstop damage // #if !defined(SENSORLESS_BACKOFF_MM) && XY_COUNTERPART_BACKOFF_MM if (!(axis_was_homed(X_AXIS) || axis_was_homed(Y_AXIS)) && (axis == X_AXIS || axis == Y_AXIS)) { const AxisEnum opposite_axis = axis == X_AXIS ? Y_AXIS : X_AXIS; const float backoff_length = -ABS(XY_COUNTERPART_BACKOFF_MM) * home_dir(opposite_axis); do_homing_move(opposite_axis, backoff_length, homing_feedrate(opposite_axis)); } #endif // Determine if a homing bump will be done and the bumps distance // When homing Z with probe respect probe clearance const bool use_probe_bump = TERN0(HOMING_Z_WITH_PROBE, axis == Z_AXIS && home_bump_mm(axis)); const float bump = axis_home_dir * ( use_probe_bump ? _MAX(TERN0(HOMING_Z_WITH_PROBE, Z_CLEARANCE_BETWEEN_PROBES), home_bump_mm(axis)) : home_bump_mm(axis) ); // // Fast move towards endstop until triggered // const float move_length = 1.5f * max_length(TERN(DELTA, Z_AXIS, axis)) * axis_home_dir; if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Home Fast: ", move_length, "mm"); do_homing_move(axis, move_length, 0.0, !use_probe_bump); // If a second homing move is configured... if (bump) { #if ALL(HOMING_Z_WITH_PROBE, BLTOUCH) if (axis == Z_AXIS && !bltouch.high_speed_mode) bltouch.stow(); // Intermediate STOW (in LOW SPEED MODE) #endif // Move away from the endstop by the axis HOMING_BUMP_MM if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Move Away: ", -bump, "mm"); do_homing_move(axis, -bump, TERN(HOMING_Z_WITH_PROBE, (axis == Z_AXIS ? z_probe_fast_mm_s : 0), 0), false); #if ENABLED(DETECT_BROKEN_ENDSTOP) // Check for a broken endstop EndstopEnum es; switch (axis) { #define _ESCASE(A) case A##_AXIS: es = A##_ENDSTOP; break; MAIN_AXIS_MAP(_ESCASE) default: break; } #if ENABLED(DUAL_X_CARRIAGE) if (axis == X_AXIS && axis_home_dir > 0) { es = X_MAX; if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("DUAL_X_CARRIAGE: Homing to X_MAX"); } #endif if (TEST(endstops.state(), es)) { SERIAL_ECHO_MSG("Bad ", C(AXIS_CHAR(axis)), " Endstop?"); kill(GET_TEXT_F(MSG_KILL_HOMING_FAILED)); } #endif // DETECT_BROKEN_ENDSTOP #if ALL(HOMING_Z_WITH_PROBE, BLTOUCH) if (axis == Z_AXIS && !bltouch.high_speed_mode && bltouch.deploy()) return; // Intermediate DEPLOY (in LOW SPEED MODE) #endif // Slow move towards endstop until triggered const float rebump = bump * 2; if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Re-bump: ", rebump, "mm"); do_homing_move(axis, rebump, get_homing_bump_feedrate(axis), true); } #if ALL(HOMING_Z_WITH_PROBE, BLTOUCH) if (axis == Z_AXIS) bltouch.stow(); // The final STOW #endif #if HAS_EXTRA_ENDSTOPS const bool pos_dir = axis_home_dir > 0; #if ENABLED(X_DUAL_ENDSTOPS) if (axis == X_AXIS) { const float adj = ABS(endstops.x2_endstop_adj); if (adj) { if (pos_dir ? (endstops.x2_endstop_adj > 0) : (endstops.x2_endstop_adj < 0)) stepper.set_x_lock(true); else stepper.set_x2_lock(true); do_homing_move(axis, pos_dir ? -adj : adj); stepper.set_x_lock(false); stepper.set_x2_lock(false); } } #endif #if ENABLED(Y_DUAL_ENDSTOPS) if (axis == Y_AXIS) { const float adj = ABS(endstops.y2_endstop_adj); if (adj) { if (pos_dir ? (endstops.y2_endstop_adj > 0) : (endstops.y2_endstop_adj < 0)) stepper.set_y_lock(true); else stepper.set_y2_lock(true); do_homing_move(axis, pos_dir ? -adj : adj); stepper.set_y_lock(false); stepper.set_y2_lock(false); } } #endif #if ENABLED(Z_MULTI_ENDSTOPS) if (axis == Z_AXIS) { #if NUM_Z_STEPPERS == 2 const float adj = ABS(endstops.z2_endstop_adj); if (adj) { if (pos_dir ? (endstops.z2_endstop_adj > 0) : (endstops.z2_endstop_adj < 0)) stepper.set_z1_lock(true); else stepper.set_z2_lock(true); do_homing_move(axis, pos_dir ? -adj : adj); stepper.set_z1_lock(false); stepper.set_z2_lock(false); } #else // Handy arrays of stepper lock function pointers typedef void (*adjustFunc_t)(const bool); adjustFunc_t lock[] = { stepper.set_z1_lock, stepper.set_z2_lock, stepper.set_z3_lock #if NUM_Z_STEPPERS >= 4 , stepper.set_z4_lock #endif }; float adj[] = { 0, endstops.z2_endstop_adj, endstops.z3_endstop_adj #if NUM_Z_STEPPERS >= 4 , endstops.z4_endstop_adj #endif }; adjustFunc_t tempLock; float tempAdj; // Manual bubble sort by adjust value if (adj[1] < adj[0]) { tempLock = lock[0], tempAdj = adj[0]; lock[0] = lock[1], adj[0] = adj[1]; lock[1] = tempLock, adj[1] = tempAdj; } if (adj[2] < adj[1]) { tempLock = lock[1], tempAdj = adj[1]; lock[1] = lock[2], adj[1] = adj[2]; lock[2] = tempLock, adj[2] = tempAdj; } #if NUM_Z_STEPPERS >= 4 if (adj[3] < adj[2]) { tempLock = lock[2], tempAdj = adj[2]; lock[2] = lock[3], adj[2] = adj[3]; lock[3] = tempLock, adj[3] = tempAdj; } if (adj[2] < adj[1]) { tempLock = lock[1], tempAdj = adj[1]; lock[1] = lock[2], adj[1] = adj[2]; lock[2] = tempLock, adj[2] = tempAdj; } #endif if (adj[1] < adj[0]) { tempLock = lock[0], tempAdj = adj[0]; lock[0] = lock[1], adj[0] = adj[1]; lock[1] = tempLock, adj[1] = tempAdj; } if (pos_dir) { // normalize adj to smallest value and do the first move (*lock[0])(true); do_homing_move(axis, adj[1] - adj[0]); // lock the second stepper for the final correction (*lock[1])(true); do_homing_move(axis, adj[2] - adj[1]); #if NUM_Z_STEPPERS >= 4 // lock the third stepper for the final correction (*lock[2])(true); do_homing_move(axis, adj[3] - adj[2]); #endif } else { #if NUM_Z_STEPPERS >= 4 (*lock[3])(true); do_homing_move(axis, adj[2] - adj[3]); #endif (*lock[2])(true); do_homing_move(axis, adj[1] - adj[2]); (*lock[1])(true); do_homing_move(axis, adj[0] - adj[1]); } stepper.set_z1_lock(false); stepper.set_z2_lock(false); stepper.set_z3_lock(false); #if NUM_Z_STEPPERS >= 4 stepper.set_z4_lock(false); #endif #endif } #endif // Reset flags for X, Y, Z motor locking switch (axis) { default: break; TERN_(X_DUAL_ENDSTOPS, case X_AXIS:) TERN_(Y_DUAL_ENDSTOPS, case Y_AXIS:) TERN_(Z_MULTI_ENDSTOPS, case Z_AXIS:) stepper.set_separate_multi_axis(false); } #endif // HAS_EXTRA_ENDSTOPS #ifdef TMC_HOME_PHASE // move back to homing phase if configured and capable backout_to_tmc_homing_phase(axis); #endif #if IS_SCARA set_axis_is_at_home(axis); sync_plan_position(); #elif ENABLED(DELTA) // Delta has already moved all three towers up in G28 // so here it re-homes each tower in turn. // Delta homing treats the axes as normal linear axes. const float adjDistance = delta_endstop_adj[axis], minDistance = (MIN_STEPS_PER_SEGMENT) * planner.mm_per_step[axis]; // Retrace by the amount specified in delta_endstop_adj if more than min steps. if (adjDistance * (Z_HOME_DIR) < 0 && ABS(adjDistance) > minDistance) { // away from endstop, more than min distance if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("adjDistance:", adjDistance); do_homing_move(axis, adjDistance, get_homing_bump_feedrate(axis)); } #else // CARTESIAN / CORE / MARKFORGED_XY / MARKFORGED_YX set_axis_is_at_home(axis); sync_plan_position(); destination[axis] = current_position[axis]; if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position); #endif #if ALL(BD_SENSOR, HOMING_Z_WITH_PROBE) if (axis == Z_AXIS) bdl.config_state = BDS_IDLE; #endif // Put away the Z probe if (TERN0(HOMING_Z_WITH_PROBE, axis == Z_AXIS && probe.stow())) return; #if DISABLED(DELTA) && defined(HOMING_BACKOFF_POST_MM) const xyz_float_t endstop_backoff = HOMING_BACKOFF_POST_MM; if (endstop_backoff[axis]) { current_position[axis] -= ABS(endstop_backoff[axis]) * axis_home_dir; line_to_current_position(TERN_(HOMING_Z_WITH_PROBE, (axis == Z_AXIS) ? z_probe_fast_mm_s :) homing_feedrate(axis)); #if ENABLED(SENSORLESS_HOMING) planner.synchronize(); if (false #ifdef NORMAL_AXIS || axis != NORMAL_AXIS #endif ) safe_delay(200); // Short delay to allow belts to spring back #endif } #endif // Clear retracted status if homing the Z axis #if ENABLED(FWRETRACT) if (axis == Z_AXIS) fwretract.current_hop = 0.0; #endif if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("<<< homeaxis(", C(AXIS_CHAR(axis)), ")"); } // homeaxis() #endif // HAS_ENDSTOPS /** * Set an axis' current position to its home position (after homing). * * For Core and Cartesian robots this applies one-to-one when an * individual axis has been homed. * * DELTA should wait until all homing is done before setting the XYZ * current_position to home, because homing is a single operation. * In the case where the axis positions are trusted and previously * homed, DELTA could home to X or Y individually by moving either one * to the center. However, homing Z always homes XY and Z. * * SCARA should wait until all XY homing is done before setting the XY * current_position to home, because neither X nor Y is at home until * both are at home. Z can however be homed individually. * * Callers must sync the planner position after calling this! */ void set_axis_is_at_home(const AxisEnum axis) { if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM(">>> set_axis_is_at_home(", C(AXIS_CHAR(axis)), ")"); set_axis_trusted(axis); set_axis_homed(axis); #if ENABLED(DUAL_X_CARRIAGE) if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) { current_position.x = SUM_TERN(HAS_HOME_OFFSET, x_home_pos(active_extruder), home_offset.x); return; } #endif #if ANY(MORGAN_SCARA, AXEL_TPARA) scara_set_axis_is_at_home(axis); #elif ENABLED(DELTA) current_position[axis] = (axis == Z_AXIS) ? DIFF_TERN(USE_PROBE_FOR_Z_HOMING, delta_height, probe.offset.z) : base_home_pos(axis); #else current_position[axis] = SUM_TERN(HAS_HOME_OFFSET, base_home_pos(axis), home_offset[axis]); #endif /** * Z Probe Z Homing? Account for the probe's Z offset. */ #if HAS_BED_PROBE && Z_HOME_TO_MIN if (axis == Z_AXIS) { #if HOMING_Z_WITH_PROBE #if ENABLED(BD_SENSOR) safe_delay(100); current_position.z = bdl.read(); #else current_position.z -= probe.offset.z; #endif if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("*** Z homed with PROBE" TERN_(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN, " (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)") " ***\n> (M851 Z", probe.offset.z, ")"); #else if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("*** Z homed to ENDSTOP ***"); #endif } #endif TERN_(I2C_POSITION_ENCODERS, I2CPEM.homed(axis)); TERN_(BABYSTEP_DISPLAY_TOTAL, babystep.reset_total(axis)); TERN_(HAS_WORKSPACE_OFFSET, workspace_offset[axis] = 0); if (DEBUGGING(LEVELING)) { #if HAS_HOME_OFFSET DEBUG_ECHOLNPGM("> home_offset[", C(AXIS_CHAR(axis)), "] = ", home_offset[axis]); #endif DEBUG_POS("", current_position); DEBUG_ECHOLNPGM("<<< set_axis_is_at_home(", C(AXIS_CHAR(axis)), ")"); } } #if HAS_HOME_OFFSET /** * Set the home offset for an axis. */ void set_home_offset(const AxisEnum axis, const_float_t v) { home_offset[axis] = v; } #endif
2301_81045437/Marlin
Marlin/src/module/motion.cpp
C++
agpl-3.0
89,169
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 /** * motion.h * * High-level motion commands to feed the planner * Some of these methods may migrate to the planner class. */ #include "../inc/MarlinConfig.h" #if ALL(DWIN_LCD_PROUI, INDIVIDUAL_AXIS_HOMING_SUBMENU, MESH_BED_LEVELING) #include "../lcd/e3v2/proui/dwin.h" // for Z_POST_CLEARANCE #endif #if IS_SCARA #include "scara.h" #elif ENABLED(POLAR) #include "polar.h" #endif // Error margin to work around float imprecision constexpr float fslop = 0.0001; extern bool relative_mode; extern xyze_pos_t current_position, // High-level current tool position destination; // Destination for a move // G60/G61 Position Save and Return #if SAVED_POSITIONS extern uint8_t saved_slots[(SAVED_POSITIONS + 7) >> 3]; // TODO: Add support for HAS_I_AXIS extern xyze_pos_t stored_position[SAVED_POSITIONS]; #endif // Scratch space for a cartesian result extern xyz_pos_t cartes; // Until kinematics.cpp is created, declare this here #if IS_KINEMATIC extern abce_pos_t delta; #endif #if HAS_ABL_NOT_UBL extern feedRate_t xy_probe_feedrate_mm_s; #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s #elif defined(XY_PROBE_FEEDRATE) #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_FEEDRATE) #else #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE() #endif #if HAS_BED_PROBE constexpr feedRate_t z_probe_fast_mm_s = MMM_TO_MMS(Z_PROBE_FEEDRATE_FAST); #endif /** * Feed rates are often configured with mm/m * but the planner and stepper like mm/s units. */ constexpr xyz_feedrate_t homing_feedrate_mm_m = HOMING_FEEDRATE_MM_M; FORCE_INLINE feedRate_t homing_feedrate(const AxisEnum a) { float v = TERN0(HAS_Z_AXIS, homing_feedrate_mm_m.z); #if DISABLED(DELTA) NUM_AXIS_CODE( if (a == X_AXIS) v = homing_feedrate_mm_m.x, else if (a == Y_AXIS) v = homing_feedrate_mm_m.y, else if (a == Z_AXIS) v = homing_feedrate_mm_m.z, else if (a == I_AXIS) v = homing_feedrate_mm_m.i, else if (a == J_AXIS) v = homing_feedrate_mm_m.j, else if (a == K_AXIS) v = homing_feedrate_mm_m.k, else if (a == U_AXIS) v = homing_feedrate_mm_m.u, else if (a == V_AXIS) v = homing_feedrate_mm_m.v, else if (a == W_AXIS) v = homing_feedrate_mm_m.w ); #endif return MMM_TO_MMS(v); } feedRate_t get_homing_bump_feedrate(const AxisEnum axis); /** * The default feedrate for many moves, set by the most recent move */ extern feedRate_t feedrate_mm_s; /** * Feedrate scaling is applied to all G0/G1, G2/G3, and G5 moves */ extern int16_t feedrate_percentage; #define MMS_SCALED(V) ((V) * 0.01f * feedrate_percentage) // The active extruder (tool). Set with T<extruder> command. #if HAS_MULTI_EXTRUDER extern uint8_t active_extruder; #else constexpr uint8_t active_extruder = 0; #endif #if ENABLED(LCD_SHOW_E_TOTAL) extern float e_move_accumulator; #endif #ifdef __IMXRT1062__ #define DEFS_PROGMEM #else #define DEFS_PROGMEM PROGMEM #endif inline float pgm_read_any(const float *p) { return TERN(__IMXRT1062__, *p, pgm_read_float(p)); } inline int8_t pgm_read_any(const int8_t *p) { return TERN(__IMXRT1062__, *p, pgm_read_byte(p)); } #define XYZ_DEFS(T, NAME, OPT) \ inline T NAME(const AxisEnum axis) { \ static const XYZval<T> NAME##_P DEFS_PROGMEM = NUM_AXIS_ARRAY(X_##OPT, Y_##OPT, Z_##OPT, I_##OPT, J_##OPT, K_##OPT, U_##OPT, V_##OPT, W_##OPT); \ return pgm_read_any(&NAME##_P[axis]); \ } XYZ_DEFS(float, base_min_pos, MIN_POS); XYZ_DEFS(float, base_max_pos, MAX_POS); XYZ_DEFS(float, base_home_pos, HOME_POS); XYZ_DEFS(float, max_length, MAX_LENGTH); XYZ_DEFS(int8_t, home_dir, HOME_DIR); // Flags for rotational axes constexpr AxisFlags rotational{0 LOGICAL_AXIS_GANG( | 0, | 0, | 0, | 0, | (ENABLED(AXIS4_ROTATES)<<I_AXIS), | (ENABLED(AXIS5_ROTATES)<<J_AXIS), | (ENABLED(AXIS6_ROTATES)<<K_AXIS), | (ENABLED(AXIS7_ROTATES)<<U_AXIS), | (ENABLED(AXIS8_ROTATES)<<V_AXIS), | (ENABLED(AXIS9_ROTATES)<<W_AXIS)) }; inline float home_bump_mm(const AxisEnum axis) { static const xyz_pos_t home_bump_mm_P DEFS_PROGMEM = HOMING_BUMP_MM; return pgm_read_any(&home_bump_mm_P[axis]); } #if HAS_HOTEND_OFFSET extern xyz_pos_t hotend_offset[HOTENDS]; void reset_hotend_offsets(); #elif HOTENDS constexpr xyz_pos_t hotend_offset[HOTENDS] = { { TERN_(HAS_X_AXIS, 0) } }; #else constexpr xyz_pos_t hotend_offset[1] = { { TERN_(HAS_X_AXIS, 0) } }; #endif #if HAS_SOFTWARE_ENDSTOPS typedef struct { bool _enabled, _loose; bool enabled() { return _enabled && !_loose; } xyz_pos_t min, max; void get_manual_axis_limits(const AxisEnum axis, float &amin, float &amax) { amin = -100000; amax = 100000; // "No limits" #if HAS_SOFTWARE_ENDSTOPS if (enabled()) switch (axis) { #if HAS_X_AXIS case X_AXIS: TERN_(MIN_SOFTWARE_ENDSTOP_X, amin = min.x); TERN_(MAX_SOFTWARE_ENDSTOP_X, amax = max.x); break; #endif #if HAS_Y_AXIS case Y_AXIS: TERN_(MIN_SOFTWARE_ENDSTOP_Y, amin = min.y); TERN_(MAX_SOFTWARE_ENDSTOP_Y, amax = max.y); break; #endif #if HAS_Z_AXIS case Z_AXIS: TERN_(MIN_SOFTWARE_ENDSTOP_Z, amin = min.z); TERN_(MAX_SOFTWARE_ENDSTOP_Z, amax = max.z); break; #endif #if HAS_I_AXIS case I_AXIS: TERN_(MIN_SOFTWARE_ENDSTOP_I, amin = min.i); TERN_(MIN_SOFTWARE_ENDSTOP_I, amax = max.i); break; #endif #if HAS_J_AXIS case J_AXIS: TERN_(MIN_SOFTWARE_ENDSTOP_J, amin = min.j); TERN_(MIN_SOFTWARE_ENDSTOP_J, amax = max.j); break; #endif #if HAS_K_AXIS case K_AXIS: TERN_(MIN_SOFTWARE_ENDSTOP_K, amin = min.k); TERN_(MIN_SOFTWARE_ENDSTOP_K, amax = max.k); break; #endif #if HAS_U_AXIS case U_AXIS: TERN_(MIN_SOFTWARE_ENDSTOP_U, amin = min.u); TERN_(MIN_SOFTWARE_ENDSTOP_U, amax = max.u); break; #endif #if HAS_V_AXIS case V_AXIS: TERN_(MIN_SOFTWARE_ENDSTOP_V, amin = min.v); TERN_(MIN_SOFTWARE_ENDSTOP_V, amax = max.v); break; #endif #if HAS_W_AXIS case W_AXIS: TERN_(MIN_SOFTWARE_ENDSTOP_W, amin = min.w); TERN_(MIN_SOFTWARE_ENDSTOP_W, amax = max.w); break; #endif default: break; } #endif } } soft_endstops_t; extern soft_endstops_t soft_endstop; void apply_motion_limits(xyz_pos_t &target); void update_software_endstops(const AxisEnum axis #if HAS_HOTEND_OFFSET , const uint8_t old_tool_index=0, const uint8_t new_tool_index=0 #endif ); #define SET_SOFT_ENDSTOP_LOOSE(loose) (soft_endstop._loose = loose) #else // !HAS_SOFTWARE_ENDSTOPS typedef struct { bool enabled() { return false; } void get_manual_axis_limits(const AxisEnum axis, float &amin, float &amax) { // No limits amin = current_position[axis] - 1000; amax = current_position[axis] + 1000; } } soft_endstops_t; extern soft_endstops_t soft_endstop; #define apply_motion_limits(V) NOOP #define update_software_endstops(...) NOOP #define SET_SOFT_ENDSTOP_LOOSE(V) NOOP #endif // !HAS_SOFTWARE_ENDSTOPS void report_real_position(); void report_current_position(); void report_current_position_projected(); #if ENABLED(AUTO_REPORT_POSITION) #include "../libs/autoreport.h" struct PositionReport { static void report() { TERN(AUTO_REPORT_REAL_POSITION, report_real_position(), report_current_position_projected()); } }; extern AutoReporter<PositionReport> position_auto_reporter; #endif #if ANY(FULL_REPORT_TO_HOST_FEATURE, REALTIME_REPORTING_COMMANDS) #define HAS_GRBL_STATE 1 /** * Machine states for GRBL or TinyG */ enum M_StateEnum : uint8_t { M_INIT = 0, // 0 machine is initializing M_RESET, // 1 machine is ready for use M_ALARM, // 2 machine is in alarm state (soft shut down) M_IDLE, // 3 program stop or no more blocks (M0, M1, M60) M_END, // 4 program end via M2, M30 M_RUNNING, // 5 motion is running M_HOLD, // 6 motion is holding M_PROBE, // 7 probe cycle active M_CYCLING, // 8 machine is running (cycling) M_HOMING, // 9 machine is homing M_JOGGING, // 10 machine is jogging M_ERROR // 11 machine is in hard alarm state (shut down) }; extern M_StateEnum M_State_grbl; M_StateEnum grbl_state_for_marlin_state(); void report_current_grblstate_moving(); void report_current_position_moving(); #if ENABLED(FULL_REPORT_TO_HOST_FEATURE) inline void set_and_report_grblstate(const M_StateEnum state, const bool force=true) { if (force || M_State_grbl != state) { M_State_grbl = state; report_current_grblstate_moving(); } } #endif #if ENABLED(REALTIME_REPORTING_COMMANDS) void quickpause_stepper(); void quickresume_stepper(); #endif #endif float get_move_distance(const xyze_pos_t &diff OPTARG(HAS_ROTATIONAL_AXES, bool &is_cartesian_move)); void get_cartesian_from_steppers(); void set_current_from_steppers_for_axis(const AxisEnum axis); void quickstop_stepper(); /** * Set the planner/stepper positions directly from current_position with * no kinematic translation. Used for homing axes and cartesian/core syncing. */ void sync_plan_position(); #if HAS_EXTRUDERS void sync_plan_position_e(); #endif /** * Move the planner to the current position from wherever it last moved * (or from wherever it has been told it is located). */ void line_to_current_position(const_feedRate_t fr_mm_s=feedrate_mm_s); #if HAS_EXTRUDERS void unscaled_e_move(const_float_t length, const_feedRate_t fr_mm_s); #endif void prepare_line_to_destination(); void _internal_move_to_destination(const_feedRate_t fr_mm_s=0.0f OPTARG(IS_KINEMATIC, const bool is_fast=false)); inline void prepare_internal_move_to_destination(const_feedRate_t fr_mm_s=0.0f) { _internal_move_to_destination(fr_mm_s); } #if IS_KINEMATIC void prepare_fast_move_to_destination(const_feedRate_t scaled_fr_mm_s=MMS_SCALED(feedrate_mm_s)); inline void prepare_internal_fast_move_to_destination(const_feedRate_t fr_mm_s=0.0f) { _internal_move_to_destination(fr_mm_s, true); } #endif /** * Blocking movement and shorthand functions */ void do_blocking_move_to(NUM_AXIS_ARGS_(const_float_t) const_feedRate_t fr_mm_s=0.0f); void do_blocking_move_to(const xy_pos_t &raw, const_feedRate_t fr_mm_s=0.0f); void do_blocking_move_to(const xyz_pos_t &raw, const_feedRate_t fr_mm_s=0.0f); void do_blocking_move_to(const xyze_pos_t &raw, const_feedRate_t fr_mm_s=0.0f); #if HAS_X_AXIS void do_blocking_move_to_x(const_float_t rx, const_feedRate_t fr_mm_s=0.0f); #endif #if HAS_Y_AXIS void do_blocking_move_to_y(const_float_t ry, const_feedRate_t fr_mm_s=0.0f); #endif #if HAS_Z_AXIS void do_blocking_move_to_z(const_float_t rz, const_feedRate_t fr_mm_s=0.0f); #endif #if HAS_I_AXIS void do_blocking_move_to_i(const_float_t ri, const_feedRate_t fr_mm_s=0.0f); void do_blocking_move_to_xyz_i(const xyze_pos_t &raw, const_float_t i, const_feedRate_t fr_mm_s=0.0f); #endif #if HAS_J_AXIS void do_blocking_move_to_j(const_float_t rj, const_feedRate_t fr_mm_s=0.0f); void do_blocking_move_to_xyzi_j(const xyze_pos_t &raw, const_float_t j, const_feedRate_t fr_mm_s=0.0f); #endif #if HAS_K_AXIS void do_blocking_move_to_k(const_float_t rk, const_feedRate_t fr_mm_s=0.0f); void do_blocking_move_to_xyzij_k(const xyze_pos_t &raw, const_float_t k, const_feedRate_t fr_mm_s=0.0f); #endif #if HAS_U_AXIS void do_blocking_move_to_u(const_float_t ru, const_feedRate_t fr_mm_s=0.0f); void do_blocking_move_to_xyzijk_u(const xyze_pos_t &raw, const_float_t u, const_feedRate_t fr_mm_s=0.0f); #endif #if HAS_V_AXIS void do_blocking_move_to_v(const_float_t rv, const_feedRate_t fr_mm_s=0.0f); void do_blocking_move_to_xyzijku_v(const xyze_pos_t &raw, const_float_t v, const_feedRate_t fr_mm_s=0.0f); #endif #if HAS_W_AXIS void do_blocking_move_to_w(const float rw, const feedRate_t &fr_mm_s=0.0f); void do_blocking_move_to_xyzijkuv_w(const xyze_pos_t &raw, const float w, const feedRate_t &fr_mm_s=0.0f); #endif #if HAS_Y_AXIS void do_blocking_move_to_xy(const_float_t rx, const_float_t ry, const_feedRate_t fr_mm_s=0.0f); void do_blocking_move_to_xy(const xy_pos_t &raw, const_feedRate_t fr_mm_s=0.0f); FORCE_INLINE void do_blocking_move_to_xy(const xyz_pos_t &raw, const_feedRate_t fr_mm_s=0.0f) { do_blocking_move_to_xy(xy_pos_t(raw), fr_mm_s); } FORCE_INLINE void do_blocking_move_to_xy(const xyze_pos_t &raw, const_feedRate_t fr_mm_s=0.0f) { do_blocking_move_to_xy(xy_pos_t(raw), fr_mm_s); } #endif #if HAS_Z_AXIS void do_blocking_move_to_xy_z(const xy_pos_t &raw, const_float_t z, const_feedRate_t fr_mm_s=0.0f); FORCE_INLINE void do_blocking_move_to_xy_z(const xyz_pos_t &raw, const_float_t z, const_feedRate_t fr_mm_s=0.0f) { do_blocking_move_to_xy_z(xy_pos_t(raw), z, fr_mm_s); } FORCE_INLINE void do_blocking_move_to_xy_z(const xyze_pos_t &raw, const_float_t z, const_feedRate_t fr_mm_s=0.0f) { do_blocking_move_to_xy_z(xy_pos_t(raw), z, fr_mm_s); } #endif void remember_feedrate_scaling_off(); void restore_feedrate_and_scaling(); #if HAS_Z_AXIS #ifndef Z_POST_CLEARANCE // May be set by proui/dwin.h :-P #ifdef Z_AFTER_HOMING #define Z_POST_CLEARANCE Z_AFTER_HOMING #else #define Z_POST_CLEARANCE Z_CLEARANCE_FOR_HOMING #endif #endif void do_z_clearance(const_float_t zclear, const bool with_probe=true, const bool lower_allowed=false); void do_z_clearance_by(const_float_t zclear); void do_move_after_z_homing(); inline void do_z_post_clearance() { do_z_clearance(Z_POST_CLEARANCE); } #else inline void do_z_clearance(float, bool=true, bool=false) {} inline void do_z_clearance_by(float) {} #endif /** * Homing and Trusted Axes */ typedef bits_t(NUM_AXES) main_axes_bits_t; constexpr main_axes_bits_t main_axes_mask = _BV(NUM_AXES) - 1; void set_axis_is_at_home(const AxisEnum axis); #if HAS_ENDSTOPS /** * axes_homed * Flags that each linear axis was homed. * XYZ on cartesian, ABC on delta, ABZ on SCARA. * * axes_trusted * Flags that the position is trusted in each linear axis. Set when homed. * Cleared whenever a stepper powers off, potentially losing its position. */ extern main_axes_bits_t axes_homed, axes_trusted; void homeaxis(const AxisEnum axis); void set_axis_never_homed(const AxisEnum axis); main_axes_bits_t axes_should_home(main_axes_bits_t axes_mask=main_axes_mask); bool homing_needed_error(main_axes_bits_t axes_mask=main_axes_mask); #else constexpr main_axes_bits_t axes_homed = main_axes_mask, axes_trusted = main_axes_mask; // Zero-endstop machines are always homed and trusted inline void homeaxis(const AxisEnum axis) {} inline void set_axis_never_homed(const AxisEnum) {} inline main_axes_bits_t axes_should_home(main_axes_bits_t=main_axes_mask) { return 0; } inline bool homing_needed_error(main_axes_bits_t=main_axes_mask) { return false; } #endif inline void set_axis_unhomed(const AxisEnum axis) { TERN_(HAS_ENDSTOPS, CBI(axes_homed, axis)); } inline void set_axis_untrusted(const AxisEnum axis) { TERN_(HAS_ENDSTOPS, CBI(axes_trusted, axis)); } inline void set_all_unhomed() { TERN_(HAS_ENDSTOPS, axes_homed = axes_trusted = 0); } inline void set_axis_homed(const AxisEnum axis) { TERN_(HAS_ENDSTOPS, SBI(axes_homed, axis)); } inline void set_axis_trusted(const AxisEnum axis) { TERN_(HAS_ENDSTOPS, SBI(axes_trusted, axis)); } inline void set_all_homed() { TERN_(HAS_ENDSTOPS, axes_homed = axes_trusted = main_axes_mask); } inline bool axis_was_homed(const AxisEnum axis) { return TEST(axes_homed, axis); } inline bool axis_is_trusted(const AxisEnum axis) { return TEST(axes_trusted, axis); } inline bool axis_should_home(const AxisEnum axis) { return (axes_should_home() & _BV(axis)) != 0; } inline bool no_axes_homed() { return !axes_homed; } inline bool all_axes_homed() { return main_axes_mask == (axes_homed & main_axes_mask); } inline bool homing_needed() { return !all_axes_homed(); } inline bool all_axes_trusted() { return main_axes_mask == (axes_trusted & main_axes_mask); } void home_if_needed(const bool keeplev=false); #if ENABLED(NO_MOTION_BEFORE_HOMING) #define MOTION_CONDITIONS (IsRunning() && !homing_needed_error()) #else #define MOTION_CONDITIONS IsRunning() #endif #define BABYSTEP_ALLOWED() ((ENABLED(BABYSTEP_WITHOUT_HOMING) || all_axes_trusted()) && (ENABLED(BABYSTEP_ALWAYS_AVAILABLE) || printer_busy())) #if HAS_HOME_OFFSET extern xyz_pos_t home_offset; #endif /** * Workspace offsets */ #if HAS_WORKSPACE_OFFSET extern xyz_pos_t workspace_offset; #define NATIVE_TO_LOGICAL(POS, AXIS) ((POS) + workspace_offset[AXIS]) #define LOGICAL_TO_NATIVE(POS, AXIS) ((POS) - workspace_offset[AXIS]) FORCE_INLINE void toLogical(xy_pos_t &raw) { raw += workspace_offset; } FORCE_INLINE void toLogical(xyz_pos_t &raw) { raw += workspace_offset; } FORCE_INLINE void toLogical(xyze_pos_t &raw) { raw += workspace_offset; } FORCE_INLINE void toNative(xy_pos_t &raw) { raw -= workspace_offset; } FORCE_INLINE void toNative(xyz_pos_t &raw) { raw -= workspace_offset; } FORCE_INLINE void toNative(xyze_pos_t &raw) { raw -= workspace_offset; } #else #define NATIVE_TO_LOGICAL(POS, AXIS) (POS) #define LOGICAL_TO_NATIVE(POS, AXIS) (POS) FORCE_INLINE void toLogical(xy_pos_t&) {} FORCE_INLINE void toLogical(xyz_pos_t&) {} FORCE_INLINE void toLogical(xyze_pos_t&) {} FORCE_INLINE void toNative(xy_pos_t&) {} FORCE_INLINE void toNative(xyz_pos_t&) {} FORCE_INLINE void toNative(xyze_pos_t&) {} #endif #if HAS_X_AXIS #define LOGICAL_X_POSITION(POS) NATIVE_TO_LOGICAL(POS, X_AXIS) #define RAW_X_POSITION(POS) LOGICAL_TO_NATIVE(POS, X_AXIS) #endif #if HAS_Y_AXIS #define LOGICAL_Y_POSITION(POS) NATIVE_TO_LOGICAL(POS, Y_AXIS) #define RAW_Y_POSITION(POS) LOGICAL_TO_NATIVE(POS, Y_AXIS) #endif #if HAS_Z_AXIS #define LOGICAL_Z_POSITION(POS) NATIVE_TO_LOGICAL(POS, Z_AXIS) #define RAW_Z_POSITION(POS) LOGICAL_TO_NATIVE(POS, Z_AXIS) #endif #if HAS_I_AXIS #define LOGICAL_I_POSITION(POS) NATIVE_TO_LOGICAL(POS, I_AXIS) #define RAW_I_POSITION(POS) LOGICAL_TO_NATIVE(POS, I_AXIS) #endif #if HAS_J_AXIS #define LOGICAL_J_POSITION(POS) NATIVE_TO_LOGICAL(POS, J_AXIS) #define RAW_J_POSITION(POS) LOGICAL_TO_NATIVE(POS, J_AXIS) #endif #if HAS_K_AXIS #define LOGICAL_K_POSITION(POS) NATIVE_TO_LOGICAL(POS, K_AXIS) #define RAW_K_POSITION(POS) LOGICAL_TO_NATIVE(POS, K_AXIS) #endif #if HAS_U_AXIS #define LOGICAL_U_POSITION(POS) NATIVE_TO_LOGICAL(POS, U_AXIS) #define RAW_U_POSITION(POS) LOGICAL_TO_NATIVE(POS, U_AXIS) #endif #if HAS_V_AXIS #define LOGICAL_V_POSITION(POS) NATIVE_TO_LOGICAL(POS, V_AXIS) #define RAW_V_POSITION(POS) LOGICAL_TO_NATIVE(POS, V_AXIS) #endif #if HAS_W_AXIS #define LOGICAL_W_POSITION(POS) NATIVE_TO_LOGICAL(POS, W_AXIS) #define RAW_W_POSITION(POS) LOGICAL_TO_NATIVE(POS, W_AXIS) #endif /** * position_is_reachable family of functions */ #if IS_KINEMATIC // (DELTA or SCARA) #if HAS_SCARA_OFFSET extern abc_pos_t scara_home_offset; // A and B angular offsets, Z mm offset #endif // Return true if the given point is within the printable area bool position_is_reachable(const_float_t rx, const_float_t ry, const float inset=0); inline bool position_is_reachable(const xy_pos_t &pos, const float inset=0) { return position_is_reachable(pos.x, pos.y, inset); } #else // Return true if the given position is within the machine bounds. bool position_is_reachable(TERN_(HAS_X_AXIS, const_float_t rx) OPTARG(HAS_Y_AXIS, const_float_t ry)); inline bool position_is_reachable(const xy_pos_t &pos) { return position_is_reachable(TERN_(HAS_X_AXIS, pos.x) OPTARG(HAS_Y_AXIS, pos.y)); } #endif /** * Duplication mode */ #if HAS_DUPLICATION_MODE extern bool extruder_duplication_enabled; // Used in Dual X mode 2 #endif /** * Dual X Carriage */ #if ENABLED(DUAL_X_CARRIAGE) enum DualXMode : char { DXC_FULL_CONTROL_MODE, DXC_AUTO_PARK_MODE, DXC_DUPLICATION_MODE, DXC_MIRRORED_MODE }; extern DualXMode dual_x_carriage_mode; extern float inactive_extruder_x, // Used in mode 0 & 1 duplicate_extruder_x_offset; // Used in mode 2 & 3 extern xyz_pos_t raised_parked_position; // Used in mode 1 extern bool active_extruder_parked; // Used in mode 1, 2 & 3 extern millis_t delayed_move_time; // Used in mode 1 extern celsius_t duplicate_extruder_temp_offset; // Used in mode 2 & 3 extern bool idex_mirrored_mode; // Used in mode 3 FORCE_INLINE bool idex_is_duplicating() { return dual_x_carriage_mode >= DXC_DUPLICATION_MODE; } float x_home_pos(const uint8_t extruder); #define TOOL_X_HOME_DIR(T) ((T) ? 1 : -1) void set_duplication_enabled(const bool dupe, const int8_t tool_index=-1); void idex_set_mirrored_mode(const bool mirr); void idex_set_parked(const bool park=true); #else #if ENABLED(MULTI_NOZZLE_DUPLICATION) extern uint8_t duplication_e_mask; enum DualXMode : char { DXC_DUPLICATION_MODE = 2 }; FORCE_INLINE void set_duplication_enabled(const bool dupe) { extruder_duplication_enabled = dupe; } #endif #define TOOL_X_HOME_DIR(T) X_HOME_DIR #endif #if HAS_HOME_OFFSET void set_home_offset(const AxisEnum axis, const_float_t v); #endif #if USE_SENSORLESS struct sensorless_t; sensorless_t start_sensorless_homing_per_axis(const AxisEnum axis); void end_sensorless_homing_per_axis(const AxisEnum axis, sensorless_t enable_stealth); #endif
2301_81045437/Marlin
Marlin/src/module/motion.h
C++
agpl-3.0
23,154
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * planner.cpp * * Buffer movement commands and manage the acceleration profile plan * * Derived from Grbl * Copyright (c) 2009-2011 Simen Svale Skogsrud * * Ring buffer gleaned from wiring_serial library by David A. Mellis. * * Fast inverse function needed for Bézier interpolation for AVR * was designed, written and tested by Eduardo José Tagle, April 2018. * * Planner mathematics (Mathematica-style): * * Where: s == speed, a == acceleration, t == time, d == distance * * Basic definitions: * Speed[s_, a_, t_] := s + (a*t) * Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t] * * Distance to reach a specific speed with a constant acceleration: * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t] * d -> (m^2 - s^2) / (2 a) * * Speed after a given distance of travel with constant acceleration: * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t] * m -> Sqrt[2 a d + s^2] * * DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2] * * When to start braking (di) to reach a specified destination speed (s2) after * acceleration from initial speed s1 without ever reaching a plateau: * Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di] * di -> (2 a d - s1^2 + s2^2)/(4 a) * * We note, as an optimization, that if we have already calculated an * acceleration distance d1 from s1 to m and a deceration distance d2 * from m to s2 then * * d1 -> (m^2 - s1^2) / (2 a) * d2 -> (m^2 - s2^2) / (2 a) * di -> (d + d1 - d2) / 2 */ #include "planner.h" #include "stepper.h" #include "motion.h" #include "temperature.h" #if ENABLED(FT_MOTION) #include "ft_motion.h" #endif #include "../lcd/marlinui.h" #include "../gcode/parser.h" #include "../MarlinCore.h" #if HAS_LEVELING #include "../feature/bedlevel/bedlevel.h" #endif #if ENABLED(FILAMENT_WIDTH_SENSOR) #include "../feature/filwidth.h" #endif #if ENABLED(BARICUDA) #include "../feature/baricuda.h" #endif #if ENABLED(MIXING_EXTRUDER) #include "../feature/mixing.h" #endif #if ENABLED(AUTO_POWER_CONTROL) #include "../feature/power.h" #endif #if ENABLED(BACKLASH_COMPENSATION) #include "../feature/backlash.h" #endif #if ENABLED(CANCEL_OBJECTS) #include "../feature/cancel_object.h" #endif #if ENABLED(POWER_LOSS_RECOVERY) #include "../feature/powerloss.h" #endif #if HAS_CUTTER #include "../feature/spindle_laser.h" #endif // Delay for delivery of first block to the stepper ISR, if the queue contains 2 or // fewer movements. The delay is measured in milliseconds, and must be less than 250ms #define BLOCK_DELAY_NONE 0U #define BLOCK_DELAY_FOR_1ST_MOVE 100U Planner planner; // public: /** * A ring buffer of moves described in steps */ block_t Planner::block_buffer[BLOCK_BUFFER_SIZE]; volatile uint8_t Planner::block_buffer_head, // Index of the next block to be pushed Planner::block_buffer_nonbusy, // Index of the first non-busy block Planner::block_buffer_planned, // Index of the optimally planned block Planner::block_buffer_tail; // Index of the busy block, if any uint16_t Planner::cleaning_buffer_counter; // A counter to disable queuing of blocks uint8_t Planner::delay_before_delivering; // Delay block delivery so initial blocks in an empty queue may merge #if ENABLED(EDITABLE_STEPS_PER_UNIT) float Planner::mm_per_step[DISTINCT_AXES]; // (mm) Millimeters per step #else constexpr float PlannerSettings::axis_steps_per_mm[DISTINCT_AXES]; constexpr float Planner::mm_per_step[DISTINCT_AXES]; #endif planner_settings_t Planner::settings; // Initialized by settings.load() /** * Set up inline block variables * Set laser_power_floor based on SPEED_POWER_MIN to pevent a zero power output state with LASER_POWER_TRAP */ #if ENABLED(LASER_FEATURE) laser_state_t Planner::laser_inline; // Current state for blocks const uint8_t laser_power_floor = cutter.pct_to_ocr(SPEED_POWER_MIN); #endif uint32_t Planner::max_acceleration_steps_per_s2[DISTINCT_AXES]; // (steps/s^2) Derived from mm_per_s2 #if HAS_JUNCTION_DEVIATION float Planner::junction_deviation_mm; // (mm) M205 J #if HAS_LINEAR_E_JERK float Planner::max_e_jerk[DISTINCT_E]; // Calculated from junction_deviation_mm #endif #else // CLASSIC_JERK TERN(HAS_LINEAR_E_JERK, xyz_pos_t, xyze_pos_t) Planner::max_jerk; #endif #if ENABLED(SD_ABORT_ON_ENDSTOP_HIT) bool Planner::abort_on_endstop_hit = false; #endif #if ENABLED(DISTINCT_E_FACTORS) uint8_t Planner::last_extruder = 0; // Respond to extruder change #endif #if ENABLED(DIRECT_STEPPING) uint32_t Planner::last_page_step_rate = 0; AxisBits Planner::last_page_dir; // = 0 #endif #if HAS_EXTRUDERS int16_t Planner::flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100); // Extrusion factor for each extruder float Planner::e_factor[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0f); // The flow percentage and volumetric multiplier combine to scale E movement #endif #if DISABLED(NO_VOLUMETRICS) float Planner::filament_size[EXTRUDERS], // diameter of filament (in millimeters), typically around 1.75 or 2.85, 0 disables the volumetric calculations for the extruder Planner::volumetric_area_nominal = CIRCLE_AREA(float(DEFAULT_NOMINAL_FILAMENT_DIA) * 0.5f), // Nominal cross-sectional area Planner::volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner #endif #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT) float Planner::volumetric_extruder_limit[EXTRUDERS], // max mm^3/sec the extruder is able to handle Planner::volumetric_extruder_feedrate_limit[EXTRUDERS]; // pre calculated extruder feedrate limit based on volumetric_extruder_limit; pre-calculated to reduce computation in the planner #endif #ifdef MAX7219_DEBUG_SLOWDOWN uint8_t Planner::slowdown_count = 0; #endif #if HAS_LEVELING bool Planner::leveling_active = false; // Flag that auto bed leveling is enabled #if ABL_PLANAR matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level #endif #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) float Planner::z_fade_height, // Initialized by settings.load() Planner::inverse_z_fade_height, Planner::last_fade_z; #endif #else constexpr bool Planner::leveling_active; #endif #if ENABLED(SKEW_CORRECTION) skew_factor_t Planner::skew_factor; // Initialized by settings.load() #endif #if ENABLED(AUTOTEMP) autotemp_t Planner::autotemp = { AUTOTEMP_MIN, AUTOTEMP_MAX, AUTOTEMP_FACTOR, false }; #endif // private: xyze_long_t Planner::position{0}; uint32_t Planner::acceleration_long_cutoff; xyze_float_t Planner::previous_speed; float Planner::previous_nominal_speed; #if ENABLED(DISABLE_OTHER_EXTRUDERS) last_move_t Planner::extruder_last_move[E_STEPPERS] = { 0 }; #endif #ifdef XY_FREQUENCY_LIMIT int8_t Planner::xy_freq_limit_hz = XY_FREQUENCY_LIMIT; float Planner::xy_freq_min_speed_factor = (XY_FREQUENCY_MIN_PERCENT) * 0.01f; int32_t Planner::xy_freq_min_interval_us = LROUND(1000000.0f / (XY_FREQUENCY_LIMIT)); #endif #if ENABLED(LIN_ADVANCE) float Planner::extruder_advance_K[DISTINCT_E]; // Initialized by settings.load() #endif #if HAS_POSITION_FLOAT xyze_pos_t Planner::position_float; // Needed for accurate maths. Steps cannot be used! #endif #if IS_KINEMATIC xyze_pos_t Planner::position_cart; #endif #if HAS_WIRED_LCD volatile uint32_t Planner::block_buffer_runtime_us = 0; #endif /** * Class and Instance Methods */ Planner::Planner() { init(); } void Planner::init() { position.reset(); TERN_(HAS_POSITION_FLOAT, position_float.reset()); TERN_(IS_KINEMATIC, position_cart.reset()); previous_speed.reset(); previous_nominal_speed = 0; TERN_(ABL_PLANAR, bed_level_matrix.set_to_identity()); clear_block_buffer(); delay_before_delivering = 0; #if ENABLED(DIRECT_STEPPING) last_page_step_rate = 0; last_page_dir.reset(); #endif } #if ENABLED(S_CURVE_ACCELERATION) #ifdef __AVR__ /** * This routine returns 0x1000000 / d, getting the inverse as fast as possible. * A fast-converging iterative Newton-Raphson method can reach full precision in * just 1 iteration, and takes 211 cycles (worst case; the mean case is less, up * to 30 cycles for small divisors), instead of the 500 cycles a normal division * would take. * * Inspired by the following page: * https://stackoverflow.com/questions/27801397/newton-raphson-division-with-big-integers * * Suppose we want to calculate floor(2 ^ k / B) where B is a positive integer * Then, B must be <= 2^k, otherwise, the quotient is 0. * * The Newton - Raphson iteration for x = B / 2 ^ k yields: * q[n + 1] = q[n] * (2 - q[n] * B / 2 ^ k) * * This can be rearranged to: * q[n + 1] = q[n] * (2 ^ (k + 1) - q[n] * B) >> k * * Each iteration requires only integer multiplications and bit shifts. * It doesn't necessarily converge to floor(2 ^ k / B) but in the worst case * it eventually alternates between floor(2 ^ k / B) and ceil(2 ^ k / B). * So it checks for this case and extracts floor(2 ^ k / B). * * A simple but important optimization for this approach is to truncate * multiplications (i.e., calculate only the higher bits of the product) in the * early iterations of the Newton - Raphson method. This is done so the results * of the early iterations are far from the quotient. Then it doesn't matter if * they are done inaccurately. * It's important to pick a good starting value for x. Knowing how many * digits the divisor has, it can be estimated: * * 2^k / x = 2 ^ log2(2^k / x) * 2^k / x = 2 ^(log2(2^k)-log2(x)) * 2^k / x = 2 ^(k*log2(2)-log2(x)) * 2^k / x = 2 ^ (k-log2(x)) * 2^k / x >= 2 ^ (k-floor(log2(x))) * floor(log2(x)) is simply the index of the most significant bit set. * * If this estimation can be improved even further the number of iterations can be * reduced a lot, saving valuable execution time. * The paper "Software Integer Division" by Thomas L.Rodeheffer, Microsoft * Research, Silicon Valley,August 26, 2008, available at * https://www.microsoft.com/en-us/research/wp-content/uploads/2008/08/tr-2008-141.pdf * suggests, for its integer division algorithm, using a table to supply the first * 8 bits of precision, then, due to the quadratic convergence nature of the * Newton-Raphon iteration, just 2 iterations should be enough to get maximum * precision of the division. * By precomputing values of inverses for small denominator values, just one * Newton-Raphson iteration is enough to reach full precision. * This code uses the top 9 bits of the denominator as index. * * The AVR assembly function implements this C code using the data below: * * // For small divisors, it is best to directly retrieve the results * if (d <= 110) return pgm_read_dword(&small_inv_tab[d]); * * // Compute initial estimation of 0x1000000/x - * // Get most significant bit set on divider * uint8_t idx = 0; * uint32_t nr = d; * if (!(nr & 0xFF0000)) { * nr <<= 8; idx += 8; * if (!(nr & 0xFF0000)) { nr <<= 8; idx += 8; } * } * if (!(nr & 0xF00000)) { nr <<= 4; idx += 4; } * if (!(nr & 0xC00000)) { nr <<= 2; idx += 2; } * if (!(nr & 0x800000)) { nr <<= 1; idx += 1; } * * // Isolate top 9 bits of the denominator, to be used as index into the initial estimation table * uint32_t tidx = nr >> 15, // top 9 bits. bit8 is always set * ie = inv_tab[tidx & 0xFF] + 256, // Get the table value. bit9 is always set * x = idx <= 8 ? (ie >> (8 - idx)) : (ie << (idx - 8)); // Position the estimation at the proper place * * x = uint32_t((x * uint64_t(_BV(25) - x * d)) >> 24); // Refine estimation by newton-raphson. 1 iteration is enough * const uint32_t r = _BV(24) - x * d; // Estimate remainder * if (r >= d) x++; // Check whether to adjust result * return uint32_t(x); // x holds the proper estimation */ static uint32_t get_period_inverse(uint32_t d) { static const uint8_t inv_tab[256] PROGMEM = { 255,253,252,250,248,246,244,242,240,238,236,234,233,231,229,227, 225,224,222,220,218,217,215,213,212,210,208,207,205,203,202,200, 199,197,195,194,192,191,189,188,186,185,183,182,180,179,178,176, 175,173,172,170,169,168,166,165,164,162,161,160,158,157,156,154, 153,152,151,149,148,147,146,144,143,142,141,139,138,137,136,135, 134,132,131,130,129,128,127,126,125,123,122,121,120,119,118,117, 116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101, 100,99,98,97,96,95,94,93,92,91,90,89,88,88,87,86, 85,84,83,82,81,80,80,79,78,77,76,75,74,74,73,72, 71,70,70,69,68,67,66,66,65,64,63,62,62,61,60,59, 59,58,57,56,56,55,54,53,53,52,51,50,50,49,48,48, 47,46,46,45,44,43,43,42,41,41,40,39,39,38,37,37, 36,35,35,34,33,33,32,32,31,30,30,29,28,28,27,27, 26,25,25,24,24,23,22,22,21,21,20,19,19,18,18,17, 17,16,15,15,14,14,13,13,12,12,11,10,10,9,9,8, 8,7,7,6,6,5,5,4,4,3,3,2,2,1,0,0 }; // For small denominators, it is cheaper to directly store the result. // For bigger ones, just ONE Newton-Raphson iteration is enough to get // maximum precision we need static const uint32_t small_inv_tab[111] PROGMEM = { 16777216,16777216,8388608,5592405,4194304,3355443,2796202,2396745,2097152,1864135,1677721,1525201,1398101,1290555,1198372,1118481, 1048576,986895,932067,883011,838860,798915,762600,729444,699050,671088,645277,621378,599186,578524,559240,541200, 524288,508400,493447,479349,466033,453438,441505,430185,419430,409200,399457,390167,381300,372827,364722,356962, 349525,342392,335544,328965,322638,316551,310689,305040,299593,294337,289262,284359,279620,275036,270600,266305, 262144,258111,254200,250406,246723,243148,239674,236298,233016,229824,226719,223696,220752,217885,215092,212369, 209715,207126,204600,202135,199728,197379,195083,192841,190650,188508,186413,184365,182361,180400,178481,176602, 174762,172960,171196,169466,167772,166111,164482,162885,161319,159783,158275,156796,155344,153919,152520 }; // For small divisors, it is best to directly retrieve the results if (d <= 110) return pgm_read_dword(&small_inv_tab[d]); uint8_t r8 = d & 0xFF, r9 = (d >> 8) & 0xFF, r10 = (d >> 16) & 0xFF, r2,r3,r4,r5,r6,r7,r11,r12,r13,r14,r15,r16,r17,r18; const uint8_t *ptab = inv_tab; __asm__ __volatile__( // %8:%7:%6 = interval // r31:r30: MUST be those registers, and they must point to the inv_tab A("clr %13") // %13 = 0 // Now we must compute // result = 0xFFFFFF / d // %8:%7:%6 = interval // %16:%15:%14 = nr // %13 = 0 // A plain division of 24x24 bits should take 388 cycles to complete. We will // use Newton-Raphson for the calculation, and will strive to get way less cycles // for the same result - Using C division, it takes 500cycles to complete . A("clr %3") // idx = 0 A("mov %14,%6") A("mov %15,%7") A("mov %16,%8") // nr = interval A("tst %16") // nr & 0xFF0000 == 0 ? A("brne 2f") // No, skip this A("mov %16,%15") A("mov %15,%14") // nr <<= 8, %14 not needed A("subi %3,-8") // idx += 8 A("tst %16") // nr & 0xFF0000 == 0 ? A("brne 2f") // No, skip this A("mov %16,%15") // nr <<= 8, %14 not needed A("clr %15") // We clear %14 A("subi %3,-8") // idx += 8 // here %16 != 0 and %16:%15 contains at least 9 MSBits, or both %16:%15 are 0 L("2") A("cpi %16,0x10") // (nr & 0xF00000) == 0 ? A("brcc 3f") // No, skip this A("swap %15") // Swap nybbles A("swap %16") // Swap nybbles. Low nybble is 0 A("mov %14, %15") A("andi %14,0x0F") // Isolate low nybble A("andi %15,0xF0") // Keep proper nybble in %15 A("or %16, %14") // %16:%15 <<= 4 A("subi %3,-4") // idx += 4 L("3") A("cpi %16,0x40") // (nr & 0xC00000) == 0 ? A("brcc 4f") // No, skip this A("add %15,%15") A("adc %16,%16") A("add %15,%15") A("adc %16,%16") // %16:%15 <<= 2 A("subi %3,-2") // idx += 2 L("4") A("cpi %16,0x80") // (nr & 0x800000) == 0 ? A("brcc 5f") // No, skip this A("add %15,%15") A("adc %16,%16") // %16:%15 <<= 1 A("inc %3") // idx += 1 // Now %16:%15 contains its MSBit set to 1, or %16:%15 is == 0. We are now absolutely sure // we have at least 9 MSBits available to enter the initial estimation table L("5") A("add %15,%15") A("adc %16,%16") // %16:%15 = tidx = (nr <<= 1), we lose the top MSBit (always set to 1, %16 is the index into the inverse table) A("add r30,%16") // Only use top 8 bits A("adc r31,%13") // r31:r30 = inv_tab + (tidx) A("lpm %14, Z") // %14 = inv_tab[tidx] A("ldi %15, 1") // %15 = 1 %15:%14 = inv_tab[tidx] + 256 // We must scale the approximation to the proper place A("clr %16") // %16 will always be 0 here A("subi %3,8") // idx == 8 ? A("breq 6f") // yes, no need to scale A("brcs 7f") // If C=1, means idx < 8, result was negative! // idx > 8, now %3 = idx - 8. We must perform a left shift. idx range:[1-8] A("sbrs %3,0") // shift by 1bit position? A("rjmp 8f") // No A("add %14,%14") A("adc %15,%15") // %15:16 <<= 1 L("8") A("sbrs %3,1") // shift by 2bit position? A("rjmp 9f") // No A("add %14,%14") A("adc %15,%15") A("add %14,%14") A("adc %15,%15") // %15:16 <<= 1 L("9") A("sbrs %3,2") // shift by 4bits position? A("rjmp 16f") // No A("swap %15") // Swap nybbles. lo nybble of %15 will always be 0 A("swap %14") // Swap nybbles A("mov %12,%14") A("andi %12,0x0F") // isolate low nybble A("andi %14,0xF0") // and clear it A("or %15,%12") // %15:%16 <<= 4 L("16") A("sbrs %3,3") // shift by 8bits position? A("rjmp 6f") // No, we are done A("mov %16,%15") A("mov %15,%14") A("clr %14") A("jmp 6f") // idx < 8, now %3 = idx - 8. Get the count of bits L("7") A("neg %3") // %3 = -idx = count of bits to move right. idx range:[1...8] A("sbrs %3,0") // shift by 1 bit position ? A("rjmp 10f") // No, skip it A("asr %15") // (bit7 is always 0 here) A("ror %14") L("10") A("sbrs %3,1") // shift by 2 bit position ? A("rjmp 11f") // No, skip it A("asr %15") // (bit7 is always 0 here) A("ror %14") A("asr %15") // (bit7 is always 0 here) A("ror %14") L("11") A("sbrs %3,2") // shift by 4 bit position ? A("rjmp 12f") // No, skip it A("swap %15") // Swap nybbles A("andi %14, 0xF0") // Lose the lowest nybble A("swap %14") // Swap nybbles. Upper nybble is 0 A("or %14,%15") // Pass nybble from upper byte A("andi %15, 0x0F") // And get rid of that nybble L("12") A("sbrs %3,3") // shift by 8 bit position ? A("rjmp 6f") // No, skip it A("mov %14,%15") A("clr %15") L("6") // %16:%15:%14 = initial estimation of 0x1000000 / d // Now, we must refine the estimation present on %16:%15:%14 using 1 iteration // of Newton-Raphson. As it has a quadratic convergence, 1 iteration is enough // to get more than 18bits of precision (the initial table lookup gives 9 bits of // precision to start from). 18bits of precision is all what is needed here for result // %8:%7:%6 = d = interval // %16:%15:%14 = x = initial estimation of 0x1000000 / d // %13 = 0 // %3:%2:%1:%0 = working accumulator // Compute 1<<25 - x*d. Result should never exceed 25 bits and should always be positive A("clr %0") A("clr %1") A("clr %2") A("ldi %3,2") // %3:%2:%1:%0 = 0x2000000 A("mul %6,%14") // r1:r0 = LO(d) * LO(x) A("sub %0,r0") A("sbc %1,r1") A("sbc %2,%13") A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * LO(x) A("mul %7,%14") // r1:r0 = MI(d) * LO(x) A("sub %1,r0") A("sbc %2,r1" ) A("sbc %3,%13") // %3:%2:%1:%0 -= MI(d) * LO(x) << 8 A("mul %8,%14") // r1:r0 = HI(d) * LO(x) A("sub %2,r0") A("sbc %3,r1") // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16 A("mul %6,%15") // r1:r0 = LO(d) * MI(x) A("sub %1,r0") A("sbc %2,r1") A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * MI(x) << 8 A("mul %7,%15") // r1:r0 = MI(d) * MI(x) A("sub %2,r0") A("sbc %3,r1") // %3:%2:%1:%0 -= MI(d) * MI(x) << 16 A("mul %8,%15") // r1:r0 = HI(d) * MI(x) A("sub %3,r0") // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24 A("mul %6,%16") // r1:r0 = LO(d) * HI(x) A("sub %2,r0") A("sbc %3,r1") // %3:%2:%1:%0 -= LO(d) * HI(x) << 16 A("mul %7,%16") // r1:r0 = MI(d) * HI(x) A("sub %3,r0") // %3:%2:%1:%0 -= MI(d) * HI(x) << 24 // %3:%2:%1:%0 = (1<<25) - x*d [169] // We need to multiply that result by x, and we are only interested in the top 24bits of that multiply // %16:%15:%14 = x = initial estimation of 0x1000000 / d // %3:%2:%1:%0 = (1<<25) - x*d = acc // %13 = 0 // result = %11:%10:%9:%5:%4 A("mul %14,%0") // r1:r0 = LO(x) * LO(acc) A("mov %4,r1") A("clr %5") A("clr %9") A("clr %10") A("clr %11") // %11:%10:%9:%5:%4 = LO(x) * LO(acc) >> 8 A("mul %15,%0") // r1:r0 = MI(x) * LO(acc) A("add %4,r0") A("adc %5,r1") A("adc %9,%13") A("adc %10,%13") A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * LO(acc) A("mul %16,%0") // r1:r0 = HI(x) * LO(acc) A("add %5,r0") A("adc %9,r1") A("adc %10,%13") A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * LO(acc) << 8 A("mul %14,%1") // r1:r0 = LO(x) * MIL(acc) A("add %4,r0") A("adc %5,r1") A("adc %9,%13") A("adc %10,%13") A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * MIL(acc) A("mul %15,%1") // r1:r0 = MI(x) * MIL(acc) A("add %5,r0") A("adc %9,r1") A("adc %10,%13") A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 8 A("mul %16,%1") // r1:r0 = HI(x) * MIL(acc) A("add %9,r0") A("adc %10,r1") A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 16 A("mul %14,%2") // r1:r0 = LO(x) * MIH(acc) A("add %5,r0") A("adc %9,r1") A("adc %10,%13") A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * MIH(acc) << 8 A("mul %15,%2") // r1:r0 = MI(x) * MIH(acc) A("add %9,r0") A("adc %10,r1") A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 16 A("mul %16,%2") // r1:r0 = HI(x) * MIH(acc) A("add %10,r0") A("adc %11,r1") // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 24 A("mul %14,%3") // r1:r0 = LO(x) * HI(acc) A("add %9,r0") A("adc %10,r1") A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * HI(acc) << 16 A("mul %15,%3") // r1:r0 = MI(x) * HI(acc) A("add %10,r0") A("adc %11,r1") // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 24 A("mul %16,%3") // r1:r0 = HI(x) * HI(acc) A("add %11,r0") // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 32 // At this point, %11:%10:%9 contains the new estimation of x. // Finally, we must correct the result. Estimate remainder as // (1<<24) - x*d // %11:%10:%9 = x // %8:%7:%6 = d = interval" "\n\t" A("ldi %3,1") A("clr %2") A("clr %1") A("clr %0") // %3:%2:%1:%0 = 0x1000000 A("mul %6,%9") // r1:r0 = LO(d) * LO(x) A("sub %0,r0") A("sbc %1,r1") A("sbc %2,%13") A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * LO(x) A("mul %7,%9") // r1:r0 = MI(d) * LO(x) A("sub %1,r0") A("sbc %2,r1") A("sbc %3,%13") // %3:%2:%1:%0 -= MI(d) * LO(x) << 8 A("mul %8,%9") // r1:r0 = HI(d) * LO(x) A("sub %2,r0") A("sbc %3,r1") // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16 A("mul %6,%10") // r1:r0 = LO(d) * MI(x) A("sub %1,r0") A("sbc %2,r1") A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * MI(x) << 8 A("mul %7,%10") // r1:r0 = MI(d) * MI(x) A("sub %2,r0") A("sbc %3,r1") // %3:%2:%1:%0 -= MI(d) * MI(x) << 16 A("mul %8,%10") // r1:r0 = HI(d) * MI(x) A("sub %3,r0") // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24 A("mul %6,%11") // r1:r0 = LO(d) * HI(x) A("sub %2,r0") A("sbc %3,r1") // %3:%2:%1:%0 -= LO(d) * HI(x) << 16 A("mul %7,%11") // r1:r0 = MI(d) * HI(x) A("sub %3,r0") // %3:%2:%1:%0 -= MI(d) * HI(x) << 24 // %3:%2:%1:%0 = r = (1<<24) - x*d // %8:%7:%6 = d = interval // Perform the final correction A("sub %0,%6") A("sbc %1,%7") A("sbc %2,%8") // r -= d A("brcs 14f") // if ( r >= d) // %11:%10:%9 = x A("ldi %3,1") A("add %9,%3") A("adc %10,%13") A("adc %11,%13") // x++ L("14") // Estimation is done. %11:%10:%9 = x A("clr __zero_reg__") // Make C runtime happy // [211 cycles total] : "=r" (r2), "=r" (r3), "=r" (r4), "=d" (r5), "=r" (r6), "=r" (r7), "+r" (r8), "+r" (r9), "+r" (r10), "=d" (r11), "=r" (r12), "=r" (r13), "=d" (r14), "=d" (r15), "=d" (r16), "=d" (r17), "=d" (r18), "+z" (ptab) : : "r0", "r1", "cc" ); // Return the result return r11 | (uint16_t(r12) << 8) | (uint32_t(r13) << 16); } #else // All other 32-bit MPUs can easily do inverse using hardware division, // so we don't need to reduce precision or to use assembly language at all. // This routine, for all other archs, returns 0x100000000 / d ~= 0xFFFFFFFF / d FORCE_INLINE static uint32_t get_period_inverse(const uint32_t d) { return d ? 0xFFFFFFFF / d : 0xFFFFFFFF; } #endif #endif #define MINIMAL_STEP_RATE 120 /** * Get the current block for processing * and mark the block as busy. * Return nullptr if the buffer is empty * or if there is a first-block delay. * * WARNING: Called from Stepper ISR context! */ block_t* Planner::get_current_block() { // Get the number of moves in the planner queue so far const uint8_t nr_moves = movesplanned(); // If there are any moves queued ... if (nr_moves) { // If there is still delay of delivery of blocks running, decrement it if (delay_before_delivering) { --delay_before_delivering; // If the number of movements queued is less than 3, and there is still time // to wait, do not deliver anything if (nr_moves < 3 && delay_before_delivering) return nullptr; delay_before_delivering = 0; } // If we are here, there is no excuse to deliver the block block_t * const block = &block_buffer[block_buffer_tail]; // No trapezoid calculated? Don't execute yet. if (block->flag.recalculate) return nullptr; // We can't be sure how long an active block will take, so don't count it. TERN_(HAS_WIRED_LCD, block_buffer_runtime_us -= block->segment_time_us); // As this block is busy, advance the nonbusy block pointer block_buffer_nonbusy = next_block_index(block_buffer_tail); // Push block_buffer_planned pointer, if encountered. if (block_buffer_tail == block_buffer_planned) block_buffer_planned = block_buffer_nonbusy; // Return the block return block; } // The queue became empty TERN_(HAS_WIRED_LCD, clear_block_buffer_runtime()); // paranoia. Buffer is empty now - so reset accumulated time to zero. return nullptr; } /** * Calculate trapezoid parameters, multiplying the entry- and exit-speeds * by the provided factors. ** * ############ VERY IMPORTANT ############ * NOTE that the PRECONDITION to call this function is that the block is * NOT BUSY and it is marked as RECALCULATE. That WARRANTIES the Stepper ISR * is not and will not use the block while we modify it, so it is safe to * alter its values. */ void Planner::calculate_trapezoid_for_block(block_t * const block, const_float_t entry_factor, const_float_t exit_factor) { uint32_t initial_rate = CEIL(block->nominal_rate * entry_factor), final_rate = CEIL(block->nominal_rate * exit_factor); // (steps per second) // Limit minimal step rate (Otherwise the timer will overflow.) NOLESS(initial_rate, uint32_t(MINIMAL_STEP_RATE)); NOLESS(final_rate, uint32_t(MINIMAL_STEP_RATE)); #if ANY(S_CURVE_ACCELERATION, LIN_ADVANCE) // If we have some plateau time, the cruise rate will be the nominal rate uint32_t cruise_rate = block->nominal_rate; #endif // Steps for acceleration, plateau and deceleration int32_t plateau_steps = block->step_event_count; uint32_t accelerate_steps = 0, decelerate_steps = 0; const int32_t accel = block->acceleration_steps_per_s2; float inverse_accel = 0.0f; if (accel != 0) { inverse_accel = 1.0f / accel; const float half_inverse_accel = 0.5f * inverse_accel, nominal_rate_sq = sq(float(block->nominal_rate)), // Steps required for acceleration, deceleration to/from nominal rate decelerate_steps_float = half_inverse_accel * (nominal_rate_sq - sq(float(final_rate))); float accelerate_steps_float = half_inverse_accel * (nominal_rate_sq - sq(float(initial_rate))); accelerate_steps = CEIL(accelerate_steps_float); decelerate_steps = FLOOR(decelerate_steps_float); // Steps between acceleration and deceleration, if any plateau_steps -= accelerate_steps + decelerate_steps; // Does accelerate_steps + decelerate_steps exceed step_event_count? // Then we can't possibly reach the nominal rate, there will be no cruising. // Calculate accel / braking time in order to reach the final_rate exactly // at the end of this block. if (plateau_steps < 0) { accelerate_steps_float = CEIL((block->step_event_count + accelerate_steps_float - decelerate_steps_float) * 0.5f); accelerate_steps = _MIN(uint32_t(_MAX(accelerate_steps_float, 0)), block->step_event_count); decelerate_steps = block->step_event_count - accelerate_steps; #if ANY(S_CURVE_ACCELERATION, LIN_ADVANCE) // We won't reach the cruising rate. Let's calculate the speed we will reach cruise_rate = final_speed(initial_rate, accel, accelerate_steps); #endif } } #if ENABLED(S_CURVE_ACCELERATION) const float rate_factor = inverse_accel * (STEPPER_TIMER_RATE); // Jerk controlled speed requires to express speed versus time, NOT steps uint32_t acceleration_time = rate_factor * float(cruise_rate - initial_rate), deceleration_time = rate_factor * float(cruise_rate - final_rate), // And to offload calculations from the ISR, we also calculate the inverse of those times here acceleration_time_inverse = get_period_inverse(acceleration_time), deceleration_time_inverse = get_period_inverse(deceleration_time); #endif // Store new block parameters block->accelerate_until = accelerate_steps; block->decelerate_after = block->step_event_count - decelerate_steps; block->initial_rate = initial_rate; #if ENABLED(S_CURVE_ACCELERATION) block->acceleration_time = acceleration_time; block->deceleration_time = deceleration_time; block->acceleration_time_inverse = acceleration_time_inverse; block->deceleration_time_inverse = deceleration_time_inverse; block->cruise_rate = cruise_rate; #endif block->final_rate = final_rate; #if ENABLED(LIN_ADVANCE) if (block->la_advance_rate) { const float comp = extruder_advance_K[E_INDEX_N(block->extruder)] * block->steps.e / block->step_event_count; block->max_adv_steps = cruise_rate * comp; block->final_adv_steps = final_rate * comp; } #endif #if ENABLED(LASER_POWER_TRAP) /** * Laser Trapezoid Calculations * * Approximate the trapezoid with the laser, incrementing the power every `trap_ramp_entry_incr` * steps while accelerating, and decrementing the power every `trap_ramp_exit_decr` while decelerating, * to keep power proportional to feedrate. Laser power trap will reduce the initial power to no less * than the laser_power_floor value. Based on the number of calculated accel/decel steps the power is * distributed over the trapezoid entry- and exit-ramp steps. * * trap_ramp_active_pwr - The active power is initially set at a reduced level factor of initial * power / accel steps and will be additively incremented using a trap_ramp_entry_incr value for each * accel step processed later in the stepper code. The trap_ramp_exit_decr value is calculated as * power / decel steps and is also adjusted to no less than the power floor. * * If the power == 0 the inline mode variables need to be set to zero to prevent stepper processing. * The method allows for simpler non-powered moves like G0 or G28. * * Laser Trap Power works for all Jerk and Curve modes; however Arc-based moves will have issues since * the segments are usually too small. */ if (cutter.cutter_mode == CUTTER_MODE_CONTINUOUS) { if (planner.laser_inline.status.isPowered && planner.laser_inline.status.isEnabled) { if (block->laser.power > 0) { NOLESS(block->laser.power, laser_power_floor); block->laser.trap_ramp_active_pwr = (block->laser.power - laser_power_floor) * (initial_rate / float(block->nominal_rate)) + laser_power_floor; block->laser.trap_ramp_entry_incr = (block->laser.power - block->laser.trap_ramp_active_pwr) / accelerate_steps; float laser_pwr = block->laser.power * (final_rate / float(block->nominal_rate)); NOLESS(laser_pwr, laser_power_floor); block->laser.trap_ramp_exit_decr = (block->laser.power - laser_pwr) / decelerate_steps; #if ENABLED(DEBUG_LASER_TRAP) SERIAL_ECHO_MSG("lp:",block->laser.power); SERIAL_ECHO_MSG("as:",accelerate_steps); SERIAL_ECHO_MSG("ds:",decelerate_steps); SERIAL_ECHO_MSG("p.trap:",block->laser.trap_ramp_active_pwr); SERIAL_ECHO_MSG("p.incr:",block->laser.trap_ramp_entry_incr); SERIAL_ECHO_MSG("p.decr:",block->laser.trap_ramp_exit_decr); #endif } else { block->laser.trap_ramp_active_pwr = 0; block->laser.trap_ramp_entry_incr = 0; block->laser.trap_ramp_exit_decr = 0; } } } #endif // LASER_POWER_TRAP } /** * PLANNER SPEED DEFINITION * +--------+ <- current->nominal_speed * / \ * current->entry_speed -> + \ * | + <- next->entry_speed (aka exit speed) * +-------------+ * time --> * * Recalculates the motion plan according to the following basic guidelines: * * 1. Go over every feasible block sequentially in reverse order and calculate the junction speeds * (i.e. current->entry_speed) such that: * a. No junction speed exceeds the pre-computed maximum junction speed limit or nominal speeds of * neighboring blocks. * b. A block entry speed cannot exceed one reverse-computed from its exit speed (next->entry_speed) * with a maximum allowable deceleration over the block travel distance. * c. The last (or newest appended) block is planned from a complete stop (an exit speed of zero). * 2. Go over every block in chronological (forward) order and dial down junction speed values if * a. The exit speed exceeds the one forward-computed from its entry speed with the maximum allowable * acceleration over the block travel distance. * * When these stages are complete, the planner will have maximized the velocity profiles throughout the all * of the planner blocks, where every block is operating at its maximum allowable acceleration limits. In * other words, for all of the blocks in the planner, the plan is optimal and no further speed improvements * are possible. If a new block is added to the buffer, the plan is recomputed according to the said * guidelines for a new optimal plan. * * To increase computational efficiency of these guidelines, a set of planner block pointers have been * created to indicate stop-compute points for when the planner guidelines cannot logically make any further * changes or improvements to the plan when in normal operation and new blocks are streamed and added to the * planner buffer. For example, if a subset of sequential blocks in the planner have been planned and are * bracketed by junction velocities at their maximums (or by the first planner block as well), no new block * added to the planner buffer will alter the velocity profiles within them. So we no longer have to compute * them. Or, if a set of sequential blocks from the first block in the planner (or a optimal stop-compute * point) are all accelerating, they are all optimal and can not be altered by a new block added to the * planner buffer, as this will only further increase the plan speed to chronological blocks until a maximum * junction velocity is reached. However, if the operational conditions of the plan changes from infrequently * used feed holds or feedrate overrides, the stop-compute pointers will be reset and the entire plan is * recomputed as stated in the general guidelines. * * Planner buffer index mapping: * - block_buffer_tail: Points to the beginning of the planner buffer. First to be executed or being executed. * - block_buffer_head: Points to the buffer block after the last block in the buffer. Used to indicate whether * the buffer is full or empty. As described for standard ring buffers, this block is always empty. * - block_buffer_planned: Points to the first buffer block after the last optimally planned block for normal * streaming operating conditions. Use for planning optimizations by avoiding recomputing parts of the * planner buffer that don't change with the addition of a new block, as describe above. In addition, * this block can never be less than block_buffer_tail and will always be pushed forward and maintain * this requirement when encountered by the Planner::release_current_block() routine during a cycle. * * NOTE: Since the planner only computes on what's in the planner buffer, some motions with many short * segments (e.g., complex curves) may seem to move slowly. This is because there simply isn't * enough combined distance traveled in the entire buffer to accelerate up to the nominal speed and * then decelerate to a complete stop at the end of the buffer, as stated by the guidelines. If this * happens and becomes an annoyance, there are a few simple solutions: * * - Maximize the machine acceleration. The planner will be able to compute higher velocity profiles * within the same combined distance. * * - Maximize line motion(s) distance per block to a desired tolerance. The more combined distance the * planner has to use, the faster it can go. * * - Maximize the planner buffer size. This also will increase the combined distance for the planner to * compute over. It also increases the number of computations the planner has to perform to compute an * optimal plan, so select carefully. * * - Use G2/G3 arcs instead of many short segments. Arcs inform the planner of a safe exit speed at the * end of the last segment, which alleviates this problem. */ // The kernel called by recalculate() when scanning the plan from last to first entry. void Planner::reverse_pass_kernel(block_t * const current, const block_t * const next, const_float_t safe_exit_speed_sqr) { if (current) { // If entry speed is already at the maximum entry speed, and there was no change of speed // in the next block, there is no need to recheck. Block is cruising and there is no need to // compute anything for this block, // If not, block entry speed needs to be recalculated to ensure maximum possible planned speed. const float max_entry_speed_sqr = current->max_entry_speed_sqr; // Compute maximum entry speed decelerating over the current block from its exit speed. // If not at the maximum entry speed, or the previous block entry speed changed if (current->entry_speed_sqr != max_entry_speed_sqr || (next && next->flag.recalculate)) { // If nominal length true, max junction speed is guaranteed to be reached. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then // the current block and next block junction speeds are guaranteed to always be at their maximum // junction speeds in deceleration and acceleration, respectively. This is due to how the current // block nominal speed limits both the current and next maximum junction speeds. Hence, in both // the reverse and forward planners, the corresponding block junction speed will always be at the // the maximum junction speed and may always be ignored for any speed reduction checks. const float next_entry_speed_sqr = next ? next->entry_speed_sqr : safe_exit_speed_sqr, new_entry_speed_sqr = current->flag.nominal_length ? max_entry_speed_sqr : _MIN(max_entry_speed_sqr, max_allowable_speed_sqr(-current->acceleration, next_entry_speed_sqr, current->millimeters)); if (current->entry_speed_sqr != new_entry_speed_sqr) { // Need to recalculate the block speed - Mark it now, so the stepper // ISR does not consume the block before being recalculated current->flag.recalculate = true; // But there is an inherent race condition here, as the block may have // become BUSY just before being marked RECALCULATE, so check for that! if (stepper.is_block_busy(current)) { // Block became busy. Clear the RECALCULATE flag (no point in // recalculating BUSY blocks). And don't set its speed, as it can't // be updated at this time. current->flag.recalculate = false; } else { // Block is not BUSY so this is ahead of the Stepper ISR: // Just Set the new entry speed. current->entry_speed_sqr = new_entry_speed_sqr; } } } } } /** * recalculate() needs to go over the current plan twice. * Once in reverse and once forward. This implements the reverse pass. */ void Planner::reverse_pass(const_float_t safe_exit_speed_sqr) { // Initialize block index to the last block in the planner buffer. uint8_t block_index = prev_block_index(block_buffer_head); // Read the index of the last buffer planned block. // The ISR may change it so get a stable local copy. uint8_t planned_block_index = block_buffer_planned; // If there was a race condition and block_buffer_planned was incremented // or was pointing at the head (queue empty) break loop now and avoid // planning already consumed blocks if (planned_block_index == block_buffer_head) return; // Reverse Pass: Coarsely maximize all possible deceleration curves back-planning from the last // block in buffer. Cease planning when the last optimal planned or tail pointer is reached. // NOTE: Forward pass will later refine and correct the reverse pass to create an optimal plan. const block_t *next = nullptr; while (block_index != planned_block_index) { // Perform the reverse pass block_t *current = &block_buffer[block_index]; // Only process movement blocks if (current->is_move()) { reverse_pass_kernel(current, next, safe_exit_speed_sqr); next = current; } // Advance to the next block_index = prev_block_index(block_index); // The ISR could advance the block_buffer_planned while we were doing the reverse pass. // We must try to avoid using an already consumed block as the last one - So follow // changes to the pointer and make sure to limit the loop to the currently busy block while (planned_block_index != block_buffer_planned) { // If we reached the busy block or an already processed block, break the loop now if (block_index == planned_block_index) return; // Advance the pointer, following the busy block planned_block_index = next_block_index(planned_block_index); } } } // The kernel called by recalculate() when scanning the plan from first to last entry. void Planner::forward_pass_kernel(const block_t * const previous, block_t * const current, const uint8_t block_index) { if (previous) { // If the previous block is an acceleration block, too short to complete the full speed // change, adjust the entry speed accordingly. Entry speeds have already been reset, // maximized, and reverse-planned. If nominal length is set, max junction speed is // guaranteed to be reached. No need to recheck. if (!previous->flag.nominal_length && previous->entry_speed_sqr < current->entry_speed_sqr) { // Compute the maximum allowable speed const float new_entry_speed_sqr = max_allowable_speed_sqr(-previous->acceleration, previous->entry_speed_sqr, previous->millimeters); // If true, current block is full-acceleration and we can move the planned pointer forward. if (new_entry_speed_sqr < current->entry_speed_sqr) { // Mark we need to recompute the trapezoidal shape, and do it now, // so the stepper ISR does not consume the block before being recalculated current->flag.recalculate = true; // But there is an inherent race condition here, as the block maybe // became BUSY, just before it was marked as RECALCULATE, so check // if that is the case! if (stepper.is_block_busy(current)) { // Block became busy. Clear the RECALCULATE flag (no point in // recalculating BUSY blocks and don't set its speed, as it can't // be updated at this time. current->flag.recalculate = false; } else { // Block is not BUSY, we won the race against the Stepper ISR: // Always <= max_entry_speed_sqr. Backward pass sets this. current->entry_speed_sqr = new_entry_speed_sqr; // Always <= max_entry_speed_sqr. Backward pass sets this. // Set optimal plan pointer. block_buffer_planned = block_index; } } } // Any block set at its maximum entry speed also creates an optimal plan up to this // point in the buffer. When the plan is bracketed by either the beginning of the // buffer and a maximum entry speed or two maximum entry speeds, every block in between // cannot logically be further improved. Hence, we don't have to recompute them anymore. if (current->entry_speed_sqr == current->max_entry_speed_sqr) block_buffer_planned = block_index; } } /** * recalculate() needs to go over the current plan twice. * Once in reverse and once forward. This implements the forward pass. */ void Planner::forward_pass() { // Forward Pass: Forward plan the acceleration curve from the planned pointer onward. // Also scans for optimal plan breakpoints and appropriately updates the planned pointer. // Begin at buffer planned pointer. Note that block_buffer_planned can be modified // by the stepper ISR, so read it ONCE. It it guaranteed that block_buffer_planned // will never lead head, so the loop is safe to execute. Also note that the forward // pass will never modify the values at the tail. uint8_t block_index = block_buffer_planned; block_t *block; const block_t * previous = nullptr; while (block_index != block_buffer_head) { // Perform the forward pass block = &block_buffer[block_index]; // Only process movement blocks if (block->is_move()) { // If there's no previous block or the previous block is not // BUSY (thus, modifiable) run the forward_pass_kernel. Otherwise, // the previous block became BUSY, so assume the current block's // entry speed can't be altered (since that would also require // updating the exit speed of the previous block). if (!previous || !stepper.is_block_busy(previous)) forward_pass_kernel(previous, block, block_index); previous = block; } // Advance to the previous block_index = next_block_index(block_index); } } /** * Recalculate the trapezoid speed profiles for all blocks in the plan * according to the entry_factor for each junction. Must be called by * recalculate() after updating the blocks. */ void Planner::recalculate_trapezoids(const_float_t safe_exit_speed_sqr) { // The tail may be changed by the ISR so get a local copy. uint8_t block_index = block_buffer_tail, head_block_index = block_buffer_head; // Since there could be a sync block in the head of the queue, and the // next loop must not recalculate the head block (as it needs to be // specially handled), scan backwards to the first non-SYNC block. while (head_block_index != block_index) { // Go back (head always point to the first free block) const uint8_t prev_index = prev_block_index(head_block_index); // Get the pointer to the block block_t *prev = &block_buffer[prev_index]; // It the block is a move, we're done with this loop if (prev->is_move()) break; // Examine the previous block. This and all following are SYNC blocks head_block_index = prev_index; } // Go from the tail (currently executed block) to the first block, without including it) block_t *block = nullptr, *next = nullptr; float current_entry_speed = 0.0f, next_entry_speed = 0.0f; while (block_index != head_block_index) { next = &block_buffer[block_index]; // Only process movement blocks if (next->is_move()) { next_entry_speed = SQRT(next->entry_speed_sqr); if (block) { // If the next block is marked to RECALCULATE, also mark the previously-fetched one if (next->flag.recalculate) block->flag.recalculate = true; // Recalculate if current block entry or exit junction speed has changed. if (block->flag.recalculate) { // But there is an inherent race condition here, as the block maybe // became BUSY, just before it was marked as RECALCULATE, so check // if that is the case! if (!stepper.is_block_busy(block)) { // Block is not BUSY, we won the race against the Stepper ISR: // NOTE: Entry and exit factors always > 0 by all previous logic operations. const float nomr = 1.0f / block->nominal_speed; calculate_trapezoid_for_block(block, current_entry_speed * nomr, next_entry_speed * nomr); } // Reset current only to ensure next trapezoid is computed - The // stepper is free to use the block from now on. block->flag.recalculate = false; } } block = next; current_entry_speed = next_entry_speed; } block_index = next_block_index(block_index); } // Last/newest block in buffer. Always recalculated. if (block) { next_entry_speed = SQRT(safe_exit_speed_sqr); // Mark the next(last) block as RECALCULATE, to prevent the Stepper ISR running it. // As the last block is always recalculated here, there is a chance the block isn't // marked as RECALCULATE yet. That's the reason for the following line. block->flag.recalculate = true; // But there is an inherent race condition here, as the block maybe // became BUSY, just before it was marked as RECALCULATE, so check // if that is the case! if (!stepper.is_block_busy(block)) { // Block is not BUSY, we won the race against the Stepper ISR: const float nomr = 1.0f / block->nominal_speed; calculate_trapezoid_for_block(block, current_entry_speed * nomr, next_entry_speed * nomr); } // Reset block to ensure its trapezoid is computed - The stepper is free to use // the block from now on. block->flag.recalculate = false; } } void Planner::recalculate(const_float_t safe_exit_speed_sqr) { // Initialize block index to the last block in the planner buffer. const uint8_t block_index = prev_block_index(block_buffer_head); // If there is just one block, no planning can be done. Avoid it! if (block_index != block_buffer_planned) { reverse_pass(safe_exit_speed_sqr); forward_pass(); } recalculate_trapezoids(safe_exit_speed_sqr); } /** * Apply fan speeds */ #if HAS_FAN void Planner::sync_fan_speeds(uint8_t (&fan_speed)[FAN_COUNT]) { #if ENABLED(FAN_SOFT_PWM) #define _FAN_SET(F) thermalManager.soft_pwm_amount_fan[F] = CALC_FAN_SPEED(fan_speed[F]); #else #define _FAN_SET(F) hal.set_pwm_duty(pin_t(FAN##F##_PIN), CALC_FAN_SPEED(fan_speed[F])); #endif #define FAN_SET(F) do{ kickstart_fan(fan_speed, ms, F); _FAN_SET(F); }while(0) const millis_t ms = millis(); TERN_(HAS_FAN0, FAN_SET(0)); TERN_(HAS_FAN1, FAN_SET(1)); TERN_(HAS_FAN2, FAN_SET(2)); TERN_(HAS_FAN3, FAN_SET(3)); TERN_(HAS_FAN4, FAN_SET(4)); TERN_(HAS_FAN5, FAN_SET(5)); TERN_(HAS_FAN6, FAN_SET(6)); TERN_(HAS_FAN7, FAN_SET(7)); } #if FAN_KICKSTART_TIME void Planner::kickstart_fan(uint8_t (&fan_speed)[FAN_COUNT], const millis_t &ms, const uint8_t f) { static millis_t fan_kick_end[FAN_COUNT] = { 0 }; if (fan_speed[f] > FAN_OFF_PWM) { if (fan_kick_end[f] == 0) { fan_kick_end[f] = ms + FAN_KICKSTART_TIME; fan_speed[f] = FAN_KICKSTART_POWER; } else if (PENDING(ms, fan_kick_end[f])) fan_speed[f] = FAN_KICKSTART_POWER; } else fan_kick_end[f] = 0; } #endif #endif // HAS_FAN /** * Maintain fans, paste extruder pressure, spindle/laser power */ void Planner::check_axes_activity() { #if HAS_DISABLE_AXES xyze_bool_t axis_active = { false }; #endif #if HAS_FAN && DISABLED(LASER_SYNCHRONOUS_M106_M107) #define HAS_TAIL_FAN_SPEED 1 static uint8_t tail_fan_speed[FAN_COUNT] = ARRAY_N_1(FAN_COUNT, 13); bool fans_need_update = false; #endif #if ENABLED(BARICUDA) #if HAS_HEATER_1 uint8_t tail_valve_pressure; #endif #if HAS_HEATER_2 uint8_t tail_e_to_p_pressure; #endif #endif if (has_blocks_queued()) { #if ANY(HAS_TAIL_FAN_SPEED, BARICUDA) block_t *block = &block_buffer[block_buffer_tail]; #endif #if HAS_TAIL_FAN_SPEED FANS_LOOP(i) { const uint8_t spd = thermalManager.scaledFanSpeed(i, block->fan_speed[i]); if (tail_fan_speed[i] != spd) { fans_need_update = true; tail_fan_speed[i] = spd; } } #endif #if ENABLED(BARICUDA) TERN_(HAS_HEATER_1, tail_valve_pressure = block->valve_pressure); TERN_(HAS_HEATER_2, tail_e_to_p_pressure = block->e_to_p_pressure); #endif #if HAS_DISABLE_AXES for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) { block_t * const bnext = &block_buffer[b]; LOGICAL_AXIS_CODE( if (TERN0(DISABLE_E, bnext->steps.e)) axis_active.e = true, if (TERN0(DISABLE_X, bnext->steps.x)) axis_active.x = true, if (TERN0(DISABLE_Y, bnext->steps.y)) axis_active.y = true, if (TERN0(DISABLE_Z, bnext->steps.z)) axis_active.z = true, if (TERN0(DISABLE_I, bnext->steps.i)) axis_active.i = true, if (TERN0(DISABLE_J, bnext->steps.j)) axis_active.j = true, if (TERN0(DISABLE_K, bnext->steps.k)) axis_active.k = true, if (TERN0(DISABLE_U, bnext->steps.u)) axis_active.u = true, if (TERN0(DISABLE_V, bnext->steps.v)) axis_active.v = true, if (TERN0(DISABLE_W, bnext->steps.w)) axis_active.w = true ); } #endif } else { TERN_(HAS_CUTTER, if (cutter.cutter_mode == CUTTER_MODE_STANDARD) cutter.refresh()); #if HAS_TAIL_FAN_SPEED FANS_LOOP(i) { const uint8_t spd = thermalManager.scaledFanSpeed(i); if (tail_fan_speed[i] != spd) { fans_need_update = true; tail_fan_speed[i] = spd; } } #endif #if ENABLED(BARICUDA) TERN_(HAS_HEATER_1, tail_valve_pressure = baricuda_valve_pressure); TERN_(HAS_HEATER_2, tail_e_to_p_pressure = baricuda_e_to_p_pressure); #endif } // // Disable inactive axes // #if HAS_DISABLE_AXES LOGICAL_AXIS_CODE( if (TERN0(DISABLE_E, !axis_active.e)) stepper.disable_e_steppers(), if (TERN0(DISABLE_X, !axis_active.x)) stepper.disable_axis(X_AXIS), if (TERN0(DISABLE_Y, !axis_active.y)) stepper.disable_axis(Y_AXIS), if (TERN0(DISABLE_Z, !axis_active.z)) stepper.disable_axis(Z_AXIS), if (TERN0(DISABLE_I, !axis_active.i)) stepper.disable_axis(I_AXIS), if (TERN0(DISABLE_J, !axis_active.j)) stepper.disable_axis(J_AXIS), if (TERN0(DISABLE_K, !axis_active.k)) stepper.disable_axis(K_AXIS), if (TERN0(DISABLE_U, !axis_active.u)) stepper.disable_axis(U_AXIS), if (TERN0(DISABLE_V, !axis_active.v)) stepper.disable_axis(V_AXIS), if (TERN0(DISABLE_W, !axis_active.w)) stepper.disable_axis(W_AXIS) ); #endif // // Update Fan speeds // Only if synchronous M106/M107 is disabled // TERN_(HAS_TAIL_FAN_SPEED, if (fans_need_update) sync_fan_speeds(tail_fan_speed)); TERN_(AUTOTEMP, autotemp_task()); #if ENABLED(BARICUDA) TERN_(HAS_HEATER_1, hal.set_pwm_duty(pin_t(HEATER_1_PIN), tail_valve_pressure)); TERN_(HAS_HEATER_2, hal.set_pwm_duty(pin_t(HEATER_2_PIN), tail_e_to_p_pressure)); #endif } #if ENABLED(AUTOTEMP) #if ENABLED(AUTOTEMP_PROPORTIONAL) void Planner::_autotemp_update_from_hotend() { const celsius_t target = thermalManager.degTargetHotend(active_extruder); autotemp.min = target + AUTOTEMP_MIN_P; autotemp.max = target + AUTOTEMP_MAX_P; } #endif /** * Called after changing tools to: * - Reset or re-apply the default proportional autotemp factor. * - Enable autotemp if the factor is non-zero. */ void Planner::autotemp_update() { _autotemp_update_from_hotend(); autotemp.factor = TERN(AUTOTEMP_PROPORTIONAL, AUTOTEMP_FACTOR_P, 0); autotemp.enabled = autotemp.factor != 0; } /** * Called by the M104/M109 commands after setting Hotend Temperature * */ void Planner::autotemp_M104_M109() { _autotemp_update_from_hotend(); if (parser.seenval('S')) autotemp.min = parser.value_celsius(); if (parser.seenval('B')) autotemp.max = parser.value_celsius(); // When AUTOTEMP_PROPORTIONAL is enabled, F0 disables autotemp. // Normally, leaving off F also disables autotemp. autotemp.factor = parser.seen('F') ? parser.value_float() : TERN(AUTOTEMP_PROPORTIONAL, AUTOTEMP_FACTOR_P, 0); autotemp.enabled = autotemp.factor != 0; } /** * Called every so often to adjust the hotend target temperature * based on the extrusion speed, which is calculated from the blocks * currently in the planner. */ void Planner::autotemp_task() { static float oldt = 0.0f; if (!autotemp.enabled) return; if (thermalManager.degTargetHotend(active_extruder) < autotemp.min - 2) return; // Below the min? float high = 0.0f; for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) { const block_t * const block = &block_buffer[b]; if (NUM_AXIS_GANG(block->steps.x, || block->steps.y, || block->steps.z, || block->steps.i, || block->steps.j, || block->steps.k, || block->steps.u, || block->steps.v, || block->steps.w)) { const float se = float(block->steps.e) / block->step_event_count * block->nominal_speed; // mm/sec NOLESS(high, se); } } float t = autotemp.min + high * autotemp.factor; LIMIT(t, autotemp.min, autotemp.max); if (t < oldt) t = t * (1.0f - (AUTOTEMP_OLDWEIGHT)) + oldt * (AUTOTEMP_OLDWEIGHT); oldt = t; thermalManager.setTargetHotend(t, active_extruder); } #endif // AUTOTEMP #if DISABLED(NO_VOLUMETRICS) /** * Get a volumetric multiplier from a filament diameter. * This is the reciprocal of the circular cross-section area. * Return 1.0 with volumetric off or a diameter of 0.0. */ inline float calculate_volumetric_multiplier(const_float_t diameter) { return (parser.volumetric_enabled && diameter) ? 1.0f / CIRCLE_AREA(diameter * 0.5f) : 1; } /** * Convert the filament sizes into volumetric multipliers. * The multiplier converts a given E value into a length. */ void Planner::calculate_volumetric_multipliers() { for (uint8_t i = 0; i < COUNT(filament_size); ++i) { volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]); refresh_e_factor(i); } #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT) calculate_volumetric_extruder_limits(); // update volumetric_extruder_limits as well. #endif } #endif // !NO_VOLUMETRICS #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT) /** * Convert volumetric based limits into pre calculated extruder feedrate limits. */ void Planner::calculate_volumetric_extruder_limit(const uint8_t e) { const float &lim = volumetric_extruder_limit[e], &siz = filament_size[e]; volumetric_extruder_feedrate_limit[e] = (lim && siz) ? lim / CIRCLE_AREA(siz * 0.5f) : 0; } void Planner::calculate_volumetric_extruder_limits() { EXTRUDER_LOOP() calculate_volumetric_extruder_limit(e); } #endif #if ENABLED(FILAMENT_WIDTH_SENSOR) /** * Convert the ratio value given by the filament width sensor * into a volumetric multiplier. Conversion differs when using * linear extrusion vs volumetric extrusion. */ void Planner::apply_filament_width_sensor(const int8_t encoded_ratio) { // Reconstitute the nominal/measured ratio const float nom_meas_ratio = 1 + 0.01f * encoded_ratio, ratio_2 = sq(nom_meas_ratio); volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = parser.volumetric_enabled ? ratio_2 / CIRCLE_AREA(filwidth.nominal_mm * 0.5f) // Volumetric uses a true volumetric multiplier : ratio_2; // Linear squares the ratio, which scales the volume refresh_e_factor(FILAMENT_SENSOR_EXTRUDER_NUM); } #endif #if ENABLED(IMPROVE_HOMING_RELIABILITY) void Planner::enable_stall_prevention(const bool onoff) { static motion_state_t saved_motion_state; if (onoff) { saved_motion_state.acceleration.x = settings.max_acceleration_mm_per_s2[X_AXIS]; saved_motion_state.acceleration.y = settings.max_acceleration_mm_per_s2[Y_AXIS]; settings.max_acceleration_mm_per_s2[X_AXIS] = settings.max_acceleration_mm_per_s2[Y_AXIS] = 100; #if ENABLED(DELTA) saved_motion_state.acceleration.z = settings.max_acceleration_mm_per_s2[Z_AXIS]; settings.max_acceleration_mm_per_s2[Z_AXIS] = 100; #endif #if ENABLED(CLASSIC_JERK) saved_motion_state.jerk_state = max_jerk; max_jerk.set(0, 0 OPTARG(DELTA, 0)); #endif } else { settings.max_acceleration_mm_per_s2[X_AXIS] = saved_motion_state.acceleration.x; settings.max_acceleration_mm_per_s2[Y_AXIS] = saved_motion_state.acceleration.y; TERN_(DELTA, settings.max_acceleration_mm_per_s2[Z_AXIS] = saved_motion_state.acceleration.z); TERN_(CLASSIC_JERK, max_jerk = saved_motion_state.jerk_state); } refresh_acceleration_rates(); } #endif #if HAS_LEVELING constexpr xy_pos_t level_fulcrum = { TERN(Z_SAFE_HOMING, Z_SAFE_HOMING_X_POINT, X_HOME_POS), TERN(Z_SAFE_HOMING, Z_SAFE_HOMING_Y_POINT, Y_HOME_POS) }; /** * rx, ry, rz - Cartesian positions in mm * Leveled XYZ on completion */ void Planner::apply_leveling(xyz_pos_t &raw) { if (!leveling_active) return; #if ABL_PLANAR xy_pos_t d = raw - level_fulcrum; bed_level_matrix.apply_rotation_xyz(d.x, d.y, raw.z); raw = d + level_fulcrum; #elif HAS_MESH #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) const float fade_scaling_factor = fade_scaling_factor_for_z(raw.z); if (fade_scaling_factor) raw.z += fade_scaling_factor * bedlevel.get_z_correction(raw); #else raw.z += bedlevel.get_z_correction(raw); #endif TERN_(MESH_BED_LEVELING, raw.z += bedlevel.get_z_offset()); #endif } void Planner::unapply_leveling(xyz_pos_t &raw) { if (!leveling_active) return; #if ABL_PLANAR matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix); xy_pos_t d = raw - level_fulcrum; inverse.apply_rotation_xyz(d.x, d.y, raw.z); raw = d + level_fulcrum; #elif HAS_MESH const float z_correction = bedlevel.get_z_correction(raw), z_full_fade = DIFF_TERN(MESH_BED_LEVELING, raw.z, bedlevel.get_z_offset()), z_no_fade = z_full_fade - z_correction; #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) if (!z_fade_height || z_no_fade <= 0.0f) // Not fading or at bed level? raw.z = z_no_fade; // Unapply full mesh Z. else if (z_full_fade >= z_fade_height) // Above the fade height? raw.z = z_full_fade; // Nothing more to unapply. else // Within the fade zone? raw.z = z_no_fade / (1.0f - z_correction * inverse_z_fade_height); // Unapply the faded Z offset #else raw.z = z_no_fade; #endif #endif } #endif // HAS_LEVELING #if ENABLED(FWRETRACT) /** * rz, e - Cartesian positions in mm */ void Planner::apply_retract(float &rz, float &e) { rz += fwretract.current_hop; e -= fwretract.current_retract[active_extruder]; } void Planner::unapply_retract(float &rz, float &e) { rz -= fwretract.current_hop; e += fwretract.current_retract[active_extruder]; } #endif void Planner::quick_stop() { // Remove all the queued blocks. Note that this function is NOT // called from the Stepper ISR, so we must consider tail as readonly! // that is why we set head to tail - But there is a race condition that // must be handled: The tail could change between the read and the assignment // so this must be enclosed in a critical section const bool was_enabled = stepper.suspend(); // Drop all queue entries block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail; // Restart the block delay for the first movement - As the queue was // forced to empty, there's no risk the ISR will touch this. delay_before_delivering = TERN_(FT_MOTION, ftMotion.cfg.mode ? BLOCK_DELAY_NONE :) BLOCK_DELAY_FOR_1ST_MOVE; TERN_(HAS_WIRED_LCD, clear_block_buffer_runtime()); // Clear the accumulated runtime // Make sure to drop any attempt of queuing moves for 1 second cleaning_buffer_counter = TEMP_TIMER_FREQUENCY; // Reenable Stepper ISR if (was_enabled) stepper.wake_up(); // And stop the stepper ISR stepper.quick_stop(); } #if ENABLED(REALTIME_REPORTING_COMMANDS) void Planner::quick_pause() { // Suspend until quick_resume is called // Don't empty buffers or queues const bool did_suspend = stepper.suspend(); if (did_suspend) TERN_(FULL_REPORT_TO_HOST_FEATURE, set_and_report_grblstate(M_HOLD)); } // Resume if suspended void Planner::quick_resume() { TERN_(FULL_REPORT_TO_HOST_FEATURE, set_and_report_grblstate(grbl_state_for_marlin_state())); stepper.wake_up(); } #endif void Planner::endstop_triggered(const AxisEnum axis) { // Record stepper position and discard the current block stepper.endstop_triggered(axis); } float Planner::triggered_position_mm(const AxisEnum axis) { const float result = DIFF_TERN(BACKLASH_COMPENSATION, stepper.triggered_position(axis), backlash.get_applied_steps(axis)); return result * mm_per_step[axis]; } bool Planner::busy() { return (has_blocks_queued() || cleaning_buffer_counter || TERN0(EXTERNAL_CLOSED_LOOP_CONTROLLER, CLOSED_LOOP_WAITING()) || TERN0(HAS_ZV_SHAPING, stepper.input_shaping_busy()) || TERN0(FT_MOTION, ftMotion.busy) ); } void Planner::finish_and_disable() { while (has_blocks_queued() || cleaning_buffer_counter) idle(); stepper.disable_all_steppers(); } /** * Get an axis position according to stepper position(s) * For CORE machines apply translation from ABC to XYZ. */ float Planner::get_axis_position_mm(const AxisEnum axis) { float axis_steps; #if IS_CORE // Requesting one of the "core" axes? if (axis == CORE_AXIS_1 || axis == CORE_AXIS_2) { // Protect the access to the position. const bool was_enabled = stepper.suspend(); const int32_t p1 = DIFF_TERN(BACKLASH_COMPENSATION, stepper.position(CORE_AXIS_1), backlash.get_applied_steps(CORE_AXIS_1)), p2 = DIFF_TERN(BACKLASH_COMPENSATION, stepper.position(CORE_AXIS_2), backlash.get_applied_steps(CORE_AXIS_2)); if (was_enabled) stepper.wake_up(); // ((a1+a2)+(a1-a2))/2 -> (a1+a2+a1-a2)/2 -> (a1+a1)/2 -> a1 // ((a1+a2)-(a1-a2))/2 -> (a1+a2-a1+a2)/2 -> (a2+a2)/2 -> a2 axis_steps = (axis == CORE_AXIS_2 ? CORESIGN(p1 - p2) : p1 + p2) * 0.5f; } else axis_steps = DIFF_TERN(BACKLASH_COMPENSATION, stepper.position(axis), backlash.get_applied_steps(axis)); #elif ANY(MARKFORGED_XY, MARKFORGED_YX) // Requesting one of the joined axes? if (axis == CORE_AXIS_1 || axis == CORE_AXIS_2) { // Protect the access to the position. const bool was_enabled = stepper.suspend(); const int32_t p1 = stepper.position(CORE_AXIS_1), p2 = stepper.position(CORE_AXIS_2); if (was_enabled) stepper.wake_up(); axis_steps = ((axis == CORE_AXIS_1) ? p1 - p2 : p2); } else axis_steps = DIFF_TERN(BACKLASH_COMPENSATION, stepper.position(axis), backlash.get_applied_steps(axis)); #else axis_steps = stepper.position(axis); TERN_(BACKLASH_COMPENSATION, axis_steps -= backlash.get_applied_steps(axis)); #endif return axis_steps * mm_per_step[axis]; } /** * Block until the planner is finished processing */ void Planner::synchronize() { while (busy()) idle(); } /** * @brief Add a new linear movement to the planner queue (in terms of steps). * * @param target Target position in steps units * @param target_float Target position in direct (mm, degrees) units. * @param cart_dist_mm The pre-calculated move lengths for all axes, in mm * @param fr_mm_s (target) speed of the move * @param extruder target extruder * @param hints parameters to aid planner calculations * * @return true if movement was properly queued, false otherwise (if cleaning) */ bool Planner::_buffer_steps(const xyze_long_t &target OPTARG(HAS_POSITION_FLOAT, const xyze_pos_t &target_float) OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm) , feedRate_t fr_mm_s, const uint8_t extruder, const PlannerHints &hints ) { // Wait for the next available block uint8_t next_buffer_head; block_t * const block = get_next_free_block(next_buffer_head); // If we are cleaning, do not accept queuing of movements // This must be after get_next_free_block() because it calls idle() // where cleaning_buffer_counter can be changed if (cleaning_buffer_counter) return false; // Fill the block with the specified movement float minimum_planner_speed_sqr; if (!_populate_block(block, target OPTARG(HAS_POSITION_FLOAT, target_float) OPTARG(HAS_DIST_MM_ARG, cart_dist_mm) , fr_mm_s, extruder, hints , minimum_planner_speed_sqr ) ) { // Movement was not queued, probably because it was too short. // Simply accept that as movement queued and done return true; } // If this is the first added movement, reload the delay, otherwise, cancel it. if (block_buffer_head == block_buffer_tail) { // If it was the first queued block, restart the 1st block delivery delay, to // give the planner an opportunity to queue more movements and plan them // As there are no queued movements, the Stepper ISR will not touch this // variable, so there is no risk setting this here (but it MUST be done // before the following line!!) delay_before_delivering = TERN_(FT_MOTION, ftMotion.cfg.mode ? BLOCK_DELAY_NONE :) BLOCK_DELAY_FOR_1ST_MOVE; } // Move buffer head block_buffer_head = next_buffer_head; // find a speed from which the new block can stop safely const float safe_exit_speed_sqr = _MAX( TERN0(HINTS_SAFE_EXIT_SPEED, hints.safe_exit_speed_sqr), minimum_planner_speed_sqr ); // Recalculate and optimize trapezoidal speed profiles recalculate(safe_exit_speed_sqr); // Movement successfully queued! return true; } /** * @brief Populate a block in preparation for insertion * @details Populate the fields of a new linear movement block * that will be added to the queue and processed soon * by the Stepper ISR. * * @param block A block to populate * @param target Target position in steps units * @param target_float Target position in native mm * @param cart_dist_mm The pre-calculated move lengths for all axes, in mm * @param fr_mm_s (target) speed of the move * @param extruder target extruder * @param hints parameters to aid planner calculations * * @return true if movement is acceptable, false otherwise */ bool Planner::_populate_block( block_t * const block, const abce_long_t &target OPTARG(HAS_POSITION_FLOAT, const xyze_pos_t &target_float) OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm) , feedRate_t fr_mm_s, const uint8_t extruder, const PlannerHints &hints , float &minimum_planner_speed_sqr ) { xyze_long_t dist = target - position; /* <-- add a slash to enable SERIAL_ECHOLNPGM( " _populate_block FR:", fr_mm_s, #if HAS_X_AXIS " " STR_A ":", target.a, " (", dist.a, " steps)" #endif #if HAS_Y_AXIS " " STR_B ":", target.b, " (", dist.b, " steps)" #endif #if HAS_Z_AXIS " " STR_C ":", target.c, " (", dist.c, " steps)" #endif #if HAS_I_AXIS " " STR_I ":", target.i, " (", dist.i, " steps)" #endif #if HAS_J_AXIS " " STR_J ":", target.j, " (", dist.j, " steps)" #endif #if HAS_K_AXIS " " STR_K ":", target.k, " (", dist.k, " steps)" #endif #if HAS_U_AXIS " " STR_U ":", target.u, " (", dist.u, " steps)" #endif #if HAS_V_AXIS " " STR_V ":", target.v, " (", dist.v, " steps)" #endif #if HAS_W_AXIS " " STR_W ":", target.w, " (", dist.w, " steps)" #endif #if HAS_EXTRUDERS " E:", target.e, " (", dist.e, " steps)" #endif ); //*/ #if ANY(PREVENT_COLD_EXTRUSION, PREVENT_LENGTHY_EXTRUDE) if (dist.e) { #if ENABLED(PREVENT_COLD_EXTRUSION) if (thermalManager.tooColdToExtrude(extruder)) { position.e = target.e; // Behave as if the move really took place, but ignore E part TERN_(HAS_POSITION_FLOAT, position_float.e = target_float.e); dist.e = 0; // no difference SERIAL_ECHO_MSG(STR_ERR_COLD_EXTRUDE_STOP); } #endif // PREVENT_COLD_EXTRUSION #if ENABLED(PREVENT_LENGTHY_EXTRUDE) const float e_steps = ABS(dist.e * e_factor[extruder]); const float max_e_steps = settings.axis_steps_per_mm[E_AXIS_N(extruder)] * (EXTRUDE_MAXLENGTH); if (e_steps > max_e_steps) { #if ENABLED(MIXING_EXTRUDER) bool ignore_e = false; float collector[MIXING_STEPPERS]; mixer.refresh_collector(1.0f, mixer.get_current_vtool(), collector); MIXER_STEPPER_LOOP(e) if (e_steps * collector[e] > max_e_steps) { ignore_e = true; break; } #else constexpr bool ignore_e = true; #endif if (ignore_e) { position.e = target.e; // Behave as if the move really took place, but ignore E part TERN_(HAS_POSITION_FLOAT, position_float.e = target_float.e); dist.e = 0; // no difference SERIAL_ECHO_MSG(STR_ERR_LONG_EXTRUDE_STOP); } } #endif // PREVENT_LENGTHY_EXTRUDE } #endif // PREVENT_COLD_EXTRUSION || PREVENT_LENGTHY_EXTRUDE // Compute direction bit-mask for this block AxisBits dm; #if ANY(CORE_IS_XY, CORE_IS_XZ, MARKFORGED_XY, MARKFORGED_YX) dm.hx = (dist.a > 0); // True direction in X #endif #if ANY(CORE_IS_XY, CORE_IS_YZ, MARKFORGED_XY, MARKFORGED_YX) dm.hy = (dist.b > 0); // True direction in Y #endif #if ANY(CORE_IS_XZ, CORE_IS_YZ) dm.hz = (dist.c > 0); // True direction in Z #endif #if CORE_IS_XY dm.a = (dist.a + dist.b > 0); // Motor A direction dm.b = (CORESIGN(dist.a - dist.b) > 0); // Motor B direction TERN_(HAS_Z_AXIS, dm.z = (dist.c > 0)); // Axis Z direction #elif CORE_IS_XZ dm.a = (dist.a + dist.c > 0); // Motor A direction dm.y = (dist.b > 0); // Axis Y direction dm.c = (CORESIGN(dist.a - dist.c) > 0); // Motor C direction #elif CORE_IS_YZ dm.x = (dist.a > 0); // Axis X direction dm.b = (dist.b + dist.c > 0); // Motor B direction dm.c = (CORESIGN(dist.b - dist.c) > 0); // Motor C direction #elif ENABLED(MARKFORGED_XY) dm.a = (dist.a TERN(MARKFORGED_INVERSE, -, +) dist.b > 0); // Motor A direction dm.b = (dist.b > 0); // Motor B direction TERN_(HAS_Z_AXIS, dm.z = (dist.c > 0)); // Axis Z direction #elif ENABLED(MARKFORGED_YX) dm.a = (dist.a > 0); // Motor A direction dm.b = (dist.b TERN(MARKFORGED_INVERSE, -, +) dist.a > 0); // Motor B direction TERN_(HAS_Z_AXIS, dm.z = (dist.c > 0)); // Axis Z direction #else XYZ_CODE( dm.x = (dist.a > 0), dm.y = (dist.b > 0), dm.z = (dist.c > 0) ); #endif SECONDARY_AXIS_CODE( dm.i = (dist.i > 0), dm.j = (dist.j > 0), dm.k = (dist.k > 0), dm.u = (dist.u > 0), dm.v = (dist.v > 0), dm.w = (dist.w > 0) ); #if HAS_EXTRUDERS dm.e = (dist.e > 0); const float esteps_float = dist.e * e_factor[extruder]; const uint32_t esteps = ABS(esteps_float); #else constexpr uint32_t esteps = 0; #endif // Clear all flags, including the "busy" bit block->flag.clear(); // Set direction bits block->direction_bits = dm; /** * Update block laser power * For standard mode get the cutter.power value for processing, since it's * only set by apply_power(). */ #if HAS_CUTTER switch (cutter.cutter_mode) { default: break; case CUTTER_MODE_STANDARD: block->cutter_power = cutter.power; break; #if ENABLED(LASER_FEATURE) /** * For inline mode get the laser_inline variables, including power and status. * Dynamic mode only needs to update if the feedrate has changed, since it's * calculated from the current feedrate and power level. */ case CUTTER_MODE_CONTINUOUS: block->laser.power = laser_inline.power; block->laser.status = laser_inline.status; break; case CUTTER_MODE_DYNAMIC: if (cutter.laser_feedrate_changed()) // Only process changes in rate block->laser.power = laser_inline.power = cutter.calc_dynamic_power(); break; #endif } #endif // Number of steps for each axis // See https://www.corexy.com/theory.html block->steps.set(NUM_AXIS_LIST( #if CORE_IS_XY ABS(dist.a + dist.b), ABS(dist.a - dist.b), ABS(dist.c) #elif CORE_IS_XZ ABS(dist.a + dist.c), ABS(dist.b), ABS(dist.a - dist.c) #elif CORE_IS_YZ ABS(dist.a), ABS(dist.b + dist.c), ABS(dist.b - dist.c) #elif ENABLED(MARKFORGED_XY) ABS(dist.a TERN(MARKFORGED_INVERSE, -, +) dist.b), ABS(dist.b), ABS(dist.c) #elif ENABLED(MARKFORGED_YX) ABS(dist.a), ABS(dist.b TERN(MARKFORGED_INVERSE, -, +) dist.a), ABS(dist.c) #elif IS_SCARA ABS(dist.a), ABS(dist.b), ABS(dist.c) #else // default non-h-bot planning ABS(dist.a), ABS(dist.b), ABS(dist.c) #endif , ABS(dist.i), ABS(dist.j), ABS(dist.k), ABS(dist.u), ABS(dist.v), ABS(dist.w) )); /** * This part of the code calculates the total length of the movement. * For cartesian bots, the distance along the X axis equals the X_AXIS joint displacement and same holds true for Y_AXIS. * But for geometries like CORE_XY that is not true. For these machines we need to create 2 additional variables, named X_HEAD and Y_HEAD, to store the displacent of the head along the X and Y axes in a cartesian coordinate system. * The displacement of the head along the axes of the cartesian coordinate system has to be calculated from "X_AXIS" and "Y_AXIS" (should be renamed to A_JOINT and B_JOINT) * displacements in joints space using forward kinematics (A=X+Y and B=X-Y in the case of CORE_XY). * Next we can calculate the total movement length and apply the desired speed. */ struct DistanceMM : abce_float_t { #if ANY(IS_CORE, MARKFORGED_XY, MARKFORGED_YX) struct { float x, y, z; } head; #endif } dist_mm; #if ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX) dist_mm.head.x = dist.a * mm_per_step[A_AXIS]; dist_mm.head.y = dist.b * mm_per_step[B_AXIS]; TERN_(HAS_Z_AXIS, dist_mm.z = dist.c * mm_per_step[Z_AXIS]); #endif #if CORE_IS_XY dist_mm.a = (dist.a + dist.b) * mm_per_step[A_AXIS]; dist_mm.b = CORESIGN(dist.a - dist.b) * mm_per_step[B_AXIS]; #elif CORE_IS_XZ dist_mm.head.x = dist.a * mm_per_step[A_AXIS]; dist_mm.y = dist.b * mm_per_step[Y_AXIS]; dist_mm.head.z = dist.c * mm_per_step[C_AXIS]; dist_mm.a = (dist.a + dist.c) * mm_per_step[A_AXIS]; dist_mm.c = CORESIGN(dist.a - dist.c) * mm_per_step[C_AXIS]; #elif CORE_IS_YZ dist_mm.x = dist.a * mm_per_step[X_AXIS]; dist_mm.head.y = dist.b * mm_per_step[B_AXIS]; dist_mm.head.z = dist.c * mm_per_step[C_AXIS]; dist_mm.b = (dist.b + dist.c) * mm_per_step[B_AXIS]; dist_mm.c = CORESIGN(dist.b - dist.c) * mm_per_step[C_AXIS]; #elif ENABLED(MARKFORGED_XY) dist_mm.a = (dist.a TERN(MARKFORGED_INVERSE, +, -) dist.b) * mm_per_step[A_AXIS]; dist_mm.b = dist.b * mm_per_step[B_AXIS]; #elif ENABLED(MARKFORGED_YX) dist_mm.a = dist.a * mm_per_step[A_AXIS]; dist_mm.b = (dist.b TERN(MARKFORGED_INVERSE, +, -) dist.a) * mm_per_step[B_AXIS]; #else XYZ_CODE( dist_mm.a = dist.a * mm_per_step[A_AXIS], dist_mm.b = dist.b * mm_per_step[B_AXIS], dist_mm.c = dist.c * mm_per_step[C_AXIS] ); #endif SECONDARY_AXIS_CODE( dist_mm.i = dist.i * mm_per_step[I_AXIS], dist_mm.j = dist.j * mm_per_step[J_AXIS], dist_mm.k = dist.k * mm_per_step[K_AXIS], dist_mm.u = dist.u * mm_per_step[U_AXIS], dist_mm.v = dist.v * mm_per_step[V_AXIS], dist_mm.w = dist.w * mm_per_step[W_AXIS] ); TERN_(HAS_EXTRUDERS, dist_mm.e = esteps_float * mm_per_step[E_AXIS_N(extruder)]); TERN_(LCD_SHOW_E_TOTAL, e_move_accumulator += dist_mm.e); #if HAS_ROTATIONAL_AXES bool cartesian_move = hints.cartesian_move; #endif if (true NUM_AXIS_GANG( && block->steps.a < MIN_STEPS_PER_SEGMENT, && block->steps.b < MIN_STEPS_PER_SEGMENT, && block->steps.c < MIN_STEPS_PER_SEGMENT, && block->steps.i < MIN_STEPS_PER_SEGMENT, && block->steps.j < MIN_STEPS_PER_SEGMENT, && block->steps.k < MIN_STEPS_PER_SEGMENT, && block->steps.u < MIN_STEPS_PER_SEGMENT, && block->steps.v < MIN_STEPS_PER_SEGMENT, && block->steps.w < MIN_STEPS_PER_SEGMENT ) ) { block->millimeters = TERN0(HAS_EXTRUDERS, ABS(dist_mm.e)); } else { if (hints.millimeters) block->millimeters = hints.millimeters; else { const xyze_pos_t displacement = LOGICAL_AXIS_ARRAY( dist_mm.e, #if ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX) dist_mm.head.x, dist_mm.head.y, dist_mm.z, #elif CORE_IS_XZ dist_mm.head.x, dist_mm.y, dist_mm.head.z, #elif CORE_IS_YZ dist_mm.x, dist_mm.head.y, dist_mm.head.z, #else dist_mm.x, dist_mm.y, dist_mm.z, #endif dist_mm.i, dist_mm.j, dist_mm.k, dist_mm.u, dist_mm.v, dist_mm.w ); block->millimeters = get_move_distance(displacement OPTARG(HAS_ROTATIONAL_AXES, cartesian_move)); } /** * At this point at least one of the axes has more steps than * MIN_STEPS_PER_SEGMENT, ensuring the segment won't get dropped as * zero-length. It's important to not apply corrections * to blocks that would get dropped! * * A correction function is permitted to add steps to an axis, it * should *never* remove steps! */ TERN_(BACKLASH_COMPENSATION, backlash.add_correction_steps(dist, dm, block)); } TERN_(HAS_EXTRUDERS, block->steps.e = esteps); block->step_event_count = ( #if NUM_AXES _MAX(LOGICAL_AXIS_LIST(esteps, block->steps.a, block->steps.b, block->steps.c, block->steps.i, block->steps.j, block->steps.k, block->steps.u, block->steps.v, block->steps.w )) #elif HAS_EXTRUDERS esteps #endif ); // Bail if this is a zero-length block if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return false; TERN_(MIXING_EXTRUDER, mixer.populate_block(block->b_color)); #if HAS_FAN FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i]; #endif #if ENABLED(BARICUDA) block->valve_pressure = baricuda_valve_pressure; block->e_to_p_pressure = baricuda_e_to_p_pressure; #endif E_TERN_(block->extruder = extruder); #if ENABLED(AUTO_POWER_CONTROL) if (NUM_AXIS_GANG( block->steps.x, || block->steps.y, || block->steps.z, || block->steps.i, || block->steps.j, || block->steps.k, || block->steps.u, || block->steps.v, || block->steps.w )) powerManager.power_on(); #endif // Enable active axes #if ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX) if (block->steps.a || block->steps.b) { stepper.enable_axis(X_AXIS); stepper.enable_axis(Y_AXIS); } #if HAS_Z_AXIS && DISABLED(Z_LATE_ENABLE) if (block->steps.z) stepper.enable_axis(Z_AXIS); #endif #elif CORE_IS_XZ if (block->steps.a || block->steps.c) { stepper.enable_axis(X_AXIS); stepper.enable_axis(Z_AXIS); } if (block->steps.y) stepper.enable_axis(Y_AXIS); #elif CORE_IS_YZ if (block->steps.b || block->steps.c) { stepper.enable_axis(Y_AXIS); stepper.enable_axis(Z_AXIS); } if (block->steps.x) stepper.enable_axis(X_AXIS); #else NUM_AXIS_CODE( if (block->steps.x) stepper.enable_axis(X_AXIS), if (block->steps.y) stepper.enable_axis(Y_AXIS), if (TERN(Z_LATE_ENABLE, 0, block->steps.z)) stepper.enable_axis(Z_AXIS), if (block->steps.i) stepper.enable_axis(I_AXIS), if (block->steps.j) stepper.enable_axis(J_AXIS), if (block->steps.k) stepper.enable_axis(K_AXIS), if (block->steps.u) stepper.enable_axis(U_AXIS), if (block->steps.v) stepper.enable_axis(V_AXIS), if (block->steps.w) stepper.enable_axis(W_AXIS) ); #endif #if ANY(CORE_IS_XY, MARKFORGED_XY, MARKFORGED_YX) SECONDARY_AXIS_CODE( if (block->steps.i) stepper.enable_axis(I_AXIS), if (block->steps.j) stepper.enable_axis(J_AXIS), if (block->steps.k) stepper.enable_axis(K_AXIS), if (block->steps.u) stepper.enable_axis(U_AXIS), if (block->steps.v) stepper.enable_axis(V_AXIS), if (block->steps.w) stepper.enable_axis(W_AXIS) ); #endif // Enable extruder(s) #if HAS_EXTRUDERS if (esteps) { TERN_(AUTO_POWER_CONTROL, powerManager.power_on()); #if ENABLED(DISABLE_OTHER_EXTRUDERS) // Enable only the selected extruder // Count down all steppers that were recently moved for (uint8_t i = 0; i < E_STEPPERS; ++i) if (extruder_last_move[i]) extruder_last_move[i]--; // Switching Extruder uses one E stepper motor per two nozzles #define E_STEPPER_INDEX(E) TERN(HAS_SWITCHING_EXTRUDER, (E) / 2, E) // Enable all (i.e., both) E steppers for IDEX-style duplication, but only active E steppers for multi-nozzle (i.e., single wide X carriage) duplication #define _IS_DUPE(N) TERN0(HAS_DUPLICATION_MODE, (extruder_duplication_enabled && TERN1(MULTI_NOZZLE_DUPLICATION, TEST(duplication_e_mask, N)))) #define ENABLE_ONE_E(N) do{ \ if (N == E_STEPPER_INDEX(extruder) || _IS_DUPE(N)) { /* N is 'extruder', or N is duplicating */ \ stepper.ENABLE_EXTRUDER(N); /* Enable the relevant E stepper... */ \ extruder_last_move[N] = (BLOCK_BUFFER_SIZE) * 2; /* ...and reset its counter */ \ } \ else if (!extruder_last_move[N]) /* Counter expired since last E stepper enable */ \ stepper.DISABLE_EXTRUDER(N); /* Disable the E stepper */ \ }while(0); #else #define ENABLE_ONE_E(N) stepper.ENABLE_EXTRUDER(N); #endif REPEAT(E_STEPPERS, ENABLE_ONE_E); // (ENABLE_ONE_E must end with semicolon) } #endif // HAS_EXTRUDERS if (esteps) NOLESS(fr_mm_s, settings.min_feedrate_mm_s); else NOLESS(fr_mm_s, settings.min_travel_feedrate_mm_s); const float inverse_millimeters = 1.0f / block->millimeters; // Inverse millimeters to remove multiple divides // Calculate inverse time for this move. No divide by zero due to previous checks. // Example: At 120mm/s a 60mm move involving XYZ axes takes 0.5s. So this will give 2.0. // Example 2: At 120°/s a 60° move involving only rotational axes takes 0.5s. So this will give 2.0. float inverse_secs = inverse_millimeters * ( #if ALL(HAS_ROTATIONAL_AXES, INCH_MODE_SUPPORT) /** * Workaround for premature feedrate conversion * from in/s to mm/s by get_distance_from_command. */ cartesian_move ? fr_mm_s : LINEAR_UNIT(fr_mm_s) #else fr_mm_s #endif ); // Get the number of non busy movements in queue (non busy means that they can be altered) const uint8_t moves_queued = nonbusy_movesplanned(); // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill #if ANY(SLOWDOWN, HAS_WIRED_LCD) || defined(XY_FREQUENCY_LIMIT) // Segment time in microseconds int32_t segment_time_us = LROUND(1000000.0f / inverse_secs); #endif #if ENABLED(SLOWDOWN) #ifndef SLOWDOWN_DIVISOR #define SLOWDOWN_DIVISOR 2 #endif if (WITHIN(moves_queued, 2, (BLOCK_BUFFER_SIZE) / (SLOWDOWN_DIVISOR) - 1)) { #ifdef MAX7219_DEBUG_SLOWDOWN slowdown_count = (slowdown_count + 1) & 0x0F; #endif const int32_t time_diff = settings.min_segment_time_us - segment_time_us; if (time_diff > 0) { // Buffer is draining so add extra time. The amount of time added increases if the buffer is still emptied more. const int32_t nst = segment_time_us + LROUND(2 * time_diff / moves_queued); inverse_secs = 1000000.0f / nst; #if defined(XY_FREQUENCY_LIMIT) || HAS_WIRED_LCD segment_time_us = nst; #endif } } #endif #if HAS_WIRED_LCD // Protect the access to the position. const bool was_enabled = stepper.suspend(); block_buffer_runtime_us += segment_time_us; block->segment_time_us = segment_time_us; if (was_enabled) stepper.wake_up(); #endif block->nominal_speed = block->millimeters * inverse_secs; // (mm/sec) Always > 0 block->nominal_rate = CEIL(block->step_event_count * inverse_secs); // (step/sec) Always > 0 #if ENABLED(FILAMENT_WIDTH_SENSOR) if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM) // Only for extruder with filament sensor filwidth.advance_e(dist_mm.e); #endif // Calculate and limit speed in mm/sec (linear) or degrees/sec (rotational) xyze_float_t current_speed; float speed_factor = 1.0f; // factor <1 decreases speed // Linear axes first with less logic LOOP_NUM_AXES(i) { current_speed[i] = dist_mm[i] * inverse_secs; const feedRate_t cs = ABS(current_speed[i]), max_fr = settings.max_feedrate_mm_s[i]; if (cs > max_fr) NOMORE(speed_factor, max_fr / cs); } // Limit speed on extruders, if any #if HAS_EXTRUDERS { current_speed.e = dist_mm.e * inverse_secs; #if HAS_MIXER_SYNC_CHANNEL // Move all mixing extruders at the specified rate if (mixer.get_current_vtool() == MIXER_AUTORETRACT_TOOL) current_speed.e *= MIXING_STEPPERS; #endif const feedRate_t cs = ABS(current_speed.e), max_fr = settings.max_feedrate_mm_s[E_AXIS_N(extruder)] * TERN(HAS_MIXER_SYNC_CHANNEL, MIXING_STEPPERS, 1); if (cs > max_fr) NOMORE(speed_factor, max_fr / cs); //respect max feedrate on any movement (doesn't matter if E axes only or not) #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT) const feedRate_t max_vfr = volumetric_extruder_feedrate_limit[extruder] * TERN(HAS_MIXER_SYNC_CHANNEL, MIXING_STEPPERS, 1); // TODO: Doesn't work properly for joined segments. Set MIN_STEPS_PER_SEGMENT 1 as workaround. if (block->steps.a || block->steps.b || block->steps.c) { if (max_vfr > 0 && cs > max_vfr) { NOMORE(speed_factor, max_vfr / cs); // respect volumetric extruder limit (if any) /* <-- add a slash to enable SERIAL_ECHOPGM("volumetric extruder limit enforced: ", (cs * CIRCLE_AREA(filament_size[extruder] * 0.5f))); SERIAL_ECHOPGM(" mm^3/s (", cs); SERIAL_ECHOPGM(" mm/s) limited to ", (max_vfr * CIRCLE_AREA(filament_size[extruder] * 0.5f))); SERIAL_ECHOPGM(" mm^3/s (", max_vfr); SERIAL_ECHOLNPGM(" mm/s)"); //*/ } } #endif } #endif // HAS_EXTRUDERS #ifdef XY_FREQUENCY_LIMIT static AxisBits old_direction_bits; // = 0 if (xy_freq_limit_hz) { // Check and limit the xy direction change frequency const AxisBits direction_change = block->direction_bits ^ old_direction_bits; old_direction_bits = block->direction_bits; segment_time_us = LROUND(float(segment_time_us) / speed_factor); static int32_t xs0, xs1, xs2, ys0, ys1, ys2; if (segment_time_us > xy_freq_min_interval_us) xs2 = xs1 = ys2 = ys1 = xy_freq_min_interval_us; else { xs2 = xs1; xs1 = xs0; ys2 = ys1; ys1 = ys0; } xs0 = direction_change.x ? segment_time_us : xy_freq_min_interval_us; ys0 = direction_change.y ? segment_time_us : xy_freq_min_interval_us; if (segment_time_us < xy_freq_min_interval_us) { const int32_t least_xy_segment_time = _MIN(_MAX(xs0, xs1, xs2), _MAX(ys0, ys1, ys2)); if (least_xy_segment_time < xy_freq_min_interval_us) { float freq_xy_feedrate = (speed_factor * least_xy_segment_time) / xy_freq_min_interval_us; NOLESS(freq_xy_feedrate, xy_freq_min_speed_factor); NOMORE(speed_factor, freq_xy_feedrate); } } } #endif // XY_FREQUENCY_LIMIT // Correct the speed if (speed_factor < 1.0f) { current_speed *= speed_factor; block->nominal_rate *= speed_factor; block->nominal_speed *= speed_factor; } // Compute and limit the acceleration rate for the trapezoid generator. const float steps_per_mm = block->step_event_count * inverse_millimeters; uint32_t accel; #if ENABLED(LIN_ADVANCE) bool use_advance_lead = false; #endif if (!ANY_AXIS_MOVES(block)) { // Is this a retract / recover move? accel = CEIL(settings.retract_acceleration * steps_per_mm); // Convert to: acceleration steps/sec^2 } else { #define LIMIT_ACCEL_LONG(AXIS,INDX) do{ \ if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \ const uint32_t max_possible = max_acceleration_steps_per_s2[AXIS+INDX] * block->step_event_count / block->steps[AXIS]; \ NOMORE(accel, max_possible); \ } \ }while(0) #define LIMIT_ACCEL_FLOAT(AXIS,INDX) do{ \ if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \ const float max_possible = float(max_acceleration_steps_per_s2[AXIS+INDX]) * float(block->step_event_count) / float(block->steps[AXIS]); \ NOMORE(accel, max_possible); \ } \ }while(0) // Start with print or travel acceleration accel = CEIL((esteps ? settings.acceleration : settings.travel_acceleration) * steps_per_mm); #if ENABLED(LIN_ADVANCE) // Linear advance is currently not ready for HAS_I_AXIS #define MAX_E_JERK(N) TERN(HAS_LINEAR_E_JERK, max_e_jerk[E_INDEX_N(N)], max_jerk.e) /** * Use LIN_ADVANCE for blocks if all these are true: * * esteps : This is a print move, because we checked for A, B, C steps before. * * extruder_advance_K[extruder] : There is an advance factor set for this extruder. * * dm.e : Extruder is running forward (e.g., for "Wipe while retracting" (Slic3r) or "Combing" (Cura) moves) */ use_advance_lead = esteps && extruder_advance_K[E_INDEX_N(extruder)] && dm.e; if (use_advance_lead) { float e_D_ratio = (target_float.e - position_float.e) / TERN(IS_KINEMATIC, block->millimeters, SQRT(sq(target_float.x - position_float.x) + sq(target_float.y - position_float.y) + sq(target_float.z - position_float.z)) ); // Check for unusual high e_D ratio to detect if a retract move was combined with the last print move due to min. steps per segment. Never execute this with advance! // This assumes no one will use a retract length of 0mm < retr_length < ~0.2mm and no one will print 100mm wide lines using 3mm filament or 35mm wide lines using 1.75mm filament. if (e_D_ratio > 3.0f) use_advance_lead = false; else { // Scale E acceleration so that it will be possible to jump to the advance speed. const uint32_t max_accel_steps_per_s2 = MAX_E_JERK(extruder) / (extruder_advance_K[E_INDEX_N(extruder)] * e_D_ratio) * steps_per_mm; if (accel > max_accel_steps_per_s2) { accel = max_accel_steps_per_s2; if (ENABLED(LA_DEBUG)) SERIAL_ECHOLNPGM("Acceleration limited."); } } } #endif // Limit acceleration per axis if (block->step_event_count <= acceleration_long_cutoff) { LOGICAL_AXIS_CODE( LIMIT_ACCEL_LONG(E_AXIS, E_INDEX_N(extruder)), LIMIT_ACCEL_LONG(A_AXIS, 0), LIMIT_ACCEL_LONG(B_AXIS, 0), LIMIT_ACCEL_LONG(C_AXIS, 0), LIMIT_ACCEL_LONG(I_AXIS, 0), LIMIT_ACCEL_LONG(J_AXIS, 0), LIMIT_ACCEL_LONG(K_AXIS, 0), LIMIT_ACCEL_LONG(U_AXIS, 0), LIMIT_ACCEL_LONG(V_AXIS, 0), LIMIT_ACCEL_LONG(W_AXIS, 0) ); } else { LOGICAL_AXIS_CODE( LIMIT_ACCEL_FLOAT(E_AXIS, E_INDEX_N(extruder)), LIMIT_ACCEL_FLOAT(A_AXIS, 0), LIMIT_ACCEL_FLOAT(B_AXIS, 0), LIMIT_ACCEL_FLOAT(C_AXIS, 0), LIMIT_ACCEL_FLOAT(I_AXIS, 0), LIMIT_ACCEL_FLOAT(J_AXIS, 0), LIMIT_ACCEL_FLOAT(K_AXIS, 0), LIMIT_ACCEL_FLOAT(U_AXIS, 0), LIMIT_ACCEL_FLOAT(V_AXIS, 0), LIMIT_ACCEL_FLOAT(W_AXIS, 0) ); } } block->acceleration_steps_per_s2 = accel; block->acceleration = accel / steps_per_mm; #if DISABLED(S_CURVE_ACCELERATION) block->acceleration_rate = (uint32_t)(accel * (float(1UL << 24) / (STEPPER_TIMER_RATE))); #endif #if ENABLED(LIN_ADVANCE) block->la_advance_rate = 0; block->la_scaling = 0; if (use_advance_lead) { // the Bresenham algorithm will convert this step rate into extruder steps block->la_advance_rate = extruder_advance_K[E_INDEX_N(extruder)] * block->acceleration_steps_per_s2; // reduce LA ISR frequency by calling it only often enough to ensure that there will // never be more than four extruder steps per call for (uint32_t dividend = block->steps.e << 1; dividend <= (block->step_event_count >> 2); dividend <<= 1) block->la_scaling++; #if ENABLED(LA_DEBUG) if (block->la_advance_rate >> block->la_scaling > 10000) SERIAL_ECHOLNPGM("eISR running at > 10kHz: ", block->la_advance_rate); #endif } #endif // The minimum possible speed is the average speed for // the first / last step at current acceleration limit minimum_planner_speed_sqr = 0.5f * block->acceleration / steps_per_mm; float vmax_junction_sqr; // Initial limit on the segment entry velocity (mm/s)^2 #if HAS_JUNCTION_DEVIATION /** * Compute maximum allowable entry speed at junction by centripetal acceleration approximation. * Let a circle be tangent to both previous and current path line segments, where the junction * deviation is defined as the distance from the junction to the closest edge of the circle, * colinear with the circle center. The circular segment joining the two paths represents the * path of centripetal acceleration. Solve for max velocity based on max acceleration about the * radius of the circle, defined indirectly by junction deviation. This may be also viewed as * path width or max_jerk in the previous Grbl version. This approach does not actually deviate * from path, but used as a robust way to compute cornering speeds, as it takes into account the * nonlinearities of both the junction angle and junction velocity. * * NOTE: If the junction deviation value is finite, Grbl executes the motions in an exact path * mode (G61). If the junction deviation value is zero, Grbl will execute the motion in an exact * stop mode (G61.1) manner. In the future, if continuous mode (G64) is desired, the math here * is exactly the same. Instead of motioning all the way to junction point, the machine will * just follow the arc circle defined here. The Arduino doesn't have the CPU cycles to perform * a continuous mode path, but ARM-based microcontrollers most certainly do. * * NOTE: The max junction speed is a fixed value, since machine acceleration limits cannot be * changed dynamically during operation nor can the line move geometry. This must be kept in * memory in the event of a feedrate override changing the nominal speeds of blocks, which can * change the overall maximum entry speed conditions of all blocks. * * ####### * https://github.com/MarlinFirmware/Marlin/issues/10341#issuecomment-388191754 * * hoffbaked: on May 10 2018 tuned and improved the GRBL algorithm for Marlin: Okay! It seems to be working good. I somewhat arbitrarily cut it off at 1mm on then on anything with less sides than an octagon. With this, and the reverse pass actually recalculating things, a corner acceleration value of 1000 junction deviation of .05 are pretty reasonable. If the cycles can be spared, a better acos could be used. For all I know, it may be already calculated in a different place. */ // Unit vector of previous path line segment static xyze_float_t prev_unit_vec; xyze_float_t unit_vec = #if HAS_DIST_MM_ARG cart_dist_mm #else LOGICAL_AXIS_ARRAY(dist_mm.e, dist_mm.x, dist_mm.y, dist_mm.z, dist_mm.i, dist_mm.j, dist_mm.k, dist_mm.u, dist_mm.v, dist_mm.w) #endif ; /** * On CoreXY the length of the vector [A,B] is SQRT(2) times the length of the head movement vector [X,Y]. * So taking Z and E into account, we cannot scale to a unit vector with "inverse_millimeters". * => normalize the complete junction vector. * Elsewise, when needed JD will factor-in the E component */ if (ANY(IS_CORE, MARKFORGED_XY, MARKFORGED_YX) || esteps > 0) normalize_junction_vector(unit_vec); // Normalize with XYZE components else unit_vec *= inverse_millimeters; // Use pre-calculated (1 / SQRT(x^2 + y^2 + z^2)) // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed)) { // Compute cosine of angle between previous and current path. (prev_unit_vec is negative) // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity. float junction_cos_theta = LOGICAL_AXIS_GANG( + (-prev_unit_vec.e * unit_vec.e), + (-prev_unit_vec.x * unit_vec.x), + (-prev_unit_vec.y * unit_vec.y), + (-prev_unit_vec.z * unit_vec.z), + (-prev_unit_vec.i * unit_vec.i), + (-prev_unit_vec.j * unit_vec.j), + (-prev_unit_vec.k * unit_vec.k), + (-prev_unit_vec.u * unit_vec.u), + (-prev_unit_vec.v * unit_vec.v), + (-prev_unit_vec.w * unit_vec.w) ); // NOTE: Computed without any expensive trig, sin() or acos(), by trig half angle identity of cos(theta). if (junction_cos_theta > 0.999999f) { // For a 0 degree acute junction, just set minimum junction speed. vmax_junction_sqr = minimum_planner_speed_sqr; } else { // Convert delta vector to unit vector xyze_float_t junction_unit_vec = unit_vec - prev_unit_vec; normalize_junction_vector(junction_unit_vec); const float junction_acceleration = limit_value_by_axis_maximum(block->acceleration, junction_unit_vec); if (TERN0(HINTS_CURVE_RADIUS, hints.curve_radius)) { TERN_(HINTS_CURVE_RADIUS, vmax_junction_sqr = junction_acceleration * hints.curve_radius); } else { NOLESS(junction_cos_theta, -0.999999f); // Check for numerical round-off to avoid divide by zero. const float sin_theta_d2 = SQRT(0.5f * (1.0f - junction_cos_theta)); // Trig half angle identity. Always positive. vmax_junction_sqr = junction_acceleration * junction_deviation_mm * sin_theta_d2 / (1.0f - sin_theta_d2); #if ENABLED(JD_HANDLE_SMALL_SEGMENTS) // For small moves with >135° junction (octagon) find speed for approximate arc if (block->millimeters < 1 && junction_cos_theta < -0.7071067812f) { #if ENABLED(JD_USE_MATH_ACOS) #error "TODO: Inline maths with the MCU / FPU." #elif ENABLED(JD_USE_LOOKUP_TABLE) // Fast acos approximation (max. error +-0.01 rads) // Based on LUT table and linear interpolation /** * // Generate the JD Lookup Table * constexpr float c = 1.00751495f; // Correction factor to center error around 0 * for (int i = 0; i < jd_lut_count - 1; ++i) { * const float x0 = (sq(i) - 1) / sq(i), * y0 = acos(x0) * (i == 0 ? 1 : c), * x1 = i < jd_lut_count - 1 ? 0.5 * x0 + 0.5 : 0.999999f, * y1 = acos(x1) * (i < jd_lut_count - 1 ? c : 1); * jd_lut_k[i] = (y0 - y1) / (x0 - x1); * jd_lut_b[i] = (y1 * x0 - y0 * x1) / (x0 - x1); * } * * // Compute correction factor (Set c to 1.0f first!) * float min = INFINITY, max = -min; * for (float t = 0; t <= 1; t += 0.0003f) { * const float e = acos(t) / approx(t); * if (isfinite(e)) { * if (e < min) min = e; * if (e > max) max = e; * } * } * fprintf(stderr, "%.9gf, ", (min + max) / 2); */ static constexpr int16_t jd_lut_count = 16; static constexpr uint16_t jd_lut_tll = _BV(jd_lut_count - 1); static constexpr int16_t jd_lut_tll0 = __builtin_clz(jd_lut_tll) + 1; // i.e., 16 - jd_lut_count + 1 static constexpr float jd_lut_k[jd_lut_count] PROGMEM = { -1.03145837f, -1.30760646f, -1.75205851f, -2.41705704f, -3.37769222f, -4.74888992f, -6.69649887f, -9.45661736f, -13.3640480f, -18.8928222f, -26.7136841f, -37.7754593f, -53.4201813f, -75.5458374f, -106.836761f, -218.532821f }; static constexpr float jd_lut_b[jd_lut_count] PROGMEM = { 1.57079637f, 1.70887053f, 2.04220939f, 2.62408352f, 3.52467871f, 4.85302639f, 6.77020454f, 9.50875854f, 13.4009285f, 18.9188995f, 26.7321243f, 37.7885055f, 53.4293975f, 75.5523529f, 106.841369f, 218.534011f }; const float neg = junction_cos_theta < 0 ? -1 : 1, t = neg * junction_cos_theta; const int16_t idx = (t < 0.00000003f) ? 0 : __builtin_clz(uint16_t((1.0f - t) * jd_lut_tll)) - jd_lut_tll0; float junction_theta = t * pgm_read_float(&jd_lut_k[idx]) + pgm_read_float(&jd_lut_b[idx]); if (neg > 0) junction_theta = RADIANS(180) - junction_theta; // acos(-t) #else // Fast acos(-t) approximation (max. error +-0.033rad = 1.89°) // Based on MinMax polynomial published by W. Randolph Franklin, see // https://wrf.ecse.rpi.edu/Research/Short_Notes/arcsin/onlyelem.html // acos( t) = pi / 2 - asin(x) // acos(-t) = pi - acos(t) ... pi / 2 + asin(x) const float neg = junction_cos_theta < 0 ? -1 : 1, t = neg * junction_cos_theta, asinx = 0.032843707f + t * (-1.451838349f + t * ( 29.66153956f + t * (-131.1123477f + t * ( 262.8130562f + t * (-242.7199627f + t * ( 84.31466202f ) ))))), junction_theta = RADIANS(90) + neg * asinx; // acos(-t) // NOTE: junction_theta bottoms out at 0.033 which avoids divide by 0. #endif const float limit_sqr = (block->millimeters * junction_acceleration) / junction_theta; NOMORE(vmax_junction_sqr, limit_sqr); } #endif // JD_HANDLE_SMALL_SEGMENTS } } // Get the lowest speed vmax_junction_sqr = _MIN(vmax_junction_sqr, sq(block->nominal_speed), sq(previous_nominal_speed)); } else // Init entry speed to zero. Assume it starts from rest. Planner will correct this later. vmax_junction_sqr = 0; prev_unit_vec = unit_vec; #else // CLASSIC_JERK /** * Heavily modified. Originally adapted from Průša firmware. * https://github.com/prusa3d/Prusa-Firmware */ #if defined(TRAVEL_EXTRA_XYJERK) || ENABLED(LIN_ADVANCE) xyze_float_t max_j = max_jerk; #else const xyze_float_t &max_j = max_jerk; #endif #ifdef TRAVEL_EXTRA_XYJERK if (dist.e <= 0) { max_j.x += TRAVEL_EXTRA_XYJERK; max_j.y += TRAVEL_EXTRA_XYJERK; } #endif #if ENABLED(LIN_ADVANCE) // Advance affects E_AXIS speed and therefore jerk. Add a speed correction whenever // LA is turned OFF. No correction is applied when LA is turned ON (because it didn't // perform well; it takes more time/effort to push/melt filament than the reverse). static uint32_t previous_advance_rate; static float previous_e_mm_per_step; if (dist.e < 0 && previous_advance_rate) { // Retract move after a segment with LA that ended with an E speed decrease. // Correct for this to allow a faster junction speed. Since the decrease always helps to // get E to nominal retract speed, the equation simplifies to an increase in max jerk. max_j.e += previous_advance_rate * previous_e_mm_per_step; } // Prepare for next segment. previous_advance_rate = block->la_advance_rate; previous_e_mm_per_step = mm_per_step[E_AXIS_N(extruder)]; #endif xyze_float_t speed_diff = current_speed; float vmax_junction; const bool start_from_zero = !moves_queued || UNEAR_ZERO(previous_nominal_speed); if (start_from_zero) { // Limited by a jerk to/from full halt. vmax_junction = block->nominal_speed; } else { // Compute the maximum velocity allowed at a joint of two successive segments. // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum. // Scale per-axis velocities for the same vmax_junction. if (block->nominal_speed < previous_nominal_speed) { vmax_junction = block->nominal_speed; const float previous_scale = vmax_junction / previous_nominal_speed; LOOP_LOGICAL_AXES(i) speed_diff[i] -= previous_speed[i] * previous_scale; } else { vmax_junction = previous_nominal_speed; const float current_scale = vmax_junction / block->nominal_speed; LOOP_LOGICAL_AXES(i) speed_diff[i] = speed_diff[i] * current_scale - previous_speed[i]; } } // Now limit the jerk in all axes. float v_factor = 1.0f; LOOP_LOGICAL_AXES(i) { // Jerk is the per-axis velocity difference. const float jerk = ABS(speed_diff[i]), maxj = max_j[i]; if (jerk * v_factor > maxj) v_factor = maxj / jerk; } vmax_junction_sqr = sq(vmax_junction * v_factor); if (start_from_zero) minimum_planner_speed_sqr = vmax_junction_sqr; #endif // CLASSIC_JERK // Max entry speed of this block equals the max exit speed of the previous block. block->max_entry_speed_sqr = vmax_junction_sqr; // Initialize block entry speed. Compute based on deceleration to sqrt(minimum_planner_speed_sqr). const float v_allowable_sqr = max_allowable_speed_sqr(-block->acceleration, minimum_planner_speed_sqr, block->millimeters); // Start with the minimum allowed speed block->entry_speed_sqr = minimum_planner_speed_sqr; // Initialize planner efficiency flags // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then // the current block and next block junction speeds are guaranteed to always be at their maximum // junction speeds in deceleration and acceleration, respectively. This is due to how the current // block nominal speed limits both the current and next maximum junction speeds. Hence, in both // the reverse and forward planners, the corresponding block junction speed will always be at the // the maximum junction speed and may always be ignored for any speed reduction checks. block->flag.set_nominal(sq(block->nominal_speed) <= v_allowable_sqr); // Update previous path unit_vector and nominal speed previous_speed = current_speed; previous_nominal_speed = block->nominal_speed; position = target; // Update the position #if ENABLED(POWER_LOSS_RECOVERY) block->sdpos = recovery.command_sdpos(); block->start_position = position_float.asLogical(); #endif TERN_(HAS_POSITION_FLOAT, position_float = target_float); TERN_(GRADIENT_MIX, mixer.gradient_control(target_float.z)); return true; // Movement was accepted } // _populate_block() /** * @brief Add a block to the buffer that just updates the position * Supports LASER_SYNCHRONOUS_M106_M107 and LASER_POWER_SYNC power sync block buffer queueing. * * @param sync_flag The sync flag to set, determining the type of sync the block will do */ void Planner::buffer_sync_block(const BlockFlagBit sync_flag/*=BLOCK_BIT_SYNC_POSITION*/) { // Wait for the next available block uint8_t next_buffer_head; block_t * const block = get_next_free_block(next_buffer_head); // Clear block block->reset(); block->flag.apply(sync_flag); block->position = position; #if ENABLED(BACKLASH_COMPENSATION) LOOP_NUM_AXES(axis) block->position[axis] += backlash.get_applied_steps((AxisEnum)axis); #endif #if ENABLED(LASER_SYNCHRONOUS_M106_M107) FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i]; #endif /** * M3-based power setting can be processed inline with a laser power sync block. * During active moves cutter.power is processed immediately, otherwise on the next move. */ TERN_(LASER_POWER_SYNC, block->laser.power = cutter.power); // If this is the first added movement, reload the delay, otherwise, cancel it. if (block_buffer_head == block_buffer_tail) { // If it was the first queued block, restart the 1st block delivery delay, to // give the planner an opportunity to queue more movements and plan them // As there are no queued movements, the Stepper ISR will not touch this // variable, so there is no risk setting this here (but it MUST be done // before the following line!!) delay_before_delivering = TERN_(FT_MOTION, ftMotion.cfg.mode ? BLOCK_DELAY_NONE :) BLOCK_DELAY_FOR_1ST_MOVE; } block_buffer_head = next_buffer_head; stepper.wake_up(); } // buffer_sync_block() /** * @brief Add a single linear movement * * @description Add a new linear movement to the buffer in axis units. * Leveling and kinematics should be applied before calling this. * * @param abce Target position in mm and/or degrees * @param cart_dist_mm The pre-calculated move lengths for all axes, in mm * @param fr_mm_s (target) speed of the move * @param extruder optional target extruder (otherwise active_extruder) * @param hints optional parameters to aid planner calculations * * @return false if no segment was queued due to cleaning, cold extrusion, full queue, etc. */ bool Planner::buffer_segment(const abce_pos_t &abce OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm) , const_feedRate_t fr_mm_s , const uint8_t extruder/*=active_extruder*/ , const PlannerHints &hints/*=PlannerHints()*/ ) { // If we are cleaning, do not accept queuing of movements if (cleaning_buffer_counter) return false; // When changing extruders recalculate steps corresponding to the E position #if ENABLED(DISTINCT_E_FACTORS) if (last_extruder != extruder && settings.axis_steps_per_mm[E_AXIS_N(extruder)] != settings.axis_steps_per_mm[E_AXIS_N(last_extruder)]) { position.e = LROUND(position.e * settings.axis_steps_per_mm[E_AXIS_N(extruder)] * mm_per_step[E_AXIS_N(last_extruder)]); last_extruder = extruder; } #endif // The target position of the tool in absolute steps // Calculate target position in absolute steps const abce_long_t target = { LOGICAL_AXIS_LIST( int32_t(LROUND(abce.e * settings.axis_steps_per_mm[E_AXIS_N(extruder)])), int32_t(LROUND(abce.a * settings.axis_steps_per_mm[A_AXIS])), int32_t(LROUND(abce.b * settings.axis_steps_per_mm[B_AXIS])), int32_t(LROUND(abce.c * settings.axis_steps_per_mm[C_AXIS])), int32_t(LROUND(abce.i * settings.axis_steps_per_mm[I_AXIS])), int32_t(LROUND(abce.j * settings.axis_steps_per_mm[J_AXIS])), int32_t(LROUND(abce.k * settings.axis_steps_per_mm[K_AXIS])), int32_t(LROUND(abce.u * settings.axis_steps_per_mm[U_AXIS])), int32_t(LROUND(abce.v * settings.axis_steps_per_mm[V_AXIS])), int32_t(LROUND(abce.w * settings.axis_steps_per_mm[W_AXIS])) ) }; #if HAS_POSITION_FLOAT const xyze_pos_t target_float = abce; #endif #if HAS_EXTRUDERS // DRYRUN prevents E moves from taking place if (DEBUGGING(DRYRUN) || TERN0(CANCEL_OBJECTS, cancelable.skipping)) { position.e = target.e; TERN_(HAS_POSITION_FLOAT, position_float.e = abce.e); } #endif /* <-- add a slash to enable SERIAL_ECHOPGM(" buffer_segment FR:", fr_mm_s); #if IS_KINEMATIC SERIAL_ECHOPGM(" A:", abce.a, " (", position.a, "->", target.a, ") B:", abce.b); #else SERIAL_ECHOPGM_P(SP_X_LBL, abce.a); SERIAL_ECHOPGM(" (", position.x, "->", target.x); SERIAL_CHAR(')'); SERIAL_ECHOPGM_P(SP_Y_LBL, abce.b); #endif SERIAL_ECHOPGM(" (", position.y, "->", target.y); #if HAS_Z_AXIS #if ENABLED(DELTA) SERIAL_ECHOPGM(") C:", abce.c); #else SERIAL_CHAR(')'); SERIAL_ECHOPGM_P(SP_Z_LBL, abce.c); #endif SERIAL_ECHOPGM(" (", position.z, "->", target.z); SERIAL_CHAR(')'); #endif #if HAS_I_AXIS SERIAL_ECHOPGM_P(SP_I_LBL, abce.i); SERIAL_ECHOPGM(" (", position.i, "->", target.i); SERIAL_CHAR(')'); #endif #if HAS_J_AXIS SERIAL_ECHOPGM_P(SP_J_LBL, abce.j); SERIAL_ECHOPGM(" (", position.j, "->", target.j); SERIAL_CHAR(')'); #endif #if HAS_K_AXIS SERIAL_ECHOPGM_P(SP_K_LBL, abce.k); SERIAL_ECHOPGM(" (", position.k, "->", target.k); SERIAL_CHAR(')'); #endif #if HAS_U_AXIS SERIAL_ECHOPGM_P(SP_U_LBL, abce.u); SERIAL_ECHOPGM(" (", position.u, "->", target.u); SERIAL_CHAR(')'); #endif #if HAS_V_AXIS SERIAL_ECHOPGM_P(SP_V_LBL, abce.v); SERIAL_ECHOPGM(" (", position.v, "->", target.v); SERIAL_CHAR(')'); #endif #if HAS_W_AXIS SERIAL_ECHOPGM_P(SP_W_LBL, abce.w); SERIAL_ECHOPGM(" (", position.w, "->", target.w); SERIAL_CHAR(')'); #endif #if HAS_EXTRUDERS SERIAL_ECHOPGM_P(SP_E_LBL, abce.e); SERIAL_ECHOLNPGM(" (", position.e, "->", target.e, ")"); #else SERIAL_EOL(); #endif //*/ // Queue the movement. Return 'false' if the move was not queued. if (!_buffer_steps(target OPTARG(HAS_POSITION_FLOAT, target_float) OPTARG(HAS_DIST_MM_ARG, cart_dist_mm) , fr_mm_s, extruder, hints )) return false; stepper.wake_up(); return true; } // buffer_segment() /** * Add a new linear movement to the buffer. * The target is cartesian. It's translated to * delta/scara if needed. * * cart - target position in mm or degrees * fr_mm_s - (target) speed of the move (mm/s) * extruder - optional target extruder (otherwise active_extruder) * hints - optional parameters to aid planner calculations */ bool Planner::buffer_line(const xyze_pos_t &cart, const_feedRate_t fr_mm_s , const uint8_t extruder/*=active_extruder*/ , const PlannerHints &hints/*=PlannerHints()*/ ) { xyze_pos_t machine = cart; TERN_(HAS_POSITION_MODIFIERS, apply_modifiers(machine)); #if IS_KINEMATIC #if HAS_JUNCTION_DEVIATION const xyze_pos_t cart_dist_mm = LOGICAL_AXIS_ARRAY( cart.e - position_cart.e, cart.x - position_cart.x, cart.y - position_cart.y, cart.z - position_cart.z, cart.i - position_cart.i, cart.j - position_cart.j, cart.k - position_cart.k, cart.u - position_cart.u, cart.v - position_cart.v, cart.w - position_cart.w ); #else const xyz_pos_t cart_dist_mm = NUM_AXIS_ARRAY( cart.x - position_cart.x, cart.y - position_cart.y, cart.z - position_cart.z, cart.i - position_cart.i, cart.j - position_cart.j, cart.k - position_cart.k, cart.u - position_cart.u, cart.v - position_cart.v, cart.w - position_cart.w ); #endif // Cartesian XYZ to kinematic ABC, stored in global 'delta' inverse_kinematics(machine); PlannerHints ph = hints; if (!hints.millimeters) ph.millimeters = get_move_distance(xyze_pos_t(cart_dist_mm) OPTARG(HAS_ROTATIONAL_AXES, ph.cartesian_move)); #if DISABLED(FEEDRATE_SCALING) const feedRate_t feedrate = fr_mm_s; #elif IS_SCARA // For SCARA scale the feedrate from mm/s to degrees/s // i.e., Complete the angular vector in the given time. const float duration_recip = hints.inv_duration ?: fr_mm_s / ph.millimeters; const xyz_pos_t diff = delta - position_float; const feedRate_t feedrate = diff.magnitude() * duration_recip; #elif ENABLED(POLAR) /** * Motion problem for Polar axis near center / origin: * * 3D printing: * Movements very close to the center of the polar axis take more time than others. * This brief delay results in more material deposition due to the pressure in the nozzle. * * Current Kinematics and feedrate scaling deals with this by making the movement as fast * as possible. It works for slow movements but doesn't work well with fast ones. A more * complicated extrusion compensation must be implemented. * * Ideally, it should estimate that a long rotation near the center is ahead and will cause * unwanted deposition. Therefore it can compensate the extrusion beforehand. * * Laser cutting: * Same thing would be a problem for laser engraving too. As it spends time rotating at the * center point, more likely it will burn more material than it should. Therefore similar * compensation would be implemented for laser-cutting operations. * * Milling: * This shouldn't be a problem for cutting/milling operations. */ feedRate_t calculated_feedrate = fr_mm_s; const xyz_pos_t diff = delta - position_float; if (!NEAR_ZERO(diff.b)) { if (delta.a <= POLAR_FAST_RADIUS ) calculated_feedrate = settings.max_feedrate_mm_s[Y_AXIS]; else { // Normalized vector of movement const float diffBLength = ABS((2.0f * M_PI * diff.a) * (diff.b / 360.0f)), diffTheta = DEGREES(ATAN2(diff.a, diffBLength)), normalizedTheta = 1.0f - (ABS(diffTheta > 90.0f ? 180.0f - diffTheta : diffTheta) / 90.0f); // Normalized position along the radius const float radiusRatio = (PRINTABLE_RADIUS) / delta.a; calculated_feedrate += (fr_mm_s * radiusRatio * normalizedTheta); } } const feedRate_t feedrate = calculated_feedrate; #endif // POLAR && FEEDRATE_SCALING TERN_(HAS_EXTRUDERS, delta.e = machine.e); if (buffer_segment(delta OPTARG(HAS_DIST_MM_ARG, cart_dist_mm), feedrate, extruder, ph)) { position_cart = cart; return true; } return false; #else // !IS_KINEMATIC return buffer_segment(machine, fr_mm_s, extruder, hints); #endif } // buffer_line() #if ENABLED(DIRECT_STEPPING) void Planner::buffer_page(const page_idx_t page_idx, const uint8_t extruder, const uint16_t num_steps) { if (!last_page_step_rate) { kill(GET_TEXT_F(MSG_BAD_PAGE_SPEED)); return; } uint8_t next_buffer_head; block_t * const block = get_next_free_block(next_buffer_head); block->flag.reset(BLOCK_BIT_PAGE); #if HAS_FAN FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i]; #endif E_TERN_(block->extruder = extruder); block->page_idx = page_idx; block->step_event_count = num_steps; block->initial_rate = block->final_rate = block->nominal_rate = last_page_step_rate; // steps/s block->accelerate_until = 0; block->decelerate_after = block->step_event_count; // Will be set to last direction later if directional format. block->direction_bits.reset(); if (!DirectStepping::Config::DIRECTIONAL) { #define PAGE_UPDATE_DIR(AXIS) do{ if (last_page_dir.AXIS) block->direction_bits.AXIS = true; }while(0); LOGICAL_AXIS_MAP(PAGE_UPDATE_DIR); } // If this is the first added movement, reload the delay, otherwise, cancel it. if (block_buffer_head == block_buffer_tail) { // If it was the first queued block, restart the 1st block delivery delay, to // give the planner an opportunity to queue more movements and plan them // As there are no queued movements, the Stepper ISR will not touch this // variable, so there is no risk setting this here (but it MUST be done // before the following line!!) delay_before_delivering = TERN_(FT_MOTION, ftMotion.cfg.mode ? BLOCK_DELAY_NONE :) BLOCK_DELAY_FOR_1ST_MOVE; } // Move buffer head block_buffer_head = next_buffer_head; stepper.enable_all_steppers(); stepper.wake_up(); } #endif // DIRECT_STEPPING /** * Directly set the planner ABCE position (and stepper positions) * converting mm (or angles for SCARA) into steps. * * The provided ABCE position is in machine units. */ void Planner::set_machine_position_mm(const abce_pos_t &abce) { // When FT Motion is enabled, call synchronize() here instead of generating a sync block if (TERN0(FT_MOTION, ftMotion.cfg.mode)) synchronize(); TERN_(DISTINCT_E_FACTORS, last_extruder = active_extruder); TERN_(HAS_POSITION_FLOAT, position_float = abce); position.set( LOGICAL_AXIS_LIST( LROUND(abce.e * settings.axis_steps_per_mm[E_AXIS_N(active_extruder)]), LROUND(abce.a * settings.axis_steps_per_mm[A_AXIS]), LROUND(abce.b * settings.axis_steps_per_mm[B_AXIS]), LROUND(abce.c * settings.axis_steps_per_mm[C_AXIS]), LROUND(abce.i * settings.axis_steps_per_mm[I_AXIS]), LROUND(abce.j * settings.axis_steps_per_mm[J_AXIS]), LROUND(abce.k * settings.axis_steps_per_mm[K_AXIS]), LROUND(abce.u * settings.axis_steps_per_mm[U_AXIS]), LROUND(abce.v * settings.axis_steps_per_mm[V_AXIS]), LROUND(abce.w * settings.axis_steps_per_mm[W_AXIS]) ) ); if (has_blocks_queued()) { //previous_nominal_speed = 0.0f; // Reset planner junction speeds. Assume start from rest. //previous_speed.reset(); buffer_sync_block(BLOCK_BIT_SYNC_POSITION); } else { #if ENABLED(BACKLASH_COMPENSATION) abce_long_t stepper_pos = position; LOOP_NUM_AXES(axis) stepper_pos[axis] += backlash.get_applied_steps((AxisEnum)axis); stepper.set_position(stepper_pos); #else stepper.set_position(position); #endif } } void Planner::set_position_mm(const xyze_pos_t &xyze) { xyze_pos_t machine = xyze; TERN_(HAS_POSITION_MODIFIERS, apply_modifiers(machine, true)); #if IS_KINEMATIC position_cart = xyze; inverse_kinematics(machine); TERN_(HAS_EXTRUDERS, delta.e = machine.e); set_machine_position_mm(delta); #else set_machine_position_mm(machine); #endif } #if HAS_EXTRUDERS /** * Setters for planner position (also setting stepper position). */ void Planner::set_e_position_mm(const_float_t e) { const uint8_t axis_index = E_AXIS_N(active_extruder); TERN_(DISTINCT_E_FACTORS, last_extruder = active_extruder); const float e_new = DIFF_TERN(FWRETRACT, e, fwretract.current_retract[active_extruder]); position.e = LROUND(settings.axis_steps_per_mm[axis_index] * e_new); TERN_(HAS_POSITION_FLOAT, position_float.e = e_new); TERN_(IS_KINEMATIC, TERN_(HAS_EXTRUDERS, position_cart.e = e)); if (has_blocks_queued()) buffer_sync_block(BLOCK_BIT_SYNC_POSITION); else stepper.set_axis_position(E_AXIS, position.e); } #endif // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2 void Planner::refresh_acceleration_rates() { uint32_t highest_rate = 1; LOOP_DISTINCT_AXES(i) { max_acceleration_steps_per_s2[i] = settings.max_acceleration_mm_per_s2[i] * settings.axis_steps_per_mm[i]; if (TERN1(DISTINCT_E_FACTORS, i < E_AXIS || i == E_AXIS_N(active_extruder))) NOLESS(highest_rate, max_acceleration_steps_per_s2[i]); } acceleration_long_cutoff = 4294967295UL / highest_rate; // 0xFFFFFFFFUL TERN_(HAS_LINEAR_E_JERK, recalculate_max_e_jerk()); } /** * Recalculate 'position' and 'mm_per_step'. * Must be called whenever settings.axis_steps_per_mm changes! */ void Planner::refresh_positioning() { #if ENABLED(EDITABLE_STEPS_PER_UNIT) LOOP_DISTINCT_AXES(i) mm_per_step[i] = 1.0f / settings.axis_steps_per_mm[i]; #endif set_position_mm(current_position); refresh_acceleration_rates(); } // Apply limits to a variable and give a warning if the value was out of range inline void limit_and_warn(float &val, const AxisEnum axis, FSTR_P const setting_name, const xyze_float_t &max_limit) { const uint8_t lim_axis = TERN_(HAS_EXTRUDERS, axis > E_AXIS ? E_AXIS :) axis; const float before = val; LIMIT(val, 0.1f, max_limit[lim_axis]); if (before != val) SERIAL_ECHOLN(C(AXIS_CHAR(lim_axis)), F(" Max "), setting_name, F(" limited to "), val); } /** * For the specified 'axis' set the Maximum Acceleration to the given value (mm/s^2) * The value may be limited with warning feedback, if configured. * Calls refresh_acceleration_rates to precalculate planner terms in steps. * * This hard limit is applied as a block is being added to the planner queue. */ void Planner::set_max_acceleration(const AxisEnum axis, float inMaxAccelMMS2) { #if ENABLED(LIMITED_MAX_ACCEL_EDITING) #ifdef MAX_ACCEL_EDIT_VALUES constexpr xyze_float_t max_accel_edit = MAX_ACCEL_EDIT_VALUES; const xyze_float_t &max_acc_edit_scaled = max_accel_edit; #else constexpr xyze_float_t max_accel_edit = DEFAULT_MAX_ACCELERATION; const xyze_float_t max_acc_edit_scaled = max_accel_edit * 2; #endif limit_and_warn(inMaxAccelMMS2, axis, F("Acceleration"), max_acc_edit_scaled); #endif settings.max_acceleration_mm_per_s2[axis] = inMaxAccelMMS2; // Update steps per s2 to agree with the units per s2 (since they are used in the planner) refresh_acceleration_rates(); } /** * For the specified 'axis' set the Maximum Feedrate to the given value (mm/s) * The value may be limited with warning feedback, if configured. * * This hard limit is applied as a block is being added to the planner queue. */ void Planner::set_max_feedrate(const AxisEnum axis, float inMaxFeedrateMMS) { #if ENABLED(LIMITED_MAX_FR_EDITING) #ifdef MAX_FEEDRATE_EDIT_VALUES constexpr xyze_float_t max_fr_edit = MAX_FEEDRATE_EDIT_VALUES; const xyze_float_t &max_fr_edit_scaled = max_fr_edit; #else constexpr xyze_float_t max_fr_edit = DEFAULT_MAX_FEEDRATE; const xyze_float_t max_fr_edit_scaled = max_fr_edit * 2; #endif limit_and_warn(inMaxFeedrateMMS, axis, F("Feedrate"), max_fr_edit_scaled); #endif settings.max_feedrate_mm_s[axis] = inMaxFeedrateMMS; } #if ENABLED(CLASSIC_JERK) /** * For the specified 'axis' set the Maximum Jerk (instant change) to the given value (mm/s) * The value may be limited with warning feedback, if configured. * * This hard limit is applied (to the block start speed) as the block is being added to the planner queue. */ void Planner::set_max_jerk(const AxisEnum axis, float inMaxJerkMMS) { #if ENABLED(LIMITED_JERK_EDITING) constexpr xyze_float_t max_jerk_edit = #ifdef MAX_JERK_EDIT_VALUES MAX_JERK_EDIT_VALUES #else LOGICAL_AXIS_ARRAY( (DEFAULT_EJERK) * 2, (DEFAULT_XJERK) * 2, (DEFAULT_YJERK) * 2, (DEFAULT_ZJERK) * 2, (DEFAULT_IJERK) * 2, (DEFAULT_JJERK) * 2, (DEFAULT_KJERK) * 2, (DEFAULT_UJERK) * 2, (DEFAULT_VJERK) * 2, (DEFAULT_WJERK) * 2 ) #endif ; limit_and_warn(inMaxJerkMMS, axis, F("Jerk"), max_jerk_edit); #endif max_jerk[axis] = inMaxJerkMMS; } #endif #if HAS_WIRED_LCD uint16_t Planner::block_buffer_runtime() { #ifdef __AVR__ // Protect the access to the variable. Only required for AVR, as // any 32bit CPU offers atomic access to 32bit variables const bool was_enabled = stepper.suspend(); #endif uint32_t bbru = block_buffer_runtime_us; #ifdef __AVR__ // Reenable Stepper ISR if (was_enabled) stepper.wake_up(); #endif // To translate µs to ms a division by 1000 would be required. // We introduce 2.4% error here by dividing by 1024. // Doesn't matter because block_buffer_runtime_us is already too small an estimation. bbru >>= 10; // limit to about a minute. return _MIN(bbru, 0x0000FFFFUL); } void Planner::clear_block_buffer_runtime() { #ifdef __AVR__ // Protect the access to the variable. Only required for AVR, as // any 32bit CPU offers atomic access to 32bit variables const bool was_enabled = stepper.suspend(); #endif block_buffer_runtime_us = 0; #ifdef __AVR__ // Reenable Stepper ISR if (was_enabled) stepper.wake_up(); #endif } #endif
2301_81045437/Marlin
Marlin/src/module/planner.cpp
C++
agpl-3.0
142,654
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 /** * planner.h * * Buffer movement commands and manage the acceleration profile plan * * Derived from Grbl * Copyright (c) 2009-2011 Simen Svale Skogsrud */ #include "../MarlinCore.h" #if ENABLED(JD_HANDLE_SMALL_SEGMENTS) // Enable this option for perfect accuracy but maximum // computation. Should be fine on ARM processors. //#define JD_USE_MATH_ACOS // Disable this option to save 120 bytes of PROGMEM, // but incur increased computation and a reduction // in accuracy. #define JD_USE_LOOKUP_TABLE #endif #include "motion.h" #include "../gcode/queue.h" #if ENABLED(DELTA) #include "delta.h" #elif ENABLED(POLARGRAPH) #include "polargraph.h" #elif ENABLED(POLAR) #include "polar.h" #endif #if ABL_PLANAR #include "../libs/vector_3.h" // for matrix_3x3 #endif #if ENABLED(FWRETRACT) #include "../feature/fwretract.h" #endif #if ENABLED(MIXING_EXTRUDER) #include "../feature/mixing.h" #endif #if HAS_CUTTER #include "../feature/spindle_laser_types.h" #endif #if ENABLED(DIRECT_STEPPING) #include "../feature/direct_stepping.h" #endif #if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER) #include "../feature/closedloop.h" #endif // Feedrate for manual moves #ifdef MANUAL_FEEDRATE constexpr xyze_feedrate_t manual_feedrate_mm_m = MANUAL_FEEDRATE, manual_feedrate_mm_s = LOGICAL_AXIS_ARRAY( MMM_TO_MMS(manual_feedrate_mm_m.e), MMM_TO_MMS(manual_feedrate_mm_m.x), MMM_TO_MMS(manual_feedrate_mm_m.y), MMM_TO_MMS(manual_feedrate_mm_m.z), MMM_TO_MMS(manual_feedrate_mm_m.i), MMM_TO_MMS(manual_feedrate_mm_m.j), MMM_TO_MMS(manual_feedrate_mm_m.k), MMM_TO_MMS(manual_feedrate_mm_m.u), MMM_TO_MMS(manual_feedrate_mm_m.v), MMM_TO_MMS(manual_feedrate_mm_m.w)); #endif #if ENABLED(BABYSTEPPING) #if ENABLED(BABYSTEP_MILLIMETER_UNITS) #define BABYSTEP_SIZE_X int32_t((BABYSTEP_MULTIPLICATOR_XY) * planner.settings.axis_steps_per_mm[X_AXIS]) #define BABYSTEP_SIZE_Y int32_t((BABYSTEP_MULTIPLICATOR_XY) * planner.settings.axis_steps_per_mm[Y_AXIS]) #define BABYSTEP_SIZE_Z int32_t((BABYSTEP_MULTIPLICATOR_Z) * planner.settings.axis_steps_per_mm[Z_AXIS]) #else #define BABYSTEP_SIZE_X BABYSTEP_MULTIPLICATOR_XY #define BABYSTEP_SIZE_Y BABYSTEP_MULTIPLICATOR_XY #define BABYSTEP_SIZE_Z BABYSTEP_MULTIPLICATOR_Z #endif #endif #if IS_KINEMATIC && HAS_JUNCTION_DEVIATION #define HAS_DIST_MM_ARG 1 #endif /** * Planner block flags as boolean bit fields */ enum BlockFlagBit { // Recalculate trapezoids on entry junction. For optimization. BLOCK_BIT_RECALCULATE, // Nominal speed always reached. // i.e., The segment is long enough, so the nominal speed is reachable if accelerating // from a safe speed (in consideration of jerking from zero speed). BLOCK_BIT_NOMINAL_LENGTH, // The block is segment 2+ of a longer move BLOCK_BIT_CONTINUED, // Sync the stepper counts from the block BLOCK_BIT_SYNC_POSITION // Direct stepping page OPTARG(DIRECT_STEPPING, BLOCK_BIT_PAGE) // Sync the fan speeds from the block OPTARG(LASER_SYNCHRONOUS_M106_M107, BLOCK_BIT_SYNC_FANS) // Sync laser power from a queued block OPTARG(LASER_POWER_SYNC, BLOCK_BIT_LASER_PWR) }; /** * Planner block flags as boolean bit fields */ typedef struct { union { uint8_t bits; struct { bool recalculate:1; bool nominal_length:1; bool continued:1; bool sync_position:1; #if ENABLED(DIRECT_STEPPING) bool page:1; #endif #if ENABLED(LASER_SYNCHRONOUS_M106_M107) bool sync_fans:1; #endif #if ENABLED(LASER_POWER_SYNC) bool sync_laser_pwr:1; #endif }; }; void clear() volatile { bits = 0; } void apply(const uint8_t f) volatile { bits |= f; } void apply(const BlockFlagBit b) volatile { SBI(bits, b); } void reset(const BlockFlagBit b) volatile { bits = _BV(b); } void set_nominal(const bool n) volatile { recalculate = true; if (n) nominal_length = true; } } block_flags_t; #if ENABLED(AUTOTEMP) typedef struct { celsius_t min, max; float factor; bool enabled; } autotemp_t; #endif #if ENABLED(LASER_FEATURE) typedef struct { bool isEnabled:1; // Set to engage the inline laser power output. bool dir:1; bool isPowered:1; // Set on any parsed G1, G2, G3, or G5 powered move, cleared on G0 and G28. bool isSyncPower:1; // Set on a M3 sync based set laser power, used to determine active trap power bool Reserved:4; } power_status_t; typedef struct { power_status_t status; // See planner settings for meaning uint8_t power; // Ditto; When in trapezoid mode this is nominal power #if ENABLED(LASER_POWER_TRAP) float trap_ramp_active_pwr; // Laser power level during active trapezoid smoothing float trap_ramp_entry_incr; // Acceleration per step laser power increment (trap entry) float trap_ramp_exit_decr; // Deceleration per step laser power decrement (trap exit) #endif } block_laser_t; #endif /** * struct block_t * * A single entry in the planner buffer. * Tracks linear movement over multiple axes. * * The "nominal" values are as-specified by G-code, and * may never actually be reached due to acceleration limits. */ typedef struct PlannerBlock { volatile block_flags_t flag; // Block flags bool is_sync_pos() { return flag.sync_position; } bool is_sync_fan() { return TERN0(LASER_SYNCHRONOUS_M106_M107, flag.sync_fans); } bool is_sync_pwr() { return TERN0(LASER_POWER_SYNC, flag.sync_laser_pwr); } bool is_sync() { return is_sync_pos() || is_sync_fan() || is_sync_pwr(); } bool is_page() { return TERN0(DIRECT_STEPPING, flag.page); } bool is_move() { return !(is_sync() || is_page()); } // Fields used by the motion planner to manage acceleration float nominal_speed, // The nominal speed for this block in (mm/sec) entry_speed_sqr, // Entry speed at previous-current junction in (mm/sec)^2 max_entry_speed_sqr, // Maximum allowable junction entry speed in (mm/sec)^2 millimeters, // The total travel of this block in mm acceleration; // acceleration mm/sec^2 union { abce_ulong_t steps; // Step count along each axis abce_long_t position; // New position to force when this sync block is executed }; uint32_t step_event_count; // The number of step events required to complete this block #if HAS_MULTI_EXTRUDER uint8_t extruder; // The extruder to move (if E move) #else static constexpr uint8_t extruder = 0; #endif #if ENABLED(MIXING_EXTRUDER) mixer_comp_t b_color[MIXING_STEPPERS]; // Normalized color for the mixing steppers #endif // Settings for the trapezoid generator uint32_t accelerate_until, // The index of the step event on which to stop acceleration decelerate_after; // The index of the step event on which to start decelerating #if ENABLED(S_CURVE_ACCELERATION) uint32_t cruise_rate, // The actual cruise rate to use, between end of the acceleration phase and start of deceleration phase acceleration_time, // Acceleration time and deceleration time in STEP timer counts deceleration_time, acceleration_time_inverse, // Inverse of acceleration and deceleration periods, expressed as integer. Scale depends on CPU being used deceleration_time_inverse; #else uint32_t acceleration_rate; // The acceleration rate used for acceleration calculation #endif AxisBits direction_bits; // Direction bits set for this block, where 1 is negative motion // Advance extrusion #if ENABLED(LIN_ADVANCE) uint32_t la_advance_rate; // The rate at which steps are added whilst accelerating uint8_t la_scaling; // Scale ISR frequency down and step frequency up by 2 ^ la_scaling uint16_t max_adv_steps, // Max advance steps to get cruising speed pressure final_adv_steps; // Advance steps for exit speed pressure #endif uint32_t nominal_rate, // The nominal step rate for this block in step_events/sec initial_rate, // The jerk-adjusted step rate at start of block final_rate, // The minimal rate at exit acceleration_steps_per_s2; // acceleration steps/sec^2 #if ENABLED(DIRECT_STEPPING) page_idx_t page_idx; // Page index used for direct stepping #endif #if HAS_CUTTER cutter_power_t cutter_power; // Power level for Spindle, Laser, etc. #endif #if HAS_FAN uint8_t fan_speed[FAN_COUNT]; #endif #if ENABLED(BARICUDA) uint8_t valve_pressure, e_to_p_pressure; #endif #if HAS_WIRED_LCD uint32_t segment_time_us; #endif #if ENABLED(POWER_LOSS_RECOVERY) uint32_t sdpos; xyze_pos_t start_position; #endif #if ENABLED(LASER_FEATURE) block_laser_t laser; #endif void reset() { memset((char*)this, 0, sizeof(*this)); } } block_t; #if ANY(LIN_ADVANCE, FEEDRATE_SCALING, GRADIENT_MIX, LCD_SHOW_E_TOTAL, POWER_LOSS_RECOVERY) #define HAS_POSITION_FLOAT 1 #endif constexpr uint8_t block_dec_mod(const uint8_t v1, const uint8_t v2) { return v1 >= v2 ? v1 - v2 : v1 - v2 + BLOCK_BUFFER_SIZE; } constexpr uint8_t block_inc_mod(const uint8_t v1, const uint8_t v2) { return v1 + v2 < BLOCK_BUFFER_SIZE ? v1 + v2 : v1 + v2 - BLOCK_BUFFER_SIZE; } #if IS_POWER_OF_2(BLOCK_BUFFER_SIZE) #define BLOCK_MOD(n) ((n)&((BLOCK_BUFFER_SIZE)-1)) #else #define BLOCK_MOD(n) ((n)%(BLOCK_BUFFER_SIZE)) #endif #if ENABLED(LASER_FEATURE) typedef struct { /** * Laser status flags */ power_status_t status; /** * Laser power: 0 or 255 in case of PWM-less laser, * or the OCR (oscillator count register) value; * Using OCR instead of raw power, because it avoids * floating point operations during the move loop. */ volatile uint8_t power; } laser_state_t; #endif #if DISABLED(EDITABLE_STEPS_PER_UNIT) static constexpr float _dasu[] = DEFAULT_AXIS_STEPS_PER_UNIT; #endif typedef struct PlannerSettings { uint32_t max_acceleration_mm_per_s2[DISTINCT_AXES], // (mm/s^2) M201 XYZE min_segment_time_us; // (µs) M205 B // (steps) M92 XYZE - Steps per millimeter #if ENABLED(EDITABLE_STEPS_PER_UNIT) float axis_steps_per_mm[DISTINCT_AXES]; #else #define _DLIM(I) _MIN(I, (signed)COUNT(_dasu) - 1) #define _DASU(N) _dasu[_DLIM(N)], #define _EASU(N) _dasu[_DLIM(E_AXIS + N)], static constexpr float axis_steps_per_mm[DISTINCT_AXES] = { REPEAT(NUM_AXES, _DASU) TERN_(HAS_EXTRUDERS, REPEAT(DISTINCT_E, _EASU)) }; #undef _EASU #undef _DASU #undef _DLIM #endif feedRate_t max_feedrate_mm_s[DISTINCT_AXES]; // (mm/s) M203 XYZE - Max speeds float acceleration, // (mm/s^2) M204 S - Normal acceleration. DEFAULT ACCELERATION for all printing moves. retract_acceleration, // (mm/s^2) M204 R - Retract acceleration. Filament pull-back and push-forward while standing still in the other axes travel_acceleration; // (mm/s^2) M204 T - Travel acceleration. DEFAULT ACCELERATION for all NON printing moves. feedRate_t min_feedrate_mm_s, // (mm/s) M205 S - Minimum linear feedrate min_travel_feedrate_mm_s; // (mm/s) M205 T - Minimum travel feedrate } planner_settings_t; #if ENABLED(IMPROVE_HOMING_RELIABILITY) struct motion_state_t { TERN(DELTA, xyz_ulong_t, xy_ulong_t) acceleration; #if ENABLED(CLASSIC_JERK) TERN(DELTA, xyz_float_t, xy_float_t) jerk_state; #endif }; #endif #if ENABLED(SKEW_CORRECTION) typedef struct { #if ENABLED(SKEW_CORRECTION_GCODE) float xy; #if ENABLED(SKEW_CORRECTION_FOR_Z) float xz, yz; #else const float xz = XZ_SKEW_FACTOR, yz = YZ_SKEW_FACTOR; #endif #else const float xy = XY_SKEW_FACTOR, xz = XZ_SKEW_FACTOR, yz = YZ_SKEW_FACTOR; #endif } skew_factor_t; #endif #if ENABLED(DISABLE_OTHER_EXTRUDERS) typedef uvalue_t((BLOCK_BUFFER_SIZE) * 2) last_move_t; #endif #if ENABLED(ARC_SUPPORT) #define HINTS_CURVE_RADIUS #define HINTS_SAFE_EXIT_SPEED #endif struct PlannerHints { float millimeters = 0.0; // Move Length, if known, else 0. #if ENABLED(FEEDRATE_SCALING) float inv_duration = 0.0; // Reciprocal of the move duration, if known #endif #if ENABLED(HINTS_CURVE_RADIUS) float curve_radius = 0.0; // Radius of curvature of the motion path - to calculate cornering speed #else static constexpr float curve_radius = 0.0; #endif #if ENABLED(HINTS_SAFE_EXIT_SPEED) float safe_exit_speed_sqr = 0.0; // Square of the speed considered "safe" at the end of the segment // i.e., at or below the exit speed of the segment that the planner // would calculate if it knew the as-yet-unbuffered path #endif #if HAS_ROTATIONAL_AXES bool cartesian_move = true; // True if linear motion of the tool centerpoint relative to the workpiece occurs. // False if no movement of the tool center point relative to the work piece occurs // (i.e. the tool rotates around the tool centerpoint) #endif PlannerHints(const_float_t mm=0.0f) : millimeters(mm) {} }; class Planner { public: /** * The move buffer, calculated in stepper steps * * block_buffer is a ring buffer... * * head,tail : indexes for write,read * head==tail : the buffer is empty * head!=tail : blocks are in the buffer * head==(tail-1)%size : the buffer is full * * Writer of head is Planner::buffer_segment(). * Reader of tail is Stepper::isr(). Always consider tail busy / read-only */ static block_t block_buffer[BLOCK_BUFFER_SIZE]; static volatile uint8_t block_buffer_head, // Index of the next block to be pushed block_buffer_nonbusy, // Index of the first non busy block block_buffer_planned, // Index of the optimally planned block block_buffer_tail; // Index of the busy block, if any static uint16_t cleaning_buffer_counter; // A counter to disable queuing of blocks static uint8_t delay_before_delivering; // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks #if ENABLED(DISTINCT_E_FACTORS) static uint8_t last_extruder; // Respond to extruder change #endif #if ENABLED(DIRECT_STEPPING) static uint32_t last_page_step_rate; // Last page step rate given static AxisBits last_page_dir; // Last page direction given, where 1 represents forward or positive motion #endif #if HAS_EXTRUDERS static int16_t flow_percentage[EXTRUDERS]; // Extrusion factor for each extruder static float e_factor[EXTRUDERS]; // The flow percentage and volumetric multiplier combine to scale E movement #endif #if DISABLED(NO_VOLUMETRICS) static float filament_size[EXTRUDERS], // (mm) Diameter of filament, typically around 1.75 or 2.85, 0 disables the volumetric calculations for the extruder volumetric_area_nominal, // (mm^3) Nominal cross-sectional area volumetric_multiplier[EXTRUDERS]; // (1/mm^2) Reciprocal of cross-sectional area of filament. Pre-calculated to reduce computation in the planner // May be auto-adjusted by a filament width sensor #endif #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT) static float volumetric_extruder_limit[EXTRUDERS], // (mm^3/sec) Maximum volume the extruder can handle volumetric_extruder_feedrate_limit[EXTRUDERS]; // (mm/s) Feedrate limit calculated from volume limit #endif static planner_settings_t settings; #if ENABLED(LASER_FEATURE) static laser_state_t laser_inline; #endif static uint32_t max_acceleration_steps_per_s2[DISTINCT_AXES]; // (steps/s^2) Derived from mm_per_s2 #if ENABLED(EDITABLE_STEPS_PER_UNIT) static float mm_per_step[DISTINCT_AXES]; // Millimeters per step #else #define _RSTEP(N) RECIPROCAL(settings.axis_steps_per_mm[N]), static constexpr float mm_per_step[DISTINCT_AXES] = { REPEAT(DISTINCT_AXES, _RSTEP) }; #undef _RSTEP #endif #if HAS_JUNCTION_DEVIATION static float junction_deviation_mm; // (mm) M205 J #if HAS_LINEAR_E_JERK static float max_e_jerk[DISTINCT_E]; // Calculated from junction_deviation_mm #endif #else // CLASSIC_JERK // (mm/s^2) M205 XYZ(E) - The largest speed change requiring no acceleration. static TERN(HAS_LINEAR_E_JERK, xyz_pos_t, xyze_pos_t) max_jerk; #endif #if HAS_LEVELING static bool leveling_active; // Flag that bed leveling is enabled #if ABL_PLANAR static matrix_3x3 bed_level_matrix; // Transform to compensate for bed level #endif #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) static float z_fade_height, inverse_z_fade_height; #endif #else static constexpr bool leveling_active = false; #endif #if ENABLED(LIN_ADVANCE) static float extruder_advance_K[DISTINCT_E]; #endif /** * The current position of the tool in absolute steps * Recalculated if any axis_steps_per_mm are changed by G-code */ static xyze_long_t position; #if HAS_POSITION_FLOAT static xyze_pos_t position_float; #endif #if IS_KINEMATIC static xyze_pos_t position_cart; #endif #if ENABLED(SKEW_CORRECTION) static skew_factor_t skew_factor; #endif #if ENABLED(SD_ABORT_ON_ENDSTOP_HIT) static bool abort_on_endstop_hit; #endif #ifdef XY_FREQUENCY_LIMIT static int8_t xy_freq_limit_hz; // Minimum XY frequency setting static float xy_freq_min_speed_factor; // Minimum speed factor setting static int32_t xy_freq_min_interval_us; // Minimum segment time based on xy_freq_limit_hz static void refresh_frequency_limit() { //xy_freq_min_interval_us = xy_freq_limit_hz ?: LROUND(1000000.0f / xy_freq_limit_hz); if (xy_freq_limit_hz) xy_freq_min_interval_us = LROUND(1000000.0f / xy_freq_limit_hz); } static void set_min_speed_factor_u8(const uint8_t v255) { xy_freq_min_speed_factor = float(ui8_to_percent(v255)) / 100; } static void set_frequency_limit(const uint8_t hz) { xy_freq_limit_hz = constrain(hz, 0, 100); refresh_frequency_limit(); } #endif private: /** * Speed of previous path line segment */ static xyze_float_t previous_speed; /** * Nominal speed of previous path line segment (mm/s)^2 */ static float previous_nominal_speed; /** * Limit where 64bit math is necessary for acceleration calculation */ static uint32_t acceleration_long_cutoff; #ifdef MAX7219_DEBUG_SLOWDOWN friend class Max7219; static uint8_t slowdown_count; #endif #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) static float last_fade_z; #endif #if ENABLED(DISABLE_OTHER_EXTRUDERS) // Counters to manage disabling inactive extruder steppers static last_move_t extruder_last_move[E_STEPPERS]; #endif #if HAS_WIRED_LCD volatile static uint32_t block_buffer_runtime_us; // Theoretical block buffer runtime in µs #endif public: /** * Instance Methods */ Planner(); void init(); /** * Static (class) Methods */ // Recalculate steps/s^2 accelerations based on mm/s^2 settings static void refresh_acceleration_rates(); /** * Recalculate 'position' and 'mm_per_step'. * Must be called whenever settings.axis_steps_per_mm changes! */ static void refresh_positioning(); // For an axis set the Maximum Acceleration in mm/s^2 static void set_max_acceleration(const AxisEnum axis, float inMaxAccelMMS2); // For an axis set the Maximum Feedrate in mm/s static void set_max_feedrate(const AxisEnum axis, float inMaxFeedrateMMS); // For an axis set the Maximum Jerk (instant change) in mm/s #if ENABLED(CLASSIC_JERK) static void set_max_jerk(const AxisEnum axis, float inMaxJerkMMS); #else static void set_max_jerk(const AxisEnum, const_float_t) {} #endif #if HAS_EXTRUDERS FORCE_INLINE static void refresh_e_factor(const uint8_t e) { e_factor[e] = flow_percentage[e] * 0.01f * TERN(NO_VOLUMETRICS, 1.0f, volumetric_multiplier[e]); } static void set_flow(const uint8_t e, const int16_t flow) { flow_percentage[e] = flow; refresh_e_factor(e); } #endif // Manage fans, paste pressure, etc. static void check_axes_activity(); // Apply fan speeds #if HAS_FAN static void sync_fan_speeds(uint8_t (&fan_speed)[FAN_COUNT]); #if FAN_KICKSTART_TIME static void kickstart_fan(uint8_t (&fan_speed)[FAN_COUNT], const millis_t &ms, const uint8_t f); #else FORCE_INLINE static void kickstart_fan(uint8_t (&)[FAN_COUNT], const millis_t &, const uint8_t) {} #endif #endif #if ENABLED(FILAMENT_WIDTH_SENSOR) void apply_filament_width_sensor(const int8_t encoded_ratio); static float volumetric_percent(const bool vol) { return 100.0f * (vol ? volumetric_area_nominal / volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] : volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] ); } #endif #if ENABLED(IMPROVE_HOMING_RELIABILITY) void enable_stall_prevention(const bool onoff); #endif #if DISABLED(NO_VOLUMETRICS) // Update multipliers based on new diameter measurements static void calculate_volumetric_multipliers(); #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT) // Update pre calculated extruder feedrate limits based on volumetric values static void calculate_volumetric_extruder_limit(const uint8_t e); static void calculate_volumetric_extruder_limits(); #endif FORCE_INLINE static void set_filament_size(const uint8_t e, const_float_t v) { filament_size[e] = v; if (v > 0) volumetric_area_nominal = CIRCLE_AREA(v * 0.5); //TODO: should it be per extruder // make sure all extruders have some sane value for the filament size for (uint8_t i = 0; i < COUNT(filament_size); ++i) if (!filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA; } #endif #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT) FORCE_INLINE static void set_volumetric_extruder_limit(const uint8_t e, const_float_t v) { volumetric_extruder_limit[e] = v; calculate_volumetric_extruder_limit(e); } #endif #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) /** * Get the Z leveling fade factor based on the given Z height, * re-calculating only when needed. * * Returns 1.0 if planner.z_fade_height is 0.0. * Returns 0.0 if Z is past the specified 'Fade Height'. */ static float fade_scaling_factor_for_z(const_float_t rz) { static float z_fade_factor = 1; if (!z_fade_height || rz <= 0) return 1; if (rz >= z_fade_height) return 0; if (last_fade_z != rz) { last_fade_z = rz; z_fade_factor = 1 - rz * inverse_z_fade_height; } return z_fade_factor; } FORCE_INLINE static void force_fade_recalc() { last_fade_z = -999.999f; } FORCE_INLINE static void set_z_fade_height(const_float_t zfh) { z_fade_height = zfh > 0 ? zfh : 0; inverse_z_fade_height = RECIPROCAL(z_fade_height); force_fade_recalc(); } FORCE_INLINE static bool leveling_active_at_z(const_float_t rz) { return !z_fade_height || rz < z_fade_height; } #else FORCE_INLINE static float fade_scaling_factor_for_z(const_float_t) { return 1; } FORCE_INLINE static bool leveling_active_at_z(const_float_t) { return true; } #endif #if ENABLED(SKEW_CORRECTION) FORCE_INLINE static void skew(float &cx, float &cy, const_float_t cz) { if (COORDINATE_OKAY(cx, X_MIN_POS + 1, X_MAX_POS) && COORDINATE_OKAY(cy, Y_MIN_POS + 1, Y_MAX_POS)) { const float sx = cx - cy * skew_factor.xy - cz * (skew_factor.xz - (skew_factor.xy * skew_factor.yz)), sy = cy - cz * skew_factor.yz; if (COORDINATE_OKAY(sx, X_MIN_POS, X_MAX_POS) && COORDINATE_OKAY(sy, Y_MIN_POS, Y_MAX_POS)) { cx = sx; cy = sy; } } } FORCE_INLINE static void skew(xyz_pos_t &raw) { skew(raw.x, raw.y, raw.z); } FORCE_INLINE static void unskew(float &cx, float &cy, const_float_t cz) { if (COORDINATE_OKAY(cx, X_MIN_POS, X_MAX_POS) && COORDINATE_OKAY(cy, Y_MIN_POS, Y_MAX_POS)) { const float sx = cx + cy * skew_factor.xy + cz * skew_factor.xz, sy = cy + cz * skew_factor.yz; if (COORDINATE_OKAY(sx, X_MIN_POS, X_MAX_POS) && COORDINATE_OKAY(sy, Y_MIN_POS, Y_MAX_POS)) { cx = sx; cy = sy; } } } FORCE_INLINE static void unskew(xyz_pos_t &raw) { unskew(raw.x, raw.y, raw.z); } #endif // SKEW_CORRECTION #if HAS_LEVELING /** * Apply leveling to transform a cartesian position * as it will be given to the planner and steppers. */ static void apply_leveling(xyz_pos_t &raw); static void unapply_leveling(xyz_pos_t &raw); FORCE_INLINE static void force_unapply_leveling(xyz_pos_t &raw) { leveling_active = true; unapply_leveling(raw); leveling_active = false; } #else FORCE_INLINE static void apply_leveling(xyz_pos_t&) {} FORCE_INLINE static void unapply_leveling(xyz_pos_t&) {} #endif #if ENABLED(FWRETRACT) static void apply_retract(float &rz, float &e); FORCE_INLINE static void apply_retract(xyze_pos_t &raw) { apply_retract(raw.z, raw.e); } static void unapply_retract(float &rz, float &e); FORCE_INLINE static void unapply_retract(xyze_pos_t &raw) { unapply_retract(raw.z, raw.e); } #endif #if HAS_POSITION_MODIFIERS FORCE_INLINE static void apply_modifiers(xyze_pos_t &pos, bool leveling=ENABLED(PLANNER_LEVELING)) { TERN_(SKEW_CORRECTION, skew(pos)); if (leveling) apply_leveling(pos); TERN_(FWRETRACT, apply_retract(pos)); } FORCE_INLINE static void unapply_modifiers(xyze_pos_t &pos, bool leveling=ENABLED(PLANNER_LEVELING)) { TERN_(FWRETRACT, unapply_retract(pos)); if (leveling) unapply_leveling(pos); TERN_(SKEW_CORRECTION, unskew(pos)); } #endif // HAS_POSITION_MODIFIERS // Number of moves currently in the planner including the busy block, if any FORCE_INLINE static uint8_t movesplanned() { return block_dec_mod(block_buffer_head, block_buffer_tail); } // Number of nonbusy moves currently in the planner FORCE_INLINE static uint8_t nonbusy_movesplanned() { return block_dec_mod(block_buffer_head, block_buffer_nonbusy); } // Remove all blocks from the buffer FORCE_INLINE static void clear_block_buffer() { block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail = 0; } // Check if movement queue is full FORCE_INLINE static bool is_full() { return block_buffer_tail == next_block_index(block_buffer_head); } // Get count of movement slots free FORCE_INLINE static uint8_t moves_free() { return (BLOCK_BUFFER_SIZE) - 1 - movesplanned(); } /** * Planner::get_next_free_block * * - Get the next head indices (passed by reference) * - Wait for the number of spaces to open up in the planner * - Return the first head block */ FORCE_INLINE static block_t* get_next_free_block(uint8_t &next_buffer_head, const uint8_t count=1) { // Wait until there are enough slots free while (moves_free() < count) { idle(); } // Return the first available block next_buffer_head = next_block_index(block_buffer_head); return &block_buffer[block_buffer_head]; } /** * Planner::_buffer_steps * * Add a new linear movement to the buffer (in terms of steps). * * target - target position in steps units * fr_mm_s - (target) speed of the move * extruder - target extruder * hints - parameters to aid planner calculations * * Returns true if movement was buffered, false otherwise */ static bool _buffer_steps(const xyze_long_t &target OPTARG(HAS_POSITION_FLOAT, const xyze_pos_t &target_float) OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm) , feedRate_t fr_mm_s, const uint8_t extruder, const PlannerHints &hints ); /** * @brief Populate a block in preparation for insertion * @details Populate the fields of a new linear movement block * that will be added to the queue and processed soon * by the Stepper ISR. * * @param block A block to populate * @param target Target position in steps units * @param target_float Target position in native mm * @param cart_dist_mm The pre-calculated move lengths for all axes, in mm * @param fr_mm_s (target) speed of the move * @param extruder target extruder * @param hints parameters to aid planner calculations * * @return true if movement is acceptable, false otherwise */ static bool _populate_block(block_t * const block, const xyze_long_t &target OPTARG(HAS_POSITION_FLOAT, const xyze_pos_t &target_float) OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm) , feedRate_t fr_mm_s, const uint8_t extruder, const PlannerHints &hints , float &minimum_planner_speed_sqr ); /** * Planner::buffer_sync_block * Add a block to the buffer that just updates the position * @param sync_flag sets a condition bit to process additional items * such as sync fan pwm or sync M3/M4 laser power into a queued block */ static void buffer_sync_block(const BlockFlagBit flag=BLOCK_BIT_SYNC_POSITION); #if IS_KINEMATIC private: // Allow do_homing_move to access internal functions, such as buffer_segment. friend void do_homing_move(const AxisEnum, const float, const feedRate_t, const bool); #endif /** * Planner::buffer_segment * * Add a new linear movement to the buffer in axis units. * * Leveling and kinematics should be applied ahead of calling this. * * a,b,c,e - target positions in mm and/or degrees * fr_mm_s - (target) speed of the move * extruder - optional target extruder (otherwise active_extruder) * hints - optional parameters to aid planner calculations */ static bool buffer_segment(const abce_pos_t &abce OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm) , const_feedRate_t fr_mm_s , const uint8_t extruder=active_extruder , const PlannerHints &hints=PlannerHints() ); public: /** * Add a new linear movement to the buffer. * The target is cartesian. It's translated to * delta/scara if needed. * * cart - target position in mm or degrees * fr_mm_s - (target) speed of the move (mm/s) * extruder - optional target extruder (otherwise active_extruder) * hints - optional parameters to aid planner calculations */ static bool buffer_line(const xyze_pos_t &cart, const_feedRate_t fr_mm_s , const uint8_t extruder=active_extruder , const PlannerHints &hints=PlannerHints() ); #if ENABLED(DIRECT_STEPPING) static void buffer_page(const page_idx_t page_idx, const uint8_t extruder, const uint16_t num_steps); #endif /** * Set the planner.position and individual stepper positions. * Used by G92, G28, G29, and other procedures. * * The supplied position is in the cartesian coordinate space and is * translated in to machine space as needed. Modifiers such as leveling * and skew are also applied. * * Multiplies by axis_steps_per_mm[] and does necessary conversion * for COREXY / COREXZ / COREYZ to set the corresponding stepper positions. * * Clears previous speed values. */ static void set_position_mm(const xyze_pos_t &xyze); #if HAS_EXTRUDERS static void set_e_position_mm(const_float_t e); #endif /** * Set the planner.position and individual stepper positions. * * The supplied position is in machine space, and no additional * conversions are applied. */ static void set_machine_position_mm(const abce_pos_t &abce); /** * Get an axis position according to stepper position(s) * For CORE machines apply translation from ABC to XYZ. */ static float get_axis_position_mm(const AxisEnum axis); static abce_pos_t get_axis_positions_mm() { const abce_pos_t out = LOGICAL_AXIS_ARRAY( get_axis_position_mm(E_AXIS), get_axis_position_mm(A_AXIS), get_axis_position_mm(B_AXIS), get_axis_position_mm(C_AXIS), get_axis_position_mm(I_AXIS), get_axis_position_mm(J_AXIS), get_axis_position_mm(K_AXIS), get_axis_position_mm(U_AXIS), get_axis_position_mm(V_AXIS), get_axis_position_mm(W_AXIS) ); return out; } // SCARA AB and Polar YB axes are in degrees, not mm #if ANY(IS_SCARA, POLAR) FORCE_INLINE static float get_axis_position_degrees(const AxisEnum axis) { return get_axis_position_mm(axis); } #endif // Called to force a quick stop of the machine (for example, when // a Full Shutdown is required, or when endstops are hit) static void quick_stop(); #if ENABLED(REALTIME_REPORTING_COMMANDS) // Force a quick pause of the machine (e.g., when a pause is required in the middle of move). // NOTE: Hard-stops will lose steps so encoders are highly recommended if using these! static void quick_pause(); static void quick_resume(); #endif // Called when an endstop is triggered. Causes the machine to stop immediately static void endstop_triggered(const AxisEnum axis); // Triggered position of an axis in mm (not core-savvy) static float triggered_position_mm(const AxisEnum axis); // Blocks are queued, or we're running out moves, or the closed loop controller is waiting static bool busy(); // Block until all buffered steps are executed / cleaned static void synchronize(); // Wait for moves to finish and disable all steppers static void finish_and_disable(); // Periodic handler to manage the cleaning buffer counter // Called from the Temperature ISR at ~1kHz static void isr() { if (cleaning_buffer_counter) --cleaning_buffer_counter; } /** * Does the buffer have any blocks queued? */ FORCE_INLINE static bool has_blocks_queued() { return (block_buffer_head != block_buffer_tail); } /** * Get the current block for processing * and mark the block as busy. * Return nullptr if the buffer is empty * or if there is a first-block delay. * * WARNING: Called from Stepper ISR context! */ static block_t* get_current_block(); /** * "Release" the current block so its slot can be reused. * Called when the current block is no longer needed. */ FORCE_INLINE static void release_current_block() { if (has_blocks_queued()) block_buffer_tail = next_block_index(block_buffer_tail); } #if HAS_WIRED_LCD static uint16_t block_buffer_runtime(); static void clear_block_buffer_runtime(); #endif #if ENABLED(AUTOTEMP) static autotemp_t autotemp; static void autotemp_update(); static void autotemp_M104_M109(); static void autotemp_task(); #endif #if HAS_LINEAR_E_JERK FORCE_INLINE static void recalculate_max_e_jerk() { const float prop = junction_deviation_mm * SQRT(0.5) / (1.0f - SQRT(0.5)); EXTRUDER_LOOP() max_e_jerk[E_INDEX_N(e)] = SQRT(prop * settings.max_acceleration_mm_per_s2[E_AXIS_N(e)]); } #endif private: #if ENABLED(AUTOTEMP) #if ENABLED(AUTOTEMP_PROPORTIONAL) static void _autotemp_update_from_hotend(); #else static void _autotemp_update_from_hotend() {} #endif #endif /** * Get the index of the next / previous block in the ring buffer */ static constexpr uint8_t next_block_index(const uint8_t block_index) { return block_inc_mod(block_index, 1); } static constexpr uint8_t prev_block_index(const uint8_t block_index) { return block_dec_mod(block_index, 1); } /** * Calculate the maximum allowable speed squared at this point, in order * to reach 'target_velocity_sqr' using 'acceleration' within a given * 'distance'. */ static float max_allowable_speed_sqr(const_float_t accel, const_float_t target_velocity_sqr, const_float_t distance) { return target_velocity_sqr - 2 * accel * distance; } #if ANY(S_CURVE_ACCELERATION, LIN_ADVANCE) /** * Calculate the speed reached given initial speed, acceleration and distance */ static float final_speed(const_float_t initial_velocity, const_float_t accel, const_float_t distance) { return SQRT(sq(initial_velocity) + 2 * accel * distance); } #endif static void calculate_trapezoid_for_block(block_t * const block, const_float_t entry_factor, const_float_t exit_factor); static void reverse_pass_kernel(block_t * const current, const block_t * const next, const_float_t safe_exit_speed_sqr); static void forward_pass_kernel(const block_t * const previous, block_t * const current, uint8_t block_index); static void reverse_pass(const_float_t safe_exit_speed_sqr); static void forward_pass(); static void recalculate_trapezoids(const_float_t safe_exit_speed_sqr); static void recalculate(const_float_t safe_exit_speed_sqr); #if HAS_JUNCTION_DEVIATION FORCE_INLINE static void normalize_junction_vector(xyze_float_t &vector) { float magnitude_sq = 0; LOOP_LOGICAL_AXES(idx) if (vector[idx]) magnitude_sq += sq(vector[idx]); vector *= RSQRT(magnitude_sq); } FORCE_INLINE static float limit_value_by_axis_maximum(const_float_t max_value, xyze_float_t &unit_vec) { float limit_value = max_value; LOOP_LOGICAL_AXES(idx) { if (unit_vec[idx]) { if (limit_value * ABS(unit_vec[idx]) > settings.max_acceleration_mm_per_s2[idx]) limit_value = ABS(settings.max_acceleration_mm_per_s2[idx] / unit_vec[idx]); } } return limit_value; } #endif // HAS_JUNCTION_DEVIATION }; #define PLANNER_XY_FEEDRATE() _MIN(planner.settings.max_feedrate_mm_s[X_AXIS], planner.settings.max_feedrate_mm_s[Y_AXIS]) #define ANY_AXIS_MOVES(BLOCK) \ (false NUM_AXIS_GANG( \ || BLOCK->steps.a, || BLOCK->steps.b, || BLOCK->steps.c, \ || BLOCK->steps.i, || BLOCK->steps.j, || BLOCK->steps.k, \ || BLOCK->steps.u, || BLOCK->steps.v, || BLOCK->steps.w)) extern Planner planner;
2301_81045437/Marlin
Marlin/src/module/planner.h
C++
agpl-3.0
41,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/>. * */ /** * planner_bezier.cpp * * Compute and buffer movement commands for bezier curves */ #include "../inc/MarlinConfig.h" #if ENABLED(BEZIER_CURVE_SUPPORT) #include "planner.h" #include "motion.h" #include "temperature.h" #include "../MarlinCore.h" #include "../gcode/queue.h" // See the meaning in the documentation of cubic_b_spline(). #define MIN_STEP 0.002f #define MAX_STEP 0.1f #define SIGMA 0.1f // Compute the linear interpolation between two real numbers. static inline float interp(const_float_t a, const_float_t b, const_float_t t) { return (1 - t) * a + t * b; } /** * Compute a Bézier curve using the De Casteljau's algorithm (see * https://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm), which is * easy to code and has good numerical stability (very important, * since Arudino works with limited precision real numbers). */ static inline float eval_bezier(const_float_t a, const_float_t b, const_float_t c, const_float_t d, const_float_t t) { const float iab = interp(a, b, t), ibc = interp(b, c, t), icd = interp(c, d, t), iabc = interp(iab, ibc, t), ibcd = interp(ibc, icd, t); return interp(iabc, ibcd, t); } /** * We approximate Euclidean distance with the sum of the coordinates * offset (so-called "norm 1"), which is quicker to compute. */ static inline float dist1(const_float_t x1, const_float_t y1, const_float_t x2, const_float_t y2) { return ABS(x1 - x2) + ABS(y1 - y2); } /** * The algorithm for computing the step is loosely based on the one in Kig * (See https://sources.debian.net/src/kig/4:15.08.3-1/misc/kigpainter.cpp/#L759) * However, we do not use the stack. * * The algorithm goes as it follows: the parameters t runs from 0.0 to * 1.0 describing the curve, which is evaluated by eval_bezier(). At * each iteration we have to choose a step, i.e., the increment of the * t variable. By default the step of the previous iteration is taken, * and then it is enlarged or reduced depending on how straight the * curve locally is. The step is always clamped between MIN_STEP/2 and * 2*MAX_STEP. MAX_STEP is taken at the first iteration. * * For some t, the step value is considered acceptable if the curve in * the interval [t, t+step] is sufficiently straight, i.e., * sufficiently close to linear interpolation. In practice the * following test is performed: the distance between eval_bezier(..., * t+step/2) is evaluated and compared with 0.5*(eval_bezier(..., * t)+eval_bezier(..., t+step)). If it is smaller than SIGMA, then the * step value is considered acceptable, otherwise it is not. The code * seeks to find the larger step value which is considered acceptable. * * At every iteration the recorded step value is considered and then * iteratively halved until it becomes acceptable. If it was already * acceptable in the beginning (i.e., no halving were done), then * maybe it was necessary to enlarge it; then it is iteratively * doubled while it remains acceptable. The last acceptable value * found is taken, provided that it is between MIN_STEP and MAX_STEP * and does not bring t over 1.0. * * Caveat: this algorithm is not perfect, since it can happen that a * step is considered acceptable even when the curve is not linear at * all in the interval [t, t+step] (but its mid point coincides "by * chance" with the midpoint according to the parametrization). This * kind of glitches can be eliminated with proper first derivative * estimates; however, given the improbability of such configurations, * the mitigation offered by MIN_STEP and the small computational * power available on Arduino, I think it is not wise to implement it. */ void cubic_b_spline( const xyze_pos_t &position, // current position const xyze_pos_t &target, // target position const xy_pos_t (&offsets)[2], // a pair of offsets const_feedRate_t scaled_fr_mm_s, // mm/s scaled by feedrate % const uint8_t extruder ) { // Absolute first and second control points are recovered. const xy_pos_t first = position + offsets[0], second = target + offsets[1]; xyze_pos_t bez_target; bez_target.set(position.x, position.y); float step = MAX_STEP; millis_t next_idle_ms = millis() + 200UL; // Hints to help optimize the move PlannerHints hints; for (float t = 0; t < 1;) { thermalManager.task(); millis_t now = millis(); if (ELAPSED(now, next_idle_ms)) { next_idle_ms = now + 200UL; idle(); } // First try to reduce the step in order to make it sufficiently // close to a linear interpolation. bool did_reduce = false; float new_t = t + step; NOMORE(new_t, 1); float new_pos0 = eval_bezier(position.x, first.x, second.x, target.x, new_t), new_pos1 = eval_bezier(position.y, first.y, second.y, target.y, new_t); for (;;) { if (new_t - t < (MIN_STEP)) break; const float candidate_t = 0.5f * (t + new_t), candidate_pos0 = eval_bezier(position.x, first.x, second.x, target.x, candidate_t), candidate_pos1 = eval_bezier(position.y, first.y, second.y, target.y, candidate_t), interp_pos0 = 0.5f * (bez_target.x + new_pos0), interp_pos1 = 0.5f * (bez_target.y + new_pos1); if (dist1(candidate_pos0, candidate_pos1, interp_pos0, interp_pos1) <= (SIGMA)) break; new_t = candidate_t; new_pos0 = candidate_pos0; new_pos1 = candidate_pos1; did_reduce = true; } // If we did not reduce the step, maybe we should enlarge it. if (!did_reduce) for (;;) { if (new_t - t > MAX_STEP) break; const float candidate_t = t + 2 * (new_t - t); if (candidate_t >= 1) break; const float candidate_pos0 = eval_bezier(position.x, first.x, second.x, target.x, candidate_t), candidate_pos1 = eval_bezier(position.y, first.y, second.y, target.y, candidate_t), interp_pos0 = 0.5f * (bez_target.x + candidate_pos0), interp_pos1 = 0.5f * (bez_target.y + candidate_pos1); if (dist1(new_pos0, new_pos1, interp_pos0, interp_pos1) > (SIGMA)) break; new_t = candidate_t; new_pos0 = candidate_pos0; new_pos1 = candidate_pos1; } // Check some postcondition; they are disabled in the actual // Marlin build, but if you test the same code on a computer you // may want to check they are respect. /* assert(new_t <= 1.0); if (new_t < 1.0) { assert(new_t - t >= (MIN_STEP) / 2.0); assert(new_t - t <= (MAX_STEP) * 2.0); } */ hints.millimeters = new_t - t; t = new_t; // Compute and send new position xyze_pos_t new_bez = LOGICAL_AXIS_ARRAY( interp(position.e, target.e, t), // FIXME. Wrong, since t is not linear in the distance. new_pos0, new_pos1, interp(position.z, target.z, t), // FIXME. Wrong, since t is not linear in the distance. interp(position.i, target.i, t), // FIXME. Wrong, since t is not linear in the distance. interp(position.j, target.j, t), // FIXME. Wrong, since t is not linear in the distance. interp(position.k, target.k, t), // FIXME. Wrong, since t is not linear in the distance. interp(position.u, target.u, t), // FIXME. Wrong, since t is not linear in the distance. interp(position.v, target.v, t), // FIXME. Wrong, since t is not linear in the distance. interp(position.w, target.w, t) // FIXME. Wrong, since t is not linear in the distance. ); apply_motion_limits(new_bez); bez_target = new_bez; #if HAS_LEVELING && !PLANNER_LEVELING xyze_pos_t pos = bez_target; planner.apply_leveling(pos); #else const xyze_pos_t &pos = bez_target; #endif if (!planner.buffer_line(pos, scaled_fr_mm_s, active_extruder, hints)) break; } } #endif // BEZIER_CURVE_SUPPORT
2301_81045437/Marlin
Marlin/src/module/planner_bezier.cpp
C++
agpl-3.0
8,786
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 /** * planner_bezier.h * * Compute and buffer movement commands for Bézier curves */ #include "../core/types.h" void cubic_b_spline( const xyze_pos_t &position, // current position const xyze_pos_t &target, // target position const xy_pos_t (&offsets)[2], // a pair of offsets const_feedRate_t scaled_fr_mm_s, // mm/s scaled by feedrate % const uint8_t extruder );
2301_81045437/Marlin
Marlin/src/module/planner_bezier.h
C
agpl-3.0
1,277
/** * Marlin 3D Printer Firmware * Copyright (c) 2023 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * POLAR Kinematics * developed by Kadir ilkimen for PolarBear CNC and babyBear * https://github.com/kadirilkimen/Polar-Bear-Cnc-Machine * https://github.com/kadirilkimen/babyBear-3D-printer * * A polar machine can have different configurations. * This kinematics is only compatible with the following configuration: * X : Independent linear * Y or B : Polar * Z : Independent linear * * For example, PolarBear has CoreXZ plus Polar Y or B. */ #include "../inc/MarlinConfigPre.h" #if ENABLED(POLAR) #include "polar.h" #include "motion.h" #include "planner.h" #include "../inc/MarlinConfig.h" float segments_per_second = DEFAULT_SEGMENTS_PER_SECOND, polar_center_offset = POLAR_CENTER_OFFSET; float absoluteAngle(float a) { if (a < 0.0) while (a < 0.0) a += 360.0; else if (a > 360.0) while (a > 360.0) a -= 360.0; return a; } void forward_kinematics(const_float_t r, const_float_t theta) { const float absTheta = absoluteAngle(theta); float radius = r; if (polar_center_offset > 0.0) radius = SQRT( ABS( sq(r) - sq(-polar_center_offset) ) ); cartes.x = cos(RADIANS(absTheta))*radius; cartes.y = sin(RADIANS(absTheta))*radius; } void inverse_kinematics(const xyz_pos_t &raw) { const float x = raw.x, y = raw.y, rawRadius = HYPOT(x,y), posTheta = DEGREES(ATAN2(y, x)); static float current_polar_theta = 0; float r = rawRadius, theta = absoluteAngle(posTheta), currentAbsTheta = absoluteAngle(current_polar_theta); if (polar_center_offset > 0.0) { const float offsetRadius = SQRT(ABS(sq(r) - sq(polar_center_offset))); float offsetTheta = absoluteAngle(DEGREES(ATAN2(polar_center_offset, offsetRadius))); theta = absoluteAngle(offsetTheta + theta); } const float deltaTheta = theta - currentAbsTheta; if (ABS(deltaTheta) <= 180) theta = current_polar_theta + deltaTheta; else { if (currentAbsTheta > 180) theta = current_polar_theta + 360 + deltaTheta; else theta = current_polar_theta - (360 - deltaTheta); } current_polar_theta = theta; delta.set(r, theta, raw.z); } void polar_report_positions() { SERIAL_ECHOLNPGM("X: ", planner.get_axis_position_mm(X_AXIS), " POLAR Theta:", planner.get_axis_position_degrees(B_AXIS), " Z: ", planner.get_axis_position_mm(Z_AXIS) ); } #endif
2301_81045437/Marlin
Marlin/src/module/polar.cpp
C++
agpl-3.0
3,277
/** * Marlin 3D Printer Firmware * Copyright (c) 2023 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * polar.h - POLAR-specific functions */ #include "../core/types.h" extern float segments_per_second; float absoluteAngle(float a); void forward_kinematics(const_float_t r, const_float_t theta); void inverse_kinematics(const xyz_pos_t &raw); void polar_report_positions();
2301_81045437/Marlin
Marlin/src/module/polar.h
C
agpl-3.0
1,158
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * polargraph.cpp */ #include "../inc/MarlinConfig.h" #if ENABLED(POLARGRAPH) #include "polargraph.h" #include "motion.h" // For homing: #include "planner.h" #include "endstops.h" #include "../lcd/marlinui.h" #include "../MarlinCore.h" // Initialized by settings.load() float segments_per_second, polargraph_max_belt_len; xy_pos_t draw_area_min, draw_area_max; void inverse_kinematics(const xyz_pos_t &raw) { const float x1 = raw.x - draw_area_min.x, x2 = draw_area_max.x - raw.x, y = raw.y - draw_area_max.y; delta.set(HYPOT(x1, y), HYPOT(x2, y) OPTARG(HAS_Z_AXIS, raw.z)); } #endif // POLARGRAPH
2301_81045437/Marlin
Marlin/src/module/polargraph.cpp
C++
agpl-3.0
1,477
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 /** * polargraph.h - Polargraph-specific functions */ #include "../core/types.h" #include "../core/macros.h" extern float segments_per_second; extern xy_pos_t draw_area_min, draw_area_max; extern float polargraph_max_belt_len; void inverse_kinematics(const xyz_pos_t &raw);
2301_81045437/Marlin
Marlin/src/module/polargraph.h
C
agpl-3.0
1,155
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 DISABLED(PRINTCOUNTER) #include "../libs/stopwatch.h" Stopwatch print_job_timer; // Global Print Job Timer instance #else // PRINTCOUNTER #if ENABLED(EXTENSIBLE_UI) #include "../lcd/extui/ui_api.h" #endif #include "printcounter.h" #include "../MarlinCore.h" #include "../HAL/shared/eeprom_api.h" #if HAS_SOUND && SERVICE_WARNING_BUZZES > 0 #include "../libs/buzzer.h" #endif #if ENABLED(PRINTCOUNTER_SYNC) #include "../module/planner.h" #endif // Service intervals #if HAS_SERVICE_INTERVALS #if SERVICE_INTERVAL_1 > 0 #define SERVICE_INTERVAL_SEC_1 (3600UL * SERVICE_INTERVAL_1) #else #define SERVICE_INTERVAL_SEC_1 (3600UL * 100) #endif #if SERVICE_INTERVAL_2 > 0 #define SERVICE_INTERVAL_SEC_2 (3600UL * SERVICE_INTERVAL_2) #else #define SERVICE_INTERVAL_SEC_2 (3600UL * 100) #endif #if SERVICE_INTERVAL_3 > 0 #define SERVICE_INTERVAL_SEC_3 (3600UL * SERVICE_INTERVAL_3) #else #define SERVICE_INTERVAL_SEC_3 (3600UL * 100) #endif #endif PrintCounter print_job_timer; // Global Print Job Timer instance printStatistics PrintCounter::data; const PrintCounter::eeprom_address_t PrintCounter::address = STATS_EEPROM_ADDRESS; millis_t PrintCounter::lastDuration; bool PrintCounter::loaded = false; millis_t PrintCounter::deltaDuration() { TERN_(DEBUG_PRINTCOUNTER, debug(PSTR("deltaDuration"))); millis_t tmp = lastDuration; lastDuration = duration(); return lastDuration - tmp; } #if HAS_EXTRUDERS void PrintCounter::incFilamentUsed(float const &amount) { TERN_(DEBUG_PRINTCOUNTER, debug(PSTR("incFilamentUsed"))); // Refuses to update data if object is not loaded if (!isLoaded()) return; data.filamentUsed += amount; // mm } #endif void PrintCounter::initStats() { TERN_(DEBUG_PRINTCOUNTER, debug(PSTR("initStats"))); loaded = true; data = { .totalPrints = 0 , .finishedPrints = 0 , .printTime = 0 , .longestPrint = 0 OPTARG(HAS_EXTRUDERS, .filamentUsed = 0.0) #if SERVICE_INTERVAL_1 > 0 , .nextService1 = SERVICE_INTERVAL_SEC_1 #endif #if SERVICE_INTERVAL_2 > 0 , .nextService2 = SERVICE_INTERVAL_SEC_2 #endif #if SERVICE_INTERVAL_3 > 0 , .nextService3 = SERVICE_INTERVAL_SEC_3 #endif }; saveStats(); persistentStore.access_start(); persistentStore.write_data(address, (uint8_t)0x16); persistentStore.access_finish(); } #if HAS_SERVICE_INTERVALS inline void _print_divider() { SERIAL_ECHO_MSG("============================================="); } inline bool _service_warn(const char * const msg) { _print_divider(); SERIAL_ECHO_START(); SERIAL_ECHOPGM_P(msg); SERIAL_ECHOLNPGM("!"); _print_divider(); return true; } #endif void PrintCounter::loadStats() { TERN_(DEBUG_PRINTCOUNTER, debug(PSTR("loadStats"))); // Check if the EEPROM block is initialized uint8_t value = 0; persistentStore.access_start(); persistentStore.read_data(address, &value, sizeof(uint8_t)); if (value != 0x16) initStats(); else persistentStore.read_data(address + sizeof(uint8_t), (uint8_t*)&data, sizeof(printStatistics)); persistentStore.access_finish(); loaded = true; #if HAS_SERVICE_INTERVALS bool doBuzz = false; #if SERVICE_INTERVAL_1 > 0 if (data.nextService1 == 0) doBuzz = _service_warn(PSTR(" " SERVICE_NAME_1)); #endif #if SERVICE_INTERVAL_2 > 0 if (data.nextService2 == 0) doBuzz = _service_warn(PSTR(" " SERVICE_NAME_2)); #endif #if SERVICE_INTERVAL_3 > 0 if (data.nextService3 == 0) doBuzz = _service_warn(PSTR(" " SERVICE_NAME_3)); #endif #if HAS_SOUND && SERVICE_WARNING_BUZZES > 0 if (doBuzz) for (int i = 0; i < SERVICE_WARNING_BUZZES; i++) { BUZZ(200, 404); BUZZ(10, 0); } #else UNUSED(doBuzz); #endif #endif // HAS_SERVICE_INTERVALS } void PrintCounter::saveStats() { TERN_(DEBUG_PRINTCOUNTER, debug(PSTR("saveStats"))); // Refuses to save data if object is not loaded if (!isLoaded()) return; TERN_(PRINTCOUNTER_SYNC, planner.synchronize()); // Saves the struct to EEPROM persistentStore.access_start(); persistentStore.write_data(address + sizeof(uint8_t), (uint8_t*)&data, sizeof(printStatistics)); persistentStore.access_finish(); TERN_(EXTENSIBLE_UI, ExtUI::onSettingsStored(true)); } #if HAS_SERVICE_INTERVALS inline void _service_when(char buffer[], const char * const msg, const uint32_t when) { SERIAL_ECHOPGM(STR_STATS); SERIAL_ECHOPGM_P(msg); SERIAL_ECHOLNPGM(" in ", duration_t(when).toString(buffer)); } #endif void PrintCounter::showStats() { char buffer[22]; SERIAL_ECHOPGM(STR_STATS); SERIAL_ECHOLNPGM( "Prints: ", data.totalPrints, ", Finished: ", data.finishedPrints, ", Failed: ", data.totalPrints - data.finishedPrints - ((isRunning() || isPaused()) ? 1 : 0) // Remove 1 from failures with an active counter ); SERIAL_ECHOPGM(STR_STATS); duration_t elapsed = data.printTime; elapsed.toString(buffer); SERIAL_ECHOPGM("Total time: ", buffer); #if ENABLED(DEBUG_PRINTCOUNTER) SERIAL_ECHOPGM(" (", data.printTime); SERIAL_CHAR(')'); #endif elapsed = data.longestPrint; elapsed.toString(buffer); SERIAL_ECHOPGM(", Longest job: ", buffer); #if ENABLED(DEBUG_PRINTCOUNTER) SERIAL_ECHOPGM(" (", data.longestPrint); SERIAL_CHAR(')'); #endif #if HAS_EXTRUDERS SERIAL_ECHOPGM("\n" STR_STATS "Filament used: ", data.filamentUsed / 1000); SERIAL_CHAR('m'); #endif SERIAL_EOL(); #if SERVICE_INTERVAL_1 > 0 _service_when(buffer, PSTR(SERVICE_NAME_1), data.nextService1); #endif #if SERVICE_INTERVAL_2 > 0 _service_when(buffer, PSTR(SERVICE_NAME_2), data.nextService2); #endif #if SERVICE_INTERVAL_3 > 0 _service_when(buffer, PSTR(SERVICE_NAME_3), data.nextService3); #endif } void PrintCounter::tick() { if (!isRunning()) return; millis_t now = millis(); static millis_t update_next; // = 0 if (ELAPSED(now, update_next)) { update_next = now + updateInterval; TERN_(DEBUG_PRINTCOUNTER, debug(PSTR("tick"))); millis_t delta = deltaDuration(); data.printTime += delta; #if SERVICE_INTERVAL_1 > 0 data.nextService1 -= _MIN(delta, data.nextService1); #endif #if SERVICE_INTERVAL_2 > 0 data.nextService2 -= _MIN(delta, data.nextService2); #endif #if SERVICE_INTERVAL_3 > 0 data.nextService3 -= _MIN(delta, data.nextService3); #endif } #if PRINTCOUNTER_SAVE_INTERVAL > 0 static millis_t eeprom_next; // = 0 if (ELAPSED(now, eeprom_next)) { eeprom_next = now + saveInterval; saveStats(); } #endif } // @Override bool PrintCounter::start() { TERN_(DEBUG_PRINTCOUNTER, debug(PSTR("start"))); bool paused = isPaused(); if (super::start()) { if (!paused) { data.totalPrints++; lastDuration = 0; } return true; } return false; } bool PrintCounter::_stop(const bool completed) { TERN_(DEBUG_PRINTCOUNTER, debug(PSTR("stop"))); const bool did_stop = super::stop(); if (did_stop) { data.printTime += deltaDuration(); if (completed) { data.finishedPrints++; if (duration() > data.longestPrint) data.longestPrint = duration(); } } saveStats(); return did_stop; } // @Override void PrintCounter::reset() { TERN_(DEBUG_PRINTCOUNTER, debug(PSTR("stop"))); super::reset(); lastDuration = 0; } #if HAS_SERVICE_INTERVALS void PrintCounter::resetServiceInterval(const int index) { switch (index) { #if SERVICE_INTERVAL_1 > 0 case 1: data.nextService1 = SERVICE_INTERVAL_SEC_1; break; #endif #if SERVICE_INTERVAL_2 > 0 case 2: data.nextService2 = SERVICE_INTERVAL_SEC_2; break; #endif #if SERVICE_INTERVAL_3 > 0 case 3: data.nextService3 = SERVICE_INTERVAL_SEC_3; break; #endif } saveStats(); } bool PrintCounter::needsService(const int index) { if (!loaded) loadStats(); switch (index) { #if SERVICE_INTERVAL_1 > 0 case 1: return data.nextService1 == 0; #endif #if SERVICE_INTERVAL_2 > 0 case 2: return data.nextService2 == 0; #endif #if SERVICE_INTERVAL_3 > 0 case 3: return data.nextService3 == 0; #endif default: return false; } } #endif // HAS_SERVICE_INTERVALS #if ENABLED(DEBUG_PRINTCOUNTER) void PrintCounter::debug(const char func[]) { if (DEBUGGING(INFO)) { SERIAL_ECHOPGM("PrintCounter::"); SERIAL_ECHOPGM_P(func); SERIAL_ECHOLNPGM("()"); } } #endif #endif // PRINTCOUNTER
2301_81045437/Marlin
Marlin/src/module/printcounter.cpp
C++
agpl-3.0
9,542
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 "../libs/stopwatch.h" #include "../libs/duration_t.h" #include "../inc/MarlinConfig.h" // Print debug messages with M111 S2 //#define DEBUG_PRINTCOUNTER // Round up I2C / SPI address to next page boundary (assuming 32 byte pages) #define STATS_EEPROM_ADDRESS TERN(USE_WIRED_EEPROM, 0x40, 0x32) struct printStatistics { // 16 bytes //const uint8_t magic; // Magic header, it will always be 0x16 uint16_t totalPrints; // Number of prints uint16_t finishedPrints; // Number of complete prints uint32_t printTime; // Accumulated printing time uint32_t longestPrint; // Longest successful print job #if HAS_EXTRUDERS float filamentUsed; // Accumulated filament consumed in mm #endif #if SERVICE_INTERVAL_1 > 0 uint32_t nextService1; // Service intervals (or placeholders) #endif #if SERVICE_INTERVAL_2 > 0 uint32_t nextService2; #endif #if SERVICE_INTERVAL_3 > 0 uint32_t nextService3; #endif }; class PrintCounter: public Stopwatch { private: typedef Stopwatch super; typedef IF<ANY(USE_WIRED_EEPROM, CPU_32_BIT), uint32_t, uint16_t>::type eeprom_address_t; static printStatistics data; /** * @brief EEPROM address * @details Defines the start offset address where the data is stored. */ static const eeprom_address_t address; /** * @brief Interval in seconds between counter updates * @details This const value defines what will be the time between each * accumulator update. This is different from the EEPROM save interval. */ static constexpr millis_t updateInterval = SEC_TO_MS(10); #if PRINTCOUNTER_SAVE_INTERVAL > 0 /** * @brief Interval in seconds between EEPROM saves * @details This const value defines what will be the time between each * EEPROM save cycle, the development team recommends to set this value * no lower than 3600 secs (1 hour). */ static constexpr millis_t saveInterval = MIN_TO_MS(PRINTCOUNTER_SAVE_INTERVAL); #endif /** * @brief Timestamp of the last call to deltaDuration() * @details Store the timestamp of the last deltaDuration(), this is * required due to the updateInterval cycle. */ static millis_t lastDuration; /** * @brief Stats were loaded from EEPROM * @details If set to true it indicates if the statistical data was already * loaded from the EEPROM. */ static bool loaded; protected: /** * @brief dT since the last call * @details Return the elapsed time in seconds since the last call, this is * used internally for print statistics accounting is not intended to be a * user callable function. */ static millis_t deltaDuration(); public: /** * @brief Initialize the print counter */ static void init() { super::init(); loadStats(); } /** * @brief Check if Print Statistics has been loaded * @details Return true if the statistical data has been loaded. * @return bool */ FORCE_INLINE static bool isLoaded() { return loaded; } #if HAS_EXTRUDERS /** * @brief Increment the total filament used * @details The total filament used counter will be incremented by "amount". * * @param amount The amount of filament used in mm */ static void incFilamentUsed(float const &amount); #endif /** * @brief Reset the Print Statistics * @details Reset the statistics to zero and saves them to EEPROM creating * also the magic header. */ static void initStats(); /** * @brief Load the Print Statistics * @details Load the statistics from EEPROM */ static void loadStats(); /** * @brief Save the Print Statistics * @details Save the statistics to EEPROM */ static void saveStats(); /** * @brief Serial output the Print Statistics * @details This function may change in the future, for now it directly * prints the statistical data to serial. */ static void showStats(); /** * @brief Return the currently loaded statistics * @details Return the raw data, in the same structure used internally */ static printStatistics getStats() { return data; } /** * @brief Loop function * @details This function should be called at loop, it will take care of * periodically save the statistical data to EEPROM and do time keeping. */ static void tick(); /** * The following functions are being overridden */ static bool start(); static bool _stop(const bool completed); static bool stop() { return _stop(true); } static bool abort() { return _stop(false); } static void reset(); #if HAS_SERVICE_INTERVALS static void resetServiceInterval(const int index); static bool needsService(const int index); #endif #if ENABLED(DEBUG_PRINTCOUNTER) /** * @brief Print a debug message * @details Print a simple debug message */ static void debug(const char func[]); #endif }; // Global Print Job Timer instance #if ENABLED(PRINTCOUNTER) extern PrintCounter print_job_timer; #else extern Stopwatch print_job_timer; #endif
2301_81045437/Marlin
Marlin/src/module/printcounter.h
C++
agpl-3.0
6,180
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * module/probe.cpp */ #include "../inc/MarlinConfig.h" #if HAS_BED_PROBE #include "probe.h" #include "../libs/buzzer.h" #include "motion.h" #include "temperature.h" #include "endstops.h" #include "../gcode/gcode.h" #include "../lcd/marlinui.h" #include "../MarlinCore.h" // for stop(), disable_e_steppers(), wait_for_user_response() #if HAS_LEVELING #include "../feature/bedlevel/bedlevel.h" #endif #if ENABLED(BD_SENSOR) #include "../feature/bedlevel/bdl/bdl.h" #endif #if ENABLED(DELTA) #include "delta.h" #endif #if ENABLED(SENSORLESS_PROBING) abc_float_t offset_sensorless_adj{0}; float largest_sensorless_adj = 0; #endif #if ANY(HAS_QUIET_PROBING, USE_SENSORLESS) #include "stepper/indirection.h" #if ALL(HAS_QUIET_PROBING, PROBING_ESTEPPERS_OFF) #include "stepper.h" #endif #if USE_SENSORLESS #include "../feature/tmc_util.h" #if ENABLED(IMPROVE_HOMING_RELIABILITY) #include "planner.h" #endif #endif #endif #if ENABLED(MEASURE_BACKLASH_WHEN_PROBING) #include "../feature/backlash.h" #endif #if ENABLED(BLTOUCH) #include "../feature/bltouch.h" #endif #if ENABLED(HOST_PROMPT_SUPPORT) #include "../feature/host_actions.h" // for PROMPT_USER_CONTINUE #endif #if HAS_Z_SERVO_PROBE #include "servo.h" #endif #if HAS_PTC #include "../feature/probe_temp_comp.h" #endif #if ENABLED(X_AXIS_TWIST_COMPENSATION) #include "../feature/x_twist.h" #endif #if ENABLED(EXTENSIBLE_UI) #include "../lcd/extui/ui_api.h" #endif #define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) #include "../core/debug_out.h" Probe probe; xyz_pos_t Probe::offset; // Initialized by settings.load() #if HAS_PROBE_XY_OFFSET const xy_pos_t &Probe::offset_xy = Probe::offset; #endif #if ENABLED(SENSORLESS_PROBING) Probe::sense_bool_t Probe::test_sensitivity = { true, true, true }; #endif #if ENABLED(Z_PROBE_SLED) #ifndef SLED_DOCKING_OFFSET #define SLED_DOCKING_OFFSET 0 #endif /** * Method to dock/undock a sled designed by Charles Bell. * * stow[in] If false, move to MAX_X and engage the solenoid * If true, move to MAX_X and release the solenoid */ static void dock_sled(const bool stow) { if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("dock_sled(", stow, ")"); // Dock sled a bit closer to ensure proper capturing do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0)); #if HAS_SOLENOID_1 && DISABLED(EXT_SOLENOID) WRITE(SOL1_PIN, !stow); // switch solenoid #endif } #elif ENABLED(MAGLEV4) // Write trigger pin to release the probe inline void maglev_deploy() { WRITE(MAGLEV_TRIGGER_PIN, HIGH); delay(MAGLEV_TRIGGER_DELAY); WRITE(MAGLEV_TRIGGER_PIN, LOW); } inline void maglev_idle() { do_z_clearance(10); } #elif ENABLED(TOUCH_MI_PROBE) // Move to the magnet to unlock the probe inline void run_deploy_moves() { #ifndef TOUCH_MI_DEPLOY_XPOS #define TOUCH_MI_DEPLOY_XPOS X_MIN_POS #elif TOUCH_MI_DEPLOY_XPOS > X_MAX_BED TemporaryGlobalEndstopsState unlock_x(false); #endif #if TOUCH_MI_DEPLOY_YPOS > Y_MAX_BED TemporaryGlobalEndstopsState unlock_y(false); #endif #if ENABLED(TOUCH_MI_MANUAL_DEPLOY) const screenFunc_t prev_screen = ui.currentScreen; LCD_MESSAGE(MSG_MANUAL_DEPLOY_TOUCHMI); ui.return_to_status(); TERN_(HOST_PROMPT_SUPPORT, hostui.continue_prompt(F("Deploy TouchMI"))); TERN_(HAS_RESUME_CONTINUE, wait_for_user_response()); ui.reset_status(); ui.goto_screen(prev_screen); #elif defined(TOUCH_MI_DEPLOY_XPOS) && defined(TOUCH_MI_DEPLOY_YPOS) do_blocking_move_to_xy(TOUCH_MI_DEPLOY_XPOS, TOUCH_MI_DEPLOY_YPOS); #elif defined(TOUCH_MI_DEPLOY_XPOS) do_blocking_move_to_x(TOUCH_MI_DEPLOY_XPOS); #elif defined(TOUCH_MI_DEPLOY_YPOS) do_blocking_move_to_y(TOUCH_MI_DEPLOY_YPOS); #endif } // Move down to the bed to stow the probe // TODO: Handle cases where it would be a bad idea to move down. inline void run_stow_moves() { const float oldz = current_position.z; endstops.enable_z_probe(false); do_blocking_move_to_z(TOUCH_MI_RETRACT_Z, homing_feedrate(Z_AXIS)); do_blocking_move_to_z(oldz, homing_feedrate(Z_AXIS)); } #elif ENABLED(Z_PROBE_ALLEN_KEY) inline void run_deploy_moves() { #ifdef Z_PROBE_ALLEN_KEY_DEPLOY_1 #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0f #endif constexpr xyz_pos_t deploy_1 = Z_PROBE_ALLEN_KEY_DEPLOY_1; do_blocking_move_to(deploy_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE)); #endif #ifdef Z_PROBE_ALLEN_KEY_DEPLOY_2 #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0f #endif constexpr xyz_pos_t deploy_2 = Z_PROBE_ALLEN_KEY_DEPLOY_2; do_blocking_move_to(deploy_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE)); #endif #ifdef Z_PROBE_ALLEN_KEY_DEPLOY_3 #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0f #endif constexpr xyz_pos_t deploy_3 = Z_PROBE_ALLEN_KEY_DEPLOY_3; do_blocking_move_to(deploy_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE)); #endif #ifdef Z_PROBE_ALLEN_KEY_DEPLOY_4 #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0f #endif constexpr xyz_pos_t deploy_4 = Z_PROBE_ALLEN_KEY_DEPLOY_4; do_blocking_move_to(deploy_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE)); #endif #ifdef Z_PROBE_ALLEN_KEY_DEPLOY_5 #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0f #endif constexpr xyz_pos_t deploy_5 = Z_PROBE_ALLEN_KEY_DEPLOY_5; do_blocking_move_to(deploy_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE)); #endif } inline void run_stow_moves() { #ifdef Z_PROBE_ALLEN_KEY_STOW_1 #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0f #endif constexpr xyz_pos_t stow_1 = Z_PROBE_ALLEN_KEY_STOW_1; do_blocking_move_to(stow_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE)); #endif #ifdef Z_PROBE_ALLEN_KEY_STOW_2 #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0f #endif constexpr xyz_pos_t stow_2 = Z_PROBE_ALLEN_KEY_STOW_2; do_blocking_move_to(stow_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE)); #endif #ifdef Z_PROBE_ALLEN_KEY_STOW_3 #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0f #endif constexpr xyz_pos_t stow_3 = Z_PROBE_ALLEN_KEY_STOW_3; do_blocking_move_to(stow_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE)); #endif #ifdef Z_PROBE_ALLEN_KEY_STOW_4 #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0f #endif constexpr xyz_pos_t stow_4 = Z_PROBE_ALLEN_KEY_STOW_4; do_blocking_move_to(stow_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE)); #endif #ifdef Z_PROBE_ALLEN_KEY_STOW_5 #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0f #endif constexpr xyz_pos_t stow_5 = Z_PROBE_ALLEN_KEY_STOW_5; do_blocking_move_to(stow_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE)); #endif } #elif ENABLED(MAG_MOUNTED_PROBE) typedef struct { float fr_mm_min; xyz_pos_t where; } mag_probe_move_t; inline void run_deploy_moves() { #ifdef MAG_MOUNTED_DEPLOY_1 constexpr mag_probe_move_t deploy_1 = MAG_MOUNTED_DEPLOY_1; do_blocking_move_to(deploy_1.where, MMM_TO_MMS(deploy_1.fr_mm_min)); #endif #ifdef MAG_MOUNTED_DEPLOY_2 constexpr mag_probe_move_t deploy_2 = MAG_MOUNTED_DEPLOY_2; do_blocking_move_to(deploy_2.where, MMM_TO_MMS(deploy_2.fr_mm_min)); #endif #ifdef MAG_MOUNTED_DEPLOY_3 constexpr mag_probe_move_t deploy_3 = MAG_MOUNTED_DEPLOY_3; do_blocking_move_to(deploy_3.where, MMM_TO_MMS(deploy_3.fr_mm_min)); #endif #ifdef MAG_MOUNTED_DEPLOY_4 constexpr mag_probe_move_t deploy_4 = MAG_MOUNTED_DEPLOY_4; do_blocking_move_to(deploy_4.where, MMM_TO_MMS(deploy_4.fr_mm_min)); #endif #ifdef MAG_MOUNTED_DEPLOY_5 constexpr mag_probe_move_t deploy_5 = MAG_MOUNTED_DEPLOY_5; do_blocking_move_to(deploy_5.where, MMM_TO_MMS(deploy_5.fr_mm_min)); #endif } inline void run_stow_moves() { #ifdef MAG_MOUNTED_STOW_1 constexpr mag_probe_move_t stow_1 = MAG_MOUNTED_STOW_1; do_blocking_move_to(stow_1.where, MMM_TO_MMS(stow_1.fr_mm_min)); #endif #ifdef MAG_MOUNTED_STOW_2 constexpr mag_probe_move_t stow_2 = MAG_MOUNTED_STOW_2; do_blocking_move_to(stow_2.where, MMM_TO_MMS(stow_2.fr_mm_min)); #endif #ifdef MAG_MOUNTED_STOW_3 constexpr mag_probe_move_t stow_3 = MAG_MOUNTED_STOW_3; do_blocking_move_to(stow_3.where, MMM_TO_MMS(stow_3.fr_mm_min)); #endif #ifdef MAG_MOUNTED_STOW_4 constexpr mag_probe_move_t stow_4 = MAG_MOUNTED_STOW_4; do_blocking_move_to(stow_4.where, MMM_TO_MMS(stow_4.fr_mm_min)); #endif #ifdef MAG_MOUNTED_STOW_5 constexpr mag_probe_move_t stow_5 = MAG_MOUNTED_STOW_5; do_blocking_move_to(stow_5.where, MMM_TO_MMS(stow_5.fr_mm_min)); #endif } #endif // MAG_MOUNTED_PROBE #if HAS_QUIET_PROBING #ifndef DELAY_BEFORE_PROBING #define DELAY_BEFORE_PROBING 25 #endif void Probe::set_probing_paused(const bool dopause) { TERN_(PROBING_HEATERS_OFF, thermalManager.pause_heaters(dopause)); TERN_(PROBING_FANS_OFF, thermalManager.set_fans_paused(dopause)); TERN_(PROBING_ESTEPPERS_OFF, if (dopause) stepper.disable_e_steppers()); #if ENABLED(PROBING_STEPPERS_OFF) && DISABLED(DELTA) static uint8_t old_trusted; if (dopause) { old_trusted = axes_trusted; stepper.disable_axis(X_AXIS); stepper.disable_axis(Y_AXIS); } else { if (TEST(old_trusted, X_AXIS)) stepper.enable_axis(X_AXIS); if (TEST(old_trusted, Y_AXIS)) stepper.enable_axis(Y_AXIS); axes_trusted = old_trusted; } #endif if (dopause) safe_delay(_MAX(DELAY_BEFORE_PROBING, 25)); } #endif // HAS_QUIET_PROBING FORCE_INLINE void probe_specific_action(const bool deploy) { DEBUG_SECTION(log_psa, "Probe::probe_specific_action", DEBUGGING(LEVELING)); #if ENABLED(PAUSE_BEFORE_DEPLOY_STOW) // Start preheating before waiting for user confirmation that the probe is ready. TERN_(PREHEAT_BEFORE_PROBING, if (deploy) probe.preheat_for_probing(0, PROBING_BED_TEMP, true)); FSTR_P const ds_fstr = deploy ? GET_TEXT_F(MSG_MANUAL_DEPLOY) : GET_TEXT_F(MSG_MANUAL_STOW); ui.return_to_status(); // To display the new status message ui.set_max_status(ds_fstr); SERIAL_ECHOLN(deploy ? GET_EN_TEXT_F(MSG_MANUAL_DEPLOY) : GET_EN_TEXT_F(MSG_MANUAL_STOW)); OKAY_BUZZ(); #if ENABLED(PAUSE_PROBE_DEPLOY_WHEN_TRIGGERED) { // Wait for the probe to be attached or detached before asking for explicit user confirmation // Allow the user to interrupt KEEPALIVE_STATE(PAUSED_FOR_USER); TERN_(HAS_RESUME_CONTINUE, wait_for_user = true); while (deploy == PROBE_TRIGGERED() && TERN1(HAS_RESUME_CONTINUE, wait_for_user)) idle_no_sleep(); TERN_(HAS_RESUME_CONTINUE, wait_for_user = false); OKAY_BUZZ(); } #endif TERN_(HOST_PROMPT_SUPPORT, hostui.continue_prompt(ds_fstr)); #if ENABLED(DWIN_LCD_PROUI) ExtUI::onUserConfirmRequired(ICON_BLTouch, ds_fstr, FPSTR(CONTINUE_STR)); #elif ENABLED(EXTENSIBLE_UI) ExtUI::onUserConfirmRequired(ds_fstr); #endif TERN_(HAS_RESUME_CONTINUE, wait_for_user_response()); ui.reset_status(); #endif // PAUSE_BEFORE_DEPLOY_STOW #if ENABLED(SOLENOID_PROBE) #if HAS_SOLENOID_1 WRITE(SOL1_PIN, deploy); #endif #elif ENABLED(MAGLEV4) deploy ? maglev_deploy() : maglev_idle(); #elif ENABLED(Z_PROBE_SLED) dock_sled(!deploy); #elif ENABLED(BLTOUCH) deploy ? bltouch.deploy() : bltouch.stow(); #elif HAS_Z_SERVO_PROBE // i.e., deploy ? DEPLOY_Z_SERVO() : STOW_Z_SERVO(); servo[Z_PROBE_SERVO_NR].move(servo_angles[Z_PROBE_SERVO_NR][deploy ? 0 : 1]); #ifdef Z_SERVO_MEASURE_ANGLE // After deploy move back to the measure angle... if (deploy) servo[Z_PROBE_SERVO_NR].move(Z_SERVO_MEASURE_ANGLE); #endif if (TERN0(Z_SERVO_DEACTIVATE_AFTER_STOW, !deploy)) servo[Z_PROBE_SERVO_NR].detach(); #elif ANY(TOUCH_MI_PROBE, Z_PROBE_ALLEN_KEY, MAG_MOUNTED_PROBE) deploy ? run_deploy_moves() : run_stow_moves(); #elif ENABLED(RACK_AND_PINION_PROBE) do_blocking_move_to_x(deploy ? Z_PROBE_DEPLOY_X : Z_PROBE_RETRACT_X); #elif DISABLED(PAUSE_BEFORE_DEPLOY_STOW) UNUSED(deploy); #endif } #if ANY(PREHEAT_BEFORE_PROBING, PREHEAT_BEFORE_LEVELING) #if ENABLED(PREHEAT_BEFORE_PROBING) #ifndef PROBING_NOZZLE_TEMP #define PROBING_NOZZLE_TEMP 0 #endif #ifndef PROBING_BED_TEMP #define PROBING_BED_TEMP 0 #endif #endif /** * Do preheating as required before leveling or probing. * - If a preheat input is higher than the current target, raise the target temperature. * - If a preheat input is higher than the current temperature, wait for stabilization. */ void Probe::preheat_for_probing(const celsius_t hotend_temp, const celsius_t bed_temp, const bool early/*=false*/) { #if HAS_HOTEND && (PROBING_NOZZLE_TEMP || LEVELING_NOZZLE_TEMP) #define WAIT_FOR_NOZZLE_HEAT #endif #if HAS_HEATED_BED && (PROBING_BED_TEMP || LEVELING_BED_TEMP) #define WAIT_FOR_BED_HEAT #endif if (!early) LCD_MESSAGE(MSG_PREHEATING); DEBUG_ECHOPGM("Preheating "); #if ENABLED(WAIT_FOR_NOZZLE_HEAT) const celsius_t hotendPreheat = hotend_temp > thermalManager.degTargetHotend(0) ? hotend_temp : 0; if (hotendPreheat) { DEBUG_ECHOPGM("hotend (", hotendPreheat, ")"); thermalManager.setTargetHotend(hotendPreheat, 0); } #endif #if ENABLED(WAIT_FOR_BED_HEAT) const celsius_t bedPreheat = bed_temp > thermalManager.degTargetBed() ? bed_temp : 0; if (bedPreheat) { if (TERN0(WAIT_FOR_NOZZLE_HEAT, hotendPreheat)) DEBUG_ECHOPGM(" and "); DEBUG_ECHOPGM("bed (", bedPreheat, ")"); thermalManager.setTargetBed(bedPreheat); } #endif DEBUG_EOL(); if (!early) { TERN_(WAIT_FOR_NOZZLE_HEAT, if (hotend_temp > thermalManager.wholeDegHotend(0) + (TEMP_WINDOW)) thermalManager.wait_for_hotend(0)); TERN_(WAIT_FOR_BED_HEAT, if (bed_temp > thermalManager.wholeDegBed() + (TEMP_BED_WINDOW)) thermalManager.wait_for_bed_heating()); } } #endif /** * Print an error and stop() */ void Probe::probe_error_stop() { SERIAL_ERROR_START(); SERIAL_ECHOPGM(STR_STOP_PRE); #if ANY(Z_PROBE_SLED, Z_PROBE_ALLEN_KEY) SERIAL_ECHOPGM(STR_STOP_UNHOMED); #elif ENABLED(BLTOUCH) SERIAL_ECHOPGM(STR_STOP_BLTOUCH); #endif SERIAL_ECHOLNPGM(STR_STOP_POST); stop(); } /** * Attempt to deploy or stow the probe * * Return TRUE if the probe could not be deployed/stowed */ bool Probe::set_deployed(const bool deploy, const bool no_return/*=false*/) { if (DEBUGGING(LEVELING)) { DEBUG_POS("Probe::set_deployed", current_position); DEBUG_ECHOLNPGM("deploy=", deploy, " no_return=", no_return); } if (endstops.z_probe_enabled == deploy) return false; // Make room for probe to deploy (or stow) // Fix-mounted probe should only raise for deploy // unless PAUSE_BEFORE_DEPLOY_STOW is enabled #if ANY(FIX_MOUNTED_PROBE, NOZZLE_AS_PROBE) && DISABLED(PAUSE_BEFORE_DEPLOY_STOW) const bool z_raise_wanted = deploy; #else constexpr bool z_raise_wanted = true; #endif if (z_raise_wanted) { const float zdest = DIFF_TERN(HAS_HOTEND_OFFSET, Z_CLEARANCE_DEPLOY_PROBE, hotend_offset[active_extruder].z); if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Raise Z to ", zdest); do_z_clearance(zdest); } #if ANY(Z_PROBE_SLED, Z_PROBE_ALLEN_KEY) if (homing_needed_error(TERN_(Z_PROBE_SLED, _BV(X_AXIS)))) { probe_error_stop(); return true; } #endif const xy_pos_t old_xy = current_position; // Remember location before probe deployment #if ENABLED(PROBE_TRIGGERED_WHEN_STOWED_TEST) // Only deploy/stow if needed if (PROBE_TRIGGERED() == deploy) { if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early // otherwise an Allen-Key probe can't be stowed. probe_specific_action(deploy); } if (PROBE_TRIGGERED() == deploy) { // Unchanged after deploy/stow action? if (IsRunning()) { SERIAL_ERROR_MSG("Z-Probe failed"); LCD_ALERTMESSAGE_F("Err: ZPROBE"); } stop(); return true; } #else probe_specific_action(deploy); #endif // If preheating is required before any probing... // TODO: Consider skipping this for things like M401, G34, etc. TERN_(PREHEAT_BEFORE_PROBING, if (deploy) preheat_for_probing(PROBING_NOZZLE_TEMP, PROBING_BED_TEMP)); if (!no_return) do_blocking_move_to(old_xy); // Return to the original location unless handled externally endstops.enable_z_probe(deploy); return false; } /** * @brief Move down until the probe triggers or the low limit is reached * Used by run_z_probe to do a single Z probe move. * * @param z Z destination * @param fr_mm_s Feedrate in mm/s * @return true to indicate an error * * @details Used by run_z_probe to get each bed Z height measurement. * Sets current_position.z to the height where the probe triggered * (according to the Z stepper count). The float Z is propagated * back to the planner.position to preempt any rounding error. * * @return TRUE if the probe failed to trigger. */ bool Probe::probe_down_to_z(const_float_t z, const_feedRate_t fr_mm_s) { DEBUG_SECTION(log_probe, "Probe::probe_down_to_z", DEBUGGING(LEVELING)); #if ALL(HAS_HEATED_BED, WAIT_FOR_BED_HEATER) thermalManager.wait_for_bed_heating(); #endif #if ALL(HAS_TEMP_HOTEND, WAIT_FOR_HOTEND) thermalManager.wait_for_hotend_heating(active_extruder); #endif #if ENABLED(BLTOUCH) // Ensure the BLTouch is deployed. (Does nothing if already deployed.) // Don't deploy with high_speed_mode enabled. The probe already re-deploys itself. if (TERN(MEASURE_BACKLASH_WHEN_PROBING, true, !bltouch.high_speed_mode) && bltouch.deploy()) return true; #endif #if HAS_Z_SERVO_PROBE && (ENABLED(Z_SERVO_INTERMEDIATE_STOW) || defined(Z_SERVO_MEASURE_ANGLE)) probe_specific_action(true); // Always re-deploy in this case #endif // Disable stealthChop if used. Enable diag1 pin on driver. #if ENABLED(SENSORLESS_PROBING) sensorless_t stealth_states { false }; #if HAS_DELTA_SENSORLESS_PROBING if (test_sensitivity.x) stealth_states.x = tmc_enable_stallguard(stepperX); // Delta watches all DIAG pins for a stall if (test_sensitivity.y) stealth_states.y = tmc_enable_stallguard(stepperY); #endif if (test_sensitivity.z) { stealth_states.z = tmc_enable_stallguard(stepperZ); // All machines will check Z-DIAG for stall #if ENABLED(Z_MULTI_ENDSTOPS) stealth_states.z2 = tmc_enable_stallguard(stepperZ2); #if NUM_Z_STEPPERS >= 3 stealth_states.z3 = tmc_enable_stallguard(stepperZ3); #if NUM_Z_STEPPERS >= 4 stealth_states.z4 = tmc_enable_stallguard(stepperZ4); #endif #endif #endif } endstops.set_z_sensorless_current(true); // The "homing" current also applies to probing endstops.enable(true); #endif // SENSORLESS_PROBING TERN_(HAS_QUIET_PROBING, set_probing_paused(true)); // Move down until the probe is triggered do_blocking_move_to_z(z, fr_mm_s); // Check to see if the probe was triggered const bool probe_triggered = ( #if HAS_DELTA_SENSORLESS_PROBING endstops.trigger_state() & (_BV(X_MAX) | _BV(Y_MAX) | _BV(Z_MAX)) #else TEST(endstops.trigger_state(), Z_MIN_PROBE) #endif ); // Offset sensorless probing #if HAS_DELTA_SENSORLESS_PROBING if (probe_triggered) refresh_largest_sensorless_adj(); #endif TERN_(HAS_QUIET_PROBING, set_probing_paused(false)); // Re-enable stealthChop if used. Disable diag1 pin on driver. #if ENABLED(SENSORLESS_PROBING) endstops.not_homing(); #if HAS_DELTA_SENSORLESS_PROBING if (test_sensitivity.x) tmc_disable_stallguard(stepperX, stealth_states.x); if (test_sensitivity.y) tmc_disable_stallguard(stepperY, stealth_states.y); #endif if (test_sensitivity.z) { tmc_disable_stallguard(stepperZ, stealth_states.z); #if ENABLED(Z_MULTI_ENDSTOPS) tmc_disable_stallguard(stepperZ2, stealth_states.z2); #if NUM_Z_STEPPERS >= 3 tmc_disable_stallguard(stepperZ3, stealth_states.z3); #if NUM_Z_STEPPERS >= 4 tmc_disable_stallguard(stepperZ4, stealth_states.z4); #endif #endif #endif } endstops.set_z_sensorless_current(false); #endif // SENSORLESS_PROBING #if ENABLED(BLTOUCH) if (probe_triggered && !bltouch.high_speed_mode && bltouch.stow()) return true; // Stow in LOW SPEED MODE on every trigger #endif #if ALL(HAS_Z_SERVO_PROBE, Z_SERVO_INTERMEDIATE_STOW) probe_specific_action(false); // Always stow #endif // Clear endstop flags endstops.hit_on_purpose(); // Get Z where the steppers were interrupted set_current_from_steppers_for_axis(Z_AXIS); // Tell the planner where we actually are sync_plan_position(); return !probe_triggered; } #if ENABLED(PROBE_TARE) /** * @brief Init the tare pin * * @details Init tare pin to ON state for a strain gauge, otherwise OFF */ void Probe::tare_init() { OUT_WRITE(PROBE_TARE_PIN, !PROBE_TARE_STATE); } /** * @brief Tare the Z probe * * @details Signal to the probe to tare itself * * @return TRUE if the tare cold not be completed */ bool Probe::tare() { #if ALL(PROBE_ACTIVATION_SWITCH, PROBE_TARE_ONLY_WHILE_INACTIVE) if (endstops.probe_switch_activated()) { if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Cannot tare an active probe"); return true; } #endif if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Taring probe"); WRITE(PROBE_TARE_PIN, PROBE_TARE_STATE); delay(PROBE_TARE_TIME); WRITE(PROBE_TARE_PIN, !PROBE_TARE_STATE); delay(PROBE_TARE_DELAY); endstops.hit_on_purpose(); return false; } #endif /** * @brief Probe at the current XY (possibly more than once) to find the bed Z. * * @details Used by probe_at_point to get the bed Z height at the current XY. * Leaves current_position.z at the height where the probe triggered. * * @param sanity_check Flag to compare the probe result with the expected result * based on the probe Z offset. If the result is too far away * (more than Z_PROBE_ERROR_TOLERANCE too early) then throw an error. * @param z_min_point Override the minimum probing height (-2mm), to allow deeper probing. * @param z_clearance Z clearance to apply on probe failure. * * @return The Z position of the bed at the current XY or NAN on error. */ float Probe::run_z_probe(const bool sanity_check/*=true*/, const_float_t z_min_point/*=Z_PROBE_LOW_POINT*/, const_float_t z_clearance/*=Z_TWEEN_SAFE_CLEARANCE*/) { DEBUG_SECTION(log_probe, "Probe::run_z_probe", DEBUGGING(LEVELING)); const float zoffs = SUM_TERN(HAS_HOTEND_OFFSET, -offset.z, hotend_offset[active_extruder].z); auto try_to_probe = [&](PGM_P const plbl, const_float_t z_probe_low_point, const feedRate_t fr_mm_s, const bool scheck) -> bool { constexpr float error_tolerance = Z_PROBE_ERROR_TOLERANCE; if (DEBUGGING(LEVELING)) { DEBUG_ECHOPGM_P(plbl); DEBUG_ECHOLNPGM("> try_to_probe(..., ", z_probe_low_point, ", ", fr_mm_s, ", ...)"); } // Tare the probe, if supported if (TERN0(PROBE_TARE, tare())) return true; // Do a first probe at the fast speed const bool probe_fail = probe_down_to_z(z_probe_low_point, fr_mm_s), // No probe trigger? early_fail = (scheck && current_position.z > zoffs + error_tolerance); // Probe triggered too high? #if ENABLED(DEBUG_LEVELING_FEATURE) if (DEBUGGING(LEVELING) && (probe_fail || early_fail)) { DEBUG_ECHOPGM(" Probe fail! - "); if (probe_fail) DEBUG_ECHOLNPGM("No trigger."); if (early_fail) DEBUG_ECHOLNPGM("Triggered early (above ", zoffs + error_tolerance, "mm)"); } #else UNUSED(plbl); #endif return probe_fail || early_fail; }; // Stop the probe before it goes too low to prevent damage. // For known Z probe below the expected trigger point, otherwise -10mm lower. const float z_probe_low_point = zoffs + z_min_point -float((!axis_is_trusted(Z_AXIS)) * 10); if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Probe Low Point: ", z_probe_low_point); // Double-probing does a fast probe followed by a slow probe #if TOTAL_PROBING == 2 // Attempt to tare the probe if (TERN0(PROBE_TARE, tare())) return NAN; // Do a first probe at the fast speed if (try_to_probe(PSTR("FAST"), z_probe_low_point, z_probe_fast_mm_s, sanity_check)) return NAN; const float z1 = DIFF_TERN(HAS_DELTA_SENSORLESS_PROBING, current_position.z, largest_sensorless_adj); if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("1st Probe Z:", z1); // Raise to give the probe clearance do_z_clearance(z1 + (Z_CLEARANCE_MULTI_PROBE), false); #elif Z_PROBE_FEEDRATE_FAST != Z_PROBE_FEEDRATE_SLOW // If the nozzle is well over the travel height then // move down quickly before doing the slow probe const float z = (Z_CLEARANCE_DEPLOY_PROBE) + 5.0f + _MAX(zoffs, 0.0f); if (current_position.z > z) { // Probe down fast. If the probe never triggered, raise for probe clearance if (!probe_down_to_z(z, z_probe_fast_mm_s)) do_z_clearance(z_clearance); } #endif #if EXTRA_PROBING > 0 float probes[TOTAL_PROBING]; #endif #if TOTAL_PROBING > 2 float probes_z_sum = 0; for ( #if EXTRA_PROBING > 0 uint8_t p = 0; p < TOTAL_PROBING; p++ #else uint8_t p = TOTAL_PROBING; p--; #endif ) #endif { // If the probe won't tare, return if (TERN0(PROBE_TARE, tare())) return true; // Probe downward slowly to find the bed if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Slow Probe:"); if (try_to_probe(PSTR("SLOW"), z_probe_low_point, MMM_TO_MMS(Z_PROBE_FEEDRATE_SLOW), sanity_check)) return NAN; TERN_(MEASURE_BACKLASH_WHEN_PROBING, backlash.measure_with_probe()); const float z = DIFF_TERN(HAS_DELTA_SENSORLESS_PROBING, current_position.z, largest_sensorless_adj); #if EXTRA_PROBING > 0 // Insert Z measurement into probes[]. Keep it sorted ascending. for (uint8_t i = 0; i <= p; ++i) { // Iterate the saved Zs to insert the new Z if (i == p || probes[i] > z) { // Last index or new Z is smaller than this Z for (int8_t m = p; --m >= i;) probes[m + 1] = probes[m]; // Shift items down after the insertion point probes[i] = z; // Insert the new Z measurement break; // Only one to insert. Done! } } #elif TOTAL_PROBING > 2 probes_z_sum += z; #else UNUSED(z); #endif #if TOTAL_PROBING > 2 // Small Z raise after all but the last probe if (p #if EXTRA_PROBING > 0 < TOTAL_PROBING - 1 #endif ) do_z_clearance(z + (Z_CLEARANCE_MULTI_PROBE), false); #endif } #if TOTAL_PROBING > 2 #if EXTRA_PROBING > 0 // Take the center value (or average the two middle values) as the median static constexpr int PHALF = (TOTAL_PROBING - 1) / 2; const float middle = probes[PHALF], median = ((TOTAL_PROBING) & 1) ? middle : (middle + probes[PHALF + 1]) * 0.5f; // Remove values farthest from the median uint8_t min_avg_idx = 0, max_avg_idx = TOTAL_PROBING - 1; for (uint8_t i = EXTRA_PROBING; i--;) if (ABS(probes[max_avg_idx] - median) > ABS(probes[min_avg_idx] - median)) max_avg_idx--; else min_avg_idx++; // Return the average value of all remaining probes. for (uint8_t i = min_avg_idx; i <= max_avg_idx; ++i) probes_z_sum += probes[i]; #endif const float measured_z = probes_z_sum * RECIPROCAL(MULTIPLE_PROBING); #elif TOTAL_PROBING == 2 const float z2 = DIFF_TERN(HAS_DELTA_SENSORLESS_PROBING, current_position.z, largest_sensorless_adj); if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("2nd Probe Z:", z2, " Discrepancy:", z1 - z2); // Return a weighted average of the fast and slow probes const float measured_z = (z2 * 3.0f + z1 * 2.0f) * 0.2f; #else // Return the single probe result const float measured_z = current_position.z; #endif return DIFF_TERN(HAS_HOTEND_OFFSET, measured_z, hotend_offset[active_extruder].z); } #if DO_TOOLCHANGE_FOR_PROBING #include "tool_change.h" /** * Switches to the appropriate tool (PROBING_TOOL) for probing (probing = true), and switches * back to the old tool when probing = false. Uses statics to avoid unnecessary checks and to * cache the previous tool, so always call with false after calling with true. */ void Probe::use_probing_tool(const bool probing/*=true*/) { static uint8_t old_tool; static bool old_state = false; if (probing == old_state) return; old_state = probing; if (probing) old_tool = active_extruder; const uint8_t tool = probing ? PROBING_TOOL : old_tool; if (tool != active_extruder) tool_change(tool, ENABLED(PROBE_TOOLCHANGE_NO_MOVE)); } #endif /** * - Move to the given XY * - Deploy the probe, if not already deployed * - Probe the bed, get the Z position * - Depending on the 'stow' flag * - Stow the probe, or * - Raise to the BETWEEN height * - Return the probed Z position * - Revert to previous tool * * A batch of multiple probing operations should always be preceded by use_probing_tool() invocation * and succeeded by use_probing_tool(false), in order to avoid multiple tool changes and to end up * with the previously active tool. * */ float Probe::probe_at_point(const_float_t rx, const_float_t ry, const ProbePtRaise raise_after/*=PROBE_PT_NONE*/, const uint8_t verbose_level/*=0*/, const bool probe_relative/*=true*/, const bool sanity_check/*=true*/, const_float_t z_min_point/*=Z_PROBE_LOW_POINT*/, const_float_t z_clearance/*=Z_TWEEN_SAFE_CLEARANCE*/, const bool raise_after_is_relative/*=false*/ ) { DEBUG_SECTION(log_probe, "Probe::probe_at_point", DEBUGGING(LEVELING)); if (DEBUGGING(LEVELING)) { DEBUG_ECHOLNPGM( "...(", LOGICAL_X_POSITION(rx), ", ", LOGICAL_Y_POSITION(ry), ", ", raise_after == PROBE_PT_RAISE ? "raise" : raise_after == PROBE_PT_LAST_STOW ? "stow (last)" : raise_after == PROBE_PT_STOW ? "stow" : "none", ", ", verbose_level, ", ", probe_relative ? "probe" : "nozzle", "_relative)" ); DEBUG_POS("", current_position); } #if ENABLED(BLTOUCH) // Reset a BLTouch in HS mode if already triggered if (bltouch.high_speed_mode && bltouch.triggered()) bltouch._reset(); #endif // Use a safe Z height for the XY move const float safe_z = _MAX(current_position.z, z_clearance); // On delta keep Z below clip height or do_blocking_move_to will abort xyz_pos_t npos = NUM_AXIS_ARRAY( rx, ry, TERN(DELTA, _MIN(delta_clip_start_height, safe_z), safe_z), current_position.i, current_position.j, current_position.k, current_position.u, current_position.v, current_position.w ); if (!can_reach(npos, probe_relative)) { if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM("Not Reachable"); return NAN; } if (DEBUGGING(LEVELING)) DEBUG_ECHOPGM("Move to probe"); if (probe_relative) { // Get the nozzle position, adjust for active hotend if not 0 if (DEBUGGING(LEVELING)) DEBUG_ECHOPGM("-relative"); npos -= DIFF_TERN(HAS_HOTEND_OFFSET, offset_xy, xy_pos_t(hotend_offset[active_extruder])); } if (DEBUGGING(LEVELING)) DEBUG_ECHOLNPGM(" point"); // Move the probe to the starting XYZ do_blocking_move_to(npos, feedRate_t(XY_PROBE_FEEDRATE_MM_S)); #if ENABLED(BD_SENSOR) safe_delay(4); return current_position.z - bdl.read(); // Difference between Z-home-relative Z and sensor reading #else // !BD_SENSOR float measured_z = deploy() ? NAN : run_z_probe(sanity_check, z_min_point, z_clearance) + offset.z; // Deploy succeeded and a successful measurement was done. // Raise and/or stow the probe depending on 'raise_after' and settings. if (!isnan(measured_z)) { switch (raise_after) { default: break; case PROBE_PT_RAISE: if (raise_after_is_relative) do_z_clearance(current_position.z + z_clearance, false); else do_z_clearance(z_clearance); break; case PROBE_PT_STOW: case PROBE_PT_LAST_STOW: if (stow()) measured_z = NAN; // Error on stow? break; } } // If any error occurred stow the probe and set an alert if (isnan(measured_z)) { // TODO: Disable steppers (unless G29_RETRY_AND_RECOVER or G29_HALT_ON_FAILURE are set). // Something definitely went wrong at this point, so it might be a good idea to release the steppers. // The user may want to quickly move the carriage or bed by hand to avoid bed damage from the (hot) nozzle. // This would also benefit from the contemplated "Audio Alerts" feature. stow(); LCD_MESSAGE(MSG_LCD_PROBING_FAILED); #if DISABLED(G29_RETRY_AND_RECOVER) SERIAL_ERROR_MSG(STR_ERR_PROBING_FAILED); #endif } else { TERN_(HAS_PTC, ptc.apply_compensation(measured_z)); TERN_(X_AXIS_TWIST_COMPENSATION, measured_z += xatc.compensation(npos + offset_xy)); if (verbose_level > 2 || DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Bed X: ", LOGICAL_X_POSITION(rx), " Y: ", LOGICAL_Y_POSITION(ry), " Z: ", measured_z); } return measured_z; #endif // !BD_SENSOR } #if HAS_Z_SERVO_PROBE void Probe::servo_probe_init() { /** * Set position of Z Servo Endstop * * The servo might be deployed and positioned too low to stow * when starting up the machine or rebooting the board. * There's no way to know where the nozzle is positioned until * homing has been done - no homing with z-probe without init! */ STOW_Z_SERVO(); TERN_(Z_SERVO_DEACTIVATE_AFTER_STOW, servo[Z_PROBE_SERVO_NR].detach()); } #endif // HAS_Z_SERVO_PROBE #if HAS_DELTA_SENSORLESS_PROBING /** * Set the sensorless Z offset */ void Probe::set_offset_sensorless_adj(const_float_t sz) { DEBUG_SECTION(pso, "Probe::set_offset_sensorless_adj", true); if (test_sensitivity.x) offset_sensorless_adj.a = sz; if (test_sensitivity.y) offset_sensorless_adj.b = sz; if (test_sensitivity.z) offset_sensorless_adj.c = sz; } /** * Refresh largest_sensorless_adj based on triggered endstops */ void Probe::refresh_largest_sensorless_adj() { DEBUG_SECTION(rso, "Probe::refresh_largest_sensorless_adj", true); largest_sensorless_adj = -3; // A reference away from any real probe height const Endstops::endstop_mask_t state = endstops.state(); if (TEST(state, X_MAX)) { NOLESS(largest_sensorless_adj, offset_sensorless_adj.a); DEBUG_ECHOLNPGM("Endstop_X: ", largest_sensorless_adj, " TowerX"); } if (TEST(state, Y_MAX)) { NOLESS(largest_sensorless_adj, offset_sensorless_adj.b); DEBUG_ECHOLNPGM("Endstop_Y: ", largest_sensorless_adj, " TowerY"); } if (TEST(state, Z_MAX)) { NOLESS(largest_sensorless_adj, offset_sensorless_adj.c); DEBUG_ECHOLNPGM("Endstop_Z: ", largest_sensorless_adj, " TowerZ"); } } #endif #endif // HAS_BED_PROBE
2301_81045437/Marlin
Marlin/src/module/probe.cpp
C++
agpl-3.0
37,562
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 /** * module/probe.h - Move, deploy, enable, etc. */ #include "../inc/MarlinConfig.h" #include "motion.h" #if ENABLED(BLTOUCH) #include "../feature/bltouch.h" #endif #define DEBUG_OUT ENABLED(DEBUG_LEVELING_FEATURE) #include "../core/debug_out.h" #if HAS_BED_PROBE enum ProbePtRaise : uint8_t { PROBE_PT_NONE, // No raise or stow after run_z_probe PROBE_PT_STOW, // Do a complete stow after run_z_probe PROBE_PT_LAST_STOW, // Stow for sure, even in BLTouch HS mode PROBE_PT_RAISE // Raise to "between" clearance after run_z_probe }; #endif #if ENABLED(BD_SENSOR) #define PROBE_READ() bdp_state #elif USE_Z_MIN_PROBE #define PROBE_READ() READ(Z_MIN_PROBE_PIN) #else #define PROBE_READ() READ(Z_MIN_PIN) #endif #if USE_Z_MIN_PROBE #define PROBE_HIT_STATE Z_MIN_PROBE_ENDSTOP_HIT_STATE #else #define PROBE_HIT_STATE Z_MIN_ENDSTOP_HIT_STATE #endif #define PROBE_TRIGGERED() (PROBE_READ() == PROBE_HIT_STATE) // In BLTOUCH HS mode, the probe travels in a deployed state. #define Z_TWEEN_SAFE_CLEARANCE SUM_TERN(BLTOUCH, Z_CLEARANCE_BETWEEN_PROBES, bltouch.z_extra_clearance()) #if ENABLED(PREHEAT_BEFORE_LEVELING) #ifndef LEVELING_NOZZLE_TEMP #define LEVELING_NOZZLE_TEMP 0 #endif #ifndef LEVELING_BED_TEMP #define LEVELING_BED_TEMP 0 #endif #endif #if ENABLED(SENSORLESS_PROBING) extern abc_float_t offset_sensorless_adj; #endif class Probe { public: #if ENABLED(SENSORLESS_PROBING) typedef struct { bool x:1, y:1, z:1; } sense_bool_t; static sense_bool_t test_sensitivity; #endif #if HAS_BED_PROBE static xyz_pos_t offset; #if ANY(PREHEAT_BEFORE_PROBING, PREHEAT_BEFORE_LEVELING) static void preheat_for_probing(const celsius_t hotend_temp, const celsius_t bed_temp, const bool early=false); #endif static void probe_error_stop(); static bool set_deployed(const bool deploy, const bool no_return=false); #if IS_KINEMATIC #if HAS_PROBE_XY_OFFSET // Return true if the both nozzle and the probe can reach the given point. // Note: This won't work on SCARA since the probe offset rotates with the arm. static bool can_reach(const_float_t rx, const_float_t ry, const bool probe_relative=true) { if (probe_relative) { return position_is_reachable(rx - offset_xy.x, ry - offset_xy.y) // The nozzle can go where it needs to go? && position_is_reachable(rx, ry, PROBING_MARGIN); // Can the probe also go near there? } else { return position_is_reachable(rx, ry) && position_is_reachable(rx + offset_xy.x, ry + offset_xy.y, PROBING_MARGIN); } } #else static bool can_reach(const_float_t rx, const_float_t ry, const bool=true) { return position_is_reachable(rx, ry) && position_is_reachable(rx, ry, PROBING_MARGIN); } #endif #else // !IS_KINEMATIC static bool obstacle_check(const_float_t rx, const_float_t ry) { #if ENABLED(AVOID_OBSTACLES) #ifdef OBSTACLE1 constexpr float obst1[] = OBSTACLE1; static_assert(COUNT(obst1) == 4, "OBSTACLE1 must define a rectangle in the form { X1, Y1, X2, Y2 }."); if (WITHIN(rx, obst1[0], obst1[2]) && WITHIN(ry, obst1[1], obst1[3])) return false; #endif #ifdef OBSTACLE2 constexpr float obst2[] = OBSTACLE2; static_assert(COUNT(obst2) == 4, "OBSTACLE2 must define a rectangle in the form { X1, Y1, X2, Y2 }."); if (WITHIN(rx, obst2[0], obst2[2]) && WITHIN(ry, obst2[1], obst2[3])) return false; #endif #ifdef OBSTACLE3 constexpr float obst3[] = OBSTACLE3; static_assert(COUNT(obst3) == 4, "OBSTACLE3 must define a rectangle in the form { X1, Y1, X2, Y2 }."); if (WITHIN(rx, obst3[0], obst3[2]) && WITHIN(ry, obst3[1], obst3[3])) return false; #endif #ifdef OBSTACLE4 constexpr float obst4[] = OBSTACLE4; static_assert(COUNT(obst4) == 4, "OBSTACLE4 must define a rectangle in the form { X1, Y1, X2, Y2 }."); if (WITHIN(rx, obst4[0], obst4[2]) && WITHIN(ry, obst4[1], obst4[3])) return false; #endif #endif return true; } /** * Return whether the given position is within the bed, and whether the nozzle * can reach the position required to put the probe at the given position. * * Example: For a probe offset of -10,+10, then for the probe to reach 0,0 the * nozzle must be be able to reach +10,-10. */ static bool can_reach(const_float_t rx, const_float_t ry, const bool probe_relative=true) { if (probe_relative) { return position_is_reachable(rx - offset_xy.x, ry - offset_xy.y) && COORDINATE_OKAY(rx, min_x() - fslop, max_x() + fslop) && COORDINATE_OKAY(ry, min_y() - fslop, max_y() + fslop) && obstacle_check(rx, ry) && obstacle_check(rx - offset_xy.x, ry - offset_xy.y); } else { return position_is_reachable(rx, ry) && COORDINATE_OKAY(rx + offset_xy.x, min_x() - fslop, max_x() + fslop) && COORDINATE_OKAY(ry + offset_xy.y, min_y() - fslop, max_y() + fslop) && obstacle_check(rx, ry) && obstacle_check(rx + offset_xy.x, ry + offset_xy.y); } } #endif // !IS_KINEMATIC static float probe_at_point(const_float_t rx, const_float_t ry, const ProbePtRaise raise_after=PROBE_PT_NONE, const uint8_t verbose_level=0, const bool probe_relative=true, const bool sanity_check=true, const_float_t z_min_point=Z_PROBE_LOW_POINT, const_float_t z_clearance=Z_TWEEN_SAFE_CLEARANCE, const bool raise_after_is_relative=false); static float probe_at_point(const xy_pos_t &pos, const ProbePtRaise raise_after=PROBE_PT_NONE, const uint8_t verbose_level=0, const bool probe_relative=true, const bool sanity_check=true, const_float_t z_min_point=Z_PROBE_LOW_POINT, float z_clearance=Z_TWEEN_SAFE_CLEARANCE, const bool raise_after_is_relative=false ) { return probe_at_point(pos.x, pos.y, raise_after, verbose_level, probe_relative, sanity_check, z_min_point, z_clearance, raise_after_is_relative); } #else // !HAS_BED_PROBE static constexpr xyz_pos_t offset = xyz_pos_t(NUM_AXIS_ARRAY_1(0)); // See #16767 static bool set_deployed(const bool, const bool=false) { return false; } static bool can_reach(const_float_t rx, const_float_t ry, const bool=true) { return position_is_reachable(TERN_(HAS_X_AXIS, rx) OPTARG(HAS_Y_AXIS, ry)); } #endif // !HAS_BED_PROBE static void use_probing_tool(const bool=true) IF_DISABLED(DO_TOOLCHANGE_FOR_PROBING, {}); static void move_z_after_probing() { DEBUG_SECTION(mzah, "move_z_after_probing", DEBUGGING(LEVELING)); #ifdef Z_AFTER_PROBING do_z_clearance(Z_AFTER_PROBING, true, true); // Move down still permitted #endif } static bool can_reach(const xy_pos_t &pos, const bool probe_relative=true) { return can_reach(pos.x, pos.y, probe_relative); } static bool good_bounds(const xy_pos_t &lf, const xy_pos_t &rb) { return ( #if IS_KINEMATIC can_reach(lf.x, 0) && can_reach(rb.x, 0) && can_reach(0, lf.y) && can_reach(0, rb.y) #else can_reach(lf) && can_reach(rb) #endif ); } // Use offset_xy for read only access // More optimal the XY offset is known to always be zero. #if HAS_PROBE_XY_OFFSET static const xy_pos_t &offset_xy; #else static constexpr xy_pos_t offset_xy = xy_pos_t({ 0, 0 }); // See #16767 #endif static bool deploy(const bool no_return=false) { return set_deployed(true, no_return); } static bool stow(const bool no_return=false) { return set_deployed(false, no_return); } #if HAS_BED_PROBE || HAS_LEVELING #if IS_KINEMATIC static constexpr float probe_radius(const xy_pos_t &probe_offset_xy=offset_xy) { return float(PRINTABLE_RADIUS) - _MAX(PROBING_MARGIN, HYPOT(probe_offset_xy.x, probe_offset_xy.y)); } #endif /** * The nozzle is only able to move within the physical bounds of the machine. * If the PROBE has an OFFSET Marlin may need to apply additional limits so * the probe can be prevented from going to unreachable points. * * e.g., If the PROBE is to the LEFT of the NOZZLE, it will be limited in how * close it can get the RIGHT edge of the bed (unless the nozzle is able move * far enough past the right edge). */ static constexpr float _min_x(const xy_pos_t &probe_offset_xy=offset_xy) { return TERN(IS_KINEMATIC, (X_CENTER) - probe_radius(probe_offset_xy), _MAX((X_MIN_BED) + (PROBING_MARGIN_LEFT), (X_MIN_POS) + probe_offset_xy.x) ); } static constexpr float _max_x(const xy_pos_t &probe_offset_xy=offset_xy) { return TERN(IS_KINEMATIC, (X_CENTER) + probe_radius(probe_offset_xy), _MIN((X_MAX_BED) - (PROBING_MARGIN_RIGHT), (X_MAX_POS) + probe_offset_xy.x) ); } static constexpr float _min_y(const xy_pos_t &probe_offset_xy=offset_xy) { return TERN(IS_KINEMATIC, (Y_CENTER) - probe_radius(probe_offset_xy), _MAX((Y_MIN_BED) + (PROBING_MARGIN_FRONT), (Y_MIN_POS) + probe_offset_xy.y) ); } static constexpr float _max_y(const xy_pos_t &probe_offset_xy=offset_xy) { return TERN(IS_KINEMATIC, (Y_CENTER) + probe_radius(probe_offset_xy), _MIN((Y_MAX_BED) - (PROBING_MARGIN_BACK), (Y_MAX_POS) + probe_offset_xy.y) ); } static float min_x() { return _min_x() TERN_(NOZZLE_AS_PROBE, TERN_(HAS_HOME_OFFSET, - home_offset.x)); } static float max_x() { return _max_x() TERN_(NOZZLE_AS_PROBE, TERN_(HAS_HOME_OFFSET, - home_offset.x)); } static float min_y() { return _min_y() TERN_(NOZZLE_AS_PROBE, TERN_(HAS_HOME_OFFSET, - home_offset.y)); } static float max_y() { return _max_y() TERN_(NOZZLE_AS_PROBE, TERN_(HAS_HOME_OFFSET, - home_offset.y)); } // constexpr helpers used in build-time static_asserts, relying on default probe offsets. class build_time { static constexpr xyz_pos_t default_probe_xyz_offset = xyz_pos_t( #if HAS_BED_PROBE NOZZLE_TO_PROBE_OFFSET #else { 0 } #endif ); static constexpr xy_pos_t default_probe_xy_offset = xy_pos_t({ default_probe_xyz_offset.x, default_probe_xyz_offset.y }); public: static constexpr bool can_reach(float x, float y) { #if IS_KINEMATIC return HYPOT2(x, y) <= sq(probe_radius(default_probe_xy_offset)); #else return COORDINATE_OKAY(x, _min_x(default_probe_xy_offset) - fslop, _max_x(default_probe_xy_offset) + fslop) && COORDINATE_OKAY(y, _min_y(default_probe_xy_offset) - fslop, _max_y(default_probe_xy_offset) + fslop); #endif } static constexpr bool can_reach(const xy_pos_t &point) { return can_reach(point.x, point.y); } }; #if NEEDS_THREE_PROBE_POINTS // Retrieve three points to probe the bed. Any type exposing set(X,Y) may be used. template <typename T> static void get_three_points(T points[3]) { #if HAS_FIXED_3POINT #define VALIDATE_PROBE_PT(N) static_assert(Probe::build_time::can_reach(xy_pos_t(PROBE_PT_##N)), \ "PROBE_PT_" STRINGIFY(N) " is unreachable using default NOZZLE_TO_PROBE_OFFSET and PROBING_MARGIN."); VALIDATE_PROBE_PT(1); VALIDATE_PROBE_PT(2); VALIDATE_PROBE_PT(3); points[0] = xy_float_t(PROBE_PT_1); points[1] = xy_float_t(PROBE_PT_2); points[2] = xy_float_t(PROBE_PT_3); #else #if IS_KINEMATIC constexpr float SIN0 = 0.0, SIN120 = 0.866025, SIN240 = -0.866025, COS0 = 1.0, COS120 = -0.5 , COS240 = -0.5; points[0] = xy_float_t({ (X_CENTER) + probe_radius() * COS0, (Y_CENTER) + probe_radius() * SIN0 }); points[1] = xy_float_t({ (X_CENTER) + probe_radius() * COS120, (Y_CENTER) + probe_radius() * SIN120 }); points[2] = xy_float_t({ (X_CENTER) + probe_radius() * COS240, (Y_CENTER) + probe_radius() * SIN240 }); #elif ENABLED(AUTO_BED_LEVELING_UBL) points[0] = xy_float_t({ _MAX(float(MESH_MIN_X), min_x()), _MAX(float(MESH_MIN_Y), min_y()) }); points[1] = xy_float_t({ _MIN(float(MESH_MAX_X), max_x()), _MAX(float(MESH_MIN_Y), min_y()) }); points[2] = xy_float_t({ (_MAX(float(MESH_MIN_X), min_x()) + _MIN(float(MESH_MAX_X), max_x())) / 2, _MIN(float(MESH_MAX_Y), max_y()) }); #else points[0] = xy_float_t({ min_x(), min_y() }); points[1] = xy_float_t({ max_x(), min_y() }); points[2] = xy_float_t({ (min_x() + max_x()) / 2, max_y() }); #endif #endif } #endif #endif // HAS_BED_PROBE #if HAS_Z_SERVO_PROBE static void servo_probe_init(); #endif #if HAS_QUIET_PROBING static void set_probing_paused(const bool p); #endif #if ENABLED(PROBE_TARE) static void tare_init(); static bool tare(); #endif // Basic functions for Sensorless Homing and Probing #if HAS_DELTA_SENSORLESS_PROBING static void set_offset_sensorless_adj(const_float_t sz); static void refresh_largest_sensorless_adj(); #endif private: static bool probe_down_to_z(const_float_t z, const_feedRate_t fr_mm_s); static float run_z_probe(const bool sanity_check=true, const_float_t z_min_point=Z_PROBE_LOW_POINT, const_float_t z_clearance=Z_TWEEN_SAFE_CLEARANCE); }; extern Probe probe;
2301_81045437/Marlin
Marlin/src/module/probe.h
C++
agpl-3.0
14,645
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * scara.cpp */ #include "../inc/MarlinConfig.h" #if IS_SCARA #include "scara.h" #include "motion.h" #include "planner.h" #if ENABLED(AXEL_TPARA) #include "endstops.h" #include "../MarlinCore.h" #endif float segments_per_second = DEFAULT_SEGMENTS_PER_SECOND; #if ANY(MORGAN_SCARA, MP_SCARA) static constexpr xy_pos_t scara_offset = { SCARA_OFFSET_X, SCARA_OFFSET_Y }; /** * Morgan SCARA Forward Kinematics. Results in 'cartes'. * Maths and first version by QHARLEY. * Integrated into Marlin and slightly restructured by Joachim Cerny. */ void forward_kinematics(const_float_t a, const_float_t b) { const float a_sin = sin(RADIANS(a)) * L1, a_cos = cos(RADIANS(a)) * L1, b_sin = sin(RADIANS(SUM_TERN(MP_SCARA, b, a))) * L2, b_cos = cos(RADIANS(SUM_TERN(MP_SCARA, b, a))) * L2; cartes.x = a_cos + b_cos + scara_offset.x; // theta cartes.y = a_sin + b_sin + scara_offset.y; // phi /* DEBUG_ECHOLNPGM( "SCARA FK Angle a=", a, " b=", b, " a_sin=", a_sin, " a_cos=", a_cos, " b_sin=", b_sin, " b_cos=", b_cos ); DEBUG_ECHOLNPGM(" cartes (X,Y) = "(cartes.x, ", ", cartes.y, ")"); //*/ } #endif #if ENABLED(MORGAN_SCARA) void scara_set_axis_is_at_home(const AxisEnum axis) { if (axis == Z_AXIS) current_position.z = Z_HOME_POS; else { // MORGAN_SCARA uses a Cartesian XY home position xyz_pos_t homeposition = { X_HOME_POS, Y_HOME_POS, Z_HOME_POS }; //DEBUG_ECHOLNPGM_P(PSTR("homeposition X"), homeposition.x, SP_Y_LBL, homeposition.y); delta = homeposition; forward_kinematics(delta.a, delta.b); current_position[axis] = cartes[axis]; //DEBUG_ECHOLNPGM_P(PSTR("Cartesian X"), current_position.x, SP_Y_LBL, current_position.y); update_software_endstops(axis); } } /** * Morgan SCARA Inverse Kinematics. Results are stored in 'delta'. * * See https://reprap.org/forum/read.php?185,283327 * * Maths and first version by QHARLEY. * Integrated into Marlin and slightly restructured by Joachim Cerny. */ void inverse_kinematics(const xyz_pos_t &raw) { float C2, S2, SK1, SK2, THETA, PSI; // Translate SCARA to standard XY with scaling factor const xy_pos_t spos = raw - scara_offset; const float H2 = HYPOT2(spos.x, spos.y); if (L1 == L2) C2 = H2 / L1_2_2 - 1; else C2 = (H2 - (L1_2 + L2_2)) / (2.0f * L1 * L2); LIMIT(C2, -1, 1); S2 = SQRT(1.0f - sq(C2)); // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End SK1 = L1 + L2 * C2; // Rotated Arm2 gives the distance from Arm1 to Arm2 SK2 = L2 * S2; // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow THETA = ATAN2(SK1, SK2) - ATAN2(spos.x, spos.y); // Angle of Arm2 PSI = ATAN2(S2, C2); delta.set(DEGREES(THETA), DEGREES(SUM_TERN(MORGAN_SCARA, PSI, THETA)), raw.z); /* DEBUG_POS("SCARA IK", raw); DEBUG_POS("SCARA IK", delta); DEBUG_ECHOLNPGM(" SCARA (x,y) ", sx, ",", sy, " C2=", C2, " S2=", S2, " Theta=", THETA, " Psi=", PSI); //*/ } #elif ENABLED(MP_SCARA) void scara_set_axis_is_at_home(const AxisEnum axis) { if (axis == Z_AXIS) current_position.z = Z_HOME_POS; else { // MP_SCARA uses arm angles for AB home position #ifndef SCARA_OFFSET_THETA1 #define SCARA_OFFSET_THETA1 12 // degrees #endif #ifndef SCARA_OFFSET_THETA2 #define SCARA_OFFSET_THETA2 131 // degrees #endif ab_float_t homeposition = { SCARA_OFFSET_THETA1, SCARA_OFFSET_THETA2 }; //DEBUG_ECHOLNPGM("homeposition A:", homeposition.a, " B:", homeposition.b); inverse_kinematics(homeposition); forward_kinematics(delta.a, delta.b); current_position[axis] = cartes[axis]; //DEBUG_ECHOLNPGM_P(PSTR("Cartesian X"), current_position.x, SP_Y_LBL, current_position.y); update_software_endstops(axis); } } void inverse_kinematics(const xyz_pos_t &raw) { const float x = raw.x, y = raw.y, c = HYPOT(x, y), THETA3 = ATAN2(y, x), THETA1 = THETA3 + ACOS((sq(c) + sq(L1) - sq(L2)) / (2.0f * c * L1)), THETA2 = THETA3 - ACOS((sq(c) + sq(L2) - sq(L1)) / (2.0f * c * L2)); delta.set(DEGREES(THETA1), DEGREES(THETA2), raw.z); /* DEBUG_POS("SCARA IK", raw); DEBUG_POS("SCARA IK", delta); SERIAL_ECHOLNPGM(" SCARA (x,y) ", x, ",", y," Theta1=", THETA1, " Theta2=", THETA2); //*/ } #elif ENABLED(AXEL_TPARA) static constexpr xyz_pos_t robot_offset = { TPARA_OFFSET_X, TPARA_OFFSET_Y, TPARA_OFFSET_Z }; void scara_set_axis_is_at_home(const AxisEnum axis) { if (axis == Z_AXIS) current_position.z = Z_HOME_POS; else { xyz_pos_t homeposition = { X_HOME_POS, Y_HOME_POS, Z_HOME_POS }; //DEBUG_ECHOLNPGM_P(PSTR("homeposition X"), homeposition.x, SP_Y_LBL, homeposition.y, SP_Z_LBL, homeposition.z); inverse_kinematics(homeposition); forward_kinematics(delta.a, delta.b, delta.c); current_position[axis] = cartes[axis]; //DEBUG_ECHOLNPGM_P(PSTR("Cartesian X"), current_position.x, SP_Y_LBL, current_position.y); update_software_endstops(axis); } } // Convert ABC inputs in degrees to XYZ outputs in mm void forward_kinematics(const_float_t a, const_float_t b, const_float_t c) { const float w = c - b, r = L1 * cos(RADIANS(b)) + L2 * sin(RADIANS(w - (90 - b))), x = r * cos(RADIANS(a)), y = r * sin(RADIANS(a)), rho2 = L1_2 + L2_2 - 2.0f * L1 * L2 * cos(RADIANS(w)); cartes = robot_offset + xyz_pos_t({ x, y, SQRT(rho2 - sq(x) - sq(y)) }); } // Home YZ together, then X (or all at once). Based on quick_home_xy & home_delta void home_TPARA() { // Init the current position of all carriages to 0,0,0 current_position.reset(); destination.reset(); sync_plan_position(); // Disable stealthChop if used. Enable diag1 pin on driver. #if ENABLED(SENSORLESS_HOMING) TERN_(X_SENSORLESS, sensorless_t stealth_states_x = start_sensorless_homing_per_axis(X_AXIS)); TERN_(Y_SENSORLESS, sensorless_t stealth_states_y = start_sensorless_homing_per_axis(Y_AXIS)); TERN_(Z_SENSORLESS, sensorless_t stealth_states_z = start_sensorless_homing_per_axis(Z_AXIS)); #endif //const int x_axis_home_dir = TOOL_X_HOME_DIR(active_extruder); //const xy_pos_t pos { max_length(X_AXIS) , max_length(Y_AXIS) }; //const float mlz = max_length(X_AXIS), // Move all carriages together linearly until an endstop is hit. //do_blocking_move_to_xy_z(pos, mlz, homing_feedrate(Z_AXIS)); current_position.set(0, 0, max_length(Z_AXIS)); line_to_current_position(homing_feedrate(Z_AXIS)); planner.synchronize(); // Re-enable stealthChop if used. Disable diag1 pin on driver. #if ENABLED(SENSORLESS_HOMING) TERN_(X_SENSORLESS, end_sensorless_homing_per_axis(X_AXIS, stealth_states_x)); TERN_(Y_SENSORLESS, end_sensorless_homing_per_axis(Y_AXIS, stealth_states_y)); TERN_(Z_SENSORLESS, end_sensorless_homing_per_axis(Z_AXIS, stealth_states_z)); #endif endstops.validate_homing_move(); // At least one motor has reached its endstop. // Now re-home each motor separately. homeaxis(A_AXIS); homeaxis(C_AXIS); homeaxis(B_AXIS); // Set all carriages to their home positions // Do this here all at once for Delta, because // XYZ isn't ABC. Applying this per-tower would // give the impression that they are the same. LOOP_NUM_AXES(i) set_axis_is_at_home((AxisEnum)i); sync_plan_position(); } void inverse_kinematics(const xyz_pos_t &raw) { const xyz_pos_t spos = raw - robot_offset; const float RXY = SQRT(HYPOT2(spos.x, spos.y)), RHO2 = NORMSQ(spos.x, spos.y, spos.z), //RHO = SQRT(RHO2), LSS = L1_2 + L2_2, LM = 2.0f * L1 * L2, CG = (LSS - RHO2) / LM, SG = SQRT(1 - POW(CG, 2)), // Method 2 K1 = L1 - L2 * CG, K2 = L2 * SG, // Angle of Body Joint THETA = ATAN2(spos.y, spos.x), // Angle of Elbow Joint //GAMMA = ACOS(CG), GAMMA = ATAN2(SG, CG), // Method 2 // Angle of Shoulder Joint, elevation angle measured from horizontal (r+) //PHI = asin(spos.z/RHO) + asin(L2 * sin(GAMMA) / RHO), PHI = ATAN2(spos.z, RXY) + ATAN2(K2, K1), // Method 2 // Elbow motor angle measured from horizontal, same frame as shoulder (r+) PSI = PHI + GAMMA; delta.set(DEGREES(THETA), DEGREES(PHI), DEGREES(PSI)); //SERIAL_ECHOLNPGM(" SCARA (x,y,z) ", spos.x , ",", spos.y, ",", spos.z, " Rho=", RHO, " Rho2=", RHO2, " Theta=", THETA, " Phi=", PHI, " Psi=", PSI, " Gamma=", GAMMA); } #endif void scara_report_positions() { SERIAL_ECHOLNPGM("SCARA Theta:", planner.get_axis_position_degrees(A_AXIS) #if ENABLED(AXEL_TPARA) , " Phi:", planner.get_axis_position_degrees(B_AXIS) , " Psi:", planner.get_axis_position_degrees(C_AXIS) #else , " Psi" TERN_(MORGAN_SCARA, "+Theta") ":", planner.get_axis_position_degrees(B_AXIS) #endif ); SERIAL_EOL(); } #endif // IS_SCARA
2301_81045437/Marlin
Marlin/src/module/scara.cpp
C++
agpl-3.0
10,380
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 /** * scara.h - SCARA-specific functions */ #include "../core/macros.h" extern float segments_per_second; #if ENABLED(AXEL_TPARA) float constexpr L1 = TPARA_LINKAGE_1, L2 = TPARA_LINKAGE_2, // Float constants for Robot arm calculations L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2, L2_2 = sq(float(L2)); void forward_kinematics(const_float_t a, const_float_t b, const_float_t c); void home_TPARA(); #else float constexpr L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2, // Float constants for SCARA calculations L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2, L2_2 = sq(float(L2)); void forward_kinematics(const_float_t a, const_float_t b); #endif void inverse_kinematics(const xyz_pos_t &raw); void scara_set_axis_is_at_home(const AxisEnum axis); void scara_report_positions();
2301_81045437/Marlin
Marlin/src/module/scara.h
C
agpl-3.0
1,740
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * module/servo.cpp */ #include "../inc/MarlinConfig.h" #if HAS_SERVOS #include "servo.h" hal_servo_t servo[NUM_SERVOS]; #if ENABLED(EDITABLE_SERVO_ANGLES) uint16_t servo_angles[NUM_SERVOS][2]; #endif void servo_init() { #if HAS_SERVO_0 servo[0].attach(SERVO0_PIN); servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position. #endif #if HAS_SERVO_1 servo[1].attach(SERVO1_PIN); servo[1].detach(); #endif #if HAS_SERVO_2 servo[2].attach(SERVO2_PIN); servo[2].detach(); #endif #if HAS_SERVO_3 servo[3].attach(SERVO3_PIN); servo[3].detach(); #endif #if HAS_SERVO_4 servo[4].attach(SERVO4_PIN); servo[4].detach(); #endif #if HAS_SERVO_5 servo[5].attach(SERVO5_PIN); servo[5].detach(); #endif } #endif // HAS_SERVOS
2301_81045437/Marlin
Marlin/src/module/servo.cpp
C++
agpl-3.0
1,706
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 /** * module/servo.h */ #include "../inc/MarlinConfig.h" #include "../HAL/shared/servo.h" #if HAS_SERVO_ANGLES #if ENABLED(SWITCHING_EXTRUDER) // Switching extruder can have 2 or 4 angles #if EXTRUDERS > 3 #define REQ_ANGLES 4 #else #define REQ_ANGLES 2 #endif constexpr uint16_t sase[] = SWITCHING_EXTRUDER_SERVO_ANGLES; static_assert(COUNT(sase) == REQ_ANGLES, "SWITCHING_EXTRUDER_SERVO_ANGLES needs " STRINGIFY(REQ_ANGLES) " angles."); #else constexpr uint16_t sase[4] = { 0 }; #endif #if ENABLED(SWITCHING_NOZZLE) #if SWITCHING_NOZZLE_TWO_SERVOS constexpr uint16_t sasn[][2] = SWITCHING_NOZZLE_SERVO_ANGLES; static_assert(COUNT(sasn) == 2, "SWITCHING_NOZZLE_SERVO_ANGLES (with SWITCHING_NOZZLE_E1_SERVO_NR) needs 2 sets of angles: { { lower, raise }, { lower, raise } }."); #else constexpr uint16_t sasn[] = SWITCHING_NOZZLE_SERVO_ANGLES; static_assert(COUNT(sasn) == 2, "SWITCHING_NOZZLE_SERVO_ANGLES needs two angles: { E0, E1 }."); #endif #else constexpr uint16_t sasn[2] = { 0 }; #endif #ifdef Z_PROBE_SERVO_NR #if ENABLED(BLTOUCH) #include "../feature/bltouch.h" #undef Z_SERVO_ANGLES #define Z_SERVO_ANGLES { BLTOUCH_DEPLOY, BLTOUCH_STOW } #endif constexpr uint16_t sazp[] = Z_SERVO_ANGLES; static_assert(COUNT(sazp) == 2, "Z_SERVO_ANGLES needs 2 angles."); #else constexpr uint16_t sazp[2] = { 0 }; #endif #ifndef SWITCHING_EXTRUDER_SERVO_NR #define SWITCHING_EXTRUDER_SERVO_NR -1 #endif #ifndef SWITCHING_EXTRUDER_E23_SERVO_NR #define SWITCHING_EXTRUDER_E23_SERVO_NR -1 #endif #ifndef SWITCHING_NOZZLE_SERVO_NR #define SWITCHING_NOZZLE_SERVO_NR -1 #endif #ifndef Z_PROBE_SERVO_NR #define Z_PROBE_SERVO_NR -1 #endif #define SASN(J,I) TERN(SWITCHING_NOZZLE_TWO_SERVOS, sasn[J][I], sasn[I]) #define ASRC(N,I) ( \ N == SWITCHING_EXTRUDER_SERVO_NR ? sase[I] \ : N == SWITCHING_EXTRUDER_E23_SERVO_NR ? sase[I+2] \ : N == SWITCHING_NOZZLE_SERVO_NR ? SASN(0,I) \ TERN_(SWITCHING_NOZZLE_TWO_SERVOS, : N == SWITCHING_NOZZLE_E1_SERVO_NR ? SASN(1,I)) \ : N == Z_PROBE_SERVO_NR ? sazp[I] \ : 0 ) #if ENABLED(EDITABLE_SERVO_ANGLES) extern uint16_t servo_angles[NUM_SERVOS][2]; #define CONST_SERVO_ANGLES base_servo_angles #else #define CONST_SERVO_ANGLES servo_angles #endif constexpr uint16_t CONST_SERVO_ANGLES [NUM_SERVOS][2] = { { ASRC(0,0), ASRC(0,1) } #if NUM_SERVOS > 1 , { ASRC(1,0), ASRC(1,1) } #if NUM_SERVOS > 2 , { ASRC(2,0), ASRC(2,1) } #if NUM_SERVOS > 3 , { ASRC(3,0), ASRC(3,1) } #if NUM_SERVOS > 4 , { ASRC(4,0), ASRC(4,1) } #if NUM_SERVOS > 5 , { ASRC(5,0), ASRC(5,1) } #endif #endif #endif #endif #endif }; #if HAS_Z_SERVO_PROBE #define DEPLOY_Z_SERVO() servo[Z_PROBE_SERVO_NR].move(servo_angles[Z_PROBE_SERVO_NR][0]) #define STOW_Z_SERVO() servo[Z_PROBE_SERVO_NR].move(servo_angles[Z_PROBE_SERVO_NR][1]) #endif #endif // HAS_SERVO_ANGLES extern hal_servo_t servo[NUM_SERVOS]; void servo_init();
2301_81045437/Marlin
Marlin/src/module/servo.h
C++
agpl-3.0
4,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/>. * */ /** * settings.cpp * * Settings and EEPROM storage * * IMPORTANT: Whenever there are changes made to the variables stored in EEPROM * in the functions below, also increment the version number. This makes sure that * the default values are used whenever there is a change to the data, to prevent * wrong data being written to the variables. * * ALSO: Variables in the Store and Retrieve sections must be in the same order. * If a feature is disabled, some data must still be written that, when read, * either sets a Sane Default, or results in No Change to the existing value. */ // Change EEPROM version if the structure changes #define EEPROM_VERSION "V90" #define EEPROM_OFFSET 100 // Check the integrity of data offsets. // Can be disabled for production build. //#define DEBUG_EEPROM_READWRITE //#define DEBUG_EEPROM_OBSERVE #include "settings.h" #include "endstops.h" #include "planner.h" #include "stepper.h" #include "temperature.h" #include "../lcd/marlinui.h" #include "../libs/vector_3.h" // for matrix_3x3 #include "../gcode/gcode.h" #include "../MarlinCore.h" #if ANY(EEPROM_SETTINGS, SD_FIRMWARE_UPDATE) #include "../HAL/shared/eeprom_api.h" #endif #if HAS_BED_PROBE #include "probe.h" #endif #if HAS_LEVELING #include "../feature/bedlevel/bedlevel.h" #if ENABLED(X_AXIS_TWIST_COMPENSATION) #include "../feature/x_twist.h" #endif #endif #if ENABLED(Z_STEPPER_AUTO_ALIGN) #include "../feature/z_stepper_align.h" #endif #if ENABLED(DWIN_LCD_PROUI) #include "../lcd/e3v2/proui/dwin.h" #include "../lcd/e3v2/proui/bedlevel_tools.h" #endif #if ENABLED(EXTENSIBLE_UI) #include "../lcd/extui/ui_api.h" #elif ENABLED(DWIN_CREALITY_LCD_JYERSUI) #include "../lcd/e3v2/jyersui/dwin.h" #endif #if ENABLED(HOST_PROMPT_SUPPORT) #include "../feature/host_actions.h" #endif #if HAS_SERVOS #include "servo.h" #endif #include "../feature/fwretract.h" #if ENABLED(POWER_LOSS_RECOVERY) #include "../feature/powerloss.h" #endif #if HAS_POWER_MONITOR #include "../feature/power_monitor.h" #endif #include "../feature/pause.h" #if ENABLED(BACKLASH_COMPENSATION) #include "../feature/backlash.h" #endif #if ENABLED(FT_MOTION) #include "../module/ft_motion.h" #endif #if HAS_FILAMENT_SENSOR #include "../feature/runout.h" #ifndef FIL_RUNOUT_ENABLED_DEFAULT #define FIL_RUNOUT_ENABLED_DEFAULT true #endif #endif #if ENABLED(ADVANCE_K_EXTRA) extern float other_extruder_advance_K[DISTINCT_E]; #endif #if HAS_MULTI_EXTRUDER #include "tool_change.h" void M217_report(const bool eeprom); #endif #if ENABLED(BLTOUCH) #include "../feature/bltouch.h" #endif #if HAS_TRINAMIC_CONFIG #include "stepper/indirection.h" #include "../feature/tmc_util.h" #endif #if HAS_PTC #include "../feature/probe_temp_comp.h" #endif #include "../feature/controllerfan.h" #if ENABLED(CASE_LIGHT_ENABLE) #include "../feature/caselight.h" #endif #if ENABLED(PASSWORD_FEATURE) #include "../feature/password/password.h" #endif #if ENABLED(TOUCH_SCREEN_CALIBRATION) #include "../lcd/tft_io/touch_calibration.h" #endif #if HAS_ETHERNET #include "../feature/ethernet.h" #endif #if ENABLED(SOUND_MENU_ITEM) #include "../libs/buzzer.h" #endif #if HAS_FANCHECK #include "../feature/fancheck.h" #endif #if DGUS_LCD_UI_MKS #include "../lcd/extui/dgus/DGUSScreenHandler.h" #include "../lcd/extui/dgus/DGUSDisplayDef.h" #endif #if ENABLED(HOTEND_IDLE_TIMEOUT) #include "../feature/hotend_idle.h" #endif #pragma pack(push, 1) // No padding between variables #if HAS_ETHERNET void ETH0_report(); void MAC_report(); #endif #define _EN_ITEM(N) , E##N #define _EN1_ITEM(N) , E##N:1 typedef struct { uint16_t MAIN_AXIS_NAMES_ X2, Y2, Z2, Z3, Z4 REPEAT(E_STEPPERS, _EN_ITEM); } per_stepper_uint16_t; typedef struct { uint32_t MAIN_AXIS_NAMES_ X2, Y2, Z2, Z3, Z4 REPEAT(E_STEPPERS, _EN_ITEM); } per_stepper_uint32_t; typedef struct { int16_t MAIN_AXIS_NAMES_ X2, Y2, Z2, Z3, Z4; } mot_stepper_int16_t; typedef struct { bool NUM_AXIS_LIST_(X:1, Y:1, Z:1, I:1, J:1, K:1, U:1, V:1, W:1) X2:1, Y2:1, Z2:1, Z3:1, Z4:1 REPEAT(E_STEPPERS, _EN1_ITEM); } per_stepper_bool_t; #undef _EN_ITEM // Limit an index to an array size #define ALIM(I,ARR) _MIN(I, (signed)COUNT(ARR) - 1) // Defaults for reset / fill in on load static const uint32_t _DMA[] PROGMEM = DEFAULT_MAX_ACCELERATION; static const feedRate_t _DMF[] PROGMEM = DEFAULT_MAX_FEEDRATE; #if ENABLED(EDITABLE_STEPS_PER_UNIT) static const float _DASU[] PROGMEM = DEFAULT_AXIS_STEPS_PER_UNIT; #endif /** * Current EEPROM Layout * * Keep this data structure up to date so * EEPROM size is known at compile time! */ typedef struct SettingsDataStruct { char version[4]; // Vnn\0 #if ENABLED(EEPROM_INIT_NOW) uint32_t build_hash; // Unique build hash #endif uint16_t crc; // Data Checksum for validation uint16_t data_size; // Data Size for validation // // DISTINCT_E_FACTORS // uint8_t e_factors; // DISTINCT_AXES - NUM_AXES // // Planner settings // planner_settings_t planner_settings; xyze_float_t planner_max_jerk; // M205 XYZE planner.max_jerk float planner_junction_deviation_mm; // M205 J planner.junction_deviation_mm // // Home Offset // #if NUM_AXES xyz_pos_t home_offset; // M206 XYZ / M665 TPZ #endif // // Hotend Offset // #if HAS_HOTEND_OFFSET xyz_pos_t hotend_offset[HOTENDS - 1]; // M218 XYZ #endif // // FILAMENT_RUNOUT_SENSOR // bool runout_sensor_enabled; // M412 S float runout_distance_mm; // M412 D // // ENABLE_LEVELING_FADE_HEIGHT // float planner_z_fade_height; // M420 Zn planner.z_fade_height // // AUTOTEMP // #if ENABLED(AUTOTEMP) celsius_t planner_autotemp_max, planner_autotemp_min; float planner_autotemp_factor; #endif // // MESH_BED_LEVELING // float mbl_z_offset; // bedlevel.z_offset uint8_t mesh_num_x, mesh_num_y; // GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y uint16_t mesh_check; // Hash to check against X/Y float mbl_z_values[TERN(MESH_BED_LEVELING, GRID_MAX_POINTS_X, 3)] // bedlevel.z_values [TERN(MESH_BED_LEVELING, GRID_MAX_POINTS_Y, 3)]; // // HAS_BED_PROBE // #if NUM_AXES xyz_pos_t probe_offset; // M851 X Y Z #endif // // ABL_PLANAR // matrix_3x3 planner_bed_level_matrix; // planner.bed_level_matrix // // AUTO_BED_LEVELING_BILINEAR // uint8_t grid_max_x, grid_max_y; // GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y uint16_t grid_check; // Hash to check against X/Y xy_pos_t bilinear_grid_spacing, bilinear_start; // G29 L F #if ENABLED(AUTO_BED_LEVELING_BILINEAR) bed_mesh_t z_values; // G29 #else float z_values[3][3]; #endif // // X_AXIS_TWIST_COMPENSATION // #if ENABLED(X_AXIS_TWIST_COMPENSATION) float xatc_spacing; // M423 X Z float xatc_start; xatc_array_t xatc_z_offset; #endif // // AUTO_BED_LEVELING_UBL // bool planner_leveling_active; // M420 S planner.leveling_active int8_t ubl_storage_slot; // bedlevel.storage_slot // // SERVO_ANGLES // #if HAS_SERVO_ANGLES uint16_t servo_angles[NUM_SERVOS][2]; // M281 P L U #endif // // Temperature first layer compensation values // #if HAS_PTC #if ENABLED(PTC_PROBE) int16_t z_offsets_probe[COUNT(ptc.z_offsets_probe)]; // M871 P I V #endif #if ENABLED(PTC_BED) int16_t z_offsets_bed[COUNT(ptc.z_offsets_bed)]; // M871 B I V #endif #if ENABLED(PTC_HOTEND) int16_t z_offsets_hotend[COUNT(ptc.z_offsets_hotend)]; // M871 E I V #endif #endif // // BLTOUCH // bool bltouch_od_5v_mode; #if HAS_BLTOUCH_HS_MODE bool bltouch_high_speed_mode; // M401 S #endif // // Kinematic Settings (Delta, SCARA, TPARA, Polargraph...) // #if IS_KINEMATIC float segments_per_second; // M665 S #if ENABLED(DELTA) float delta_height; // M666 H abc_float_t delta_endstop_adj; // M666 X Y Z float delta_radius, // M665 R delta_diagonal_rod; // M665 L abc_float_t delta_tower_angle_trim, // M665 X Y Z delta_diagonal_rod_trim; // M665 A B C #elif ENABLED(POLARGRAPH) xy_pos_t draw_area_min, draw_area_max; // M665 L R T B float polargraph_max_belt_len; // M665 H #endif #endif // // Extra Endstops offsets // #if HAS_EXTRA_ENDSTOPS float x2_endstop_adj, // M666 X y2_endstop_adj, // M666 Y z2_endstop_adj, // M666 (S2) Z z3_endstop_adj, // M666 (S3) Z z4_endstop_adj; // M666 (S4) Z #endif // // Z_STEPPER_AUTO_ALIGN, HAS_Z_STEPPER_ALIGN_STEPPER_XY // #if ENABLED(Z_STEPPER_AUTO_ALIGN) xy_pos_t z_stepper_align_xy[NUM_Z_STEPPERS]; // M422 S X Y #if HAS_Z_STEPPER_ALIGN_STEPPER_XY xy_pos_t z_stepper_align_stepper_xy[NUM_Z_STEPPERS]; // M422 W X Y #endif #endif // // Material Presets // #if HAS_PREHEAT preheat_t ui_material_preset[PREHEAT_COUNT]; // M145 S0 H B F #endif // // PIDTEMP // raw_pidcf_t hotendPID[HOTENDS]; // M301 En PIDCF / M303 En U int16_t lpq_len; // M301 L // // PIDTEMPBED // raw_pid_t bedPID; // M304 PID / M303 E-1 U // // PIDTEMPCHAMBER // raw_pid_t chamberPID; // M309 PID / M303 E-2 U // // User-defined Thermistors // #if HAS_USER_THERMISTORS user_thermistor_t user_thermistor[USER_THERMISTORS]; // M305 P0 R4700 T100000 B3950 #endif // // Power monitor // uint8_t power_monitor_flags; // M430 I V W // // HAS_LCD_CONTRAST // uint8_t lcd_contrast; // M250 C // // HAS_LCD_BRIGHTNESS // uint8_t lcd_brightness; // M256 B // // Display Sleep // #if ENABLED(EDITABLE_DISPLAY_TIMEOUT) #if HAS_BACKLIGHT_TIMEOUT uint8_t backlight_timeout_minutes; // M255 S #elif HAS_DISPLAY_SLEEP uint8_t sleep_timeout_minutes; // M255 S #endif #endif // // Controller fan settings // controllerFan_settings_t controllerFan_settings; // M710 // // POWER_LOSS_RECOVERY // bool recovery_enabled; // M413 S celsius_t bed_temp_threshold; // M413 B // // FWRETRACT // fwretract_settings_t fwretract_settings; // M207 S F Z W, M208 S F W R bool autoretract_enabled; // M209 S // // !NO_VOLUMETRIC // bool parser_volumetric_enabled; // M200 S parser.volumetric_enabled float planner_filament_size[EXTRUDERS]; // M200 T D planner.filament_size[] float planner_volumetric_extruder_limit[EXTRUDERS]; // M200 T L planner.volumetric_extruder_limit[] // // HAS_TRINAMIC_CONFIG // per_stepper_uint16_t tmc_stepper_current; // M906 X Y Z... per_stepper_uint32_t tmc_hybrid_threshold; // M913 X Y Z... mot_stepper_int16_t tmc_sgt; // M914 X Y Z... per_stepper_bool_t tmc_stealth_enabled; // M569 X Y Z... // // LIN_ADVANCE // float planner_extruder_advance_K[DISTINCT_E]; // M900 K planner.extruder_advance_K // // HAS_MOTOR_CURRENT_PWM // #ifndef MOTOR_CURRENT_COUNT #if HAS_MOTOR_CURRENT_PWM #define MOTOR_CURRENT_COUNT 3 #elif HAS_MOTOR_CURRENT_DAC #define MOTOR_CURRENT_COUNT LOGICAL_AXES #elif HAS_MOTOR_CURRENT_I2C #define MOTOR_CURRENT_COUNT DIGIPOT_I2C_NUM_CHANNELS #else // HAS_MOTOR_CURRENT_SPI #define MOTOR_CURRENT_COUNT DISTINCT_AXES #endif #endif uint32_t motor_current_setting[MOTOR_CURRENT_COUNT]; // M907 X Z E ... // // Adaptive Step Smoothing state // #if ENABLED(ADAPTIVE_STEP_SMOOTHING_TOGGLE) bool adaptive_step_smoothing_enabled; // G-code pending #endif // // CNC_COORDINATE_SYSTEMS // #if NUM_AXES xyz_pos_t coordinate_system[MAX_COORDINATE_SYSTEMS]; // G54-G59.3 #endif // // SKEW_CORRECTION // #if ENABLED(SKEW_CORRECTION) skew_factor_t planner_skew_factor; // M852 I J K #endif // // ADVANCED_PAUSE_FEATURE // #if ENABLED(CONFIGURE_FILAMENT_CHANGE) fil_change_settings_t fc_settings[EXTRUDERS]; // M603 T U L #endif // // Tool-change settings // #if HAS_MULTI_EXTRUDER toolchange_settings_t toolchange_settings; // M217 S P R #endif // // BACKLASH_COMPENSATION // #if NUM_AXES xyz_float_t backlash_distance_mm; // M425 X Y Z uint8_t backlash_correction; // M425 F float backlash_smoothing_mm; // M425 S #endif // // EXTENSIBLE_UI // #if ENABLED(EXTENSIBLE_UI) uint8_t extui_data[ExtUI::eeprom_data_size]; #endif // // Ender-3 V2 DWIN // #if ENABLED(DWIN_CREALITY_LCD_JYERSUI) uint8_t dwin_settings[jyersDWIN.eeprom_data_size]; #endif // // CASELIGHT_USES_BRIGHTNESS // #if CASELIGHT_USES_BRIGHTNESS uint8_t caselight_brightness; // M355 P #endif // // PASSWORD_FEATURE // #if ENABLED(PASSWORD_FEATURE) bool password_is_set; uint32_t password_value; #endif // // TOUCH_SCREEN_CALIBRATION // #if ENABLED(TOUCH_SCREEN_CALIBRATION) touch_calibration_t touch_calibration_data; #endif // Ethernet settings #if HAS_ETHERNET bool ethernet_hardware_enabled; // M552 S uint32_t ethernet_ip, // M552 P ethernet_dns, ethernet_gateway, // M553 P ethernet_subnet; // M554 P #endif // // Buzzer enable/disable // #if ENABLED(SOUND_MENU_ITEM) bool sound_on; #endif // // Fan tachometer check // #if HAS_FANCHECK bool fan_check_enabled; #endif // // MKS UI controller // #if DGUS_LCD_UI_MKS MKS_Language mks_language_index; // Display Language xy_int_t mks_corner_offsets[5]; // Bed Tramming xyz_int_t mks_park_pos; // Custom Parking (without NOZZLE_PARK) celsius_t mks_min_extrusion_temp; // Min E Temp (shadow M302 value) #endif #if HAS_MULTI_LANGUAGE uint8_t ui_language; // M414 S #endif // // Model predictive control // #if ENABLED(MPCTEMP) MPC_t mpc_constants[HOTENDS]; // M306 #endif // // Fixed-Time Motion // #if ENABLED(FT_MOTION) ft_config_t ftMotion_cfg; // M493 #endif // // Input Shaping // #if ENABLED(INPUT_SHAPING_X) float shaping_x_frequency, // M593 X F shaping_x_zeta; // M593 X D #endif #if ENABLED(INPUT_SHAPING_Y) float shaping_y_frequency, // M593 Y F shaping_y_zeta; // M593 Y D #endif // // HOTEND_IDLE_TIMEOUT // #if ENABLED(HOTEND_IDLE_TIMEOUT) hotend_idle_settings_t hotend_idle_config; // M86 S T E B #endif // // Nonlinear Extrusion // #if ENABLED(NONLINEAR_EXTRUSION) ne_coeff_t stepper_ne; // M592 A B C #endif } SettingsData; //static_assert(sizeof(SettingsData) <= MARLIN_EEPROM_SIZE, "EEPROM too small to contain SettingsData!"); MarlinSettings settings; uint16_t MarlinSettings::datasize() { return sizeof(SettingsData); } /** * Post-process after Retrieve or Reset */ #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) float new_z_fade_height; #endif void MarlinSettings::postprocess() { xyze_pos_t oldpos = current_position; // steps per s2 needs to be updated to agree with units per s2 planner.refresh_acceleration_rates(); // Make sure delta kinematics are updated before refreshing the // planner position so the stepper counts will be set correctly. TERN_(DELTA, recalc_delta_settings()); TERN_(PIDTEMP, thermalManager.updatePID()); #if DISABLED(NO_VOLUMETRICS) planner.calculate_volumetric_multipliers(); #elif EXTRUDERS for (uint8_t i = COUNT(planner.e_factor); i--;) planner.refresh_e_factor(i); #endif // Software endstops depend on home_offset LOOP_NUM_AXES(i) update_software_endstops((AxisEnum)i); TERN_(ENABLE_LEVELING_FADE_HEIGHT, set_z_fade_height(new_z_fade_height, false)); // false = no report TERN_(AUTO_BED_LEVELING_BILINEAR, bedlevel.refresh_bed_level()); TERN_(HAS_MOTOR_CURRENT_PWM, stepper.refresh_motor_power()); TERN_(FWRETRACT, fwretract.refresh_autoretract()); TERN_(HAS_LINEAR_E_JERK, planner.recalculate_max_e_jerk()); TERN_(CASELIGHT_USES_BRIGHTNESS, caselight.update_brightness()); TERN_(EXTENSIBLE_UI, ExtUI::onPostprocessSettings()); // Refresh mm_per_step with the reciprocal of axis_steps_per_mm // and init stepper.count[], planner.position[] with current_position planner.refresh_positioning(); // Various factors can change the current position if (oldpos != current_position) report_current_position(); // Moved as last update due to interference with NeoPixel init TERN_(HAS_LCD_CONTRAST, ui.refresh_contrast()); TERN_(HAS_LCD_BRIGHTNESS, ui.refresh_brightness()); TERN_(HAS_BACKLIGHT_TIMEOUT, ui.refresh_backlight_timeout()); TERN_(HAS_DISPLAY_SLEEP, ui.refresh_screen_timeout()); } #if ALL(PRINTCOUNTER, EEPROM_SETTINGS) #include "printcounter.h" static_assert( !WITHIN(STATS_EEPROM_ADDRESS, EEPROM_OFFSET, EEPROM_OFFSET + sizeof(SettingsData)) && !WITHIN(STATS_EEPROM_ADDRESS + sizeof(printStatistics), EEPROM_OFFSET, EEPROM_OFFSET + sizeof(SettingsData)), "STATS_EEPROM_ADDRESS collides with EEPROM settings storage." ); #endif #if ENABLED(SD_FIRMWARE_UPDATE) #if ENABLED(EEPROM_SETTINGS) static_assert( !WITHIN(SD_FIRMWARE_UPDATE_EEPROM_ADDR, EEPROM_OFFSET, EEPROM_OFFSET + sizeof(SettingsData)), "SD_FIRMWARE_UPDATE_EEPROM_ADDR collides with EEPROM settings storage." ); #endif bool MarlinSettings::sd_update_status() { uint8_t val; int pos = SD_FIRMWARE_UPDATE_EEPROM_ADDR; persistentStore.read_data(pos, &val); return (val == SD_FIRMWARE_UPDATE_ACTIVE_VALUE); } bool MarlinSettings::set_sd_update_status(const bool enable) { if (enable != sd_update_status()) persistentStore.write_data( SD_FIRMWARE_UPDATE_EEPROM_ADDR, enable ? SD_FIRMWARE_UPDATE_ACTIVE_VALUE : SD_FIRMWARE_UPDATE_INACTIVE_VALUE ); return true; } #endif // SD_FIRMWARE_UPDATE #ifdef ARCHIM2_SPI_FLASH_EEPROM_BACKUP_SIZE static_assert(EEPROM_OFFSET + sizeof(SettingsData) < ARCHIM2_SPI_FLASH_EEPROM_BACKUP_SIZE, "ARCHIM2_SPI_FLASH_EEPROM_BACKUP_SIZE is insufficient to capture all EEPROM data."); #endif // // This file simply uses the DEBUG_ECHO macros to implement EEPROM_CHITCHAT. // For deeper debugging of EEPROM issues enable DEBUG_EEPROM_READWRITE. // #define DEBUG_OUT ANY(EEPROM_CHITCHAT, DEBUG_LEVELING_FEATURE) #include "../core/debug_out.h" #if ALL(EEPROM_CHITCHAT, HOST_PROMPT_SUPPORT) #define HOST_EEPROM_CHITCHAT 1 #endif #if ENABLED(EEPROM_SETTINGS) #define EEPROM_ASSERT(TST,ERR) do{ if (!(TST)) { SERIAL_WARN_MSG(ERR); eeprom_error = ERR_EEPROM_SIZE; } }while(0) #define TWO_BYTE_HASH(A,B) uint16_t((uint16_t(A ^ 0xC3) << 4) ^ (uint16_t(B ^ 0xC3) << 12)) #if ENABLED(DEBUG_EEPROM_READWRITE) #define _FIELD_TEST(FIELD) \ SERIAL_ECHOLNPGM("Field: " STRINGIFY(FIELD)); \ EEPROM_ASSERT( \ eeprom_error || eeprom_index == offsetof(SettingsData, FIELD) + EEPROM_OFFSET, \ "Field " STRINGIFY(FIELD) " mismatch." \ ) #else #define _FIELD_TEST(FIELD) NOOP #endif #if ENABLED(DEBUG_EEPROM_OBSERVE) #define EEPROM_READ(V...) do{ SERIAL_ECHOLNPGM("READ: ", F(STRINGIFY(FIRST(V)))); EEPROM_READ_(V); }while(0) #define EEPROM_READ_ALWAYS(V...) do{ SERIAL_ECHOLNPGM("READ: ", F(STRINGIFY(FIRST(V)))); EEPROM_READ_ALWAYS_(V); }while(0) #else #define EEPROM_READ(V...) EEPROM_READ_(V) #define EEPROM_READ_ALWAYS(V...) EEPROM_READ_ALWAYS_(V) #endif const char version[4] = EEPROM_VERSION; #if ENABLED(EEPROM_INIT_NOW) constexpr uint32_t strhash32(const char *s, const uint32_t h=0) { return *s ? strhash32(s + 1, ((h + *s) << (*s & 3)) ^ *s) : h; } constexpr uint32_t build_hash = strhash32(__DATE__ __TIME__); #endif bool MarlinSettings::validating; int MarlinSettings::eeprom_index; uint16_t MarlinSettings::working_crc; EEPROM_Error MarlinSettings::size_error(const uint16_t size) { if (size != datasize()) { DEBUG_WARN_MSG("EEPROM datasize error." #if ENABLED(MARLIN_DEV_MODE) " (Actual:", size, " Expected:", datasize(), ")" #endif ); return ERR_EEPROM_SIZE; } return ERR_EEPROM_NOERR; } /** * M500 - Store Configuration */ bool MarlinSettings::save() { float dummyf = 0; MString<3> ver(F("ERR")); if (!EEPROM_START(EEPROM_OFFSET)) return false; EEPROM_Error eeprom_error = ERR_EEPROM_NOERR; // Write or Skip version. (Flash doesn't allow rewrite without erase.) TERN(FLASH_EEPROM_EMULATION, EEPROM_SKIP, EEPROM_WRITE)(ver); #if ENABLED(EEPROM_INIT_NOW) EEPROM_SKIP(build_hash); // Skip the hash slot which will be written later #endif EEPROM_SKIP(working_crc); // Skip the checksum slot // // Clear after skipping CRC and before writing the CRC'ed data // working_crc = 0; // Write the size of the data structure for use in validation const uint16_t data_size = datasize(); EEPROM_WRITE(data_size); const uint8_t e_factors = DISTINCT_AXES - (NUM_AXES); _FIELD_TEST(e_factors); EEPROM_WRITE(e_factors); // // Planner Motion // { EEPROM_WRITE(planner.settings); #if ENABLED(CLASSIC_JERK) EEPROM_WRITE(planner.max_jerk); #if HAS_LINEAR_E_JERK dummyf = float(DEFAULT_EJERK); EEPROM_WRITE(dummyf); #endif #else const xyze_pos_t planner_max_jerk = LOGICAL_AXIS_ARRAY(5, 10, 10, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4); EEPROM_WRITE(planner_max_jerk); #endif TERN_(CLASSIC_JERK, dummyf = 0.02f); EEPROM_WRITE(TERN(CLASSIC_JERK, dummyf, planner.junction_deviation_mm)); } // // Home Offset // #if NUM_AXES { _FIELD_TEST(home_offset); #if HAS_SCARA_OFFSET EEPROM_WRITE(scara_home_offset); #else #if !HAS_HOME_OFFSET const xyz_pos_t home_offset{0}; #endif EEPROM_WRITE(home_offset); #endif } #endif // NUM_AXES // // Hotend Offsets, if any // { #if HAS_HOTEND_OFFSET // Skip hotend 0 which must be 0 for (uint8_t e = 1; e < HOTENDS; ++e) EEPROM_WRITE(hotend_offset[e]); #endif } // // Filament Runout Sensor // { #if HAS_FILAMENT_SENSOR const bool &runout_sensor_enabled = runout.enabled; #else constexpr int8_t runout_sensor_enabled = -1; #endif _FIELD_TEST(runout_sensor_enabled); EEPROM_WRITE(runout_sensor_enabled); #if HAS_FILAMENT_RUNOUT_DISTANCE const float &runout_distance_mm = runout.runout_distance(); #else constexpr float runout_distance_mm = 0; #endif EEPROM_WRITE(runout_distance_mm); } // // Global Leveling // { const float zfh = TERN(ENABLE_LEVELING_FADE_HEIGHT, planner.z_fade_height, (DEFAULT_LEVELING_FADE_HEIGHT)); EEPROM_WRITE(zfh); } // // AUTOTEMP // #if ENABLED(AUTOTEMP) _FIELD_TEST(planner_autotemp_max); EEPROM_WRITE(planner.autotemp.max); EEPROM_WRITE(planner.autotemp.min); EEPROM_WRITE(planner.autotemp.factor); #endif // // Mesh Bed Leveling // { #if ENABLED(MESH_BED_LEVELING) static_assert( sizeof(bedlevel.z_values) == GRID_MAX_POINTS * sizeof(bedlevel.z_values[0][0]), "MBL Z array is the wrong size." ); #else dummyf = 0; #endif const uint8_t mesh_num_x = TERN(MESH_BED_LEVELING, GRID_MAX_POINTS_X, 3), mesh_num_y = TERN(MESH_BED_LEVELING, GRID_MAX_POINTS_Y, 3); EEPROM_WRITE(TERN(MESH_BED_LEVELING, bedlevel.z_offset, dummyf)); EEPROM_WRITE(mesh_num_x); EEPROM_WRITE(mesh_num_y); // Check value for the X/Y values const uint16_t mesh_check = TWO_BYTE_HASH(mesh_num_x, mesh_num_y); EEPROM_WRITE(mesh_check); #if ENABLED(MESH_BED_LEVELING) EEPROM_WRITE(bedlevel.z_values); #else for (uint8_t q = mesh_num_x * mesh_num_y; q--;) EEPROM_WRITE(dummyf); #endif } // // Probe XYZ Offsets // #if NUM_AXES { _FIELD_TEST(probe_offset); #if HAS_BED_PROBE const xyz_pos_t &zpo = probe.offset; #else constexpr xyz_pos_t zpo{0}; #endif EEPROM_WRITE(zpo); } #endif // // Planar Bed Leveling matrix // { #if ABL_PLANAR EEPROM_WRITE(planner.bed_level_matrix); #else dummyf = 0; for (uint8_t q = 9; q--;) EEPROM_WRITE(dummyf); #endif } // // Bilinear Auto Bed Leveling // { #if ENABLED(AUTO_BED_LEVELING_BILINEAR) static_assert( sizeof(bedlevel.z_values) == GRID_MAX_POINTS * sizeof(bedlevel.z_values[0][0]), "Bilinear Z array is the wrong size." ); #endif const uint8_t grid_max_x = TERN(AUTO_BED_LEVELING_BILINEAR, GRID_MAX_POINTS_X, 3), grid_max_y = TERN(AUTO_BED_LEVELING_BILINEAR, GRID_MAX_POINTS_Y, 3); EEPROM_WRITE(grid_max_x); EEPROM_WRITE(grid_max_y); // Check value for the X/Y values const uint16_t grid_check = TWO_BYTE_HASH(grid_max_x, grid_max_y); EEPROM_WRITE(grid_check); #if ENABLED(AUTO_BED_LEVELING_BILINEAR) EEPROM_WRITE(bedlevel.grid_spacing); EEPROM_WRITE(bedlevel.grid_start); #else const xy_pos_t bilinear_grid_spacing{0}, bilinear_start{0}; EEPROM_WRITE(bilinear_grid_spacing); EEPROM_WRITE(bilinear_start); #endif #if ENABLED(AUTO_BED_LEVELING_BILINEAR) EEPROM_WRITE(bedlevel.z_values); // 9-256 floats #else dummyf = 0; for (uint16_t q = grid_max_x * grid_max_y; q--;) EEPROM_WRITE(dummyf); #endif } // // X Axis Twist Compensation // #if ENABLED(X_AXIS_TWIST_COMPENSATION) _FIELD_TEST(xatc_spacing); EEPROM_WRITE(xatc.spacing); EEPROM_WRITE(xatc.start); EEPROM_WRITE(xatc.z_offset); #endif // // Unified Bed Leveling // { _FIELD_TEST(planner_leveling_active); const bool ubl_active = TERN(AUTO_BED_LEVELING_UBL, planner.leveling_active, false); const int8_t storage_slot = TERN(AUTO_BED_LEVELING_UBL, bedlevel.storage_slot, -1); EEPROM_WRITE(ubl_active); EEPROM_WRITE(storage_slot); } // // Servo Angles // #if HAS_SERVO_ANGLES { _FIELD_TEST(servo_angles); EEPROM_WRITE(servo_angles); } #endif // // Thermal first layer compensation values // #if HAS_PTC #if ENABLED(PTC_PROBE) EEPROM_WRITE(ptc.z_offsets_probe); #endif #if ENABLED(PTC_BED) EEPROM_WRITE(ptc.z_offsets_bed); #endif #if ENABLED(PTC_HOTEND) EEPROM_WRITE(ptc.z_offsets_hotend); #endif #else // No placeholder data for this feature #endif // // BLTOUCH // { _FIELD_TEST(bltouch_od_5v_mode); const bool bltouch_od_5v_mode = TERN0(BLTOUCH, bltouch.od_5v_mode); EEPROM_WRITE(bltouch_od_5v_mode); #if HAS_BLTOUCH_HS_MODE _FIELD_TEST(bltouch_high_speed_mode); const bool bltouch_high_speed_mode = TERN0(BLTOUCH, bltouch.high_speed_mode); EEPROM_WRITE(bltouch_high_speed_mode); #endif } // // Kinematic Settings (Delta, SCARA, TPARA, Polargraph...) // #if IS_KINEMATIC { EEPROM_WRITE(segments_per_second); #if ENABLED(DELTA) _FIELD_TEST(delta_height); EEPROM_WRITE(delta_height); // 1 float EEPROM_WRITE(delta_endstop_adj); // 3 floats EEPROM_WRITE(delta_radius); // 1 float EEPROM_WRITE(delta_diagonal_rod); // 1 float EEPROM_WRITE(delta_tower_angle_trim); // 3 floats EEPROM_WRITE(delta_diagonal_rod_trim); // 3 floats #elif ENABLED(POLARGRAPH) _FIELD_TEST(draw_area_min); EEPROM_WRITE(draw_area_min); // 2 floats EEPROM_WRITE(draw_area_max); // 2 floats EEPROM_WRITE(polargraph_max_belt_len); // 1 float #endif } #endif // // Extra Endstops offsets // #if HAS_EXTRA_ENDSTOPS { _FIELD_TEST(x2_endstop_adj); // Write dual endstops in X, Y, Z order. Unused = 0.0 dummyf = 0; EEPROM_WRITE(TERN(X_DUAL_ENDSTOPS, endstops.x2_endstop_adj, dummyf)); // 1 float EEPROM_WRITE(TERN(Y_DUAL_ENDSTOPS, endstops.y2_endstop_adj, dummyf)); // 1 float EEPROM_WRITE(TERN(Z_MULTI_ENDSTOPS, endstops.z2_endstop_adj, dummyf)); // 1 float #if ENABLED(Z_MULTI_ENDSTOPS) && NUM_Z_STEPPERS >= 3 EEPROM_WRITE(endstops.z3_endstop_adj); // 1 float #else EEPROM_WRITE(dummyf); #endif #if ENABLED(Z_MULTI_ENDSTOPS) && NUM_Z_STEPPERS >= 4 EEPROM_WRITE(endstops.z4_endstop_adj); // 1 float #else EEPROM_WRITE(dummyf); #endif } #endif #if ENABLED(Z_STEPPER_AUTO_ALIGN) EEPROM_WRITE(z_stepper_align.xy); #if HAS_Z_STEPPER_ALIGN_STEPPER_XY EEPROM_WRITE(z_stepper_align.stepper_xy); #endif #endif // // LCD Preheat settings // #if HAS_PREHEAT _FIELD_TEST(ui_material_preset); EEPROM_WRITE(ui.material_preset); #endif // // PIDTEMP // { _FIELD_TEST(hotendPID); #if DISABLED(PIDTEMP) raw_pidcf_t pidcf = { NAN, NAN, NAN, NAN, NAN }; #endif HOTEND_LOOP() { #if ENABLED(PIDTEMP) const hotend_pid_t &pid = thermalManager.temp_hotend[e].pid; raw_pidcf_t pidcf = { pid.p(), pid.i(), pid.d(), pid.c(), pid.f() }; #endif EEPROM_WRITE(pidcf); } _FIELD_TEST(lpq_len); const int16_t lpq_len = TERN(PID_EXTRUSION_SCALING, thermalManager.lpq_len, 20); EEPROM_WRITE(lpq_len); } // // PIDTEMPBED // { _FIELD_TEST(bedPID); #if ENABLED(PIDTEMPBED) const auto &pid = thermalManager.temp_bed.pid; const raw_pid_t bed_pid = { pid.p(), pid.i(), pid.d() }; #else const raw_pid_t bed_pid = { NAN, NAN, NAN }; #endif EEPROM_WRITE(bed_pid); } // // PIDTEMPCHAMBER // { _FIELD_TEST(chamberPID); #if ENABLED(PIDTEMPCHAMBER) const auto &pid = thermalManager.temp_chamber.pid; const raw_pid_t chamber_pid = { pid.p(), pid.i(), pid.d() }; #else const raw_pid_t chamber_pid = { NAN, NAN, NAN }; #endif EEPROM_WRITE(chamber_pid); } // // User-defined Thermistors // #if HAS_USER_THERMISTORS _FIELD_TEST(user_thermistor); EEPROM_WRITE(thermalManager.user_thermistor); #endif // // Power monitor // { #if HAS_POWER_MONITOR const uint8_t &power_monitor_flags = power_monitor.flags; #else constexpr uint8_t power_monitor_flags = 0x00; #endif _FIELD_TEST(power_monitor_flags); EEPROM_WRITE(power_monitor_flags); } // // LCD Contrast // { _FIELD_TEST(lcd_contrast); const uint8_t lcd_contrast = TERN(HAS_LCD_CONTRAST, ui.contrast, 127); EEPROM_WRITE(lcd_contrast); } // // LCD Brightness // { _FIELD_TEST(lcd_brightness); const uint8_t lcd_brightness = TERN(HAS_LCD_BRIGHTNESS, ui.brightness, 255); EEPROM_WRITE(lcd_brightness); } // // LCD Backlight / Sleep Timeout // #if ENABLED(EDITABLE_DISPLAY_TIMEOUT) #if HAS_BACKLIGHT_TIMEOUT EEPROM_WRITE(ui.backlight_timeout_minutes); #elif HAS_DISPLAY_SLEEP EEPROM_WRITE(ui.sleep_timeout_minutes); #endif #endif // // Controller Fan // { _FIELD_TEST(controllerFan_settings); #if ENABLED(USE_CONTROLLER_FAN) const controllerFan_settings_t &cfs = controllerFan.settings; #else constexpr controllerFan_settings_t cfs = controllerFan_defaults; #endif EEPROM_WRITE(cfs); } // // Power-Loss Recovery // { _FIELD_TEST(recovery_enabled); const bool recovery_enabled = TERN0(POWER_LOSS_RECOVERY, recovery.enabled); const celsius_t bed_temp_threshold = TERN0(HAS_PLR_BED_THRESHOLD, recovery.bed_temp_threshold); EEPROM_WRITE(recovery_enabled); EEPROM_WRITE(bed_temp_threshold); } // // Firmware Retraction // { _FIELD_TEST(fwretract_settings); #if DISABLED(FWRETRACT) const fwretract_settings_t autoretract_defaults = { 3, 45, 0, 0, 0, 13, 0, 8 }; #endif EEPROM_WRITE(TERN(FWRETRACT, fwretract.settings, autoretract_defaults)); #if DISABLED(FWRETRACT_AUTORETRACT) const bool autoretract_enabled = false; #endif EEPROM_WRITE(TERN(FWRETRACT_AUTORETRACT, fwretract.autoretract_enabled, autoretract_enabled)); } // // Volumetric & Filament Size // { _FIELD_TEST(parser_volumetric_enabled); #if DISABLED(NO_VOLUMETRICS) EEPROM_WRITE(parser.volumetric_enabled); EEPROM_WRITE(planner.filament_size); #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT) EEPROM_WRITE(planner.volumetric_extruder_limit); #else dummyf = DEFAULT_VOLUMETRIC_EXTRUDER_LIMIT; for (uint8_t q = EXTRUDERS; q--;) EEPROM_WRITE(dummyf); #endif #else const bool volumetric_enabled = false; EEPROM_WRITE(volumetric_enabled); dummyf = DEFAULT_NOMINAL_FILAMENT_DIA; for (uint8_t q = EXTRUDERS; q--;) EEPROM_WRITE(dummyf); dummyf = DEFAULT_VOLUMETRIC_EXTRUDER_LIMIT; for (uint8_t q = EXTRUDERS; q--;) EEPROM_WRITE(dummyf); #endif } // // TMC Configuration // { _FIELD_TEST(tmc_stepper_current); per_stepper_uint16_t tmc_stepper_current{0}; #if HAS_TRINAMIC_CONFIG #if AXIS_IS_TMC(X) tmc_stepper_current.X = stepperX.getMilliamps(); #endif #if AXIS_IS_TMC(Y) tmc_stepper_current.Y = stepperY.getMilliamps(); #endif #if AXIS_IS_TMC(Z) tmc_stepper_current.Z = stepperZ.getMilliamps(); #endif #if AXIS_IS_TMC(I) tmc_stepper_current.I = stepperI.getMilliamps(); #endif #if AXIS_IS_TMC(J) tmc_stepper_current.J = stepperJ.getMilliamps(); #endif #if AXIS_IS_TMC(K) tmc_stepper_current.K = stepperK.getMilliamps(); #endif #if AXIS_IS_TMC(U) tmc_stepper_current.U = stepperU.getMilliamps(); #endif #if AXIS_IS_TMC(V) tmc_stepper_current.V = stepperV.getMilliamps(); #endif #if AXIS_IS_TMC(W) tmc_stepper_current.W = stepperW.getMilliamps(); #endif #if AXIS_IS_TMC(X2) tmc_stepper_current.X2 = stepperX2.getMilliamps(); #endif #if AXIS_IS_TMC(Y2) tmc_stepper_current.Y2 = stepperY2.getMilliamps(); #endif #if AXIS_IS_TMC(Z2) tmc_stepper_current.Z2 = stepperZ2.getMilliamps(); #endif #if AXIS_IS_TMC(Z3) tmc_stepper_current.Z3 = stepperZ3.getMilliamps(); #endif #if AXIS_IS_TMC(Z4) tmc_stepper_current.Z4 = stepperZ4.getMilliamps(); #endif #if AXIS_IS_TMC(E0) tmc_stepper_current.E0 = stepperE0.getMilliamps(); #endif #if AXIS_IS_TMC(E1) tmc_stepper_current.E1 = stepperE1.getMilliamps(); #endif #if AXIS_IS_TMC(E2) tmc_stepper_current.E2 = stepperE2.getMilliamps(); #endif #if AXIS_IS_TMC(E3) tmc_stepper_current.E3 = stepperE3.getMilliamps(); #endif #if AXIS_IS_TMC(E4) tmc_stepper_current.E4 = stepperE4.getMilliamps(); #endif #if AXIS_IS_TMC(E5) tmc_stepper_current.E5 = stepperE5.getMilliamps(); #endif #if AXIS_IS_TMC(E6) tmc_stepper_current.E6 = stepperE6.getMilliamps(); #endif #if AXIS_IS_TMC(E7) tmc_stepper_current.E7 = stepperE7.getMilliamps(); #endif #endif EEPROM_WRITE(tmc_stepper_current); } // // TMC Hybrid Threshold, and placeholder values // { _FIELD_TEST(tmc_hybrid_threshold); #if ENABLED(HYBRID_THRESHOLD) per_stepper_uint32_t tmc_hybrid_threshold{0}; TERN_(X_HAS_STEALTHCHOP, tmc_hybrid_threshold.X = stepperX.get_pwm_thrs()); TERN_(Y_HAS_STEALTHCHOP, tmc_hybrid_threshold.Y = stepperY.get_pwm_thrs()); TERN_(Z_HAS_STEALTHCHOP, tmc_hybrid_threshold.Z = stepperZ.get_pwm_thrs()); TERN_(I_HAS_STEALTHCHOP, tmc_hybrid_threshold.I = stepperI.get_pwm_thrs()); TERN_(J_HAS_STEALTHCHOP, tmc_hybrid_threshold.J = stepperJ.get_pwm_thrs()); TERN_(K_HAS_STEALTHCHOP, tmc_hybrid_threshold.K = stepperK.get_pwm_thrs()); TERN_(U_HAS_STEALTHCHOP, tmc_hybrid_threshold.U = stepperU.get_pwm_thrs()); TERN_(V_HAS_STEALTHCHOP, tmc_hybrid_threshold.V = stepperV.get_pwm_thrs()); TERN_(W_HAS_STEALTHCHOP, tmc_hybrid_threshold.W = stepperW.get_pwm_thrs()); TERN_(X2_HAS_STEALTHCHOP, tmc_hybrid_threshold.X2 = stepperX2.get_pwm_thrs()); TERN_(Y2_HAS_STEALTHCHOP, tmc_hybrid_threshold.Y2 = stepperY2.get_pwm_thrs()); TERN_(Z2_HAS_STEALTHCHOP, tmc_hybrid_threshold.Z2 = stepperZ2.get_pwm_thrs()); TERN_(Z3_HAS_STEALTHCHOP, tmc_hybrid_threshold.Z3 = stepperZ3.get_pwm_thrs()); TERN_(Z4_HAS_STEALTHCHOP, tmc_hybrid_threshold.Z4 = stepperZ4.get_pwm_thrs()); TERN_(E0_HAS_STEALTHCHOP, tmc_hybrid_threshold.E0 = stepperE0.get_pwm_thrs()); TERN_(E1_HAS_STEALTHCHOP, tmc_hybrid_threshold.E1 = stepperE1.get_pwm_thrs()); TERN_(E2_HAS_STEALTHCHOP, tmc_hybrid_threshold.E2 = stepperE2.get_pwm_thrs()); TERN_(E3_HAS_STEALTHCHOP, tmc_hybrid_threshold.E3 = stepperE3.get_pwm_thrs()); TERN_(E4_HAS_STEALTHCHOP, tmc_hybrid_threshold.E4 = stepperE4.get_pwm_thrs()); TERN_(E5_HAS_STEALTHCHOP, tmc_hybrid_threshold.E5 = stepperE5.get_pwm_thrs()); TERN_(E6_HAS_STEALTHCHOP, tmc_hybrid_threshold.E6 = stepperE6.get_pwm_thrs()); TERN_(E7_HAS_STEALTHCHOP, tmc_hybrid_threshold.E7 = stepperE7.get_pwm_thrs()); #else #define _EN_ITEM(N) , .E##N = 30 const per_stepper_uint32_t tmc_hybrid_threshold = { NUM_AXIS_LIST_(.X = 100, .Y = 100, .Z = 3, .I = 3, .J = 3, .K = 3, .U = 3, .V = 3, .W = 3) .X2 = 100, .Y2 = 100, .Z2 = 3, .Z3 = 3, .Z4 = 3 REPEAT(E_STEPPERS, _EN_ITEM) }; #undef _EN_ITEM #endif EEPROM_WRITE(tmc_hybrid_threshold); } // // TMC StallGuard threshold // { mot_stepper_int16_t tmc_sgt{0}; #if USE_SENSORLESS NUM_AXIS_CODE( TERN_(X_SENSORLESS, tmc_sgt.X = stepperX.homing_threshold()), TERN_(Y_SENSORLESS, tmc_sgt.Y = stepperY.homing_threshold()), TERN_(Z_SENSORLESS, tmc_sgt.Z = stepperZ.homing_threshold()), TERN_(I_SENSORLESS, tmc_sgt.I = stepperI.homing_threshold()), TERN_(J_SENSORLESS, tmc_sgt.J = stepperJ.homing_threshold()), TERN_(K_SENSORLESS, tmc_sgt.K = stepperK.homing_threshold()), TERN_(U_SENSORLESS, tmc_sgt.U = stepperU.homing_threshold()), TERN_(V_SENSORLESS, tmc_sgt.V = stepperV.homing_threshold()), TERN_(W_SENSORLESS, tmc_sgt.W = stepperW.homing_threshold()) ); TERN_(X2_SENSORLESS, tmc_sgt.X2 = stepperX2.homing_threshold()); TERN_(Y2_SENSORLESS, tmc_sgt.Y2 = stepperY2.homing_threshold()); TERN_(Z2_SENSORLESS, tmc_sgt.Z2 = stepperZ2.homing_threshold()); TERN_(Z3_SENSORLESS, tmc_sgt.Z3 = stepperZ3.homing_threshold()); TERN_(Z4_SENSORLESS, tmc_sgt.Z4 = stepperZ4.homing_threshold()); #endif EEPROM_WRITE(tmc_sgt); } // // TMC stepping mode // { _FIELD_TEST(tmc_stealth_enabled); per_stepper_bool_t tmc_stealth_enabled = { false }; TERN_(X_HAS_STEALTHCHOP, tmc_stealth_enabled.X = stepperX.get_stored_stealthChop()); TERN_(Y_HAS_STEALTHCHOP, tmc_stealth_enabled.Y = stepperY.get_stored_stealthChop()); TERN_(Z_HAS_STEALTHCHOP, tmc_stealth_enabled.Z = stepperZ.get_stored_stealthChop()); TERN_(I_HAS_STEALTHCHOP, tmc_stealth_enabled.I = stepperI.get_stored_stealthChop()); TERN_(J_HAS_STEALTHCHOP, tmc_stealth_enabled.J = stepperJ.get_stored_stealthChop()); TERN_(K_HAS_STEALTHCHOP, tmc_stealth_enabled.K = stepperK.get_stored_stealthChop()); TERN_(U_HAS_STEALTHCHOP, tmc_stealth_enabled.U = stepperU.get_stored_stealthChop()); TERN_(V_HAS_STEALTHCHOP, tmc_stealth_enabled.V = stepperV.get_stored_stealthChop()); TERN_(W_HAS_STEALTHCHOP, tmc_stealth_enabled.W = stepperW.get_stored_stealthChop()); TERN_(X2_HAS_STEALTHCHOP, tmc_stealth_enabled.X2 = stepperX2.get_stored_stealthChop()); TERN_(Y2_HAS_STEALTHCHOP, tmc_stealth_enabled.Y2 = stepperY2.get_stored_stealthChop()); TERN_(Z2_HAS_STEALTHCHOP, tmc_stealth_enabled.Z2 = stepperZ2.get_stored_stealthChop()); TERN_(Z3_HAS_STEALTHCHOP, tmc_stealth_enabled.Z3 = stepperZ3.get_stored_stealthChop()); TERN_(Z4_HAS_STEALTHCHOP, tmc_stealth_enabled.Z4 = stepperZ4.get_stored_stealthChop()); TERN_(E0_HAS_STEALTHCHOP, tmc_stealth_enabled.E0 = stepperE0.get_stored_stealthChop()); TERN_(E1_HAS_STEALTHCHOP, tmc_stealth_enabled.E1 = stepperE1.get_stored_stealthChop()); TERN_(E2_HAS_STEALTHCHOP, tmc_stealth_enabled.E2 = stepperE2.get_stored_stealthChop()); TERN_(E3_HAS_STEALTHCHOP, tmc_stealth_enabled.E3 = stepperE3.get_stored_stealthChop()); TERN_(E4_HAS_STEALTHCHOP, tmc_stealth_enabled.E4 = stepperE4.get_stored_stealthChop()); TERN_(E5_HAS_STEALTHCHOP, tmc_stealth_enabled.E5 = stepperE5.get_stored_stealthChop()); TERN_(E6_HAS_STEALTHCHOP, tmc_stealth_enabled.E6 = stepperE6.get_stored_stealthChop()); TERN_(E7_HAS_STEALTHCHOP, tmc_stealth_enabled.E7 = stepperE7.get_stored_stealthChop()); EEPROM_WRITE(tmc_stealth_enabled); } // // Linear Advance // { _FIELD_TEST(planner_extruder_advance_K); #if ENABLED(LIN_ADVANCE) EEPROM_WRITE(planner.extruder_advance_K); #else dummyf = 0; for (uint8_t q = DISTINCT_E; q--;) EEPROM_WRITE(dummyf); #endif } // // Motor Current PWM // { _FIELD_TEST(motor_current_setting); #if HAS_MOTOR_CURRENT_SPI || HAS_MOTOR_CURRENT_PWM EEPROM_WRITE(stepper.motor_current_setting); #else const uint32_t no_current[MOTOR_CURRENT_COUNT] = { 0 }; EEPROM_WRITE(no_current); #endif } // // Adaptive Step Smoothing state // #if ENABLED(ADAPTIVE_STEP_SMOOTHING_TOGGLE) _FIELD_TEST(adaptive_step_smoothing_enabled); EEPROM_WRITE(stepper.adaptive_step_smoothing_enabled); #endif // // CNC Coordinate Systems // #if NUM_AXES _FIELD_TEST(coordinate_system); #if DISABLED(CNC_COORDINATE_SYSTEMS) const xyz_pos_t coordinate_system[MAX_COORDINATE_SYSTEMS] = { { 0 } }; #endif EEPROM_WRITE(TERN(CNC_COORDINATE_SYSTEMS, gcode.coordinate_system, coordinate_system)); #endif // // Skew correction factors // #if ENABLED(SKEW_CORRECTION) _FIELD_TEST(planner_skew_factor); EEPROM_WRITE(planner.skew_factor); #endif // // Advanced Pause filament load & unload lengths // #if ENABLED(CONFIGURE_FILAMENT_CHANGE) { _FIELD_TEST(fc_settings); EEPROM_WRITE(fc_settings); } #endif // // Multiple Extruders // #if HAS_MULTI_EXTRUDER _FIELD_TEST(toolchange_settings); EEPROM_WRITE(toolchange_settings); #endif // // Backlash Compensation // #if NUM_AXES { #if ENABLED(BACKLASH_GCODE) xyz_float_t backlash_distance_mm; LOOP_NUM_AXES(axis) backlash_distance_mm[axis] = backlash.get_distance_mm((AxisEnum)axis); const uint8_t backlash_correction = backlash.get_correction_uint8(); #else const xyz_float_t backlash_distance_mm{0}; const uint8_t backlash_correction = 0; #endif #if ENABLED(BACKLASH_GCODE) && defined(BACKLASH_SMOOTHING_MM) const float backlash_smoothing_mm = backlash.get_smoothing_mm(); #else const float backlash_smoothing_mm = 3; #endif _FIELD_TEST(backlash_distance_mm); EEPROM_WRITE(backlash_distance_mm); EEPROM_WRITE(backlash_correction); EEPROM_WRITE(backlash_smoothing_mm); } #endif // NUM_AXES // // Extensible UI User Data // #if ENABLED(EXTENSIBLE_UI) { char extui_data[ExtUI::eeprom_data_size] = { 0 }; ExtUI::onStoreSettings(extui_data); _FIELD_TEST(extui_data); EEPROM_WRITE(extui_data); } #endif // // JyersUI DWIN User Data // #if ENABLED(DWIN_CREALITY_LCD_JYERSUI) { _FIELD_TEST(dwin_settings); char dwin_settings[jyersDWIN.eeprom_data_size] = { 0 }; jyersDWIN.saveSettings(dwin_settings); EEPROM_WRITE(dwin_settings); } #endif // // Case Light Brightness // #if CASELIGHT_USES_BRIGHTNESS EEPROM_WRITE(caselight.brightness); #endif // // Password feature // #if ENABLED(PASSWORD_FEATURE) EEPROM_WRITE(password.is_set); EEPROM_WRITE(password.value); #endif // // TOUCH_SCREEN_CALIBRATION // #if ENABLED(TOUCH_SCREEN_CALIBRATION) EEPROM_WRITE(touch_calibration.calibration); #endif // // Ethernet network info // #if HAS_ETHERNET { _FIELD_TEST(ethernet_hardware_enabled); const bool ethernet_hardware_enabled = ethernet.hardware_enabled; const uint32_t ethernet_ip = ethernet.ip, ethernet_dns = ethernet.myDns, ethernet_gateway = ethernet.gateway, ethernet_subnet = ethernet.subnet; EEPROM_WRITE(ethernet_hardware_enabled); EEPROM_WRITE(ethernet_ip); EEPROM_WRITE(ethernet_dns); EEPROM_WRITE(ethernet_gateway); EEPROM_WRITE(ethernet_subnet); } #endif // // Buzzer enable/disable // #if ENABLED(SOUND_MENU_ITEM) EEPROM_WRITE(ui.sound_on); #endif // // Fan tachometer check // #if HAS_FANCHECK EEPROM_WRITE(fan_check.enabled); #endif // // MKS UI controller // #if DGUS_LCD_UI_MKS EEPROM_WRITE(mks_language_index); EEPROM_WRITE(mks_corner_offsets); EEPROM_WRITE(mks_park_pos); EEPROM_WRITE(mks_min_extrusion_temp); #endif // // Selected LCD language // #if HAS_MULTI_LANGUAGE EEPROM_WRITE(ui.language); #endif // // Model predictive control // #if ENABLED(MPCTEMP) HOTEND_LOOP() EEPROM_WRITE(thermalManager.temp_hotend[e].mpc); #endif // // Fixed-Time Motion // #if ENABLED(FT_MOTION) _FIELD_TEST(ftMotion_cfg); EEPROM_WRITE(ftMotion.cfg); #endif // // Input Shaping // #if HAS_ZV_SHAPING #if ENABLED(INPUT_SHAPING_X) EEPROM_WRITE(stepper.get_shaping_frequency(X_AXIS)); EEPROM_WRITE(stepper.get_shaping_damping_ratio(X_AXIS)); #endif #if ENABLED(INPUT_SHAPING_Y) EEPROM_WRITE(stepper.get_shaping_frequency(Y_AXIS)); EEPROM_WRITE(stepper.get_shaping_damping_ratio(Y_AXIS)); #endif #endif // // HOTEND_IDLE_TIMEOUT // #if ENABLED(HOTEND_IDLE_TIMEOUT) EEPROM_WRITE(hotend_idle.cfg); #endif // // Nonlinear Extrusion // #if ENABLED(NONLINEAR_EXTRUSION) EEPROM_WRITE(stepper.ne); #endif // // Report final CRC and Data Size // if (eeprom_error == ERR_EEPROM_NOERR) { const uint16_t eeprom_size = eeprom_index - (EEPROM_OFFSET), final_crc = working_crc; // Write the EEPROM header eeprom_index = EEPROM_OFFSET; EEPROM_WRITE(version); #if ENABLED(EEPROM_INIT_NOW) EEPROM_WRITE(build_hash); #endif EEPROM_WRITE(final_crc); // Report storage size DEBUG_ECHO_MSG("Settings Stored (", eeprom_size, " bytes; crc ", (uint32_t)final_crc, ")"); eeprom_error = size_error(eeprom_size); } EEPROM_FINISH(); // // UBL Mesh // #if ENABLED(UBL_SAVE_ACTIVE_ON_M500) if (bedlevel.storage_slot >= 0) store_mesh(bedlevel.storage_slot); #endif const bool success = (eeprom_error == ERR_EEPROM_NOERR); if (success) { LCD_MESSAGE(MSG_SETTINGS_STORED); TERN_(HOST_PROMPT_SUPPORT, hostui.notify(GET_TEXT_F(MSG_SETTINGS_STORED))); } TERN_(EXTENSIBLE_UI, ExtUI::onSettingsStored(success)); return success; } /** * M501 - Retrieve Configuration */ EEPROM_Error MarlinSettings::_load() { EEPROM_Error eeprom_error = ERR_EEPROM_NOERR; if (!EEPROM_START(EEPROM_OFFSET)) return eeprom_error; char stored_ver[4]; EEPROM_READ_ALWAYS(stored_ver); uint16_t stored_crc; do { // A block to break out of on error // Version has to match or defaults are used if (strncmp(version, stored_ver, 3) != 0) { if (stored_ver[3] != '\0') { stored_ver[0] = '?'; stored_ver[1] = '\0'; } DEBUG_ECHO_MSG("EEPROM version mismatch (EEPROM=", stored_ver, " Marlin=" EEPROM_VERSION ")"); eeprom_error = ERR_EEPROM_VERSION; break; } // // Optionally reset on first boot after flashing // #if ENABLED(EEPROM_INIT_NOW) uint32_t stored_hash; EEPROM_READ_ALWAYS(stored_hash); if (stored_hash != build_hash) { eeprom_error = ERR_EEPROM_CORRUPT; break; } #endif // // Get the stored CRC to compare at the end // EEPROM_READ_ALWAYS(stored_crc); // // A temporary float for safe storage // float dummyf = 0; // // Init to 0. Accumulated by EEPROM_READ // working_crc = 0; // // Validate the stored size against the current data structure size // uint16_t stored_size; EEPROM_READ_ALWAYS(stored_size); if ((eeprom_error = size_error(stored_size))) break; // // Extruder Parameter Count // Number of e_factors may change // _FIELD_TEST(e_factors); uint8_t e_factors; EEPROM_READ_ALWAYS(e_factors); // // Planner Motion // { // Get only the number of E stepper parameters previously stored // Any steppers added later are set to their defaults uint32_t tmp1[NUM_AXES + e_factors]; EEPROM_READ((uint8_t *)tmp1, sizeof(tmp1)); // max_acceleration_mm_per_s2 EEPROM_READ(planner.settings.min_segment_time_us); #if ENABLED(EDITABLE_STEPS_PER_UNIT) float tmp2[NUM_AXES + e_factors]; EEPROM_READ((uint8_t *)tmp2, sizeof(tmp2)); // axis_steps_per_mm #endif feedRate_t tmp3[NUM_AXES + e_factors]; EEPROM_READ((uint8_t *)tmp3, sizeof(tmp3)); // max_feedrate_mm_s if (!validating) LOOP_DISTINCT_AXES(i) { const bool in = (i < e_factors + NUM_AXES); planner.settings.max_acceleration_mm_per_s2[i] = in ? tmp1[i] : pgm_read_dword(&_DMA[ALIM(i, _DMA)]); #if ENABLED(EDITABLE_STEPS_PER_UNIT) planner.settings.axis_steps_per_mm[i] = in ? tmp2[i] : pgm_read_float(&_DASU[ALIM(i, _DASU)]); #endif planner.settings.max_feedrate_mm_s[i] = in ? tmp3[i] : pgm_read_float(&_DMF[ALIM(i, _DMF)]); } EEPROM_READ(planner.settings.acceleration); EEPROM_READ(planner.settings.retract_acceleration); EEPROM_READ(planner.settings.travel_acceleration); EEPROM_READ(planner.settings.min_feedrate_mm_s); EEPROM_READ(planner.settings.min_travel_feedrate_mm_s); #if ENABLED(CLASSIC_JERK) EEPROM_READ(planner.max_jerk); #if HAS_LINEAR_E_JERK EEPROM_READ(dummyf); #endif #else for (uint8_t q = LOGICAL_AXES; q--;) EEPROM_READ(dummyf); #endif EEPROM_READ(TERN(CLASSIC_JERK, dummyf, planner.junction_deviation_mm)); } // // Home Offset (M206 / M665) // #if NUM_AXES { _FIELD_TEST(home_offset); #if HAS_SCARA_OFFSET EEPROM_READ(scara_home_offset); #else #if !HAS_HOME_OFFSET xyz_pos_t home_offset; #endif EEPROM_READ(home_offset); #endif } #endif // NUM_AXES // // Hotend Offsets, if any // { #if HAS_HOTEND_OFFSET // Skip hotend 0 which must be 0 for (uint8_t e = 1; e < HOTENDS; ++e) EEPROM_READ(hotend_offset[e]); #endif } // // Filament Runout Sensor // { int8_t runout_sensor_enabled; _FIELD_TEST(runout_sensor_enabled); EEPROM_READ(runout_sensor_enabled); #if HAS_FILAMENT_SENSOR if (!validating) runout.enabled = runout_sensor_enabled < 0 ? FIL_RUNOUT_ENABLED_DEFAULT : runout_sensor_enabled; #endif TERN_(HAS_FILAMENT_SENSOR, if (runout.enabled) runout.reset()); float runout_distance_mm; EEPROM_READ(runout_distance_mm); #if HAS_FILAMENT_RUNOUT_DISTANCE if (!validating) runout.set_runout_distance(runout_distance_mm); #endif } // // Global Leveling // EEPROM_READ(TERN(ENABLE_LEVELING_FADE_HEIGHT, new_z_fade_height, dummyf)); // // AUTOTEMP // #if ENABLED(AUTOTEMP) EEPROM_READ(planner.autotemp.max); EEPROM_READ(planner.autotemp.min); EEPROM_READ(planner.autotemp.factor); #endif // // Mesh (Manual) Bed Leveling // { uint8_t mesh_num_x, mesh_num_y; uint16_t mesh_check; EEPROM_READ(dummyf); EEPROM_READ_ALWAYS(mesh_num_x); EEPROM_READ_ALWAYS(mesh_num_y); // Check value must correspond to the X/Y values EEPROM_READ_ALWAYS(mesh_check); if (mesh_check != TWO_BYTE_HASH(mesh_num_x, mesh_num_y)) { eeprom_error = ERR_EEPROM_CORRUPT; break; } #if ENABLED(MESH_BED_LEVELING) if (!validating) bedlevel.z_offset = dummyf; if (mesh_num_x == (GRID_MAX_POINTS_X) && mesh_num_y == (GRID_MAX_POINTS_Y)) { // EEPROM data fits the current mesh EEPROM_READ(bedlevel.z_values); } else if (mesh_num_x > (GRID_MAX_POINTS_X) || mesh_num_y > (GRID_MAX_POINTS_Y)) { eeprom_error = ERR_EEPROM_CORRUPT; break; } else { // EEPROM data is stale if (!validating) bedlevel.reset(); for (uint16_t q = mesh_num_x * mesh_num_y; q--;) EEPROM_READ(dummyf); } #else // MBL is disabled - skip the stored data for (uint16_t q = mesh_num_x * mesh_num_y; q--;) EEPROM_READ(dummyf); #endif } // // Probe Z Offset // #if NUM_AXES { _FIELD_TEST(probe_offset); #if HAS_BED_PROBE const xyz_pos_t &zpo = probe.offset; #else xyz_pos_t zpo; #endif EEPROM_READ(zpo); } #endif // // Planar Bed Leveling matrix // { #if ABL_PLANAR EEPROM_READ(planner.bed_level_matrix); #else for (uint8_t q = 9; q--;) EEPROM_READ(dummyf); #endif } // // Bilinear Auto Bed Leveling // { uint8_t grid_max_x, grid_max_y; EEPROM_READ_ALWAYS(grid_max_x); // 1 byte EEPROM_READ_ALWAYS(grid_max_y); // 1 byte // Check value must correspond to the X/Y values uint16_t grid_check; EEPROM_READ_ALWAYS(grid_check); if (grid_check != TWO_BYTE_HASH(grid_max_x, grid_max_y)) { eeprom_error = ERR_EEPROM_CORRUPT; break; } xy_pos_t spacing, start; EEPROM_READ(spacing); // 2 ints EEPROM_READ(start); // 2 ints #if ENABLED(AUTO_BED_LEVELING_BILINEAR) if (grid_max_x == (GRID_MAX_POINTS_X) && grid_max_y == (GRID_MAX_POINTS_Y)) { if (!validating) set_bed_leveling_enabled(false); bedlevel.set_grid(spacing, start); EEPROM_READ(bedlevel.z_values); // 9 to 256 floats } else if (grid_max_x > (GRID_MAX_POINTS_X) || grid_max_y > (GRID_MAX_POINTS_Y)) { eeprom_error = ERR_EEPROM_CORRUPT; break; } else // EEPROM data is stale #endif // AUTO_BED_LEVELING_BILINEAR { // Skip past disabled (or stale) Bilinear Grid data for (uint16_t q = grid_max_x * grid_max_y; q--;) EEPROM_READ(dummyf); } } // // X Axis Twist Compensation // #if ENABLED(X_AXIS_TWIST_COMPENSATION) _FIELD_TEST(xatc_spacing); EEPROM_READ(xatc.spacing); EEPROM_READ(xatc.start); EEPROM_READ(xatc.z_offset); #endif // // Unified Bed Leveling active state // { _FIELD_TEST(planner_leveling_active); #if ENABLED(AUTO_BED_LEVELING_UBL) const bool &planner_leveling_active = planner.leveling_active; const int8_t &ubl_storage_slot = bedlevel.storage_slot; #else bool planner_leveling_active; int8_t ubl_storage_slot; #endif EEPROM_READ(planner_leveling_active); EEPROM_READ(ubl_storage_slot); } // // SERVO_ANGLES // #if HAS_SERVO_ANGLES { _FIELD_TEST(servo_angles); #if ENABLED(EDITABLE_SERVO_ANGLES) uint16_t (&servo_angles_arr)[NUM_SERVOS][2] = servo_angles; #else uint16_t servo_angles_arr[NUM_SERVOS][2]; #endif EEPROM_READ(servo_angles_arr); } #endif // // Thermal first layer compensation values // #if HAS_PTC #if ENABLED(PTC_PROBE) EEPROM_READ(ptc.z_offsets_probe); #endif # if ENABLED(PTC_BED) EEPROM_READ(ptc.z_offsets_bed); #endif #if ENABLED(PTC_HOTEND) EEPROM_READ(ptc.z_offsets_hotend); #endif if (!validating) ptc.reset_index(); #else // No placeholder data for this feature #endif // // BLTOUCH // { _FIELD_TEST(bltouch_od_5v_mode); #if ENABLED(BLTOUCH) const bool &bltouch_od_5v_mode = bltouch.od_5v_mode; #else bool bltouch_od_5v_mode; #endif EEPROM_READ(bltouch_od_5v_mode); #if HAS_BLTOUCH_HS_MODE _FIELD_TEST(bltouch_high_speed_mode); #if ENABLED(BLTOUCH) const bool &bltouch_high_speed_mode = bltouch.high_speed_mode; #else bool bltouch_high_speed_mode; #endif EEPROM_READ(bltouch_high_speed_mode); #endif } // // Kinematic Settings (Delta, SCARA, TPARA, Polargraph...) // #if IS_KINEMATIC { EEPROM_READ(segments_per_second); #if ENABLED(DELTA) _FIELD_TEST(delta_height); EEPROM_READ(delta_height); // 1 float EEPROM_READ(delta_endstop_adj); // 3 floats EEPROM_READ(delta_radius); // 1 float EEPROM_READ(delta_diagonal_rod); // 1 float EEPROM_READ(delta_tower_angle_trim); // 3 floats EEPROM_READ(delta_diagonal_rod_trim); // 3 floats #elif ENABLED(POLARGRAPH) _FIELD_TEST(draw_area_min); EEPROM_READ(draw_area_min); // 2 floats EEPROM_READ(draw_area_max); // 2 floats EEPROM_READ(polargraph_max_belt_len); // 1 float #endif } #endif // // Extra Endstops offsets // #if HAS_EXTRA_ENDSTOPS { _FIELD_TEST(x2_endstop_adj); EEPROM_READ(TERN(X_DUAL_ENDSTOPS, endstops.x2_endstop_adj, dummyf)); // 1 float EEPROM_READ(TERN(Y_DUAL_ENDSTOPS, endstops.y2_endstop_adj, dummyf)); // 1 float EEPROM_READ(TERN(Z_MULTI_ENDSTOPS, endstops.z2_endstop_adj, dummyf)); // 1 float #if ENABLED(Z_MULTI_ENDSTOPS) && NUM_Z_STEPPERS >= 3 EEPROM_READ(endstops.z3_endstop_adj); // 1 float #else EEPROM_READ(dummyf); #endif #if ENABLED(Z_MULTI_ENDSTOPS) && NUM_Z_STEPPERS >= 4 EEPROM_READ(endstops.z4_endstop_adj); // 1 float #else EEPROM_READ(dummyf); #endif } #endif #if ENABLED(Z_STEPPER_AUTO_ALIGN) EEPROM_READ(z_stepper_align.xy); #if HAS_Z_STEPPER_ALIGN_STEPPER_XY EEPROM_READ(z_stepper_align.stepper_xy); #endif #endif // // LCD Preheat settings // #if HAS_PREHEAT _FIELD_TEST(ui_material_preset); EEPROM_READ(ui.material_preset); #endif // // Hotend PID // { HOTEND_LOOP() { raw_pidcf_t pidcf; EEPROM_READ(pidcf); #if ENABLED(PIDTEMP) if (!validating && !isnan(pidcf.p)) thermalManager.temp_hotend[e].pid.set(pidcf); #endif } } // // PID Extrusion Scaling // { _FIELD_TEST(lpq_len); #if ENABLED(PID_EXTRUSION_SCALING) const int16_t &lpq_len = thermalManager.lpq_len; #else int16_t lpq_len; #endif EEPROM_READ(lpq_len); } // // Heated Bed PID // { raw_pid_t pid; EEPROM_READ(pid); #if ENABLED(PIDTEMPBED) if (!validating && !isnan(pid.p)) thermalManager.temp_bed.pid.set(pid); #endif } // // Heated Chamber PID // { raw_pid_t pid; EEPROM_READ(pid); #if ENABLED(PIDTEMPCHAMBER) if (!validating && !isnan(pid.p)) thermalManager.temp_chamber.pid.set(pid); #endif } // // User-defined Thermistors // #if HAS_USER_THERMISTORS { user_thermistor_t user_thermistor[USER_THERMISTORS]; _FIELD_TEST(user_thermistor); EEPROM_READ(user_thermistor); if (!validating) COPY(thermalManager.user_thermistor, user_thermistor); } #endif // // Power monitor // { uint8_t power_monitor_flags; _FIELD_TEST(power_monitor_flags); EEPROM_READ(power_monitor_flags); TERN_(HAS_POWER_MONITOR, if (!validating) power_monitor.flags = power_monitor_flags); } // // LCD Contrast // { uint8_t lcd_contrast; _FIELD_TEST(lcd_contrast); EEPROM_READ(lcd_contrast); TERN_(HAS_LCD_CONTRAST, if (!validating) ui.contrast = lcd_contrast); } // // LCD Brightness // { uint8_t lcd_brightness; _FIELD_TEST(lcd_brightness); EEPROM_READ(lcd_brightness); TERN_(HAS_LCD_BRIGHTNESS, if (!validating) ui.brightness = lcd_brightness); } // // LCD Backlight / Sleep Timeout // #if ENABLED(EDITABLE_DISPLAY_TIMEOUT) #if HAS_BACKLIGHT_TIMEOUT EEPROM_READ(ui.backlight_timeout_minutes); #elif HAS_DISPLAY_SLEEP EEPROM_READ(ui.sleep_timeout_minutes); #endif #endif // // Controller Fan // { controllerFan_settings_t cfs = { 0 }; _FIELD_TEST(controllerFan_settings); EEPROM_READ(cfs); TERN_(CONTROLLER_FAN_EDITABLE, if (!validating) controllerFan.settings = cfs); } // // Power-Loss Recovery // { _FIELD_TEST(recovery_enabled); bool recovery_enabled; celsius_t bed_temp_threshold; EEPROM_READ(recovery_enabled); EEPROM_READ(bed_temp_threshold); if (!validating) { TERN_(POWER_LOSS_RECOVERY, recovery.enabled = recovery_enabled); TERN_(HAS_PLR_BED_THRESHOLD, recovery.bed_temp_threshold = bed_temp_threshold); } } // // Firmware Retraction // { fwretract_settings_t fwretract_settings; bool autoretract_enabled; _FIELD_TEST(fwretract_settings); EEPROM_READ(fwretract_settings); EEPROM_READ(autoretract_enabled); #if ENABLED(FWRETRACT) if (!validating) { fwretract.settings = fwretract_settings; TERN_(FWRETRACT_AUTORETRACT, fwretract.autoretract_enabled = autoretract_enabled); } #endif } // // Volumetric & Filament Size // { struct { bool volumetric_enabled; float filament_size[EXTRUDERS]; float volumetric_extruder_limit[EXTRUDERS]; } storage; _FIELD_TEST(parser_volumetric_enabled); EEPROM_READ(storage); #if DISABLED(NO_VOLUMETRICS) if (!validating) { parser.volumetric_enabled = storage.volumetric_enabled; COPY(planner.filament_size, storage.filament_size); #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT) COPY(planner.volumetric_extruder_limit, storage.volumetric_extruder_limit); #endif } #endif } // // TMC Stepper Settings // if (!validating) reset_stepper_drivers(); // TMC Stepper Current { _FIELD_TEST(tmc_stepper_current); per_stepper_uint16_t currents; EEPROM_READ(currents); #if HAS_TRINAMIC_CONFIG #define SET_CURR(Q) stepper##Q.rms_current(currents.Q ? currents.Q : Q##_CURRENT) if (!validating) { #if AXIS_IS_TMC(X) SET_CURR(X); #endif #if AXIS_IS_TMC(Y) SET_CURR(Y); #endif #if AXIS_IS_TMC(Z) SET_CURR(Z); #endif #if AXIS_IS_TMC(X2) SET_CURR(X2); #endif #if AXIS_IS_TMC(Y2) SET_CURR(Y2); #endif #if AXIS_IS_TMC(Z2) SET_CURR(Z2); #endif #if AXIS_IS_TMC(Z3) SET_CURR(Z3); #endif #if AXIS_IS_TMC(Z4) SET_CURR(Z4); #endif #if AXIS_IS_TMC(I) SET_CURR(I); #endif #if AXIS_IS_TMC(J) SET_CURR(J); #endif #if AXIS_IS_TMC(K) SET_CURR(K); #endif #if AXIS_IS_TMC(U) SET_CURR(U); #endif #if AXIS_IS_TMC(V) SET_CURR(V); #endif #if AXIS_IS_TMC(W) SET_CURR(W); #endif #if AXIS_IS_TMC(E0) SET_CURR(E0); #endif #if AXIS_IS_TMC(E1) SET_CURR(E1); #endif #if AXIS_IS_TMC(E2) SET_CURR(E2); #endif #if AXIS_IS_TMC(E3) SET_CURR(E3); #endif #if AXIS_IS_TMC(E4) SET_CURR(E4); #endif #if AXIS_IS_TMC(E5) SET_CURR(E5); #endif #if AXIS_IS_TMC(E6) SET_CURR(E6); #endif #if AXIS_IS_TMC(E7) SET_CURR(E7); #endif } #endif } // TMC Hybrid Threshold { per_stepper_uint32_t tmc_hybrid_threshold; _FIELD_TEST(tmc_hybrid_threshold); EEPROM_READ(tmc_hybrid_threshold); #if ENABLED(HYBRID_THRESHOLD) if (!validating) { TERN_(X_HAS_STEALTHCHOP, stepperX.set_pwm_thrs(tmc_hybrid_threshold.X)); TERN_(Y_HAS_STEALTHCHOP, stepperY.set_pwm_thrs(tmc_hybrid_threshold.Y)); TERN_(Z_HAS_STEALTHCHOP, stepperZ.set_pwm_thrs(tmc_hybrid_threshold.Z)); TERN_(X2_HAS_STEALTHCHOP, stepperX2.set_pwm_thrs(tmc_hybrid_threshold.X2)); TERN_(Y2_HAS_STEALTHCHOP, stepperY2.set_pwm_thrs(tmc_hybrid_threshold.Y2)); TERN_(Z2_HAS_STEALTHCHOP, stepperZ2.set_pwm_thrs(tmc_hybrid_threshold.Z2)); TERN_(Z3_HAS_STEALTHCHOP, stepperZ3.set_pwm_thrs(tmc_hybrid_threshold.Z3)); TERN_(Z4_HAS_STEALTHCHOP, stepperZ4.set_pwm_thrs(tmc_hybrid_threshold.Z4)); TERN_(I_HAS_STEALTHCHOP, stepperI.set_pwm_thrs(tmc_hybrid_threshold.I)); TERN_(J_HAS_STEALTHCHOP, stepperJ.set_pwm_thrs(tmc_hybrid_threshold.J)); TERN_(K_HAS_STEALTHCHOP, stepperK.set_pwm_thrs(tmc_hybrid_threshold.K)); TERN_(U_HAS_STEALTHCHOP, stepperU.set_pwm_thrs(tmc_hybrid_threshold.U)); TERN_(V_HAS_STEALTHCHOP, stepperV.set_pwm_thrs(tmc_hybrid_threshold.V)); TERN_(W_HAS_STEALTHCHOP, stepperW.set_pwm_thrs(tmc_hybrid_threshold.W)); TERN_(E0_HAS_STEALTHCHOP, stepperE0.set_pwm_thrs(tmc_hybrid_threshold.E0)); TERN_(E1_HAS_STEALTHCHOP, stepperE1.set_pwm_thrs(tmc_hybrid_threshold.E1)); TERN_(E2_HAS_STEALTHCHOP, stepperE2.set_pwm_thrs(tmc_hybrid_threshold.E2)); TERN_(E3_HAS_STEALTHCHOP, stepperE3.set_pwm_thrs(tmc_hybrid_threshold.E3)); TERN_(E4_HAS_STEALTHCHOP, stepperE4.set_pwm_thrs(tmc_hybrid_threshold.E4)); TERN_(E5_HAS_STEALTHCHOP, stepperE5.set_pwm_thrs(tmc_hybrid_threshold.E5)); TERN_(E6_HAS_STEALTHCHOP, stepperE6.set_pwm_thrs(tmc_hybrid_threshold.E6)); TERN_(E7_HAS_STEALTHCHOP, stepperE7.set_pwm_thrs(tmc_hybrid_threshold.E7)); } #endif } // // TMC StallGuard threshold. // { mot_stepper_int16_t tmc_sgt; _FIELD_TEST(tmc_sgt); EEPROM_READ(tmc_sgt); #if USE_SENSORLESS if (!validating) { NUM_AXIS_CODE( TERN_(X_SENSORLESS, stepperX.homing_threshold(tmc_sgt.X)), TERN_(Y_SENSORLESS, stepperY.homing_threshold(tmc_sgt.Y)), TERN_(Z_SENSORLESS, stepperZ.homing_threshold(tmc_sgt.Z)), TERN_(I_SENSORLESS, stepperI.homing_threshold(tmc_sgt.I)), TERN_(J_SENSORLESS, stepperJ.homing_threshold(tmc_sgt.J)), TERN_(K_SENSORLESS, stepperK.homing_threshold(tmc_sgt.K)), TERN_(U_SENSORLESS, stepperU.homing_threshold(tmc_sgt.U)), TERN_(V_SENSORLESS, stepperV.homing_threshold(tmc_sgt.V)), TERN_(W_SENSORLESS, stepperW.homing_threshold(tmc_sgt.W)) ); TERN_(X2_SENSORLESS, stepperX2.homing_threshold(tmc_sgt.X2)); TERN_(Y2_SENSORLESS, stepperY2.homing_threshold(tmc_sgt.Y2)); TERN_(Z2_SENSORLESS, stepperZ2.homing_threshold(tmc_sgt.Z2)); TERN_(Z3_SENSORLESS, stepperZ3.homing_threshold(tmc_sgt.Z3)); TERN_(Z4_SENSORLESS, stepperZ4.homing_threshold(tmc_sgt.Z4)); } #endif } // TMC stepping mode { _FIELD_TEST(tmc_stealth_enabled); per_stepper_bool_t tmc_stealth_enabled; EEPROM_READ(tmc_stealth_enabled); #if HAS_TRINAMIC_CONFIG #define SET_STEPPING_MODE(ST) stepper##ST.stored.stealthChop_enabled = tmc_stealth_enabled.ST; stepper##ST.refresh_stepping_mode(); if (!validating) { TERN_(X_HAS_STEALTHCHOP, SET_STEPPING_MODE(X)); TERN_(Y_HAS_STEALTHCHOP, SET_STEPPING_MODE(Y)); TERN_(Z_HAS_STEALTHCHOP, SET_STEPPING_MODE(Z)); TERN_(I_HAS_STEALTHCHOP, SET_STEPPING_MODE(I)); TERN_(J_HAS_STEALTHCHOP, SET_STEPPING_MODE(J)); TERN_(K_HAS_STEALTHCHOP, SET_STEPPING_MODE(K)); TERN_(U_HAS_STEALTHCHOP, SET_STEPPING_MODE(U)); TERN_(V_HAS_STEALTHCHOP, SET_STEPPING_MODE(V)); TERN_(W_HAS_STEALTHCHOP, SET_STEPPING_MODE(W)); TERN_(X2_HAS_STEALTHCHOP, SET_STEPPING_MODE(X2)); TERN_(Y2_HAS_STEALTHCHOP, SET_STEPPING_MODE(Y2)); TERN_(Z2_HAS_STEALTHCHOP, SET_STEPPING_MODE(Z2)); TERN_(Z3_HAS_STEALTHCHOP, SET_STEPPING_MODE(Z3)); TERN_(Z4_HAS_STEALTHCHOP, SET_STEPPING_MODE(Z4)); TERN_(E0_HAS_STEALTHCHOP, SET_STEPPING_MODE(E0)); TERN_(E1_HAS_STEALTHCHOP, SET_STEPPING_MODE(E1)); TERN_(E2_HAS_STEALTHCHOP, SET_STEPPING_MODE(E2)); TERN_(E3_HAS_STEALTHCHOP, SET_STEPPING_MODE(E3)); TERN_(E4_HAS_STEALTHCHOP, SET_STEPPING_MODE(E4)); TERN_(E5_HAS_STEALTHCHOP, SET_STEPPING_MODE(E5)); TERN_(E6_HAS_STEALTHCHOP, SET_STEPPING_MODE(E6)); TERN_(E7_HAS_STEALTHCHOP, SET_STEPPING_MODE(E7)); } #endif } // // Linear Advance // { float extruder_advance_K[DISTINCT_E]; _FIELD_TEST(planner_extruder_advance_K); EEPROM_READ(extruder_advance_K); #if ENABLED(LIN_ADVANCE) if (!validating) COPY(planner.extruder_advance_K, extruder_advance_K); #endif } // // Motor Current PWM // { _FIELD_TEST(motor_current_setting); uint32_t motor_current_setting[MOTOR_CURRENT_COUNT] #if HAS_MOTOR_CURRENT_SPI = DIGIPOT_MOTOR_CURRENT #endif ; #if HAS_MOTOR_CURRENT_SPI DEBUG_ECHO_MSG("DIGIPOTS Loading"); #endif EEPROM_READ(motor_current_setting); #if HAS_MOTOR_CURRENT_SPI DEBUG_ECHO_MSG("DIGIPOTS Loaded"); #endif #if HAS_MOTOR_CURRENT_SPI || HAS_MOTOR_CURRENT_PWM if (!validating) COPY(stepper.motor_current_setting, motor_current_setting); #endif } // // Adaptive Step Smoothing state // #if ENABLED(ADAPTIVE_STEP_SMOOTHING_TOGGLE) EEPROM_READ(stepper.adaptive_step_smoothing_enabled); #endif // // CNC Coordinate System // #if NUM_AXES { _FIELD_TEST(coordinate_system); #if ENABLED(CNC_COORDINATE_SYSTEMS) if (!validating) (void)gcode.select_coordinate_system(-1); // Go back to machine space EEPROM_READ(gcode.coordinate_system); #else xyz_pos_t coordinate_system[MAX_COORDINATE_SYSTEMS]; EEPROM_READ(coordinate_system); #endif } #endif // // Skew correction factors // #if ENABLED(SKEW_CORRECTION) { skew_factor_t skew_factor; _FIELD_TEST(planner_skew_factor); EEPROM_READ(skew_factor); #if ENABLED(SKEW_CORRECTION_GCODE) if (!validating) { planner.skew_factor.xy = skew_factor.xy; #if ENABLED(SKEW_CORRECTION_FOR_Z) planner.skew_factor.xz = skew_factor.xz; planner.skew_factor.yz = skew_factor.yz; #endif } #endif } #endif // // Advanced Pause filament load & unload lengths // #if ENABLED(CONFIGURE_FILAMENT_CHANGE) { _FIELD_TEST(fc_settings); EEPROM_READ(fc_settings); } #endif // // Tool-change settings // #if HAS_MULTI_EXTRUDER _FIELD_TEST(toolchange_settings); EEPROM_READ(toolchange_settings); #endif // // Backlash Compensation // #if NUM_AXES { xyz_float_t backlash_distance_mm; uint8_t backlash_correction; float backlash_smoothing_mm; _FIELD_TEST(backlash_distance_mm); EEPROM_READ(backlash_distance_mm); EEPROM_READ(backlash_correction); EEPROM_READ(backlash_smoothing_mm); #if ENABLED(BACKLASH_GCODE) if (!validating) { LOOP_NUM_AXES(axis) backlash.set_distance_mm((AxisEnum)axis, backlash_distance_mm[axis]); backlash.set_correction_uint8(backlash_correction); #ifdef BACKLASH_SMOOTHING_MM backlash.set_smoothing_mm(backlash_smoothing_mm); #endif } #endif } #endif // NUM_AXES // // Extensible UI User Data // #if ENABLED(EXTENSIBLE_UI) { // This is a significant hardware change; don't reserve EEPROM space when not present const char extui_data[ExtUI::eeprom_data_size] = { 0 }; _FIELD_TEST(extui_data); EEPROM_READ(extui_data); if (!validating) ExtUI::onLoadSettings(extui_data); } #endif // // JyersUI User Data // #if ENABLED(DWIN_CREALITY_LCD_JYERSUI) { const char dwin_settings[jyersDWIN.eeprom_data_size] = { 0 }; _FIELD_TEST(dwin_settings); EEPROM_READ(dwin_settings); if (!validating) jyersDWIN.loadSettings(dwin_settings); } #endif // // Case Light Brightness // #if CASELIGHT_USES_BRIGHTNESS _FIELD_TEST(caselight_brightness); EEPROM_READ(caselight.brightness); #endif // // Password feature // #if ENABLED(PASSWORD_FEATURE) _FIELD_TEST(password_is_set); EEPROM_READ(password.is_set); EEPROM_READ(password.value); #endif // // TOUCH_SCREEN_CALIBRATION // #if ENABLED(TOUCH_SCREEN_CALIBRATION) _FIELD_TEST(touch_calibration_data); EEPROM_READ(touch_calibration.calibration); #endif // // Ethernet network info // #if HAS_ETHERNET _FIELD_TEST(ethernet_hardware_enabled); uint32_t ethernet_ip, ethernet_dns, ethernet_gateway, ethernet_subnet; EEPROM_READ(ethernet.hardware_enabled); EEPROM_READ(ethernet_ip); ethernet.ip = ethernet_ip; EEPROM_READ(ethernet_dns); ethernet.myDns = ethernet_dns; EEPROM_READ(ethernet_gateway); ethernet.gateway = ethernet_gateway; EEPROM_READ(ethernet_subnet); ethernet.subnet = ethernet_subnet; #endif // // Buzzer enable/disable // #if ENABLED(SOUND_MENU_ITEM) _FIELD_TEST(sound_on); EEPROM_READ(ui.sound_on); #endif // // Fan tachometer check // #if HAS_FANCHECK _FIELD_TEST(fan_check_enabled); EEPROM_READ(fan_check.enabled); #endif // // MKS UI controller // #if DGUS_LCD_UI_MKS _FIELD_TEST(mks_language_index); EEPROM_READ(mks_language_index); EEPROM_READ(mks_corner_offsets); EEPROM_READ(mks_park_pos); EEPROM_READ(mks_min_extrusion_temp); #endif // // Selected LCD language // #if HAS_MULTI_LANGUAGE { uint8_t ui_language; EEPROM_READ(ui_language); if (ui_language >= NUM_LANGUAGES) ui_language = 0; if (!validating) ui.set_language(ui_language); } #endif // // Model predictive control // #if ENABLED(MPCTEMP) HOTEND_LOOP() EEPROM_READ(thermalManager.temp_hotend[e].mpc); #endif // // Fixed-Time Motion // #if ENABLED(FT_MOTION) _FIELD_TEST(ftMotion_cfg); EEPROM_READ(ftMotion.cfg); #endif // // Input Shaping // #if ENABLED(INPUT_SHAPING_X) { float _data[2]; EEPROM_READ(_data); if (!validating) { stepper.set_shaping_frequency(X_AXIS, _data[0]); stepper.set_shaping_damping_ratio(X_AXIS, _data[1]); } } #endif #if ENABLED(INPUT_SHAPING_Y) { float _data[2]; EEPROM_READ(_data); if (!validating) { stepper.set_shaping_frequency(Y_AXIS, _data[0]); stepper.set_shaping_damping_ratio(Y_AXIS, _data[1]); } } #endif // // HOTEND_IDLE_TIMEOUT // #if ENABLED(HOTEND_IDLE_TIMEOUT) EEPROM_READ(hotend_idle.cfg); #endif // // Nonlinear Extrusion // #if ENABLED(NONLINEAR_EXTRUSION) EEPROM_READ(stepper.ne); #endif // // Validate Final Size and CRC // const uint16_t eeprom_total = eeprom_index - (EEPROM_OFFSET); if ((eeprom_error = size_error(eeprom_total))) { // Handle below and on return break; } else if (working_crc != stored_crc) { eeprom_error = ERR_EEPROM_CRC; break; } else if (!validating) { DEBUG_ECHO_START(); DEBUG_ECHO(version); DEBUG_ECHOLNPGM(" stored settings retrieved (", eeprom_total, " bytes; crc ", working_crc, ")"); TERN_(HOST_EEPROM_CHITCHAT, hostui.notify(F("Stored settings retrieved"))); } #if ENABLED(AUTO_BED_LEVELING_UBL) if (!validating) { bedlevel.report_state(); if (!bedlevel.sanity_check()) { #if ALL(EEPROM_CHITCHAT, DEBUG_LEVELING_FEATURE) bedlevel.echo_name(); DEBUG_ECHOLNPGM(" initialized.\n"); #endif } else { eeprom_error = ERR_EEPROM_CORRUPT; #if ALL(EEPROM_CHITCHAT, DEBUG_LEVELING_FEATURE) DEBUG_ECHOPGM("?Can't enable "); bedlevel.echo_name(); DEBUG_ECHOLNPGM("."); #endif bedlevel.reset(); } if (bedlevel.storage_slot >= 0) { load_mesh(bedlevel.storage_slot); DEBUG_ECHOLNPGM("Mesh ", bedlevel.storage_slot, " loaded from storage."); } else { bedlevel.reset(); DEBUG_ECHOLNPGM("UBL reset"); } } #endif } while(0); EEPROM_FINISH(); switch (eeprom_error) { case ERR_EEPROM_NOERR: if (!validating) postprocess(); break; case ERR_EEPROM_SIZE: DEBUG_ECHO_MSG("Index: ", eeprom_index - (EEPROM_OFFSET), " Size: ", datasize()); break; case ERR_EEPROM_CORRUPT: DEBUG_WARN_MSG(STR_ERR_EEPROM_CORRUPT); break; case ERR_EEPROM_CRC: DEBUG_WARN_MSG("EEPROM CRC mismatch - (stored) ", stored_crc, " != ", working_crc, " (calculated)!"); TERN_(HOST_EEPROM_CHITCHAT, hostui.notify(GET_TEXT_F(MSG_ERR_EEPROM_CRC))); break; default: break; } #if ENABLED(EEPROM_CHITCHAT) && DISABLED(DISABLE_M503) // Report the EEPROM settings if (!validating && TERN1(EEPROM_BOOT_SILENT, IsRunning())) report(); #endif return eeprom_error; } #ifdef ARCHIM2_SPI_FLASH_EEPROM_BACKUP_SIZE extern bool restoreEEPROM(); #endif bool MarlinSettings::validate() { validating = true; #ifdef ARCHIM2_SPI_FLASH_EEPROM_BACKUP_SIZE EEPROM_Error err = _load(); if (err != ERR_EEPROM_NOERR && restoreEEPROM()) { SERIAL_ECHOLNPGM("Recovered backup EEPROM settings from SPI Flash"); err = _load(); } #else const EEPROM_Error err = _load(); #endif validating = false; if (err) ui.eeprom_alert(err); return (err == ERR_EEPROM_NOERR); } bool MarlinSettings::load() { if (validate()) { const EEPROM_Error err = _load(); const bool success = (err == ERR_EEPROM_NOERR); TERN_(EXTENSIBLE_UI, ExtUI::onSettingsLoaded(success)); return success; } reset(); #if ANY(EEPROM_AUTO_INIT, EEPROM_INIT_NOW) (void)save(); SERIAL_ECHO_MSG("EEPROM Initialized"); #endif return false; } #if ENABLED(AUTO_BED_LEVELING_UBL) inline void ubl_invalid_slot(const int s) { DEBUG_ECHOLNPGM("?Invalid slot.\n", s, " mesh slots available."); UNUSED(s); } // 128 (+1 because of the change to capacity rather than last valid address) // is a placeholder for the size of the MAT; the MAT will always // live at the very end of the eeprom const uint16_t MarlinSettings::meshes_end = persistentStore.capacity() - 129; uint16_t MarlinSettings::meshes_start_index() { // Pad the end of configuration data so it can float up // or down a little bit without disrupting the mesh data return (datasize() + EEPROM_OFFSET + 32) & 0xFFF8; } #define MESH_STORE_SIZE sizeof(TERN(OPTIMIZED_MESH_STORAGE, mesh_store_t, bedlevel.z_values)) uint16_t MarlinSettings::calc_num_meshes() { return (meshes_end - meshes_start_index()) / MESH_STORE_SIZE; } int MarlinSettings::mesh_slot_offset(const int8_t slot) { return meshes_end - (slot + 1) * MESH_STORE_SIZE; } void MarlinSettings::store_mesh(const int8_t slot) { #if ENABLED(AUTO_BED_LEVELING_UBL) const int16_t a = calc_num_meshes(); if (!WITHIN(slot, 0, a - 1)) { ubl_invalid_slot(a); DEBUG_ECHOLNPGM("E2END=", persistentStore.capacity() - 1, " meshes_end=", meshes_end, " slot=", slot); DEBUG_EOL(); return; } int pos = mesh_slot_offset(slot); uint16_t crc = 0; #if ENABLED(OPTIMIZED_MESH_STORAGE) int16_t z_mesh_store[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y]; bedlevel.set_store_from_mesh(bedlevel.z_values, z_mesh_store); uint8_t * const src = (uint8_t*)&z_mesh_store; #else uint8_t * const src = (uint8_t*)&bedlevel.z_values; #endif // Write crc to MAT along with other data, or just tack on to the beginning or end persistentStore.access_start(); const bool status = persistentStore.write_data(pos, src, MESH_STORE_SIZE, &crc); persistentStore.access_finish(); if (status) SERIAL_ECHOLNPGM("?Unable to save mesh data."); else DEBUG_ECHOLNPGM("Mesh saved in slot ", slot); #else // Other mesh types #endif } void MarlinSettings::load_mesh(const int8_t slot, void * const into/*=nullptr*/) { #if ENABLED(AUTO_BED_LEVELING_UBL) const int16_t a = settings.calc_num_meshes(); if (!WITHIN(slot, 0, a - 1)) { ubl_invalid_slot(a); return; } int pos = mesh_slot_offset(slot); uint16_t crc = 0; #if ENABLED(OPTIMIZED_MESH_STORAGE) int16_t z_mesh_store[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y]; uint8_t * const dest = (uint8_t*)&z_mesh_store; #else uint8_t * const dest = into ? (uint8_t*)into : (uint8_t*)&bedlevel.z_values; #endif persistentStore.access_start(); uint16_t status = persistentStore.read_data(pos, dest, MESH_STORE_SIZE, &crc); persistentStore.access_finish(); #if ENABLED(OPTIMIZED_MESH_STORAGE) if (into) { float z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y]; bedlevel.set_mesh_from_store(z_mesh_store, z_values); memcpy(into, z_values, sizeof(z_values)); } else bedlevel.set_mesh_from_store(z_mesh_store, bedlevel.z_values); #endif #if ENABLED(DWIN_LCD_PROUI) status = !bedLevelTools.meshValidate(); if (status) { bedlevel.invalidate(); LCD_MESSAGE(MSG_UBL_MESH_INVALID); } else ui.status_printf(0, GET_TEXT_F(MSG_MESH_LOADED), bedlevel.storage_slot); #endif if (status) SERIAL_ECHOLNPGM("?Unable to load mesh data."); else DEBUG_ECHOLNPGM("Mesh loaded from slot ", slot); EEPROM_FINISH(); #else // Other mesh types #endif } //void MarlinSettings::delete_mesh() { return; } //void MarlinSettings::defrag_meshes() { return; } #endif // AUTO_BED_LEVELING_UBL #else // !EEPROM_SETTINGS bool MarlinSettings::save() { DEBUG_WARN_MSG("EEPROM disabled"); return false; } #endif // !EEPROM_SETTINGS /** * M502 - Reset Configuration */ void MarlinSettings::reset() { LOOP_DISTINCT_AXES(i) { planner.settings.max_acceleration_mm_per_s2[i] = pgm_read_dword(&_DMA[ALIM(i, _DMA)]); #if ENABLED(EDITABLE_STEPS_PER_UNIT) planner.settings.axis_steps_per_mm[i] = pgm_read_float(&_DASU[ALIM(i, _DASU)]); #endif planner.settings.max_feedrate_mm_s[i] = pgm_read_float(&_DMF[ALIM(i, _DMF)]); } planner.settings.min_segment_time_us = DEFAULT_MINSEGMENTTIME; planner.settings.acceleration = DEFAULT_ACCELERATION; planner.settings.retract_acceleration = DEFAULT_RETRACT_ACCELERATION; planner.settings.travel_acceleration = DEFAULT_TRAVEL_ACCELERATION; planner.settings.min_feedrate_mm_s = feedRate_t(DEFAULT_MINIMUMFEEDRATE); planner.settings.min_travel_feedrate_mm_s = feedRate_t(DEFAULT_MINTRAVELFEEDRATE); #if ENABLED(CLASSIC_JERK) #if HAS_X_AXIS && !defined(DEFAULT_XJERK) #define DEFAULT_XJERK 0 #endif #if HAS_Y_AXIS && !defined(DEFAULT_YJERK) #define DEFAULT_YJERK 0 #endif #if HAS_Z_AXIS && !defined(DEFAULT_ZJERK) #define DEFAULT_ZJERK 0 #endif #if HAS_I_AXIS && !defined(DEFAULT_IJERK) #define DEFAULT_IJERK 0 #endif #if HAS_J_AXIS && !defined(DEFAULT_JJERK) #define DEFAULT_JJERK 0 #endif #if HAS_K_AXIS && !defined(DEFAULT_KJERK) #define DEFAULT_KJERK 0 #endif #if HAS_U_AXIS && !defined(DEFAULT_UJERK) #define DEFAULT_UJERK 0 #endif #if HAS_V_AXIS && !defined(DEFAULT_VJERK) #define DEFAULT_VJERK 0 #endif #if HAS_W_AXIS && !defined(DEFAULT_WJERK) #define DEFAULT_WJERK 0 #endif planner.max_jerk.set( NUM_AXIS_LIST(DEFAULT_XJERK, DEFAULT_YJERK, DEFAULT_ZJERK, DEFAULT_IJERK, DEFAULT_JJERK, DEFAULT_KJERK, DEFAULT_UJERK, DEFAULT_VJERK, DEFAULT_WJERK) ); TERN_(HAS_CLASSIC_E_JERK, planner.max_jerk.e = DEFAULT_EJERK); #endif TERN_(HAS_JUNCTION_DEVIATION, planner.junction_deviation_mm = float(JUNCTION_DEVIATION_MM)); #if HAS_SCARA_OFFSET scara_home_offset.reset(); #elif HAS_HOME_OFFSET home_offset.reset(); #endif TERN_(HAS_HOTEND_OFFSET, reset_hotend_offsets()); // // Filament Runout Sensor // #if HAS_FILAMENT_SENSOR runout.enabled = FIL_RUNOUT_ENABLED_DEFAULT; runout.reset(); TERN_(HAS_FILAMENT_RUNOUT_DISTANCE, runout.set_runout_distance(FILAMENT_RUNOUT_DISTANCE_MM)); #endif // // Tool-change Settings // #if HAS_MULTI_EXTRUDER #if ENABLED(TOOLCHANGE_FILAMENT_SWAP) toolchange_settings.swap_length = TOOLCHANGE_FS_LENGTH; toolchange_settings.extra_resume = TOOLCHANGE_FS_EXTRA_RESUME_LENGTH; toolchange_settings.retract_speed = TOOLCHANGE_FS_RETRACT_SPEED; toolchange_settings.unretract_speed = TOOLCHANGE_FS_UNRETRACT_SPEED; toolchange_settings.extra_prime = TOOLCHANGE_FS_EXTRA_PRIME; toolchange_settings.prime_speed = TOOLCHANGE_FS_PRIME_SPEED; toolchange_settings.wipe_retract = TOOLCHANGE_FS_WIPE_RETRACT; toolchange_settings.fan_speed = TOOLCHANGE_FS_FAN_SPEED; toolchange_settings.fan_time = TOOLCHANGE_FS_FAN_TIME; #endif #if ENABLED(TOOLCHANGE_FS_PRIME_FIRST_USED) enable_first_prime = false; #endif #if ENABLED(TOOLCHANGE_PARK) constexpr xyz_pos_t tpxy = TOOLCHANGE_PARK_XY; toolchange_settings.enable_park = true; toolchange_settings.change_point = tpxy; #endif toolchange_settings.z_raise = TOOLCHANGE_ZRAISE; #if ENABLED(TOOLCHANGE_MIGRATION_FEATURE) migration = migration_defaults; #endif #endif #if ENABLED(BACKLASH_GCODE) backlash.set_correction(BACKLASH_CORRECTION); constexpr xyz_float_t tmp = BACKLASH_DISTANCE_MM; LOOP_NUM_AXES(axis) backlash.set_distance_mm((AxisEnum)axis, tmp[axis]); #ifdef BACKLASH_SMOOTHING_MM backlash.set_smoothing_mm(BACKLASH_SMOOTHING_MM); #endif #endif TERN_(DWIN_CREALITY_LCD_JYERSUI, jyersDWIN.resetSettings()); // // Case Light Brightness // TERN_(CASELIGHT_USES_BRIGHTNESS, caselight.brightness = CASE_LIGHT_DEFAULT_BRIGHTNESS); // // TOUCH_SCREEN_CALIBRATION // TERN_(TOUCH_SCREEN_CALIBRATION, touch_calibration.calibration_reset()); // // Buzzer enable/disable // #if ENABLED(SOUND_MENU_ITEM) ui.sound_on = ENABLED(SOUND_ON_DEFAULT); #endif // // Magnetic Parking Extruder // TERN_(MAGNETIC_PARKING_EXTRUDER, mpe_settings_init()); // // Global Leveling // TERN_(ENABLE_LEVELING_FADE_HEIGHT, new_z_fade_height = (DEFAULT_LEVELING_FADE_HEIGHT)); TERN_(HAS_LEVELING, reset_bed_level()); // // AUTOTEMP // #if ENABLED(AUTOTEMP) planner.autotemp.max = AUTOTEMP_MAX; planner.autotemp.min = AUTOTEMP_MIN; planner.autotemp.factor = AUTOTEMP_FACTOR; #endif // // X Axis Twist Compensation // TERN_(X_AXIS_TWIST_COMPENSATION, xatc.reset()); // // Nozzle-to-probe Offset // #if HAS_BED_PROBE constexpr float dpo[] = NOZZLE_TO_PROBE_OFFSET; static_assert(COUNT(dpo) == NUM_AXES, "NOZZLE_TO_PROBE_OFFSET must contain offsets for each linear axis X, Y, Z...."); #if HAS_PROBE_XY_OFFSET LOOP_NUM_AXES(a) probe.offset[a] = dpo[a]; #else probe.offset.set(NUM_AXIS_LIST(0, 0, dpo[Z_AXIS], 0, 0, 0, 0, 0, 0)); #endif #endif // // Z Stepper Auto-alignment points // TERN_(Z_STEPPER_AUTO_ALIGN, z_stepper_align.reset_to_default()); // // Servo Angles // TERN_(EDITABLE_SERVO_ANGLES, COPY(servo_angles, base_servo_angles)); // When not editable only one copy of servo angles exists // // Probe Temperature Compensation // TERN_(HAS_PTC, ptc.reset()); // // BLTouch // TERN_(HAS_BLTOUCH_HS_MODE, bltouch.high_speed_mode = BLTOUCH_HS_MODE); // // Kinematic Settings (Delta, SCARA, TPARA, Polargraph...) // #if IS_KINEMATIC segments_per_second = DEFAULT_SEGMENTS_PER_SECOND; #if ENABLED(DELTA) const abc_float_t adj = DELTA_ENDSTOP_ADJ, dta = DELTA_TOWER_ANGLE_TRIM, ddr = DELTA_DIAGONAL_ROD_TRIM_TOWER; delta_height = DELTA_HEIGHT; delta_endstop_adj = adj; delta_radius = DELTA_RADIUS; delta_diagonal_rod = DELTA_DIAGONAL_ROD; delta_tower_angle_trim = dta; delta_diagonal_rod_trim = ddr; #elif ENABLED(POLARGRAPH) draw_area_min.set(X_MIN_POS, Y_MIN_POS); draw_area_max.set(X_MAX_POS, Y_MAX_POS); polargraph_max_belt_len = POLARGRAPH_MAX_BELT_LEN; #endif #endif // // Endstop Adjustments // #if ENABLED(X_DUAL_ENDSTOPS) #ifndef X2_ENDSTOP_ADJUSTMENT #define X2_ENDSTOP_ADJUSTMENT 0 #endif endstops.x2_endstop_adj = X2_ENDSTOP_ADJUSTMENT; #endif #if ENABLED(Y_DUAL_ENDSTOPS) #ifndef Y2_ENDSTOP_ADJUSTMENT #define Y2_ENDSTOP_ADJUSTMENT 0 #endif endstops.y2_endstop_adj = Y2_ENDSTOP_ADJUSTMENT; #endif #if ENABLED(Z_MULTI_ENDSTOPS) #ifndef Z2_ENDSTOP_ADJUSTMENT #define Z2_ENDSTOP_ADJUSTMENT 0 #endif endstops.z2_endstop_adj = Z2_ENDSTOP_ADJUSTMENT; #if NUM_Z_STEPPERS >= 3 #ifndef Z3_ENDSTOP_ADJUSTMENT #define Z3_ENDSTOP_ADJUSTMENT 0 #endif endstops.z3_endstop_adj = Z3_ENDSTOP_ADJUSTMENT; #endif #if NUM_Z_STEPPERS >= 4 #ifndef Z4_ENDSTOP_ADJUSTMENT #define Z4_ENDSTOP_ADJUSTMENT 0 #endif endstops.z4_endstop_adj = Z4_ENDSTOP_ADJUSTMENT; #endif #endif // // Preheat parameters // #if HAS_PREHEAT #define _PITEM(N,T) PREHEAT_##N##_##T, #if HAS_HOTEND constexpr uint16_t hpre[] = { REPEAT2_S(1, INCREMENT(PREHEAT_COUNT), _PITEM, TEMP_HOTEND) }; #endif #if HAS_HEATED_BED constexpr uint16_t bpre[] = { REPEAT2_S(1, INCREMENT(PREHEAT_COUNT), _PITEM, TEMP_BED) }; #endif #if HAS_FAN constexpr uint8_t fpre[] = { REPEAT2_S(1, INCREMENT(PREHEAT_COUNT), _PITEM, FAN_SPEED) }; #endif for (uint8_t i = 0; i < PREHEAT_COUNT; ++i) { TERN_(HAS_HOTEND, ui.material_preset[i].hotend_temp = hpre[i]); TERN_(HAS_HEATED_BED, ui.material_preset[i].bed_temp = bpre[i]); TERN_(HAS_FAN, ui.material_preset[i].fan_speed = fpre[i]); } #endif // // Hotend PID // #if ENABLED(PIDTEMP) #if ENABLED(PID_PARAMS_PER_HOTEND) constexpr float defKp[] = #ifdef DEFAULT_Kp_LIST DEFAULT_Kp_LIST #else ARRAY_BY_HOTENDS1(DEFAULT_Kp) #endif , defKi[] = #ifdef DEFAULT_Ki_LIST DEFAULT_Ki_LIST #else ARRAY_BY_HOTENDS1(DEFAULT_Ki) #endif , defKd[] = #ifdef DEFAULT_Kd_LIST DEFAULT_Kd_LIST #else ARRAY_BY_HOTENDS1(DEFAULT_Kd) #endif ; static_assert(WITHIN(COUNT(defKp), 1, HOTENDS), "DEFAULT_Kp_LIST must have between 1 and HOTENDS items."); static_assert(WITHIN(COUNT(defKi), 1, HOTENDS), "DEFAULT_Ki_LIST must have between 1 and HOTENDS items."); static_assert(WITHIN(COUNT(defKd), 1, HOTENDS), "DEFAULT_Kd_LIST must have between 1 and HOTENDS items."); #if ENABLED(PID_EXTRUSION_SCALING) constexpr float defKc[] = #ifdef DEFAULT_Kc_LIST DEFAULT_Kc_LIST #else ARRAY_BY_HOTENDS1(DEFAULT_Kc) #endif ; static_assert(WITHIN(COUNT(defKc), 1, HOTENDS), "DEFAULT_Kc_LIST must have between 1 and HOTENDS items."); #endif #if ENABLED(PID_FAN_SCALING) constexpr float defKf[] = #ifdef DEFAULT_Kf_LIST DEFAULT_Kf_LIST #else ARRAY_BY_HOTENDS1(DEFAULT_Kf) #endif ; static_assert(WITHIN(COUNT(defKf), 1, HOTENDS), "DEFAULT_Kf_LIST must have between 1 and HOTENDS items."); #endif #define PID_DEFAULT(N,E) def##N[E] #else #define PID_DEFAULT(N,E) DEFAULT_##N #endif HOTEND_LOOP() { thermalManager.temp_hotend[e].pid.set( PID_DEFAULT(Kp, ALIM(e, defKp)), PID_DEFAULT(Ki, ALIM(e, defKi)), PID_DEFAULT(Kd, ALIM(e, defKd)) OPTARG(PID_EXTRUSION_SCALING, PID_DEFAULT(Kc, ALIM(e, defKc))) OPTARG(PID_FAN_SCALING, PID_DEFAULT(Kf, ALIM(e, defKf))) ); } #endif // // PID Extrusion Scaling // TERN_(PID_EXTRUSION_SCALING, thermalManager.lpq_len = 20); // Default last-position-queue size // // Heated Bed PID // #if ENABLED(PIDTEMPBED) thermalManager.temp_bed.pid.set(DEFAULT_bedKp, DEFAULT_bedKi, DEFAULT_bedKd); #endif // // Heated Chamber PID // #if ENABLED(PIDTEMPCHAMBER) thermalManager.temp_chamber.pid.set(DEFAULT_chamberKp, DEFAULT_chamberKi, DEFAULT_chamberKd); #endif // // User-Defined Thermistors // TERN_(HAS_USER_THERMISTORS, thermalManager.reset_user_thermistors()); // // Power Monitor // TERN_(POWER_MONITOR, power_monitor.reset()); // // LCD Contrast // TERN_(HAS_LCD_CONTRAST, ui.contrast = LCD_CONTRAST_DEFAULT); // // LCD Brightness // TERN_(HAS_LCD_BRIGHTNESS, ui.brightness = LCD_BRIGHTNESS_DEFAULT); // // LCD Backlight / Sleep Timeout // #if ENABLED(EDITABLE_DISPLAY_TIMEOUT) #if HAS_BACKLIGHT_TIMEOUT ui.backlight_timeout_minutes = LCD_BACKLIGHT_TIMEOUT_MINS; #elif HAS_DISPLAY_SLEEP ui.sleep_timeout_minutes = DISPLAY_SLEEP_MINUTES; #endif #endif // // Controller Fan // TERN_(USE_CONTROLLER_FAN, controllerFan.reset()); // // Power-Loss Recovery // #if ENABLED(POWER_LOSS_RECOVERY) recovery.enable(ENABLED(PLR_ENABLED_DEFAULT)); TERN_(HAS_PLR_BED_THRESHOLD, recovery.bed_temp_threshold = PLR_BED_THRESHOLD); #endif // // Firmware Retraction // TERN_(FWRETRACT, fwretract.reset()); // // Volumetric & Filament Size // #if DISABLED(NO_VOLUMETRICS) parser.volumetric_enabled = ENABLED(VOLUMETRIC_DEFAULT_ON); for (uint8_t q = 0; q < COUNT(planner.filament_size); ++q) planner.filament_size[q] = DEFAULT_NOMINAL_FILAMENT_DIA; #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT) for (uint8_t q = 0; q < COUNT(planner.volumetric_extruder_limit); ++q) planner.volumetric_extruder_limit[q] = DEFAULT_VOLUMETRIC_EXTRUDER_LIMIT; #endif #endif endstops.enable_globally(ENABLED(ENDSTOPS_ALWAYS_ON_DEFAULT)); reset_stepper_drivers(); // // Linear Advance // #if ENABLED(LIN_ADVANCE) #if ENABLED(DISTINCT_E_FACTORS) constexpr float linAdvanceK[] = ADVANCE_K; EXTRUDER_LOOP() { const float a = linAdvanceK[_MAX(uint8_t(e), COUNT(linAdvanceK) - 1)]; planner.extruder_advance_K[e] = a; TERN_(ADVANCE_K_EXTRA, other_extruder_advance_K[e] = a); } #else planner.extruder_advance_K[0] = ADVANCE_K; #endif #endif // // Motor Current PWM // #if HAS_MOTOR_CURRENT_PWM constexpr uint32_t tmp_motor_current_setting[MOTOR_CURRENT_COUNT] = PWM_MOTOR_CURRENT; for (uint8_t q = 0; q < MOTOR_CURRENT_COUNT; ++q) stepper.set_digipot_current(q, (stepper.motor_current_setting[q] = tmp_motor_current_setting[q])); #endif // // DIGIPOTS // #if HAS_MOTOR_CURRENT_SPI static constexpr uint32_t tmp_motor_current_setting[] = DIGIPOT_MOTOR_CURRENT; DEBUG_ECHOLNPGM("Writing Digipot"); for (uint8_t q = 0; q < COUNT(tmp_motor_current_setting); ++q) stepper.set_digipot_current(q, tmp_motor_current_setting[q]); DEBUG_ECHOLNPGM("Digipot Written"); #endif // // Adaptive Step Smoothing state // #if ENABLED(ADAPTIVE_STEP_SMOOTHING_TOGGLE) stepper.adaptive_step_smoothing_enabled = true; #endif // // CNC Coordinate System // TERN_(CNC_COORDINATE_SYSTEMS, (void)gcode.select_coordinate_system(-1)); // Go back to machine space // // Skew Correction // #if ENABLED(SKEW_CORRECTION_GCODE) planner.skew_factor.xy = XY_SKEW_FACTOR; #if ENABLED(SKEW_CORRECTION_FOR_Z) planner.skew_factor.xz = XZ_SKEW_FACTOR; planner.skew_factor.yz = YZ_SKEW_FACTOR; #endif #endif // // Advanced Pause filament load & unload lengths // #if ENABLED(CONFIGURE_FILAMENT_CHANGE) EXTRUDER_LOOP() { fc_settings[e].unload_length = FILAMENT_CHANGE_UNLOAD_LENGTH; fc_settings[e].load_length = FILAMENT_CHANGE_FAST_LOAD_LENGTH; } #endif #if ENABLED(PASSWORD_FEATURE) #ifdef PASSWORD_DEFAULT_VALUE password.is_set = true; password.value = PASSWORD_DEFAULT_VALUE; #else password.is_set = false; #endif #endif // // Fan tachometer check // TERN_(HAS_FANCHECK, fan_check.enabled = true); // // MKS UI controller // TERN_(DGUS_LCD_UI_MKS, MKS_reset_settings()); // // Model predictive control // #if ENABLED(MPCTEMP) constexpr float _mpc_heater_power[] = MPC_HEATER_POWER; constexpr float _mpc_block_heat_capacity[] = MPC_BLOCK_HEAT_CAPACITY; constexpr float _mpc_sensor_responsiveness[] = MPC_SENSOR_RESPONSIVENESS; constexpr float _mpc_ambient_xfer_coeff[] = MPC_AMBIENT_XFER_COEFF; #if ENABLED(MPC_INCLUDE_FAN) constexpr float _mpc_ambient_xfer_coeff_fan255[] = MPC_AMBIENT_XFER_COEFF_FAN255; #endif constexpr float _filament_heat_capacity_permm[] = FILAMENT_HEAT_CAPACITY_PERMM; static_assert(COUNT(_mpc_heater_power) == HOTENDS, "MPC_HEATER_POWER must have HOTENDS items."); static_assert(COUNT(_mpc_block_heat_capacity) == HOTENDS, "MPC_BLOCK_HEAT_CAPACITY must have HOTENDS items."); static_assert(COUNT(_mpc_sensor_responsiveness) == HOTENDS, "MPC_SENSOR_RESPONSIVENESS must have HOTENDS items."); static_assert(COUNT(_mpc_ambient_xfer_coeff) == HOTENDS, "MPC_AMBIENT_XFER_COEFF must have HOTENDS items."); #if ENABLED(MPC_INCLUDE_FAN) static_assert(COUNT(_mpc_ambient_xfer_coeff_fan255) == HOTENDS, "MPC_AMBIENT_XFER_COEFF_FAN255 must have HOTENDS items."); #endif static_assert(COUNT(_filament_heat_capacity_permm) == HOTENDS, "FILAMENT_HEAT_CAPACITY_PERMM must have HOTENDS items."); HOTEND_LOOP() { MPC_t &mpc = thermalManager.temp_hotend[e].mpc; mpc.heater_power = _mpc_heater_power[e]; mpc.block_heat_capacity = _mpc_block_heat_capacity[e]; mpc.sensor_responsiveness = _mpc_sensor_responsiveness[e]; mpc.ambient_xfer_coeff_fan0 = _mpc_ambient_xfer_coeff[e]; #if ENABLED(MPC_INCLUDE_FAN) mpc.fan255_adjustment = _mpc_ambient_xfer_coeff_fan255[e] - _mpc_ambient_xfer_coeff[e]; #endif mpc.filament_heat_capacity_permm = _filament_heat_capacity_permm[e]; } #endif // // Fixed-Time Motion // TERN_(FT_MOTION, ftMotion.set_defaults()); // // Nonlinear Extrusion // TERN_(NONLINEAR_EXTRUSION, stepper.ne.reset()); // // Input Shaping // #if HAS_ZV_SHAPING #if ENABLED(INPUT_SHAPING_X) stepper.set_shaping_frequency(X_AXIS, SHAPING_FREQ_X); stepper.set_shaping_damping_ratio(X_AXIS, SHAPING_ZETA_X); #endif #if ENABLED(INPUT_SHAPING_Y) stepper.set_shaping_frequency(Y_AXIS, SHAPING_FREQ_Y); stepper.set_shaping_damping_ratio(Y_AXIS, SHAPING_ZETA_Y); #endif #endif // // Hotend Idle Timeout // TERN_(HOTEND_IDLE_TIMEOUT, hotend_idle.cfg.set_defaults()); postprocess(); #if ANY(EEPROM_CHITCHAT, DEBUG_LEVELING_FEATURE) FSTR_P const hdsl = F("Hardcoded Default Settings Loaded"); TERN_(HOST_EEPROM_CHITCHAT, hostui.notify(hdsl)); DEBUG_ECHO_START(); DEBUG_ECHOLN(hdsl); #endif TERN_(EXTENSIBLE_UI, ExtUI::onFactoryReset()); } #if DISABLED(DISABLE_M503) #define CONFIG_ECHO_START() gcode.report_echo_start(forReplay) #define CONFIG_ECHO_MSG(V...) do{ CONFIG_ECHO_START(); SERIAL_ECHOLNPGM(V); }while(0) #define CONFIG_ECHO_MSG_P(V...) do{ CONFIG_ECHO_START(); SERIAL_ECHOLNPGM_P(V); }while(0) #define CONFIG_ECHO_HEADING(STR) gcode.report_heading(forReplay, F(STR)) #if ENABLED(EDITABLE_STEPS_PER_UNIT) void M92_report(const bool echo=true, const int8_t e=-1); #endif /** * M503 - Report current settings in RAM * * Unless specifically disabled, M503 is available even without EEPROM */ void MarlinSettings::report(const bool forReplay) { // // Announce current units, in case inches are being displayed // CONFIG_ECHO_HEADING("Linear Units"); CONFIG_ECHO_START(); #if ENABLED(INCH_MODE_SUPPORT) SERIAL_ECHOPGM(" G2", AS_DIGIT(parser.linear_unit_factor == 1.0), " ;"); #else SERIAL_ECHOPGM(" G21 ;"); #endif gcode.say_units(); // " (in/mm)" // // M149 Temperature units // #if ENABLED(TEMPERATURE_UNITS_SUPPORT) gcode.M149_report(forReplay); #else CONFIG_ECHO_HEADING(STR_TEMPERATURE_UNITS); CONFIG_ECHO_MSG(" M149 C ; Units in Celsius"); #endif // // M200 Volumetric Extrusion // IF_DISABLED(NO_VOLUMETRICS, gcode.M200_report(forReplay)); // // M92 Steps per Unit // TERN_(EDITABLE_STEPS_PER_UNIT, gcode.M92_report(forReplay)); // // M203 Maximum feedrates (units/s) // gcode.M203_report(forReplay); // // M201 Maximum Acceleration (units/s2) // gcode.M201_report(forReplay); // // M204 Acceleration (units/s2) // gcode.M204_report(forReplay); // // M205 "Advanced" Settings // gcode.M205_report(forReplay); // // M206 Home Offset // TERN_(HAS_HOME_OFFSET, gcode.M206_report(forReplay)); // // M218 Hotend offsets // TERN_(HAS_HOTEND_OFFSET, gcode.M218_report(forReplay)); // // Bed Leveling // #if HAS_LEVELING gcode.M420_report(forReplay); #if ENABLED(MESH_BED_LEVELING) if (leveling_is_valid()) { for (uint8_t py = 0; py < GRID_MAX_POINTS_Y; ++py) { for (uint8_t px = 0; px < GRID_MAX_POINTS_X; ++px) { CONFIG_ECHO_START(); SERIAL_ECHOLN(F(" G29 S3 I"), px, F(" J"), py, FPSTR(SP_Z_STR), p_float_t(LINEAR_UNIT(bedlevel.z_values[px][py]), 5)); } } CONFIG_ECHO_START(); SERIAL_ECHOLNPGM(" G29 S4 Z", p_float_t(LINEAR_UNIT(bedlevel.z_offset), 5)); } #elif ENABLED(AUTO_BED_LEVELING_UBL) if (!forReplay) { SERIAL_EOL(); bedlevel.report_state(); SERIAL_ECHO_MSG("Active Mesh Slot ", bedlevel.storage_slot); SERIAL_ECHO_MSG("EEPROM can hold ", calc_num_meshes(), " meshes.\n"); } //bedlevel.report_current_mesh(); // This is too verbose for large meshes. A better (more terse) // solution needs to be found. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) if (leveling_is_valid()) { for (uint8_t py = 0; py < GRID_MAX_POINTS_Y; ++py) { for (uint8_t px = 0; px < GRID_MAX_POINTS_X; ++px) { CONFIG_ECHO_START(); SERIAL_ECHOLN(F(" G29 W I"), px, F(" J"), py, FPSTR(SP_Z_STR), p_float_t(LINEAR_UNIT(bedlevel.z_values[px][py]), 5)); } } } #endif #endif // HAS_LEVELING // // X Axis Twist Compensation // TERN_(X_AXIS_TWIST_COMPENSATION, gcode.M423_report(forReplay)); // // Editable Servo Angles // TERN_(EDITABLE_SERVO_ANGLES, gcode.M281_report(forReplay)); // // Kinematic Settings // TERN_(IS_KINEMATIC, gcode.M665_report(forReplay)); // // M666 Endstops Adjustment // #if ANY(DELTA, HAS_EXTRA_ENDSTOPS) gcode.M666_report(forReplay); #endif // // Z Auto-Align // TERN_(Z_STEPPER_AUTO_ALIGN, gcode.M422_report(forReplay)); // // LCD Preheat Settings // TERN_(HAS_PREHEAT, gcode.M145_report(forReplay)); // // PID // TERN_(PIDTEMP, gcode.M301_report(forReplay)); TERN_(PIDTEMPBED, gcode.M304_report(forReplay)); TERN_(PIDTEMPCHAMBER, gcode.M309_report(forReplay)); #if HAS_USER_THERMISTORS for (uint8_t i = 0; i < USER_THERMISTORS; ++i) thermalManager.M305_report(i, forReplay); #endif // // LCD Contrast // TERN_(HAS_LCD_CONTRAST, gcode.M250_report(forReplay)); // // Display Sleep // TERN_(EDITABLE_DISPLAY_TIMEOUT, gcode.M255_report(forReplay)); // // LCD Brightness // TERN_(HAS_LCD_BRIGHTNESS, gcode.M256_report(forReplay)); // // Controller Fan // TERN_(CONTROLLER_FAN_EDITABLE, gcode.M710_report(forReplay)); // // Power-Loss Recovery // TERN_(POWER_LOSS_RECOVERY, gcode.M413_report(forReplay)); // // Firmware Retraction // #if ENABLED(FWRETRACT) gcode.M207_report(forReplay); gcode.M208_report(forReplay); TERN_(FWRETRACT_AUTORETRACT, gcode.M209_report(forReplay)); #endif // // Probe Offset // TERN_(HAS_BED_PROBE, gcode.M851_report(forReplay)); // // Bed Skew Correction // TERN_(SKEW_CORRECTION_GCODE, gcode.M852_report(forReplay)); #if HAS_TRINAMIC_CONFIG // // TMC Stepper driver current // gcode.M906_report(forReplay); // // TMC Hybrid Threshold // TERN_(HYBRID_THRESHOLD, gcode.M913_report(forReplay)); // // TMC Sensorless homing thresholds // TERN_(USE_SENSORLESS, gcode.M914_report(forReplay)); #endif // // TMC stepping mode // TERN_(HAS_STEALTHCHOP, gcode.M569_report(forReplay)); // // Fixed-Time Motion // TERN_(FT_MOTION, gcode.M493_report(forReplay)); // // Nonlinear Extrusion // TERN_(NONLINEAR_EXTRUSION, gcode.M592_report(forReplay)); // // Input Shaping // TERN_(HAS_ZV_SHAPING, gcode.M593_report(forReplay)); // // Hotend Idle Timeout // TERN_(HOTEND_IDLE_TIMEOUT, gcode.M86_report(forReplay)); // // Linear Advance // TERN_(LIN_ADVANCE, gcode.M900_report(forReplay)); // // Motor Current (SPI or PWM) // #if HAS_MOTOR_CURRENT_SPI || HAS_MOTOR_CURRENT_PWM gcode.M907_report(forReplay); #endif // // Advanced Pause filament load & unload lengths // TERN_(CONFIGURE_FILAMENT_CHANGE, gcode.M603_report(forReplay)); // // Tool-changing Parameters // E_TERN_(gcode.M217_report(forReplay)); // // Backlash Compensation // TERN_(BACKLASH_GCODE, gcode.M425_report(forReplay)); // // Filament Runout Sensor // TERN_(HAS_FILAMENT_SENSOR, gcode.M412_report(forReplay)); #if HAS_ETHERNET CONFIG_ECHO_HEADING("Ethernet"); if (!forReplay) ETH0_report(); CONFIG_ECHO_START(); SERIAL_ECHO_SP(2); MAC_report(); CONFIG_ECHO_START(); SERIAL_ECHO_SP(2); gcode.M552_report(); CONFIG_ECHO_START(); SERIAL_ECHO_SP(2); gcode.M553_report(); CONFIG_ECHO_START(); SERIAL_ECHO_SP(2); gcode.M554_report(); #endif TERN_(HAS_MULTI_LANGUAGE, gcode.M414_report(forReplay)); // // Model predictive control // TERN_(MPCTEMP, gcode.M306_report(forReplay)); } #endif // !DISABLE_M503 #pragma pack(pop)
2301_81045437/Marlin
Marlin/src/module/settings.cpp
C++
agpl-3.0
116,449
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // // settings.cpp - Settings and EEPROM storage // #include "../inc/MarlinConfig.h" #if ENABLED(EEPROM_SETTINGS) #include "../HAL/shared/eeprom_api.h" enum EEPROM_Error : uint8_t { ERR_EEPROM_NOERR, ERR_EEPROM_VERSION, ERR_EEPROM_SIZE, ERR_EEPROM_CRC, ERR_EEPROM_CORRUPT }; #endif class MarlinSettings { public: static uint16_t datasize(); static void reset(); static bool save(); // Return 'true' if data was saved FORCE_INLINE static bool init_eeprom() { reset(); #if ENABLED(EEPROM_SETTINGS) const bool success = save(); if (TERN0(EEPROM_CHITCHAT, success)) report(); return success; #else return true; #endif } #if ENABLED(SD_FIRMWARE_UPDATE) static bool sd_update_status(); // True if the SD-Firmware-Update EEPROM flag is set static bool set_sd_update_status(const bool enable); // Return 'true' after EEPROM is set (-> always true) #endif #if ENABLED(EEPROM_SETTINGS) static bool load(); // Return 'true' if data was loaded ok static bool validate(); // Return 'true' if EEPROM data is ok static void first_load() { static bool loaded = false; if (!loaded && load()) loaded = true; } #if ENABLED(AUTO_BED_LEVELING_UBL) // Eventually make these available if any leveling system // That can store is enabled static uint16_t meshes_start_index(); FORCE_INLINE static uint16_t meshes_end_index() { return meshes_end; } static uint16_t calc_num_meshes(); static int mesh_slot_offset(const int8_t slot); static void store_mesh(const int8_t slot); static void load_mesh(const int8_t slot, void * const into=nullptr); //static void delete_mesh(); // necessary if we have a MAT //static void defrag_meshes(); // " #endif #else // !EEPROM_SETTINGS FORCE_INLINE static bool load() { reset(); report(); return true; } FORCE_INLINE static void first_load() { (void)load(); } #endif // !EEPROM_SETTINGS #if DISABLED(DISABLE_M503) static void report(const bool forReplay=false); #else FORCE_INLINE static void report(const bool=false) {} #endif private: static void postprocess(); #if ENABLED(EEPROM_SETTINGS) static bool validating; #if ENABLED(AUTO_BED_LEVELING_UBL) // Eventually make these available if any leveling system // That can store is enabled static const uint16_t meshes_end; // 128 is a placeholder for the size of the MAT; the MAT will always // live at the very end of the eeprom #endif static EEPROM_Error _load(); static EEPROM_Error size_error(const uint16_t size); static int eeprom_index; static uint16_t working_crc; static bool EEPROM_START(int eeprom_offset) { if (!persistentStore.access_start()) { SERIAL_ECHO_MSG("No EEPROM."); return false; } eeprom_index = eeprom_offset; working_crc = 0; return true; } static void EEPROM_FINISH(void) { persistentStore.access_finish(); } template<typename T> static void EEPROM_SKIP(const T &VAR) { eeprom_index += sizeof(VAR); } template<typename T> static void EEPROM_WRITE(const T &VAR) { persistentStore.write_data(eeprom_index, (const uint8_t *) &VAR, sizeof(VAR), &working_crc); } template<typename T> static void EEPROM_READ_(T &VAR) { persistentStore.read_data(eeprom_index, (uint8_t *) &VAR, sizeof(VAR), &working_crc, !validating); } static void EEPROM_READ_(uint8_t *VAR, size_t sizeof_VAR) { persistentStore.read_data(eeprom_index, VAR, sizeof_VAR, &working_crc, !validating); } template<typename T> static void EEPROM_READ_ALWAYS_(T &VAR) { persistentStore.read_data(eeprom_index, (uint8_t *) &VAR, sizeof(VAR), &working_crc); } #endif // EEPROM_SETTINGS }; extern MarlinSettings settings;
2301_81045437/Marlin
Marlin/src/module/settings.h
C++
agpl-3.0
5,059
/** * Marlin 3D Printer Firmware * Copyright (c) 2023 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once /** * cycles.h - Cycle counting for the Stepper ISR * * Estimate the amount of time the Stepper ISR will take to execute. * * These cycle counts are rough estimates used to determine whether the ISR * has enough time to do all its work before it should yield back to userland. * These constants may be updated as data is gathered from a variety of MCUs. */ #ifdef CPU_32_BIT /** * Duration of START_TIMED_PULSE * * ...as measured on an LPC1768 with a scope and converted to cycles. * Not applicable to other 32-bit processors, but as long as others * take longer, pulses will be longer. For example the SKR Pro * (stm32f407zgt6) requires ~60 cyles. */ #define TIMER_READ_ADD_AND_STORE_CYCLES 34UL // The base ISR #define ISR_BASE_CYCLES 770UL // Linear advance base time is 64 cycles #if ENABLED(LIN_ADVANCE) #define ISR_LA_BASE_CYCLES 64UL #else #define ISR_LA_BASE_CYCLES 0UL #endif // S curve interpolation adds 40 cycles #if ENABLED(S_CURVE_ACCELERATION) #ifdef STM32G0B1xx #define ISR_S_CURVE_CYCLES 500UL #else #define ISR_S_CURVE_CYCLES 40UL #endif #else #define ISR_S_CURVE_CYCLES 0UL #endif // Input shaping base time #if HAS_ZV_SHAPING #define ISR_SHAPING_BASE_CYCLES 180UL #else #define ISR_SHAPING_BASE_CYCLES 0UL #endif // Stepper Loop base cycles #define ISR_LOOP_BASE_CYCLES 4UL // And each stepper (start + stop pulse) takes in worst case #define ISR_STEPPER_CYCLES 100UL #else // Cycles to perform actions in START_TIMED_PULSE #define TIMER_READ_ADD_AND_STORE_CYCLES 13UL // The base ISR #define ISR_BASE_CYCLES 882UL // Linear advance base time is 32 cycles #if ENABLED(LIN_ADVANCE) #define ISR_LA_BASE_CYCLES 30UL #else #define ISR_LA_BASE_CYCLES 0UL #endif // S curve interpolation adds 160 cycles #if ENABLED(S_CURVE_ACCELERATION) #define ISR_S_CURVE_CYCLES 160UL #else #define ISR_S_CURVE_CYCLES 0UL #endif // Input shaping base time #if HAS_ZV_SHAPING #define ISR_SHAPING_BASE_CYCLES 290UL #else #define ISR_SHAPING_BASE_CYCLES 0UL #endif // Stepper Loop base cycles #define ISR_LOOP_BASE_CYCLES 32UL // And each stepper (start + stop pulse) takes in worst case #define ISR_STEPPER_CYCLES 60UL #endif // If linear advance is disabled, the loop also handles them #if DISABLED(LIN_ADVANCE) && ENABLED(MIXING_EXTRUDER) #define ISR_MIXING_STEPPER_CYCLES ((MIXING_STEPPERS) * (ISR_STEPPER_CYCLES)) #else #define ISR_MIXING_STEPPER_CYCLES 0UL #endif // Add time for each stepper #if HAS_X_STEP #define ISR_X_STEPPER_CYCLES ISR_STEPPER_CYCLES #endif #if HAS_Y_STEP #define ISR_Y_STEPPER_CYCLES ISR_STEPPER_CYCLES #endif #if HAS_Z_STEP #define ISR_Z_STEPPER_CYCLES ISR_STEPPER_CYCLES #endif #if HAS_I_STEP #define ISR_I_STEPPER_CYCLES ISR_STEPPER_CYCLES #endif #if HAS_J_STEP #define ISR_J_STEPPER_CYCLES ISR_STEPPER_CYCLES #endif #if HAS_K_STEP #define ISR_K_STEPPER_CYCLES ISR_STEPPER_CYCLES #endif #if HAS_U_STEP #define ISR_U_STEPPER_CYCLES ISR_STEPPER_CYCLES #endif #if HAS_V_STEP #define ISR_V_STEPPER_CYCLES ISR_STEPPER_CYCLES #endif #if HAS_W_STEP #define ISR_W_STEPPER_CYCLES ISR_STEPPER_CYCLES #endif #if HAS_EXTRUDERS #define ISR_E_STEPPER_CYCLES ISR_STEPPER_CYCLES // E is always interpolated, even for mixing extruders #endif // And the total minimum loop time, not including the base #define _PLUS_AXIS_CYCLES(A) + (ISR_##A##_STEPPER_CYCLES) #define MIN_ISR_LOOP_CYCLES (ISR_MIXING_STEPPER_CYCLES LOGICAL_AXIS_MAP(_PLUS_AXIS_CYCLES)) // Calculate the minimum MPU cycles needed per pulse to enforce, limited to the max stepper rate #define _MIN_STEPPER_PULSE_CYCLES(N) _MAX(uint32_t((F_CPU) / (MAXIMUM_STEPPER_RATE)), ((F_CPU) / 500000UL) * (N)) #if MINIMUM_STEPPER_PULSE #define MIN_STEPPER_PULSE_CYCLES _MIN_STEPPER_PULSE_CYCLES(uint32_t(MINIMUM_STEPPER_PULSE)) #elif HAS_DRIVER(LV8729) #define MIN_STEPPER_PULSE_CYCLES uint32_t((((F_CPU) - 1) / 2000000) + 1) // 0.5µs, aka 500ns #else #define MIN_STEPPER_PULSE_CYCLES _MIN_STEPPER_PULSE_CYCLES(1UL) #endif // Calculate the minimum pulse times (high and low) #if MINIMUM_STEPPER_PULSE && MAXIMUM_STEPPER_RATE constexpr uint32_t _MIN_STEP_PERIOD_NS = 1000000000UL / MAXIMUM_STEPPER_RATE; constexpr uint32_t _MIN_PULSE_HIGH_NS = 1000UL * MINIMUM_STEPPER_PULSE; constexpr uint32_t _MIN_PULSE_LOW_NS = _MAX((_MIN_STEP_PERIOD_NS - _MIN(_MIN_STEP_PERIOD_NS, _MIN_PULSE_HIGH_NS)), _MIN_PULSE_HIGH_NS); #elif MINIMUM_STEPPER_PULSE // Assume 50% duty cycle constexpr uint32_t _MIN_PULSE_HIGH_NS = 1000UL * MINIMUM_STEPPER_PULSE; constexpr uint32_t _MIN_PULSE_LOW_NS = _MIN_PULSE_HIGH_NS; #elif MAXIMUM_STEPPER_RATE // Assume 50% duty cycle constexpr uint32_t _MIN_PULSE_HIGH_NS = 500000000UL / MAXIMUM_STEPPER_RATE; constexpr uint32_t _MIN_PULSE_LOW_NS = _MIN_PULSE_HIGH_NS; #else #error "Expected at least one of MINIMUM_STEPPER_PULSE or MAXIMUM_STEPPER_RATE to be defined" #endif // The loop takes the base time plus the time for all the bresenham logic for 1 << R pulses plus the time // between pulses for ((1 << R) - 1) pulses. But the user could be enforcing a minimum time so the loop time is: #define ISR_LOOP_CYCLES(R) ((ISR_LOOP_BASE_CYCLES + MIN_ISR_LOOP_CYCLES + MIN_STEPPER_PULSE_CYCLES) * ((1UL << R) - 1) + _MAX(MIN_ISR_LOOP_CYCLES, MIN_STEPPER_PULSE_CYCLES)) // Model input shaping as an extra loop call #define ISR_SHAPING_LOOP_CYCLES(R) (TERN0(HAS_ZV_SHAPING, (ISR_LOOP_BASE_CYCLES + TERN0(INPUT_SHAPING_X, ISR_X_STEPPER_CYCLES) + TERN0(INPUT_SHAPING_Y, ISR_Y_STEPPER_CYCLES)) << R)) // If linear advance is enabled, then it is handled separately #if ENABLED(LIN_ADVANCE) // Estimate the minimum LA loop time #if ENABLED(MIXING_EXTRUDER) // ToDo: ??? // HELP ME: What is what? // Directions are set up for MIXING_STEPPERS - like before. // Finding the right stepper may last up to MIXING_STEPPERS loops in get_next_stepper(). // These loops are a bit faster than advancing a bresenham counter. // Always only one E stepper is stepped. #define MIN_ISR_LA_LOOP_CYCLES ((MIXING_STEPPERS) * (ISR_STEPPER_CYCLES)) #else #define MIN_ISR_LA_LOOP_CYCLES ISR_STEPPER_CYCLES #endif // And the real loop time #define ISR_LA_LOOP_CYCLES _MAX(MIN_STEPPER_PULSE_CYCLES, MIN_ISR_LA_LOOP_CYCLES) #else #define ISR_LA_LOOP_CYCLES 0UL #endif // Estimate the total ISR execution time in cycles given a step-per-ISR shift multiplier #define ISR_EXECUTION_CYCLES(R) ((ISR_BASE_CYCLES + ISR_S_CURVE_CYCLES + ISR_SHAPING_BASE_CYCLES + ISR_LOOP_CYCLES(R) + ISR_SHAPING_LOOP_CYCLES(R) + ISR_LA_BASE_CYCLES + ISR_LA_LOOP_CYCLES) >> R) // The maximum allowable stepping frequency when doing 1x stepping (in Hz) #define MAX_STEP_ISR_FREQUENCY_1X ((F_CPU) / ISR_EXECUTION_CYCLES(0)) // The minimum step ISR rate used by ADAPTIVE_STEP_SMOOTHING to target 50% CPU usage // This does not account for the possibility of multi-stepping. #define MIN_STEP_ISR_FREQUENCY (MAX_STEP_ISR_FREQUENCY_1X >> 1)
2301_81045437/Marlin
Marlin/src/module/stepper/cycles.h
C++
agpl-3.0
7,936
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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/indirection.cpp * * Stepper motor driver indirection to allow some stepper functions to * be done via SPI/I2c instead of direct pin manipulation. * * Copyright (c) 2015 Dominik Wenger */ #include "../../inc/MarlinConfig.h" #include "indirection.h" void restore_stepper_drivers() { TERN_(HAS_TRINAMIC_CONFIG, restore_trinamic_drivers()); } void reset_stepper_drivers() { TERN_(HAS_TRINAMIC_CONFIG, reset_trinamic_drivers()); } #if ENABLED(SOFTWARE_DRIVER_ENABLE) // Flags to optimize axis enabled state xyz_bool_t axis_sw_enabled; // = { false, false, false } #endif
2301_81045437/Marlin
Marlin/src/module/stepper/indirection.cpp
C++
agpl-3.0
1,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 /** * stepper/indirection.h - Stepper Indirection Macros * * Each axis in a machine may have between 1 and 4 stepper motors. * Currently X and Y allow for 1 or 2 steppers. Z can have up to 4. * Extruders usually have one E stepper per nozzle. * * XYZ Special Cases * - Delta: 3 steppers contribute to X, Y, and Z. * - SCARA: A and B steppers contribute to X and Y by angular transformation. * - CoreXY: A and B steppers contribute to X and Y in combination. * - CoreXZ: A and B steppers contribute to X and Z in combination. * - CoreYZ: A and B steppers contribute to Y and Z in combination. * * E Special Cases * - SINGLENOZZLE: All Extruders have a single nozzle so there is one heater and no XYZ offset. * - Switching Extruder: One stepper is used for each pair of nozzles with a switching mechanism. * - Duplication Mode: Two or more steppers move in sync when `extruder_duplication_enabled` is set. * With MULTI_NOZZLE_DUPLICATION a `duplication_e_mask` is also used. * - Průša MMU1: One stepper is used with a switching mechanism. Odd numbered E indexes are reversed. * - Průša MMU2: One stepper is used with a switching mechanism. * - E_DUAL_STEPPER_DRIVERS: Two steppers always move in sync, possibly with opposite DIR states. * * Direct Stepper Control * Where "Q" represents X Y Z I J K U V W / X2 Y2 Z2 Z3 Z4 / E0 E1 E2 E3 E4 E5 E6 E7 * Here each E index corresponds to a single E stepper driver. * * Q_ENABLE_INIT() Q_ENABLE_WRITE(S) Q_ENABLE_READ() * Q_DIR_INIT() Q_DIR_WRITE(S) Q_DIR_READ() * Q_STEP_INIT() Q_STEP_WRITE(S) Q_STEP_READ() * * Steppers may not have an enable state or may be enabled by other methods * beyond a single pin (SOFTWARE_DRIVER_ENABLE) so these can be overriden: * ENABLE_STEPPER_Q() DISABLE_STEPPER_Q() * * Axis Stepper Control (X Y Z I J K U V W) * SOFTWARE_DRIVER_ENABLE gives all axes a status flag, so these macros will * skip sending commands to steppers that are already in the desired state: * ENABLE_AXIS_Q() DISABLE_AXIS_Q() * * E-Axis Stepper Control (0..n) * For these macros the E index indicates a logical extruder (e.g., active_extruder). * * E_STEP_WRITE(E,V) FWD_E_DIR(E) REV_E_DIR(E) * */ #include "../../inc/MarlinConfig.h" #if HAS_TRINAMIC_CONFIG #include "trinamic.h" #endif void restore_stepper_drivers(); // Called by powerManager.power_on() void reset_stepper_drivers(); // Called by settings.load / settings.reset #define INVERT_DIR(AXIS, D) (TERN_(INVERT_## AXIS ##_DIR, !)(D)) // X Stepper #if HAS_X_AXIS #ifndef X_ENABLE_INIT #define X_ENABLE_INIT() SET_OUTPUT(X_ENABLE_PIN) #define X_ENABLE_WRITE(STATE) WRITE(X_ENABLE_PIN,STATE) #define X_ENABLE_READ() bool(READ(X_ENABLE_PIN)) #endif #ifndef X_DIR_INIT #define X_DIR_INIT() SET_OUTPUT(X_DIR_PIN) #define X_DIR_WRITE(STATE) WRITE(X_DIR_PIN,INVERT_DIR(X, STATE)) #define X_DIR_READ() INVERT_DIR(X, bool(READ(X_DIR_PIN))) #endif #define X_STEP_INIT() SET_OUTPUT(X_STEP_PIN) #ifndef X_STEP_WRITE #define X_STEP_WRITE(STATE) WRITE(X_STEP_PIN,STATE) #endif #define X_STEP_READ() bool(READ(X_STEP_PIN)) #endif // Y Stepper #if HAS_Y_AXIS #ifndef Y_ENABLE_INIT #define Y_ENABLE_INIT() SET_OUTPUT(Y_ENABLE_PIN) #define Y_ENABLE_WRITE(STATE) WRITE(Y_ENABLE_PIN,STATE) #define Y_ENABLE_READ() bool(READ(Y_ENABLE_PIN)) #endif #ifndef Y_DIR_INIT #define Y_DIR_INIT() SET_OUTPUT(Y_DIR_PIN) #define Y_DIR_WRITE(STATE) WRITE(Y_DIR_PIN,INVERT_DIR(Y, STATE)) #define Y_DIR_READ() INVERT_DIR(Y, bool(READ(Y_DIR_PIN))) #endif #define Y_STEP_INIT() SET_OUTPUT(Y_STEP_PIN) #ifndef Y_STEP_WRITE #define Y_STEP_WRITE(STATE) WRITE(Y_STEP_PIN,STATE) #endif #define Y_STEP_READ() bool(READ(Y_STEP_PIN)) #endif // Z Stepper #if HAS_Z_AXIS #ifndef Z_ENABLE_INIT #define Z_ENABLE_INIT() SET_OUTPUT(Z_ENABLE_PIN) #define Z_ENABLE_WRITE(STATE) WRITE(Z_ENABLE_PIN,STATE) #define Z_ENABLE_READ() bool(READ(Z_ENABLE_PIN)) #endif #ifndef Z_DIR_INIT #define Z_DIR_INIT() SET_OUTPUT(Z_DIR_PIN) #define Z_DIR_WRITE(STATE) WRITE(Z_DIR_PIN,INVERT_DIR(Z, STATE)) #define Z_DIR_READ() INVERT_DIR(Z, bool(READ(Z_DIR_PIN))) #endif #define Z_STEP_INIT() SET_OUTPUT(Z_STEP_PIN) #ifndef Z_STEP_WRITE #define Z_STEP_WRITE(STATE) WRITE(Z_STEP_PIN,STATE) #endif #define Z_STEP_READ() bool(READ(Z_STEP_PIN)) #endif // X2 Stepper #if HAS_X2_ENABLE #ifndef X2_ENABLE_INIT #define X2_ENABLE_INIT() SET_OUTPUT(X2_ENABLE_PIN) #define X2_ENABLE_WRITE(STATE) WRITE(X2_ENABLE_PIN,STATE) #define X2_ENABLE_READ() bool(READ(X2_ENABLE_PIN)) #endif #ifndef X2_DIR_INIT #define X2_DIR_INIT() SET_OUTPUT(X2_DIR_PIN) #define X2_DIR_WRITE(STATE) WRITE(X2_DIR_PIN,INVERT_DIR(X2, STATE)) #define X2_DIR_READ() INVERT_DIR(X2, bool(READ(X2_DIR_PIN))) #endif #define X2_STEP_INIT() SET_OUTPUT(X2_STEP_PIN) #ifndef X2_STEP_WRITE #define X2_STEP_WRITE(STATE) WRITE(X2_STEP_PIN,STATE) #endif #define X2_STEP_READ() bool(READ(X2_STEP_PIN)) #endif // Y2 Stepper #if HAS_Y2_ENABLE #ifndef Y2_ENABLE_INIT #define Y2_ENABLE_INIT() SET_OUTPUT(Y2_ENABLE_PIN) #define Y2_ENABLE_WRITE(STATE) WRITE(Y2_ENABLE_PIN,STATE) #define Y2_ENABLE_READ() bool(READ(Y2_ENABLE_PIN)) #endif #ifndef Y2_DIR_INIT #define Y2_DIR_INIT() SET_OUTPUT(Y2_DIR_PIN) #define Y2_DIR_WRITE(STATE) WRITE(Y2_DIR_PIN,INVERT_DIR(Y2, STATE)) #define Y2_DIR_READ() INVERT_DIR(Y2, bool(READ(Y2_DIR_PIN))) #endif #define Y2_STEP_INIT() SET_OUTPUT(Y2_STEP_PIN) #ifndef Y2_STEP_WRITE #define Y2_STEP_WRITE(STATE) WRITE(Y2_STEP_PIN,STATE) #endif #define Y2_STEP_READ() bool(READ(Y2_STEP_PIN)) #else #define Y2_DIR_WRITE(STATE) NOOP #endif // Z2 Stepper #if HAS_Z2_ENABLE #ifndef Z2_ENABLE_INIT #define Z2_ENABLE_INIT() SET_OUTPUT(Z2_ENABLE_PIN) #define Z2_ENABLE_WRITE(STATE) WRITE(Z2_ENABLE_PIN,STATE) #define Z2_ENABLE_READ() bool(READ(Z2_ENABLE_PIN)) #endif #ifndef Z2_DIR_INIT #define Z2_DIR_INIT() SET_OUTPUT(Z2_DIR_PIN) #define Z2_DIR_WRITE(STATE) WRITE(Z2_DIR_PIN,INVERT_DIR(Z2, STATE)) #define Z2_DIR_READ() INVERT_DIR(Z2, bool(READ(Z2_DIR_PIN))) #endif #define Z2_STEP_INIT() SET_OUTPUT(Z2_STEP_PIN) #ifndef Z2_STEP_WRITE #define Z2_STEP_WRITE(STATE) WRITE(Z2_STEP_PIN,STATE) #endif #define Z2_STEP_READ() bool(READ(Z2_STEP_PIN)) #else #define Z2_DIR_WRITE(STATE) NOOP #endif // Z3 Stepper #if HAS_Z3_ENABLE #ifndef Z3_ENABLE_INIT #define Z3_ENABLE_INIT() SET_OUTPUT(Z3_ENABLE_PIN) #define Z3_ENABLE_WRITE(STATE) WRITE(Z3_ENABLE_PIN,STATE) #define Z3_ENABLE_READ() bool(READ(Z3_ENABLE_PIN)) #endif #ifndef Z3_DIR_INIT #define Z3_DIR_INIT() SET_OUTPUT(Z3_DIR_PIN) #define Z3_DIR_WRITE(STATE) WRITE(Z3_DIR_PIN,INVERT_DIR(Z3, STATE)) #define Z3_DIR_READ() INVERT_DIR(Z3, bool(READ(Z3_DIR_PIN))) #endif #define Z3_STEP_INIT() SET_OUTPUT(Z3_STEP_PIN) #ifndef Z3_STEP_WRITE #define Z3_STEP_WRITE(STATE) WRITE(Z3_STEP_PIN,STATE) #endif #define Z3_STEP_READ() bool(READ(Z3_STEP_PIN)) #else #define Z3_DIR_WRITE(STATE) NOOP #endif // Z4 Stepper #if HAS_Z4_ENABLE #ifndef Z4_ENABLE_INIT #define Z4_ENABLE_INIT() SET_OUTPUT(Z4_ENABLE_PIN) #define Z4_ENABLE_WRITE(STATE) WRITE(Z4_ENABLE_PIN,STATE) #define Z4_ENABLE_READ() bool(READ(Z4_ENABLE_PIN)) #endif #ifndef Z4_DIR_INIT #define Z4_DIR_INIT() SET_OUTPUT(Z4_DIR_PIN) #define Z4_DIR_WRITE(STATE) WRITE(Z4_DIR_PIN,INVERT_DIR(Z4, STATE)) #define Z4_DIR_READ() INVERT_DIR(Z4, bool(READ(Z4_DIR_PIN))) #endif #define Z4_STEP_INIT() SET_OUTPUT(Z4_STEP_PIN) #ifndef Z4_STEP_WRITE #define Z4_STEP_WRITE(STATE) WRITE(Z4_STEP_PIN,STATE) #endif #define Z4_STEP_READ() bool(READ(Z4_STEP_PIN)) #else #define Z4_DIR_WRITE(STATE) NOOP #endif // I Stepper #if HAS_I_AXIS #ifndef I_ENABLE_INIT #define I_ENABLE_INIT() SET_OUTPUT(I_ENABLE_PIN) #define I_ENABLE_WRITE(STATE) WRITE(I_ENABLE_PIN,STATE) #define I_ENABLE_READ() bool(READ(I_ENABLE_PIN)) #endif #ifndef I_DIR_INIT #define I_DIR_INIT() SET_OUTPUT(I_DIR_PIN) #define I_DIR_WRITE(STATE) WRITE(I_DIR_PIN,INVERT_DIR(I, STATE)) #define I_DIR_READ() INVERT_DIR(I, bool(READ(I_DIR_PIN))) #endif #define I_STEP_INIT() SET_OUTPUT(I_STEP_PIN) #ifndef I_STEP_WRITE #define I_STEP_WRITE(STATE) WRITE(I_STEP_PIN,STATE) #endif #define I_STEP_READ() bool(READ(I_STEP_PIN)) #endif // J Stepper #if HAS_J_AXIS #ifndef J_ENABLE_INIT #define J_ENABLE_INIT() SET_OUTPUT(J_ENABLE_PIN) #define J_ENABLE_WRITE(STATE) WRITE(J_ENABLE_PIN,STATE) #define J_ENABLE_READ() bool(READ(J_ENABLE_PIN)) #endif #ifndef J_DIR_INIT #define J_DIR_INIT() SET_OUTPUT(J_DIR_PIN) #define J_DIR_WRITE(STATE) WRITE(J_DIR_PIN,INVERT_DIR(J, STATE)) #define J_DIR_READ() INVERT_DIR(J, bool(READ(J_DIR_PIN))) #endif #define J_STEP_INIT() SET_OUTPUT(J_STEP_PIN) #ifndef J_STEP_WRITE #define J_STEP_WRITE(STATE) WRITE(J_STEP_PIN,STATE) #endif #define J_STEP_READ() bool(READ(J_STEP_PIN)) #endif // K Stepper #if HAS_K_AXIS #ifndef K_ENABLE_INIT #define K_ENABLE_INIT() SET_OUTPUT(K_ENABLE_PIN) #define K_ENABLE_WRITE(STATE) WRITE(K_ENABLE_PIN,STATE) #define K_ENABLE_READ() bool(READ(K_ENABLE_PIN)) #endif #ifndef K_DIR_INIT #define K_DIR_INIT() SET_OUTPUT(K_DIR_PIN) #define K_DIR_WRITE(STATE) WRITE(K_DIR_PIN,INVERT_DIR(K, STATE)) #define K_DIR_READ() INVERT_DIR(K, bool(READ(K_DIR_PIN))) #endif #define K_STEP_INIT() SET_OUTPUT(K_STEP_PIN) #ifndef K_STEP_WRITE #define K_STEP_WRITE(STATE) WRITE(K_STEP_PIN,STATE) #endif #define K_STEP_READ() bool(READ(K_STEP_PIN)) #endif // U Stepper #if HAS_U_AXIS #ifndef U_ENABLE_INIT #define U_ENABLE_INIT() SET_OUTPUT(U_ENABLE_PIN) #define U_ENABLE_WRITE(STATE) WRITE(U_ENABLE_PIN,STATE) #define U_ENABLE_READ() bool(READ(U_ENABLE_PIN)) #endif #ifndef U_DIR_INIT #define U_DIR_INIT() SET_OUTPUT(U_DIR_PIN) #define U_DIR_WRITE(STATE) WRITE(U_DIR_PIN,INVERT_DIR(U, STATE)) #define U_DIR_READ() INVERT_DIR(U, bool(READ(U_DIR_PIN))) #endif #define U_STEP_INIT() SET_OUTPUT(U_STEP_PIN) #ifndef U_STEP_WRITE #define U_STEP_WRITE(STATE) WRITE(U_STEP_PIN,STATE) #endif #define U_STEP_READ() bool(READ(U_STEP_PIN)) #endif // V Stepper #if HAS_V_AXIS #ifndef V_ENABLE_INIT #define V_ENABLE_INIT() SET_OUTPUT(V_ENABLE_PIN) #define V_ENABLE_WRITE(STATE) WRITE(V_ENABLE_PIN,STATE) #define V_ENABLE_READ() bool(READ(V_ENABLE_PIN)) #endif #ifndef V_DIR_INIT #define V_DIR_INIT() SET_OUTPUT(V_DIR_PIN) #define V_DIR_WRITE(STATE) WRITE(V_DIR_PIN,INVERT_DIR(V, STATE)) #define V_DIR_READ() INVERT_DIR(V, bool(READ(V_DIR_PIN))) #endif #define V_STEP_INIT() SET_OUTPUT(V_STEP_PIN) #ifndef V_STEP_WRITE #define V_STEP_WRITE(STATE) WRITE(V_STEP_PIN,STATE) #endif #define V_STEP_READ() bool(READ(V_STEP_PIN)) #endif // W Stepper #if HAS_W_AXIS #ifndef W_ENABLE_INIT #define W_ENABLE_INIT() SET_OUTPUT(W_ENABLE_PIN) #define W_ENABLE_WRITE(STATE) WRITE(W_ENABLE_PIN,STATE) #define W_ENABLE_READ() bool(READ(W_ENABLE_PIN)) #endif #ifndef W_DIR_INIT #define W_DIR_INIT() SET_OUTPUT(W_DIR_PIN) #define W_DIR_WRITE(STATE) WRITE(W_DIR_PIN,INVERT_DIR(W, STATE)) #define W_DIR_READ() INVERT_DIR(W, bool(READ(W_DIR_PIN))) #endif #define W_STEP_INIT() SET_OUTPUT(W_STEP_PIN) #ifndef W_STEP_WRITE #define W_STEP_WRITE(STATE) WRITE(W_STEP_PIN,STATE) #endif #define W_STEP_READ() bool(READ(W_STEP_PIN)) #endif // E0 Stepper #ifndef E0_ENABLE_INIT #define E0_ENABLE_INIT() SET_OUTPUT(E0_ENABLE_PIN) #define E0_ENABLE_WRITE(STATE) WRITE(E0_ENABLE_PIN,STATE) #define E0_ENABLE_READ() bool(READ(E0_ENABLE_PIN)) #endif #ifndef E0_DIR_INIT #define E0_DIR_INIT() SET_OUTPUT(E0_DIR_PIN) #define E0_DIR_WRITE(STATE) WRITE(E0_DIR_PIN,INVERT_DIR(E0, STATE)) #define E0_DIR_READ() INVERT_DIR(E0, bool(READ(E0_DIR_PIN))) #endif #define E0_STEP_INIT() SET_OUTPUT(E0_STEP_PIN) #ifndef E0_STEP_WRITE #define E0_STEP_WRITE(STATE) WRITE(E0_STEP_PIN,STATE) #endif #define E0_STEP_READ() bool(READ(E0_STEP_PIN)) // E1 Stepper #ifndef E1_ENABLE_INIT #define E1_ENABLE_INIT() SET_OUTPUT(E1_ENABLE_PIN) #define E1_ENABLE_WRITE(STATE) WRITE(E1_ENABLE_PIN,STATE) #define E1_ENABLE_READ() bool(READ(E1_ENABLE_PIN)) #endif #ifndef E1_DIR_INIT #define E1_DIR_INIT() SET_OUTPUT(E1_DIR_PIN) #define E1_DIR_WRITE(STATE) WRITE(E1_DIR_PIN,INVERT_DIR(E1, STATE)) #define E1_DIR_READ() INVERT_DIR(E1, bool(READ(E1_DIR_PIN))) #endif #define E1_STEP_INIT() SET_OUTPUT(E1_STEP_PIN) #ifndef E1_STEP_WRITE #define E1_STEP_WRITE(STATE) WRITE(E1_STEP_PIN,STATE) #endif #define E1_STEP_READ() bool(READ(E1_STEP_PIN)) // E2 Stepper #ifndef E2_ENABLE_INIT #define E2_ENABLE_INIT() SET_OUTPUT(E2_ENABLE_PIN) #define E2_ENABLE_WRITE(STATE) WRITE(E2_ENABLE_PIN,STATE) #define E2_ENABLE_READ() bool(READ(E2_ENABLE_PIN)) #endif #ifndef E2_DIR_INIT #define E2_DIR_INIT() SET_OUTPUT(E2_DIR_PIN) #define E2_DIR_WRITE(STATE) WRITE(E2_DIR_PIN,INVERT_DIR(E2, STATE)) #define E2_DIR_READ() INVERT_DIR(E2, bool(READ(E2_DIR_PIN))) #endif #define E2_STEP_INIT() SET_OUTPUT(E2_STEP_PIN) #ifndef E2_STEP_WRITE #define E2_STEP_WRITE(STATE) WRITE(E2_STEP_PIN,STATE) #endif #define E2_STEP_READ() bool(READ(E2_STEP_PIN)) // E3 Stepper #ifndef E3_ENABLE_INIT #define E3_ENABLE_INIT() SET_OUTPUT(E3_ENABLE_PIN) #define E3_ENABLE_WRITE(STATE) WRITE(E3_ENABLE_PIN,STATE) #define E3_ENABLE_READ() bool(READ(E3_ENABLE_PIN)) #endif #ifndef E3_DIR_INIT #define E3_DIR_INIT() SET_OUTPUT(E3_DIR_PIN) #define E3_DIR_WRITE(STATE) WRITE(E3_DIR_PIN,INVERT_DIR(E3, STATE)) #define E3_DIR_READ() INVERT_DIR(E3, bool(READ(E3_DIR_PIN))) #endif #define E3_STEP_INIT() SET_OUTPUT(E3_STEP_PIN) #ifndef E3_STEP_WRITE #define E3_STEP_WRITE(STATE) WRITE(E3_STEP_PIN,STATE) #endif #define E3_STEP_READ() bool(READ(E3_STEP_PIN)) // E4 Stepper #ifndef E4_ENABLE_INIT #define E4_ENABLE_INIT() SET_OUTPUT(E4_ENABLE_PIN) #define E4_ENABLE_WRITE(STATE) WRITE(E4_ENABLE_PIN,STATE) #define E4_ENABLE_READ() bool(READ(E4_ENABLE_PIN)) #endif #ifndef E4_DIR_INIT #define E4_DIR_INIT() SET_OUTPUT(E4_DIR_PIN) #define E4_DIR_WRITE(STATE) WRITE(E4_DIR_PIN,INVERT_DIR(E4, STATE)) #define E4_DIR_READ() INVERT_DIR(E4, bool(READ(E4_DIR_PIN))) #endif #define E4_STEP_INIT() SET_OUTPUT(E4_STEP_PIN) #ifndef E4_STEP_WRITE #define E4_STEP_WRITE(STATE) WRITE(E4_STEP_PIN,STATE) #endif #define E4_STEP_READ() bool(READ(E4_STEP_PIN)) // E5 Stepper #ifndef E5_ENABLE_INIT #define E5_ENABLE_INIT() SET_OUTPUT(E5_ENABLE_PIN) #define E5_ENABLE_WRITE(STATE) WRITE(E5_ENABLE_PIN,STATE) #define E5_ENABLE_READ() bool(READ(E5_ENABLE_PIN)) #endif #ifndef E5_DIR_INIT #define E5_DIR_INIT() SET_OUTPUT(E5_DIR_PIN) #define E5_DIR_WRITE(STATE) WRITE(E5_DIR_PIN,INVERT_DIR(E5, STATE)) #define E5_DIR_READ() INVERT_DIR(E5, bool(READ(E5_DIR_PIN))) #endif #define E5_STEP_INIT() SET_OUTPUT(E5_STEP_PIN) #ifndef E5_STEP_WRITE #define E5_STEP_WRITE(STATE) WRITE(E5_STEP_PIN,STATE) #endif #define E5_STEP_READ() bool(READ(E5_STEP_PIN)) // E6 Stepper #ifndef E6_ENABLE_INIT #define E6_ENABLE_INIT() SET_OUTPUT(E6_ENABLE_PIN) #define E6_ENABLE_WRITE(STATE) WRITE(E6_ENABLE_PIN,STATE) #define E6_ENABLE_READ() bool(READ(E6_ENABLE_PIN)) #endif #ifndef E6_DIR_INIT #define E6_DIR_INIT() SET_OUTPUT(E6_DIR_PIN) #define E6_DIR_WRITE(STATE) WRITE(E6_DIR_PIN,INVERT_DIR(E6, STATE)) #define E6_DIR_READ() INVERT_DIR(E6, bool(READ(E6_DIR_PIN))) #endif #define E6_STEP_INIT() SET_OUTPUT(E6_STEP_PIN) #ifndef E6_STEP_WRITE #define E6_STEP_WRITE(STATE) WRITE(E6_STEP_PIN,STATE) #endif #define E6_STEP_READ() bool(READ(E6_STEP_PIN)) // E7 Stepper #ifndef E7_ENABLE_INIT #define E7_ENABLE_INIT() SET_OUTPUT(E7_ENABLE_PIN) #define E7_ENABLE_WRITE(STATE) WRITE(E7_ENABLE_PIN,STATE) #define E7_ENABLE_READ() bool(READ(E7_ENABLE_PIN)) #endif #ifndef E7_DIR_INIT #define E7_DIR_INIT() SET_OUTPUT(E7_DIR_PIN) #define E7_DIR_WRITE(STATE) WRITE(E7_DIR_PIN,INVERT_DIR(E7, STATE)) #define E7_DIR_READ() INVERT_DIR(E7, bool(READ(E7_DIR_PIN))) #endif #define E7_STEP_INIT() SET_OUTPUT(E7_STEP_PIN) #ifndef E7_STEP_WRITE #define E7_STEP_WRITE(STATE) WRITE(E7_STEP_PIN,STATE) #endif #define E7_STEP_READ() bool(READ(E7_STEP_PIN)) /** * Extruder indirection for the single E axis */ #if HAS_SWITCHING_EXTRUDER // One stepper driver per two extruders, reversed on odd index #if EXTRUDERS > 7 #define E_STEP_WRITE(E,V) do{ if (E < 2) { E0_STEP_WRITE(V); } else if (E < 4) { E1_STEP_WRITE(V); } else if (E < 6) { E2_STEP_WRITE(V); } else { E3_STEP_WRITE(V); } }while(0) #define FWD_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(HIGH); break; case 1: E0_DIR_WRITE(LOW ); break; \ case 2: E1_DIR_WRITE(HIGH); break; case 3: E1_DIR_WRITE(LOW ); break; \ case 4: E2_DIR_WRITE(HIGH); break; case 5: E2_DIR_WRITE(LOW ); break; \ case 6: E3_DIR_WRITE(HIGH); break; case 7: E3_DIR_WRITE(LOW ); break; \ } }while(0) #define REV_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(LOW ); break; case 1: E0_DIR_WRITE(HIGH); break; \ case 2: E1_DIR_WRITE(LOW ); break; case 3: E1_DIR_WRITE(HIGH); break; \ case 4: E2_DIR_WRITE(LOW ); break; case 5: E2_DIR_WRITE(HIGH); break; \ case 6: E3_DIR_WRITE(LOW ); break; case 7: E3_DIR_WRITE(HIGH); break; \ } }while(0) #elif EXTRUDERS > 6 #define E_STEP_WRITE(E,V) do{ if (E < 2) { E0_STEP_WRITE(V); } else if (E < 4) { E1_STEP_WRITE(V); } else if (E < 6) { E2_STEP_WRITE(V); } else { E3_STEP_WRITE(V); } }while(0) #define FWD_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(HIGH); break; case 1: E0_DIR_WRITE(LOW ); break; \ case 2: E1_DIR_WRITE(HIGH); break; case 3: E1_DIR_WRITE(LOW ); break; \ case 4: E2_DIR_WRITE(HIGH); break; case 5: E2_DIR_WRITE(LOW ); break; \ case 6: E3_DIR_WRITE(HIGH); break; \ } }while(0) #define REV_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(LOW ); break; case 1: E0_DIR_WRITE(HIGH); break; \ case 2: E1_DIR_WRITE(LOW ); break; case 3: E1_DIR_WRITE(HIGH); break; \ case 4: E2_DIR_WRITE(LOW ); break; case 5: E2_DIR_WRITE(HIGH); break; \ case 6: E3_DIR_WRITE(LOW ); } }while(0) #elif EXTRUDERS > 5 #define E_STEP_WRITE(E,V) do{ if (E < 2) { E0_STEP_WRITE(V); } else if (E < 4) { E1_STEP_WRITE(V); } else { E2_STEP_WRITE(V); } }while(0) #define FWD_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(HIGH); break; case 1: E0_DIR_WRITE(LOW ); break; \ case 2: E1_DIR_WRITE(HIGH); break; case 3: E1_DIR_WRITE(LOW ); break; \ case 4: E2_DIR_WRITE(HIGH); break; case 5: E2_DIR_WRITE(LOW ); break; \ } }while(0) #define REV_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(LOW ); break; case 1: E0_DIR_WRITE(HIGH); break; \ case 2: E1_DIR_WRITE(LOW ); break; case 3: E1_DIR_WRITE(HIGH); break; \ case 4: E2_DIR_WRITE(LOW ); break; case 5: E2_DIR_WRITE(HIGH); break; \ } }while(0) #elif EXTRUDERS > 4 #define E_STEP_WRITE(E,V) do{ if (E < 2) { E0_STEP_WRITE(V); } else if (E < 4) { E1_STEP_WRITE(V); } else { E2_STEP_WRITE(V); } }while(0) #define FWD_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(HIGH); break; case 1: E0_DIR_WRITE(LOW ); break; \ case 2: E1_DIR_WRITE(HIGH); break; case 3: E1_DIR_WRITE(LOW ); break; \ case 4: E2_DIR_WRITE(HIGH); break; \ } }while(0) #define REV_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(LOW ); break; case 1: E0_DIR_WRITE(HIGH); break; \ case 2: E1_DIR_WRITE(LOW ); break; case 3: E1_DIR_WRITE(HIGH); break; \ case 4: E2_DIR_WRITE(LOW ); break; \ } }while(0) #elif EXTRUDERS > 3 #define E_STEP_WRITE(E,V) do{ if (E < 2) { E0_STEP_WRITE(V); } else { E1_STEP_WRITE(V); } }while(0) #define FWD_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(HIGH); break; case 1: E0_DIR_WRITE(LOW ); break; \ case 2: E1_DIR_WRITE(HIGH); break; case 3: E1_DIR_WRITE(LOW ); break; \ } }while(0) #define REV_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(LOW ); break; case 1: E0_DIR_WRITE(HIGH); break; \ case 2: E1_DIR_WRITE(LOW ); break; case 3: E1_DIR_WRITE(HIGH); break; \ } }while(0) #elif EXTRUDERS > 2 #define E_STEP_WRITE(E,V) do{ if (E < 2) { E0_STEP_WRITE(V); } else { E1_STEP_WRITE(V); } }while(0) #define FWD_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(HIGH); break; case 1: E0_DIR_WRITE(LOW ); break; \ case 2: E1_DIR_WRITE(HIGH); break; \ } }while(0) #define REV_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(LOW ); break; case 1: E0_DIR_WRITE(HIGH); break; \ case 2: E1_DIR_WRITE(LOW ); break; \ } }while(0) #else #define E_STEP_WRITE(E,V) E0_STEP_WRITE(V) #define FWD_E_DIR(E) do{ E0_DIR_WRITE((E) ? LOW : HIGH); }while(0) #define REV_E_DIR(E) do{ E0_DIR_WRITE((E) ? HIGH : LOW ); }while(0) #endif #define TOOL_ESTEPPER(T) ((T) >> 1) #elif HAS_PRUSA_MMU2 // One multiplexed stepper driver #define E_STEP_WRITE(E,V) E0_STEP_WRITE(V) #define FWD_E_DIR(E) E0_DIR_WRITE(HIGH) #define REV_E_DIR(E) E0_DIR_WRITE(LOW ) #elif HAS_PRUSA_MMU1 // One multiplexed stepper driver, reversed on odd index #define E_STEP_WRITE(E,V) E0_STEP_WRITE(V) #define FWD_E_DIR(E) do{ E0_DIR_WRITE(TEST(E, 0) ? HIGH : LOW ); }while(0) #define REV_E_DIR(E) do{ E0_DIR_WRITE(TEST(E, 0) ? LOW : HIGH); }while(0) #elif E_STEPPERS > 1 #if E_STEPPERS > 7 #define _E_STEP_WRITE(E,V) do{ switch (E) { \ case 0: E0_STEP_WRITE(V); break; case 1: E1_STEP_WRITE(V); break; case 2: E2_STEP_WRITE(V); break; case 3: E3_STEP_WRITE(V); break; \ case 4: E4_STEP_WRITE(V); break; case 5: E5_STEP_WRITE(V); break; case 6: E6_STEP_WRITE(V); break; case 7: E7_STEP_WRITE(V); break; \ } }while(0) #define _FWD_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(HIGH); break; case 1: E1_DIR_WRITE(HIGH); break; \ case 2: E2_DIR_WRITE(HIGH); break; case 3: E3_DIR_WRITE(HIGH); break; \ case 4: E4_DIR_WRITE(HIGH); break; case 5: E5_DIR_WRITE(HIGH); break; \ case 6: E6_DIR_WRITE(HIGH); break; case 7: E7_DIR_WRITE(HIGH); break; \ } }while(0) #define _REV_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(LOW ); break; case 1: E1_DIR_WRITE(LOW ); break; \ case 2: E2_DIR_WRITE(LOW ); break; case 3: E3_DIR_WRITE(LOW ); break; \ case 4: E4_DIR_WRITE(LOW ); break; case 5: E5_DIR_WRITE(LOW ); break; \ case 6: E6_DIR_WRITE(LOW ); break; case 7: E7_DIR_WRITE(LOW ); break; \ } }while(0) #elif E_STEPPERS > 6 #define _E_STEP_WRITE(E,V) do{ switch (E) { \ case 0: E0_STEP_WRITE(V); break; case 1: E1_STEP_WRITE(V); break; case 2: E2_STEP_WRITE(V); break; case 3: E3_STEP_WRITE(V); break; \ case 4: E4_STEP_WRITE(V); break; case 5: E5_STEP_WRITE(V); break; case 6: E6_STEP_WRITE(V); break; \ } }while(0) #define _FWD_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(HIGH); break; case 1: E1_DIR_WRITE(HIGH); break; \ case 2: E2_DIR_WRITE(HIGH); break; case 3: E3_DIR_WRITE(HIGH); break; \ case 4: E4_DIR_WRITE(HIGH); break; case 5: E5_DIR_WRITE(HIGH); break; \ case 6: E6_DIR_WRITE(HIGH); break; \ } }while(0) #define _REV_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(LOW ); break; case 1: E1_DIR_WRITE(LOW ); break; \ case 2: E2_DIR_WRITE(LOW ); break; case 3: E3_DIR_WRITE(LOW ); break; \ case 4: E4_DIR_WRITE(LOW ); break; case 5: E5_DIR_WRITE(LOW ); break; \ case 6: E6_DIR_WRITE(LOW ); break; \ } }while(0) #elif E_STEPPERS > 5 #define _E_STEP_WRITE(E,V) do{ switch (E) { \ case 0: E0_STEP_WRITE(V); break; case 1: E1_STEP_WRITE(V); break; case 2: E2_STEP_WRITE(V); break; case 3: E3_STEP_WRITE(V); break; \ case 4: E4_STEP_WRITE(V); break; case 5: E5_STEP_WRITE(V); break; \ } }while(0) #define _FWD_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(HIGH); break; case 1: E1_DIR_WRITE(HIGH); break; \ case 2: E2_DIR_WRITE(HIGH); break; case 3: E3_DIR_WRITE(HIGH); break; \ case 4: E4_DIR_WRITE(HIGH); break; case 5: E5_DIR_WRITE(HIGH); break; \ } }while(0) #define _REV_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(LOW ); break; case 1: E1_DIR_WRITE(LOW ); break; \ case 2: E2_DIR_WRITE(LOW ); break; case 3: E3_DIR_WRITE(LOW ); break; \ case 4: E4_DIR_WRITE(LOW ); break; case 5: E5_DIR_WRITE(LOW ); break; \ } }while(0) #elif E_STEPPERS > 4 #define _E_STEP_WRITE(E,V) do{ switch (E) { \ case 0: E0_STEP_WRITE(V); break; case 1: E1_STEP_WRITE(V); break; case 2: E2_STEP_WRITE(V); break; case 3: E3_STEP_WRITE(V); break; \ case 4: E4_STEP_WRITE(V); break; \ } }while(0) #define _FWD_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(HIGH); break; case 1: E1_DIR_WRITE(HIGH); break; \ case 2: E2_DIR_WRITE(HIGH); break; case 3: E3_DIR_WRITE(HIGH); break; \ case 4: E4_DIR_WRITE(HIGH); break; \ } }while(0) #define _REV_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(LOW ); break; case 1: E1_DIR_WRITE(LOW ); break; \ case 2: E2_DIR_WRITE(LOW ); break; case 3: E3_DIR_WRITE(LOW ); break; \ case 4: E4_DIR_WRITE(LOW ); break; \ } }while(0) #elif E_STEPPERS > 3 #define _E_STEP_WRITE(E,V) do{ switch (E) { \ case 0: E0_STEP_WRITE(V); break; case 1: E1_STEP_WRITE(V); break; case 2: E2_STEP_WRITE(V); break; case 3: E3_STEP_WRITE(V); break; \ } }while(0) #define _FWD_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(HIGH); break; case 1: E1_DIR_WRITE(HIGH); break; \ case 2: E2_DIR_WRITE(HIGH); break; case 3: E3_DIR_WRITE(HIGH); break; \ } }while(0) #define _REV_E_DIR(E) do{ switch (E) { \ case 0: E0_DIR_WRITE(LOW ); break; case 1: E1_DIR_WRITE(LOW ); break; \ case 2: E2_DIR_WRITE(LOW ); break; case 3: E3_DIR_WRITE(LOW ); break; \ } }while(0) #elif E_STEPPERS > 2 #define _E_STEP_WRITE(E,V) do{ switch (E) { case 0: E0_STEP_WRITE(V); break; case 1: E1_STEP_WRITE(V); break; case 2: E2_STEP_WRITE(V); } }while(0) #define _FWD_E_DIR(E) do{ switch (E) { case 0: E0_DIR_WRITE(HIGH); break; case 1: E1_DIR_WRITE(HIGH); break; case 2: E2_DIR_WRITE(HIGH); } }while(0) #define _REV_E_DIR(E) do{ switch (E) { case 0: E0_DIR_WRITE(LOW ); break; case 1: E1_DIR_WRITE(LOW ); break; case 2: E2_DIR_WRITE(LOW ); } }while(0) #else #define _E_STEP_WRITE(E,V) do{ if (E == 0) { E0_STEP_WRITE(V); } else { E1_STEP_WRITE(V); } }while(0) #define _FWD_E_DIR(E) do{ if (E == 0) { E0_DIR_WRITE(HIGH); } else { E1_DIR_WRITE(HIGH); } }while(0) #define _REV_E_DIR(E) do{ if (E == 0) { E0_DIR_WRITE(LOW ); } else { E1_DIR_WRITE(LOW ); } }while(0) #endif #if HAS_DUPLICATION_MODE #if ENABLED(MULTI_NOZZLE_DUPLICATION) #define DUPE(N,T,V) do{ if (TEST(duplication_e_mask, N)) E##N##_##T##_WRITE(V); }while(0); #else #define DUPE(N,T,V) E##N##_##T##_WRITE(V); #endif #define NDIR(N) DUPE(N,DIR,HIGH); #define RDIR(N) DUPE(N,DIR,LOW ); #define E_STEP_WRITE(E,V) do{ if (extruder_duplication_enabled) { REPEAT2(E_STEPPERS, DUPE, STEP, V); } else _E_STEP_WRITE(E,V); }while(0) #define FWD_E_DIR(E) do{ if (extruder_duplication_enabled) { REPEAT(E_STEPPERS, NDIR); } else _FWD_E_DIR(E); }while(0) #define REV_E_DIR(E) do{ if (extruder_duplication_enabled) { REPEAT(E_STEPPERS, RDIR); } else _REV_E_DIR(E); }while(0) #else #define E_STEP_WRITE(E,V) _E_STEP_WRITE(E,V) #define FWD_E_DIR(E) _FWD_E_DIR(E) #define REV_E_DIR(E) _REV_E_DIR(E) #endif #elif ENABLED(E_DUAL_STEPPER_DRIVERS) #define E_STEP_WRITE(E,V) do{ E0_STEP_WRITE(V); E1_STEP_WRITE(V); }while(0) #define FWD_E_DIR(E) do{ E0_DIR_WRITE(HIGH); E1_DIR_WRITE(INVERT_DIR(E1_VS_E0, HIGH)); }while(0) #define REV_E_DIR(E) do{ E0_DIR_WRITE(LOW ); E1_DIR_WRITE(INVERT_DIR(E1_VS_E0, LOW )); }while(0) #elif E_STEPPERS == 1 #define E_STEP_WRITE(E,V) E0_STEP_WRITE(V) #define FWD_E_DIR(E) E0_DIR_WRITE(HIGH) #define REV_E_DIR(E) E0_DIR_WRITE(LOW ) #else #define E_STEP_WRITE(E,V) NOOP #define FWD_E_DIR(E) NOOP #define REV_E_DIR(E) NOOP #endif #ifndef TOOL_ESTEPPER #define TOOL_ESTEPPER(T) (T) #endif // // Individual stepper enable / disable macros // #ifndef ENABLE_STEPPER_X #define ENABLE_STEPPER_X() TERN(HAS_X_ENABLE, X_ENABLE_WRITE( X_ENABLE_ON), NOOP) #endif #ifndef DISABLE_STEPPER_X #define DISABLE_STEPPER_X() TERN(HAS_X_ENABLE, X_ENABLE_WRITE(!X_ENABLE_ON), NOOP) #endif #ifndef ENABLE_STEPPER_X2 #define ENABLE_STEPPER_X2() TERN(HAS_X2_ENABLE, X2_ENABLE_WRITE( X_ENABLE_ON), NOOP) #endif #ifndef DISABLE_STEPPER_X2 #define DISABLE_STEPPER_X2() TERN(HAS_X2_ENABLE, X2_ENABLE_WRITE(!X_ENABLE_ON), NOOP) #endif #ifndef ENABLE_STEPPER_Y #define ENABLE_STEPPER_Y() TERN(HAS_Y_ENABLE, Y_ENABLE_WRITE( Y_ENABLE_ON), NOOP) #endif #ifndef DISABLE_STEPPER_Y #define DISABLE_STEPPER_Y() TERN(HAS_Y_ENABLE, Y_ENABLE_WRITE(!Y_ENABLE_ON), NOOP) #endif #ifndef ENABLE_STEPPER_Y2 #define ENABLE_STEPPER_Y2() TERN(HAS_Y2_ENABLE, Y2_ENABLE_WRITE( Y_ENABLE_ON), NOOP) #endif #ifndef DISABLE_STEPPER_Y2 #define DISABLE_STEPPER_Y2() TERN(HAS_Y2_ENABLE, Y2_ENABLE_WRITE(!Y_ENABLE_ON), NOOP) #endif #ifndef ENABLE_STEPPER_Z #define ENABLE_STEPPER_Z() TERN(HAS_Z_ENABLE, Z_ENABLE_WRITE( Z_ENABLE_ON), NOOP) #endif #ifndef DISABLE_STEPPER_Z #define DISABLE_STEPPER_Z() TERN(HAS_Z_ENABLE, Z_ENABLE_WRITE(!Z_ENABLE_ON), NOOP) #endif #ifndef ENABLE_STEPPER_Z2 #define ENABLE_STEPPER_Z2() TERN(HAS_Z2_ENABLE, Z2_ENABLE_WRITE( Z_ENABLE_ON), NOOP) #endif #ifndef DISABLE_STEPPER_Z2 #define DISABLE_STEPPER_Z2() TERN(HAS_Z2_ENABLE, Z2_ENABLE_WRITE(!Z_ENABLE_ON), NOOP) #endif #ifndef ENABLE_STEPPER_Z3 #define ENABLE_STEPPER_Z3() TERN(HAS_Z3_ENABLE, Z3_ENABLE_WRITE( Z_ENABLE_ON), NOOP) #endif #ifndef DISABLE_STEPPER_Z3 #define DISABLE_STEPPER_Z3() TERN(HAS_Z3_ENABLE, Z3_ENABLE_WRITE(!Z_ENABLE_ON), NOOP) #endif #ifndef ENABLE_STEPPER_Z4 #define ENABLE_STEPPER_Z4() TERN(HAS_Z4_ENABLE, Z4_ENABLE_WRITE( Z_ENABLE_ON), NOOP) #endif #ifndef DISABLE_STEPPER_Z4 #define DISABLE_STEPPER_Z4() TERN(HAS_Z4_ENABLE, Z4_ENABLE_WRITE(!Z_ENABLE_ON), NOOP) #endif #ifndef ENABLE_STEPPER_I #define ENABLE_STEPPER_I() TERN(HAS_I_ENABLE, I_ENABLE_WRITE( I_ENABLE_ON), NOOP) #endif #ifndef DISABLE_STEPPER_I #define DISABLE_STEPPER_I() TERN(HAS_I_ENABLE, I_ENABLE_WRITE(!I_ENABLE_ON), NOOP) #endif #ifndef ENABLE_STEPPER_J #define ENABLE_STEPPER_J() TERN(HAS_J_ENABLE, J_ENABLE_WRITE( J_ENABLE_ON), NOOP) #endif #ifndef DISABLE_STEPPER_J #define DISABLE_STEPPER_J() TERN(HAS_J_ENABLE, J_ENABLE_WRITE(!J_ENABLE_ON), NOOP) #endif #ifndef ENABLE_STEPPER_K #define ENABLE_STEPPER_K() TERN(HAS_K_ENABLE, K_ENABLE_WRITE( K_ENABLE_ON), NOOP) #endif #ifndef DISABLE_STEPPER_K #define DISABLE_STEPPER_K() TERN(HAS_K_ENABLE, K_ENABLE_WRITE(!K_ENABLE_ON), NOOP) #endif #ifndef ENABLE_STEPPER_U #if HAS_U_ENABLE #define ENABLE_STEPPER_U() U_ENABLE_WRITE( U_ENABLE_ON) #else #define ENABLE_STEPPER_U() NOOP #endif #endif #ifndef DISABLE_STEPPER_U #if HAS_U_ENABLE #define DISABLE_STEPPER_U() U_ENABLE_WRITE(!U_ENABLE_ON) #else #define DISABLE_STEPPER_U() NOOP #endif #endif #ifndef ENABLE_STEPPER_V #if HAS_V_ENABLE #define ENABLE_STEPPER_V() V_ENABLE_WRITE( V_ENABLE_ON) #else #define ENABLE_STEPPER_V() NOOP #endif #endif #ifndef DISABLE_STEPPER_V #if HAS_V_ENABLE #define DISABLE_STEPPER_V() V_ENABLE_WRITE(!V_ENABLE_ON) #else #define DISABLE_STEPPER_V() NOOP #endif #endif #ifndef ENABLE_STEPPER_W #if HAS_W_ENABLE #define ENABLE_STEPPER_W() W_ENABLE_WRITE( W_ENABLE_ON) #else #define ENABLE_STEPPER_W() NOOP #endif #endif #ifndef DISABLE_STEPPER_W #if HAS_W_ENABLE #define DISABLE_STEPPER_W() W_ENABLE_WRITE(!W_ENABLE_ON) #else #define DISABLE_STEPPER_W() NOOP #endif #endif #ifndef ENABLE_STEPPER_E0 #define ENABLE_STEPPER_E0() TERN(HAS_E0_ENABLE, E0_ENABLE_WRITE( E_ENABLE_ON), NOOP) #endif #ifndef DISABLE_STEPPER_E0 #define DISABLE_STEPPER_E0() TERN(HAS_E0_ENABLE, E0_ENABLE_WRITE(!E_ENABLE_ON), NOOP) #endif #ifndef ENABLE_STEPPER_E1 #if (E_STEPPERS > 1 || ENABLED(E_DUAL_STEPPER_DRIVERS)) && HAS_E1_ENABLE #define ENABLE_STEPPER_E1() E1_ENABLE_WRITE( E_ENABLE_ON) #else #define ENABLE_STEPPER_E1() NOOP #endif #endif #ifndef DISABLE_STEPPER_E1 #if (E_STEPPERS > 1 || ENABLED(E_DUAL_STEPPER_DRIVERS)) && HAS_E1_ENABLE #define DISABLE_STEPPER_E1() E1_ENABLE_WRITE(!E_ENABLE_ON) #else #define DISABLE_STEPPER_E1() NOOP #endif #endif #ifndef ENABLE_STEPPER_E2 #if E_STEPPERS > 2 && HAS_E2_ENABLE #define ENABLE_STEPPER_E2() E2_ENABLE_WRITE( E_ENABLE_ON) #else #define ENABLE_STEPPER_E2() NOOP #endif #endif #ifndef DISABLE_STEPPER_E2 #if E_STEPPERS > 2 && HAS_E2_ENABLE #define DISABLE_STEPPER_E2() E2_ENABLE_WRITE(!E_ENABLE_ON) #else #define DISABLE_STEPPER_E2() NOOP #endif #endif #ifndef ENABLE_STEPPER_E3 #if E_STEPPERS > 3 && HAS_E3_ENABLE #define ENABLE_STEPPER_E3() E3_ENABLE_WRITE( E_ENABLE_ON) #else #define ENABLE_STEPPER_E3() NOOP #endif #endif #ifndef DISABLE_STEPPER_E3 #if E_STEPPERS > 3 && HAS_E3_ENABLE #define DISABLE_STEPPER_E3() E3_ENABLE_WRITE(!E_ENABLE_ON) #else #define DISABLE_STEPPER_E3() NOOP #endif #endif #ifndef ENABLE_STEPPER_E4 #if E_STEPPERS > 4 && HAS_E4_ENABLE #define ENABLE_STEPPER_E4() E4_ENABLE_WRITE( E_ENABLE_ON) #else #define ENABLE_STEPPER_E4() NOOP #endif #endif #ifndef DISABLE_STEPPER_E4 #if E_STEPPERS > 4 && HAS_E4_ENABLE #define DISABLE_STEPPER_E4() E4_ENABLE_WRITE(!E_ENABLE_ON) #else #define DISABLE_STEPPER_E4() NOOP #endif #endif #ifndef ENABLE_STEPPER_E5 #if E_STEPPERS > 5 && HAS_E5_ENABLE #define ENABLE_STEPPER_E5() E5_ENABLE_WRITE( E_ENABLE_ON) #else #define ENABLE_STEPPER_E5() NOOP #endif #endif #ifndef DISABLE_STEPPER_E5 #if E_STEPPERS > 5 && HAS_E5_ENABLE #define DISABLE_STEPPER_E5() E5_ENABLE_WRITE(!E_ENABLE_ON) #else #define DISABLE_STEPPER_E5() NOOP #endif #endif #ifndef ENABLE_STEPPER_E6 #if E_STEPPERS > 6 && HAS_E6_ENABLE #define ENABLE_STEPPER_E6() E6_ENABLE_WRITE( E_ENABLE_ON) #else #define ENABLE_STEPPER_E6() NOOP #endif #endif #ifndef DISABLE_STEPPER_E6 #if E_STEPPERS > 6 && HAS_E6_ENABLE #define DISABLE_STEPPER_E6() E6_ENABLE_WRITE(!E_ENABLE_ON) #else #define DISABLE_STEPPER_E6() NOOP #endif #endif #ifndef ENABLE_STEPPER_E7 #if E_STEPPERS > 7 && HAS_E7_ENABLE #define ENABLE_STEPPER_E7() E7_ENABLE_WRITE( E_ENABLE_ON) #else #define ENABLE_STEPPER_E7() NOOP #endif #endif #ifndef DISABLE_STEPPER_E7 #if E_STEPPERS > 7 && HAS_E7_ENABLE #define DISABLE_STEPPER_E7() E7_ENABLE_WRITE(!E_ENABLE_ON) #else #define DISABLE_STEPPER_E7() NOOP #endif #endif // // Axis steppers enable / disable macros // #if ENABLED(SOFTWARE_DRIVER_ENABLE) // Avoid expensive calls to enable / disable steppers extern xyz_bool_t axis_sw_enabled; #define SHOULD_ENABLE(N) !axis_sw_enabled.N #define SHOULD_DISABLE(N) axis_sw_enabled.N #define AFTER_CHANGE(N,TF) axis_sw_enabled.N = TF #else #define SHOULD_ENABLE(N) true #define SHOULD_DISABLE(N) true #define AFTER_CHANGE(N,TF) NOOP #endif #if HAS_X_AXIS #define ENABLE_AXIS_X() if (SHOULD_ENABLE(x)) { ENABLE_STEPPER_X(); ENABLE_STEPPER_X2(); AFTER_CHANGE(x, true); } #define DISABLE_AXIS_X() if (SHOULD_DISABLE(x)) { DISABLE_STEPPER_X(); DISABLE_STEPPER_X2(); AFTER_CHANGE(x, false); set_axis_untrusted(X_AXIS); } #else #define ENABLE_AXIS_X() NOOP #define DISABLE_AXIS_X() NOOP #endif #if HAS_Y_AXIS #define ENABLE_AXIS_Y() if (SHOULD_ENABLE(y)) { ENABLE_STEPPER_Y(); ENABLE_STEPPER_Y2(); AFTER_CHANGE(y, true); } #define DISABLE_AXIS_Y() if (SHOULD_DISABLE(y)) { DISABLE_STEPPER_Y(); DISABLE_STEPPER_Y2(); AFTER_CHANGE(y, false); set_axis_untrusted(Y_AXIS); } #else #define ENABLE_AXIS_Y() NOOP #define DISABLE_AXIS_Y() NOOP #endif #if HAS_Z_AXIS #define ENABLE_AXIS_Z() if (SHOULD_ENABLE(z)) { ENABLE_STEPPER_Z(); ENABLE_STEPPER_Z2(); ENABLE_STEPPER_Z3(); ENABLE_STEPPER_Z4(); AFTER_CHANGE(z, true); } #define DISABLE_AXIS_Z() if (SHOULD_DISABLE(z)) { DISABLE_STEPPER_Z(); DISABLE_STEPPER_Z2(); DISABLE_STEPPER_Z3(); DISABLE_STEPPER_Z4(); AFTER_CHANGE(z, false); set_axis_untrusted(Z_AXIS); Z_RESET(); TERN_(BD_SENSOR, bdl.config_state = BDS_IDLE); } #else #define ENABLE_AXIS_Z() NOOP #define DISABLE_AXIS_Z() NOOP #endif #ifdef Z_IDLE_HEIGHT #define Z_RESET() do{ current_position.z = Z_IDLE_HEIGHT; sync_plan_position(); }while(0) #else #define Z_RESET() #endif #if HAS_I_AXIS #define ENABLE_AXIS_I() if (SHOULD_ENABLE(i)) { ENABLE_STEPPER_I(); AFTER_CHANGE(i, true); } #define DISABLE_AXIS_I() if (SHOULD_DISABLE(i)) { DISABLE_STEPPER_I(); AFTER_CHANGE(i, false); set_axis_untrusted(I_AXIS); } #else #define ENABLE_AXIS_I() NOOP #define DISABLE_AXIS_I() NOOP #endif #if HAS_J_AXIS #define ENABLE_AXIS_J() if (SHOULD_ENABLE(j)) { ENABLE_STEPPER_J(); AFTER_CHANGE(j, true); } #define DISABLE_AXIS_J() if (SHOULD_DISABLE(j)) { DISABLE_STEPPER_J(); AFTER_CHANGE(j, false); set_axis_untrusted(J_AXIS); } #else #define ENABLE_AXIS_J() NOOP #define DISABLE_AXIS_J() NOOP #endif #if HAS_K_AXIS #define ENABLE_AXIS_K() if (SHOULD_ENABLE(k)) { ENABLE_STEPPER_K(); AFTER_CHANGE(k, true); } #define DISABLE_AXIS_K() if (SHOULD_DISABLE(k)) { DISABLE_STEPPER_K(); AFTER_CHANGE(k, false); set_axis_untrusted(K_AXIS); } #else #define ENABLE_AXIS_K() NOOP #define DISABLE_AXIS_K() NOOP #endif #if HAS_U_AXIS #define ENABLE_AXIS_U() if (SHOULD_ENABLE(u)) { ENABLE_STEPPER_U(); AFTER_CHANGE(u, true); } #define DISABLE_AXIS_U() if (SHOULD_DISABLE(u)) { DISABLE_STEPPER_U(); AFTER_CHANGE(u, false); set_axis_untrusted(U_AXIS); } #else #define ENABLE_AXIS_U() NOOP #define DISABLE_AXIS_U() NOOP #endif #if HAS_V_AXIS #define ENABLE_AXIS_V() if (SHOULD_ENABLE(v)) { ENABLE_STEPPER_V(); AFTER_CHANGE(v, true); } #define DISABLE_AXIS_V() if (SHOULD_DISABLE(v)) { DISABLE_STEPPER_V(); AFTER_CHANGE(v, false); set_axis_untrusted(V_AXIS); } #else #define ENABLE_AXIS_V() NOOP #define DISABLE_AXIS_V() NOOP #endif #if HAS_W_AXIS #define ENABLE_AXIS_W() if (SHOULD_ENABLE(w)) { ENABLE_STEPPER_W(); AFTER_CHANGE(w, true); } #define DISABLE_AXIS_W() if (SHOULD_DISABLE(w)) { DISABLE_STEPPER_W(); AFTER_CHANGE(w, false); set_axis_untrusted(W_AXIS); } #else #define ENABLE_AXIS_W() NOOP #define DISABLE_AXIS_W() NOOP #endif // // Extruder steppers enable / disable macros // #if ENABLED(MIXING_EXTRUDER) /** * Mixing steppers keep all their enable (and direction) states synchronized */ #define _CALL_ENA_E(N) ENABLE_STEPPER_E##N () ; #define _CALL_DIS_E(N) DISABLE_STEPPER_E##N () ; #define ENABLE_AXIS_E0() { RREPEAT(MIXING_STEPPERS, _CALL_ENA_E) } #define DISABLE_AXIS_E0() { RREPEAT(MIXING_STEPPERS, _CALL_DIS_E) } #elif ENABLED(E_DUAL_STEPPER_DRIVERS) #define ENABLE_AXIS_E0() do{ ENABLE_STEPPER_E0(); ENABLE_STEPPER_E1(); }while(0) #define DISABLE_AXIS_E0() do{ DISABLE_STEPPER_E0(); DISABLE_STEPPER_E1(); }while(0) #endif #ifndef ENABLE_AXIS_E0 #if E_STEPPERS && HAS_E0_ENABLE #define ENABLE_AXIS_E0() ENABLE_STEPPER_E0() #else #define ENABLE_AXIS_E0() NOOP #endif #endif #ifndef DISABLE_AXIS_E0 #if E_STEPPERS && HAS_E0_ENABLE #define DISABLE_AXIS_E0() DISABLE_STEPPER_E0() #else #define DISABLE_AXIS_E0() NOOP #endif #endif #ifndef ENABLE_AXIS_E1 #if E_STEPPERS > 1 && HAS_E1_ENABLE #define ENABLE_AXIS_E1() ENABLE_STEPPER_E1() #else #define ENABLE_AXIS_E1() NOOP #endif #endif #ifndef DISABLE_AXIS_E1 #if E_STEPPERS > 1 && HAS_E1_ENABLE #define DISABLE_AXIS_E1() DISABLE_STEPPER_E1() #else #define DISABLE_AXIS_E1() NOOP #endif #endif #ifndef ENABLE_AXIS_E2 #if E_STEPPERS > 2 && HAS_E2_ENABLE #define ENABLE_AXIS_E2() ENABLE_STEPPER_E2() #else #define ENABLE_AXIS_E2() NOOP #endif #endif #ifndef DISABLE_AXIS_E2 #if E_STEPPERS > 2 && HAS_E2_ENABLE #define DISABLE_AXIS_E2() DISABLE_STEPPER_E2() #else #define DISABLE_AXIS_E2() NOOP #endif #endif #ifndef ENABLE_AXIS_E3 #if E_STEPPERS > 3 && HAS_E3_ENABLE #define ENABLE_AXIS_E3() ENABLE_STEPPER_E3() #else #define ENABLE_AXIS_E3() NOOP #endif #endif #ifndef DISABLE_AXIS_E3 #if E_STEPPERS > 3 && HAS_E3_ENABLE #define DISABLE_AXIS_E3() DISABLE_STEPPER_E3() #else #define DISABLE_AXIS_E3() NOOP #endif #endif #ifndef ENABLE_AXIS_E4 #if E_STEPPERS > 4 && HAS_E4_ENABLE #define ENABLE_AXIS_E4() ENABLE_STEPPER_E4() #else #define ENABLE_AXIS_E4() NOOP #endif #endif #ifndef DISABLE_AXIS_E4 #if E_STEPPERS > 4 && HAS_E4_ENABLE #define DISABLE_AXIS_E4() DISABLE_STEPPER_E4() #else #define DISABLE_AXIS_E4() NOOP #endif #endif #ifndef ENABLE_AXIS_E5 #if E_STEPPERS > 5 && HAS_E5_ENABLE #define ENABLE_AXIS_E5() ENABLE_STEPPER_E5() #else #define ENABLE_AXIS_E5() NOOP #endif #endif #ifndef DISABLE_AXIS_E5 #if E_STEPPERS > 5 && HAS_E5_ENABLE #define DISABLE_AXIS_E5() DISABLE_STEPPER_E5() #else #define DISABLE_AXIS_E5() NOOP #endif #endif #ifndef ENABLE_AXIS_E6 #if E_STEPPERS > 6 && HAS_E6_ENABLE #define ENABLE_AXIS_E6() ENABLE_STEPPER_E6() #else #define ENABLE_AXIS_E6() NOOP #endif #endif #ifndef DISABLE_AXIS_E6 #if E_STEPPERS > 6 && HAS_E6_ENABLE #define DISABLE_AXIS_E6() DISABLE_STEPPER_E6() #else #define DISABLE_AXIS_E6() NOOP #endif #endif #ifndef ENABLE_AXIS_E7 #if E_STEPPERS > 7 && HAS_E7_ENABLE #define ENABLE_AXIS_E7() ENABLE_STEPPER_E7() #else #define ENABLE_AXIS_E7() NOOP #endif #endif #ifndef DISABLE_AXIS_E7 #if E_STEPPERS > 7 && HAS_E7_ENABLE #define DISABLE_AXIS_E7() DISABLE_STEPPER_E7() #else #define DISABLE_AXIS_E7() NOOP #endif #endif
2301_81045437/Marlin
Marlin/src/module/stepper/indirection.h
C
agpl-3.0
43,414
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #if F_CPU == 16000000 const struct { uint16_t base; uint8_t gain; } speed_lookuptable_fast[256] PROGMEM = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, // dummy first row { 977, 109 }, { 868, 87 }, { 781, 71 }, { 710, 59 }, { 651, 50 }, { 601, 43 }, { 558, 37 }, { 521, 33 }, { 488, 28 }, { 460, 26 }, { 434, 23 }, { 411, 20 }, { 391, 19 }, { 372, 17 }, { 355, 15 }, { 340, 14 }, { 326, 13 }, { 313, 13 }, { 300, 11 }, { 289, 10 }, { 279, 10 }, { 269, 9 }, { 260, 8 }, { 252, 8 }, { 244, 7 }, { 237, 7 }, { 230, 7 }, { 223, 6 }, { 217, 6 }, { 211, 5 }, { 206, 6 }, { 200, 5 }, { 195, 4 }, { 191, 5 }, { 186, 4 }, { 182, 4 }, { 178, 4 }, { 174, 4 }, { 170, 4 }, { 166, 3 }, { 163, 4 }, { 159, 3 }, { 156, 3 }, { 153, 3 }, { 150, 3 }, { 147, 2 }, { 145, 3 }, { 142, 2 }, { 140, 3 }, { 137, 2 }, { 135, 3 }, { 132, 2 }, { 130, 2 }, { 128, 2 }, { 126, 2 }, { 124, 2 }, { 122, 2 }, { 120, 2 }, { 118, 1 }, { 117, 2 }, { 115, 2 }, { 113, 1 }, { 112, 2 }, { 110, 1 }, { 109, 2 }, { 107, 1 }, { 106, 2 }, { 104, 1 }, { 103, 2 }, { 101, 1 }, { 100, 1 }, { 99, 1 }, { 98, 2 }, { 96, 1 }, { 95, 1 }, { 94, 1 }, { 93, 1 }, { 92, 1 }, { 91, 1 }, { 90, 1 }, { 89, 1 }, { 88, 1 }, { 87, 1 }, { 86, 1 }, { 85, 1 }, { 84, 1 }, { 83, 1 }, { 82, 1 }, { 81, 0 }, { 81, 1 }, { 80, 1 }, { 79, 1 }, { 78, 1 }, { 77, 0 }, { 77, 1 }, { 76, 1 }, { 75, 1 }, { 74, 0 }, { 74, 1 }, { 73, 1 }, { 72, 0 }, { 72, 1 }, { 71, 1 }, { 70, 0 }, { 70, 1 }, { 69, 0 }, { 69, 1 }, { 68, 1 }, { 67, 0 }, { 67, 1 }, { 66, 0 }, { 66, 1 }, { 65, 0 }, { 65, 1 }, { 64, 0 }, { 64, 1 }, { 63, 0 }, { 63, 1 }, { 62, 0 }, { 62, 1 }, { 61, 0 }, { 61, 1 }, { 60, 0 }, { 60, 1 }, { 59, 0 }, { 59, 1 }, { 58, 0 }, { 58, 1 }, { 57, 0 }, { 57, 0 }, { 57, 1 }, { 56, 0 }, { 56, 1 }, { 55, 0 }, { 55, 0 }, { 55, 1 }, { 54, 0 }, { 54, 0 }, { 54, 1 }, { 53, 0 }, { 53, 1 }, { 52, 0 }, { 52, 0 }, { 52, 1 }, { 51, 0 }, { 51, 0 }, { 51, 1 }, { 50, 0 }, { 50, 0 }, { 50, 1 }, { 49, 0 }, { 49, 0 }, { 49, 0 }, { 49, 1 }, { 48, 0 }, { 48, 0 }, { 48, 1 }, { 47, 0 }, { 47, 0 }, { 47, 0 }, { 47, 1 }, { 46, 0 }, { 46, 0 }, { 46, 1 }, { 45, 0 }, { 45, 0 }, { 45, 0 }, { 45, 1 }, { 44, 0 }, { 44, 0 }, { 44, 0 }, { 44, 1 }, { 43, 0 }, { 43, 0 }, { 43, 0 }, { 43, 1 }, { 42, 0 }, { 42, 0 }, { 42, 0 }, { 42, 0 }, { 42, 1 }, { 41, 0 }, { 41, 0 }, { 41, 0 }, { 41, 1 }, { 40, 0 }, { 40, 0 }, { 40, 0 }, { 40, 0 }, { 40, 1 }, { 39, 0 }, { 39, 0 }, { 39, 0 }, { 39, 0 }, { 39, 1 }, { 38, 0 }, { 38, 0 }, { 38, 0 }, { 38, 0 }, { 38, 0 }, { 38, 1 }, { 37, 0 }, { 37, 0 }, { 37, 0 }, { 37, 0 }, { 37, 0 }, { 37, 1 }, { 36, 0 }, { 36, 0 }, { 36, 0 }, { 36, 0 }, { 36, 0 }, { 36, 1 }, { 35, 0 }, { 35, 0 }, { 35, 0 }, { 35, 0 }, { 35, 0 }, { 35, 1 }, { 34, 0 }, { 34, 0 }, { 34, 0 }, { 34, 0 }, { 34, 0 }, { 34, 0 }, { 34, 1 }, { 33, 0 }, { 33, 0 }, { 33, 0 }, { 33, 0 }, { 33, 0 }, { 33, 0 }, { 33, 1 }, { 32, 0 }, { 32, 0 }, { 32, 0 }, { 32, 0 }, { 32, 0 }, { 32, 0 }, { 32, 0 }, { 32, 1 }, { 31, 0 }, { 31, 0 }, { 31, 0 }, { 31, 0 }, { 31, 0 }, { 31, 0 }, { 31, 0 }, }; const uint16_t speed_lookuptable_slow[256][2] PROGMEM = { { 62500, 12500 }, { 50000, 8333 }, { 41667, 5953 }, { 35714, 4464 }, { 31250, 3472 }, { 27778, 2778 }, { 25000, 2273 }, { 22727, 1894 }, { 20833, 1602 }, { 19231, 1374 }, { 17857, 1190 }, { 16667, 1042 }, { 15625, 919 }, { 14706, 817 }, { 13889, 731 }, { 13158, 658 }, { 12500, 595 }, { 11905, 541 }, { 11364, 494 }, { 10870, 453 }, { 10417, 417 }, { 10000, 385 }, { 9615, 356 }, { 9259, 330 }, { 8929, 308 }, { 8621, 288 }, { 8333, 268 }, { 8065, 252 }, { 7813, 237 }, { 7576, 223 }, { 7353, 210 }, { 7143, 199 }, { 6944, 187 }, { 6757, 178 }, { 6579, 169 }, { 6410, 160 }, { 6250, 152 }, { 6098, 146 }, { 5952, 138 }, { 5814, 132 }, { 5682, 126 }, { 5556, 121 }, { 5435, 116 }, { 5319, 111 }, { 5208, 106 }, { 5102, 102 }, { 5000, 98 }, { 4902, 94 }, { 4808, 91 }, { 4717, 87 }, { 4630, 85 }, { 4545, 81 }, { 4464, 78 }, { 4386, 76 }, { 4310, 73 }, { 4237, 70 }, { 4167, 69 }, { 4098, 66 }, { 4032, 64 }, { 3968, 62 }, { 3906, 60 }, { 3846, 58 }, { 3788, 57 }, { 3731, 55 }, { 3676, 53 }, { 3623, 52 }, { 3571, 50 }, { 3521, 49 }, { 3472, 47 }, { 3425, 47 }, { 3378, 45 }, { 3333, 44 }, { 3289, 42 }, { 3247, 42 }, { 3205, 40 }, { 3165, 40 }, { 3125, 39 }, { 3086, 37 }, { 3049, 37 }, { 3012, 36 }, { 2976, 35 }, { 2941, 34 }, { 2907, 33 }, { 2874, 33 }, { 2841, 32 }, { 2809, 31 }, { 2778, 31 }, { 2747, 30 }, { 2717, 29 }, { 2688, 28 }, { 2660, 28 }, { 2632, 28 }, { 2604, 27 }, { 2577, 26 }, { 2551, 26 }, { 2525, 25 }, { 2500, 25 }, { 2475, 24 }, { 2451, 24 }, { 2427, 23 }, { 2404, 23 }, { 2381, 23 }, { 2358, 22 }, { 2336, 21 }, { 2315, 21 }, { 2294, 21 }, { 2273, 21 }, { 2252, 20 }, { 2232, 20 }, { 2212, 19 }, { 2193, 19 }, { 2174, 19 }, { 2155, 18 }, { 2137, 18 }, { 2119, 18 }, { 2101, 18 }, { 2083, 17 }, { 2066, 17 }, { 2049, 16 }, { 2033, 17 }, { 2016, 16 }, { 2000, 16 }, { 1984, 15 }, { 1969, 16 }, { 1953, 15 }, { 1938, 15 }, { 1923, 15 }, { 1908, 14 }, { 1894, 14 }, { 1880, 14 }, { 1866, 14 }, { 1852, 14 }, { 1838, 13 }, { 1825, 13 }, { 1812, 13 }, { 1799, 13 }, { 1786, 13 }, { 1773, 12 }, { 1761, 13 }, { 1748, 12 }, { 1736, 12 }, { 1724, 12 }, { 1712, 11 }, { 1701, 12 }, { 1689, 11 }, { 1678, 11 }, { 1667, 11 }, { 1656, 11 }, { 1645, 11 }, { 1634, 11 }, { 1623, 10 }, { 1613, 10 }, { 1603, 11 }, { 1592, 10 }, { 1582, 10 }, { 1572, 9 }, { 1563, 10 }, { 1553, 10 }, { 1543, 9 }, { 1534, 10 }, { 1524, 9 }, { 1515, 9 }, { 1506, 9 }, { 1497, 9 }, { 1488, 9 }, { 1479, 8 }, { 1471, 9 }, { 1462, 9 }, { 1453, 8 }, { 1445, 8 }, { 1437, 8 }, { 1429, 9 }, { 1420, 8 }, { 1412, 8 }, { 1404, 7 }, { 1397, 8 }, { 1389, 8 }, { 1381, 7 }, { 1374, 8 }, { 1366, 7 }, { 1359, 8 }, { 1351, 7 }, { 1344, 7 }, { 1337, 7 }, { 1330, 7 }, { 1323, 7 }, { 1316, 7 }, { 1309, 7 }, { 1302, 7 }, { 1295, 6 }, { 1289, 7 }, { 1282, 6 }, { 1276, 7 }, { 1269, 6 }, { 1263, 7 }, { 1256, 6 }, { 1250, 6 }, { 1244, 6 }, { 1238, 6 }, { 1232, 7 }, { 1225, 5 }, { 1220, 6 }, { 1214, 6 }, { 1208, 6 }, { 1202, 6 }, { 1196, 6 }, { 1190, 5 }, { 1185, 6 }, { 1179, 5 }, { 1174, 6 }, { 1168, 5 }, { 1163, 6 }, { 1157, 5 }, { 1152, 5 }, { 1147, 5 }, { 1142, 6 }, { 1136, 5 }, { 1131, 5 }, { 1126, 5 }, { 1121, 5 }, { 1116, 5 }, { 1111, 5 }, { 1106, 5 }, { 1101, 5 }, { 1096, 4 }, { 1092, 5 }, { 1087, 5 }, { 1082, 4 }, { 1078, 5 }, { 1073, 5 }, { 1068, 4 }, { 1064, 5 }, { 1059, 4 }, { 1055, 5 }, { 1050, 4 }, { 1046, 4 }, { 1042, 5 }, { 1037, 4 }, { 1033, 4 }, { 1029, 4 }, { 1025, 5 }, { 1020, 4 }, { 1016, 4 }, { 1012, 4 }, { 1008, 4 }, { 1004, 4 }, { 1000, 4 }, { 996, 4 }, { 992, 4 }, { 988, 4 }, { 984, 4 }, { 980, 3 }, { 977, 4 }, { 973, 4 }, { 969, 4 }, { 965, 4 }, }; #elif F_CPU == 20000000 const struct { uint16_t base; uint8_t gain; } speed_lookuptable_fast[256] PROGMEM = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, // dummy first row { 1221, 136 }, { 1085, 108 }, { 977, 89 }, { 888, 74 }, { 814, 63 }, { 751, 53 }, { 698, 47 }, { 651, 41 }, { 610, 36 }, { 574, 31 }, { 543, 29 }, { 514, 26 }, { 488, 23 }, { 465, 21 }, { 444, 19 }, { 425, 18 }, { 407, 16 }, { 391, 15 }, { 376, 14 }, { 362, 13 }, { 349, 12 }, { 337, 11 }, { 326, 11 }, { 315, 10 }, { 305, 9 }, { 296, 9 }, { 287, 8 }, { 279, 8 }, { 271, 7 }, { 264, 7 }, { 257, 7 }, { 250, 6 }, { 244, 6 }, { 238, 5 }, { 233, 6 }, { 227, 5 }, { 222, 5 }, { 217, 5 }, { 212, 4 }, { 208, 5 }, { 203, 4 }, { 199, 4 }, { 195, 4 }, { 191, 3 }, { 188, 4 }, { 184, 3 }, { 181, 3 }, { 178, 4 }, { 174, 3 }, { 171, 3 }, { 168, 2 }, { 166, 3 }, { 163, 3 }, { 160, 2 }, { 158, 3 }, { 155, 2 }, { 153, 3 }, { 150, 2 }, { 148, 2 }, { 146, 2 }, { 144, 2 }, { 142, 2 }, { 140, 2 }, { 138, 2 }, { 136, 2 }, { 134, 2 }, { 132, 2 }, { 130, 2 }, { 128, 1 }, { 127, 2 }, { 125, 1 }, { 124, 2 }, { 122, 1 }, { 121, 2 }, { 119, 1 }, { 118, 2 }, { 116, 1 }, { 115, 1 }, { 114, 2 }, { 112, 1 }, { 111, 1 }, { 110, 1 }, { 109, 2 }, { 107, 1 }, { 106, 1 }, { 105, 1 }, { 104, 1 }, { 103, 1 }, { 102, 1 }, { 101, 1 }, { 100, 1 }, { 99, 1 }, { 98, 1 }, { 97, 1 }, { 96, 1 }, { 95, 1 }, { 94, 1 }, { 93, 1 }, { 92, 1 }, { 91, 1 }, { 90, 0 }, { 90, 1 }, { 89, 1 }, { 88, 1 }, { 87, 1 }, { 86, 0 }, { 86, 1 }, { 85, 1 }, { 84, 1 }, { 83, 0 }, { 83, 1 }, { 82, 1 }, { 81, 0 }, { 81, 1 }, { 80, 1 }, { 79, 0 }, { 79, 1 }, { 78, 0 }, { 78, 1 }, { 77, 1 }, { 76, 0 }, { 76, 1 }, { 75, 0 }, { 75, 1 }, { 74, 1 }, { 73, 0 }, { 73, 1 }, { 72, 0 }, { 72, 1 }, { 71, 0 }, { 71, 1 }, { 70, 0 }, { 70, 1 }, { 69, 0 }, { 69, 1 }, { 68, 0 }, { 68, 1 }, { 67, 0 }, { 67, 1 }, { 66, 0 }, { 66, 0 }, { 66, 1 }, { 65, 0 }, { 65, 1 }, { 64, 0 }, { 64, 1 }, { 63, 0 }, { 63, 0 }, { 63, 1 }, { 62, 0 }, { 62, 1 }, { 61, 0 }, { 61, 0 }, { 61, 1 }, { 60, 0 }, { 60, 0 }, { 60, 1 }, { 59, 0 }, { 59, 1 }, { 58, 0 }, { 58, 0 }, { 58, 1 }, { 57, 0 }, { 57, 0 }, { 57, 1 }, { 56, 0 }, { 56, 0 }, { 56, 1 }, { 55, 0 }, { 55, 0 }, { 55, 0 }, { 55, 1 }, { 54, 0 }, { 54, 0 }, { 54, 1 }, { 53, 0 }, { 53, 0 }, { 53, 0 }, { 53, 1 }, { 52, 0 }, { 52, 0 }, { 52, 1 }, { 51, 0 }, { 51, 0 }, { 51, 0 }, { 51, 1 }, { 50, 0 }, { 50, 0 }, { 50, 0 }, { 50, 1 }, { 49, 0 }, { 49, 0 }, { 49, 0 }, { 49, 1 }, { 48, 0 }, { 48, 0 }, { 48, 0 }, { 48, 1 }, { 47, 0 }, { 47, 0 }, { 47, 0 }, { 47, 0 }, { 47, 1 }, { 46, 0 }, { 46, 0 }, { 46, 0 }, { 46, 1 }, { 45, 0 }, { 45, 0 }, { 45, 0 }, { 45, 0 }, { 45, 1 }, { 44, 0 }, { 44, 0 }, { 44, 0 }, { 44, 0 }, { 44, 1 }, { 43, 0 }, { 43, 0 }, { 43, 0 }, { 43, 0 }, { 43, 1 }, { 42, 0 }, { 42, 0 }, { 42, 0 }, { 42, 0 }, { 42, 0 }, { 42, 1 }, { 41, 0 }, { 41, 0 }, { 41, 0 }, { 41, 0 }, { 41, 0 }, { 41, 1 }, { 40, 0 }, { 40, 0 }, { 40, 0 }, { 40, 0 }, { 40, 0 }, { 40, 1 }, { 39, 0 }, { 39, 0 }, { 39, 0 }, { 39, 0 }, { 39, 0 }, { 39, 1 }, { 38, 0 }, { 38, 0 }, }; const uint16_t speed_lookuptable_slow[256][2] PROGMEM = { { 62500, 10417 }, { 52083, 7440 }, { 44643, 5580 }, { 39063, 4341 }, { 34722, 3472 }, { 31250, 2841 }, { 28409, 2367 }, { 26042, 2004 }, { 24038, 1717 }, { 22321, 1488 }, { 20833, 1302 }, { 19531, 1149 }, { 18382, 1021 }, { 17361, 914 }, { 16447, 822 }, { 15625, 744 }, { 14881, 676 }, { 14205, 618 }, { 13587, 566 }, { 13021, 521 }, { 12500, 481 }, { 12019, 445 }, { 11574, 413 }, { 11161, 385 }, { 10776, 359 }, { 10417, 336 }, { 10081, 315 }, { 9766, 296 }, { 9470, 279 }, { 9191, 262 }, { 8929, 248 }, { 8681, 235 }, { 8446, 222 }, { 8224, 211 }, { 8013, 200 }, { 7813, 191 }, { 7622, 182 }, { 7440, 173 }, { 7267, 165 }, { 7102, 158 }, { 6944, 151 }, { 6793, 144 }, { 6649, 139 }, { 6510, 132 }, { 6378, 128 }, { 6250, 123 }, { 6127, 117 }, { 6010, 114 }, { 5896, 109 }, { 5787, 105 }, { 5682, 102 }, { 5580, 98 }, { 5482, 94 }, { 5388, 91 }, { 5297, 89 }, { 5208, 85 }, { 5123, 83 }, { 5040, 80 }, { 4960, 77 }, { 4883, 75 }, { 4808, 73 }, { 4735, 71 }, { 4664, 68 }, { 4596, 67 }, { 4529, 65 }, { 4464, 63 }, { 4401, 61 }, { 4340, 59 }, { 4281, 58 }, { 4223, 56 }, { 4167, 55 }, { 4112, 54 }, { 4058, 52 }, { 4006, 50 }, { 3956, 50 }, { 3906, 48 }, { 3858, 47 }, { 3811, 46 }, { 3765, 45 }, { 3720, 44 }, { 3676, 42 }, { 3634, 42 }, { 3592, 41 }, { 3551, 40 }, { 3511, 39 }, { 3472, 38 }, { 3434, 37 }, { 3397, 37 }, { 3360, 36 }, { 3324, 35 }, { 3289, 34 }, { 3255, 33 }, { 3222, 33 }, { 3189, 32 }, { 3157, 32 }, { 3125, 31 }, { 3094, 30 }, { 3064, 30 }, { 3034, 29 }, { 3005, 29 }, { 2976, 28 }, { 2948, 27 }, { 2921, 27 }, { 2894, 27 }, { 2867, 26 }, { 2841, 26 }, { 2815, 25 }, { 2790, 25 }, { 2765, 24 }, { 2741, 24 }, { 2717, 23 }, { 2694, 23 }, { 2671, 23 }, { 2648, 22 }, { 2626, 22 }, { 2604, 21 }, { 2583, 22 }, { 2561, 20 }, { 2541, 21 }, { 2520, 20 }, { 2500, 20 }, { 2480, 19 }, { 2461, 20 }, { 2441, 19 }, { 2422, 18 }, { 2404, 19 }, { 2385, 18 }, { 2367, 17 }, { 2350, 18 }, { 2332, 17 }, { 2315, 17 }, { 2298, 17 }, { 2281, 17 }, { 2264, 16 }, { 2248, 16 }, { 2232, 16 }, { 2216, 15 }, { 2201, 16 }, { 2185, 15 }, { 2170, 15 }, { 2155, 15 }, { 2140, 14 }, { 2126, 15 }, { 2111, 14 }, { 2097, 14 }, { 2083, 13 }, { 2070, 14 }, { 2056, 14 }, { 2042, 13 }, { 2029, 13 }, { 2016, 13 }, { 2003, 13 }, { 1990, 12 }, { 1978, 13 }, { 1965, 12 }, { 1953, 12 }, { 1941, 12 }, { 1929, 12 }, { 1917, 12 }, { 1905, 11 }, { 1894, 11 }, { 1883, 12 }, { 1871, 11 }, { 1860, 11 }, { 1849, 11 }, { 1838, 11 }, { 1827, 10 }, { 1817, 11 }, { 1806, 10 }, { 1796, 10 }, { 1786, 10 }, { 1776, 10 }, { 1766, 10 }, { 1756, 10 }, { 1746, 10 }, { 1736, 9 }, { 1727, 10 }, { 1717, 9 }, { 1708, 10 }, { 1698, 9 }, { 1689, 9 }, { 1680, 9 }, { 1671, 9 }, { 1662, 9 }, { 1653, 8 }, { 1645, 9 }, { 1636, 8 }, { 1628, 9 }, { 1619, 8 }, { 1611, 8 }, { 1603, 9 }, { 1594, 8 }, { 1586, 8 }, { 1578, 8 }, { 1570, 7 }, { 1563, 8 }, { 1555, 8 }, { 1547, 8 }, { 1539, 7 }, { 1532, 8 }, { 1524, 7 }, { 1517, 7 }, { 1510, 8 }, { 1502, 7 }, { 1495, 7 }, { 1488, 7 }, { 1481, 7 }, { 1474, 7 }, { 1467, 7 }, { 1460, 7 }, { 1453, 6 }, { 1447, 7 }, { 1440, 7 }, { 1433, 6 }, { 1427, 7 }, { 1420, 6 }, { 1414, 6 }, { 1408, 7 }, { 1401, 6 }, { 1395, 6 }, { 1389, 6 }, { 1383, 6 }, { 1377, 6 }, { 1371, 6 }, { 1365, 6 }, { 1359, 6 }, { 1353, 6 }, { 1347, 6 }, { 1341, 6 }, { 1335, 5 }, { 1330, 6 }, { 1324, 5 }, { 1319, 6 }, { 1313, 5 }, { 1308, 6 }, { 1302, 5 }, { 1297, 6 }, { 1291, 5 }, { 1286, 5 }, { 1281, 5 }, { 1276, 6 }, { 1270, 5 }, { 1265, 5 }, { 1260, 5 }, { 1255, 5 }, { 1250, 5 }, { 1245, 5 }, { 1240, 5 }, { 1235, 5 }, { 1230, 5 }, { 1225, 4 }, { 1221, 5 }, { 1216, 5 }, { 1211, 4 }, { 1207, 5 }, { 1202, 5 }, }; #endif
2301_81045437/Marlin
Marlin/src/module/stepper/speed_lookuptable.h
C
agpl-3.0
20,233
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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/trinamic.cpp * Stepper driver indirection for Trinamic */ #include "../../inc/MarlinConfig.h" #if HAS_TRINAMIC_CONFIG #include "trinamic.h" #include "../stepper.h" #include <HardwareSerial.h> #include <SPI.h> enum StealthIndex : uint8_t { LOGICAL_AXIS_LIST(STEALTH_AXIS_E, STEALTH_AXIS_X, STEALTH_AXIS_Y, STEALTH_AXIS_Z, STEALTH_AXIS_I, STEALTH_AXIS_J, STEALTH_AXIS_K, STEALTH_AXIS_U, STEALTH_AXIS_V, STEALTH_AXIS_W) }; #define TMC_INIT(ST, STEALTH_INDEX) tmc_init(stepper##ST, ST##_CURRENT, ST##_MICROSTEPS, ST##_HYBRID_THRESHOLD, stealthchop_by_axis[STEALTH_INDEX], chopper_timing_##ST, ST##_INTERPOLATE, ST##_HOLD_MULTIPLIER) // IC = TMC model number // ST = Stepper object letter // L = Label characters // AI = Axis Enum Index // SWHW = SW/SH UART selection #if ENABLED(TMC_USE_SW_SPI) #define __TMC_SPI_DEFINE(IC, ST, L, AI) TMCMarlin<IC##Stepper, L, AI> stepper##ST(ST##_CS_PIN, float(ST##_RSENSE), TMC_SPI_MOSI, TMC_SPI_MISO, TMC_SPI_SCK, ST##_CHAIN_POS) #else #define __TMC_SPI_DEFINE(IC, ST, L, AI) TMCMarlin<IC##Stepper, L, AI> stepper##ST(ST##_CS_PIN, float(ST##_RSENSE), ST##_CHAIN_POS) #endif #if ENABLED(TMC_SERIAL_MULTIPLEXER) #define TMC_UART_HW_DEFINE(IC, ST, L, AI) TMCMarlin<IC##Stepper, L, AI> stepper##ST(&ST##_HARDWARE_SERIAL, float(ST##_RSENSE), ST##_SLAVE_ADDRESS, SERIAL_MUL_PIN1, SERIAL_MUL_PIN2) #else #define TMC_UART_HW_DEFINE(IC, ST, L, AI) TMCMarlin<IC##Stepper, L, AI> stepper##ST(&ST##_HARDWARE_SERIAL, float(ST##_RSENSE), ST##_SLAVE_ADDRESS) #endif #define TMC_UART_SW_DEFINE(IC, ST, L, AI) TMCMarlin<IC##Stepper, L, AI> stepper##ST(ST##_SERIAL_RX_PIN, ST##_SERIAL_TX_PIN, float(ST##_RSENSE), ST##_SLAVE_ADDRESS) #define _TMC_SPI_DEFINE(IC, ST, AI) __TMC_SPI_DEFINE(IC, ST, TMC_##ST##_LABEL, AI) #define TMC_SPI_DEFINE(ST, AI) _TMC_SPI_DEFINE(ST##_DRIVER_TYPE, ST, AI##_AXIS) #define _TMC_UART_DEFINE(SWHW, IC, ST, AI) TMC_UART_##SWHW##_DEFINE(IC, ST, TMC_##ST##_LABEL, AI) #define TMC_UART_DEFINE(SWHW, ST, AI) _TMC_UART_DEFINE(SWHW, ST##_DRIVER_TYPE, ST, AI##_AXIS) #if ENABLED(DISTINCT_E_FACTORS) #define TMC_SPI_DEFINE_E(AI) TMC_SPI_DEFINE(E##AI, E##AI) #define TMC_UART_DEFINE_E(SWHW, AI) TMC_UART_DEFINE(SWHW, E##AI, E##AI) #else #define TMC_SPI_DEFINE_E(AI) TMC_SPI_DEFINE(E##AI, E) #define TMC_UART_DEFINE_E(SWHW, AI) TMC_UART_DEFINE(SWHW, E##AI, E) #endif // Stepper objects of TMC2130/TMC2160/TMC2660/TMC5130/TMC5160 steppers used #if AXIS_HAS_SPI(X) TMC_SPI_DEFINE(X, X); #endif #if AXIS_HAS_SPI(X2) TMC_SPI_DEFINE(X2, X); #endif #if AXIS_HAS_SPI(Y) TMC_SPI_DEFINE(Y, Y); #endif #if AXIS_HAS_SPI(Y2) TMC_SPI_DEFINE(Y2, Y); #endif #if AXIS_HAS_SPI(Z) TMC_SPI_DEFINE(Z, Z); #endif #if AXIS_HAS_SPI(Z2) TMC_SPI_DEFINE(Z2, Z); #endif #if AXIS_HAS_SPI(Z3) TMC_SPI_DEFINE(Z3, Z); #endif #if AXIS_HAS_SPI(Z4) TMC_SPI_DEFINE(Z4, Z); #endif #if AXIS_HAS_SPI(I) TMC_SPI_DEFINE(I, I); #endif #if AXIS_HAS_SPI(J) TMC_SPI_DEFINE(J, J); #endif #if AXIS_HAS_SPI(K) TMC_SPI_DEFINE(K, K); #endif #if AXIS_HAS_SPI(U) TMC_SPI_DEFINE(U, U); #endif #if AXIS_HAS_SPI(V) TMC_SPI_DEFINE(V, V); #endif #if AXIS_HAS_SPI(W) TMC_SPI_DEFINE(W, W); #endif #if AXIS_HAS_SPI(E0) TMC_SPI_DEFINE_E(0); #endif #if AXIS_HAS_SPI(E1) TMC_SPI_DEFINE_E(1); #endif #if AXIS_HAS_SPI(E2) TMC_SPI_DEFINE_E(2); #endif #if AXIS_HAS_SPI(E3) TMC_SPI_DEFINE_E(3); #endif #if AXIS_HAS_SPI(E4) TMC_SPI_DEFINE_E(4); #endif #if AXIS_HAS_SPI(E5) TMC_SPI_DEFINE_E(5); #endif #if AXIS_HAS_SPI(E6) TMC_SPI_DEFINE_E(6); #endif #if AXIS_HAS_SPI(E7) TMC_SPI_DEFINE_E(7); #endif #ifndef TMC_BAUD_RATE // Reduce baud rate for boards not already overriding TMC_BAUD_RATE for software serial. // Testing has shown that 115200 is not 100% reliable on AVR platforms, occasionally // failing to read status properly. 32-bit platforms typically define an even lower // TMC_BAUD_RATE, due to differences in how SoftwareSerial libraries work on different // platforms. #define TMC_BAUD_RATE TERN(HAS_TMC_SW_SERIAL, 57600, 115200) #endif #ifndef TMC_X_BAUD_RATE #define TMC_X_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_X2_BAUD_RATE #define TMC_X2_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_Y_BAUD_RATE #define TMC_Y_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_Y2_BAUD_RATE #define TMC_Y2_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_Z_BAUD_RATE #define TMC_Z_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_Z2_BAUD_RATE #define TMC_Z2_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_Z3_BAUD_RATE #define TMC_Z3_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_Z4_BAUD_RATE #define TMC_Z4_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_I_BAUD_RATE #define TMC_I_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_J_BAUD_RATE #define TMC_J_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_K_BAUD_RATE #define TMC_K_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_U_BAUD_RATE #define TMC_U_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_V_BAUD_RATE #define TMC_V_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_W_BAUD_RATE #define TMC_W_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_E0_BAUD_RATE #define TMC_E0_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_E1_BAUD_RATE #define TMC_E1_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_E2_BAUD_RATE #define TMC_E2_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_E3_BAUD_RATE #define TMC_E3_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_E4_BAUD_RATE #define TMC_E4_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_E5_BAUD_RATE #define TMC_E5_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_E6_BAUD_RATE #define TMC_E6_BAUD_RATE TMC_BAUD_RATE #endif #ifndef TMC_E7_BAUD_RATE #define TMC_E7_BAUD_RATE TMC_BAUD_RATE #endif #if HAS_DRIVER(TMC2130) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC2130Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t hyb_thrs, const bool stealth, const chopper_timing_t &chop_init, const bool interpolate, float hold_multiplier) { st.begin(); CHOPCONF_t chopconf{0}; chopconf.tbl = 0b01; chopconf.toff = chop_init.toff; chopconf.intpol = interpolate; chopconf.hend = chop_init.hend + 3; chopconf.hstrt = chop_init.hstrt - 1; TERN_(EDGE_STEPPING, chopconf.dedge = true); st.CHOPCONF(chopconf.sr); st.rms_current(mA, hold_multiplier); st.microsteps(microsteps); st.iholddelay(10); st.TPOWERDOWN(128); // ~2s until driver lowers to hold current st.en_pwm_mode(stealth); st.stored.stealthChop_enabled = stealth; PWMCONF_t pwmconf{0}; pwmconf.pwm_freq = 0b01; // f_pwm = 2/683 f_clk pwmconf.pwm_autoscale = true; pwmconf.pwm_grad = 5; pwmconf.pwm_ampl = 180; st.PWMCONF(pwmconf.sr); TERN(HYBRID_THRESHOLD, st.set_pwm_thrs(hyb_thrs), UNUSED(hyb_thrs)); st.GSTAT(); // Clear GSTAT } #endif // TMC2130 #if HAS_DRIVER(TMC2160) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC2160Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t hyb_thrs, const bool stealth, const chopper_timing_t &chop_init, const bool interpolate, float hold_multiplier) { st.begin(); CHOPCONF_t chopconf{0}; chopconf.tbl = 0b01; chopconf.toff = chop_init.toff; chopconf.intpol = interpolate; chopconf.hend = chop_init.hend + 3; chopconf.hstrt = chop_init.hstrt - 1; TERN_(EDGE_STEPPING, chopconf.dedge = true); st.CHOPCONF(chopconf.sr); st.rms_current(mA, hold_multiplier); st.microsteps(microsteps); st.iholddelay(10); st.TPOWERDOWN(128); // ~2s until driver lowers to hold current st.en_pwm_mode(stealth); st.stored.stealthChop_enabled = stealth; TMC2160_n::PWMCONF_t pwmconf{0}; pwmconf.pwm_lim = 12; pwmconf.pwm_reg = 8; pwmconf.pwm_autograd = true; pwmconf.pwm_autoscale = true; pwmconf.pwm_freq = 0b01; pwmconf.pwm_grad = 14; pwmconf.pwm_ofs = 36; st.PWMCONF(pwmconf.sr); TERN(HYBRID_THRESHOLD, st.set_pwm_thrs(hyb_thrs), UNUSED(hyb_thrs)); st.GSTAT(); // Clear GSTAT } #endif // TMC2160 // // TMC2208/2209 Driver objects and inits // #if HAS_TMC220x #if AXIS_HAS_UART(X) #ifdef X_HARDWARE_SERIAL TMC_UART_DEFINE(HW, X, X); #define X_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, X, X); #define X_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(X2) #ifdef X2_HARDWARE_SERIAL TMC_UART_DEFINE(HW, X2, X); #define X2_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, X2, X); #define X2_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(Y) #ifdef Y_HARDWARE_SERIAL TMC_UART_DEFINE(HW, Y, Y); #define Y_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, Y, Y); #define Y_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(Y2) #ifdef Y2_HARDWARE_SERIAL TMC_UART_DEFINE(HW, Y2, Y); #define Y2_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, Y2, Y); #define Y2_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(Z) #ifdef Z_HARDWARE_SERIAL TMC_UART_DEFINE(HW, Z, Z); #define Z_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, Z, Z); #define Z_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(Z2) #ifdef Z2_HARDWARE_SERIAL TMC_UART_DEFINE(HW, Z2, Z); #define Z2_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, Z2, Z); #define Z2_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(Z3) #ifdef Z3_HARDWARE_SERIAL TMC_UART_DEFINE(HW, Z3, Z); #define Z3_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, Z3, Z); #define Z3_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(Z4) #ifdef Z4_HARDWARE_SERIAL TMC_UART_DEFINE(HW, Z4, Z); #define Z4_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, Z4, Z); #define Z4_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(I) #ifdef I_HARDWARE_SERIAL TMC_UART_DEFINE(HW, I, I); #define I_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, I, I); #define I_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(J) #ifdef J_HARDWARE_SERIAL TMC_UART_DEFINE(HW, J, J); #define J_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, J, J); #define J_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(K) #ifdef K_HARDWARE_SERIAL TMC_UART_DEFINE(HW, K, K); #define K_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, K, K); #define K_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(U) #ifdef U_HARDWARE_SERIAL TMC_UART_DEFINE(HW, U, U); #define U_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, U, U); #define U_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(V) #ifdef V_HARDWARE_SERIAL TMC_UART_DEFINE(HW, V, V); #else TMC_UART_DEFINE(SW, V, V); #define V_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(W) #ifdef W_HARDWARE_SERIAL TMC_UART_DEFINE(HW, W, W); #define W_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE(SW, W, W); #define W_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(E0) #ifdef E0_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 0); #define E0_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE_E(SW, 0); #define E0_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(E1) #ifdef E1_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 1); #define E1_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE_E(SW, 1); #define E1_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(E2) #ifdef E2_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 2); #define E2_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE_E(SW, 2); #define E2_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(E3) #ifdef E3_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 3); #define E3_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE_E(SW, 3); #define E3_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(E4) #ifdef E4_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 4); #define E4_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE_E(SW, 4); #define E4_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(E5) #ifdef E5_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 5); #define E5_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE_E(SW, 5); #define E5_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(E6) #ifdef E6_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 6); #define E6_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE_E(SW, 6); #define E6_HAS_SW_SERIAL 1 #endif #endif #if AXIS_HAS_UART(E7) #ifdef E7_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 7); #define E7_HAS_HW_SERIAL 1 #else TMC_UART_DEFINE_E(SW, 7); #define E7_HAS_SW_SERIAL 1 #endif #endif #define _EN_ITEM(N) , E##N enum TMCAxis : uint8_t { MAIN_AXIS_NAMES_ X2, Y2, Z2, Z3, Z4 REPEAT(EXTRUDERS, _EN_ITEM), TOTAL }; #undef _EN_ITEM void tmc_serial_begin() { #if HAS_TMC_HW_SERIAL struct { const void *ptr[TMCAxis::TOTAL]; bool began(const TMCAxis a, const void * const p) { for (uint8_t i = 0; i < a; ++i) if (p == ptr[i]) return true; ptr[a] = p; return false; }; } sp_helper; #define HW_SERIAL_BEGIN(A) do{ if (!sp_helper.began(TMCAxis::A, &A##_HARDWARE_SERIAL)) \ A##_HARDWARE_SERIAL.begin(TMC_##A##_BAUD_RATE); }while(0) #endif #if AXIS_HAS_UART(X) #ifdef X_HARDWARE_SERIAL HW_SERIAL_BEGIN(X); #else stepperX.beginSerial(TMC_X_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(X2) #ifdef X2_HARDWARE_SERIAL HW_SERIAL_BEGIN(X2); #else stepperX2.beginSerial(TMC_X2_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(Y) #ifdef Y_HARDWARE_SERIAL HW_SERIAL_BEGIN(Y); #else stepperY.beginSerial(TMC_Y_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(Y2) #ifdef Y2_HARDWARE_SERIAL HW_SERIAL_BEGIN(Y2); #else stepperY2.beginSerial(TMC_Y2_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(Z) #ifdef Z_HARDWARE_SERIAL HW_SERIAL_BEGIN(Z); #else stepperZ.beginSerial(TMC_Z_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(Z2) #ifdef Z2_HARDWARE_SERIAL HW_SERIAL_BEGIN(Z2); #else stepperZ2.beginSerial(TMC_Z2_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(Z3) #ifdef Z3_HARDWARE_SERIAL HW_SERIAL_BEGIN(Z3); #else stepperZ3.beginSerial(TMC_Z3_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(Z4) #ifdef Z4_HARDWARE_SERIAL HW_SERIAL_BEGIN(Z4); #else stepperZ4.beginSerial(TMC_Z4_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(I) #ifdef I_HARDWARE_SERIAL HW_SERIAL_BEGIN(I); #else stepperI.beginSerial(TMC_I_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(J) #ifdef J_HARDWARE_SERIAL HW_SERIAL_BEGIN(J); #else stepperJ.beginSerial(TMC_J_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(K) #ifdef K_HARDWARE_SERIAL HW_SERIAL_BEGIN(K); #else stepperK.beginSerial(TMC_K_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(U) #ifdef U_HARDWARE_SERIAL HW_SERIAL_BEGIN(U); #else stepperU.beginSerial(TMC_U_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(V) #ifdef V_HARDWARE_SERIAL HW_SERIAL_BEGIN(V); #else stepperV.beginSerial(TMC_V_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(W) #ifdef W_HARDWARE_SERIAL HW_SERIAL_BEGIN(W); #else stepperW.beginSerial(TMC_W_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E0) #ifdef E0_HARDWARE_SERIAL HW_SERIAL_BEGIN(E0); #else stepperE0.beginSerial(TMC_E0_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E1) #ifdef E1_HARDWARE_SERIAL HW_SERIAL_BEGIN(E1); #else stepperE1.beginSerial(TMC_E1_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E2) #ifdef E2_HARDWARE_SERIAL HW_SERIAL_BEGIN(E2); #else stepperE2.beginSerial(TMC_E2_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E3) #ifdef E3_HARDWARE_SERIAL HW_SERIAL_BEGIN(E3); #else stepperE3.beginSerial(TMC_E3_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E4) #ifdef E4_HARDWARE_SERIAL HW_SERIAL_BEGIN(E4); #else stepperE4.beginSerial(TMC_E4_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E5) #ifdef E5_HARDWARE_SERIAL HW_SERIAL_BEGIN(E5); #else stepperE5.beginSerial(TMC_E5_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E6) #ifdef E6_HARDWARE_SERIAL HW_SERIAL_BEGIN(E6); #else stepperE6.beginSerial(TMC_E6_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E7) #ifdef E7_HARDWARE_SERIAL HW_SERIAL_BEGIN(E7); #else stepperE7.beginSerial(TMC_E7_BAUD_RATE); #endif #endif } #endif #if HAS_DRIVER(TMC2208) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC2208Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t hyb_thrs, const bool stealth, const chopper_timing_t &chop_init, const bool interpolate, float hold_multiplier) { TMC2208_n::GCONF_t gconf{0}; gconf.pdn_disable = true; // Use UART gconf.mstep_reg_select = true; // Select microsteps with UART gconf.i_scale_analog = false; gconf.en_spreadcycle = !stealth; st.GCONF(gconf.sr); st.stored.stealthChop_enabled = stealth; TMC2208_n::CHOPCONF_t chopconf{0}; chopconf.tbl = 0b01; // blank_time = 24 chopconf.toff = chop_init.toff; chopconf.intpol = interpolate; chopconf.hend = chop_init.hend + 3; chopconf.hstrt = chop_init.hstrt - 1; TERN_(EDGE_STEPPING, chopconf.dedge = true); st.CHOPCONF(chopconf.sr); st.rms_current(mA, hold_multiplier); st.microsteps(microsteps); st.iholddelay(10); st.TPOWERDOWN(128); // ~2s until driver lowers to hold current TMC2208_n::PWMCONF_t pwmconf{0}; pwmconf.pwm_lim = 12; pwmconf.pwm_reg = 8; pwmconf.pwm_autograd = true; pwmconf.pwm_autoscale = true; pwmconf.pwm_freq = 0b01; pwmconf.pwm_grad = 14; pwmconf.pwm_ofs = 36; st.PWMCONF(pwmconf.sr); TERN(HYBRID_THRESHOLD, st.set_pwm_thrs(hyb_thrs), UNUSED(hyb_thrs)); st.GSTAT(0b111); // Clear delay(200); } #endif // TMC2208 #if HAS_DRIVER(TMC2209) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC2209Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t hyb_thrs, const bool stealth, const chopper_timing_t &chop_init, const bool interpolate, float hold_multiplier) { TMC2208_n::GCONF_t gconf{0}; gconf.pdn_disable = true; // Use UART gconf.mstep_reg_select = true; // Select microsteps with UART gconf.i_scale_analog = false; gconf.en_spreadcycle = !stealth; st.GCONF(gconf.sr); st.stored.stealthChop_enabled = stealth; TMC2208_n::CHOPCONF_t chopconf{0}; chopconf.tbl = 0b01; // blank_time = 24 chopconf.toff = chop_init.toff; chopconf.intpol = interpolate; chopconf.hend = chop_init.hend + 3; chopconf.hstrt = chop_init.hstrt - 1; TERN_(EDGE_STEPPING, chopconf.dedge = true); st.CHOPCONF(chopconf.sr); st.rms_current(mA, hold_multiplier); st.microsteps(microsteps); st.iholddelay(10); st.TPOWERDOWN(128); // ~2s until driver lowers to hold current TMC2208_n::PWMCONF_t pwmconf{0}; pwmconf.pwm_lim = 12; pwmconf.pwm_reg = 8; pwmconf.pwm_autograd = true; pwmconf.pwm_autoscale = true; pwmconf.pwm_freq = 0b01; pwmconf.pwm_grad = 14; pwmconf.pwm_ofs = 36; st.PWMCONF(pwmconf.sr); TERN(HYBRID_THRESHOLD, st.set_pwm_thrs(hyb_thrs), UNUSED(hyb_thrs)); st.GSTAT(0b111); // Clear delay(200); } #endif // TMC2209 #if HAS_DRIVER(TMC2660) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC2660Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t, const bool, const chopper_timing_t &chop_init, const bool interpolate, float hold_multiplier) { st.begin(); TMC2660_n::CHOPCONF_t chopconf{0}; chopconf.tbl = 0b01; chopconf.toff = chop_init.toff; chopconf.hend = chop_init.hend + 3; chopconf.hstrt = chop_init.hstrt - 1; st.CHOPCONF(chopconf.sr); st.sdoff(0); st.rms_current(mA); st.microsteps(microsteps); TERN_(EDGE_STEPPING, st.dedge(true)); st.intpol(interpolate); st.diss2g(true); // Disable short to ground protection. Too many false readings? TERN_(TMC_DEBUG, st.rdsel(0b01)); } #endif // TMC2660 #if HAS_DRIVER(TMC5130) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC5130Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t hyb_thrs, const bool stealth, const chopper_timing_t &chop_init, const bool interpolate, float hold_multiplier) { st.begin(); CHOPCONF_t chopconf{0}; chopconf.tbl = 0b01; chopconf.toff = chop_init.toff; chopconf.intpol = interpolate; chopconf.hend = chop_init.hend + 3; chopconf.hstrt = chop_init.hstrt - 1; TERN_(EDGE_STEPPING, chopconf.dedge = true); st.CHOPCONF(chopconf.sr); st.rms_current(mA, hold_multiplier); st.microsteps(microsteps); st.iholddelay(10); st.TPOWERDOWN(128); // ~2s until driver lowers to hold current st.en_pwm_mode(stealth); st.stored.stealthChop_enabled = stealth; PWMCONF_t pwmconf{0}; pwmconf.pwm_freq = 0b01; // f_pwm = 2/683 f_clk pwmconf.pwm_autoscale = true; pwmconf.pwm_grad = 5; pwmconf.pwm_ampl = 180; st.PWMCONF(pwmconf.sr); TERN(HYBRID_THRESHOLD, st.set_pwm_thrs(hyb_thrs), UNUSED(hyb_thrs)); st.GSTAT(); // Clear GSTAT } #endif // TMC5130 #if HAS_DRIVER(TMC5160) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC5160Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t hyb_thrs, const bool stealth, const chopper_timing_t &chop_init, const bool interpolate, float hold_multiplier) { st.begin(); CHOPCONF_t chopconf{0}; chopconf.tbl = 0b01; chopconf.toff = chop_init.toff; chopconf.intpol = interpolate; chopconf.hend = chop_init.hend + 3; chopconf.hstrt = chop_init.hstrt - 1; TERN_(EDGE_STEPPING, chopconf.dedge = true); st.CHOPCONF(chopconf.sr); st.rms_current(mA, hold_multiplier); st.microsteps(microsteps); st.iholddelay(10); st.TPOWERDOWN(128); // ~2s until driver lowers to hold current st.en_pwm_mode(stealth); st.stored.stealthChop_enabled = stealth; TMC2160_n::PWMCONF_t pwmconf{0}; pwmconf.pwm_lim = 12; pwmconf.pwm_reg = 8; pwmconf.pwm_autograd = true; pwmconf.pwm_autoscale = true; pwmconf.pwm_freq = 0b01; pwmconf.pwm_grad = 14; pwmconf.pwm_ofs = 36; st.PWMCONF(pwmconf.sr); TERN(HYBRID_THRESHOLD, st.set_pwm_thrs(hyb_thrs), UNUSED(hyb_thrs)); st.GSTAT(); // Clear GSTAT } #endif // TMC5160 void restore_trinamic_drivers() { #if AXIS_IS_TMC(X) stepperX.push(); #endif #if AXIS_IS_TMC(X2) stepperX2.push(); #endif #if AXIS_IS_TMC(Y) stepperY.push(); #endif #if AXIS_IS_TMC(Y2) stepperY2.push(); #endif #if AXIS_IS_TMC(Z) stepperZ.push(); #endif #if AXIS_IS_TMC(Z2) stepperZ2.push(); #endif #if AXIS_IS_TMC(Z3) stepperZ3.push(); #endif #if AXIS_IS_TMC(Z4) stepperZ4.push(); #endif #if AXIS_IS_TMC(I) stepperI.push(); #endif #if AXIS_IS_TMC(J) stepperJ.push(); #endif #if AXIS_IS_TMC(K) stepperK.push(); #endif #if AXIS_IS_TMC(U) stepperU.push(); #endif #if AXIS_IS_TMC(V) stepperV.push(); #endif #if AXIS_IS_TMC(W) stepperW.push(); #endif #if AXIS_IS_TMC(E0) stepperE0.push(); #endif #if AXIS_IS_TMC(E1) stepperE1.push(); #endif #if AXIS_IS_TMC(E2) stepperE2.push(); #endif #if AXIS_IS_TMC(E3) stepperE3.push(); #endif #if AXIS_IS_TMC(E4) stepperE4.push(); #endif #if AXIS_IS_TMC(E5) stepperE5.push(); #endif #if AXIS_IS_TMC(E6) stepperE6.push(); #endif #if AXIS_IS_TMC(E7) stepperE7.push(); #endif } void reset_trinamic_drivers() { static constexpr bool stealthchop_by_axis[] = LOGICAL_AXIS_ARRAY( ENABLED(STEALTHCHOP_E), ENABLED(STEALTHCHOP_XY), ENABLED(STEALTHCHOP_XY), ENABLED(STEALTHCHOP_Z), ENABLED(STEALTHCHOP_I), ENABLED(STEALTHCHOP_J), ENABLED(STEALTHCHOP_K), ENABLED(STEALTHCHOP_U), ENABLED(STEALTHCHOP_V), ENABLED(STEALTHCHOP_W) ); #if AXIS_IS_TMC(X) TMC_INIT(X, STEALTH_AXIS_X); #endif #if AXIS_IS_TMC(X2) TMC_INIT(X2, STEALTH_AXIS_X); #endif #if AXIS_IS_TMC(Y) TMC_INIT(Y, STEALTH_AXIS_Y); #endif #if AXIS_IS_TMC(Y2) TMC_INIT(Y2, STEALTH_AXIS_Y); #endif #if AXIS_IS_TMC(Z) TMC_INIT(Z, STEALTH_AXIS_Z); #endif #if AXIS_IS_TMC(Z2) TMC_INIT(Z2, STEALTH_AXIS_Z); #endif #if AXIS_IS_TMC(Z3) TMC_INIT(Z3, STEALTH_AXIS_Z); #endif #if AXIS_IS_TMC(Z4) TMC_INIT(Z4, STEALTH_AXIS_Z); #endif #if AXIS_IS_TMC(I) TMC_INIT(I, STEALTH_AXIS_I); #endif #if AXIS_IS_TMC(J) TMC_INIT(J, STEALTH_AXIS_J); #endif #if AXIS_IS_TMC(K) TMC_INIT(K, STEALTH_AXIS_K); #endif #if AXIS_IS_TMC(U) TMC_INIT(U, STEALTH_AXIS_U); #endif #if AXIS_IS_TMC(V) TMC_INIT(V, STEALTH_AXIS_V); #endif #if AXIS_IS_TMC(W) TMC_INIT(W, STEALTH_AXIS_W); #endif #if AXIS_IS_TMC(E0) TMC_INIT(E0, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E1) TMC_INIT(E1, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E2) TMC_INIT(E2, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E3) TMC_INIT(E3, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E4) TMC_INIT(E4, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E5) TMC_INIT(E5, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E6) TMC_INIT(E6, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E7) TMC_INIT(E7, STEALTH_AXIS_E); #endif #if USE_SENSORLESS TERN_(X_SENSORLESS, stepperX.homing_threshold(X_STALL_SENSITIVITY)); TERN_(X2_SENSORLESS, stepperX2.homing_threshold(X2_STALL_SENSITIVITY)); TERN_(Y_SENSORLESS, stepperY.homing_threshold(Y_STALL_SENSITIVITY)); TERN_(Y2_SENSORLESS, stepperY2.homing_threshold(Y2_STALL_SENSITIVITY)); TERN_(Z_SENSORLESS, stepperZ.homing_threshold(Z_STALL_SENSITIVITY)); TERN_(Z2_SENSORLESS, stepperZ2.homing_threshold(Z2_STALL_SENSITIVITY)); TERN_(Z3_SENSORLESS, stepperZ3.homing_threshold(Z3_STALL_SENSITIVITY)); TERN_(Z4_SENSORLESS, stepperZ4.homing_threshold(Z4_STALL_SENSITIVITY)); TERN_(I_SENSORLESS, stepperI.homing_threshold(I_STALL_SENSITIVITY)); TERN_(J_SENSORLESS, stepperJ.homing_threshold(J_STALL_SENSITIVITY)); TERN_(K_SENSORLESS, stepperK.homing_threshold(K_STALL_SENSITIVITY)); TERN_(U_SENSORLESS, stepperU.homing_threshold(U_STALL_SENSITIVITY)); TERN_(V_SENSORLESS, stepperV.homing_threshold(V_STALL_SENSITIVITY)); TERN_(W_SENSORLESS, stepperW.homing_threshold(W_STALL_SENSITIVITY)); #endif #ifdef TMC_ADV TMC_ADV() #endif stepper.apply_directions(); } // TMC Slave Address Conflict Detection // // Conflict detection is performed in the following way. Similar methods are used for // hardware and software serial, but the implementations are independent. // // 1. Populate a data structure with UART parameters and addresses for all possible axis. // If an axis is not in use, populate it with recognizable placeholder data. // 2. For each axis in use, static_assert using a constexpr function, which counts the // number of matching/conflicting axis. If the value is not exactly 1, fail. #if ANY_AXIS_HAS(HW_SERIAL) // Hardware serial names are compared as strings, since actually resolving them cannot occur in a constexpr. // Using a fixed-length character array for the port name allows this to be constexpr compatible. struct SanityHwSerialDetails { const char port[20]; uint32_t address; }; #define TMC_HW_DETAIL_ARGS(A) TERN(A##_HAS_HW_SERIAL, STRINGIFY(A##_HARDWARE_SERIAL), ""), TERN0(A##_HAS_HW_SERIAL, A##_SLAVE_ADDRESS) #define TMC_HW_DETAIL(A) { TMC_HW_DETAIL_ARGS(A) } constexpr SanityHwSerialDetails sanity_tmc_hw_details[] = { MAPLIST(TMC_HW_DETAIL, ALL_AXIS_NAMES) }; // constexpr compatible string comparison constexpr bool str_eq_ce(const char * a, const char * b) { return *a == *b && (*a == '\0' || str_eq_ce(a+1,b+1)); } constexpr bool sc_hw_done(size_t start, size_t end) { return start == end; } constexpr bool sc_hw_skip(const char *port_name) { return !(*port_name); } constexpr bool sc_hw_match(const char *port_name, uint32_t address, size_t start, size_t end) { return !sc_hw_done(start, end) && !sc_hw_skip(port_name) && (address == sanity_tmc_hw_details[start].address && str_eq_ce(port_name, sanity_tmc_hw_details[start].port)); } constexpr int count_tmc_hw_serial_matches(const char *port_name, uint32_t address, size_t start, size_t end) { return sc_hw_done(start, end) ? 0 : ((sc_hw_skip(port_name) ? 0 : (sc_hw_match(port_name, address, start, end) ? 1 : 0)) + count_tmc_hw_serial_matches(port_name, address, start + 1, end)); } #define TMC_HWSERIAL_CONFLICT_MSG(A) STRINGIFY(A) "_SLAVE_ADDRESS conflicts with another driver using the same " STRINGIFY(A) "_HARDWARE_SERIAL" #define SA_NO_TMC_HW_C(A) static_assert(1 >= count_tmc_hw_serial_matches(TMC_HW_DETAIL_ARGS(A), 0, COUNT(sanity_tmc_hw_details)), TMC_HWSERIAL_CONFLICT_MSG(A)); MAP(SA_NO_TMC_HW_C, ALL_AXIS_NAMES) #endif #if ANY_AXIS_HAS(SW_SERIAL) struct SanitySwSerialDetails { int32_t txpin; int32_t rxpin; uint32_t address; }; #define TMC_SW_DETAIL_ARGS(A) TERN(A##_HAS_SW_SERIAL, A##_SERIAL_TX_PIN, -1), TERN(A##_HAS_SW_SERIAL, A##_SERIAL_RX_PIN, -1), TERN0(A##_HAS_SW_SERIAL, A##_SLAVE_ADDRESS) #define TMC_SW_DETAIL(A) { TMC_SW_DETAIL_ARGS(A) } constexpr SanitySwSerialDetails sanity_tmc_sw_details[] = { MAPLIST(TMC_SW_DETAIL, ALL_AXIS_NAMES) }; constexpr bool sc_sw_done(size_t start, size_t end) { return start == end; } constexpr bool sc_sw_skip(int32_t txpin) { return txpin < 0; } constexpr bool sc_sw_match(int32_t txpin, int32_t rxpin, uint32_t address, size_t start, size_t end) { return !sc_sw_done(start, end) && !sc_sw_skip(txpin) && (txpin == sanity_tmc_sw_details[start].txpin || rxpin == sanity_tmc_sw_details[start].rxpin) && (address == sanity_tmc_sw_details[start].address); } constexpr int count_tmc_sw_serial_matches(int32_t txpin, int32_t rxpin, uint32_t address, size_t start, size_t end) { return sc_sw_done(start, end) ? 0 : ((sc_sw_skip(txpin) ? 0 : (sc_sw_match(txpin, rxpin, address, start, end) ? 1 : 0)) + count_tmc_sw_serial_matches(txpin, rxpin, address, start + 1, end)); } #define TMC_SWSERIAL_CONFLICT_MSG(A) STRINGIFY(A) "_SLAVE_ADDRESS conflicts with another driver using the same " STRINGIFY(A) "_SERIAL_RX_PIN or " STRINGIFY(A) "_SERIAL_TX_PIN" #define SA_NO_TMC_SW_C(A) static_assert(1 >= count_tmc_sw_serial_matches(TMC_SW_DETAIL_ARGS(A), 0, COUNT(sanity_tmc_sw_details)), TMC_SWSERIAL_CONFLICT_MSG(A)); MAP(SA_NO_TMC_SW_C, ALL_AXIS_NAMES) #endif #endif // HAS_TRINAMIC_CONFIG
2301_81045437/Marlin
Marlin/src/module/stepper/trinamic.cpp
C++
agpl-3.0
32,637
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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/trinamic.h * Stepper driver indirection for Trinamic */ #include <TMCStepper.h> #if TMCSTEPPER_VERSION < 0x000500 #error "Update TMCStepper library to 0.5.0 or newer." #endif #include "../../inc/MarlinConfig.h" #include "../../feature/tmc_util.h" #define CLASS_TMC2130 TMC2130Stepper #define CLASS_TMC2160 TMC2160Stepper #define CLASS_TMC2208 TMC2208Stepper #define CLASS_TMC2209 TMC2209Stepper #define CLASS_TMC2660 TMC2660Stepper #define CLASS_TMC5130 TMC5130Stepper #define CLASS_TMC5160 TMC5160Stepper #define TMC_X_LABEL 'X', '0' #define TMC_Y_LABEL 'Y', '0' #define TMC_Z_LABEL 'Z', '0' #define TMC_I_LABEL 'I', '0' #define TMC_J_LABEL 'J', '0' #define TMC_K_LABEL 'K', '0' #define TMC_U_LABEL 'U', '0' #define TMC_V_LABEL 'V', '0' #define TMC_W_LABEL 'W', '0' #define TMC_X2_LABEL 'X', '2' #define TMC_Y2_LABEL 'Y', '2' #define TMC_Z2_LABEL 'Z', '2' #define TMC_Z3_LABEL 'Z', '3' #define TMC_Z4_LABEL 'Z', '4' #define TMC_E0_LABEL 'E', '0' #define TMC_E1_LABEL 'E', '1' #define TMC_E2_LABEL 'E', '2' #define TMC_E3_LABEL 'E', '3' #define TMC_E4_LABEL 'E', '4' #define TMC_E5_LABEL 'E', '5' #define TMC_E6_LABEL 'E', '6' #define TMC_E7_LABEL 'E', '7' #define __TMC_CLASS(TYPE, L, I, A) TMCMarlin<CLASS_##TYPE, L, I, A> #define _TMC_CLASS(TYPE, LandI, A) __TMC_CLASS(TYPE, LandI, A) #define TMC_CLASS(ST, A) _TMC_CLASS(ST##_DRIVER_TYPE, TMC_##ST##_LABEL, A##_AXIS) #if ENABLED(DISTINCT_E_FACTORS) #define TMC_CLASS_E(N) TMC_CLASS(E##N, E##N) #else #define TMC_CLASS_E(N) TMC_CLASS(E##N, E) #endif #if HAS_X_AXIS && !defined(CHOPPER_TIMING_X) #define CHOPPER_TIMING_X CHOPPER_TIMING #endif #if HAS_Y_AXIS && !defined(CHOPPER_TIMING_Y) #define CHOPPER_TIMING_Y CHOPPER_TIMING #endif #if HAS_Z_AXIS && !defined(CHOPPER_TIMING_Z) #define CHOPPER_TIMING_Z CHOPPER_TIMING #endif #if HAS_I_AXIS && !defined(CHOPPER_TIMING_I) #define CHOPPER_TIMING_I CHOPPER_TIMING #endif #if HAS_J_AXIS && !defined(CHOPPER_TIMING_J) #define CHOPPER_TIMING_J CHOPPER_TIMING #endif #if HAS_K_AXIS && !defined(CHOPPER_TIMING_K) #define CHOPPER_TIMING_K CHOPPER_TIMING #endif #if HAS_U_AXIS && !defined(CHOPPER_TIMING_U) #define CHOPPER_TIMING_U CHOPPER_TIMING #endif #if HAS_V_AXIS && !defined(CHOPPER_TIMING_V) #define CHOPPER_TIMING_V CHOPPER_TIMING #endif #if HAS_W_AXIS && !defined(CHOPPER_TIMING_W) #define CHOPPER_TIMING_W CHOPPER_TIMING #endif #if HAS_EXTRUDERS && !defined(CHOPPER_TIMING_E) #define CHOPPER_TIMING_E CHOPPER_TIMING #endif #if HAS_TMC220x void tmc_serial_begin(); #endif void restore_trinamic_drivers(); void reset_trinamic_drivers(); // X Stepper #if AXIS_IS_TMC(X) extern TMC_CLASS(X, X) stepperX; static constexpr chopper_timing_t chopper_timing_X = CHOPPER_TIMING_X; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define X_ENABLE_INIT() NOOP #define X_ENABLE_WRITE(STATE) stepperX.toff((STATE)==X_ENABLE_ON ? chopper_timing_X.toff : 0) #define X_ENABLE_READ() stepperX.isEnabled() #endif #if AXIS_HAS_DEDGE(X) #define X_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(X_STEP_PIN); }while(0) #endif #endif // Y Stepper #if AXIS_IS_TMC(Y) extern TMC_CLASS(Y, Y) stepperY; static constexpr chopper_timing_t chopper_timing_Y = CHOPPER_TIMING_Y; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define Y_ENABLE_INIT() NOOP #define Y_ENABLE_WRITE(STATE) stepperY.toff((STATE)==Y_ENABLE_ON ? chopper_timing_Y.toff : 0) #define Y_ENABLE_READ() stepperY.isEnabled() #endif #if AXIS_HAS_DEDGE(Y) #define Y_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(Y_STEP_PIN); }while(0) #endif #endif // Z Stepper #if AXIS_IS_TMC(Z) extern TMC_CLASS(Z, Z) stepperZ; static constexpr chopper_timing_t chopper_timing_Z = CHOPPER_TIMING_Z; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define Z_ENABLE_INIT() NOOP #define Z_ENABLE_WRITE(STATE) stepperZ.toff((STATE)==Z_ENABLE_ON ? chopper_timing_Z.toff : 0) #define Z_ENABLE_READ() stepperZ.isEnabled() #endif #if AXIS_HAS_DEDGE(Z) #define Z_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(Z_STEP_PIN); }while(0) #endif #endif // X2 Stepper #if HAS_X2_ENABLE && AXIS_IS_TMC(X2) extern TMC_CLASS(X2, X) stepperX2; #ifndef CHOPPER_TIMING_X2 #define CHOPPER_TIMING_X2 CHOPPER_TIMING_X #endif static constexpr chopper_timing_t chopper_timing_X2 = CHOPPER_TIMING_X2; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define X2_ENABLE_INIT() NOOP #define X2_ENABLE_WRITE(STATE) stepperX2.toff((STATE)==X_ENABLE_ON ? chopper_timing_X2.toff : 0) #define X2_ENABLE_READ() stepperX2.isEnabled() #endif #if AXIS_HAS_DEDGE(X2) #define X2_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(X2_STEP_PIN); }while(0) #endif #endif // Y2 Stepper #if HAS_Y2_ENABLE && AXIS_IS_TMC(Y2) extern TMC_CLASS(Y2, Y) stepperY2; #ifndef CHOPPER_TIMING_Y2 #define CHOPPER_TIMING_Y2 CHOPPER_TIMING_Y #endif static constexpr chopper_timing_t chopper_timing_Y2 = CHOPPER_TIMING_Y2; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define Y2_ENABLE_INIT() NOOP #define Y2_ENABLE_WRITE(STATE) stepperY2.toff((STATE)==Y_ENABLE_ON ? chopper_timing_Y2.toff : 0) #define Y2_ENABLE_READ() stepperY2.isEnabled() #endif #if AXIS_HAS_DEDGE(Y2) #define Y2_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(Y2_STEP_PIN); }while(0) #endif #endif // Z2 Stepper #if HAS_Z2_ENABLE && AXIS_IS_TMC(Z2) extern TMC_CLASS(Z2, Z) stepperZ2; #ifndef CHOPPER_TIMING_Z2 #define CHOPPER_TIMING_Z2 CHOPPER_TIMING_Z #endif static constexpr chopper_timing_t chopper_timing_Z2 = CHOPPER_TIMING_Z2; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define Z2_ENABLE_INIT() NOOP #define Z2_ENABLE_WRITE(STATE) stepperZ2.toff((STATE)==Z_ENABLE_ON ? chopper_timing_Z2.toff : 0) #define Z2_ENABLE_READ() stepperZ2.isEnabled() #endif #if AXIS_HAS_DEDGE(Z2) #define Z2_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(Z2_STEP_PIN); }while(0) #endif #endif // Z3 Stepper #if HAS_Z3_ENABLE && AXIS_IS_TMC(Z3) extern TMC_CLASS(Z3, Z) stepperZ3; #ifndef CHOPPER_TIMING_Z3 #define CHOPPER_TIMING_Z3 CHOPPER_TIMING_Z #endif static constexpr chopper_timing_t chopper_timing_Z3 = CHOPPER_TIMING_Z3; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define Z3_ENABLE_INIT() NOOP #define Z3_ENABLE_WRITE(STATE) stepperZ3.toff((STATE)==Z_ENABLE_ON ? chopper_timing_Z3.toff : 0) #define Z3_ENABLE_READ() stepperZ3.isEnabled() #endif #if AXIS_HAS_DEDGE(Z3) #define Z3_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(Z3_STEP_PIN); }while(0) #endif #endif // Z4 Stepper #if HAS_Z4_ENABLE && AXIS_IS_TMC(Z4) extern TMC_CLASS(Z4, Z) stepperZ4; #ifndef CHOPPER_TIMING_Z4 #define CHOPPER_TIMING_Z4 CHOPPER_TIMING_Z #endif static constexpr chopper_timing_t chopper_timing_Z4 = CHOPPER_TIMING_Z4; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define Z4_ENABLE_INIT() NOOP #define Z4_ENABLE_WRITE(STATE) stepperZ4.toff((STATE)==Z_ENABLE_ON ? chopper_timing_Z4.toff : 0) #define Z4_ENABLE_READ() stepperZ4.isEnabled() #endif #if AXIS_HAS_DEDGE(Z4) #define Z4_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(Z4_STEP_PIN); }while(0) #endif #endif // I Stepper #if AXIS_IS_TMC(I) extern TMC_CLASS(I, I) stepperI; static constexpr chopper_timing_t chopper_timing_I = CHOPPER_TIMING_I; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define I_ENABLE_INIT() NOOP #define I_ENABLE_WRITE(STATE) stepperI.toff((STATE)==I_ENABLE_ON ? chopper_timing_I.toff : 0) #define I_ENABLE_READ() stepperI.isEnabled() #endif #if AXIS_HAS_DEDGE(I) #define I_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(I_STEP_PIN); }while(0) #endif #endif // J Stepper #if AXIS_IS_TMC(J) extern TMC_CLASS(J, J) stepperJ; static constexpr chopper_timing_t chopper_timing_J = CHOPPER_TIMING_J; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define J_ENABLE_INIT() NOOP #define J_ENABLE_WRITE(STATE) stepperJ.toff((STATE)==J_ENABLE_ON ? chopper_timing_J.toff : 0) #define J_ENABLE_READ() stepperJ.isEnabled() #endif #if AXIS_HAS_DEDGE(J) #define J_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(J_STEP_PIN); }while(0) #endif #endif // K Stepper #if AXIS_IS_TMC(K) extern TMC_CLASS(K, K) stepperK; static constexpr chopper_timing_t chopper_timing_K = CHOPPER_TIMING_K; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define K_ENABLE_INIT() NOOP #define K_ENABLE_WRITE(STATE) stepperK.toff((STATE)==K_ENABLE_ON ? chopper_timing_K.toff : 0) #define K_ENABLE_READ() stepperK.isEnabled() #endif #if AXIS_HAS_DEDGE(K) #define K_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(K_STEP_PIN); }while(0) #endif #endif // U Stepper #if AXIS_IS_TMC(U) extern TMC_CLASS(U, U) stepperU; static constexpr chopper_timing_t chopper_timing_U = CHOPPER_TIMING_U; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define U_ENABLE_INIT() NOOP #define U_ENABLE_WRITE(STATE) stepperU.toff((STATE)==U_ENABLE_ON ? chopper_timing_U.toff : 0) #define U_ENABLE_READ() stepperU.isEnabled() #endif #if AXIS_HAS_DEDGE(U) #define U_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(U_STEP_PIN); }while(0) #endif #endif // V Stepper #if AXIS_IS_TMC(V) extern TMC_CLASS(V, V) stepperV; static constexpr chopper_timing_t chopper_timing_V = CHOPPER_TIMING_V; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define V_ENABLE_INIT() NOOP #define V_ENABLE_WRITE(STATE) stepperV.toff((STATE)==V_ENABLE_ON ? chopper_timing_V.toff : 0) #define V_ENABLE_READ() stepperV.isEnabled() #endif #if AXIS_HAS_DEDGE(V) #define V_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(V_STEP_PIN); }while(0) #endif #endif // W Stepper #if AXIS_IS_TMC(W) extern TMC_CLASS(W, W) stepperW; static constexpr chopper_timing_t chopper_timing_W = CHOPPER_TIMING_W; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define W_ENABLE_INIT() NOOP #define W_ENABLE_WRITE(STATE) stepperW.toff((STATE)==W_ENABLE_ON ? chopper_timing_W.toff : 0) #define W_ENABLE_READ() stepperW.isEnabled() #endif #if AXIS_HAS_DEDGE(W) #define W_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(W_STEP_PIN); }while(0) #endif #endif // E0 Stepper #if AXIS_IS_TMC(E0) extern TMC_CLASS_E(0) stepperE0; #ifndef CHOPPER_TIMING_E0 #define CHOPPER_TIMING_E0 CHOPPER_TIMING_E #endif static constexpr chopper_timing_t chopper_timing_E0 = CHOPPER_TIMING_E0; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define E0_ENABLE_INIT() NOOP #define E0_ENABLE_WRITE(STATE) stepperE0.toff((STATE)==E_ENABLE_ON ? chopper_timing_E0.toff : 0) #define E0_ENABLE_READ() stepperE0.isEnabled() #endif #if AXIS_HAS_DEDGE(E0) #define E0_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(E0_STEP_PIN); }while(0) #endif #endif // E1 Stepper #if AXIS_IS_TMC(E1) extern TMC_CLASS_E(1) stepperE1; #ifndef CHOPPER_TIMING_E1 #define CHOPPER_TIMING_E1 CHOPPER_TIMING_E #endif static constexpr chopper_timing_t chopper_timing_E1 = CHOPPER_TIMING_E1; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define E1_ENABLE_INIT() NOOP #define E1_ENABLE_WRITE(STATE) stepperE1.toff((STATE)==E_ENABLE_ON ? chopper_timing_E1.toff : 0) #define E1_ENABLE_READ() stepperE1.isEnabled() #endif #if AXIS_HAS_DEDGE(E1) #define E1_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(E1_STEP_PIN); }while(0) #endif #endif // E2 Stepper #if AXIS_IS_TMC(E2) extern TMC_CLASS_E(2) stepperE2; #ifndef CHOPPER_TIMING_E2 #define CHOPPER_TIMING_E2 CHOPPER_TIMING_E #endif static constexpr chopper_timing_t chopper_timing_E2 = CHOPPER_TIMING_E2; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define E2_ENABLE_INIT() NOOP #define E2_ENABLE_WRITE(STATE) stepperE2.toff((STATE)==E_ENABLE_ON ? chopper_timing_E2.toff : 0) #define E2_ENABLE_READ() stepperE2.isEnabled() #endif #if AXIS_HAS_DEDGE(E2) #define E2_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(E2_STEP_PIN); }while(0) #endif #endif // E3 Stepper #if AXIS_IS_TMC(E3) extern TMC_CLASS_E(3) stepperE3; #ifndef CHOPPER_TIMING_E3 #define CHOPPER_TIMING_E3 CHOPPER_TIMING_E #endif static constexpr chopper_timing_t chopper_timing_E3 = CHOPPER_TIMING_E3; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define E3_ENABLE_INIT() NOOP #define E3_ENABLE_WRITE(STATE) stepperE3.toff((STATE)==E_ENABLE_ON ? chopper_timing_E3.toff : 0) #define E3_ENABLE_READ() stepperE3.isEnabled() #endif #if AXIS_HAS_DEDGE(E3) #define E3_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(E3_STEP_PIN); }while(0) #endif #endif // E4 Stepper #if AXIS_IS_TMC(E4) extern TMC_CLASS_E(4) stepperE4; #ifndef CHOPPER_TIMING_E4 #define CHOPPER_TIMING_E4 CHOPPER_TIMING_E #endif static constexpr chopper_timing_t chopper_timing_E4 = CHOPPER_TIMING_E4; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define E4_ENABLE_INIT() NOOP #define E4_ENABLE_WRITE(STATE) stepperE4.toff((STATE)==E_ENABLE_ON ? chopper_timing_E4.toff : 0) #define E4_ENABLE_READ() stepperE4.isEnabled() #endif #if AXIS_HAS_DEDGE(E4) #define E4_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(E4_STEP_PIN); }while(0) #endif #endif // E5 Stepper #if AXIS_IS_TMC(E5) extern TMC_CLASS_E(5) stepperE5; #ifndef CHOPPER_TIMING_E5 #define CHOPPER_TIMING_E5 CHOPPER_TIMING_E #endif static constexpr chopper_timing_t chopper_timing_E5 = CHOPPER_TIMING_E5; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define E5_ENABLE_INIT() NOOP #define E5_ENABLE_WRITE(STATE) stepperE5.toff((STATE)==E_ENABLE_ON ? chopper_timing_E5.toff : 0) #define E5_ENABLE_READ() stepperE5.isEnabled() #endif #if AXIS_HAS_DEDGE(E5) #define E5_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(E5_STEP_PIN); }while(0) #endif #endif // E6 Stepper #if AXIS_IS_TMC(E6) extern TMC_CLASS_E(6) stepperE6; #ifndef CHOPPER_TIMING_E6 #define CHOPPER_TIMING_E6 CHOPPER_TIMING_E #endif static constexpr chopper_timing_t chopper_timing_E6 = CHOPPER_TIMING_E6; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define E6_ENABLE_INIT() NOOP #define E6_ENABLE_WRITE(STATE) stepperE6.toff((STATE)==E_ENABLE_ON ? chopper_timing_E6.toff : 0) #define E6_ENABLE_READ() stepperE6.isEnabled() #endif #if AXIS_HAS_DEDGE(E6) #define E6_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(E6_STEP_PIN); }while(0) #endif #endif // E7 Stepper #if AXIS_IS_TMC(E7) extern TMC_CLASS_E(7) stepperE7; #ifndef CHOPPER_TIMING_E7 #define CHOPPER_TIMING_E7 CHOPPER_TIMING_E #endif static constexpr chopper_timing_t chopper_timing_E7 = CHOPPER_TIMING_E7; #if ENABLED(SOFTWARE_DRIVER_ENABLE) #define E7_ENABLE_INIT() NOOP #define E7_ENABLE_WRITE(STATE) stepperE7.toff((STATE)==E_ENABLE_ON ? chopper_timing_E7.toff : 0) #define E7_ENABLE_READ() stepperE7.isEnabled() #endif #if AXIS_HAS_DEDGE(E7) #define E7_STEP_WRITE(STATE) do{ if (STATE) TOGGLE(E7_STEP_PIN); }while(0) #endif #endif
2301_81045437/Marlin
Marlin/src/module/stepper/trinamic.h
C
agpl-3.0
15,495
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.cpp - A singleton object to execute motion plans using stepper motors * Marlin Firmware * * Derived from Grbl * Copyright (c) 2009-2011 Simen Svale Skogsrud * * Grbl is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grbl is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grbl. If not, see <https://www.gnu.org/licenses/>. */ /** * Timer calculations informed by the 'RepRap cartesian firmware' by Zack Smith * and Philipp Tiefenbacher. */ /** * __________________________ * /| |\ _________________ ^ * / | | \ /| |\ | * / | | \ / | | \ s * / | | | | | \ p * / | | | | | \ e * +-----+------------------------+---+--+---------------+----+ e * | BLOCK 1 | BLOCK 2 | d * * time -----> * * The trapezoid is the shape the speed curve over time. It starts at block->initial_rate, accelerates * first block->accelerate_until step_events_completed, then keeps going at constant speed until * step_events_completed reaches block->decelerate_after after which it decelerates until the trapezoid generator is reset. * The slope of acceleration is calculated using v = u + at where t is the accumulated timer values of the steps so far. */ /** * Marlin uses the Bresenham algorithm. For a detailed explanation of theory and * method see https://www.cs.helsinki.fi/group/goa/mallinnus/lines/bresenh.html */ /** * Jerk controlled movements planner added Apr 2018 by Eduardo José Tagle. * Equations based on Synthethos TinyG2 sources, but the fixed-point * implementation is new, as we are running the ISR with a variable period. * Also implemented the Bézier velocity curve evaluation in ARM assembler, * to avoid impacting ISR speed. */ #include "stepper.h" Stepper stepper; // Singleton #define BABYSTEPPING_EXTRA_DIR_WAIT #include "stepper/cycles.h" #ifdef __AVR__ #include "stepper/speed_lookuptable.h" #endif #include "endstops.h" #include "planner.h" #include "motion.h" #if ENABLED(FT_MOTION) #include "ft_motion.h" #endif #include "../lcd/marlinui.h" #include "../gcode/queue.h" #include "../sd/cardreader.h" #include "../MarlinCore.h" #include "../HAL/shared/Delay.h" #if ENABLED(BD_SENSOR) #include "../feature/bedlevel/bdl/bdl.h" #endif #if ENABLED(BABYSTEPPING) #include "../feature/babystep.h" #endif #if MB(ALLIGATOR) #include "../feature/dac/dac_dac084s085.h" #endif #if HAS_MOTOR_CURRENT_SPI #include <SPI.h> #endif #if ENABLED(MIXING_EXTRUDER) #include "../feature/mixing.h" #endif #if HAS_FILAMENT_RUNOUT_DISTANCE #include "../feature/runout.h" #endif #if ENABLED(AUTO_POWER_CONTROL) #include "../feature/power.h" #endif #if ENABLED(POWER_LOSS_RECOVERY) #include "../feature/powerloss.h" #endif #if HAS_CUTTER #include "../feature/spindle_laser.h" #endif #if ENABLED(EXTENSIBLE_UI) #include "../lcd/extui/ui_api.h" #endif #if ENABLED(I2S_STEPPER_STREAM) #include "../HAL/ESP32/i2s.h" #endif // public: #if ANY(HAS_EXTRA_ENDSTOPS, Z_STEPPER_AUTO_ALIGN) bool Stepper::separate_multi_axis = false; #endif #if HAS_MOTOR_CURRENT_SPI || HAS_MOTOR_CURRENT_PWM bool Stepper::initialized; // = false uint32_t Stepper::motor_current_setting[MOTOR_CURRENT_COUNT]; // Initialized by settings.load() #if HAS_MOTOR_CURRENT_SPI constexpr uint32_t Stepper::digipot_count[]; #endif #endif stepper_flags_t Stepper::axis_enabled; // {0} // private: block_t* Stepper::current_block; // (= nullptr) A pointer to the block currently being traced AxisBits Stepper::last_direction_bits, // = 0 Stepper::axis_did_move; // = 0 bool Stepper::abort_current_block; #if DISABLED(MIXING_EXTRUDER) && HAS_MULTI_EXTRUDER uint8_t Stepper::last_moved_extruder = 0xFF; #endif #if ENABLED(X_DUAL_ENDSTOPS) bool Stepper::locked_X_motor = false, Stepper::locked_X2_motor = false; #endif #if ENABLED(Y_DUAL_ENDSTOPS) bool Stepper::locked_Y_motor = false, Stepper::locked_Y2_motor = false; #endif #if ANY(Z_MULTI_ENDSTOPS, Z_STEPPER_AUTO_ALIGN) bool Stepper::locked_Z_motor = false, Stepper::locked_Z2_motor = false #if NUM_Z_STEPPERS >= 3 , Stepper::locked_Z3_motor = false #if NUM_Z_STEPPERS >= 4 , Stepper::locked_Z4_motor = false #endif #endif ; #endif uint32_t Stepper::acceleration_time, Stepper::deceleration_time; #if MULTISTEPPING_LIMIT > 1 uint8_t Stepper::steps_per_isr = 1; // Count of steps to perform per Stepper ISR call #endif #if DISABLED(OLD_ADAPTIVE_MULTISTEPPING) hal_timer_t Stepper::time_spent_in_isr = 0, Stepper::time_spent_out_isr = 0; #endif #if ENABLED(ADAPTIVE_STEP_SMOOTHING) #if ENABLED(ADAPTIVE_STEP_SMOOTHING_TOGGLE) bool Stepper::adaptive_step_smoothing_enabled; // Initialized by settings.load() #else constexpr bool Stepper::adaptive_step_smoothing_enabled; // = true #endif // Oversampling factor (log2(multiplier)) to increase temporal resolution of axis uint8_t Stepper::oversampling_factor; #else constexpr uint8_t Stepper::oversampling_factor; // = 0 #endif #if ENABLED(FREEZE_FEATURE) bool Stepper::frozen; // = false #endif xyze_long_t Stepper::delta_error{0}; xyze_long_t Stepper::advance_dividend{0}; uint32_t Stepper::advance_divisor = 0, Stepper::step_events_completed = 0, // The number of step events executed in the current block Stepper::accelerate_until, // The count at which to stop accelerating Stepper::decelerate_after, // The count at which to start decelerating Stepper::step_event_count; // The total event count for the current block #if ANY(HAS_MULTI_EXTRUDER, MIXING_EXTRUDER) uint8_t Stepper::stepper_extruder; #else constexpr uint8_t Stepper::stepper_extruder; #endif #if ENABLED(S_CURVE_ACCELERATION) int32_t __attribute__((used)) Stepper::bezier_A __asm__("bezier_A"); // A coefficient in Bézier speed curve with alias for assembler int32_t __attribute__((used)) Stepper::bezier_B __asm__("bezier_B"); // B coefficient in Bézier speed curve with alias for assembler int32_t __attribute__((used)) Stepper::bezier_C __asm__("bezier_C"); // C coefficient in Bézier speed curve with alias for assembler uint32_t __attribute__((used)) Stepper::bezier_F __asm__("bezier_F"); // F coefficient in Bézier speed curve with alias for assembler uint32_t __attribute__((used)) Stepper::bezier_AV __asm__("bezier_AV"); // AV coefficient in Bézier speed curve with alias for assembler #ifdef __AVR__ bool __attribute__((used)) Stepper::A_negative __asm__("A_negative"); // If A coefficient was negative #endif bool Stepper::bezier_2nd_half; // =false If Bézier curve has been initialized or not #endif #if ENABLED(LIN_ADVANCE) hal_timer_t Stepper::nextAdvanceISR = LA_ADV_NEVER, Stepper::la_interval = LA_ADV_NEVER; int32_t Stepper::la_delta_error = 0, Stepper::la_dividend = 0, Stepper::la_advance_steps = 0; bool Stepper::la_active = false; #endif #if ENABLED(NONLINEAR_EXTRUSION) ne_coeff_t Stepper::ne; ne_fix_t Stepper::ne_fix; int32_t Stepper::ne_edividend; uint32_t Stepper::ne_scale; #endif #if HAS_ZV_SHAPING shaping_time_t ShapingQueue::now = 0; #if ANY(MCU_LPC1768, MCU_LPC1769) && DISABLED(NO_LPC_ETHERNET_BUFFER) // Use the 16K LPC Ethernet buffer: https://github.com/MarlinFirmware/Marlin/issues/25432#issuecomment-1450420638 #define _ATTR_BUFFER __attribute__((section("AHBSRAM1"),aligned)) #else #define _ATTR_BUFFER #endif shaping_time_t ShapingQueue::times[shaping_echoes] _ATTR_BUFFER; shaping_echo_axis_t ShapingQueue::echo_axes[shaping_echoes]; uint16_t ShapingQueue::tail = 0; #if ENABLED(INPUT_SHAPING_X) shaping_time_t ShapingQueue::delay_x; shaping_time_t ShapingQueue::peek_x_val = shaping_time_t(-1); uint16_t ShapingQueue::head_x = 0; uint16_t ShapingQueue::_free_count_x = shaping_echoes - 1; ShapeParams Stepper::shaping_x; #endif #if ENABLED(INPUT_SHAPING_Y) shaping_time_t ShapingQueue::delay_y; shaping_time_t ShapingQueue::peek_y_val = shaping_time_t(-1); uint16_t ShapingQueue::head_y = 0; uint16_t ShapingQueue::_free_count_y = shaping_echoes - 1; ShapeParams Stepper::shaping_y; #endif #endif #if ENABLED(BABYSTEPPING) hal_timer_t Stepper::nextBabystepISR = BABYSTEP_NEVER; #endif #if ENABLED(DIRECT_STEPPING) page_step_state_t Stepper::page_step_state; #endif hal_timer_t Stepper::ticks_nominal = 0; #if DISABLED(S_CURVE_ACCELERATION) uint32_t Stepper::acc_step_rate; // needed for deceleration start point #endif xyz_long_t Stepper::endstops_trigsteps; xyze_long_t Stepper::count_position{0}; xyze_int8_t Stepper::count_direction{0}; #define MINDIR(A) (count_direction[_AXIS(A)] < 0) #define MAXDIR(A) (count_direction[_AXIS(A)] > 0) #define STEPTEST(A,M,I) TERN0(USE_##A##I##_##M, !(TEST(endstops.state(), A##I##_##M) && M## DIR(A)) && !locked_ ##A##I##_motor) #define DUAL_ENDSTOP_APPLY_STEP(A,V) \ if (separate_multi_axis) { \ if (ENABLED(A##_HOME_TO_MIN)) { \ if (STEPTEST(A,MIN, )) A## _STEP_WRITE(V); \ if (STEPTEST(A,MIN,2)) A##2_STEP_WRITE(V); \ } \ else if (ENABLED(A##_HOME_TO_MAX)) { \ if (STEPTEST(A,MAX, )) A## _STEP_WRITE(V); \ if (STEPTEST(A,MAX,2)) A##2_STEP_WRITE(V); \ } \ } \ else { \ A##_STEP_WRITE(V); \ A##2_STEP_WRITE(V); \ } #define DUAL_SEPARATE_APPLY_STEP(A,V) \ if (separate_multi_axis) { \ if (!locked_##A## _motor) A## _STEP_WRITE(V); \ if (!locked_##A##2_motor) A##2_STEP_WRITE(V); \ } \ else { \ A##_STEP_WRITE(V); \ A##2_STEP_WRITE(V); \ } #define TRIPLE_ENDSTOP_APPLY_STEP(A,V) \ if (separate_multi_axis) { \ if (ENABLED(A##_HOME_TO_MIN)) { \ if (STEPTEST(A,MIN, )) A## _STEP_WRITE(V); \ if (STEPTEST(A,MIN,2)) A##2_STEP_WRITE(V); \ if (STEPTEST(A,MIN,3)) A##3_STEP_WRITE(V); \ } \ else if (ENABLED(A##_HOME_TO_MAX)) { \ if (STEPTEST(A,MAX, )) A## _STEP_WRITE(V); \ if (STEPTEST(A,MAX,2)) A##2_STEP_WRITE(V); \ if (STEPTEST(A,MAX,3)) A##3_STEP_WRITE(V); \ } \ } \ else { \ A##_STEP_WRITE(V); \ A##2_STEP_WRITE(V); \ A##3_STEP_WRITE(V); \ } #define TRIPLE_SEPARATE_APPLY_STEP(A,V) \ if (separate_multi_axis) { \ if (!locked_##A## _motor) A## _STEP_WRITE(V); \ if (!locked_##A##2_motor) A##2_STEP_WRITE(V); \ if (!locked_##A##3_motor) A##3_STEP_WRITE(V); \ } \ else { \ A## _STEP_WRITE(V); \ A##2_STEP_WRITE(V); \ A##3_STEP_WRITE(V); \ } #define QUAD_ENDSTOP_APPLY_STEP(A,V) \ if (separate_multi_axis) { \ if (ENABLED(A##_HOME_TO_MIN)) { \ if (STEPTEST(A,MIN, )) A## _STEP_WRITE(V); \ if (STEPTEST(A,MIN,2)) A##2_STEP_WRITE(V); \ if (STEPTEST(A,MIN,3)) A##3_STEP_WRITE(V); \ if (STEPTEST(A,MIN,4)) A##4_STEP_WRITE(V); \ } \ else if (ENABLED(A##_HOME_TO_MAX)) { \ if (STEPTEST(A,MAX, )) A## _STEP_WRITE(V); \ if (STEPTEST(A,MAX,2)) A##2_STEP_WRITE(V); \ if (STEPTEST(A,MAX,3)) A##3_STEP_WRITE(V); \ if (STEPTEST(A,MAX,4)) A##4_STEP_WRITE(V); \ } \ } \ else { \ A## _STEP_WRITE(V); \ A##2_STEP_WRITE(V); \ A##3_STEP_WRITE(V); \ A##4_STEP_WRITE(V); \ } #define QUAD_SEPARATE_APPLY_STEP(A,V) \ if (separate_multi_axis) { \ if (!locked_##A## _motor) A## _STEP_WRITE(V); \ if (!locked_##A##2_motor) A##2_STEP_WRITE(V); \ if (!locked_##A##3_motor) A##3_STEP_WRITE(V); \ if (!locked_##A##4_motor) A##4_STEP_WRITE(V); \ } \ else { \ A## _STEP_WRITE(V); \ A##2_STEP_WRITE(V); \ A##3_STEP_WRITE(V); \ A##4_STEP_WRITE(V); \ } #if HAS_SYNCED_X_STEPPERS #define X_APPLY_DIR(FWD,Q) do{ X_DIR_WRITE(FWD); X2_DIR_WRITE(INVERT_DIR(X2_VS_X, FWD)); }while(0) #if ENABLED(X_DUAL_ENDSTOPS) #define X_APPLY_STEP(FWD,Q) DUAL_ENDSTOP_APPLY_STEP(X,FWD) #else #define X_APPLY_STEP(FWD,Q) do{ X_STEP_WRITE(FWD); X2_STEP_WRITE(FWD); }while(0) #endif #elif ENABLED(DUAL_X_CARRIAGE) #define X_APPLY_DIR(FWD,ALWAYS) do{ \ if (extruder_duplication_enabled || ALWAYS) { X_DIR_WRITE(FWD); X2_DIR_WRITE((FWD) ^ idex_mirrored_mode); } \ else if (last_moved_extruder) X2_DIR_WRITE(FWD); else X_DIR_WRITE(FWD); \ }while(0) #define X_APPLY_STEP(FWD,ALWAYS) do{ \ if (extruder_duplication_enabled || ALWAYS) { X_STEP_WRITE(FWD); X2_STEP_WRITE(FWD); } \ else if (last_moved_extruder) X2_STEP_WRITE(FWD); else X_STEP_WRITE(FWD); \ }while(0) #elif HAS_X_AXIS #define X_APPLY_DIR(FWD,Q) X_DIR_WRITE(FWD) #define X_APPLY_STEP(FWD,Q) X_STEP_WRITE(FWD) #endif #if HAS_SYNCED_Y_STEPPERS #define Y_APPLY_DIR(FWD,Q) do{ Y_DIR_WRITE(FWD); Y2_DIR_WRITE(INVERT_DIR(Y2_VS_Y, FWD)); }while(0) #if ENABLED(Y_DUAL_ENDSTOPS) #define Y_APPLY_STEP(FWD,Q) DUAL_ENDSTOP_APPLY_STEP(Y,FWD) #else #define Y_APPLY_STEP(FWD,Q) do{ Y_STEP_WRITE(FWD); Y2_STEP_WRITE(FWD); }while(0) #endif #elif HAS_Y_AXIS #define Y_APPLY_DIR(FWD,Q) Y_DIR_WRITE(FWD) #define Y_APPLY_STEP(FWD,Q) Y_STEP_WRITE(FWD) #endif #if NUM_Z_STEPPERS == 4 #define Z_APPLY_DIR(FWD,Q) do{ \ Z_DIR_WRITE(FWD); Z2_DIR_WRITE(INVERT_DIR(Z2_VS_Z, FWD)); \ Z3_DIR_WRITE(INVERT_DIR(Z3_VS_Z, FWD)); Z4_DIR_WRITE(INVERT_DIR(Z4_VS_Z, FWD)); \ }while(0) #if ENABLED(Z_MULTI_ENDSTOPS) #define Z_APPLY_STEP(FWD,Q) QUAD_ENDSTOP_APPLY_STEP(Z,FWD) #elif ENABLED(Z_STEPPER_AUTO_ALIGN) #define Z_APPLY_STEP(FWD,Q) QUAD_SEPARATE_APPLY_STEP(Z,FWD) #else #define Z_APPLY_STEP(FWD,Q) do{ Z_STEP_WRITE(FWD); Z2_STEP_WRITE(FWD); Z3_STEP_WRITE(FWD); Z4_STEP_WRITE(FWD); }while(0) #endif #elif NUM_Z_STEPPERS == 3 #define Z_APPLY_DIR(FWD,Q) do{ \ Z_DIR_WRITE(FWD); Z2_DIR_WRITE(INVERT_DIR(Z2_VS_Z, FWD)); Z3_DIR_WRITE(INVERT_DIR(Z3_VS_Z, FWD)); \ }while(0) #if ENABLED(Z_MULTI_ENDSTOPS) #define Z_APPLY_STEP(FWD,Q) TRIPLE_ENDSTOP_APPLY_STEP(Z,FWD) #elif ENABLED(Z_STEPPER_AUTO_ALIGN) #define Z_APPLY_STEP(FWD,Q) TRIPLE_SEPARATE_APPLY_STEP(Z,FWD) #else #define Z_APPLY_STEP(FWD,Q) do{ Z_STEP_WRITE(FWD); Z2_STEP_WRITE(FWD); Z3_STEP_WRITE(FWD); }while(0) #endif #elif NUM_Z_STEPPERS == 2 #define Z_APPLY_DIR(FWD,Q) do{ Z_DIR_WRITE(FWD); Z2_DIR_WRITE(INVERT_DIR(Z2_VS_Z, FWD)); }while(0) #if ENABLED(Z_MULTI_ENDSTOPS) #define Z_APPLY_STEP(FWD,Q) DUAL_ENDSTOP_APPLY_STEP(Z,FWD) #elif ENABLED(Z_STEPPER_AUTO_ALIGN) #define Z_APPLY_STEP(FWD,Q) DUAL_SEPARATE_APPLY_STEP(Z,FWD) #else #define Z_APPLY_STEP(FWD,Q) do{ Z_STEP_WRITE(FWD); Z2_STEP_WRITE(FWD); }while(0) #endif #elif HAS_Z_AXIS #define Z_APPLY_DIR(FWD,Q) Z_DIR_WRITE(FWD) #define Z_APPLY_STEP(FWD,Q) Z_STEP_WRITE(FWD) #endif #if HAS_I_AXIS #define I_APPLY_DIR(FWD,Q) I_DIR_WRITE(FWD) #define I_APPLY_STEP(FWD,Q) I_STEP_WRITE(FWD) #endif #if HAS_J_AXIS #define J_APPLY_DIR(FWD,Q) J_DIR_WRITE(FWD) #define J_APPLY_STEP(FWD,Q) J_STEP_WRITE(FWD) #endif #if HAS_K_AXIS #define K_APPLY_DIR(FWD,Q) K_DIR_WRITE(FWD) #define K_APPLY_STEP(FWD,Q) K_STEP_WRITE(FWD) #endif #if HAS_U_AXIS #define U_APPLY_DIR(FWD,Q) U_DIR_WRITE(FWD) #define U_APPLY_STEP(FWD,Q) U_STEP_WRITE(FWD) #endif #if HAS_V_AXIS #define V_APPLY_DIR(FWD,Q) V_DIR_WRITE(FWD) #define V_APPLY_STEP(FWD,Q) V_STEP_WRITE(FWD) #endif #if HAS_W_AXIS #define W_APPLY_DIR(FWD,Q) W_DIR_WRITE(FWD) #define W_APPLY_STEP(FWD,Q) W_STEP_WRITE(FWD) #endif //#define E0_APPLY_DIR(FWD) do{ (FWD) ? FWD_E_DIR(0) : REV_E_DIR(0); }while(0) //#define E1_APPLY_DIR(FWD) do{ (FWD) ? FWD_E_DIR(1) : REV_E_DIR(1); }while(0) //#define E2_APPLY_DIR(FWD) do{ (FWD) ? FWD_E_DIR(2) : REV_E_DIR(2); }while(0) //#define E3_APPLY_DIR(FWD) do{ (FWD) ? FWD_E_DIR(3) : REV_E_DIR(3); }while(0) //#define E4_APPLY_DIR(FWD) do{ (FWD) ? FWD_E_DIR(4) : REV_E_DIR(4); }while(0) //#define E5_APPLY_DIR(FWD) do{ (FWD) ? FWD_E_DIR(5) : REV_E_DIR(5); }while(0) //#define E6_APPLY_DIR(FWD) do{ (FWD) ? FWD_E_DIR(6) : REV_E_DIR(6); }while(0) //#define E7_APPLY_DIR(FWD) do{ (FWD) ? FWD_E_DIR(7) : REV_E_DIR(7); }while(0) #if ENABLED(MIXING_EXTRUDER) #define E_APPLY_DIR(FWD,Q) do{ if (FWD) { MIXER_STEPPER_LOOP(j) FWD_E_DIR(j); } else { MIXER_STEPPER_LOOP(j) REV_E_DIR(j); } }while(0) #else #define E_APPLY_STEP(FWD,Q) E_STEP_WRITE(stepper_extruder, FWD) #define E_APPLY_DIR(FWD,Q) do{ if (FWD) { FWD_E_DIR(stepper_extruder); } else { REV_E_DIR(stepper_extruder); } }while(0) #endif #define CYCLES_TO_NS(CYC) (1000UL * (CYC) / ((F_CPU) / 1000000)) #define NS_PER_PULSE_TIMER_TICK (1000000000UL / (STEPPER_TIMER_RATE)) // Round up when converting from ns to timer ticks #define NS_TO_PULSE_TIMER_TICKS(NS) (((NS) + (NS_PER_PULSE_TIMER_TICK) / 2) / (NS_PER_PULSE_TIMER_TICK)) #define TIMER_SETUP_NS (CYCLES_TO_NS(TIMER_READ_ADD_AND_STORE_CYCLES)) #define PULSE_HIGH_TICK_COUNT hal_timer_t(NS_TO_PULSE_TIMER_TICKS(_MIN_PULSE_HIGH_NS - _MIN(_MIN_PULSE_HIGH_NS, TIMER_SETUP_NS))) #define PULSE_LOW_TICK_COUNT hal_timer_t(NS_TO_PULSE_TIMER_TICKS(_MIN_PULSE_LOW_NS - _MIN(_MIN_PULSE_LOW_NS, TIMER_SETUP_NS))) #define USING_TIMED_PULSE() hal_timer_t start_pulse_count = 0 #define START_TIMED_PULSE() (start_pulse_count = HAL_timer_get_count(MF_TIMER_PULSE)) #define AWAIT_TIMED_PULSE(DIR) while (PULSE_##DIR##_TICK_COUNT > HAL_timer_get_count(MF_TIMER_PULSE) - start_pulse_count) { /* nada */ } #define AWAIT_HIGH_PULSE() AWAIT_TIMED_PULSE(HIGH) #define AWAIT_LOW_PULSE() AWAIT_TIMED_PULSE(LOW) #if MINIMUM_STEPPER_PRE_DIR_DELAY > 0 #define DIR_WAIT_BEFORE() DELAY_NS(MINIMUM_STEPPER_PRE_DIR_DELAY) #else #define DIR_WAIT_BEFORE() #endif #if MINIMUM_STEPPER_POST_DIR_DELAY > 0 #define DIR_WAIT_AFTER() DELAY_NS(MINIMUM_STEPPER_POST_DIR_DELAY) #else #define DIR_WAIT_AFTER() #endif void Stepper::enable_axis(const AxisEnum axis) { #define _CASE_ENABLE(N) case N##_AXIS: ENABLE_AXIS_##N(); break; switch (axis) { MAIN_AXIS_MAP(_CASE_ENABLE) default: break; } mark_axis_enabled(axis); TERN_(EXTENSIBLE_UI, ExtUI::onAxisEnabled(ExtUI::axis_to_axis_t(axis))); } /** * Mark an axis as disabled and power off its stepper(s). * If one of the axis steppers is still in use by a non-disabled axis the axis will remain powered. * DISCUSSION: It's basically just stepper ENA pins that are shared across axes, not whole steppers. * Used on MCUs with a shortage of pins. We already track the overlap of ENA pins, so now * we just need stronger logic to track which ENA pins are being set more than once. * * It would be better to use a bit mask (i.e., Flags<NUM_DISTINCT_AXIS_ENUMS>). * While the method try_to_disable in gcode/control/M17_M18_M84.cpp does use the * bit mask, it is still only at the axis level. * TODO: Power off steppers that don't share another axis. Currently axis-based steppers turn off as a unit. * So we'd need to power off the off axis, then power on the on axis (for a microsecond). * A global solution would keep a usage count when enabling or disabling a stepper, but this partially * defeats the purpose of an on/off mask. */ bool Stepper::disable_axis(const AxisEnum axis) { mark_axis_disabled(axis); // This scheme prevents shared steppers being disabled. It should consider several axes at once // and keep a count of how many times each ENA pin has been set. // If all the axes that share the enabled bit are disabled const bool can_disable = can_axis_disable(axis); if (can_disable) { #define _CASE_DISABLE(N) case N##_AXIS: DISABLE_AXIS_##N(); break; switch (axis) { MAIN_AXIS_MAP(_CASE_DISABLE) default: break; } TERN_(EXTENSIBLE_UI, ExtUI::onAxisDisabled(ExtUI::axis_to_axis_t(axis))); } return can_disable; } #if HAS_EXTRUDERS void Stepper::enable_extruder(E_TERN_(const uint8_t eindex)) { IF_DISABLED(HAS_MULTI_EXTRUDER, constexpr uint8_t eindex = 0); #define _CASE_ENA_E(N) case N: ENABLE_AXIS_E##N(); mark_axis_enabled(E_AXIS E_OPTARG(eindex)); break; switch (eindex) { REPEAT(E_STEPPERS, _CASE_ENA_E) } } bool Stepper::disable_extruder(E_TERN_(const uint8_t eindex/*=0*/)) { IF_DISABLED(HAS_MULTI_EXTRUDER, constexpr uint8_t eindex = 0); mark_axis_disabled(E_AXIS E_OPTARG(eindex)); const bool can_disable = can_axis_disable(E_AXIS E_OPTARG(eindex)); if (can_disable) { #define _CASE_DIS_E(N) case N: DISABLE_AXIS_E##N(); break; switch (eindex) { REPEAT(E_STEPPERS, _CASE_DIS_E) } } return can_disable; } void Stepper::enable_e_steppers() { #define _ENA_E(N) ENABLE_EXTRUDER(N); REPEAT(EXTRUDERS, _ENA_E) } void Stepper::disable_e_steppers() { #define _DIS_E(N) DISABLE_EXTRUDER(N); REPEAT(EXTRUDERS, _DIS_E) } #endif void Stepper::enable_all_steppers() { TERN_(AUTO_POWER_CONTROL, powerManager.power_on()); NUM_AXIS_CODE( enable_axis(X_AXIS), enable_axis(Y_AXIS), enable_axis(Z_AXIS), enable_axis(I_AXIS), enable_axis(J_AXIS), enable_axis(K_AXIS), enable_axis(U_AXIS), enable_axis(V_AXIS), enable_axis(W_AXIS) ); enable_e_steppers(); TERN_(EXTENSIBLE_UI, ExtUI::onSteppersEnabled()); } void Stepper::disable_all_steppers() { NUM_AXIS_CODE( disable_axis(X_AXIS), disable_axis(Y_AXIS), disable_axis(Z_AXIS), disable_axis(I_AXIS), disable_axis(J_AXIS), disable_axis(K_AXIS), disable_axis(U_AXIS), disable_axis(V_AXIS), disable_axis(W_AXIS) ); disable_e_steppers(); TERN_(EXTENSIBLE_UI, ExtUI::onSteppersDisabled()); } #if ENABLED(FTM_OPTIMIZE_DIR_STATES) // We'll compare the updated DIR bits to the last set state static AxisBits last_set_direction; #endif // Set a single axis direction based on the last set flags. // A direction bit of "1" indicates forward or positive motion. #define SET_STEP_DIR(A) do{ \ const bool fwd = motor_direction(_AXIS(A)); \ A##_APPLY_DIR(fwd, false); \ count_direction[_AXIS(A)] = fwd ? 1 : -1; \ }while(0) /** * Set the stepper direction of each axis * * COREXY: X_AXIS=A_AXIS and Y_AXIS=B_AXIS * COREXZ: X_AXIS=A_AXIS and Z_AXIS=C_AXIS * COREYZ: Y_AXIS=B_AXIS and Z_AXIS=C_AXIS */ void Stepper::apply_directions() { DIR_WAIT_BEFORE(); LOGICAL_AXIS_CODE( SET_STEP_DIR(E), SET_STEP_DIR(X), SET_STEP_DIR(Y), SET_STEP_DIR(Z), // ABC SET_STEP_DIR(I), SET_STEP_DIR(J), SET_STEP_DIR(K), SET_STEP_DIR(U), SET_STEP_DIR(V), SET_STEP_DIR(W) ); TERN_(FTM_OPTIMIZE_DIR_STATES, last_set_direction = last_direction_bits); DIR_WAIT_AFTER(); } #if ENABLED(S_CURVE_ACCELERATION) /** * This uses a quintic (fifth-degree) Bézier polynomial for the velocity curve, giving * a "linear pop" velocity curve; with pop being the sixth derivative of position: * velocity - 1st, acceleration - 2nd, jerk - 3rd, snap - 4th, crackle - 5th, pop - 6th * * The Bézier curve takes the form: * * V(t) = P_0 * B_0(t) + P_1 * B_1(t) + P_2 * B_2(t) + P_3 * B_3(t) + P_4 * B_4(t) + P_5 * B_5(t) * * Where 0 <= t <= 1, and V(t) is the velocity. P_0 through P_5 are the control points, and B_0(t) * through B_5(t) are the Bernstein basis as follows: * * B_0(t) = (1-t)^5 = -t^5 + 5t^4 - 10t^3 + 10t^2 - 5t + 1 * B_1(t) = 5(1-t)^4 * t = 5t^5 - 20t^4 + 30t^3 - 20t^2 + 5t * B_2(t) = 10(1-t)^3 * t^2 = -10t^5 + 30t^4 - 30t^3 + 10t^2 * B_3(t) = 10(1-t)^2 * t^3 = 10t^5 - 20t^4 + 10t^3 * B_4(t) = 5(1-t) * t^4 = -5t^5 + 5t^4 * B_5(t) = t^5 = t^5 * ^ ^ ^ ^ ^ ^ * | | | | | | * A B C D E F * * Unfortunately, we cannot use forward-differencing to calculate each position through * the curve, as Marlin uses variable timer periods. So, we require a formula of the form: * * V_f(t) = A*t^5 + B*t^4 + C*t^3 + D*t^2 + E*t + F * * Looking at the above B_0(t) through B_5(t) expanded forms, if we take the coefficients of t^5 * through t of the Bézier form of V(t), we can determine that: * * A = -P_0 + 5*P_1 - 10*P_2 + 10*P_3 - 5*P_4 + P_5 * B = 5*P_0 - 20*P_1 + 30*P_2 - 20*P_3 + 5*P_4 * C = -10*P_0 + 30*P_1 - 30*P_2 + 10*P_3 * D = 10*P_0 - 20*P_1 + 10*P_2 * E = - 5*P_0 + 5*P_1 * F = P_0 * * Now, since we will (currently) *always* want the initial acceleration and jerk values to be 0, * We set P_i = P_0 = P_1 = P_2 (initial velocity), and P_t = P_3 = P_4 = P_5 (target velocity), * which, after simplification, resolves to: * * A = - 6*P_i + 6*P_t = 6*(P_t - P_i) * B = 15*P_i - 15*P_t = 15*(P_i - P_t) * C = -10*P_i + 10*P_t = 10*(P_t - P_i) * D = 0 * E = 0 * F = P_i * * As the t is evaluated in non uniform steps here, there is no other way rather than evaluating * the Bézier curve at each point: * * V_f(t) = A*t^5 + B*t^4 + C*t^3 + F [0 <= t <= 1] * * Floating point arithmetic execution time cost is prohibitive, so we will transform the math to * use fixed point values to be able to evaluate it in realtime. Assuming a maximum of 250000 steps * per second (driver pulses should at least be 2µS hi/2µS lo), and allocating 2 bits to avoid * overflows on the evaluation of the Bézier curve, means we can use * * t: unsigned Q0.32 (0 <= t < 1) |range 0 to 0xFFFFFFFF unsigned * A: signed Q24.7 , |range = +/- 250000 * 6 * 128 = +/- 192000000 = 0x0B71B000 | 28 bits + sign * B: signed Q24.7 , |range = +/- 250000 *15 * 128 = +/- 480000000 = 0x1C9C3800 | 29 bits + sign * C: signed Q24.7 , |range = +/- 250000 *10 * 128 = +/- 320000000 = 0x1312D000 | 29 bits + sign * F: signed Q24.7 , |range = +/- 250000 * 128 = 32000000 = 0x01E84800 | 25 bits + sign * * The trapezoid generator state contains the following information, that we will use to create and evaluate * the Bézier curve: * * blk->step_event_count [TS] = The total count of steps for this movement. (=distance) * blk->initial_rate [VI] = The initial steps per second (=velocity) * blk->final_rate [VF] = The ending steps per second (=velocity) * and the count of events completed (step_events_completed) [CS] (=distance until now) * * Note the abbreviations we use in the following formulae are between []s * * For Any 32bit CPU: * * At the start of each trapezoid, calculate the coefficients A,B,C,F and Advance [AV], as follows: * * A = 6*128*(VF - VI) = 768*(VF - VI) * B = 15*128*(VI - VF) = 1920*(VI - VF) * C = 10*128*(VF - VI) = 1280*(VF - VI) * F = 128*VI = 128*VI * AV = (1<<32)/TS ~= 0xFFFFFFFF / TS (To use ARM UDIV, that is 32 bits) (this is computed at the planner, to offload expensive calculations from the ISR) * * And for each point, evaluate the curve with the following sequence: * * void lsrs(uint32_t& d, uint32_t s, int cnt) { * d = s >> cnt; * } * void lsls(uint32_t& d, uint32_t s, int cnt) { * d = s << cnt; * } * void lsrs(int32_t& d, uint32_t s, int cnt) { * d = uint32_t(s) >> cnt; * } * void lsls(int32_t& d, uint32_t s, int cnt) { * d = uint32_t(s) << cnt; * } * void umull(uint32_t& rlo, uint32_t& rhi, uint32_t op1, uint32_t op2) { * uint64_t res = uint64_t(op1) * op2; * rlo = uint32_t(res & 0xFFFFFFFF); * rhi = uint32_t((res >> 32) & 0xFFFFFFFF); * } * void smlal(int32_t& rlo, int32_t& rhi, int32_t op1, int32_t op2) { * int64_t mul = int64_t(op1) * op2; * int64_t s = int64_t(uint32_t(rlo) | ((uint64_t(uint32_t(rhi)) << 32U))); * mul += s; * rlo = int32_t(mul & 0xFFFFFFFF); * rhi = int32_t((mul >> 32) & 0xFFFFFFFF); * } * int32_t _eval_bezier_curve_arm(uint32_t curr_step) { * uint32_t flo = 0; * uint32_t fhi = bezier_AV * curr_step; * uint32_t t = fhi; * int32_t alo = bezier_F; * int32_t ahi = 0; * int32_t A = bezier_A; * int32_t B = bezier_B; * int32_t C = bezier_C; * * lsrs(ahi, alo, 1); // a = F << 31 * lsls(alo, alo, 31); // * umull(flo, fhi, fhi, t); // f *= t * umull(flo, fhi, fhi, t); // f>>=32; f*=t * lsrs(flo, fhi, 1); // * smlal(alo, ahi, flo, C); // a+=(f>>33)*C * umull(flo, fhi, fhi, t); // f>>=32; f*=t * lsrs(flo, fhi, 1); // * smlal(alo, ahi, flo, B); // a+=(f>>33)*B * umull(flo, fhi, fhi, t); // f>>=32; f*=t * lsrs(flo, fhi, 1); // f>>=33; * smlal(alo, ahi, flo, A); // a+=(f>>33)*A; * lsrs(alo, ahi, 6); // a>>=38 * * return alo; * } * * This is rewritten in ARM assembly for optimal performance (43 cycles to execute). * * For AVR, the precision of coefficients is scaled so the Bézier curve can be evaluated in real-time: * Let's reduce precision as much as possible. After some experimentation we found that: * * Assume t and AV with 24 bits is enough * A = 6*(VF - VI) * B = 15*(VI - VF) * C = 10*(VF - VI) * F = VI * AV = (1<<24)/TS (this is computed at the planner, to offload expensive calculations from the ISR) * * Instead of storing sign for each coefficient, we will store its absolute value, * and flag the sign of the A coefficient, so we can save to store the sign bit. * It always holds that sign(A) = - sign(B) = sign(C) * * So, the resulting range of the coefficients are: * * t: unsigned (0 <= t < 1) |range 0 to 0xFFFFFF unsigned * A: signed Q24 , range = 250000 * 6 = 1500000 = 0x16E360 | 21 bits * B: signed Q24 , range = 250000 *15 = 3750000 = 0x393870 | 22 bits * C: signed Q24 , range = 250000 *10 = 2500000 = 0x1312D0 | 21 bits * F: signed Q24 , range = 250000 = 250000 = 0x0ED090 | 20 bits * * And for each curve, estimate its coefficients with: * * void _calc_bezier_curve_coeffs(int32_t v0, int32_t v1, uint32_t av) { * // Calculate the Bézier coefficients * if (v1 < v0) { * A_negative = true; * bezier_A = 6 * (v0 - v1); * bezier_B = 15 * (v0 - v1); * bezier_C = 10 * (v0 - v1); * } * else { * A_negative = false; * bezier_A = 6 * (v1 - v0); * bezier_B = 15 * (v1 - v0); * bezier_C = 10 * (v1 - v0); * } * bezier_F = v0; * } * * And for each point, evaluate the curve with the following sequence: * * // unsigned multiplication of 24 bits x 24bits, return upper 16 bits * void umul24x24to16hi(uint16_t& r, uint24_t op1, uint24_t op2) { * r = (uint64_t(op1) * op2) >> 8; * } * // unsigned multiplication of 16 bits x 16bits, return upper 16 bits * void umul16x16to16hi(uint16_t& r, uint16_t op1, uint16_t op2) { * r = (uint32_t(op1) * op2) >> 16; * } * // unsigned multiplication of 16 bits x 24bits, return upper 24 bits * void umul16x24to24hi(uint24_t& r, uint16_t op1, uint24_t op2) { * r = uint24_t((uint64_t(op1) * op2) >> 16); * } * * int32_t _eval_bezier_curve(uint32_t curr_step) { * // To save computing, the first step is always the initial speed * if (!curr_step) * return bezier_F; * * uint16_t t; * umul24x24to16hi(t, bezier_AV, curr_step); // t: Range 0 - 1^16 = 16 bits * uint16_t f = t; * umul16x16to16hi(f, f, t); // Range 16 bits (unsigned) * umul16x16to16hi(f, f, t); // Range 16 bits : f = t^3 (unsigned) * uint24_t acc = bezier_F; // Range 20 bits (unsigned) * if (A_negative) { * uint24_t v; * umul16x24to24hi(v, f, bezier_C); // Range 21bits * acc -= v; * umul16x16to16hi(f, f, t); // Range 16 bits : f = t^4 (unsigned) * umul16x24to24hi(v, f, bezier_B); // Range 22bits * acc += v; * umul16x16to16hi(f, f, t); // Range 16 bits : f = t^5 (unsigned) * umul16x24to24hi(v, f, bezier_A); // Range 21bits + 15 = 36bits (plus sign) * acc -= v; * } * else { * uint24_t v; * umul16x24to24hi(v, f, bezier_C); // Range 21bits * acc += v; * umul16x16to16hi(f, f, t); // Range 16 bits : f = t^4 (unsigned) * umul16x24to24hi(v, f, bezier_B); // Range 22bits * acc -= v; * umul16x16to16hi(f, f, t); // Range 16 bits : f = t^5 (unsigned) * umul16x24to24hi(v, f, bezier_A); // Range 21bits + 15 = 36bits (plus sign) * acc += v; * } * return acc; * } * These functions are translated to assembler for optimal performance. * Coefficient calculation takes 70 cycles. Bezier point evaluation takes 150 cycles. */ #ifdef __AVR__ // For AVR we use assembly to maximize speed void Stepper::_calc_bezier_curve_coeffs(const int32_t v0, const int32_t v1, const uint32_t av) { // Store advance bezier_AV = av; // Calculate the rest of the coefficients uint8_t r2 = v0 & 0xFF; uint8_t r3 = (v0 >> 8) & 0xFF; uint8_t r12 = (v0 >> 16) & 0xFF; uint8_t r5 = v1 & 0xFF; uint8_t r6 = (v1 >> 8) & 0xFF; uint8_t r7 = (v1 >> 16) & 0xFF; uint8_t r4,r8,r9,r10,r11; __asm__ __volatile__( /* Calculate the Bézier coefficients */ /* %10:%1:%0 = v0*/ /* %5:%4:%3 = v1*/ /* %7:%6:%10 = temporary*/ /* %9 = val (must be high register!)*/ /* %10 (must be high register!)*/ /* Store initial velocity*/ A("sts bezier_F, %0") A("sts bezier_F+1, %1") A("sts bezier_F+2, %10") /* bezier_F = %10:%1:%0 = v0 */ /* Get delta speed */ A("ldi %2,-1") /* %2 = 0xFF, means A_negative = true */ A("clr %8") /* %8 = 0 */ A("sub %0,%3") A("sbc %1,%4") A("sbc %10,%5") /* v0 -= v1, C=1 if result is negative */ A("brcc 1f") /* branch if result is positive (C=0), that means v0 >= v1 */ /* Result was negative, get the absolute value*/ A("com %10") A("com %1") A("neg %0") A("sbc %1,%2") A("sbc %10,%2") /* %10:%1:%0 +1 -> %10:%1:%0 = -(v0 - v1) = (v1 - v0) */ A("clr %2") /* %2 = 0, means A_negative = false */ /* Store negative flag*/ L("1") A("sts A_negative, %2") /* Store negative flag */ /* Compute coefficients A,B and C [20 cycles worst case]*/ A("ldi %9,6") /* %9 = 6 */ A("mul %0,%9") /* r1:r0 = 6*LO(v0-v1) */ A("sts bezier_A, r0") A("mov %6,r1") A("clr %7") /* %7:%6:r0 = 6*LO(v0-v1) */ A("mul %1,%9") /* r1:r0 = 6*MI(v0-v1) */ A("add %6,r0") A("adc %7,r1") /* %7:%6:?? += 6*MI(v0-v1) << 8 */ A("mul %10,%9") /* r1:r0 = 6*HI(v0-v1) */ A("add %7,r0") /* %7:%6:?? += 6*HI(v0-v1) << 16 */ A("sts bezier_A+1, %6") A("sts bezier_A+2, %7") /* bezier_A = %7:%6:?? = 6*(v0-v1) [35 cycles worst] */ A("ldi %9,15") /* %9 = 15 */ A("mul %0,%9") /* r1:r0 = 5*LO(v0-v1) */ A("sts bezier_B, r0") A("mov %6,r1") A("clr %7") /* %7:%6:?? = 5*LO(v0-v1) */ A("mul %1,%9") /* r1:r0 = 5*MI(v0-v1) */ A("add %6,r0") A("adc %7,r1") /* %7:%6:?? += 5*MI(v0-v1) << 8 */ A("mul %10,%9") /* r1:r0 = 5*HI(v0-v1) */ A("add %7,r0") /* %7:%6:?? += 5*HI(v0-v1) << 16 */ A("sts bezier_B+1, %6") A("sts bezier_B+2, %7") /* bezier_B = %7:%6:?? = 5*(v0-v1) [50 cycles worst] */ A("ldi %9,10") /* %9 = 10 */ A("mul %0,%9") /* r1:r0 = 10*LO(v0-v1) */ A("sts bezier_C, r0") A("mov %6,r1") A("clr %7") /* %7:%6:?? = 10*LO(v0-v1) */ A("mul %1,%9") /* r1:r0 = 10*MI(v0-v1) */ A("add %6,r0") A("adc %7,r1") /* %7:%6:?? += 10*MI(v0-v1) << 8 */ A("mul %10,%9") /* r1:r0 = 10*HI(v0-v1) */ A("add %7,r0") /* %7:%6:?? += 10*HI(v0-v1) << 16 */ A("sts bezier_C+1, %6") " sts bezier_C+2, %7" /* bezier_C = %7:%6:?? = 10*(v0-v1) [65 cycles worst] */ : "+r" (r2), "+d" (r3), "=r" (r4), "+r" (r5), "+r" (r6), "+r" (r7), "=r" (r8), "=r" (r9), "=r" (r10), "=d" (r11), "+r" (r12) : : "r0", "r1", "cc", "memory" ); } FORCE_INLINE int32_t Stepper::_eval_bezier_curve(const uint32_t curr_step) { // If dealing with the first step, save expensive computing and return the initial speed if (!curr_step) return bezier_F; uint8_t r0 = 0; /* Zero register */ uint8_t r2 = (curr_step) & 0xFF; uint8_t r3 = (curr_step >> 8) & 0xFF; uint8_t r4 = (curr_step >> 16) & 0xFF; uint8_t r1,r5,r6,r7,r8,r9,r10,r11; /* Temporary registers */ __asm__ __volatile( /* umul24x24to16hi(t, bezier_AV, curr_step); t: Range 0 - 1^16 = 16 bits*/ A("lds %9,bezier_AV") /* %9 = LO(AV)*/ A("mul %9,%2") /* r1:r0 = LO(bezier_AV)*LO(curr_step)*/ A("mov %7,r1") /* %7 = LO(bezier_AV)*LO(curr_step) >> 8*/ A("clr %8") /* %8:%7 = LO(bezier_AV)*LO(curr_step) >> 8*/ A("lds %10,bezier_AV+1") /* %10 = MI(AV)*/ A("mul %10,%2") /* r1:r0 = MI(bezier_AV)*LO(curr_step)*/ A("add %7,r0") A("adc %8,r1") /* %8:%7 += MI(bezier_AV)*LO(curr_step)*/ A("lds r1,bezier_AV+2") /* r11 = HI(AV)*/ A("mul r1,%2") /* r1:r0 = HI(bezier_AV)*LO(curr_step)*/ A("add %8,r0") /* %8:%7 += HI(bezier_AV)*LO(curr_step) << 8*/ A("mul %9,%3") /* r1:r0 = LO(bezier_AV)*MI(curr_step)*/ A("add %7,r0") A("adc %8,r1") /* %8:%7 += LO(bezier_AV)*MI(curr_step)*/ A("mul %10,%3") /* r1:r0 = MI(bezier_AV)*MI(curr_step)*/ A("add %8,r0") /* %8:%7 += LO(bezier_AV)*MI(curr_step) << 8*/ A("mul %9,%4") /* r1:r0 = LO(bezier_AV)*HI(curr_step)*/ A("add %8,r0") /* %8:%7 += LO(bezier_AV)*HI(curr_step) << 8*/ /* %8:%7 = t*/ /* uint16_t f = t;*/ A("mov %5,%7") /* %6:%5 = f*/ A("mov %6,%8") /* %6:%5 = f*/ /* umul16x16to16hi(f, f, t); / Range 16 bits (unsigned) [17] */ A("mul %5,%7") /* r1:r0 = LO(f) * LO(t)*/ A("mov %9,r1") /* store MIL(LO(f) * LO(t)) in %9, we need it for rounding*/ A("clr %10") /* %10 = 0*/ A("clr %11") /* %11 = 0*/ A("mul %5,%8") /* r1:r0 = LO(f) * HI(t)*/ A("add %9,r0") /* %9 += LO(LO(f) * HI(t))*/ A("adc %10,r1") /* %10 = HI(LO(f) * HI(t))*/ A("adc %11,%0") /* %11 += carry*/ A("mul %6,%7") /* r1:r0 = HI(f) * LO(t)*/ A("add %9,r0") /* %9 += LO(HI(f) * LO(t))*/ A("adc %10,r1") /* %10 += HI(HI(f) * LO(t)) */ A("adc %11,%0") /* %11 += carry*/ A("mul %6,%8") /* r1:r0 = HI(f) * HI(t)*/ A("add %10,r0") /* %10 += LO(HI(f) * HI(t))*/ A("adc %11,r1") /* %11 += HI(HI(f) * HI(t))*/ A("mov %5,%10") /* %6:%5 = */ A("mov %6,%11") /* f = %10:%11*/ /* umul16x16to16hi(f, f, t); / Range 16 bits : f = t^3 (unsigned) [17]*/ A("mul %5,%7") /* r1:r0 = LO(f) * LO(t)*/ A("mov %1,r1") /* store MIL(LO(f) * LO(t)) in %1, we need it for rounding*/ A("clr %10") /* %10 = 0*/ A("clr %11") /* %11 = 0*/ A("mul %5,%8") /* r1:r0 = LO(f) * HI(t)*/ A("add %1,r0") /* %1 += LO(LO(f) * HI(t))*/ A("adc %10,r1") /* %10 = HI(LO(f) * HI(t))*/ A("adc %11,%0") /* %11 += carry*/ A("mul %6,%7") /* r1:r0 = HI(f) * LO(t)*/ A("add %1,r0") /* %1 += LO(HI(f) * LO(t))*/ A("adc %10,r1") /* %10 += HI(HI(f) * LO(t))*/ A("adc %11,%0") /* %11 += carry*/ A("mul %6,%8") /* r1:r0 = HI(f) * HI(t)*/ A("add %10,r0") /* %10 += LO(HI(f) * HI(t))*/ A("adc %11,r1") /* %11 += HI(HI(f) * HI(t))*/ A("mov %5,%10") /* %6:%5 =*/ A("mov %6,%11") /* f = %10:%11*/ /* [15 +17*2] = [49]*/ /* %4:%3:%2 will be acc from now on*/ /* uint24_t acc = bezier_F; / Range 20 bits (unsigned)*/ A("clr %9") /* "decimal place we get for free"*/ A("lds %2,bezier_F") A("lds %3,bezier_F+1") A("lds %4,bezier_F+2") /* %4:%3:%2 = acc*/ /* if (A_negative) {*/ A("lds r0,A_negative") A("or r0,%0") /* Is flag signalling negative? */ A("brne 3f") /* If yes, Skip next instruction if A was negative*/ A("rjmp 1f") /* Otherwise, jump */ /* uint24_t v; */ /* umul16x24to24hi(v, f, bezier_C); / Range 21bits [29] */ /* acc -= v; */ L("3") A("lds %10, bezier_C") /* %10 = LO(bezier_C)*/ A("mul %10,%5") /* r1:r0 = LO(bezier_C) * LO(f)*/ A("sub %9,r1") A("sbc %2,%0") A("sbc %3,%0") A("sbc %4,%0") /* %4:%3:%2:%9 -= HI(LO(bezier_C) * LO(f))*/ A("lds %11, bezier_C+1") /* %11 = MI(bezier_C)*/ A("mul %11,%5") /* r1:r0 = MI(bezier_C) * LO(f)*/ A("sub %9,r0") A("sbc %2,r1") A("sbc %3,%0") A("sbc %4,%0") /* %4:%3:%2:%9 -= MI(bezier_C) * LO(f)*/ A("lds %1, bezier_C+2") /* %1 = HI(bezier_C)*/ A("mul %1,%5") /* r1:r0 = MI(bezier_C) * LO(f)*/ A("sub %2,r0") A("sbc %3,r1") A("sbc %4,%0") /* %4:%3:%2:%9 -= HI(bezier_C) * LO(f) << 8*/ A("mul %10,%6") /* r1:r0 = LO(bezier_C) * MI(f)*/ A("sub %9,r0") A("sbc %2,r1") A("sbc %3,%0") A("sbc %4,%0") /* %4:%3:%2:%9 -= LO(bezier_C) * MI(f)*/ A("mul %11,%6") /* r1:r0 = MI(bezier_C) * MI(f)*/ A("sub %2,r0") A("sbc %3,r1") A("sbc %4,%0") /* %4:%3:%2:%9 -= MI(bezier_C) * MI(f) << 8*/ A("mul %1,%6") /* r1:r0 = HI(bezier_C) * LO(f)*/ A("sub %3,r0") A("sbc %4,r1") /* %4:%3:%2:%9 -= HI(bezier_C) * LO(f) << 16*/ /* umul16x16to16hi(f, f, t); / Range 16 bits : f = t^3 (unsigned) [17]*/ A("mul %5,%7") /* r1:r0 = LO(f) * LO(t)*/ A("mov %1,r1") /* store MIL(LO(f) * LO(t)) in %1, we need it for rounding*/ A("clr %10") /* %10 = 0*/ A("clr %11") /* %11 = 0*/ A("mul %5,%8") /* r1:r0 = LO(f) * HI(t)*/ A("add %1,r0") /* %1 += LO(LO(f) * HI(t))*/ A("adc %10,r1") /* %10 = HI(LO(f) * HI(t))*/ A("adc %11,%0") /* %11 += carry*/ A("mul %6,%7") /* r1:r0 = HI(f) * LO(t)*/ A("add %1,r0") /* %1 += LO(HI(f) * LO(t))*/ A("adc %10,r1") /* %10 += HI(HI(f) * LO(t))*/ A("adc %11,%0") /* %11 += carry*/ A("mul %6,%8") /* r1:r0 = HI(f) * HI(t)*/ A("add %10,r0") /* %10 += LO(HI(f) * HI(t))*/ A("adc %11,r1") /* %11 += HI(HI(f) * HI(t))*/ A("mov %5,%10") /* %6:%5 =*/ A("mov %6,%11") /* f = %10:%11*/ /* umul16x24to24hi(v, f, bezier_B); / Range 22bits [29]*/ /* acc += v; */ A("lds %10, bezier_B") /* %10 = LO(bezier_B)*/ A("mul %10,%5") /* r1:r0 = LO(bezier_B) * LO(f)*/ A("add %9,r1") A("adc %2,%0") A("adc %3,%0") A("adc %4,%0") /* %4:%3:%2:%9 += HI(LO(bezier_B) * LO(f))*/ A("lds %11, bezier_B+1") /* %11 = MI(bezier_B)*/ A("mul %11,%5") /* r1:r0 = MI(bezier_B) * LO(f)*/ A("add %9,r0") A("adc %2,r1") A("adc %3,%0") A("adc %4,%0") /* %4:%3:%2:%9 += MI(bezier_B) * LO(f)*/ A("lds %1, bezier_B+2") /* %1 = HI(bezier_B)*/ A("mul %1,%5") /* r1:r0 = MI(bezier_B) * LO(f)*/ A("add %2,r0") A("adc %3,r1") A("adc %4,%0") /* %4:%3:%2:%9 += HI(bezier_B) * LO(f) << 8*/ A("mul %10,%6") /* r1:r0 = LO(bezier_B) * MI(f)*/ A("add %9,r0") A("adc %2,r1") A("adc %3,%0") A("adc %4,%0") /* %4:%3:%2:%9 += LO(bezier_B) * MI(f)*/ A("mul %11,%6") /* r1:r0 = MI(bezier_B) * MI(f)*/ A("add %2,r0") A("adc %3,r1") A("adc %4,%0") /* %4:%3:%2:%9 += MI(bezier_B) * MI(f) << 8*/ A("mul %1,%6") /* r1:r0 = HI(bezier_B) * LO(f)*/ A("add %3,r0") A("adc %4,r1") /* %4:%3:%2:%9 += HI(bezier_B) * LO(f) << 16*/ /* umul16x16to16hi(f, f, t); / Range 16 bits : f = t^5 (unsigned) [17]*/ A("mul %5,%7") /* r1:r0 = LO(f) * LO(t)*/ A("mov %1,r1") /* store MIL(LO(f) * LO(t)) in %1, we need it for rounding*/ A("clr %10") /* %10 = 0*/ A("clr %11") /* %11 = 0*/ A("mul %5,%8") /* r1:r0 = LO(f) * HI(t)*/ A("add %1,r0") /* %1 += LO(LO(f) * HI(t))*/ A("adc %10,r1") /* %10 = HI(LO(f) * HI(t))*/ A("adc %11,%0") /* %11 += carry*/ A("mul %6,%7") /* r1:r0 = HI(f) * LO(t)*/ A("add %1,r0") /* %1 += LO(HI(f) * LO(t))*/ A("adc %10,r1") /* %10 += HI(HI(f) * LO(t))*/ A("adc %11,%0") /* %11 += carry*/ A("mul %6,%8") /* r1:r0 = HI(f) * HI(t)*/ A("add %10,r0") /* %10 += LO(HI(f) * HI(t))*/ A("adc %11,r1") /* %11 += HI(HI(f) * HI(t))*/ A("mov %5,%10") /* %6:%5 =*/ A("mov %6,%11") /* f = %10:%11*/ /* umul16x24to24hi(v, f, bezier_A); / Range 21bits [29]*/ /* acc -= v; */ A("lds %10, bezier_A") /* %10 = LO(bezier_A)*/ A("mul %10,%5") /* r1:r0 = LO(bezier_A) * LO(f)*/ A("sub %9,r1") A("sbc %2,%0") A("sbc %3,%0") A("sbc %4,%0") /* %4:%3:%2:%9 -= HI(LO(bezier_A) * LO(f))*/ A("lds %11, bezier_A+1") /* %11 = MI(bezier_A)*/ A("mul %11,%5") /* r1:r0 = MI(bezier_A) * LO(f)*/ A("sub %9,r0") A("sbc %2,r1") A("sbc %3,%0") A("sbc %4,%0") /* %4:%3:%2:%9 -= MI(bezier_A) * LO(f)*/ A("lds %1, bezier_A+2") /* %1 = HI(bezier_A)*/ A("mul %1,%5") /* r1:r0 = MI(bezier_A) * LO(f)*/ A("sub %2,r0") A("sbc %3,r1") A("sbc %4,%0") /* %4:%3:%2:%9 -= HI(bezier_A) * LO(f) << 8*/ A("mul %10,%6") /* r1:r0 = LO(bezier_A) * MI(f)*/ A("sub %9,r0") A("sbc %2,r1") A("sbc %3,%0") A("sbc %4,%0") /* %4:%3:%2:%9 -= LO(bezier_A) * MI(f)*/ A("mul %11,%6") /* r1:r0 = MI(bezier_A) * MI(f)*/ A("sub %2,r0") A("sbc %3,r1") A("sbc %4,%0") /* %4:%3:%2:%9 -= MI(bezier_A) * MI(f) << 8*/ A("mul %1,%6") /* r1:r0 = HI(bezier_A) * LO(f)*/ A("sub %3,r0") A("sbc %4,r1") /* %4:%3:%2:%9 -= HI(bezier_A) * LO(f) << 16*/ A("jmp 2f") /* Done!*/ L("1") /* uint24_t v; */ /* umul16x24to24hi(v, f, bezier_C); / Range 21bits [29]*/ /* acc += v; */ A("lds %10, bezier_C") /* %10 = LO(bezier_C)*/ A("mul %10,%5") /* r1:r0 = LO(bezier_C) * LO(f)*/ A("add %9,r1") A("adc %2,%0") A("adc %3,%0") A("adc %4,%0") /* %4:%3:%2:%9 += HI(LO(bezier_C) * LO(f))*/ A("lds %11, bezier_C+1") /* %11 = MI(bezier_C)*/ A("mul %11,%5") /* r1:r0 = MI(bezier_C) * LO(f)*/ A("add %9,r0") A("adc %2,r1") A("adc %3,%0") A("adc %4,%0") /* %4:%3:%2:%9 += MI(bezier_C) * LO(f)*/ A("lds %1, bezier_C+2") /* %1 = HI(bezier_C)*/ A("mul %1,%5") /* r1:r0 = MI(bezier_C) * LO(f)*/ A("add %2,r0") A("adc %3,r1") A("adc %4,%0") /* %4:%3:%2:%9 += HI(bezier_C) * LO(f) << 8*/ A("mul %10,%6") /* r1:r0 = LO(bezier_C) * MI(f)*/ A("add %9,r0") A("adc %2,r1") A("adc %3,%0") A("adc %4,%0") /* %4:%3:%2:%9 += LO(bezier_C) * MI(f)*/ A("mul %11,%6") /* r1:r0 = MI(bezier_C) * MI(f)*/ A("add %2,r0") A("adc %3,r1") A("adc %4,%0") /* %4:%3:%2:%9 += MI(bezier_C) * MI(f) << 8*/ A("mul %1,%6") /* r1:r0 = HI(bezier_C) * LO(f)*/ A("add %3,r0") A("adc %4,r1") /* %4:%3:%2:%9 += HI(bezier_C) * LO(f) << 16*/ /* umul16x16to16hi(f, f, t); / Range 16 bits : f = t^3 (unsigned) [17]*/ A("mul %5,%7") /* r1:r0 = LO(f) * LO(t)*/ A("mov %1,r1") /* store MIL(LO(f) * LO(t)) in %1, we need it for rounding*/ A("clr %10") /* %10 = 0*/ A("clr %11") /* %11 = 0*/ A("mul %5,%8") /* r1:r0 = LO(f) * HI(t)*/ A("add %1,r0") /* %1 += LO(LO(f) * HI(t))*/ A("adc %10,r1") /* %10 = HI(LO(f) * HI(t))*/ A("adc %11,%0") /* %11 += carry*/ A("mul %6,%7") /* r1:r0 = HI(f) * LO(t)*/ A("add %1,r0") /* %1 += LO(HI(f) * LO(t))*/ A("adc %10,r1") /* %10 += HI(HI(f) * LO(t))*/ A("adc %11,%0") /* %11 += carry*/ A("mul %6,%8") /* r1:r0 = HI(f) * HI(t)*/ A("add %10,r0") /* %10 += LO(HI(f) * HI(t))*/ A("adc %11,r1") /* %11 += HI(HI(f) * HI(t))*/ A("mov %5,%10") /* %6:%5 =*/ A("mov %6,%11") /* f = %10:%11*/ /* umul16x24to24hi(v, f, bezier_B); / Range 22bits [29]*/ /* acc -= v;*/ A("lds %10, bezier_B") /* %10 = LO(bezier_B)*/ A("mul %10,%5") /* r1:r0 = LO(bezier_B) * LO(f)*/ A("sub %9,r1") A("sbc %2,%0") A("sbc %3,%0") A("sbc %4,%0") /* %4:%3:%2:%9 -= HI(LO(bezier_B) * LO(f))*/ A("lds %11, bezier_B+1") /* %11 = MI(bezier_B)*/ A("mul %11,%5") /* r1:r0 = MI(bezier_B) * LO(f)*/ A("sub %9,r0") A("sbc %2,r1") A("sbc %3,%0") A("sbc %4,%0") /* %4:%3:%2:%9 -= MI(bezier_B) * LO(f)*/ A("lds %1, bezier_B+2") /* %1 = HI(bezier_B)*/ A("mul %1,%5") /* r1:r0 = MI(bezier_B) * LO(f)*/ A("sub %2,r0") A("sbc %3,r1") A("sbc %4,%0") /* %4:%3:%2:%9 -= HI(bezier_B) * LO(f) << 8*/ A("mul %10,%6") /* r1:r0 = LO(bezier_B) * MI(f)*/ A("sub %9,r0") A("sbc %2,r1") A("sbc %3,%0") A("sbc %4,%0") /* %4:%3:%2:%9 -= LO(bezier_B) * MI(f)*/ A("mul %11,%6") /* r1:r0 = MI(bezier_B) * MI(f)*/ A("sub %2,r0") A("sbc %3,r1") A("sbc %4,%0") /* %4:%3:%2:%9 -= MI(bezier_B) * MI(f) << 8*/ A("mul %1,%6") /* r1:r0 = HI(bezier_B) * LO(f)*/ A("sub %3,r0") A("sbc %4,r1") /* %4:%3:%2:%9 -= HI(bezier_B) * LO(f) << 16*/ /* umul16x16to16hi(f, f, t); / Range 16 bits : f = t^5 (unsigned) [17]*/ A("mul %5,%7") /* r1:r0 = LO(f) * LO(t)*/ A("mov %1,r1") /* store MIL(LO(f) * LO(t)) in %1, we need it for rounding*/ A("clr %10") /* %10 = 0*/ A("clr %11") /* %11 = 0*/ A("mul %5,%8") /* r1:r0 = LO(f) * HI(t)*/ A("add %1,r0") /* %1 += LO(LO(f) * HI(t))*/ A("adc %10,r1") /* %10 = HI(LO(f) * HI(t))*/ A("adc %11,%0") /* %11 += carry*/ A("mul %6,%7") /* r1:r0 = HI(f) * LO(t)*/ A("add %1,r0") /* %1 += LO(HI(f) * LO(t))*/ A("adc %10,r1") /* %10 += HI(HI(f) * LO(t))*/ A("adc %11,%0") /* %11 += carry*/ A("mul %6,%8") /* r1:r0 = HI(f) * HI(t)*/ A("add %10,r0") /* %10 += LO(HI(f) * HI(t))*/ A("adc %11,r1") /* %11 += HI(HI(f) * HI(t))*/ A("mov %5,%10") /* %6:%5 =*/ A("mov %6,%11") /* f = %10:%11*/ /* umul16x24to24hi(v, f, bezier_A); / Range 21bits [29]*/ /* acc += v; */ A("lds %10, bezier_A") /* %10 = LO(bezier_A)*/ A("mul %10,%5") /* r1:r0 = LO(bezier_A) * LO(f)*/ A("add %9,r1") A("adc %2,%0") A("adc %3,%0") A("adc %4,%0") /* %4:%3:%2:%9 += HI(LO(bezier_A) * LO(f))*/ A("lds %11, bezier_A+1") /* %11 = MI(bezier_A)*/ A("mul %11,%5") /* r1:r0 = MI(bezier_A) * LO(f)*/ A("add %9,r0") A("adc %2,r1") A("adc %3,%0") A("adc %4,%0") /* %4:%3:%2:%9 += MI(bezier_A) * LO(f)*/ A("lds %1, bezier_A+2") /* %1 = HI(bezier_A)*/ A("mul %1,%5") /* r1:r0 = MI(bezier_A) * LO(f)*/ A("add %2,r0") A("adc %3,r1") A("adc %4,%0") /* %4:%3:%2:%9 += HI(bezier_A) * LO(f) << 8*/ A("mul %10,%6") /* r1:r0 = LO(bezier_A) * MI(f)*/ A("add %9,r0") A("adc %2,r1") A("adc %3,%0") A("adc %4,%0") /* %4:%3:%2:%9 += LO(bezier_A) * MI(f)*/ A("mul %11,%6") /* r1:r0 = MI(bezier_A) * MI(f)*/ A("add %2,r0") A("adc %3,r1") A("adc %4,%0") /* %4:%3:%2:%9 += MI(bezier_A) * MI(f) << 8*/ A("mul %1,%6") /* r1:r0 = HI(bezier_A) * LO(f)*/ A("add %3,r0") A("adc %4,r1") /* %4:%3:%2:%9 += HI(bezier_A) * LO(f) << 16*/ L("2") " clr __zero_reg__" /* C runtime expects r1 = __zero_reg__ = 0 */ : "+r"(r0), "+r"(r1), "+r"(r2), "+r"(r3), "+r"(r4), "+r"(r5), "+r"(r6), "+r"(r7), "+r"(r8), "+r"(r9), "+r"(r10), "+r"(r11) : :"cc","r0","r1" ); return (r2 | (uint16_t(r3) << 8)) | (uint32_t(r4) << 16); } #else // For all the other 32bit CPUs FORCE_INLINE void Stepper::_calc_bezier_curve_coeffs(const int32_t v0, const int32_t v1, const uint32_t av) { // Calculate the Bézier coefficients bezier_A = 768 * (v1 - v0); bezier_B = 1920 * (v0 - v1); bezier_C = 1280 * (v1 - v0); bezier_F = 128 * v0; bezier_AV = av; } FORCE_INLINE int32_t Stepper::_eval_bezier_curve(const uint32_t curr_step) { #if (defined(__arm__) || defined(__thumb__)) && __ARM_ARCH >= 6 && !defined(STM32G0B1xx) // TODO: Test define STM32G0xx versus STM32G0B1xx // For ARM Cortex M3/M4 CPUs, we have the optimized assembler version, that takes 43 cycles to execute uint32_t flo = 0; uint32_t fhi = bezier_AV * curr_step; uint32_t t = fhi; int32_t alo = bezier_F; int32_t ahi = 0; int32_t A = bezier_A; int32_t B = bezier_B; int32_t C = bezier_C; __asm__ __volatile__( ".syntax unified" "\n\t" // is to prevent CM0,CM1 non-unified syntax A("lsrs %[ahi],%[alo],#1") // a = F << 31 1 cycles A("lsls %[alo],%[alo],#31") // 1 cycles A("umull %[flo],%[fhi],%[fhi],%[t]") // f *= t 5 cycles [fhi:flo=64bits] A("umull %[flo],%[fhi],%[fhi],%[t]") // f>>=32; f*=t 5 cycles [fhi:flo=64bits] A("lsrs %[flo],%[fhi],#1") // 1 cycles [31bits] A("smlal %[alo],%[ahi],%[flo],%[C]") // a+=(f>>33)*C; 5 cycles A("umull %[flo],%[fhi],%[fhi],%[t]") // f>>=32; f*=t 5 cycles [fhi:flo=64bits] A("lsrs %[flo],%[fhi],#1") // 1 cycles [31bits] A("smlal %[alo],%[ahi],%[flo],%[B]") // a+=(f>>33)*B; 5 cycles A("umull %[flo],%[fhi],%[fhi],%[t]") // f>>=32; f*=t 5 cycles [fhi:flo=64bits] A("lsrs %[flo],%[fhi],#1") // f>>=33; 1 cycles [31bits] A("smlal %[alo],%[ahi],%[flo],%[A]") // a+=(f>>33)*A; 5 cycles A("lsrs %[alo],%[ahi],#6") // a>>=38 1 cycles : [alo]"+r"( alo ) , [flo]"+r"( flo ) , [fhi]"+r"( fhi ) , [ahi]"+r"( ahi ) , [A]"+r"( A ) , // <== Note: Even if A, B, C, and t registers are INPUT ONLY [B]"+r"( B ) , // GCC does bad optimizations on the code if we list them as [C]"+r"( C ) , // such, breaking this function. So, to avoid that problem, [t]"+r"( t ) // we list all registers as input-outputs. : : "cc" ); return alo; #else // For non ARM targets, we provide a fallback implementation. Really doubt it // will be useful, unless the processor is fast and 32bit uint32_t t = bezier_AV * curr_step; // t: Range 0 - 1^32 = 32 bits uint64_t f = t; f *= t; // Range 32*2 = 64 bits (unsigned) f >>= 32; // Range 32 bits (unsigned) f *= t; // Range 32*2 = 64 bits (unsigned) f >>= 32; // Range 32 bits : f = t^3 (unsigned) int64_t acc = (int64_t) bezier_F << 31; // Range 63 bits (signed) acc += ((uint32_t) f >> 1) * (int64_t) bezier_C; // Range 29bits + 31 = 60bits (plus sign) f *= t; // Range 32*2 = 64 bits f >>= 32; // Range 32 bits : f = t^3 (unsigned) acc += ((uint32_t) f >> 1) * (int64_t) bezier_B; // Range 29bits + 31 = 60bits (plus sign) f *= t; // Range 32*2 = 64 bits f >>= 32; // Range 32 bits : f = t^3 (unsigned) acc += ((uint32_t) f >> 1) * (int64_t) bezier_A; // Range 28bits + 31 = 59bits (plus sign) acc >>= (31 + 7); // Range 24bits (plus sign) return (int32_t) acc; #endif } #endif #endif // S_CURVE_ACCELERATION /** * Stepper Driver Interrupt * * Directly pulses the stepper motors at high frequency. */ HAL_STEP_TIMER_ISR() { HAL_timer_isr_prologue(MF_TIMER_STEP); Stepper::isr(); HAL_timer_isr_epilogue(MF_TIMER_STEP); } #ifdef CPU_32_BIT #define STEP_MULTIPLY(A,B) MultiU32X24toH32(A, B) #else #define STEP_MULTIPLY(A,B) MultiU24X32toH16(A, B) #endif void Stepper::isr() { static hal_timer_t nextMainISR = 0; // Interval until the next main Stepper Pulse phase (0 = Now) #ifndef __AVR__ // Disable interrupts, to avoid ISR preemption while we reprogram the period // (AVR enters the ISR with global interrupts disabled, so no need to do it here) hal.isr_off(); #endif // Program timer compare for the maximum period, so it does NOT // flag an interrupt while this ISR is running - So changes from small // periods to big periods are respected and the timer does not reset to 0 HAL_timer_set_compare(MF_TIMER_STEP, hal_timer_t(HAL_TIMER_TYPE_MAX)); // Count of ticks for the next ISR hal_timer_t next_isr_ticks = 0; // Limit the amount of iterations uint8_t max_loops = 10; #if ENABLED(FT_MOTION) const bool using_ftMotion = ftMotion.cfg.mode; #else constexpr bool using_ftMotion = false; #endif // We need this variable here to be able to use it in the following loop hal_timer_t min_ticks; do { // Enable ISRs to reduce USART processing latency hal.isr_on(); hal_timer_t interval = 0; #if ENABLED(FT_MOTION) if (using_ftMotion) { if (!nextMainISR) { // Main ISR is ready to fire during this iteration? nextMainISR = FTM_MIN_TICKS; // Set to minimum interval (a limit on the top speed) ftMotion_stepper(); // Run FTM Stepping } #if ENABLED(BABYSTEPPING) if (nextBabystepISR == 0) { // Avoid ANY stepping too soon after baby-stepping nextBabystepISR = babystepping_isr(); NOLESS(nextMainISR, (BABYSTEP_TICKS) / 8); // FULL STOP for 125µs after a baby-step } if (nextBabystepISR != BABYSTEP_NEVER) // Avoid baby-stepping too close to axis Stepping NOLESS(nextBabystepISR, nextMainISR / 2); // TODO: Only look at axes enabled for baby-stepping #endif interval = nextMainISR; // Interval is either some old nextMainISR or FTM_MIN_TICKS TERN_(BABYSTEPPING, NOMORE(interval, nextBabystepISR)); // Come back early for Babystepping? nextMainISR = 0; // For FT Motion fire again ASAP } #endif if (!using_ftMotion) { TERN_(HAS_ZV_SHAPING, shaping_isr()); // Do Shaper stepping, if needed if (!nextMainISR) pulse_phase_isr(); // 0 = Do coordinated axes Stepper pulses #if ENABLED(LIN_ADVANCE) if (!nextAdvanceISR) { // 0 = Do Linear Advance E Stepper pulses advance_isr(); nextAdvanceISR = la_interval; } else if (nextAdvanceISR > la_interval) // Start/accelerate LA steps if necessary nextAdvanceISR = la_interval; #endif #if ENABLED(BABYSTEPPING) const bool is_babystep = (nextBabystepISR == 0); // 0 = Do Babystepping (XY)Z pulses if (is_babystep) nextBabystepISR = babystepping_isr(); #endif // ^== Time critical. NOTHING besides pulse generation should be above here!!! if (!nextMainISR) nextMainISR = block_phase_isr(); // Manage acc/deceleration, get next block #if ENABLED(BABYSTEPPING) if (is_babystep) // Avoid ANY stepping too soon after baby-stepping NOLESS(nextMainISR, (BABYSTEP_TICKS) / 8); // FULL STOP for 125µs after a baby-step if (nextBabystepISR != BABYSTEP_NEVER) // Avoid baby-stepping too close to axis Stepping NOLESS(nextBabystepISR, nextMainISR / 2); // TODO: Only look at axes enabled for baby-stepping #endif // Get the interval to the next ISR call interval = _MIN(nextMainISR, uint32_t(HAL_TIMER_TYPE_MAX)); // Time until the next Pulse / Block phase TERN_(INPUT_SHAPING_X, NOMORE(interval, ShapingQueue::peek_x())); // Time until next input shaping echo for X TERN_(INPUT_SHAPING_Y, NOMORE(interval, ShapingQueue::peek_y())); // Time until next input shaping echo for Y TERN_(LIN_ADVANCE, NOMORE(interval, nextAdvanceISR)); // Come back early for Linear Advance? TERN_(BABYSTEPPING, NOMORE(interval, nextBabystepISR)); // Come back early for Babystepping? // // Compute remaining time for each ISR phase // NEVER : The phase is idle // Zero : The phase will occur on the next ISR call // Non-zero : The phase will occur on a future ISR call // nextMainISR -= interval; TERN_(HAS_ZV_SHAPING, ShapingQueue::decrement_delays(interval)); TERN_(LIN_ADVANCE, if (nextAdvanceISR != LA_ADV_NEVER) nextAdvanceISR -= interval); TERN_(BABYSTEPPING, if (nextBabystepISR != BABYSTEP_NEVER) nextBabystepISR -= interval); } // standard motion control /** * This needs to avoid a race-condition caused by interleaving * of interrupts required by both the LA and Stepper algorithms. * * Assume the following tick times for stepper pulses: * Stepper ISR (S): 1 1000 2000 3000 4000 * Linear Adv. (E): 10 1010 2010 3010 4010 * * The current algorithm tries to interleave them, giving: * 1:S 10:E 1000:S 1010:E 2000:S 2010:E 3000:S 3010:E 4000:S 4010:E * * Ideal timing would yield these delta periods: * 1:S 9:E 990:S 10:E 990:S 10:E 990:S 10:E 990:S 10:E * * But, since each event must fire an ISR with a minimum duration, the * minimum delta might be 900, so deltas under 900 get rounded up: * 900:S d900:E d990:S d900:E d990:S d900:E d990:S d900:E d990:S d900:E * * It works, but divides the speed of all motors by half, leading to a sudden * reduction to 1/2 speed! Such jumps in speed lead to lost steps (not even * accounting for double/quad stepping, which makes it even worse). */ // Compute the tick count for the next ISR next_isr_ticks += interval; /** * The following section must be done with global interrupts disabled. * We want nothing to interrupt it, as that could mess the calculations * we do for the next value to program in the period register of the * stepper timer and lead to skipped ISRs (if the value we happen to program * is less than the current count due to something preempting between the * read and the write of the new period value). */ hal.isr_off(); /** * Get the current tick value + margin * Assuming at least 6µs between calls to this ISR... * On AVR the ISR epilogue+prologue is estimated at 100 instructions - Give 8µs as margin * On ARM the ISR epilogue+prologue is estimated at 20 instructions - Give 1µs as margin */ min_ticks = HAL_timer_get_count(MF_TIMER_STEP) + hal_timer_t(TERN(__AVR__, 8, 1) * (STEPPER_TIMER_TICKS_PER_US)); #if ENABLED(OLD_ADAPTIVE_MULTISTEPPING) /** * NB: If for some reason the stepper monopolizes the MPU, eventually the * timer will wrap around (and so will 'next_isr_ticks'). So, limit the * loop to 10 iterations. Beyond that, there's no way to ensure correct pulse * timing, since the MCU isn't fast enough. */ if (!--max_loops) next_isr_ticks = min_ticks; #endif // Advance pulses if not enough time to wait for the next ISR } while (TERN(OLD_ADAPTIVE_MULTISTEPPING, true, --max_loops) && next_isr_ticks < min_ticks); #if DISABLED(OLD_ADAPTIVE_MULTISTEPPING) // Track the time spent in the ISR const hal_timer_t time_spent = HAL_timer_get_count(MF_TIMER_STEP); time_spent_in_isr += time_spent; if (next_isr_ticks < min_ticks) { next_isr_ticks = min_ticks; // When forced out of the ISR, increase multi-stepping #if MULTISTEPPING_LIMIT > 1 if (steps_per_isr < MULTISTEPPING_LIMIT) { steps_per_isr <<= 1; // ticks_nominal will need to be recalculated if we are in cruise phase ticks_nominal = 0; } #endif } else { // Track the time spent voluntarily outside the ISR time_spent_out_isr += next_isr_ticks; time_spent_out_isr -= time_spent; } #endif // !OLD_ADAPTIVE_MULTISTEPPING // Now 'next_isr_ticks' contains the period to the next Stepper ISR - And we are // sure that the time has not arrived yet - Warrantied by the scheduler // Set the next ISR to fire at the proper time HAL_timer_set_compare(MF_TIMER_STEP, next_isr_ticks); // Don't forget to finally reenable interrupts on non-AVR. // AVR automatically calls sei() for us on Return-from-Interrupt. #ifndef __AVR__ hal.isr_on(); #endif } #if MINIMUM_STEPPER_PULSE || MAXIMUM_STEPPER_RATE #define ISR_PULSE_CONTROL 1 #endif #if ISR_PULSE_CONTROL && DISABLED(I2S_STEPPER_STREAM) #define ISR_MULTI_STEPS 1 #endif /** * This phase of the ISR should ONLY create the pulses for the steppers. * This prevents jitter caused by the interval between the start of the * interrupt and the start of the pulses. DON'T add any logic ahead of the * call to this method that might cause variation in the timing. The aim * is to keep pulse timing as regular as possible. */ void Stepper::pulse_phase_isr() { // If we must abort the current block, do so! if (abort_current_block) { abort_current_block = false; if (current_block) { discard_current_block(); #if HAS_ZV_SHAPING ShapingQueue::purge(); #if ENABLED(INPUT_SHAPING_X) shaping_x.delta_error = 0; shaping_x.last_block_end_pos = count_position.x; #endif #if ENABLED(INPUT_SHAPING_Y) shaping_y.delta_error = 0; shaping_y.last_block_end_pos = count_position.y; #endif #endif } } // If there is no current block, do nothing if (!current_block || step_events_completed >= step_event_count) return; // Skipping step processing causes motion to freeze if (TERN0(FREEZE_FEATURE, frozen)) return; // Count of pending loops and events for this iteration const uint32_t pending_events = step_event_count - step_events_completed; uint8_t events_to_do = _MIN(pending_events, steps_per_isr); // Just update the value we will get at the end of the loop step_events_completed += events_to_do; // Take multiple steps per interrupt (For high speed moves) #if ISR_MULTI_STEPS bool firstStep = true; USING_TIMED_PULSE(); #endif // Direct Stepping page? const bool is_page = current_block->is_page(); do { AxisFlags step_needed{0}; #define _APPLY_STEP(AXIS, INV, ALWAYS) AXIS ##_APPLY_STEP(INV, ALWAYS) #define _STEP_STATE(AXIS) STEP_STATE_## AXIS // Determine if a pulse is needed using Bresenham #define PULSE_PREP(AXIS) do{ \ int32_t de = delta_error[_AXIS(AXIS)] + advance_dividend[_AXIS(AXIS)]; \ if (de >= 0) { \ step_needed.set(_AXIS(AXIS)); \ de -= advance_divisor_cached; \ } \ delta_error[_AXIS(AXIS)] = de; \ }while(0) // With input shaping, direction changes can happen with almost only // AWAIT_LOW_PULSE() and DIR_WAIT_BEFORE() between steps. To work around // the TMC2208 / TMC2225 shutdown bug (#16076), add a half step hysteresis // in each direction. This results in the position being off by half an // average half step during travel but correct at the end of each segment. #if AXIS_DRIVER_TYPE_X(TMC2208) || AXIS_DRIVER_TYPE_X(TMC2208_STANDALONE) || \ AXIS_DRIVER_TYPE_X(TMC5160) || AXIS_DRIVER_TYPE_X(TMC5160_STANDALONE) #define HYSTERESIS_X 64 #else #define HYSTERESIS_X 0 #endif #if AXIS_DRIVER_TYPE_Y(TMC2208) || AXIS_DRIVER_TYPE_Y(TMC2208_STANDALONE) || \ AXIS_DRIVER_TYPE_Y(TMC5160) || AXIS_DRIVER_TYPE_Y(TMC5160_STANDALONE) #define HYSTERESIS_Y 64 #else #define HYSTERESIS_Y 0 #endif #define _HYSTERESIS(AXIS) HYSTERESIS_##AXIS #define HYSTERESIS(AXIS) _HYSTERESIS(AXIS) #define PULSE_PREP_SHAPING(AXIS, DELTA_ERROR, DIVIDEND) do{ \ int16_t de = DELTA_ERROR + (DIVIDEND); \ const bool step_fwd = de >= (64 + HYSTERESIS(AXIS)), \ step_bak = de <= -(64 + HYSTERESIS(AXIS)); \ if (step_fwd || step_bak) { \ de += step_fwd ? -128 : 128; \ if ((MAXDIR(AXIS) && step_bak) || (MINDIR(AXIS) && step_fwd)) { \ { USING_TIMED_PULSE(); START_TIMED_PULSE(); AWAIT_LOW_PULSE(); } \ last_direction_bits.toggle(_AXIS(AXIS)); \ DIR_WAIT_BEFORE(); \ SET_STEP_DIR(AXIS); \ TERN_(FTM_OPTIMIZE_DIR_STATES, last_set_direction = last_direction_bits); \ DIR_WAIT_AFTER(); \ } \ } \ else \ step_needed.clear(_AXIS(AXIS)); \ DELTA_ERROR = de; \ }while(0) // Start an active pulse if needed #define PULSE_START(AXIS) do{ \ if (step_needed.test(_AXIS(AXIS))) { \ count_position[_AXIS(AXIS)] += count_direction[_AXIS(AXIS)]; \ _APPLY_STEP(AXIS, _STEP_STATE(AXIS), 0); \ } \ }while(0) // Stop an active pulse if needed #define PULSE_STOP(AXIS) do { \ if (step_needed.test(_AXIS(AXIS))) { \ _APPLY_STEP(AXIS, !_STEP_STATE(AXIS), 0); \ } \ }while(0) #if ENABLED(DIRECT_STEPPING) // Direct stepping is currently not ready for HAS_I_AXIS if (is_page) { #if STEPPER_PAGE_FORMAT == SP_4x4D_128 #define PAGE_SEGMENT_UPDATE(AXIS, VALUE) do{ \ if ((VALUE) < 7) dm[_AXIS(AXIS)] = false; \ else if ((VALUE) > 7) dm[_AXIS(AXIS)] = true; \ page_step_state.sd[_AXIS(AXIS)] = VALUE; \ page_step_state.bd[_AXIS(AXIS)] += VALUE; \ }while(0) #define PAGE_PULSE_PREP(AXIS) do{ \ step_needed.set(_AXIS(AXIS), \ pgm_read_byte(&segment_table[page_step_state.sd[_AXIS(AXIS)]][page_step_state.segment_steps & 0x7])); \ }while(0) switch (page_step_state.segment_steps) { case DirectStepping::Config::SEGMENT_STEPS: page_step_state.segment_idx += 2; page_step_state.segment_steps = 0; // fallthru case 0: { const uint8_t low = page_step_state.page[page_step_state.segment_idx], high = page_step_state.page[page_step_state.segment_idx + 1]; const AxisBits dm = last_direction_bits; PAGE_SEGMENT_UPDATE(X, low >> 4); PAGE_SEGMENT_UPDATE(Y, low & 0xF); PAGE_SEGMENT_UPDATE(Z, high >> 4); PAGE_SEGMENT_UPDATE(E, high & 0xF); if (dm != last_direction_bits) set_directions(dm); } break; default: break; } PAGE_PULSE_PREP(X); PAGE_PULSE_PREP(Y); PAGE_PULSE_PREP(Z); TERN_(HAS_EXTRUDERS, PAGE_PULSE_PREP(E)); page_step_state.segment_steps++; #elif STEPPER_PAGE_FORMAT == SP_4x2_256 #define PAGE_SEGMENT_UPDATE(AXIS, VALUE) \ page_step_state.sd[_AXIS(AXIS)] = VALUE; \ page_step_state.bd[_AXIS(AXIS)] += VALUE; #define PAGE_PULSE_PREP(AXIS) do{ \ step_needed.set(_AXIS(AXIS), \ pgm_read_byte(&segment_table[page_step_state.sd[_AXIS(AXIS)]][page_step_state.segment_steps & 0x3])); \ }while(0) switch (page_step_state.segment_steps) { case DirectStepping::Config::SEGMENT_STEPS: page_step_state.segment_idx++; page_step_state.segment_steps = 0; // fallthru case 0: { const uint8_t b = page_step_state.page[page_step_state.segment_idx]; PAGE_SEGMENT_UPDATE(X, (b >> 6) & 0x3); PAGE_SEGMENT_UPDATE(Y, (b >> 4) & 0x3); PAGE_SEGMENT_UPDATE(Z, (b >> 2) & 0x3); PAGE_SEGMENT_UPDATE(E, (b >> 0) & 0x3); } break; default: break; } PAGE_PULSE_PREP(X); PAGE_PULSE_PREP(Y); PAGE_PULSE_PREP(Z); TERN_(HAS_EXTRUDERS, PAGE_PULSE_PREP(E)); page_step_state.segment_steps++; #elif STEPPER_PAGE_FORMAT == SP_4x1_512 #define PAGE_PULSE_PREP(AXIS, NBIT) do{ \ step_needed.set(_AXIS(AXIS), TEST(steps, NBIT)); \ if (step_needed.test(_AXIS(AXIS))) \ page_step_state.bd[_AXIS(AXIS)]++; \ }while(0) uint8_t steps = page_step_state.page[page_step_state.segment_idx >> 1]; if (page_step_state.segment_idx & 0x1) steps >>= 4; PAGE_PULSE_PREP(X, 3); PAGE_PULSE_PREP(Y, 2); PAGE_PULSE_PREP(Z, 1); PAGE_PULSE_PREP(E, 0); page_step_state.segment_idx++; #else #error "Unknown direct stepping page format!" #endif } #endif // DIRECT_STEPPING if (!is_page) { // Give the compiler a clue to store advance_divisor in registers for what follows const uint32_t advance_divisor_cached = advance_divisor; // Determine if pulses are needed #if HAS_X_STEP PULSE_PREP(X); #endif #if HAS_Y_STEP PULSE_PREP(Y); #endif #if HAS_Z_STEP PULSE_PREP(Z); #endif #if HAS_I_STEP PULSE_PREP(I); #endif #if HAS_J_STEP PULSE_PREP(J); #endif #if HAS_K_STEP PULSE_PREP(K); #endif #if HAS_U_STEP PULSE_PREP(U); #endif #if HAS_V_STEP PULSE_PREP(V); #endif #if HAS_W_STEP PULSE_PREP(W); #endif #if ANY(HAS_E0_STEP, MIXING_EXTRUDER) PULSE_PREP(E); #if ENABLED(LIN_ADVANCE) if (la_active && step_needed.e) { // don't actually step here, but do subtract movements steps // from the linear advance step count step_needed.e = false; la_advance_steps--; } #endif #endif #if HAS_ZV_SHAPING // record an echo if a step is needed in the primary bresenham const bool x_step = TERN0(INPUT_SHAPING_X, step_needed.x && shaping_x.enabled), y_step = TERN0(INPUT_SHAPING_Y, step_needed.y && shaping_y.enabled); if (x_step || y_step) ShapingQueue::enqueue(x_step, TERN0(INPUT_SHAPING_X, shaping_x.forward), y_step, TERN0(INPUT_SHAPING_Y, shaping_y.forward)); // do the first part of the secondary bresenham #if ENABLED(INPUT_SHAPING_X) if (x_step) PULSE_PREP_SHAPING(X, shaping_x.delta_error, shaping_x.forward ? shaping_x.factor1 : -shaping_x.factor1); #endif #if ENABLED(INPUT_SHAPING_Y) if (y_step) PULSE_PREP_SHAPING(Y, shaping_y.delta_error, shaping_y.forward ? shaping_y.factor1 : -shaping_y.factor1); #endif #endif } #if ISR_MULTI_STEPS if (firstStep) firstStep = false; else AWAIT_LOW_PULSE(); #endif // Pulse start #if HAS_X_STEP PULSE_START(X); #endif #if HAS_Y_STEP PULSE_START(Y); #endif #if HAS_Z_STEP PULSE_START(Z); #endif #if HAS_I_STEP PULSE_START(I); #endif #if HAS_J_STEP PULSE_START(J); #endif #if HAS_K_STEP PULSE_START(K); #endif #if HAS_U_STEP PULSE_START(U); #endif #if HAS_V_STEP PULSE_START(V); #endif #if HAS_W_STEP PULSE_START(W); #endif #if ENABLED(MIXING_EXTRUDER) if (step_needed.e) { count_position.e += count_direction.e; E_STEP_WRITE(mixer.get_next_stepper(), STEP_STATE_E); } #elif HAS_E0_STEP PULSE_START(E); #endif TERN_(I2S_STEPPER_STREAM, i2s_push_sample()); // TODO: need to deal with MINIMUM_STEPPER_PULSE over i2s #if ISR_MULTI_STEPS START_TIMED_PULSE(); AWAIT_HIGH_PULSE(); #endif // Pulse stop #if HAS_X_STEP PULSE_STOP(X); #endif #if HAS_Y_STEP PULSE_STOP(Y); #endif #if HAS_Z_STEP PULSE_STOP(Z); #endif #if HAS_I_STEP PULSE_STOP(I); #endif #if HAS_J_STEP PULSE_STOP(J); #endif #if HAS_K_STEP PULSE_STOP(K); #endif #if HAS_U_STEP PULSE_STOP(U); #endif #if HAS_V_STEP PULSE_STOP(V); #endif #if HAS_W_STEP PULSE_STOP(W); #endif #if ENABLED(MIXING_EXTRUDER) if (step_needed.e) E_STEP_WRITE(mixer.get_stepper(), !STEP_STATE_E); #elif HAS_E0_STEP PULSE_STOP(E); #endif #if ISR_MULTI_STEPS if (events_to_do) START_TIMED_PULSE(); #endif } while (--events_to_do); } #if HAS_ZV_SHAPING void Stepper::shaping_isr() { AxisFlags step_needed{0}; // Clear the echoes that are ready to process. If the buffers are too full and risk overflow, also apply echoes early. TERN_(INPUT_SHAPING_X, step_needed.x = !ShapingQueue::peek_x() || ShapingQueue::free_count_x() < steps_per_isr); TERN_(INPUT_SHAPING_Y, step_needed.y = !ShapingQueue::peek_y() || ShapingQueue::free_count_y() < steps_per_isr); if (bool(step_needed)) while (true) { #if ENABLED(INPUT_SHAPING_X) if (step_needed.x) { const bool forward = ShapingQueue::dequeue_x(); PULSE_PREP_SHAPING(X, shaping_x.delta_error, (forward ? shaping_x.factor2 : -shaping_x.factor2)); PULSE_START(X); } #endif #if ENABLED(INPUT_SHAPING_Y) if (step_needed.y) { const bool forward = ShapingQueue::dequeue_y(); PULSE_PREP_SHAPING(Y, shaping_y.delta_error, (forward ? shaping_y.factor2 : -shaping_y.factor2)); PULSE_START(Y); } #endif TERN_(I2S_STEPPER_STREAM, i2s_push_sample()); USING_TIMED_PULSE(); if (bool(step_needed)) { #if ISR_MULTI_STEPS START_TIMED_PULSE(); AWAIT_HIGH_PULSE(); #endif #if ENABLED(INPUT_SHAPING_X) PULSE_STOP(X); #endif #if ENABLED(INPUT_SHAPING_Y) PULSE_STOP(Y); #endif } TERN_(INPUT_SHAPING_X, step_needed.x = !ShapingQueue::peek_x() || ShapingQueue::free_count_x() < steps_per_isr); TERN_(INPUT_SHAPING_Y, step_needed.y = !ShapingQueue::peek_y() || ShapingQueue::free_count_y() < steps_per_isr); if (!bool(step_needed)) break; START_TIMED_PULSE(); AWAIT_LOW_PULSE(); } } #endif // HAS_ZV_SHAPING // Calculate timer interval, with all limits applied. hal_timer_t Stepper::calc_timer_interval(uint32_t step_rate) { #ifdef CPU_32_BIT // A fast processor can just do integer division constexpr uint32_t min_step_rate = uint32_t(STEPPER_TIMER_RATE) / HAL_TIMER_TYPE_MAX; return step_rate > min_step_rate ? uint32_t(STEPPER_TIMER_RATE) / step_rate : HAL_TIMER_TYPE_MAX; #else constexpr uint32_t min_step_rate = (F_CPU) / 500000U; // i.e., 32 or 40 if (step_rate >= 0x0800) { // higher step rate // AVR is able to keep up at around 65kHz Stepping ISR rate at most. // So values for step_rate > 65535 might as well be truncated. // Handle it as quickly as possible. i.e., assume highest byte is zero // because non-zero would represent a step rate far beyond AVR capabilities. if (uint8_t(step_rate >> 16)) return uint32_t(STEPPER_TIMER_RATE) / 0x10000; const uintptr_t table_address = uintptr_t(&speed_lookuptable_fast[uint8_t(step_rate >> 8)]); const uint16_t base = uint16_t(pgm_read_word(table_address)); const uint8_t gain = uint8_t(pgm_read_byte(table_address + 2)); return base - MultiU8X8toH8(uint8_t(step_rate & 0x00FF), gain); } else if (step_rate > min_step_rate) { // lower step rates step_rate -= min_step_rate; // Correct for minimal speed const uintptr_t table_address = uintptr_t(&speed_lookuptable_slow[uint8_t(step_rate >> 3)]); return uint16_t(pgm_read_word(table_address)) - ((uint16_t(pgm_read_word(table_address + 2)) * uint8_t(step_rate & 0x0007)) >> 3); } return uint16_t(pgm_read_word(uintptr_t(speed_lookuptable_slow))); #endif // !CPU_32_BIT } #if ENABLED(NONLINEAR_EXTRUSION) void Stepper::calc_nonlinear_e(uint32_t step_rate) { const uint32_t velocity = ne_scale * step_rate; // Scale step_rate first so all intermediate values stay in range of 8.24 fixed point math int32_t vd = (((int64_t)ne_fix.A * velocity) >> 24) + (((((int64_t)ne_fix.B * velocity) >> 24) * velocity) >> 24); NOLESS(vd, 0); advance_dividend.e = (uint64_t(ne_fix.C + vd) * ne_edividend) >> 24; } #endif // Get the timer interval and the number of loops to perform per tick hal_timer_t Stepper::calc_multistep_timer_interval(uint32_t step_rate) { #if ENABLED(OLD_ADAPTIVE_MULTISTEPPING) #if MULTISTEPPING_LIMIT == 1 // Just make sure the step rate is doable NOMORE(step_rate, uint32_t(MAX_STEP_ISR_FREQUENCY_1X)); #else // The stepping frequency limits for each multistepping rate static const uint32_t limit[] PROGMEM = { ( MAX_STEP_ISR_FREQUENCY_1X ) , (((F_CPU) / ISR_EXECUTION_CYCLES(1)) >> 1) #if MULTISTEPPING_LIMIT >= 4 , (((F_CPU) / ISR_EXECUTION_CYCLES(2)) >> 2) #endif #if MULTISTEPPING_LIMIT >= 8 , (((F_CPU) / ISR_EXECUTION_CYCLES(3)) >> 3) #endif #if MULTISTEPPING_LIMIT >= 16 , (((F_CPU) / ISR_EXECUTION_CYCLES(4)) >> 4) #endif #if MULTISTEPPING_LIMIT >= 32 , (((F_CPU) / ISR_EXECUTION_CYCLES(5)) >> 5) #endif #if MULTISTEPPING_LIMIT >= 64 , (((F_CPU) / ISR_EXECUTION_CYCLES(6)) >> 6) #endif #if MULTISTEPPING_LIMIT >= 128 , (((F_CPU) / ISR_EXECUTION_CYCLES(7)) >> 7) #endif }; // Find a doable step rate using multistepping uint8_t multistep = 1; for (uint8_t i = 0; i < COUNT(limit) && step_rate > uint32_t(pgm_read_dword(&limit[i])); ++i) { step_rate >>= 1; multistep <<= 1; } steps_per_isr = multistep; #endif #elif MULTISTEPPING_LIMIT > 1 uint8_t loops = steps_per_isr; if (MULTISTEPPING_LIMIT >= 16 && loops >= 16) { step_rate >>= 4; loops >>= 4; } if (MULTISTEPPING_LIMIT >= 4 && loops >= 4) { step_rate >>= 2; loops >>= 2; } if (MULTISTEPPING_LIMIT >= 2 && loops >= 2) { step_rate >>= 1; } #endif return calc_timer_interval(step_rate); } // Method to get all moving axes (for proper endstop handling) void Stepper::set_axis_moved_for_current_block() { #if IS_CORE // Define conditions for checking endstops #define S_(N) current_block->steps[CORE_AXIS_##N] #define D_(N) current_block->direction_bits[CORE_AXIS_##N] #endif #if CORE_IS_XY || CORE_IS_XZ /** * Head direction in -X axis for CoreXY and CoreXZ bots. * * If steps differ, both axes are moving. * If DeltaA == -DeltaB, the movement is only in the 2nd axis (Y or Z, handled below) * If DeltaA == DeltaB, the movement is only in the 1st axis (X) */ #if ANY(COREXY, COREXZ) #define X_CMP(A,B) ((A)==(B)) #else #define X_CMP(A,B) ((A)!=(B)) #endif #define X_MOVE_TEST ( S_(1) != S_(2) || (S_(1) > 0 && X_CMP(D_(1),D_(2))) ) #elif ENABLED(MARKFORGED_XY) #define X_MOVE_TEST (current_block->steps.a != current_block->steps.b) #else #define X_MOVE_TEST !!current_block->steps.a #endif #if CORE_IS_XY || CORE_IS_YZ /** * Head direction in -Y axis for CoreXY / CoreYZ bots. * * If steps differ, both axes are moving * If DeltaA == DeltaB, the movement is only in the 1st axis (X or Y) * If DeltaA == -DeltaB, the movement is only in the 2nd axis (Y or Z) */ #if ANY(COREYX, COREYZ) #define Y_CMP(A,B) ((A)==(B)) #else #define Y_CMP(A,B) ((A)!=(B)) #endif #define Y_MOVE_TEST ( S_(1) != S_(2) || (S_(1) > 0 && Y_CMP(D_(1),D_(2))) ) #elif ENABLED(MARKFORGED_YX) #define Y_MOVE_TEST (current_block->steps.a != current_block->steps.b) #else #define Y_MOVE_TEST !!current_block->steps.b #endif #if CORE_IS_XZ || CORE_IS_YZ /** * Head direction in -Z axis for CoreXZ or CoreYZ bots. * * If steps differ, both axes are moving * If DeltaA == DeltaB, the movement is only in the 1st axis (X or Y, already handled above) * If DeltaA == -DeltaB, the movement is only in the 2nd axis (Z) */ #if ANY(COREZX, COREZY) #define Z_CMP(A,B) ((A)==(B)) #else #define Z_CMP(A,B) ((A)!=(B)) #endif #define Z_MOVE_TEST ( S_(1) != S_(2) || (S_(1) > 0 && Z_CMP(D_(1),D_(2))) ) #else #define Z_MOVE_TEST !!current_block->steps.c #endif // Set flags for all axes that move in this block // These are set per-axis, not per-stepper AxisBits didmove; NUM_AXIS_CODE( if (X_MOVE_TEST) didmove.a = true, // Cartesian X or Kinematic A if (Y_MOVE_TEST) didmove.b = true, // Cartesian Y or Kinematic B if (Z_MOVE_TEST) didmove.c = true, // Cartesian Z or Kinematic C if (!!current_block->steps.i) didmove.i = true, if (!!current_block->steps.j) didmove.j = true, if (!!current_block->steps.k) didmove.k = true, if (!!current_block->steps.u) didmove.u = true, if (!!current_block->steps.v) didmove.v = true, if (!!current_block->steps.w) didmove.w = true ); axis_did_move = didmove; } /** * This last phase of the stepper interrupt processes and properly * schedules planner blocks. This is executed after the step pulses * have been done, so it is less time critical. */ hal_timer_t Stepper::block_phase_isr() { #if DISABLED(OLD_ADAPTIVE_MULTISTEPPING) // If the ISR uses < 50% of MPU time, halve multi-stepping const hal_timer_t time_spent = HAL_timer_get_count(MF_TIMER_STEP); #if MULTISTEPPING_LIMIT > 1 if (steps_per_isr > 1 && time_spent_out_isr >= time_spent_in_isr + time_spent) { steps_per_isr >>= 1; // ticks_nominal will need to be recalculated if we are in cruise phase ticks_nominal = 0; } #endif time_spent_in_isr = -time_spent; // unsigned but guaranteed to be +ve when needed time_spent_out_isr = 0; #endif // If no queued movements, just wait 1ms for the next block hal_timer_t interval = (STEPPER_TIMER_RATE) / 1000UL; // If there is a current block if (current_block) { // If current block is finished, reset pointer and finalize state if (step_events_completed >= step_event_count) { #if ENABLED(DIRECT_STEPPING) // Direct stepping is currently not ready for HAS_I_AXIS #if STEPPER_PAGE_FORMAT == SP_4x4D_128 #define PAGE_SEGMENT_UPDATE_POS(AXIS) \ count_position[_AXIS(AXIS)] += page_step_state.bd[_AXIS(AXIS)] - 128 * 7; #elif STEPPER_PAGE_FORMAT == SP_4x1_512 || STEPPER_PAGE_FORMAT == SP_4x2_256 #define PAGE_SEGMENT_UPDATE_POS(AXIS) \ count_position[_AXIS(AXIS)] += page_step_state.bd[_AXIS(AXIS)] * count_direction[_AXIS(AXIS)]; #endif if (current_block->is_page()) { PAGE_SEGMENT_UPDATE_POS(X); PAGE_SEGMENT_UPDATE_POS(Y); PAGE_SEGMENT_UPDATE_POS(Z); PAGE_SEGMENT_UPDATE_POS(E); } #endif TERN_(HAS_FILAMENT_RUNOUT_DISTANCE, runout.block_completed(current_block)); discard_current_block(); } else { // Step events not completed yet... // Are we in acceleration phase ? if (step_events_completed <= accelerate_until) { // Calculate new timer value #if ENABLED(S_CURVE_ACCELERATION) // Get the next speed to use (Jerk limited!) uint32_t acc_step_rate = acceleration_time < current_block->acceleration_time ? _eval_bezier_curve(acceleration_time) : current_block->cruise_rate; #else acc_step_rate = STEP_MULTIPLY(acceleration_time, current_block->acceleration_rate) + current_block->initial_rate; NOMORE(acc_step_rate, current_block->nominal_rate); #endif // acc_step_rate is in steps/second // step_rate to timer interval and steps per stepper isr interval = calc_multistep_timer_interval(acc_step_rate << oversampling_factor); acceleration_time += interval; #if ENABLED(NONLINEAR_EXTRUSION) calc_nonlinear_e(acc_step_rate << oversampling_factor); #endif #if ENABLED(LIN_ADVANCE) if (la_active) { const uint32_t la_step_rate = la_advance_steps < current_block->max_adv_steps ? current_block->la_advance_rate : 0; la_interval = calc_timer_interval((acc_step_rate + la_step_rate) >> current_block->la_scaling); } #endif /** * Adjust Laser Power - Accelerating * * isPowered - True when a move is powered. * isEnabled - laser power is active. * * Laser power variables are calulated and stored in this block by the planner code. * trap_ramp_active_pwr - the active power in this block across accel or decel trap steps. * trap_ramp_entry_incr - holds the precalculated value to increase the current power per accel step. * * Apply the starting active power and then increase power per step by the trap_ramp_entry_incr value if positive. */ #if ENABLED(LASER_POWER_TRAP) if (cutter.cutter_mode == CUTTER_MODE_CONTINUOUS) { if (planner.laser_inline.status.isPowered && planner.laser_inline.status.isEnabled) { if (current_block->laser.trap_ramp_entry_incr > 0) { cutter.apply_power(current_block->laser.trap_ramp_active_pwr); current_block->laser.trap_ramp_active_pwr += current_block->laser.trap_ramp_entry_incr; } } // Not a powered move. else cutter.apply_power(0); } #endif } // Are we in Deceleration phase ? else if (step_events_completed > decelerate_after) { uint32_t step_rate; #if ENABLED(S_CURVE_ACCELERATION) // If this is the 1st time we process the 2nd half of the trapezoid... if (!bezier_2nd_half) { // Initialize the Bézier speed curve _calc_bezier_curve_coeffs(current_block->cruise_rate, current_block->final_rate, current_block->deceleration_time_inverse); bezier_2nd_half = true; // The first point starts at cruise rate. Just save evaluation of the Bézier curve step_rate = current_block->cruise_rate; } else { // Calculate the next speed to use step_rate = deceleration_time < current_block->deceleration_time ? _eval_bezier_curve(deceleration_time) : current_block->final_rate; } #else // Using the old trapezoidal control step_rate = STEP_MULTIPLY(deceleration_time, current_block->acceleration_rate); if (step_rate < acc_step_rate) { // Still decelerating? step_rate = acc_step_rate - step_rate; NOLESS(step_rate, current_block->final_rate); } else step_rate = current_block->final_rate; #endif // step_rate to timer interval and steps per stepper isr interval = calc_multistep_timer_interval(step_rate << oversampling_factor); deceleration_time += interval; #if ENABLED(NONLINEAR_EXTRUSION) calc_nonlinear_e(step_rate << oversampling_factor); #endif #if ENABLED(LIN_ADVANCE) if (la_active) { const uint32_t la_step_rate = la_advance_steps > current_block->final_adv_steps ? current_block->la_advance_rate : 0; if (la_step_rate != step_rate) { const bool forward_e = la_step_rate < step_rate; la_interval = calc_timer_interval((forward_e ? step_rate - la_step_rate : la_step_rate - step_rate) >> current_block->la_scaling); if (forward_e != motor_direction(E_AXIS)) { last_direction_bits.toggle(E_AXIS); count_direction.e = -count_direction.e; DIR_WAIT_BEFORE(); E_APPLY_DIR(forward_e, false); TERN_(FTM_OPTIMIZE_DIR_STATES, last_set_direction = last_direction_bits); DIR_WAIT_AFTER(); } } else la_interval = LA_ADV_NEVER; } #endif // LIN_ADVANCE /** * Adjust Laser Power - Decelerating * trap_ramp_entry_decr - holds the precalculated value to decrease the current power per decel step. */ #if ENABLED(LASER_POWER_TRAP) if (cutter.cutter_mode == CUTTER_MODE_CONTINUOUS) { if (planner.laser_inline.status.isPowered && planner.laser_inline.status.isEnabled) { if (current_block->laser.trap_ramp_exit_decr > 0) { current_block->laser.trap_ramp_active_pwr -= current_block->laser.trap_ramp_exit_decr; cutter.apply_power(current_block->laser.trap_ramp_active_pwr); } // Not a powered move. else cutter.apply_power(0); } } #endif } else { // Must be in cruise phase otherwise // Calculate the ticks_nominal for this nominal speed, if not done yet if (ticks_nominal == 0) { // step_rate to timer interval and loops for the nominal speed ticks_nominal = calc_multistep_timer_interval(current_block->nominal_rate << oversampling_factor); #if ENABLED(NONLINEAR_EXTRUSION) calc_nonlinear_e(current_block->nominal_rate << oversampling_factor); #endif #if ENABLED(LIN_ADVANCE) if (la_active) la_interval = calc_timer_interval(current_block->nominal_rate >> current_block->la_scaling); #endif } // The timer interval is just the nominal value for the nominal speed interval = ticks_nominal; } /** * Adjust Laser Power - Cruise * power - direct or floor adjusted active laser power. */ #if ENABLED(LASER_POWER_TRAP) if (cutter.cutter_mode == CUTTER_MODE_CONTINUOUS) { if (step_events_completed + 1 == accelerate_until) { if (planner.laser_inline.status.isPowered && planner.laser_inline.status.isEnabled) { if (current_block->laser.trap_ramp_entry_incr > 0) { current_block->laser.trap_ramp_active_pwr = current_block->laser.power; cutter.apply_power(current_block->laser.power); } } // Not a powered move. else cutter.apply_power(0); } } #endif } #if ENABLED(LASER_FEATURE) /** * CUTTER_MODE_DYNAMIC is experimental and developing. * Super-fast method to dynamically adjust the laser power OCR value based on the input feedrate in mm-per-minute. * TODO: Set up Min/Max OCR offsets to allow tuning and scaling of various lasers. * TODO: Integrate accel/decel +-rate into the dynamic laser power calc. */ if (cutter.cutter_mode == CUTTER_MODE_DYNAMIC && planner.laser_inline.status.isPowered // isPowered flag set on any parsed G1, G2, G3, or G5 move; cleared on any others. && current_block // Block may not be available if steps completed (see discard_current_block() above) && cutter.last_block_power != current_block->laser.power // Only update if the power changed ) { cutter.apply_power(current_block->laser.power); cutter.last_block_power = current_block->laser.power; } #endif } else { // !current_block #if ENABLED(LASER_FEATURE) if (cutter.cutter_mode == CUTTER_MODE_DYNAMIC) cutter.apply_power(0); // No movement in dynamic mode so turn Laser off #endif } // If there is no current block at this point, attempt to pop one from the buffer // and prepare its movement if (!current_block) { // Anything in the buffer? if ((current_block = planner.get_current_block())) { // Run through all sync blocks while (current_block->is_sync()) { // Set laser power #if ENABLED(LASER_POWER_SYNC) if (cutter.cutter_mode == CUTTER_MODE_CONTINUOUS) { if (current_block->is_sync_pwr()) { planner.laser_inline.status.isSyncPower = true; cutter.apply_power(current_block->laser.power); } } #endif // Set "fan speeds" for a laser module #if ENABLED(LASER_SYNCHRONOUS_M106_M107) if (current_block->is_sync_fan()) planner.sync_fan_speeds(current_block->fan_speed); #endif // Set position if (current_block->is_sync_pos()) _set_position(current_block->position); // Done with this block discard_current_block(); // Try to get a new block. Exit if there are no more. if (!(current_block = planner.get_current_block())) return interval; // No more queued movements! } // For non-inline cutter, grossly apply power #if HAS_CUTTER if (cutter.cutter_mode == CUTTER_MODE_STANDARD) { cutter.apply_power(current_block->cutter_power); } #endif #if ENABLED(POWER_LOSS_RECOVERY) recovery.info.sdpos = current_block->sdpos; recovery.info.current_position = current_block->start_position; #endif #if ENABLED(DIRECT_STEPPING) if (current_block->is_page()) { page_step_state.segment_steps = 0; page_step_state.segment_idx = 0; page_step_state.page = page_manager.get_page(current_block->page_idx); page_step_state.bd.reset(); if (DirectStepping::Config::DIRECTIONAL) current_block->direction_bits = last_direction_bits; if (!page_step_state.page) { discard_current_block(); return interval; } } #endif // Set flags for all moving axes, accounting for kinematics set_axis_moved_for_current_block(); // No acceleration / deceleration time elapsed so far acceleration_time = deceleration_time = 0; #if ENABLED(ADAPTIVE_STEP_SMOOTHING) // Nonlinear Extrusion needs at least 2x oversampling to permit increase of E step rate // Otherwise assume no axis smoothing (via oversampling) oversampling_factor = TERN(NONLINEAR_EXTRUSION, 1, 0); // Decide if axis smoothing is possible if (stepper.adaptive_step_smoothing_enabled) { uint32_t max_rate = current_block->nominal_rate; // Get the step event rate while (max_rate < MIN_STEP_ISR_FREQUENCY) { // As long as more ISRs are possible... max_rate <<= 1; // Try to double the rate if (max_rate < MIN_STEP_ISR_FREQUENCY) // Don't exceed the estimated ISR limit ++oversampling_factor; // Increase the oversampling (used for left-shift) } } #endif // Based on the oversampling factor, do the calculations step_event_count = current_block->step_event_count << oversampling_factor; // Initialize Bresenham delta errors to 1/2 delta_error = TERN_(LIN_ADVANCE, la_delta_error =) -int32_t(step_event_count); // Calculate Bresenham dividends and divisors advance_dividend = (current_block->steps << 1).asLong(); advance_divisor = step_event_count << 1; #if ENABLED(INPUT_SHAPING_X) if (shaping_x.enabled) { const int64_t steps = current_block->direction_bits.x ? int64_t(current_block->steps.x) : -int64_t(current_block->steps.x); shaping_x.last_block_end_pos += steps; // If there are any remaining echos unprocessed, then direction change must // be delayed and processed in PULSE_PREP_SHAPING. This will cause half a step // to be missed, which will need recovering and this can be done through shaping_x.remainder. shaping_x.forward = current_block->direction_bits.x; if (!ShapingQueue::empty_x()) current_block->direction_bits.x = last_direction_bits.x; } #endif // Y follows the same logic as X (but the comments aren't repeated) #if ENABLED(INPUT_SHAPING_Y) if (shaping_y.enabled) { const int64_t steps = current_block->direction_bits.y ? int64_t(current_block->steps.y) : -int64_t(current_block->steps.y); shaping_y.last_block_end_pos += steps; shaping_y.forward = current_block->direction_bits.y; if (!ShapingQueue::empty_y()) current_block->direction_bits.y = last_direction_bits.y; } #endif // No step events completed so far step_events_completed = 0; // Compute the acceleration and deceleration points accelerate_until = current_block->accelerate_until << oversampling_factor; decelerate_after = current_block->decelerate_after << oversampling_factor; TERN_(MIXING_EXTRUDER, mixer.stepper_setup(current_block->b_color)); E_TERN_(stepper_extruder = current_block->extruder); // Initialize the trapezoid generator from the current block. #if ENABLED(LIN_ADVANCE) la_active = (current_block->la_advance_rate != 0); #if DISABLED(MIXING_EXTRUDER) && E_STEPPERS > 1 // If the now active extruder wasn't in use during the last move, its pressure is most likely gone. if (stepper_extruder != last_moved_extruder) la_advance_steps = 0; #endif if (la_active) { // Apply LA scaling and discount the effect of frequency scaling la_dividend = (advance_dividend.e << current_block->la_scaling) << oversampling_factor; } #endif if ( ENABLED(DUAL_X_CARRIAGE) // TODO: Find out why this fixes "jittery" small circles || current_block->direction_bits != last_direction_bits || TERN(MIXING_EXTRUDER, false, stepper_extruder != last_moved_extruder) ) { E_TERN_(last_moved_extruder = stepper_extruder); set_directions(current_block->direction_bits); } #if ENABLED(LASER_FEATURE) if (cutter.cutter_mode == CUTTER_MODE_CONTINUOUS) { // Planner controls the laser if (planner.laser_inline.status.isSyncPower) // If the previous block was a M3 sync power then skip the trap power init otherwise it will 0 the sync power. planner.laser_inline.status.isSyncPower = false; // Clear the flag to process subsequent trap calc's. else if (current_block->laser.status.isEnabled) { #if ENABLED(LASER_POWER_TRAP) TERN_(DEBUG_LASER_TRAP, SERIAL_ECHO_MSG("InitTrapPwr:",current_block->laser.trap_ramp_active_pwr)); cutter.apply_power(current_block->laser.status.isPowered ? current_block->laser.trap_ramp_active_pwr : 0); #else TERN_(DEBUG_CUTTER_POWER, SERIAL_ECHO_MSG("InlinePwr:",current_block->laser.power)); cutter.apply_power(current_block->laser.status.isPowered ? current_block->laser.power : 0); #endif } } #endif // LASER_FEATURE // If the endstop is already pressed, endstop interrupts won't invoke // endstop_triggered and the move will grind. So check here for a // triggered endstop, which marks the block for discard on the next ISR. endstops.update(); #if ENABLED(Z_LATE_ENABLE) // If delayed Z enable, enable it now. This option will severely interfere with // timing between pulses when chaining motion between blocks, and it could lead // to lost steps in both X and Y axis, so avoid using it unless strictly necessary!! if (current_block->steps.z) enable_axis(Z_AXIS); #endif // Mark ticks_nominal as not-yet-calculated ticks_nominal = 0; #if ENABLED(S_CURVE_ACCELERATION) // Initialize the Bézier speed curve _calc_bezier_curve_coeffs(current_block->initial_rate, current_block->cruise_rate, current_block->acceleration_time_inverse); // We haven't started the 2nd half of the trapezoid bezier_2nd_half = false; #else // Set as deceleration point the initial rate of the block acc_step_rate = current_block->initial_rate; #endif #if ENABLED(NONLINEAR_EXTRUSION) ne_edividend = advance_dividend.e; const float scale = (float(ne_edividend) / advance_divisor) * planner.mm_per_step[E_AXIS_N(current_block->extruder)]; ne_scale = (1L << 24) * scale; if (current_block->direction_bits.e && ANY_AXIS_MOVES(current_block)) { ne_fix.A = (1L << 24) * ne.A; ne_fix.B = (1L << 24) * ne.B; ne_fix.C = (1L << 24) * ne.C; } else { ne_fix.A = ne_fix.B = 0; ne_fix.C = (1L << 24); } #endif // Calculate the initial timer interval interval = calc_multistep_timer_interval(current_block->initial_rate << oversampling_factor); acceleration_time += interval; #if ENABLED(NONLINEAR_EXTRUSION) calc_nonlinear_e(current_block->initial_rate << oversampling_factor); #endif #if ENABLED(LIN_ADVANCE) if (la_active) { const uint32_t la_step_rate = la_advance_steps < current_block->max_adv_steps ? current_block->la_advance_rate : 0; la_interval = calc_timer_interval((current_block->initial_rate + la_step_rate) >> current_block->la_scaling); } #endif } } // !current_block // Return the interval to wait return interval; } #if ENABLED(LIN_ADVANCE) // Timer interrupt for E. LA_steps is set in the main routine void Stepper::advance_isr() { // Apply Bresenham algorithm so that linear advance can piggy back on // the acceleration and speed values calculated in block_phase_isr(). // This helps keep LA in sync with, for example, S_CURVE_ACCELERATION. la_delta_error += la_dividend; const bool e_step_needed = la_delta_error >= 0; if (e_step_needed) { count_position.e += count_direction.e; la_advance_steps += count_direction.e; la_delta_error -= advance_divisor; // Set the STEP pulse ON E_STEP_WRITE(TERN(MIXING_EXTRUDER, mixer.get_next_stepper(), stepper_extruder), STEP_STATE_E); } TERN_(I2S_STEPPER_STREAM, i2s_push_sample()); if (e_step_needed) { // Enforce a minimum duration for STEP pulse ON #if ISR_PULSE_CONTROL USING_TIMED_PULSE(); START_TIMED_PULSE(); AWAIT_HIGH_PULSE(); #endif // Set the STEP pulse OFF E_STEP_WRITE(TERN(MIXING_EXTRUDER, mixer.get_stepper(), stepper_extruder), !STEP_STATE_E); } } #endif // LIN_ADVANCE #if ENABLED(BABYSTEPPING) // Timer interrupt for baby-stepping hal_timer_t Stepper::babystepping_isr() { babystep.task(); return babystep.has_steps() ? BABYSTEP_TICKS : BABYSTEP_NEVER; } #endif // Check if the given block is busy or not - Must not be called from ISR contexts // The current_block could change in the middle of the read by an Stepper ISR, so // we must explicitly prevent that! bool Stepper::is_block_busy(const block_t * const block) { #ifdef __AVR__ // A SW memory barrier, to ensure GCC does not overoptimize loops #define sw_barrier() asm volatile("": : :"memory"); // Keep reading until 2 consecutive reads return the same value, // meaning there was no update in-between caused by an interrupt. // This works because stepper ISRs happen at a slower rate than // successive reads of a variable, so 2 consecutive reads with // the same value means no interrupt updated it. block_t *vold, *vnew = current_block; sw_barrier(); do { vold = vnew; vnew = current_block; sw_barrier(); } while (vold != vnew); #else block_t *vnew = current_block; #endif // Return if the block is busy or not return block == vnew; } void Stepper::init() { #if MB(ALLIGATOR) const float motor_current[] = MOTOR_CURRENT; unsigned int digipot_motor = 0; for (uint8_t i = 0; i < 3 + EXTRUDERS; ++i) { digipot_motor = 255 * (motor_current[i] / 2.5); dac084s085::setValue(i, digipot_motor); } #endif // Init Microstepping Pins TERN_(HAS_MICROSTEPS, microstep_init()); // Init Dir Pins TERN_(HAS_X_DIR, X_DIR_INIT()); TERN_(HAS_X2_DIR, X2_DIR_INIT()); #if HAS_Y_DIR Y_DIR_INIT(); #if ALL(HAS_Y2_STEPPER, HAS_Y2_DIR) Y2_DIR_INIT(); #endif #endif #if HAS_Z_DIR Z_DIR_INIT(); #if NUM_Z_STEPPERS >= 2 && HAS_Z2_DIR Z2_DIR_INIT(); #endif #if NUM_Z_STEPPERS >= 3 && HAS_Z3_DIR Z3_DIR_INIT(); #endif #if NUM_Z_STEPPERS >= 4 && HAS_Z4_DIR Z4_DIR_INIT(); #endif #endif SECONDARY_AXIS_CODE( I_DIR_INIT(), J_DIR_INIT(), K_DIR_INIT(), U_DIR_INIT(), V_DIR_INIT(), W_DIR_INIT() ); #if HAS_E0_DIR E0_DIR_INIT(); #endif #if HAS_E1_DIR E1_DIR_INIT(); #endif #if HAS_E2_DIR E2_DIR_INIT(); #endif #if HAS_E3_DIR E3_DIR_INIT(); #endif #if HAS_E4_DIR E4_DIR_INIT(); #endif #if HAS_E5_DIR E5_DIR_INIT(); #endif #if HAS_E6_DIR E6_DIR_INIT(); #endif #if HAS_E7_DIR E7_DIR_INIT(); #endif // Init Enable Pins - steppers default to disabled. #if HAS_X_ENABLE #ifndef X_ENABLE_INIT_STATE #define X_ENABLE_INIT_STATE !X_ENABLE_ON #endif X_ENABLE_INIT(); if (X_ENABLE_INIT_STATE) X_ENABLE_WRITE(X_ENABLE_INIT_STATE); #if ALL(HAS_X2_STEPPER, HAS_X2_ENABLE) X2_ENABLE_INIT(); if (X_ENABLE_INIT_STATE) X2_ENABLE_WRITE(X_ENABLE_INIT_STATE); #endif #endif #if HAS_Y_ENABLE #ifndef Y_ENABLE_INIT_STATE #define Y_ENABLE_INIT_STATE !Y_ENABLE_ON #endif Y_ENABLE_INIT(); if (Y_ENABLE_INIT_STATE) Y_ENABLE_WRITE(Y_ENABLE_INIT_STATE); #if ALL(HAS_Y2_STEPPER, HAS_Y2_ENABLE) Y2_ENABLE_INIT(); if (Y_ENABLE_INIT_STATE) Y2_ENABLE_WRITE(Y_ENABLE_INIT_STATE); #endif #endif #if HAS_Z_ENABLE #ifndef Z_ENABLE_INIT_STATE #define Z_ENABLE_INIT_STATE !Z_ENABLE_ON #endif Z_ENABLE_INIT(); if (Z_ENABLE_INIT_STATE) Z_ENABLE_WRITE(Z_ENABLE_INIT_STATE); #if NUM_Z_STEPPERS >= 2 && HAS_Z2_ENABLE Z2_ENABLE_INIT(); if (Z_ENABLE_INIT_STATE) Z2_ENABLE_WRITE(Z_ENABLE_INIT_STATE); #endif #if NUM_Z_STEPPERS >= 3 && HAS_Z3_ENABLE Z3_ENABLE_INIT(); if (Z_ENABLE_INIT_STATE) Z3_ENABLE_WRITE(Z_ENABLE_INIT_STATE); #endif #if NUM_Z_STEPPERS >= 4 && HAS_Z4_ENABLE Z4_ENABLE_INIT(); if (Z_ENABLE_INIT_STATE) Z4_ENABLE_WRITE(Z_ENABLE_INIT_STATE); #endif #endif #if HAS_I_ENABLE I_ENABLE_INIT(); if (!I_ENABLE_ON) I_ENABLE_WRITE(HIGH); #endif #if HAS_J_ENABLE J_ENABLE_INIT(); if (!J_ENABLE_ON) J_ENABLE_WRITE(HIGH); #endif #if HAS_K_ENABLE K_ENABLE_INIT(); if (!K_ENABLE_ON) K_ENABLE_WRITE(HIGH); #endif #if HAS_U_ENABLE U_ENABLE_INIT(); if (!U_ENABLE_ON) U_ENABLE_WRITE(HIGH); #endif #if HAS_V_ENABLE V_ENABLE_INIT(); if (!V_ENABLE_ON) V_ENABLE_WRITE(HIGH); #endif #if HAS_W_ENABLE W_ENABLE_INIT(); if (!W_ENABLE_ON) W_ENABLE_WRITE(HIGH); #endif #if HAS_E0_ENABLE #ifndef E_ENABLE_INIT_STATE #define E_ENABLE_INIT_STATE !E_ENABLE_ON #endif #ifndef E0_ENABLE_INIT_STATE #define E0_ENABLE_INIT_STATE E_ENABLE_INIT_STATE #endif E0_ENABLE_INIT(); if (E0_ENABLE_INIT_STATE) E0_ENABLE_WRITE(E0_ENABLE_INIT_STATE); #endif #if HAS_E1_ENABLE #ifndef E1_ENABLE_INIT_STATE #define E1_ENABLE_INIT_STATE E_ENABLE_INIT_STATE #endif E1_ENABLE_INIT(); if (E1_ENABLE_INIT_STATE) E1_ENABLE_WRITE(E1_ENABLE_INIT_STATE); #endif #if HAS_E2_ENABLE #ifndef E2_ENABLE_INIT_STATE #define E2_ENABLE_INIT_STATE E_ENABLE_INIT_STATE #endif E2_ENABLE_INIT(); if (E2_ENABLE_INIT_STATE) E2_ENABLE_WRITE(E2_ENABLE_INIT_STATE); #endif #if HAS_E3_ENABLE #ifndef E3_ENABLE_INIT_STATE #define E3_ENABLE_INIT_STATE E_ENABLE_INIT_STATE #endif E3_ENABLE_INIT(); if (E3_ENABLE_INIT_STATE) E3_ENABLE_WRITE(E3_ENABLE_INIT_STATE); #endif #if HAS_E4_ENABLE #ifndef E4_ENABLE_INIT_STATE #define E4_ENABLE_INIT_STATE E_ENABLE_INIT_STATE #endif E4_ENABLE_INIT(); if (E4_ENABLE_INIT_STATE) E4_ENABLE_WRITE(E4_ENABLE_INIT_STATE); #endif #if HAS_E5_ENABLE #ifndef E5_ENABLE_INIT_STATE #define E5_ENABLE_INIT_STATE E_ENABLE_INIT_STATE #endif E5_ENABLE_INIT(); if (E5_ENABLE_INIT_STATE) E5_ENABLE_WRITE(E5_ENABLE_INIT_STATE); #endif #if HAS_E6_ENABLE #ifndef E6_ENABLE_INIT_STATE #define E6_ENABLE_INIT_STATE E_ENABLE_INIT_STATE #endif E6_ENABLE_INIT(); if (E6_ENABLE_INIT_STATE) E6_ENABLE_WRITE(E6_ENABLE_INIT_STATE); #endif #if HAS_E7_ENABLE #ifndef E7_ENABLE_INIT_STATE #define E7_ENABLE_INIT_STATE E_ENABLE_INIT_STATE #endif E7_ENABLE_INIT(); if (E7_ENABLE_INIT_STATE) E7_ENABLE_WRITE(E7_ENABLE_INIT_STATE); #endif #define _STEP_INIT(AXIS) AXIS ##_STEP_INIT() #define _WRITE_STEP(AXIS, HIGHLOW) AXIS ##_STEP_WRITE(HIGHLOW) #define _DISABLE_AXIS(AXIS) DISABLE_AXIS_## AXIS() #define AXIS_INIT(AXIS, PIN) \ _STEP_INIT(AXIS); \ _WRITE_STEP(AXIS, !_STEP_STATE(PIN)); \ _DISABLE_AXIS(AXIS) #define E_AXIS_INIT(NUM) AXIS_INIT(E## NUM, E) // Init Step Pins #if HAS_X_STEP #if HAS_X2_STEPPER X2_STEP_INIT(); X2_STEP_WRITE(!STEP_STATE_X); #endif AXIS_INIT(X, X); #endif #if HAS_Y_STEP #if HAS_Y2_STEPPER Y2_STEP_INIT(); Y2_STEP_WRITE(!STEP_STATE_Y); #endif AXIS_INIT(Y, Y); #endif #if HAS_Z_STEP #if NUM_Z_STEPPERS >= 2 Z2_STEP_INIT(); Z2_STEP_WRITE(!STEP_STATE_Z); #endif #if NUM_Z_STEPPERS >= 3 Z3_STEP_INIT(); Z3_STEP_WRITE(!STEP_STATE_Z); #endif #if NUM_Z_STEPPERS >= 4 Z4_STEP_INIT(); Z4_STEP_WRITE(!STEP_STATE_Z); #endif AXIS_INIT(Z, Z); #endif #if HAS_I_STEP AXIS_INIT(I, I); #endif #if HAS_J_STEP AXIS_INIT(J, J); #endif #if HAS_K_STEP AXIS_INIT(K, K); #endif #if HAS_U_STEP AXIS_INIT(U, U); #endif #if HAS_V_STEP AXIS_INIT(V, V); #endif #if HAS_W_STEP AXIS_INIT(W, W); #endif #if E_STEPPERS && HAS_E0_STEP E_AXIS_INIT(0); #endif #if (E_STEPPERS > 1 || ENABLED(E_DUAL_STEPPER_DRIVERS)) && HAS_E1_STEP E_AXIS_INIT(1); #endif #if E_STEPPERS > 2 && HAS_E2_STEP E_AXIS_INIT(2); #endif #if E_STEPPERS > 3 && HAS_E3_STEP E_AXIS_INIT(3); #endif #if E_STEPPERS > 4 && HAS_E4_STEP E_AXIS_INIT(4); #endif #if E_STEPPERS > 5 && HAS_E5_STEP E_AXIS_INIT(5); #endif #if E_STEPPERS > 6 && HAS_E6_STEP E_AXIS_INIT(6); #endif #if E_STEPPERS > 7 && HAS_E7_STEP E_AXIS_INIT(7); #endif #if DISABLED(I2S_STEPPER_STREAM) HAL_timer_start(MF_TIMER_STEP, 122); // Init Stepper ISR to 122 Hz for quick starting wake_up(); sei(); #endif // Init direction states apply_directions(); #if HAS_MOTOR_CURRENT_SPI || HAS_MOTOR_CURRENT_PWM initialized = true; digipot_init(); #endif } #if HAS_ZV_SHAPING /** * Calculate a fixed point factor to apply to the signal and its echo * when shaping an axis. */ void Stepper::set_shaping_damping_ratio(const AxisEnum axis, const_float_t zeta) { // From the damping ratio, get a factor that can be applied to advance_dividend for fixed-point maths. // For ZV, we use amplitudes 1/(1+K) and K/(1+K) where K = exp(-zeta * π / sqrt(1.0f - zeta * zeta)) // which can be converted to 1:7 fixed point with an excellent fit with a 3rd-order polynomial. float factor2; if (zeta <= 0.0f) factor2 = 64.0f; else if (zeta >= 1.0f) factor2 = 0.0f; else { factor2 = 64.44056192 + -99.02008832 * zeta; const float zeta2 = sq(zeta); factor2 += -7.58095488 * zeta2; const float zeta3 = zeta2 * zeta; factor2 += 43.073216 * zeta3; factor2 = FLOOR(factor2); } const bool was_on = hal.isr_state(); hal.isr_off(); TERN_(INPUT_SHAPING_X, if (axis == X_AXIS) { shaping_x.factor2 = factor2; shaping_x.factor1 = 128 - factor2; shaping_x.zeta = zeta; }) TERN_(INPUT_SHAPING_Y, if (axis == Y_AXIS) { shaping_y.factor2 = factor2; shaping_y.factor1 = 128 - factor2; shaping_y.zeta = zeta; }) if (was_on) hal.isr_on(); } float Stepper::get_shaping_damping_ratio(const AxisEnum axis) { TERN_(INPUT_SHAPING_X, if (axis == X_AXIS) return shaping_x.zeta); TERN_(INPUT_SHAPING_Y, if (axis == Y_AXIS) return shaping_y.zeta); return -1; } void Stepper::set_shaping_frequency(const AxisEnum axis, const_float_t freq) { // enabling or disabling shaping whilst moving can result in lost steps planner.synchronize(); const bool was_on = hal.isr_state(); hal.isr_off(); const shaping_time_t delay = freq ? float(uint32_t(STEPPER_TIMER_RATE) / 2) / freq : shaping_time_t(-1); #if ENABLED(INPUT_SHAPING_X) if (axis == X_AXIS) { ShapingQueue::set_delay(X_AXIS, delay); shaping_x.frequency = freq; shaping_x.enabled = !!freq; shaping_x.delta_error = 0; shaping_x.last_block_end_pos = count_position.x; } #endif #if ENABLED(INPUT_SHAPING_Y) if (axis == Y_AXIS) { ShapingQueue::set_delay(Y_AXIS, delay); shaping_y.frequency = freq; shaping_y.enabled = !!freq; shaping_y.delta_error = 0; shaping_y.last_block_end_pos = count_position.y; } #endif if (was_on) hal.isr_on(); } float Stepper::get_shaping_frequency(const AxisEnum axis) { TERN_(INPUT_SHAPING_X, if (axis == X_AXIS) return shaping_x.frequency); TERN_(INPUT_SHAPING_Y, if (axis == Y_AXIS) return shaping_y.frequency); return -1; } #endif // HAS_ZV_SHAPING /** * Set the stepper positions directly in steps * * The input is based on the typical per-axis XYZE steps. * For CORE machines XYZ needs to be translated to ABC. * * This allows get_axis_position_mm to correctly * derive the current XYZE position later on. */ void Stepper::_set_position(const abce_long_t &spos) { #if ENABLED(INPUT_SHAPING_X) const int32_t x_shaping_delta = count_position.x - shaping_x.last_block_end_pos; #endif #if ENABLED(INPUT_SHAPING_Y) const int32_t y_shaping_delta = count_position.y - shaping_y.last_block_end_pos; #endif #if ANY(IS_CORE, MARKFORGED_XY, MARKFORGED_YX) // Core equations follow the form of the dA and dB equations at https://www.corexy.com/theory.html #if CORE_IS_XY count_position.set(spos.a + spos.b, CORESIGN(spos.a - spos.b) OPTARG(HAS_Z_AXIS, spos.c)); #elif CORE_IS_XZ count_position.set(spos.a + spos.c, spos.b, CORESIGN(spos.a - spos.c)); #elif CORE_IS_YZ count_position.set(spos.a, spos.b + spos.c, CORESIGN(spos.b - spos.c)); #elif ENABLED(MARKFORGED_XY) count_position.set(spos.a TERN(MARKFORGED_INVERSE, +, -) spos.b, spos.b, spos.c); #elif ENABLED(MARKFORGED_YX) count_position.set(spos.a, spos.b TERN(MARKFORGED_INVERSE, +, -) spos.a, spos.c); #endif SECONDARY_AXIS_CODE( count_position.i = spos.i, count_position.j = spos.j, count_position.k = spos.k, count_position.u = spos.u, count_position.v = spos.v, count_position.w = spos.w ); TERN_(HAS_EXTRUDERS, count_position.e = spos.e); #else // default non-h-bot planning count_position = spos; #endif #if ENABLED(INPUT_SHAPING_X) if (shaping_x.enabled) { count_position.x += x_shaping_delta; shaping_x.last_block_end_pos = spos.x; } #endif #if ENABLED(INPUT_SHAPING_Y) if (shaping_y.enabled) { count_position.y += y_shaping_delta; shaping_y.last_block_end_pos = spos.y; } #endif } /** * Get a stepper's position in steps. */ int32_t Stepper::position(const AxisEnum axis) { #ifdef __AVR__ // Protect the access to the position. Only required for AVR, as // any 32bit CPU offers atomic access to 32bit variables const bool was_enabled = suspend(); #endif const int32_t v = count_position[axis]; #ifdef __AVR__ // Reenable Stepper ISR if (was_enabled) wake_up(); #endif return v; } // Set the current position in steps void Stepper::set_position(const xyze_long_t &spos) { planner.synchronize(); const bool was_enabled = suspend(); _set_position(spos); if (was_enabled) wake_up(); } void Stepper::set_axis_position(const AxisEnum a, const int32_t &v) { planner.synchronize(); #ifdef __AVR__ // Protect the access to the position. Only required for AVR, as // any 32bit CPU offers atomic access to 32bit variables const bool was_enabled = suspend(); #endif count_position[a] = v; TERN_(INPUT_SHAPING_X, if (a == X_AXIS) shaping_x.last_block_end_pos = v); TERN_(INPUT_SHAPING_Y, if (a == Y_AXIS) shaping_y.last_block_end_pos = v); #ifdef __AVR__ // Reenable Stepper ISR if (was_enabled) wake_up(); #endif } #if ENABLED(FT_MOTION) void Stepper::ftMotion_syncPosition() { //planner.synchronize(); planner already synchronized in M493 #ifdef __AVR__ // Protect the access to the position. Only required for AVR, as // any 32bit CPU offers atomic access to 32bit variables const bool was_enabled = suspend(); #endif // Update stepper positions from the planner count_position = planner.position; #ifdef __AVR__ // Reenable Stepper ISR if (was_enabled) wake_up(); #endif } #endif // FT_MOTION // Signal endstops were triggered - This function can be called from // an ISR context (Temperature, Stepper or limits ISR), so we must // be very careful here. If the interrupt being preempted was the // Stepper ISR (this CAN happen with the endstop limits ISR) then // when the stepper ISR resumes, we must be very sure that the movement // is properly canceled void Stepper::endstop_triggered(const AxisEnum axis) { const bool was_enabled = suspend(); endstops_trigsteps[axis] = ( #if IS_CORE (axis == CORE_AXIS_2 ? CORESIGN(count_position[CORE_AXIS_1] - count_position[CORE_AXIS_2]) : count_position[CORE_AXIS_1] + count_position[CORE_AXIS_2] ) * double(0.5) #elif ENABLED(MARKFORGED_XY) axis == CORE_AXIS_1 ? count_position[CORE_AXIS_1] TERN(MARKFORGED_INVERSE, +, -) count_position[CORE_AXIS_2] : count_position[CORE_AXIS_2] #elif ENABLED(MARKFORGED_YX) axis == CORE_AXIS_1 ? count_position[CORE_AXIS_1] : count_position[CORE_AXIS_2] TERN(MARKFORGED_INVERSE, +, -) count_position[CORE_AXIS_1] #else // !IS_CORE count_position[axis] #endif ); // Discard the rest of the move if there is a current block quick_stop(); if (was_enabled) wake_up(); } int32_t Stepper::triggered_position(const AxisEnum axis) { #ifdef __AVR__ // Protect the access to the position. Only required for AVR, as // any 32bit CPU offers atomic access to 32bit variables const bool was_enabled = suspend(); #endif const int32_t v = endstops_trigsteps[axis]; #ifdef __AVR__ // Reenable Stepper ISR if (was_enabled) wake_up(); #endif return v; } #if ANY(CORE_IS_XY, CORE_IS_XZ, MARKFORGED_XY, MARKFORGED_YX, IS_SCARA, DELTA) #define SAYS_A 1 #endif #if ANY(CORE_IS_XY, CORE_IS_YZ, MARKFORGED_XY, MARKFORGED_YX, IS_SCARA, DELTA, POLAR) #define SAYS_B 1 #endif #if ANY(CORE_IS_XZ, CORE_IS_YZ, DELTA) #define SAYS_C 1 #endif void Stepper::report_a_position(const xyz_long_t &pos) { #if NUM_AXES SERIAL_ECHOLNPGM_P( LIST_N(DOUBLE(NUM_AXES), TERN(SAYS_A, PSTR(STR_COUNT_A), PSTR(STR_COUNT_X)), pos.x, TERN(SAYS_B, PSTR("B:"), SP_Y_LBL), pos.y, TERN(SAYS_C, PSTR("C:"), SP_Z_LBL), pos.z, SP_I_LBL, pos.i, SP_J_LBL, pos.j, SP_K_LBL, pos.k, SP_U_LBL, pos.u, SP_V_LBL, pos.v, SP_W_LBL, pos.w ) ); #endif } void Stepper::report_positions() { #ifdef __AVR__ // Protect the access to the position. const bool was_enabled = suspend(); #endif const xyz_long_t pos = count_position; #ifdef __AVR__ if (was_enabled) wake_up(); #endif report_a_position(pos); } #if ENABLED(FT_MOTION) /** * Run stepping from the Stepper ISR at regular short intervals. * * - Set ftMotion.sts_stepperBusy state to reflect whether there are any commands in the circular buffer. * - If there are no commands in the buffer, return. * - Get the next command from the circular buffer ftMotion.stepperCmdBuff[]. * - If the block is being aborted, return without processing the command. * - Apply STEP/DIR along with any delays required. A command may be empty, with no STEP/DIR. */ void Stepper::ftMotion_stepper() { static AxisBits direction_bits{0}; // Check if the buffer is empty. ftMotion.sts_stepperBusy = (ftMotion.stepperCmdBuff_produceIdx != ftMotion.stepperCmdBuff_consumeIdx); if (!ftMotion.sts_stepperBusy) return; // "Pop" one command from current motion buffer const ft_command_t command = ftMotion.stepperCmdBuff[ftMotion.stepperCmdBuff_consumeIdx]; if (++ftMotion.stepperCmdBuff_consumeIdx == (FTM_STEPPERCMD_BUFF_SIZE)) ftMotion.stepperCmdBuff_consumeIdx = 0; if (abort_current_block) return; USING_TIMED_PULSE(); // Get FT Motion command flags for axis STEP / DIR #define _FTM_STEP(AXIS) TEST(command, FT_BIT_STEP_##AXIS) #define _FTM_DIR(AXIS) TEST(command, FT_BIT_DIR_##AXIS) AxisBits axis_step; axis_step = LOGICAL_AXIS_ARRAY( TEST(command, FT_BIT_STEP_E), TEST(command, FT_BIT_STEP_X), TEST(command, FT_BIT_STEP_Y), TEST(command, FT_BIT_STEP_Z), TEST(command, FT_BIT_STEP_I), TEST(command, FT_BIT_STEP_J), TEST(command, FT_BIT_STEP_K), TEST(command, FT_BIT_STEP_U), TEST(command, FT_BIT_STEP_V), TEST(command, FT_BIT_STEP_W) ); direction_bits = LOGICAL_AXIS_ARRAY( axis_step.e ? TEST(command, FT_BIT_DIR_E) : direction_bits.e, axis_step.x ? TEST(command, FT_BIT_DIR_X) : direction_bits.x, axis_step.y ? TEST(command, FT_BIT_DIR_Y) : direction_bits.y, axis_step.z ? TEST(command, FT_BIT_DIR_Z) : direction_bits.z, axis_step.i ? TEST(command, FT_BIT_DIR_I) : direction_bits.i, axis_step.j ? TEST(command, FT_BIT_DIR_J) : direction_bits.j, axis_step.k ? TEST(command, FT_BIT_DIR_K) : direction_bits.k, axis_step.u ? TEST(command, FT_BIT_DIR_U) : direction_bits.u, axis_step.v ? TEST(command, FT_BIT_DIR_V) : direction_bits.v, axis_step.w ? TEST(command, FT_BIT_DIR_W) : direction_bits.w ); // Apply directions (which will apply to the entire linear move) LOGICAL_AXIS_CODE( E_APPLY_DIR(direction_bits.e, false), X_APPLY_DIR(direction_bits.x, false), Y_APPLY_DIR(direction_bits.y, false), Z_APPLY_DIR(direction_bits.z, false), I_APPLY_DIR(direction_bits.i, false), J_APPLY_DIR(direction_bits.j, false), K_APPLY_DIR(direction_bits.k, false), U_APPLY_DIR(direction_bits.u, false), V_APPLY_DIR(direction_bits.v, false), W_APPLY_DIR(direction_bits.w, false) ); /** * Update direction bits for steppers that were stepped by this command. * HX, HY, HZ direction bits were set for Core kinematics * when the block was fetched and are not overwritten here. */ // Start a step pulse LOGICAL_AXIS_CODE( E_APPLY_STEP(axis_step.e, false), X_APPLY_STEP(axis_step.x, false), Y_APPLY_STEP(axis_step.y, false), Z_APPLY_STEP(axis_step.z, false), I_APPLY_STEP(axis_step.i, false), J_APPLY_STEP(axis_step.j, false), K_APPLY_STEP(axis_step.k, false), U_APPLY_STEP(axis_step.u, false), V_APPLY_STEP(axis_step.v, false), W_APPLY_STEP(axis_step.w, false) ); if (TERN1(FTM_OPTIMIZE_DIR_STATES, last_set_direction != last_direction_bits)) { // Apply directions (generally applying to the entire linear move) #define _FTM_APPLY_DIR(AXIS) if (TERN1(FTM_OPTIMIZE_DIR_STATES, last_direction_bits[_AXIS(A)] != last_set_direction[_AXIS(AXIS)])) \ SET_STEP_DIR(AXIS); LOGICAL_AXIS_MAP(_FTM_APPLY_DIR); TERN_(FTM_OPTIMIZE_DIR_STATES, last_set_direction = last_direction_bits); // Any DIR change requires a wait period DIR_WAIT_AFTER(); } // Start step pulses. Edge stepping will toggle the STEP pin. #define _FTM_STEP_START(AXIS) AXIS##_APPLY_STEP(_FTM_STEP(AXIS), false); LOGICAL_AXIS_MAP(_FTM_STEP_START); // Apply steps via I2S TERN_(I2S_STEPPER_STREAM, i2s_push_sample()); // Begin waiting for the minimum pulse duration START_TIMED_PULSE(); // Update step counts #define _FTM_STEP_COUNT(AXIS) if (axis_step[_AXIS(AXIS)]) count_position[_AXIS(AXIS)] += direction_bits[_AXIS(AXIS)] ? 1 : -1; LOGICAL_AXIS_MAP(_FTM_STEP_COUNT); // Provide EDGE flags for E stepper(s) #if HAS_EXTRUDERS #if ENABLED(E_DUAL_STEPPER_DRIVERS) constexpr bool e_axis_has_dedge = AXIS_HAS_DEDGE(E0) && AXIS_HAS_DEDGE(E1); #else #define _EDGE_BIT(N) | (AXIS_HAS_DEDGE(E##N) << TOOL_ESTEPPER(N)) constexpr Flags<E_STEPPERS> e_stepper_dedge { 0 REPEAT(EXTRUDERS, _EDGE_BIT) }; const bool e_axis_has_dedge = e_stepper_dedge[stepper_extruder]; #endif #endif // Only wait for axes without edge stepping const bool any_wait = false LOGICAL_AXIS_GANG( || (!e_axis_has_dedge && axis_step.e), || (!AXIS_HAS_DEDGE(X) && axis_step.x), || (!AXIS_HAS_DEDGE(Y) && axis_step.y), || (!AXIS_HAS_DEDGE(Z) && axis_step.z), || (!AXIS_HAS_DEDGE(I) && axis_step.i), || (!AXIS_HAS_DEDGE(J) && axis_step.j), || (!AXIS_HAS_DEDGE(K) && axis_step.k), || (!AXIS_HAS_DEDGE(U) && axis_step.u), || (!AXIS_HAS_DEDGE(V) && axis_step.v), || (!AXIS_HAS_DEDGE(W) && axis_step.w) ); // Allow pulses to be registered by stepper drivers if (any_wait) AWAIT_HIGH_PULSE(); // Stop pulses. Axes with DEDGE will do nothing, assuming STEP_STATE_* is HIGH #define _FTM_STEP_STOP(AXIS) AXIS##_APPLY_STEP(!STEP_STATE_##AXIS, false); LOGICAL_AXIS_MAP(_FTM_STEP_STOP); // Also handle babystepping here TERN_(BABYSTEPPING, if (babystep.has_steps()) babystepping_isr()); } // Stepper::ftMotion_stepper // Called from FTMotion::loop (when !blockProcRdy) which is called from Marlin idle() void Stepper::ftMotion_blockQueueUpdate() { if (current_block) { // If the current block is not done processing, return right away. // A block is done processing when the command buffer has been // filled, not necessarily when it's done running. if (!ftMotion.getBlockProcDn()) return; planner.release_current_block(); } // Check the buffer for a new block current_block = planner.get_current_block(); if (current_block) { // Sync position, fan power, laser power? while (current_block->is_sync()) { #if 0 // TODO: Implement compatible sync blocks with FT Motion commands, // perhaps by setting a FT_BIT_SYNC flag that holds the current block // until it is processed by ftMotion_stepper // Set laser power #if ENABLED(LASER_POWER_SYNC) if (cutter.cutter_mode == CUTTER_MODE_CONTINUOUS) { if (current_block->is_sync_pwr()) { planner.laser_inline.status.isSyncPower = true; cutter.apply_power(current_block->laser.power); } } #endif // Set "fan speeds" for a laser module #if ENABLED(LASER_SYNCHRONOUS_M106_M107) if (current_block->is_sync_fan()) planner.sync_fan_speeds(current_block->fan_speed); #endif // Set position if (current_block->is_sync_pos()) _set_position(current_block->position); #endif // Done with this block planner.release_current_block(); // Try to get a new block if (!(current_block = planner.get_current_block())) return; // No queued blocks. } // Some kinematics track axis motion in HX, HY, HZ #if ANY(CORE_IS_XY, CORE_IS_XZ, MARKFORGED_XY, MARKFORGED_YX) last_direction_bits.hx = current_block->direction_bits.hx; #endif #if ANY(CORE_IS_XY, CORE_IS_YZ, MARKFORGED_XY, MARKFORGED_YX) last_direction_bits.hy = current_block->direction_bits.hy; #endif #if ANY(CORE_IS_XZ, CORE_IS_YZ) last_direction_bits.hz = current_block->direction_bits.hz; #endif ftMotion.startBlockProc(); return; } ftMotion.runoutBlock(); } // Stepper::ftMotion_blockQueueUpdate() #endif // FT_MOTION #if ENABLED(BABYSTEPPING) #define _ENABLE_AXIS(A) enable_axis(_AXIS(A)) #define _READ_DIR(AXIS) AXIS ##_DIR_READ() #define _APPLY_DIR(AXIS, FWD) AXIS ##_APPLY_DIR(FWD, true) #if MINIMUM_STEPPER_PULSE #define STEP_PULSE_CYCLES ((MINIMUM_STEPPER_PULSE) * CYCLES_PER_MICROSECOND) #else #define STEP_PULSE_CYCLES 0 #endif #if ENABLED(DELTA) #define CYCLES_EATEN_BABYSTEP (2 * 15) #else #define CYCLES_EATEN_BABYSTEP 0 #endif #if CYCLES_EATEN_BABYSTEP < STEP_PULSE_CYCLES #define EXTRA_CYCLES_BABYSTEP (STEP_PULSE_CYCLES - (CYCLES_EATEN_BABYSTEP)) #else #define EXTRA_CYCLES_BABYSTEP 0 #endif #if EXTRA_CYCLES_BABYSTEP > 20 #define _SAVE_START() const hal_timer_t pulse_start = HAL_timer_get_count(MF_TIMER_PULSE) #define _PULSE_WAIT() while (EXTRA_CYCLES_BABYSTEP > uint32_t(HAL_timer_get_count(MF_TIMER_PULSE) - pulse_start) * (PULSE_TIMER_PRESCALE)) { /* nada */ } #else #define _SAVE_START() NOOP #if EXTRA_CYCLES_BABYSTEP > 0 #define _PULSE_WAIT() DELAY_NS(EXTRA_CYCLES_BABYSTEP * NANOSECONDS_PER_CYCLE) #elif ENABLED(DELTA) #define _PULSE_WAIT() DELAY_US(2); #elif STEP_PULSE_CYCLES > 0 #define _PULSE_WAIT() NOOP #else #define _PULSE_WAIT() DELAY_US(4); #endif #endif #if ENABLED(BABYSTEPPING_EXTRA_DIR_WAIT) #define EXTRA_DIR_WAIT_BEFORE DIR_WAIT_BEFORE #define EXTRA_DIR_WAIT_AFTER DIR_WAIT_AFTER #else #define EXTRA_DIR_WAIT_BEFORE() #define EXTRA_DIR_WAIT_AFTER() #endif #if DISABLED(DELTA) #define BABYSTEP_AXIS(AXIS, FWD, INV) do{ \ const bool old_fwd = _READ_DIR(AXIS); \ _ENABLE_AXIS(AXIS); \ DIR_WAIT_BEFORE(); \ _APPLY_DIR(AXIS, (FWD)^(INV)); \ DIR_WAIT_AFTER(); \ _SAVE_START(); \ _APPLY_STEP(AXIS, _STEP_STATE(AXIS), true); \ _PULSE_WAIT(); \ _APPLY_STEP(AXIS, !_STEP_STATE(AXIS), true); \ EXTRA_DIR_WAIT_BEFORE(); \ _APPLY_DIR(AXIS, old_fwd); \ EXTRA_DIR_WAIT_AFTER(); \ }while(0) #endif #if IS_CORE #define BABYSTEP_CORE(A, B, FWD, INV, ALT) do{ \ const xy_byte_t old_fwd = { _READ_DIR(A), _READ_DIR(B) }; \ _ENABLE_AXIS(A); _ENABLE_AXIS(B); \ DIR_WAIT_BEFORE(); \ _APPLY_DIR(A, (FWD)^(INV)); \ _APPLY_DIR(B, (FWD)^(INV)^(ALT)); \ DIR_WAIT_AFTER(); \ _SAVE_START(); \ _APPLY_STEP(A, _STEP_STATE(A), true); \ _APPLY_STEP(B, _STEP_STATE(B), true); \ _PULSE_WAIT(); \ _APPLY_STEP(A, !_STEP_STATE(A), true); \ _APPLY_STEP(B, !_STEP_STATE(B), true); \ EXTRA_DIR_WAIT_BEFORE(); \ _APPLY_DIR(A, old_fwd.a); _APPLY_DIR(B, old_fwd.b); \ EXTRA_DIR_WAIT_AFTER(); \ }while(0) #endif // MUST ONLY BE CALLED BY AN ISR, // No other ISR should ever interrupt this! void Stepper::do_babystep(const AxisEnum axis, const bool direction) { IF_DISABLED(BABYSTEPPING, cli()); switch (axis) { #if ENABLED(BABYSTEP_XY) case X_AXIS: #if CORE_IS_XY BABYSTEP_CORE(X, Y, direction, 0, 0); #elif CORE_IS_XZ BABYSTEP_CORE(X, Z, direction, 0, 0); #else BABYSTEP_AXIS(X, direction, 0); #endif break; case Y_AXIS: #if CORE_IS_XY BABYSTEP_CORE(X, Y, direction, 0, (CORESIGN(1)>0)); #elif CORE_IS_YZ BABYSTEP_CORE(Y, Z, direction, 0, (CORESIGN(1)<0)); #else BABYSTEP_AXIS(Y, direction, 0); #endif break; #endif case Z_AXIS: { #if CORE_IS_XZ BABYSTEP_CORE(X, Z, direction, ENABLED(BABYSTEP_INVERT_Z), (CORESIGN(1)>0)); #elif CORE_IS_YZ BABYSTEP_CORE(Y, Z, direction, ENABLED(BABYSTEP_INVERT_Z), (CORESIGN(1)<0)); #elif DISABLED(DELTA) BABYSTEP_AXIS(Z, direction, ENABLED(BABYSTEP_INVERT_Z)); #else // DELTA const bool z_direction = TERN_(BABYSTEP_INVERT_Z, !) direction; enable_axis(A_AXIS); enable_axis(B_AXIS); enable_axis(C_AXIS); DIR_WAIT_BEFORE(); const bool old_fwd[3] = { X_DIR_READ(), Y_DIR_READ(), Z_DIR_READ() }; X_DIR_WRITE(z_direction); Y_DIR_WRITE(z_direction); Z_DIR_WRITE(z_direction); DIR_WAIT_AFTER(); _SAVE_START(); X_STEP_WRITE(STEP_STATE_X); Y_STEP_WRITE(STEP_STATE_Y); Z_STEP_WRITE(STEP_STATE_Z); _PULSE_WAIT(); X_STEP_WRITE(!STEP_STATE_X); Y_STEP_WRITE(!STEP_STATE_Y); Z_STEP_WRITE(!STEP_STATE_Z); // Restore direction bits EXTRA_DIR_WAIT_BEFORE(); X_DIR_WRITE(old_fwd[A_AXIS]); Y_DIR_WRITE(old_fwd[B_AXIS]); Z_DIR_WRITE(old_fwd[C_AXIS]); EXTRA_DIR_WAIT_AFTER(); #endif } break; default: break; } IF_DISABLED(BABYSTEPPING, sei()); } #endif // BABYSTEPPING /** * Software-controlled Stepper Motor Current */ #if HAS_MOTOR_CURRENT_SPI // From Arduino DigitalPotControl example void Stepper::set_digipot_value_spi(const int16_t address, const int16_t value) { WRITE(DIGIPOTSS_PIN, LOW); // Take the SS pin low to select the chip SPI.transfer(address); // Send the address and value via SPI SPI.transfer(value); WRITE(DIGIPOTSS_PIN, HIGH); // Take the SS pin high to de-select the chip //delay(10); } #endif // HAS_MOTOR_CURRENT_SPI #if HAS_MOTOR_CURRENT_PWM void Stepper::refresh_motor_power() { if (!initialized) return; for (uint8_t i = 0; i < COUNT(motor_current_setting); ++i) { switch (i) { #if ANY_PIN(MOTOR_CURRENT_PWM_XY, MOTOR_CURRENT_PWM_X, MOTOR_CURRENT_PWM_Y, MOTOR_CURRENT_PWM_I, MOTOR_CURRENT_PWM_J, MOTOR_CURRENT_PWM_K, MOTOR_CURRENT_PWM_U, MOTOR_CURRENT_PWM_V, MOTOR_CURRENT_PWM_W) case 0: #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z) case 1: #endif #if ANY_PIN(MOTOR_CURRENT_PWM_E, MOTOR_CURRENT_PWM_E0, MOTOR_CURRENT_PWM_E1) case 2: #endif set_digipot_current(i, motor_current_setting[i]); default: break; } } } #endif // HAS_MOTOR_CURRENT_PWM #if !MB(PRINTRBOARD_G2) #if HAS_MOTOR_CURRENT_SPI || HAS_MOTOR_CURRENT_PWM void Stepper::set_digipot_current(const uint8_t driver, const int16_t current) { if (WITHIN(driver, 0, MOTOR_CURRENT_COUNT - 1)) motor_current_setting[driver] = current; // update motor_current_setting if (!initialized) return; #if HAS_MOTOR_CURRENT_SPI //SERIAL_ECHOLNPGM("Digipotss current ", current); const uint8_t digipot_ch[] = DIGIPOT_CHANNELS; set_digipot_value_spi(digipot_ch[driver], current); #elif HAS_MOTOR_CURRENT_PWM #define _WRITE_CURRENT_PWM(P) hal.set_pwm_duty(pin_t(MOTOR_CURRENT_PWM_## P ##_PIN), 255L * current / (MOTOR_CURRENT_PWM_RANGE)) switch (driver) { case 0: #if PIN_EXISTS(MOTOR_CURRENT_PWM_X) _WRITE_CURRENT_PWM(X); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_Y) _WRITE_CURRENT_PWM(Y); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY) _WRITE_CURRENT_PWM(XY); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_I) _WRITE_CURRENT_PWM(I); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_J) _WRITE_CURRENT_PWM(J); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_K) _WRITE_CURRENT_PWM(K); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_U) _WRITE_CURRENT_PWM(U); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_V) _WRITE_CURRENT_PWM(V); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_W) _WRITE_CURRENT_PWM(W); #endif break; case 1: #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z) _WRITE_CURRENT_PWM(Z); #endif break; case 2: #if PIN_EXISTS(MOTOR_CURRENT_PWM_E) _WRITE_CURRENT_PWM(E); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_E0) _WRITE_CURRENT_PWM(E0); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_E1) _WRITE_CURRENT_PWM(E1); #endif break; } #endif } void Stepper::digipot_init() { #if HAS_MOTOR_CURRENT_SPI SPI.begin(); SET_OUTPUT(DIGIPOTSS_PIN); for (uint8_t i = 0; i < COUNT(motor_current_setting); ++i) set_digipot_current(i, motor_current_setting[i]); #elif HAS_MOTOR_CURRENT_PWM #ifdef __SAM3X8E__ #define _RESET_CURRENT_PWM_FREQ(P) NOOP #else #define _RESET_CURRENT_PWM_FREQ(P) hal.set_pwm_frequency(pin_t(P), MOTOR_CURRENT_PWM_FREQUENCY) #endif #define INIT_CURRENT_PWM(P) do{ SET_PWM(MOTOR_CURRENT_PWM_## P ##_PIN); _RESET_CURRENT_PWM_FREQ(MOTOR_CURRENT_PWM_## P ##_PIN); }while(0) #if PIN_EXISTS(MOTOR_CURRENT_PWM_X) INIT_CURRENT_PWM(X); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_Y) INIT_CURRENT_PWM(Y); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY) INIT_CURRENT_PWM(XY); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_I) INIT_CURRENT_PWM(I); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_J) INIT_CURRENT_PWM(J); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_K) INIT_CURRENT_PWM(K); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_U) INIT_CURRENT_PWM(U); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_V) INIT_CURRENT_PWM(V); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_W) INIT_CURRENT_PWM(W); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z) INIT_CURRENT_PWM(Z); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_E) INIT_CURRENT_PWM(E); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_E0) INIT_CURRENT_PWM(E0); #endif #if PIN_EXISTS(MOTOR_CURRENT_PWM_E1) INIT_CURRENT_PWM(E1); #endif refresh_motor_power(); #endif } #endif #else // PRINTRBOARD_G2 #include HAL_PATH(.., fastio/G2_PWM.h) #endif #if HAS_MICROSTEPS /** * Software-controlled Microstepping */ void Stepper::microstep_init() { #if HAS_X_MS_PINS SET_OUTPUT(X_MS1_PIN); SET_OUTPUT(X_MS2_PIN); #if PIN_EXISTS(X_MS3) SET_OUTPUT(X_MS3_PIN); #endif #endif #if HAS_X2_MS_PINS SET_OUTPUT(X2_MS1_PIN); SET_OUTPUT(X2_MS2_PIN); #if PIN_EXISTS(X2_MS3) SET_OUTPUT(X2_MS3_PIN); #endif #endif #if HAS_Y_MS_PINS SET_OUTPUT(Y_MS1_PIN); SET_OUTPUT(Y_MS2_PIN); #if PIN_EXISTS(Y_MS3) SET_OUTPUT(Y_MS3_PIN); #endif #endif #if HAS_Y2_MS_PINS SET_OUTPUT(Y2_MS1_PIN); SET_OUTPUT(Y2_MS2_PIN); #if PIN_EXISTS(Y2_MS3) SET_OUTPUT(Y2_MS3_PIN); #endif #endif #if HAS_Z_MS_PINS SET_OUTPUT(Z_MS1_PIN); SET_OUTPUT(Z_MS2_PIN); #if PIN_EXISTS(Z_MS3) SET_OUTPUT(Z_MS3_PIN); #endif #endif #if HAS_Z2_MS_PINS SET_OUTPUT(Z2_MS1_PIN); SET_OUTPUT(Z2_MS2_PIN); #if PIN_EXISTS(Z2_MS3) SET_OUTPUT(Z2_MS3_PIN); #endif #endif #if HAS_Z3_MS_PINS SET_OUTPUT(Z3_MS1_PIN); SET_OUTPUT(Z3_MS2_PIN); #if PIN_EXISTS(Z3_MS3) SET_OUTPUT(Z3_MS3_PIN); #endif #endif #if HAS_Z4_MS_PINS SET_OUTPUT(Z4_MS1_PIN); SET_OUTPUT(Z4_MS2_PIN); #if PIN_EXISTS(Z4_MS3) SET_OUTPUT(Z4_MS3_PIN); #endif #endif #if HAS_I_MS_PINS SET_OUTPUT(I_MS1_PIN); SET_OUTPUT(I_MS2_PIN); #if PIN_EXISTS(I_MS3) SET_OUTPUT(I_MS3_PIN); #endif #endif #if HAS_J_MS_PINS SET_OUTPUT(J_MS1_PIN); SET_OUTPUT(J_MS2_PIN); #if PIN_EXISTS(J_MS3) SET_OUTPUT(J_MS3_PIN); #endif #endif #if HAS_K_MS_PINS SET_OUTPUT(K_MS1_PIN); SET_OUTPUT(K_MS2_PIN); #if PIN_EXISTS(K_MS3) SET_OUTPUT(K_MS3_PIN); #endif #endif #if HAS_U_MS_PINS SET_OUTPUT(U_MS1_PIN); SET_OUTPUT(U_MS2_PIN); #if PIN_EXISTS(U_MS3) SET_OUTPUT(U_MS3_PIN); #endif #endif #if HAS_V_MS_PINS SET_OUTPUT(V_MS1_PIN); SET_OUTPUT(V_MS2_PIN); #if PIN_EXISTS(V_MS3) SET_OUTPUT(V_MS3_PIN); #endif #endif #if HAS_W_MS_PINS SET_OUTPUT(W_MS1_PIN); SET_OUTPUT(W_MS2_PIN); #if PIN_EXISTS(W_MS3) SET_OUTPUT(W_MS3_PIN); #endif #endif #if HAS_E0_MS_PINS SET_OUTPUT(E0_MS1_PIN); SET_OUTPUT(E0_MS2_PIN); #if PIN_EXISTS(E0_MS3) SET_OUTPUT(E0_MS3_PIN); #endif #endif #if HAS_E1_MS_PINS SET_OUTPUT(E1_MS1_PIN); SET_OUTPUT(E1_MS2_PIN); #if PIN_EXISTS(E1_MS3) SET_OUTPUT(E1_MS3_PIN); #endif #endif #if HAS_E2_MS_PINS SET_OUTPUT(E2_MS1_PIN); SET_OUTPUT(E2_MS2_PIN); #if PIN_EXISTS(E2_MS3) SET_OUTPUT(E2_MS3_PIN); #endif #endif #if HAS_E3_MS_PINS SET_OUTPUT(E3_MS1_PIN); SET_OUTPUT(E3_MS2_PIN); #if PIN_EXISTS(E3_MS3) SET_OUTPUT(E3_MS3_PIN); #endif #endif #if HAS_E4_MS_PINS SET_OUTPUT(E4_MS1_PIN); SET_OUTPUT(E4_MS2_PIN); #if PIN_EXISTS(E4_MS3) SET_OUTPUT(E4_MS3_PIN); #endif #endif #if HAS_E5_MS_PINS SET_OUTPUT(E5_MS1_PIN); SET_OUTPUT(E5_MS2_PIN); #if PIN_EXISTS(E5_MS3) SET_OUTPUT(E5_MS3_PIN); #endif #endif #if HAS_E6_MS_PINS SET_OUTPUT(E6_MS1_PIN); SET_OUTPUT(E6_MS2_PIN); #if PIN_EXISTS(E6_MS3) SET_OUTPUT(E6_MS3_PIN); #endif #endif #if HAS_E7_MS_PINS SET_OUTPUT(E7_MS1_PIN); SET_OUTPUT(E7_MS2_PIN); #if PIN_EXISTS(E7_MS3) SET_OUTPUT(E7_MS3_PIN); #endif #endif static const uint8_t microstep_modes[] = MICROSTEP_MODES; for (uint16_t i = 0; i < COUNT(microstep_modes); i++) microstep_mode(i, microstep_modes[i]); } void Stepper::microstep_ms(const uint8_t driver, const int8_t ms1, const int8_t ms2, const int8_t ms3) { if (ms1 >= 0) switch (driver) { #if HAS_X_MS_PINS || HAS_X2_MS_PINS case X_AXIS: #if HAS_X_MS_PINS WRITE(X_MS1_PIN, ms1); #endif #if HAS_X2_MS_PINS WRITE(X2_MS1_PIN, ms1); #endif break; #endif #if HAS_Y_MS_PINS || HAS_Y2_MS_PINS case Y_AXIS: #if HAS_Y_MS_PINS WRITE(Y_MS1_PIN, ms1); #endif #if HAS_Y2_MS_PINS WRITE(Y2_MS1_PIN, ms1); #endif break; #endif #if HAS_SOME_Z_MS_PINS case Z_AXIS: #if HAS_Z_MS_PINS WRITE(Z_MS1_PIN, ms1); #endif #if HAS_Z2_MS_PINS WRITE(Z2_MS1_PIN, ms1); #endif #if HAS_Z3_MS_PINS WRITE(Z3_MS1_PIN, ms1); #endif #if HAS_Z4_MS_PINS WRITE(Z4_MS1_PIN, ms1); #endif break; #endif #if HAS_I_MS_PINS case I_AXIS: WRITE(I_MS1_PIN, ms1); break; #endif #if HAS_J_MS_PINS case J_AXIS: WRITE(J_MS1_PIN, ms1); break; #endif #if HAS_K_MS_PINS case K_AXIS: WRITE(K_MS1_PIN, ms1); break; #endif #if HAS_U_MS_PINS case U_AXIS: WRITE(U_MS1_PIN, ms1); break; #endif #if HAS_V_MS_PINS case V_AXIS: WRITE(V_MS1_PIN, ms1); break; #endif #if HAS_W_MS_PINS case W_AXIS: WRITE(W_MS1_PIN, ms1); break; #endif #if HAS_E0_MS_PINS case E_AXIS: WRITE(E0_MS1_PIN, ms1); break; #endif #if HAS_E1_MS_PINS case (E_AXIS + 1): WRITE(E1_MS1_PIN, ms1); break; #endif #if HAS_E2_MS_PINS case (E_AXIS + 2): WRITE(E2_MS1_PIN, ms1); break; #endif #if HAS_E3_MS_PINS case (E_AXIS + 3): WRITE(E3_MS1_PIN, ms1); break; #endif #if HAS_E4_MS_PINS case (E_AXIS + 4): WRITE(E4_MS1_PIN, ms1); break; #endif #if HAS_E5_MS_PINS case (E_AXIS + 5): WRITE(E5_MS1_PIN, ms1); break; #endif #if HAS_E6_MS_PINS case (E_AXIS + 6): WRITE(E6_MS1_PIN, ms1); break; #endif #if HAS_E7_MS_PINS case (E_AXIS + 7): WRITE(E7_MS1_PIN, ms1); break; #endif } if (ms2 >= 0) switch (driver) { #if HAS_X_MS_PINS || HAS_X2_MS_PINS case X_AXIS: #if HAS_X_MS_PINS WRITE(X_MS2_PIN, ms2); #endif #if HAS_X2_MS_PINS WRITE(X2_MS2_PIN, ms2); #endif break; #endif #if HAS_Y_MS_PINS || HAS_Y2_MS_PINS case Y_AXIS: #if HAS_Y_MS_PINS WRITE(Y_MS2_PIN, ms2); #endif #if HAS_Y2_MS_PINS WRITE(Y2_MS2_PIN, ms2); #endif break; #endif #if HAS_SOME_Z_MS_PINS case Z_AXIS: #if HAS_Z_MS_PINS WRITE(Z_MS2_PIN, ms2); #endif #if HAS_Z2_MS_PINS WRITE(Z2_MS2_PIN, ms2); #endif #if HAS_Z3_MS_PINS WRITE(Z3_MS2_PIN, ms2); #endif #if HAS_Z4_MS_PINS WRITE(Z4_MS2_PIN, ms2); #endif break; #endif #if HAS_I_MS_PINS case I_AXIS: WRITE(I_MS2_PIN, ms2); break; #endif #if HAS_J_MS_PINS case J_AXIS: WRITE(J_MS2_PIN, ms2); break; #endif #if HAS_K_MS_PINS case K_AXIS: WRITE(K_MS2_PIN, ms2); break; #endif #if HAS_U_MS_PINS case U_AXIS: WRITE(U_MS2_PIN, ms2); break; #endif #if HAS_V_MS_PINS case V_AXIS: WRITE(V_MS2_PIN, ms2); break; #endif #if HAS_W_MS_PINS case W_AXIS: WRITE(W_MS2_PIN, ms2); break; #endif #if HAS_E0_MS_PINS case E_AXIS: WRITE(E0_MS2_PIN, ms2); break; #endif #if HAS_E1_MS_PINS case (E_AXIS + 1): WRITE(E1_MS2_PIN, ms2); break; #endif #if HAS_E2_MS_PINS case (E_AXIS + 2): WRITE(E2_MS2_PIN, ms2); break; #endif #if HAS_E3_MS_PINS case (E_AXIS + 3): WRITE(E3_MS2_PIN, ms2); break; #endif #if HAS_E4_MS_PINS case (E_AXIS + 4): WRITE(E4_MS2_PIN, ms2); break; #endif #if HAS_E5_MS_PINS case (E_AXIS + 5): WRITE(E5_MS2_PIN, ms2); break; #endif #if HAS_E6_MS_PINS case (E_AXIS + 6): WRITE(E6_MS2_PIN, ms2); break; #endif #if HAS_E7_MS_PINS case (E_AXIS + 7): WRITE(E7_MS2_PIN, ms2); break; #endif } if (ms3 >= 0) switch (driver) { #if HAS_X_MS_PINS || HAS_X2_MS_PINS case X_AXIS: #if HAS_X_MS_PINS && PIN_EXISTS(X_MS3) WRITE(X_MS3_PIN, ms3); #endif #if HAS_X2_MS_PINS && PIN_EXISTS(X2_MS3) WRITE(X2_MS3_PIN, ms3); #endif break; #endif #if HAS_Y_MS_PINS || HAS_Y2_MS_PINS case Y_AXIS: #if HAS_Y_MS_PINS && PIN_EXISTS(Y_MS3) WRITE(Y_MS3_PIN, ms3); #endif #if HAS_Y2_MS_PINS && PIN_EXISTS(Y2_MS3) WRITE(Y2_MS3_PIN, ms3); #endif break; #endif #if HAS_SOME_Z_MS_PINS case Z_AXIS: #if HAS_Z_MS_PINS && PIN_EXISTS(Z_MS3) WRITE(Z_MS3_PIN, ms3); #endif #if HAS_Z2_MS_PINS && PIN_EXISTS(Z2_MS3) WRITE(Z2_MS3_PIN, ms3); #endif #if HAS_Z3_MS_PINS && PIN_EXISTS(Z3_MS3) WRITE(Z3_MS3_PIN, ms3); #endif #if HAS_Z4_MS_PINS && PIN_EXISTS(Z4_MS3) WRITE(Z4_MS3_PIN, ms3); #endif break; #endif #if HAS_I_MS_PINS && PIN_EXISTS(I_MS3) case I_AXIS: WRITE(I_MS3_PIN, ms3); break; #endif #if HAS_J_MS_PINS && PIN_EXISTS(J_MS3) case J_AXIS: WRITE(J_MS3_PIN, ms3); break; #endif #if HAS_K_MS_PINS && PIN_EXISTS(K_MS3) case K_AXIS: WRITE(K_MS3_PIN, ms3); break; #endif #if HAS_U_MS_PINS && PIN_EXISTS(U_MS3) case U_AXIS: WRITE(U_MS3_PIN, ms3); break; #endif #if HAS_V_MS_PINS && PIN_EXISTS(V_MS3) case V_AXIS: WRITE(V_MS3_PIN, ms3); break; #endif #if HAS_W_MS_PINS && PIN_EXISTS(W_MS3) case W_AXIS: WRITE(W_MS3_PIN, ms3); break; #endif #if HAS_E0_MS_PINS && PIN_EXISTS(E0_MS3) case E_AXIS: WRITE(E0_MS3_PIN, ms3); break; #endif #if HAS_E1_MS_PINS && PIN_EXISTS(E1_MS3) case (E_AXIS + 1): WRITE(E1_MS3_PIN, ms3); break; #endif #if HAS_E2_MS_PINS && PIN_EXISTS(E2_MS3) case (E_AXIS + 2): WRITE(E2_MS3_PIN, ms3); break; #endif #if HAS_E3_MS_PINS && PIN_EXISTS(E3_MS3) case (E_AXIS + 3): WRITE(E3_MS3_PIN, ms3); break; #endif #if HAS_E4_MS_PINS && PIN_EXISTS(E4_MS3) case (E_AXIS + 4): WRITE(E4_MS3_PIN, ms3); break; #endif #if HAS_E5_MS_PINS && PIN_EXISTS(E5_MS3) case (E_AXIS + 5): WRITE(E5_MS3_PIN, ms3); break; #endif #if HAS_E6_MS_PINS && PIN_EXISTS(E6_MS3) case (E_AXIS + 6): WRITE(E6_MS3_PIN, ms3); break; #endif #if HAS_E7_MS_PINS && PIN_EXISTS(E7_MS3) case (E_AXIS + 7): WRITE(E7_MS3_PIN, ms3); break; #endif } } // MS1 MS2 MS3 Stepper Driver Microstepping mode table #ifndef MICROSTEP1 #define MICROSTEP1 LOW,LOW,LOW #endif #if ENABLED(HEROIC_STEPPER_DRIVERS) #ifndef MICROSTEP128 #define MICROSTEP128 LOW,HIGH,LOW #endif #else #ifndef MICROSTEP2 #define MICROSTEP2 HIGH,LOW,LOW #endif #ifndef MICROSTEP4 #define MICROSTEP4 LOW,HIGH,LOW #endif #endif #ifndef MICROSTEP8 #define MICROSTEP8 HIGH,HIGH,LOW #endif #ifndef MICROSTEP16 #define MICROSTEP16 HIGH,HIGH,LOW #endif void Stepper::microstep_mode(const uint8_t driver, const uint8_t stepping_mode) { switch (stepping_mode) { #ifdef MICROSTEP1 case 1: microstep_ms(driver, MICROSTEP1); break; #endif #ifdef MICROSTEP2 case 2: microstep_ms(driver, MICROSTEP2); break; #endif #ifdef MICROSTEP4 case 4: microstep_ms(driver, MICROSTEP4); break; #endif #ifdef MICROSTEP8 case 8: microstep_ms(driver, MICROSTEP8); break; #endif #ifdef MICROSTEP16 case 16: microstep_ms(driver, MICROSTEP16); break; #endif #ifdef MICROSTEP32 case 32: microstep_ms(driver, MICROSTEP32); break; #endif #ifdef MICROSTEP64 case 64: microstep_ms(driver, MICROSTEP64); break; #endif #ifdef MICROSTEP128 case 128: microstep_ms(driver, MICROSTEP128); break; #endif default: SERIAL_ERROR_MSG("Microsteps unavailable"); break; } } void Stepper::microstep_readings() { #define PIN_CHAR(P) SERIAL_CHAR('0' + READ(P##_PIN)) #define MS_LINE(A) do{ SERIAL_ECHOPGM(" " STRINGIFY(A) ":"); PIN_CHAR(A##_MS1); PIN_CHAR(A##_MS2); }while(0) SERIAL_ECHOPGM("MS1|2|3 Pins"); #if HAS_X_MS_PINS MS_LINE(X); #if PIN_EXISTS(X_MS3) PIN_CHAR(X_MS3); #endif #endif #if HAS_Y_MS_PINS MS_LINE(Y); #if PIN_EXISTS(Y_MS3) PIN_CHAR(Y_MS3); #endif #endif #if HAS_Z_MS_PINS MS_LINE(Z); #if PIN_EXISTS(Z_MS3) PIN_CHAR(Z_MS3); #endif #endif #if HAS_I_MS_PINS MS_LINE(I); #if PIN_EXISTS(I_MS3) PIN_CHAR(I_MS3); #endif #endif #if HAS_J_MS_PINS MS_LINE(J); #if PIN_EXISTS(J_MS3) PIN_CHAR(J_MS3); #endif #endif #if HAS_K_MS_PINS MS_LINE(K); #if PIN_EXISTS(K_MS3) PIN_CHAR(K_MS3); #endif #endif #if HAS_U_MS_PINS MS_LINE(U); #if PIN_EXISTS(U_MS3) PIN_CHAR(U_MS3); #endif #endif #if HAS_V_MS_PINS MS_LINE(V); #if PIN_EXISTS(V_MS3) PIN_CHAR(V_MS3); #endif #endif #if HAS_W_MS_PINS MS_LINE(W); #if PIN_EXISTS(W_MS3) PIN_CHAR(W_MS3); #endif #endif #if HAS_E0_MS_PINS MS_LINE(E0); #if PIN_EXISTS(E0_MS3) PIN_CHAR(E0_MS3); #endif #endif #if HAS_E1_MS_PINS MS_LINE(E1); #if PIN_EXISTS(E1_MS3) PIN_CHAR(E1_MS3); #endif #endif #if HAS_E2_MS_PINS MS_LINE(E2); #if PIN_EXISTS(E2_MS3) PIN_CHAR(E2_MS3); #endif #endif #if HAS_E3_MS_PINS MS_LINE(E3); #if PIN_EXISTS(E3_MS3) PIN_CHAR(E3_MS3); #endif #endif #if HAS_E4_MS_PINS MS_LINE(E4); #if PIN_EXISTS(E4_MS3) PIN_CHAR(E4_MS3); #endif #endif #if HAS_E5_MS_PINS MS_LINE(E5); #if PIN_EXISTS(E5_MS3) PIN_CHAR(E5_MS3); #endif #endif #if HAS_E6_MS_PINS MS_LINE(E6); #if PIN_EXISTS(E6_MS3) PIN_CHAR(E6_MS3); #endif #endif #if HAS_E7_MS_PINS MS_LINE(E7); #if PIN_EXISTS(E7_MS3) PIN_CHAR(E7_MS3); #endif #endif SERIAL_EOL(); } #endif // HAS_MICROSTEPS
2301_81045437/Marlin
Marlin/src/module/stepper.cpp
C++
agpl-3.0
168,088
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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.h - stepper motor driver: executes motion plans of planner.c using the stepper motors * Derived from Grbl * * Copyright (c) 2009-2011 Simen Svale Skogsrud * * Grbl is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grbl is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grbl. If not, see <https://www.gnu.org/licenses/>. */ #include "../inc/MarlinConfig.h" #include "planner.h" #include "stepper/indirection.h" #include "stepper/cycles.h" #ifdef __AVR__ #include "stepper/speed_lookuptable.h" #endif #if ENABLED(FT_MOTION) #include "ft_types.h" #endif // TODO: Review and ensure proper handling for special E axes with commands like M17/M18, stepper timeout, etc. #if ENABLED(MIXING_EXTRUDER) #define E_STATES EXTRUDERS // All steppers are set together for each mixer. (Currently limited to 1.) #elif HAS_SWITCHING_EXTRUDER #define E_STATES E_STEPPERS // One stepper for every two EXTRUDERS. The last extruder can be non-switching. #elif HAS_PRUSA_MMU2 #define E_STATES E_STEPPERS // One E stepper shared with all EXTRUDERS, so setting any only sets one. #else #define E_STATES E_STEPPERS // One stepper for each extruder, so each can be disabled individually. #endif // Number of axes that could be enabled/disabled. Dual/multiple steppers are combined. #define ENABLE_COUNT (NUM_AXES + E_STATES) typedef bits_t(ENABLE_COUNT) ena_mask_t; // Axis flags type, for enabled state or other simple state typedef struct { union { ena_mask_t bits; struct { #if NUM_AXES bool NUM_AXIS_LIST(X:1, Y:1, Z:1, I:1, J:1, K:1, U:1, V:1, W:1); #endif #if E_STATES bool LIST_N(E_STATES, E0:1, E1:1, E2:1, E3:1, E4:1, E5:1, E6:1, E7:1); #endif }; }; } stepper_flags_t; typedef bits_t(NUM_AXES + E_STATES) e_axis_bits_t; constexpr e_axis_bits_t e_axis_mask = (_BV(E_STATES) - 1) << NUM_AXES; // All the stepper enable pins constexpr pin_t ena_pins[] = { NUM_AXIS_LIST_(X_ENABLE_PIN, Y_ENABLE_PIN, Z_ENABLE_PIN, I_ENABLE_PIN, J_ENABLE_PIN, K_ENABLE_PIN, U_ENABLE_PIN, V_ENABLE_PIN, W_ENABLE_PIN) LIST_N(E_STEPPERS, E0_ENABLE_PIN, E1_ENABLE_PIN, E2_ENABLE_PIN, E3_ENABLE_PIN, E4_ENABLE_PIN, E5_ENABLE_PIN, E6_ENABLE_PIN, E7_ENABLE_PIN) }; // Index of the axis or extruder element in a combined array constexpr uint8_t index_of_axis(const AxisEnum axis E_OPTARG(const uint8_t eindex=0)) { return uint8_t(axis) + (E_TERN0(axis < NUM_AXES ? 0 : eindex)); } //#define __IAX_N(N,V...) _IAX_##N(V) //#define _IAX_N(N,V...) __IAX_N(N,V) //#define _IAX_1(A) index_of_axis(A) //#define _IAX_2(A,B) index_of_axis(A E_OPTARG(B)) //#define INDEX_OF_AXIS(V...) _IAX_N(TWO_ARGS(V),V) #define INDEX_OF_AXIS(A,V...) index_of_axis(A E_OPTARG(V+0)) // Bit mask for a matching enable pin, or 0 constexpr ena_mask_t ena_same(const uint8_t a, const uint8_t b) { return ena_pins[a] == ena_pins[b] ? _BV(b) : 0; } // Recursively get the enable overlaps mask for a given linear axis or extruder constexpr ena_mask_t ena_overlap(const uint8_t a=0, const uint8_t b=0) { return b >= ENABLE_COUNT ? 0 : (a == b ? 0 : ena_same(a, b)) | ena_overlap(a, b + 1); } // Recursively get whether there's any overlap at all constexpr bool any_enable_overlap(const uint8_t a=0) { return a >= ENABLE_COUNT ? false : ena_overlap(a) || any_enable_overlap(a + 1); } // Array of axes that overlap with each // TODO: Consider cases where >=2 steppers are used by a linear axis or extruder // (e.g., CoreXY, Dual XYZ, or E with multiple steppers, etc.). constexpr ena_mask_t enable_overlap[] = { #define _OVERLAP(N) ena_overlap(INDEX_OF_AXIS(AxisEnum(N))), REPEAT(NUM_AXES, _OVERLAP) #if HAS_EXTRUDERS #define _E_OVERLAP(N) ena_overlap(INDEX_OF_AXIS(E_AXIS, N)), REPEAT(E_STEPPERS, _E_OVERLAP) #endif }; //static_assert(!any_enable_overlap(), "There is some overlap."); #if HAS_ZV_SHAPING #ifdef SHAPING_MAX_STEPRATE constexpr float max_step_rate = SHAPING_MAX_STEPRATE; #else #define ISALIM(I, ARR) _MIN(I, COUNT(ARR) - 1) constexpr float _ISDASU[] = DEFAULT_AXIS_STEPS_PER_UNIT; constexpr feedRate_t _ISDMF[] = DEFAULT_MAX_FEEDRATE; constexpr float max_shaped_rate = TERN0(INPUT_SHAPING_X, _ISDMF[X_AXIS] * _ISDASU[X_AXIS]) + TERN0(INPUT_SHAPING_Y, _ISDMF[Y_AXIS] * _ISDASU[Y_AXIS]); #if defined(__AVR__) || !defined(ADAPTIVE_STEP_SMOOTHING) // MIN_STEP_ISR_FREQUENCY is known at compile time on AVRs and any reduction in SRAM is welcome template<unsigned int INDEX=DISTINCT_AXES> constexpr float max_isr_rate() { return _MAX(_ISDMF[ISALIM(INDEX - 1, _ISDMF)] * _ISDASU[ISALIM(INDEX - 1, _ISDASU)], max_isr_rate<INDEX - 1>()); } template<> constexpr float max_isr_rate<0>() { return TERN0(ADAPTIVE_STEP_SMOOTHING, MIN_STEP_ISR_FREQUENCY); } constexpr float max_step_rate = _MIN(max_isr_rate(), max_shaped_rate); #else constexpr float max_step_rate = max_shaped_rate; #endif #endif #ifndef SHAPING_MIN_FREQ #define SHAPING_MIN_FREQ _MIN(__FLT_MAX__ OPTARG(INPUT_SHAPING_X, SHAPING_FREQ_X) OPTARG(INPUT_SHAPING_Y, SHAPING_FREQ_Y)) #endif constexpr float shaping_min_freq = SHAPING_MIN_FREQ; constexpr uint16_t shaping_echoes = FLOOR(max_step_rate / shaping_min_freq / 2) + 3; typedef hal_timer_t shaping_time_t; enum shaping_echo_t { ECHO_NONE = 0, ECHO_FWD = 1, ECHO_BWD = 2 }; struct shaping_echo_axis_t { TERN_(INPUT_SHAPING_X, shaping_echo_t x:2); TERN_(INPUT_SHAPING_Y, shaping_echo_t y:2); }; class ShapingQueue { private: static shaping_time_t now; static shaping_time_t times[shaping_echoes]; static shaping_echo_axis_t echo_axes[shaping_echoes]; static uint16_t tail; #if ENABLED(INPUT_SHAPING_X) static shaping_time_t delay_x; // = shaping_time_t(-1) to disable queueing static shaping_time_t peek_x_val; static uint16_t head_x; static uint16_t _free_count_x; #endif #if ENABLED(INPUT_SHAPING_Y) static shaping_time_t delay_y; // = shaping_time_t(-1) to disable queueing static shaping_time_t peek_y_val; static uint16_t head_y; static uint16_t _free_count_y; #endif public: static void decrement_delays(const shaping_time_t interval) { now += interval; TERN_(INPUT_SHAPING_X, if (peek_x_val != shaping_time_t(-1)) peek_x_val -= interval); TERN_(INPUT_SHAPING_Y, if (peek_y_val != shaping_time_t(-1)) peek_y_val -= interval); } static void set_delay(const AxisEnum axis, const shaping_time_t delay) { TERN_(INPUT_SHAPING_X, if (axis == X_AXIS) delay_x = delay); TERN_(INPUT_SHAPING_Y, if (axis == Y_AXIS) delay_y = delay); } static void enqueue(const bool x_step, const bool x_forward, const bool y_step, const bool y_forward) { #if ENABLED(INPUT_SHAPING_X) if (x_step) { if (head_x == tail) peek_x_val = delay_x; echo_axes[tail].x = x_forward ? ECHO_FWD : ECHO_BWD; _free_count_x--; } else { echo_axes[tail].x = ECHO_NONE; if (head_x != tail) _free_count_x--; else if (++head_x == shaping_echoes) head_x = 0; } #endif #if ENABLED(INPUT_SHAPING_Y) if (y_step) { if (head_y == tail) peek_y_val = delay_y; echo_axes[tail].y = y_forward ? ECHO_FWD : ECHO_BWD; _free_count_y--; } else { echo_axes[tail].y = ECHO_NONE; if (head_y != tail) _free_count_y--; else if (++head_y == shaping_echoes) head_y = 0; } #endif times[tail] = now; if (++tail == shaping_echoes) tail = 0; } #if ENABLED(INPUT_SHAPING_X) static shaping_time_t peek_x() { return peek_x_val; } static bool dequeue_x() { bool forward = echo_axes[head_x].x == ECHO_FWD; do { _free_count_x++; if (++head_x == shaping_echoes) head_x = 0; } while (head_x != tail && echo_axes[head_x].x == ECHO_NONE); peek_x_val = head_x == tail ? shaping_time_t(-1) : times[head_x] + delay_x - now; return forward; } static bool empty_x() { return head_x == tail; } static uint16_t free_count_x() { return _free_count_x; } #endif #if ENABLED(INPUT_SHAPING_Y) static shaping_time_t peek_y() { return peek_y_val; } static bool dequeue_y() { bool forward = echo_axes[head_y].y == ECHO_FWD; do { _free_count_y++; if (++head_y == shaping_echoes) head_y = 0; } while (head_y != tail && echo_axes[head_y].y == ECHO_NONE); peek_y_val = head_y == tail ? shaping_time_t(-1) : times[head_y] + delay_y - now; return forward; } static bool empty_y() { return head_y == tail; } static uint16_t free_count_y() { return _free_count_y; } #endif static void purge() { const auto st = shaping_time_t(-1); #if ENABLED(INPUT_SHAPING_X) head_x = tail; _free_count_x = shaping_echoes - 1; peek_x_val = st; #endif #if ENABLED(INPUT_SHAPING_Y) head_y = tail; _free_count_y = shaping_echoes - 1; peek_y_val = st; #endif } }; struct ShapeParams { float frequency; float zeta; bool enabled : 1; bool forward : 1; int16_t delta_error = 0; // delta_error for seconday bresenham mod 128 uint8_t factor1; uint8_t factor2; int32_t last_block_end_pos = 0; }; #endif // HAS_ZV_SHAPING #if ENABLED(NONLINEAR_EXTRUSION) typedef struct { float A, B, C; void reset() { A = B = 0.0f; C = 1.0f; } } ne_coeff_t; typedef struct { int32_t A, B, C; } ne_fix_t; #endif // // Stepper class definition // class Stepper { friend class Max7219; friend class FTMotion; friend void stepperTask(void *); public: #if ANY(HAS_EXTRA_ENDSTOPS, Z_STEPPER_AUTO_ALIGN) static bool separate_multi_axis; #endif #if HAS_MOTOR_CURRENT_SPI || HAS_MOTOR_CURRENT_PWM #if HAS_MOTOR_CURRENT_PWM #ifndef PWM_MOTOR_CURRENT #define PWM_MOTOR_CURRENT DEFAULT_PWM_MOTOR_CURRENT #endif #ifndef MOTOR_CURRENT_PWM_FREQUENCY #define MOTOR_CURRENT_PWM_FREQUENCY 31400 #endif #define MOTOR_CURRENT_COUNT 3 #elif HAS_MOTOR_CURRENT_SPI static constexpr uint32_t digipot_count[] = DIGIPOT_MOTOR_CURRENT; #define MOTOR_CURRENT_COUNT COUNT(Stepper::digipot_count) #endif static bool initialized; static uint32_t motor_current_setting[MOTOR_CURRENT_COUNT]; // Initialized by settings.load() #endif // Last-moved extruder, as set when the last movement was fetched from planner #if HAS_MULTI_EXTRUDER static uint8_t last_moved_extruder; #else static constexpr uint8_t last_moved_extruder = 0; #endif #if ENABLED(FREEZE_FEATURE) static bool frozen; // Set this flag to instantly freeze motion #endif #if ENABLED(NONLINEAR_EXTRUSION) static ne_coeff_t ne; #endif #if ENABLED(ADAPTIVE_STEP_SMOOTHING_TOGGLE) static bool adaptive_step_smoothing_enabled; #else static constexpr bool adaptive_step_smoothing_enabled = true; #endif private: static block_t* current_block; // A pointer to the block currently being traced static AxisBits last_direction_bits, // The next stepping-bits to be output axis_did_move; // Last Movement in the given direction is not null, as computed when the last movement was fetched from planner static bool abort_current_block; // Signals to the stepper that current block should be aborted #if ENABLED(X_DUAL_ENDSTOPS) static bool locked_X_motor, locked_X2_motor; #endif #if ENABLED(Y_DUAL_ENDSTOPS) static bool locked_Y_motor, locked_Y2_motor; #endif #if ANY(Z_MULTI_ENDSTOPS, Z_STEPPER_AUTO_ALIGN) static bool locked_Z_motor, locked_Z2_motor #if NUM_Z_STEPPERS >= 3 , locked_Z3_motor #if NUM_Z_STEPPERS >= 4 , locked_Z4_motor #endif #endif ; #endif static uint32_t acceleration_time, deceleration_time; // time measured in Stepper Timer ticks #if MULTISTEPPING_LIMIT == 1 static constexpr uint8_t steps_per_isr = 1; // Count of steps to perform per Stepper ISR call #else static uint8_t steps_per_isr; #endif #if DISABLED(OLD_ADAPTIVE_MULTISTEPPING) static hal_timer_t time_spent_in_isr, time_spent_out_isr; #endif #if ENABLED(ADAPTIVE_STEP_SMOOTHING) static uint8_t oversampling_factor; // Oversampling factor (log2(multiplier)) to increase temporal resolution of axis #else static constexpr uint8_t oversampling_factor = 0; // Without smoothing apply no shift #endif // Delta error variables for the Bresenham line tracer static xyze_long_t delta_error; static xyze_long_t advance_dividend; static uint32_t advance_divisor, step_events_completed, // The number of step events executed in the current block accelerate_until, // The point from where we need to stop acceleration decelerate_after, // The point from where we need to start decelerating step_event_count; // The total event count for the current block #if ANY(HAS_MULTI_EXTRUDER, MIXING_EXTRUDER) static uint8_t stepper_extruder; #else static constexpr uint8_t stepper_extruder = 0; #endif #if ENABLED(S_CURVE_ACCELERATION) static int32_t bezier_A, // A coefficient in Bézier speed curve bezier_B, // B coefficient in Bézier speed curve bezier_C; // C coefficient in Bézier speed curve static uint32_t bezier_F, // F coefficient in Bézier speed curve bezier_AV; // AV coefficient in Bézier speed curve #ifdef __AVR__ static bool A_negative; // If A coefficient was negative #endif static bool bezier_2nd_half; // If Bézier curve has been initialized or not #endif #if HAS_ZV_SHAPING #if ENABLED(INPUT_SHAPING_X) static ShapeParams shaping_x; #endif #if ENABLED(INPUT_SHAPING_Y) static ShapeParams shaping_y; #endif #endif #if ENABLED(LIN_ADVANCE) static constexpr hal_timer_t LA_ADV_NEVER = HAL_TIMER_TYPE_MAX; static hal_timer_t nextAdvanceISR, la_interval; // Interval between ISR calls for LA static int32_t la_delta_error, // Analogue of delta_error.e for E steps in LA ISR la_dividend, // Analogue of advance_dividend.e for E steps in LA ISR la_advance_steps; // Count of steps added to increase nozzle pressure static bool la_active; // Whether linear advance is used on the present segment. #endif #if ENABLED(NONLINEAR_EXTRUSION) static int32_t ne_edividend; static uint32_t ne_scale; static ne_fix_t ne_fix; #endif #if ENABLED(BABYSTEPPING) static constexpr hal_timer_t BABYSTEP_NEVER = HAL_TIMER_TYPE_MAX; static hal_timer_t nextBabystepISR; #endif #if ENABLED(DIRECT_STEPPING) static page_step_state_t page_step_state; #endif static hal_timer_t ticks_nominal; #if DISABLED(S_CURVE_ACCELERATION) static uint32_t acc_step_rate; // needed for deceleration start point #endif // Exact steps at which an endstop was triggered static xyz_long_t endstops_trigsteps; // Positions of stepper motors, in step units static xyze_long_t count_position; // Current stepper motor directions (+1 or -1) static xyze_int8_t count_direction; public: // Initialize stepper hardware static void init(); // Interrupt Service Routine and phases // The stepper subsystem goes to sleep when it runs out of things to execute. // Call this to notify the subsystem that it is time to go to work. static void wake_up() { ENABLE_STEPPER_DRIVER_INTERRUPT(); } static bool is_awake() { return STEPPER_ISR_ENABLED(); } static bool suspend() { const bool awake = is_awake(); if (awake) DISABLE_STEPPER_DRIVER_INTERRUPT(); return awake; } // The ISR scheduler static void isr(); // The stepper pulse ISR phase static void pulse_phase_isr(); // The stepper block processing ISR phase static hal_timer_t block_phase_isr(); #if HAS_ZV_SHAPING static void shaping_isr(); #endif #if ENABLED(LIN_ADVANCE) // The Linear advance ISR phase static void advance_isr(); #endif #if ENABLED(BABYSTEPPING) // The Babystepping ISR phase static hal_timer_t babystepping_isr(); FORCE_INLINE static void initiateBabystepping() { if (nextBabystepISR == BABYSTEP_NEVER) { nextBabystepISR = 0; wake_up(); } } #endif // Check if the given block is busy or not - Must not be called from ISR contexts static bool is_block_busy(const block_t * const block); #if HAS_ZV_SHAPING // Check whether the stepper is processing any input shaping echoes static bool input_shaping_busy() { const bool was_on = hal.isr_state(); hal.isr_off(); const bool result = TERN0(INPUT_SHAPING_X, !ShapingQueue::empty_x()) || TERN0(INPUT_SHAPING_Y, !ShapingQueue::empty_y()); if (was_on) hal.isr_on(); return result; } #endif // Get the position of a stepper, in steps static int32_t position(const AxisEnum axis); // Set the current position in steps static void set_position(const xyze_long_t &spos); static void set_axis_position(const AxisEnum a, const int32_t &v); // Report the positions of the steppers, in steps static void report_a_position(const xyz_long_t &pos); static void report_positions(); // Discard current block and free any resources FORCE_INLINE static void discard_current_block() { #if ENABLED(DIRECT_STEPPING) if (current_block->is_page()) page_manager.free_page(current_block->page_idx); #endif current_block = nullptr; axis_did_move.reset(); planner.release_current_block(); TERN_(LIN_ADVANCE, la_interval = nextAdvanceISR = LA_ADV_NEVER); } // Quickly stop all steppers FORCE_INLINE static void quick_stop() { abort_current_block = true; } // The direction of a single motor. A true result indicates forward or positive motion. FORCE_INLINE static bool motor_direction(const AxisEnum axis) { return last_direction_bits[axis]; } // The last movement direction was not null on the specified axis. Note that motor direction is not necessarily the same. FORCE_INLINE static bool axis_is_moving(const AxisEnum axis) { return axis_did_move[axis]; } // Handle a triggered endstop static void endstop_triggered(const AxisEnum axis); // Triggered position of an axis in steps static int32_t triggered_position(const AxisEnum axis); #if HAS_MOTOR_CURRENT_SPI || HAS_MOTOR_CURRENT_PWM static void set_digipot_value_spi(const int16_t address, const int16_t value); static void set_digipot_current(const uint8_t driver, const int16_t current); #endif #if HAS_MICROSTEPS static void microstep_ms(const uint8_t driver, const int8_t ms1, const int8_t ms2, const int8_t ms3); static void microstep_mode(const uint8_t driver, const uint8_t stepping); static void microstep_readings(); #endif #if ANY(HAS_EXTRA_ENDSTOPS, Z_STEPPER_AUTO_ALIGN) FORCE_INLINE static void set_separate_multi_axis(const bool state) { separate_multi_axis = state; } #endif #if ENABLED(X_DUAL_ENDSTOPS) FORCE_INLINE static void set_x_lock(const bool state) { locked_X_motor = state; } FORCE_INLINE static void set_x2_lock(const bool state) { locked_X2_motor = state; } #endif #if ENABLED(Y_DUAL_ENDSTOPS) FORCE_INLINE static void set_y_lock(const bool state) { locked_Y_motor = state; } FORCE_INLINE static void set_y2_lock(const bool state) { locked_Y2_motor = state; } #endif #if ANY(Z_MULTI_ENDSTOPS, Z_STEPPER_AUTO_ALIGN) FORCE_INLINE static void set_z1_lock(const bool state) { locked_Z_motor = state; } FORCE_INLINE static void set_z2_lock(const bool state) { locked_Z2_motor = state; } #if NUM_Z_STEPPERS >= 3 FORCE_INLINE static void set_z3_lock(const bool state) { locked_Z3_motor = state; } #if NUM_Z_STEPPERS >= 4 FORCE_INLINE static void set_z4_lock(const bool state) { locked_Z4_motor = state; } #endif #endif static void set_all_z_lock(const bool lock, const int8_t except=-1) { set_z1_lock(lock ^ (except == 0)); set_z2_lock(lock ^ (except == 1)); #if NUM_Z_STEPPERS >= 3 set_z3_lock(lock ^ (except == 2)); #if NUM_Z_STEPPERS >= 4 set_z4_lock(lock ^ (except == 3)); #endif #endif } #endif #if ENABLED(BABYSTEPPING) static void do_babystep(const AxisEnum axis, const bool direction); // perform a short step with a single stepper motor, outside of any convention #endif #if HAS_MOTOR_CURRENT_PWM static void refresh_motor_power(); #endif static stepper_flags_t axis_enabled; // Axis stepper(s) ENABLED states static bool axis_is_enabled(const AxisEnum axis E_OPTARG(const uint8_t eindex=0)) { return TEST(axis_enabled.bits, INDEX_OF_AXIS(axis, eindex)); } static void mark_axis_enabled(const AxisEnum axis E_OPTARG(const uint8_t eindex=0)) { SBI(axis_enabled.bits, INDEX_OF_AXIS(axis, eindex)); } static void mark_axis_disabled(const AxisEnum axis E_OPTARG(const uint8_t eindex=0)) { CBI(axis_enabled.bits, INDEX_OF_AXIS(axis, eindex)); } static bool can_axis_disable(const AxisEnum axis E_OPTARG(const uint8_t eindex=0)) { return !any_enable_overlap() || !(axis_enabled.bits & enable_overlap[INDEX_OF_AXIS(axis, eindex)]); } static void enable_axis(const AxisEnum axis); static bool disable_axis(const AxisEnum axis); #if HAS_EXTRUDERS static void enable_extruder(E_TERN_(const uint8_t eindex=0)); static bool disable_extruder(E_TERN_(const uint8_t eindex=0)); static void enable_e_steppers(); static void disable_e_steppers(); #else static void enable_extruder() {} static bool disable_extruder() { return true; } static void enable_e_steppers() {} static void disable_e_steppers() {} #endif #define ENABLE_EXTRUDER(N) enable_extruder(E_TERN_(N)) #define DISABLE_EXTRUDER(N) disable_extruder(E_TERN_(N)) #define AXIS_IS_ENABLED(N,V...) axis_is_enabled(N E_OPTARG(#V)) static void enable_all_steppers(); static void disable_all_steppers(); // Update direction states for all steppers static void apply_directions(); // Set direction bits and update all stepper DIR states static void set_directions(const AxisBits bits) { last_direction_bits = bits; apply_directions(); } #if ENABLED(FT_MOTION) // Manage the planner static void ftMotion_blockQueueUpdate(); // Set current position in steps when reset flag is set in M493 and planner already synchronized static void ftMotion_syncPosition(); #endif #if HAS_ZV_SHAPING static void set_shaping_damping_ratio(const AxisEnum axis, const_float_t zeta); static float get_shaping_damping_ratio(const AxisEnum axis); static void set_shaping_frequency(const AxisEnum axis, const_float_t freq); static float get_shaping_frequency(const AxisEnum axis); #endif private: // Set the current position in steps static void _set_position(const abce_long_t &spos); // Calculate the timing interval for the given step rate static hal_timer_t calc_timer_interval(uint32_t step_rate); // Calculate timing interval and steps-per-ISR for the given step rate static hal_timer_t calc_multistep_timer_interval(uint32_t step_rate); // Evaluate axis motions and set bits in axis_did_move static void set_axis_moved_for_current_block(); #if ENABLED(NONLINEAR_EXTRUSION) static void calc_nonlinear_e(uint32_t step_rate); #endif #if ENABLED(S_CURVE_ACCELERATION) static void _calc_bezier_curve_coeffs(const int32_t v0, const int32_t v1, const uint32_t av); static int32_t _eval_bezier_curve(const uint32_t curr_step); #endif #if HAS_MOTOR_CURRENT_SPI || HAS_MOTOR_CURRENT_PWM static void digipot_init(); #endif #if HAS_MICROSTEPS static void microstep_init(); #endif #if ENABLED(FT_MOTION) static void ftMotion_stepper(); #endif }; extern Stepper stepper;
2301_81045437/Marlin
Marlin/src/module/stepper.h
C++
agpl-3.0
26,716
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * temperature.cpp - temperature control */ // Useful when debugging thermocouples //#define IGNORE_THERMOCOUPLE_ERRORS #include "../MarlinCore.h" #include "../HAL/shared/Delay.h" #include "../lcd/marlinui.h" #include "../gcode/gcode.h" #include "temperature.h" #include "endstops.h" #include "planner.h" #include "printcounter.h" #if ANY(HAS_COOLER, LASER_COOLANT_FLOW_METER) #include "../feature/cooler.h" #include "../feature/spindle_laser.h" #endif #if ENABLED(USE_CONTROLLER_FAN) #include "../feature/controllerfan.h" #endif #if ENABLED(EMERGENCY_PARSER) #include "motion.h" #endif #if ENABLED(DWIN_CREALITY_LCD) #include "../lcd/e3v2/creality/dwin.h" #endif #if ENABLED(EXTENSIBLE_UI) #include "../lcd/extui/ui_api.h" #endif #if ENABLED(HOST_PROMPT_SUPPORT) #include "../feature/host_actions.h" #endif #if ENABLED(NOZZLE_PARK_FEATURE) #include "../libs/nozzle.h" #endif #if LASER_SAFETY_TIMEOUT_MS > 0 #include "../feature/spindle_laser.h" #endif // MAX TC related macros #define TEMP_SENSOR_IS_MAX(n, M) (ENABLED(TEMP_SENSOR_##n##_IS_MAX##M) || (ENABLED(TEMP_SENSOR_REDUNDANT_IS_MAX##M) && REDUNDANT_TEMP_MATCH(SOURCE, E##n))) // LIB_MAX6675 can be added to the build_flags in platformio.ini to use a user-defined library // If LIB_MAX6675 is not on the build_flags then raw SPI reads will be used. #if HAS_MAX6675 && USE_LIB_MAX6675 #include <max6675.h> #define HAS_MAX6675_LIBRARY 1 #endif // LIB_MAX31855 can be added to the build_flags in platformio.ini to use a user-defined library. // If LIB_MAX31855 is not on the build_flags then raw SPI reads will be used. #if HAS_MAX31855 && USE_ADAFRUIT_MAX31855 #include <Adafruit_MAX31855.h> #define HAS_MAX31855_LIBRARY 1 typedef Adafruit_MAX31855 MAX31855; #endif #if HAS_MAX31865 #if USE_ADAFRUIT_MAX31865 #include <Adafruit_MAX31865.h> typedef Adafruit_MAX31865 MAX31865; #else #include "../libs/MAX31865.h" #endif #endif #if HAS_MAX6675_LIBRARY || HAS_MAX31855_LIBRARY || HAS_MAX31865 #define HAS_MAXTC_LIBRARIES 1 #endif // If we have a MAX TC with SCK and MISO pins defined, it's either on a separate/dedicated Hardware // SPI bus, or some pins for Software SPI. Alternate Hardware SPI buses are not supported yet, so // your SPI options are: // // 1. Only CS pin(s) defined: Hardware SPI on the default bus (usually the SD card SPI). // 2. CS, MISO, and SCK pins defined: Software SPI on a separate bus, as defined by MISO, SCK. // 3. CS, MISO, and SCK pins w/ FORCE_HW_SPI: Hardware SPI on the default bus, ignoring MISO, SCK. // #if TEMP_SENSOR_IS_ANY_MAX_TC(0) && TEMP_SENSOR_0_HAS_SPI_PINS && DISABLED(TEMP_SENSOR_FORCE_HW_SPI) #define TEMP_SENSOR_0_USES_SW_SPI 1 #endif #if TEMP_SENSOR_IS_ANY_MAX_TC(1) && TEMP_SENSOR_1_HAS_SPI_PINS && DISABLED(TEMP_SENSOR_FORCE_HW_SPI) #define TEMP_SENSOR_1_USES_SW_SPI 1 #endif #if TEMP_SENSOR_IS_ANY_MAX_TC(2) && TEMP_SENSOR_2_HAS_SPI_PINS && DISABLED(TEMP_SENSOR_FORCE_HW_SPI) #define TEMP_SENSOR_2_USES_SW_SPI 1 #endif #if TEMP_SENSOR_IS_ANY_MAX_TC(BED) && TEMP_SENSOR_0_HAS_SPI_PINS && DISABLED(TEMP_SENSOR_FORCE_HW_SPI) #define TEMP_SENSOR_BED_USES_SW_SPI 1 #endif #if (TEMP_SENSOR_0_USES_SW_SPI || TEMP_SENSOR_1_USES_SW_SPI || TEMP_SENSOR_2_USES_SW_SPI) && !HAS_MAXTC_LIBRARIES #include "../libs/private_spi.h" #define HAS_MAXTC_SW_SPI 1 // Define pins for SPI-based sensors #if TEMP_SENSOR_0_USES_SW_SPI #define SW_SPI_SCK_PIN TEMP_0_SCK_PIN #define SW_SPI_MISO_PIN TEMP_0_MISO_PIN #if PIN_EXISTS(TEMP_0_MOSI) #define SW_SPI_MOSI_PIN TEMP_0_MOSI_PIN #endif #elif TEMP_SENSOR_1_USES_SW_SPI #define SW_SPI_SCK_PIN TEMP_1_SCK_PIN #define SW_SPI_MISO_PIN TEMP_1_MISO_PIN #if PIN_EXISTS(TEMP_1_MOSI) #define SW_SPI_MOSI_PIN TEMP_1_MOSI_PIN #endif #elif TEMP_SENSOR_2_USES_SW_SPI #define SW_SPI_SCK_PIN TEMP_2_SCK_PIN #define SW_SPI_MISO_PIN TEMP_2_MISO_PIN #if PIN_EXISTS(TEMP_2_MOSI) #define SW_SPI_MOSI_PIN TEMP_2_MOSI_PIN #endif #endif #ifndef SW_SPI_MOSI_PIN #define SW_SPI_MOSI_PIN SD_MOSI_PIN #endif #endif #if ENABLED(MPCTEMP) #include <math.h> #include "probe.h" #endif #if ANY(MPCTEMP, PID_EXTRUSION_SCALING) #include "stepper.h" #endif #if ENABLED(FILAMENT_WIDTH_SENSOR) #include "../feature/filwidth.h" #endif #if HAS_POWER_MONITOR #include "../feature/power_monitor.h" #endif #if ENABLED(EMERGENCY_PARSER) #include "../feature/e_parser.h" #endif #if ENABLED(PRINTER_EVENT_LEDS) #include "../feature/leds/printer_event_leds.h" #endif #if ENABLED(JOYSTICK) #include "../feature/joystick.h" #endif #if HAS_BEEPER #include "../libs/buzzer.h" #endif #if HAS_SERVOS #include "servo.h" #endif #if ANY(TEMP_SENSOR_0_IS_THERMISTOR, TEMP_SENSOR_1_IS_THERMISTOR, TEMP_SENSOR_2_IS_THERMISTOR, TEMP_SENSOR_3_IS_THERMISTOR, \ TEMP_SENSOR_4_IS_THERMISTOR, TEMP_SENSOR_5_IS_THERMISTOR, TEMP_SENSOR_6_IS_THERMISTOR, TEMP_SENSOR_7_IS_THERMISTOR ) #define HAS_HOTEND_THERMISTOR 1 #endif #if HAS_HOTEND_THERMISTOR #define NEXT_TEMPTABLE(N) ,TEMPTABLE_##N #define NEXT_TEMPTABLE_LEN(N) ,TEMPTABLE_##N##_LEN static const temp_entry_t* heater_ttbl_map[HOTENDS] = ARRAY_BY_HOTENDS(TEMPTABLE_0 REPEAT_S(1, HOTENDS, NEXT_TEMPTABLE)); static constexpr uint8_t heater_ttbllen_map[HOTENDS] = ARRAY_BY_HOTENDS(TEMPTABLE_0_LEN REPEAT_S(1, HOTENDS, NEXT_TEMPTABLE_LEN)); #endif Temperature thermalManager; PGMSTR(str_t_thermal_runaway, STR_T_THERMAL_RUNAWAY); PGMSTR(str_t_heating_failed, STR_T_HEATING_FAILED); // // Initialize MAX TC objects/SPI // #if HAS_MAX_TC #if HAS_MAXTC_SW_SPI // Initialize SoftSPI for non-lib Software SPI; Libraries take care of it themselves. template<uint8_t MisoPin, uint8_t MosiPin, uint8_t SckPin> SoftSPI<MisoPin, MosiPin, SckPin> SPIclass<MisoPin, MosiPin, SckPin>::softSPI; SPIclass<SW_SPI_MISO_PIN, SW_SPI_MOSI_PIN, SW_SPI_SCK_PIN> max_tc_spi; #endif #define MAXTC_INIT(n, M) \ MAX##M max##M##_##n = MAX##M( \ TEMP_##n##_CS_PIN \ OPTARG(_MAX31865_##n##_SW, TEMP_##n##_MOSI_PIN) \ OPTARG(TEMP_SENSOR_##n##_USES_SW_SPI, TEMP_##n##_MISO_PIN, TEMP_##n##_SCK_PIN) \ OPTARG(LARGE_PINMAP, HIGH) \ ) #if HAS_MAX6675_LIBRARY #if TEMP_SENSOR_IS_MAX(0, 6675) MAXTC_INIT(0, 6675); #endif #if TEMP_SENSOR_IS_MAX(1, 6675) MAXTC_INIT(1, 6675); #endif #if TEMP_SENSOR_IS_MAX(2, 6675) MAXTC_INIT(2, 6675); #endif #endif #if HAS_MAX31855_LIBRARY #if TEMP_SENSOR_IS_MAX(0, 31855) MAXTC_INIT(0, 31855); #endif #if TEMP_SENSOR_IS_MAX(1, 31855) MAXTC_INIT(1, 31855); #endif #if TEMP_SENSOR_IS_MAX(2, 31855) MAXTC_INIT(2, 31855); #endif #endif // MAX31865 always uses a library, unlike '55 & 6675 #if HAS_MAX31865 #define _MAX31865_0_SW TEMP_SENSOR_0_USES_SW_SPI #define _MAX31865_1_SW TEMP_SENSOR_1_USES_SW_SPI #define _MAX31865_2_SW TEMP_SENSOR_2_USES_SW_SPI #define _MAX31865_BED_SW TEMP_SENSOR_BED_USES_SW_SPI #if TEMP_SENSOR_IS_MAX(0, 31865) MAXTC_INIT(0, 31865); #endif #if TEMP_SENSOR_IS_MAX(1, 31865) MAXTC_INIT(1, 31865); #endif #if TEMP_SENSOR_IS_MAX(2, 31865) MAXTC_INIT(2, 31865); #endif #if TEMP_SENSOR_IS_MAX(BED, 31865) MAXTC_INIT(BED, 31865); #endif #undef _MAX31865_0_SW #undef _MAX31865_1_SW #undef _MAX31865_2_SW #undef _MAX31865_BED_SW #endif #undef MAXTC_INIT #endif /** * public: */ #if ENABLED(TEMP_TUNING_MAINTAIN_FAN) bool Temperature::adaptive_fan_slowing = true; #endif #if HAS_HOTEND hotend_info_t Temperature::temp_hotend[HOTENDS]; constexpr celsius_t Temperature::hotend_maxtemp[HOTENDS]; #if ENABLED(MPCTEMP) bool MPC::e_paused; // = false int32_t MPC::e_position; // = 0 #endif // Sanity-check max readable temperatures #define CHECK_MAXTEMP_(N,M,S) static_assert( \ S >= 998 || M <= _MAX(TT_NAME(S)[0].celsius, TT_NAME(S)[COUNT(TT_NAME(S)) - 1].celsius) - (HOTEND_OVERSHOOT), \ "HEATER_" STRINGIFY(N) "_MAXTEMP (" STRINGIFY(M) ") is too high for thermistor_" STRINGIFY(S) ".h with HOTEND_OVERSHOOT=" STRINGIFY(HOTEND_OVERSHOOT) "."); #define CHECK_MAXTEMP(N) TERN(TEMP_SENSOR_##N##_IS_THERMISTOR, CHECK_MAXTEMP_, CODE_0)(N, HEATER_##N##_MAXTEMP, TEMP_SENSOR_##N) REPEAT(HOTENDS, CHECK_MAXTEMP) #if HAS_PREHEAT #define CHECK_PREHEAT__(N,P,T,M) static_assert(T <= (M) - (HOTEND_OVERSHOOT), "PREHEAT_" STRINGIFY(P) "_TEMP_HOTEND (" STRINGIFY(T) ") must be less than HEATER_" STRINGIFY(N) "_MAXTEMP (" STRINGIFY(M) ") - " STRINGIFY(HOTEND_OVERSHOOT) "."); #define CHECK_PREHEAT_(N,P) CHECK_PREHEAT__(N, P, PREHEAT_##P##_TEMP_HOTEND, HEATER_##N##_MAXTEMP) #define CHECK_PREHEAT(P) REPEAT2(HOTENDS, CHECK_PREHEAT_, P) #if PREHEAT_COUNT >= 1 CHECK_PREHEAT(1) #endif #if PREHEAT_COUNT >= 2 CHECK_PREHEAT(2) #endif #if PREHEAT_COUNT >= 3 CHECK_PREHEAT(3) #endif #if PREHEAT_COUNT >= 4 CHECK_PREHEAT(4) #endif #if PREHEAT_COUNT >= 5 CHECK_PREHEAT(5) #endif #if PREHEAT_COUNT >= 6 CHECK_PREHEAT(6) #endif #if PREHEAT_COUNT >= 7 CHECK_PREHEAT(7) #endif #if PREHEAT_COUNT >= 8 CHECK_PREHEAT(8) #endif #if PREHEAT_COUNT >= 9 CHECK_PREHEAT(9) #endif #if PREHEAT_COUNT >= 10 CHECK_PREHEAT(10) #endif #endif // HAS_PREHEAT #endif // HAS_HOTEND #if HAS_TEMP_REDUNDANT redundant_info_t Temperature::temp_redundant; #endif #if ANY(AUTO_POWER_E_FANS, HAS_FANCHECK) uint8_t Temperature::autofan_speed[HOTENDS] = ARRAY_N_1(HOTENDS, FAN_OFF_PWM); #endif #if ENABLED(AUTO_POWER_CHAMBER_FAN) uint8_t Temperature::chamberfan_speed = FAN_OFF_PWM; #endif #if ENABLED(AUTO_POWER_COOLER_FAN) uint8_t Temperature::coolerfan_speed = FAN_OFF_PWM; #endif #if ALL(FAN_SOFT_PWM, USE_CONTROLLER_FAN) uint8_t Temperature::soft_pwm_controller_speed = FAN_OFF_PWM; #endif // Init fans according to whether they're native PWM or Software PWM #ifdef BOARD_OPENDRAIN_MOSFETS #define _INIT_SOFT_FAN(P) OUT_WRITE_OD(P, ENABLED(FAN_INVERTING) ? LOW : HIGH) #else #define _INIT_SOFT_FAN(P) OUT_WRITE(P, ENABLED(FAN_INVERTING) ? LOW : HIGH) #endif #if ENABLED(FAN_SOFT_PWM) #define _INIT_FAN_PIN(P) _INIT_SOFT_FAN(P) #else #define _INIT_FAN_PIN(P) do{ if (PWM_PIN(P)) SET_PWM(P); else _INIT_SOFT_FAN(P); }while(0) #endif #if ENABLED(FAST_PWM_FAN) #define SET_FAST_PWM_FREQ(P) hal.set_pwm_frequency(pin_t(P), FAST_PWM_FAN_FREQUENCY) #else #define SET_FAST_PWM_FREQ(P) NOOP #endif #define INIT_FAN_PIN(P) do{ _INIT_FAN_PIN(P); SET_FAST_PWM_FREQ(P); }while(0) // HAS_FAN does not include CONTROLLER_FAN #if HAS_FAN uint8_t Temperature::fan_speed[FAN_COUNT] = ARRAY_N_1(FAN_COUNT, FAN_OFF_PWM); #if ENABLED(EXTRA_FAN_SPEED) Temperature::extra_fan_t Temperature::extra_fan_speed[FAN_COUNT] = ARRAY_N_1(FAN_COUNT, FAN_OFF_PWM); /** * Handle the M106 P<fan> T<speed> command: * T1 = Restore fan speed saved on the last T2 * T2 = Save the fan speed, then set to the last T<3-255> value * T<3-255> = Set the "extra fan speed" */ void Temperature::set_temp_fan_speed(const uint8_t fan, const uint16_t command_or_speed) { switch (command_or_speed) { case 1: set_fan_speed(fan, extra_fan_speed[fan].saved); break; case 2: extra_fan_speed[fan].saved = fan_speed[fan]; set_fan_speed(fan, extra_fan_speed[fan].speed); break; default: extra_fan_speed[fan].speed = _MIN(command_or_speed, 255U); break; } } #endif #if ANY(PROBING_FANS_OFF, ADVANCED_PAUSE_FANS_PAUSE) bool Temperature::fans_paused; // = false; uint8_t Temperature::saved_fan_speed[FAN_COUNT] = ARRAY_N_1(FAN_COUNT, FAN_OFF_PWM); #endif #if ENABLED(ADAPTIVE_FAN_SLOWING) uint8_t Temperature::fan_speed_scaler[FAN_COUNT] = ARRAY_N_1(FAN_COUNT, 128); #endif /** * Set the print fan speed for a target extruder */ void Temperature::set_fan_speed(uint8_t fan, uint16_t speed) { NOMORE(speed, 255U); #if ENABLED(SINGLENOZZLE_STANDBY_FAN) if (fan != active_extruder) { if (fan < EXTRUDERS) singlenozzle_fan_speed[fan] = speed; return; } #endif TERN_(SINGLENOZZLE, if (fan < EXTRUDERS) fan = 0); // Always fan 0 for SINGLENOZZLE E fan if (fan >= FAN_COUNT) return; fan_speed[fan] = speed; #if NUM_REDUNDANT_FANS if (fan == 0) { for (uint8_t f = REDUNDANT_PART_COOLING_FAN; f < REDUNDANT_PART_COOLING_FAN + NUM_REDUNDANT_FANS; ++f) thermalManager.set_fan_speed(f, speed); } #endif TERN_(REPORT_FAN_CHANGE, report_fan_speed(fan)); } #if ENABLED(REPORT_FAN_CHANGE) /** * Report print fan speed for a target extruder */ void Temperature::report_fan_speed(const uint8_t fan) { if (fan >= FAN_COUNT) return; PORT_REDIRECT(SerialMask::All); SERIAL_ECHOLNPGM("M106 P", fan, " S", fan_speed[fan]); } #endif #if ANY(PROBING_FANS_OFF, ADVANCED_PAUSE_FANS_PAUSE) void Temperature::set_fans_paused(const bool p) { if (p != fans_paused) { fans_paused = p; if (p) FANS_LOOP(i) { saved_fan_speed[i] = fan_speed[i]; fan_speed[i] = 0; } else FANS_LOOP(i) fan_speed[i] = saved_fan_speed[i]; } } #endif #endif // HAS_FAN #if WATCH_HOTENDS hotend_watch_t Temperature::watch_hotend[HOTENDS]; // = { { 0 } } #endif #if HEATER_IDLE_HANDLER Temperature::heater_idle_t Temperature::heater_idle[NR_HEATER_IDLE]; // = { { 0 } } #endif #if HAS_HEATED_BED bed_info_t Temperature::temp_bed; // = { 0 } // Init min and max temp with extreme values to prevent false errors during startup temp_raw_range_t Temperature::temp_sensor_range_bed = { TEMP_SENSOR_BED_RAW_LO_TEMP, TEMP_SENSOR_BED_RAW_HI_TEMP }; #if WATCH_BED bed_watch_t Temperature::watch_bed; // = { 0 } #endif #if DISABLED(PIDTEMPBED) millis_t Temperature::next_bed_check_ms; #endif #endif #if HAS_TEMP_CHAMBER chamber_info_t Temperature::temp_chamber; // = { 0 } #if HAS_HEATED_CHAMBER millis_t next_cool_check_ms = 0; celsius_float_t old_temp = 9999; temp_raw_range_t Temperature::temp_sensor_range_chamber = { TEMP_SENSOR_CHAMBER_RAW_LO_TEMP, TEMP_SENSOR_CHAMBER_RAW_HI_TEMP }; #if WATCH_CHAMBER chamber_watch_t Temperature::watch_chamber; // = { 0 } #endif #if DISABLED(PIDTEMPCHAMBER) millis_t Temperature::next_chamber_check_ms; #endif #endif #endif #if HAS_TEMP_COOLER cooler_info_t Temperature::temp_cooler; // = { 0 } #if HAS_COOLER bool flag_cooler_state; //bool flag_cooler_excess = false; celsius_float_t previous_temp = 9999; temp_raw_range_t Temperature::temp_sensor_range_cooler = { TEMP_SENSOR_COOLER_RAW_LO_TEMP, TEMP_SENSOR_COOLER_RAW_HI_TEMP }; #if WATCH_COOLER cooler_watch_t Temperature::watch_cooler; // = { 0 } #endif millis_t Temperature::next_cooler_check_ms, Temperature::cooler_fan_flush_ms; #endif #endif #if HAS_TEMP_PROBE probe_info_t Temperature::temp_probe; // = { 0 } #endif #if HAS_TEMP_BOARD board_info_t Temperature::temp_board; // = { 0 } #if ENABLED(THERMAL_PROTECTION_BOARD) temp_raw_range_t Temperature::temp_sensor_range_board = { TEMP_SENSOR_BOARD_RAW_LO_TEMP, TEMP_SENSOR_BOARD_RAW_HI_TEMP }; #endif #endif #if HAS_TEMP_SOC soc_info_t Temperature::temp_soc; // = { 0 } raw_adc_t Temperature::maxtemp_raw_SOC = TEMP_SENSOR_SOC_RAW_HI_TEMP; #endif #if ALL(HAS_MARLINUI_MENU, PREVENT_COLD_EXTRUSION) && E_MANUAL > 0 bool Temperature::allow_cold_extrude_override = false; #else constexpr bool Temperature::allow_cold_extrude_override; #endif #if ENABLED(PREVENT_COLD_EXTRUSION) bool Temperature::allow_cold_extrude = false; celsius_t Temperature::extrude_min_temp = EXTRUDE_MINTEMP; #else constexpr bool Temperature::allow_cold_extrude; constexpr celsius_t Temperature::extrude_min_temp; #endif #if HAS_ADC_BUTTONS uint32_t Temperature::current_ADCKey_raw = HAL_ADC_RANGE; uint16_t Temperature::ADCKey_count = 0; #endif #if ENABLED(PID_EXTRUSION_SCALING) int16_t Temperature::lpq_len; // Initialized in settings.cpp #endif /** * private: */ volatile bool Temperature::raw_temps_ready = false; #define TEMPDIR(N) ((TEMP_SENSOR_##N##_RAW_LO_TEMP) < (TEMP_SENSOR_##N##_RAW_HI_TEMP) ? 1 : -1) #define TP_CMP(S,A,B) (TEMPDIR(S) < 0 ? ((A)<(B)) : ((A)>(B))) #if HAS_HOTEND // Init mintemp and maxtemp with extreme values to prevent false errors during startup constexpr temp_range_t sensor_heater_0 { TEMP_SENSOR_0_RAW_LO_TEMP, TEMP_SENSOR_0_RAW_HI_TEMP, 0, 16383 }, sensor_heater_1 { TEMP_SENSOR_1_RAW_LO_TEMP, TEMP_SENSOR_1_RAW_HI_TEMP, 0, 16383 }, sensor_heater_2 { TEMP_SENSOR_2_RAW_LO_TEMP, TEMP_SENSOR_2_RAW_HI_TEMP, 0, 16383 }, sensor_heater_3 { TEMP_SENSOR_3_RAW_LO_TEMP, TEMP_SENSOR_3_RAW_HI_TEMP, 0, 16383 }, sensor_heater_4 { TEMP_SENSOR_4_RAW_LO_TEMP, TEMP_SENSOR_4_RAW_HI_TEMP, 0, 16383 }, sensor_heater_5 { TEMP_SENSOR_5_RAW_LO_TEMP, TEMP_SENSOR_5_RAW_HI_TEMP, 0, 16383 }, sensor_heater_6 { TEMP_SENSOR_6_RAW_LO_TEMP, TEMP_SENSOR_6_RAW_HI_TEMP, 0, 16383 }, sensor_heater_7 { TEMP_SENSOR_7_RAW_LO_TEMP, TEMP_SENSOR_7_RAW_HI_TEMP, 0, 16383 }; temp_range_t Temperature::temp_range[HOTENDS] = ARRAY_BY_HOTENDS(sensor_heater_0, sensor_heater_1, sensor_heater_2, sensor_heater_3, sensor_heater_4, sensor_heater_5, sensor_heater_6, sensor_heater_7); #endif #if MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED > 1 #define MULTI_MAX_CONSECUTIVE_LOW_TEMP_ERR 1 uint8_t Temperature::consecutive_low_temperature_error[HOTENDS]; // = { 0 } #endif #if PREHEAT_TIME_HOTEND_MS > 0 millis_t Temperature::preheat_end_ms_hotend[HOTENDS]; // = { 0 }; #endif #if HAS_HEATED_BED && PREHEAT_TIME_BED_MS > 0 millis_t Temperature::preheat_end_ms_bed = 0; #endif #if HAS_FAN_LOGIC constexpr millis_t Temperature::fan_update_interval_ms; millis_t Temperature::fan_update_ms = 0; #endif #if ENABLED(FAN_SOFT_PWM) uint8_t Temperature::soft_pwm_amount_fan[FAN_COUNT], Temperature::soft_pwm_count_fan[FAN_COUNT]; #endif #if ENABLED(SINGLENOZZLE_STANDBY_TEMP) celsius_t Temperature::singlenozzle_temp[EXTRUDERS]; #endif #if ENABLED(SINGLENOZZLE_STANDBY_FAN) uint8_t Temperature::singlenozzle_fan_speed[EXTRUDERS]; #endif #if ENABLED(PROBING_HEATERS_OFF) bool Temperature::paused_for_probing; #endif /** * public: * Class and Instance Methods */ #if ANY(HAS_PID_HEATING, MPC_AUTOTUNE) /** * Run the minimal required activities during a tuning loop. * TODO: Allow tuning routines to call idle() for more complete keepalive. */ bool Temperature::tuning_idle(const millis_t &ms) { // Run HAL idle tasks hal.idletask(); const bool temp_ready = updateTemperaturesIfReady(); #if HAS_FAN_LOGIC if (temp_ready) manage_extruder_fans(ms); #else UNUSED(ms); #endif // Run Controller Fan check (normally handled by manage_inactivity) TERN_(USE_CONTROLLER_FAN, controllerFan.update()); // Run UI update ui.update(); return temp_ready; } #endif #if HAS_PID_HEATING inline void say_default_() { SERIAL_ECHOPGM("#define DEFAULT_"); } /** * PID Autotuning (M303) * * Alternately heat and cool the nozzle, observing its behavior to * determine the best PID values to achieve a stable temperature. * Needs sufficient heater power to make some overshoot at target * temperature to succeed. */ void Temperature::PID_autotune(const celsius_t target, const heater_id_t heater_id, const int8_t ncycles, const bool set_result/*=false*/) { celsius_float_t current_temp = 0.0; int cycles = 0; bool heating = true; millis_t next_temp_ms = millis(), t1 = next_temp_ms, t2 = next_temp_ms; long t_high = 0, t_low = 0; raw_pid_t tune_pid = { 0, 0, 0 }; celsius_float_t maxT = 0, minT = 10000; const bool isbed = (heater_id == H_BED), ischamber = (heater_id == H_CHAMBER); #if ENABLED(PIDTEMPCHAMBER) #define C_TERN(T,A,B) ((T) ? (A) : (B)) #else #define C_TERN(T,A,B) (B) #endif #if ENABLED(PIDTEMPBED) #define B_TERN(T,A,B) ((T) ? (A) : (B)) #else #define B_TERN(T,A,B) (B) #endif #define GHV(C,B,H) C_TERN(ischamber, C, B_TERN(isbed, B, H)) #define SHV(V) C_TERN(ischamber, temp_chamber.soft_pwm_amount = V, B_TERN(isbed, temp_bed.soft_pwm_amount = V, temp_hotend[heater_id].soft_pwm_amount = V)) #define ONHEATINGSTART() C_TERN(ischamber, printerEventLEDs.onChamberHeatingStart(), B_TERN(isbed, printerEventLEDs.onBedHeatingStart(), printerEventLEDs.onHotendHeatingStart())) #define ONHEATING(S,C,T) C_TERN(ischamber, printerEventLEDs.onChamberHeating(S,C,T), B_TERN(isbed, printerEventLEDs.onBedHeating(S,C,T), printerEventLEDs.onHotendHeating(S,C,T))) #define WATCH_PID DISABLED(NO_WATCH_PID_TUNING) && (ALL(WATCH_CHAMBER, PIDTEMPCHAMBER) || ALL(WATCH_BED, PIDTEMPBED) || ALL(WATCH_HOTENDS, PIDTEMP)) #if WATCH_PID #if ALL(THERMAL_PROTECTION_CHAMBER, PIDTEMPCHAMBER) #define C_GTV(T,A,B) ((T) ? (A) : (B)) #else #define C_GTV(T,A,B) (B) #endif #if ALL(THERMAL_PROTECTION_BED, PIDTEMPBED) #define B_GTV(T,A,B) ((T) ? (A) : (B)) #else #define B_GTV(T,A,B) (B) #endif #define GTV(C,B,H) C_GTV(ischamber, C, B_GTV(isbed, B, H)) const uint16_t watch_temp_period = GTV(WATCH_CHAMBER_TEMP_PERIOD, WATCH_BED_TEMP_PERIOD, WATCH_TEMP_PERIOD); const uint8_t watch_temp_increase = GTV(WATCH_CHAMBER_TEMP_INCREASE, WATCH_BED_TEMP_INCREASE, WATCH_TEMP_INCREASE); const celsius_float_t watch_temp_target = celsius_float_t(target - (watch_temp_increase + GTV(TEMP_CHAMBER_HYSTERESIS, TEMP_BED_HYSTERESIS, TEMP_HYSTERESIS) + 1)); millis_t temp_change_ms = next_temp_ms + SEC_TO_MS(watch_temp_period); celsius_float_t next_watch_temp = 0.0; bool heated = false; #endif TERN_(HAS_FAN_LOGIC, fan_update_ms = next_temp_ms + fan_update_interval_ms); TERN_(EXTENSIBLE_UI, ExtUI::onPIDTuning(ischamber ? ExtUI::pidresult_t::PID_CHAMBER_STARTED : isbed ? ExtUI::pidresult_t::PID_BED_STARTED : ExtUI::pidresult_t::PID_STARTED)); if (target > GHV(CHAMBER_MAX_TARGET, BED_MAX_TARGET, hotend_max_target(heater_id))) { SERIAL_ECHOPGM(STR_PID_AUTOTUNE); SERIAL_ECHOLNPGM(STR_PID_TEMP_TOO_HIGH); TERN_(EXTENSIBLE_UI, ExtUI::onPIDTuning(ExtUI::pidresult_t::PID_TEMP_TOO_HIGH)); TERN_(HOST_PROMPT_SUPPORT, hostui.notify(GET_TEXT_F(MSG_PID_TEMP_TOO_HIGH))); return; } SERIAL_ECHOPGM(STR_PID_AUTOTUNE); SERIAL_ECHOLNPGM(STR_PID_AUTOTUNE_START); disable_all_heaters(); TERN_(AUTO_POWER_CONTROL, powerManager.power_on()); long bias = GHV(MAX_CHAMBER_POWER, MAX_BED_POWER, PID_MAX) >> 1, d = bias; SHV(bias); #if ENABLED(PRINTER_EVENT_LEDS) const celsius_float_t start_temp = GHV(degChamber(), degBed(), degHotend(heater_id)); const LEDColor oldcolor = ONHEATINGSTART(); #endif TERN_(TEMP_TUNING_MAINTAIN_FAN, adaptive_fan_slowing = false); LCD_MESSAGE(MSG_HEATING); // PID Tuning loop wait_for_heatup = true; while (wait_for_heatup) { // Can be interrupted with M108 const millis_t ms = millis(); // Run minimal necessary machine tasks const bool temp_ready = tuning_idle(ms); // If a new sample has arrived process things if (temp_ready) { // Get the current temperature and constrain it current_temp = GHV(degChamber(), degBed(), degHotend(heater_id)); NOLESS(maxT, current_temp); NOMORE(minT, current_temp); #if ENABLED(PRINTER_EVENT_LEDS) ONHEATING(start_temp, current_temp, target); #endif if (heating && current_temp > target && ELAPSED(ms, t2 + 5000UL)) { heating = false; SHV((bias - d) >> 1); t1 = ms; t_high = t1 - t2; maxT = target; } if (!heating && current_temp < target && ELAPSED(ms, t1 + 5000UL)) { heating = true; t2 = ms; t_low = t2 - t1; if (cycles > 0) { const long max_pow = GHV(MAX_CHAMBER_POWER, MAX_BED_POWER, PID_MAX); bias += (d * (t_high - t_low)) / (t_low + t_high); LIMIT(bias, 20, max_pow - 20); d = (bias > max_pow >> 1) ? max_pow - 1 - bias : bias; SERIAL_ECHOPGM(STR_BIAS, bias, STR_D_COLON, d, STR_T_MIN, minT, STR_T_MAX, maxT); if (cycles > 2) { const float Ku = (4.0f * d) / (float(M_PI) * (maxT - minT) * 0.5f), Tu = float(t_low + t_high) * 0.001f, pf = (ischamber || isbed) ? 0.2f : 0.6f, df = (ischamber || isbed) ? 1.0f / 3.0f : 1.0f / 8.0f; tune_pid.p = Ku * pf; tune_pid.i = tune_pid.p * 2.0f / Tu; tune_pid.d = tune_pid.p * Tu * df; SERIAL_ECHOLNPGM(STR_KU, Ku, STR_TU, Tu); if (ischamber || isbed) SERIAL_ECHOLNPGM(" No overshoot"); else SERIAL_ECHOLNPGM(STR_CLASSIC_PID); SERIAL_ECHOLNPGM(STR_KP, tune_pid.p, STR_KI, tune_pid.i, STR_KD, tune_pid.d); } } SHV((bias + d) >> 1); TERN_(HAS_STATUS_MESSAGE, ui.status_printf(0, F(S_FMT " %i/%i"), GET_TEXT_F(MSG_PID_CYCLE), cycles, ncycles)); cycles++; minT = target; } } // Did the temperature overshoot very far? #ifndef MAX_OVERSHOOT_PID_AUTOTUNE #define MAX_OVERSHOOT_PID_AUTOTUNE 30 #endif if (current_temp > target + MAX_OVERSHOOT_PID_AUTOTUNE) { SERIAL_ECHOPGM(STR_PID_AUTOTUNE); SERIAL_ECHOLNPGM(STR_PID_TEMP_TOO_HIGH); TERN_(EXTENSIBLE_UI, ExtUI::onPIDTuning(ExtUI::pidresult_t::PID_TEMP_TOO_HIGH)); TERN_(HOST_PROMPT_SUPPORT, hostui.notify(GET_TEXT_F(MSG_PID_TEMP_TOO_HIGH))); break; } // Report heater states every 2 seconds if (ELAPSED(ms, next_temp_ms)) { #if HAS_TEMP_SENSOR print_heater_states(heater_id < 0 ? active_extruder : (int8_t)heater_id); SERIAL_EOL(); #endif next_temp_ms = ms + 2000UL; // Make sure heating is actually working #if WATCH_PID if (ALL(WATCH_BED, WATCH_HOTENDS) || isbed == DISABLED(WATCH_HOTENDS) || ischamber == DISABLED(WATCH_HOTENDS)) { if (!heated) { // If not yet reached target... if (current_temp > next_watch_temp) { // Over the watch temp? next_watch_temp = current_temp + watch_temp_increase; // - set the next temp to watch for temp_change_ms = ms + SEC_TO_MS(watch_temp_period); // - move the expiration timer up if (current_temp > watch_temp_target) heated = true; // - Flag if target temperature reached } else if (ELAPSED(ms, temp_change_ms)) // Watch timer expired _TEMP_ERROR(heater_id, FPSTR(str_t_heating_failed), MSG_ERR_HEATING_FAILED, current_temp); } else if (current_temp < target - (MAX_OVERSHOOT_PID_AUTOTUNE)) // Heated, then temperature fell too far? _TEMP_ERROR(heater_id, FPSTR(str_t_thermal_runaway), MSG_ERR_THERMAL_RUNAWAY, current_temp); } #endif } // every 2 seconds // Timeout after PID_AUTOTUNE_MAX_CYCLE_MINS minutes since the last undershoot/overshoot cycle #ifndef PID_AUTOTUNE_MAX_CYCLE_MINS #define PID_AUTOTUNE_MAX_CYCLE_MINS 20L #endif if ((ms - _MIN(t1, t2)) > MIN_TO_MS(PID_AUTOTUNE_MAX_CYCLE_MINS)) { TERN_(DWIN_CREALITY_LCD, dwinPopupTemperature(0)); TERN_(EXTENSIBLE_UI, ExtUI::onPIDTuning(ExtUI::pidresult_t::PID_TUNING_TIMEOUT)); TERN_(HOST_PROMPT_SUPPORT, hostui.notify(GET_TEXT_F(MSG_PID_TIMEOUT))); SERIAL_ECHOPGM(STR_PID_AUTOTUNE); SERIAL_ECHOLNPGM(STR_PID_TIMEOUT); break; } if (cycles > ncycles && cycles > 2) { SERIAL_ECHOPGM(STR_PID_AUTOTUNE); SERIAL_ECHOLNPGM(STR_PID_AUTOTUNE_FINISHED); TERN_(HOST_PROMPT_SUPPORT, hostui.notify(GET_TEXT_F(MSG_PID_AUTOTUNE_DONE))); #if ANY(PIDTEMPBED, PIDTEMPCHAMBER) FSTR_P const estring = GHV(F("chamber"), F("bed"), FPSTR(NUL_STR)); say_default_(); SERIAL_ECHOLN(estring, F("Kp "), tune_pid.p); say_default_(); SERIAL_ECHOLN(estring, F("Ki "), tune_pid.i); say_default_(); SERIAL_ECHOLN(estring, F("Kd "), tune_pid.d); #else say_default_(); SERIAL_ECHOLNPGM("Kp ", tune_pid.p); say_default_(); SERIAL_ECHOLNPGM("Ki ", tune_pid.i); say_default_(); SERIAL_ECHOLNPGM("Kd ", tune_pid.d); #endif auto _set_hotend_pid = [](const uint8_t tool, const raw_pid_t &in_pid) { #if ENABLED(PIDTEMP) #if ENABLED(PID_PARAMS_PER_HOTEND) thermalManager.temp_hotend[tool].pid.set(in_pid); #else HOTEND_LOOP() thermalManager.temp_hotend[e].pid.set(in_pid); #endif updatePID(); #endif UNUSED(tool); UNUSED(in_pid); }; #if ENABLED(PIDTEMPBED) auto _set_bed_pid = [](const raw_pid_t &in_pid) { temp_bed.pid.set(in_pid); }; #endif #if ENABLED(PIDTEMPCHAMBER) auto _set_chamber_pid = [](const raw_pid_t &in_pid) { temp_chamber.pid.set(in_pid); }; #endif // Use the result? (As with "M303 U1") if (set_result) GHV(_set_chamber_pid(tune_pid), _set_bed_pid(tune_pid), _set_hotend_pid(heater_id, tune_pid)); goto EXIT_M303; } } wait_for_heatup = false; disable_all_heaters(); EXIT_M303: TERN_(PRINTER_EVENT_LEDS, printerEventLEDs.onPIDTuningDone(oldcolor)); TERN_(EXTENSIBLE_UI, ExtUI::onPIDTuning(ExtUI::pidresult_t::PID_DONE)); TERN_(TEMP_TUNING_MAINTAIN_FAN, adaptive_fan_slowing = true); return; } #endif // HAS_PID_HEATING #if ENABLED(MPC_AUTOTUNE) #if ANY(MPC_FAN_0_ALL_HOTENDS, MPC_FAN_0_ACTIVE_HOTEND) #define SINGLEFAN 1 #endif #define DEBUG_MPC_AUTOTUNE 1 millis_t Temperature::MPC_autotuner::curr_time_ms, Temperature::MPC_autotuner::next_report_ms; celsius_float_t Temperature::MPC_autotuner::temp_samples[16]; uint8_t Temperature::MPC_autotuner::sample_count; uint16_t Temperature::MPC_autotuner::sample_distance; // Parameters from differential analysis celsius_float_t Temperature::MPC_autotuner::temp_fastest; #if HAS_FAN float Temperature::MPC_autotuner::power_fan255; #endif Temperature::MPC_autotuner::MPC_autotuner(const uint8_t extruderIdx) : e(extruderIdx) { TERN_(TEMP_TUNING_MAINTAIN_FAN, adaptive_fan_slowing = false); } Temperature::MPC_autotuner::~MPC_autotuner() { wait_for_heatup = false; ui.reset_status(); temp_hotend[e].target = 0.0f; temp_hotend[e].soft_pwm_amount = 0; #if HAS_FAN set_fan_speed(TERN(SINGLEFAN, 0, e), 0); planner.sync_fan_speeds(fan_speed); #endif do_z_clearance(MPC_TUNING_END_Z, false); TERN_(TEMP_TUNING_MAINTAIN_FAN, adaptive_fan_slowing = true); } Temperature::MPC_autotuner::MeasurementState Temperature::MPC_autotuner::measure_ambient_temp() { init_timers(); const millis_t test_interval_ms = 10000UL; millis_t next_test_ms = curr_time_ms + test_interval_ms; ambient_temp = current_temp = degHotend(e); wait_for_heatup = true; for (;;) { // Can be interrupted with M108 if (housekeeping() == CANCELLED) return CANCELLED; if (ELAPSED(curr_time_ms, next_test_ms)) { if (current_temp >= ambient_temp) { ambient_temp = (ambient_temp + current_temp) / 2.0f; break; } ambient_temp = current_temp; next_test_ms += test_interval_ms; } } wait_for_heatup = false; #if ENABLED(DEBUG_MPC_AUTOTUNE) SERIAL_ECHOLNPGM("MPC_autotuner::measure_ambient_temp() Completed"); SERIAL_ECHOLNPGM("====="); SERIAL_ECHOLNPGM("ambient_temp ", get_ambient_temp()); #endif return SUCCESS; } Temperature::MPC_autotuner::MeasurementState Temperature::MPC_autotuner::measure_heatup() { init_timers(); constexpr millis_t test_interval_ms = 1000UL; millis_t next_test_time_ms = curr_time_ms + test_interval_ms; MPCHeaterInfo &hotend = temp_hotend[e]; current_temp = degHotend(e); millis_t heat_start_time_ms = curr_time_ms; sample_count = 0; sample_distance = 1; t1_time = 0; hotend.target = 200.0f; // So M105 looks nice hotend.soft_pwm_amount = (MPC_MAX) >> 1; // Initialise rate of change to to steady state at current time temp_samples[0] = temp_samples[1] = temp_samples[2] = current_temp; time_fastest = rate_fastest = 0; wait_for_heatup = true; for (;;) { // Can be interrupted with M108 if (housekeeping() == CANCELLED) return CANCELLED; if (ELAPSED(curr_time_ms, next_test_time_ms)) { if (current_temp < 100.0f) { // Initial regime (below 100deg): Measure rate of change of heating for differential tuning // Update the buffer of previous readings temp_samples[0] = temp_samples[1]; temp_samples[1] = temp_samples[2]; temp_samples[2] = current_temp; // Measure the rate of change of temperature, https://en.wikipedia.org/wiki/Symmetric_derivative const float h = MS_TO_SEC_PRECISE(test_interval_ms), curr_rate = (temp_samples[2] - temp_samples[0]) / 2 * h; if (curr_rate > rate_fastest) { // Update fastest values rate_fastest = curr_rate; temp_fastest = temp_samples[1]; time_fastest = get_elapsed_heating_time(); } next_test_time_ms += test_interval_ms; } else if (current_temp < 200.0f) { // Second regime (after 100deg) measure 3 points to determine asymptotic temperature // If there are too many samples, space them more widely if (sample_count == COUNT(temp_samples)) { for (uint8_t i = 0; i < COUNT(temp_samples) / 2; i++) temp_samples[i] = temp_samples[i * 2]; sample_count /= 2; sample_distance *= 2; } if (sample_count == 0) t1_time = MS_TO_SEC_PRECISE(curr_time_ms - heat_start_time_ms); temp_samples[sample_count++] = current_temp; next_test_time_ms += test_interval_ms * sample_distance; } else { // Third regime (after 200deg) finished gathering data so finish break; } } } wait_for_heatup = false; hotend.soft_pwm_amount = 0; elapsed_heating_time = MS_TO_SEC_PRECISE(curr_time_ms - heat_start_time_ms); // Ensure sample count is odd so that we have 3 equally spaced samples if (sample_count == 0) return FAILED; if (sample_count % 2 == 0) sample_count--; #if ENABLED(DEBUG_MPC_AUTOTUNE) SERIAL_ECHOLNPGM("MPC_autotuner::measure_heatup() Completed"); SERIAL_ECHOLNPGM("====="); SERIAL_ECHOLNPGM("t1_time ", t1_time); SERIAL_ECHOLNPGM("sample_count ", sample_count); SERIAL_ECHOLNPGM("sample_distance ", sample_distance); for (uint8_t i = 0; i < sample_count; i++) SERIAL_ECHOLNPGM("sample ", i, " : ", temp_samples[i]); SERIAL_ECHOLNPGM("t1 ", get_sample_1_temp(), " t2 ", get_sample_2_temp(), " t3 ", get_sample_3_temp()); #endif return SUCCESS; } Temperature::MPC_autotuner::MeasurementState Temperature::MPC_autotuner::measure_transfer() { init_timers(); const millis_t test_interval_ms = SEC_TO_MS(MPC_dT); millis_t next_test_ms = curr_time_ms + test_interval_ms; MPCHeaterInfo &hotend = temp_hotend[e]; MPC_t &mpc = hotend.mpc; constexpr millis_t settle_time = 20000UL, test_duration = 20000UL; millis_t settle_end_ms = curr_time_ms + settle_time, test_end_ms = settle_end_ms + test_duration; float total_energy_fan0 = 0.0f; #if HAS_FAN bool fan0_done = false; float total_energy_fan255 = 0.0f; #endif float last_temp = current_temp; wait_for_heatup = true; for (;;) { // Can be interrupted with M108 if (housekeeping() == CANCELLED) return CANCELLED; if (ELAPSED(curr_time_ms, next_test_ms)) { hotend.soft_pwm_amount = (int)get_pid_output_hotend(e) >> 1; if (ELAPSED(curr_time_ms, settle_end_ms) && !ELAPSED(curr_time_ms, test_end_ms) && TERN1(HAS_FAN, !fan0_done)) total_energy_fan0 += mpc.heater_power * hotend.soft_pwm_amount / 127 * MPC_dT + (last_temp - current_temp) * mpc.block_heat_capacity; #if HAS_FAN else if (ELAPSED(curr_time_ms, test_end_ms) && !fan0_done) { set_fan_speed(TERN(SINGLEFAN, 0, e), 255); planner.sync_fan_speeds(fan_speed); settle_end_ms = curr_time_ms + settle_time; test_end_ms = settle_end_ms + test_duration; fan0_done = true; } else if (ELAPSED(curr_time_ms, settle_end_ms) && !ELAPSED(curr_time_ms, test_end_ms)) total_energy_fan255 += mpc.heater_power * hotend.soft_pwm_amount / 127 * MPC_dT + (last_temp - current_temp) * mpc.block_heat_capacity; #endif else if (ELAPSED(curr_time_ms, test_end_ms)) break; last_temp = current_temp; next_test_ms += test_interval_ms; } // Ensure we don't drift too far from the window between the last sampled temp and the target temperature if (!WITHIN(current_temp, get_sample_3_temp() - 15.0f, hotend.target + 15.0f)) { SERIAL_ECHOLNPGM(STR_MPC_TEMPERATURE_ERROR); TERN_(EXTENSIBLE_UI, ExtUI::onMPCTuning(ExtUI::mpcresult_t::MPC_TEMP_ERROR)); wait_for_heatup = false; return FAILED; } } wait_for_heatup = false; power_fan0 = total_energy_fan0 / MS_TO_SEC_PRECISE(test_duration); TERN_(HAS_FAN, power_fan255 = (total_energy_fan255 * 1000) / test_duration); #if ENABLED(DEBUG_MPC_AUTOTUNE) SERIAL_ECHOLNPGM("MPC_autotuner::measure_transfer() Completed"); SERIAL_ECHOLNPGM("====="); SERIAL_ECHOLNPGM("power_fan0 ", power_fan0); TERN_(HAS_FAN, SERIAL_ECHOLNPGM("power_fan255 ", power_fan255)); #endif return SUCCESS; } Temperature::MPC_autotuner::MeasurementState Temperature::MPC_autotuner::housekeeping() { constexpr millis_t report_interval_ms = 1000UL; curr_time_ms = millis(); // Run minimal necessary machine tasks const bool temp_ready = tuning_idle(curr_time_ms); // Set MPC temp if a new sample is ready if (temp_ready) current_temp = degHotend(e); if (ELAPSED(curr_time_ms, next_report_ms)) { next_report_ms += report_interval_ms; print_heater_states(e); SERIAL_EOL(); } if (!wait_for_heatup) { SERIAL_ECHOLNPGM(STR_MPC_AUTOTUNE_INTERRUPTED); TERN_(EXTENSIBLE_UI, ExtUI::onMPCTuning(ExtUI::mpcresult_t::MPC_INTERRUPTED)); return MeasurementState::CANCELLED; } return MeasurementState::SUCCESS; } void Temperature::MPC_autotune(const uint8_t e, MPCTuningType tuning_type=AUTO) { SERIAL_ECHOLNPGM(STR_MPC_AUTOTUNE_START, e); MPC_autotuner tuner(e); MPCHeaterInfo &hotend = temp_hotend[e]; MPC_t &mpc = hotend.mpc; // Move to center of bed, just above bed height and cool with max fan gcode.home_all_axes(true); disable_all_heaters(); #if HAS_FAN zero_fan_speeds(); set_fan_speed(TERN(SINGLEFAN, 0, e), 255); planner.sync_fan_speeds(fan_speed); #endif do_blocking_move_to(xyz_pos_t(MPC_TUNING_POS)); // Determine ambient temperature. SERIAL_ECHOLNPGM(STR_MPC_COOLING_TO_AMBIENT); TERN_(EXTENSIBLE_UI, ExtUI::onMPCTuning(ExtUI::mpcresult_t::MPC_STARTED)); TERN(DWIN_LCD_PROUI, LCD_ALERTMESSAGE(MSG_MPC_COOLING_TO_AMBIENT), LCD_MESSAGE(MSG_COOLING)); if (tuner.measure_ambient_temp() != MPC_autotuner::MeasurementState::SUCCESS) return; hotend.modeled_ambient_temp = tuner.get_ambient_temp(); #if HAS_FAN set_fan_speed(TERN(SINGLEFAN, 0, e), 0); planner.sync_fan_speeds(fan_speed); #endif // Heat to 200 degrees SERIAL_ECHOLNPGM(STR_MPC_HEATING_PAST_200); LCD_ALERTMESSAGE(MSG_MPC_HEATING_PAST_200); if (tuner.measure_heatup() != MPC_autotuner::MeasurementState::SUCCESS) return; // Calculate physical constants from three equally-spaced samples const float t1 = tuner.get_sample_1_temp(), t2 = tuner.get_sample_2_temp(), t3 = tuner.get_sample_3_temp(); float asymp_temp = (t2 * t2 - t1 * t3) / (2 * t2 - t1 - t3), block_responsiveness = -log((t2 - asymp_temp) / (t1 - asymp_temp)) / tuner.get_sample_interval(); #if ENABLED(DEBUG_MPC_AUTOTUNE) SERIAL_ECHOLNPGM("asymp_temp ", asymp_temp); SERIAL_ECHOLNPGM("block_responsiveness ", p_float_t(block_responsiveness, 4)); #endif // Make initial guess at transfer coefficients mpc.ambient_xfer_coeff_fan0 = mpc.heater_power * (MPC_MAX) / 255 / (asymp_temp - tuner.get_ambient_temp()); TERN_(MPC_INCLUDE_FAN, mpc.fan255_adjustment = 0.0f); if (tuning_type == AUTO || tuning_type == FORCE_ASYMPTOTIC) { // Analytic tuning mpc.block_heat_capacity = mpc.ambient_xfer_coeff_fan0 / block_responsiveness; mpc.sensor_responsiveness = block_responsiveness / (1.0f - (tuner.get_ambient_temp() - asymp_temp) * exp(-block_responsiveness * tuner.get_sample_1_time()) / (t1 - asymp_temp)); } // If analytic tuning fails, fall back to differential tuning if (tuning_type == AUTO) { if (mpc.sensor_responsiveness <= 0 || mpc.block_heat_capacity <= 0) tuning_type = FORCE_DIFFERENTIAL; } if (tuning_type == FORCE_DIFFERENTIAL) { // Differential tuning mpc.block_heat_capacity = mpc.heater_power / tuner.get_rate_fastest(); mpc.sensor_responsiveness = tuner.get_rate_fastest() / (tuner.get_rate_fastest() * tuner.get_time_fastest() + tuner.get_ambient_temp() - tuner.get_time_fastest()); } hotend.modeled_block_temp = asymp_temp + (tuner.get_ambient_temp() - asymp_temp) * exp(-block_responsiveness * tuner.get_elapsed_heating_time()); hotend.modeled_sensor_temp = tuner.get_last_measured_temp(); // Allow the system to stabilize under MPC, then get a better measure of ambient loss with and without fan SERIAL_ECHOLNPGM(STR_MPC_MEASURING_AMBIENT, hotend.modeled_block_temp); TERN(DWIN_LCD_PROUI, LCD_ALERTMESSAGE(MSG_MPC_MEASURING_AMBIENT), LCD_MESSAGE(MSG_MPC_MEASURING_AMBIENT)); // Use the estimated overshoot of the temperature as the target to achieve. hotend.target = hotend.modeled_block_temp; if (tuner.measure_transfer() != MPC_autotuner::MeasurementState::SUCCESS) return; // Update the transfer coefficients mpc.ambient_xfer_coeff_fan0 = tuner.get_power_fan0() / (hotend.target - tuner.get_ambient_temp()); #if HAS_FAN const float ambient_xfer_coeff_fan255 = tuner.get_power_fan255() / (hotend.target - tuner.get_ambient_temp()); mpc.applyFanAdjustment(ambient_xfer_coeff_fan255); #endif if (tuning_type == AUTO || tuning_type == FORCE_ASYMPTOTIC) { // Calculate a new and better asymptotic temperature and re-evaluate the other constants asymp_temp = tuner.get_ambient_temp() + mpc.heater_power * (MPC_MAX) / 255 / mpc.ambient_xfer_coeff_fan0; block_responsiveness = -log((t2 - asymp_temp) / (t1 - asymp_temp)) / tuner.get_sample_interval(); #if ENABLED(DEBUG_MPC_AUTOTUNE) SERIAL_ECHOLNPGM("Refining estimates for:"); SERIAL_ECHOLNPGM("asymp_temp ", asymp_temp); SERIAL_ECHOLNPGM("block_responsiveness ", p_float_t(block_responsiveness, 4)); #endif // Update analytic tuning values based on the above mpc.block_heat_capacity = mpc.ambient_xfer_coeff_fan0 / block_responsiveness; mpc.sensor_responsiveness = block_responsiveness / (1.0f - (tuner.get_ambient_temp() - asymp_temp) * exp(-block_responsiveness * tuner.get_sample_1_time()) / (t1 - asymp_temp)); } SERIAL_ECHOLNPGM(STR_MPC_AUTOTUNE_FINISHED); TERN_(EXTENSIBLE_UI, ExtUI::onMPCTuning(ExtUI::mpcresult_t::MPC_DONE)); SERIAL_ECHOLNPGM("MPC_BLOCK_HEAT_CAPACITY ", mpc.block_heat_capacity); SERIAL_ECHOLNPGM("MPC_SENSOR_RESPONSIVENESS ", p_float_t(mpc.sensor_responsiveness, 4)); SERIAL_ECHOLNPGM("MPC_AMBIENT_XFER_COEFF ", p_float_t(mpc.ambient_xfer_coeff_fan0, 4)); TERN_(HAS_FAN, SERIAL_ECHOLNPGM("MPC_AMBIENT_XFER_COEFF_FAN255 ", p_float_t(ambient_xfer_coeff_fan255, 4))); } #endif // MPC_AUTOTUNE int16_t Temperature::getHeaterPower(const heater_id_t heater_id) { switch (heater_id) { #if HAS_HEATED_BED case H_BED: return temp_bed.soft_pwm_amount; #endif #if HAS_HEATED_CHAMBER case H_CHAMBER: return temp_chamber.soft_pwm_amount; #endif #if HAS_COOLER case H_COOLER: return temp_cooler.soft_pwm_amount; #endif default: return TERN0(HAS_HOTEND, temp_hotend[heater_id].soft_pwm_amount); } } #if HAS_AUTO_FAN #define _EFANOVERLAP(I,N) ((I != N) && _FANOVERLAP(I,E##N)) #if EXTRUDER_AUTO_FAN_SPEED != 255 #define INIT_E_AUTO_FAN_PIN(P) do{ if (PWM_PIN(P)) { SET_PWM(P); SET_FAST_PWM_FREQ(P); } else SET_OUTPUT(P); }while(0) #else #define INIT_E_AUTO_FAN_PIN(P) SET_OUTPUT(P) #endif #if CHAMBER_AUTO_FAN_SPEED != 255 #define INIT_CHAMBER_AUTO_FAN_PIN(P) do{ if (PWM_PIN(P)) { SET_PWM(P); SET_FAST_PWM_FREQ(P); } else SET_OUTPUT(P); }while(0) #else #define INIT_CHAMBER_AUTO_FAN_PIN(P) SET_OUTPUT(P) #endif #if COOLER_AUTO_FAN_SPEED != 255 #define INIT_COOLER_AUTO_FAN_PIN(P) do{ if (PWM_PIN(P)) { SET_PWM(P); SET_FAST_PWM_FREQ(P); } else SET_OUTPUT(P); }while(0) #else #define INIT_COOLER_AUTO_FAN_PIN(P) SET_OUTPUT(P) #endif #ifndef CHAMBER_FAN_INDEX #define CHAMBER_FAN_INDEX HOTENDS #endif void Temperature::update_autofans() { #define _EFAN(I,N) _EFANOVERLAP(I,N) ? I : static const uint8_t fanBit[] PROGMEM = { 0 #if HAS_MULTI_HOTEND #define _NEXT_FAN(N) , REPEAT2(N,_EFAN,N) N RREPEAT_S(1, HOTENDS, _NEXT_FAN) #endif #define _NFAN HOTENDS #if HAS_AUTO_CHAMBER_FAN #define _CHFAN(I) _FANOVERLAP(I,CHAMBER) ? I : , (REPEAT(HOTENDS,_CHFAN) (_NFAN)) #undef _NFAN #define _NFAN INCREMENT(HOTENDS) #endif #if HAS_AUTO_COOLER_FAN #define _COFAN(I) _FANOVERLAP(I,COOLER) ? I : , (REPEAT(HOTENDS,_COFAN) (_NFAN)) #endif }; uint8_t fanState = 0; HOTEND_LOOP() { if (temp_hotend[e].celsius >= EXTRUDER_AUTO_FAN_TEMPERATURE) SBI(fanState, pgm_read_byte(&fanBit[e])); } #if HAS_AUTO_CHAMBER_FAN if (temp_chamber.celsius >= CHAMBER_AUTO_FAN_TEMPERATURE) SBI(fanState, pgm_read_byte(&fanBit[CHAMBER_FAN_INDEX])); #endif #if HAS_AUTO_COOLER_FAN if (temp_cooler.celsius >= COOLER_AUTO_FAN_TEMPERATURE) SBI(fanState, pgm_read_byte(&fanBit[COOLER_FAN_INDEX])); #endif #define _UPDATE_AUTO_FAN(P,D,A) do{ \ if (PWM_PIN(P##_AUTO_FAN_PIN) && A < 255) \ hal.set_pwm_duty(pin_t(P##_AUTO_FAN_PIN), D ? A : 0); \ else \ WRITE(P##_AUTO_FAN_PIN, D); \ }while(0) uint8_t fanDone = 0; for (uint8_t f = 0; f < COUNT(fanBit); ++f) { const uint8_t realFan = pgm_read_byte(&fanBit[f]); if (TEST(fanDone, realFan)) continue; const bool fan_on = TEST(fanState, realFan); switch (f) { #if ENABLED(AUTO_POWER_CHAMBER_FAN) case CHAMBER_FAN_INDEX: chamberfan_speed = fan_on ? CHAMBER_AUTO_FAN_SPEED : 0; break; #endif #if ENABLED(AUTO_POWER_COOLER_FAN) case COOLER_FAN_INDEX: coolerfan_speed = fan_on ? COOLER_AUTO_FAN_SPEED : 0; break; #endif default: #if ANY(AUTO_POWER_E_FANS, HAS_FANCHECK) autofan_speed[realFan] = fan_on ? EXTRUDER_AUTO_FAN_SPEED : 0; #endif break; } #if ALL(HAS_FANCHECK, HAS_PWMFANCHECK) #define _AUTOFAN_SPEED() fan_check.is_measuring() ? 255 : EXTRUDER_AUTO_FAN_SPEED #else #define _AUTOFAN_SPEED() EXTRUDER_AUTO_FAN_SPEED #endif #define _AUTOFAN_CASE(N) case N: _UPDATE_AUTO_FAN(E##N, fan_on, _AUTOFAN_SPEED()); break; #define _AUTOFAN_NOT(N) #define AUTOFAN_CASE(N) TERN(HAS_AUTO_FAN_##N, _AUTOFAN_CASE, _AUTOFAN_NOT)(N) switch (f) { REPEAT(HOTENDS, AUTOFAN_CASE) #if HAS_AUTO_CHAMBER_FAN && !AUTO_CHAMBER_IS_E case CHAMBER_FAN_INDEX: _UPDATE_AUTO_FAN(CHAMBER, fan_on, CHAMBER_AUTO_FAN_SPEED); break; #endif #if HAS_AUTO_COOLER_FAN && !AUTO_COOLER_IS_E case COOLER_FAN_INDEX: _UPDATE_AUTO_FAN(COOLER, fan_on, COOLER_AUTO_FAN_SPEED); break; #endif } SBI(fanDone, realFan); } } #endif // HAS_AUTO_FAN // // Temperature Error Handlers // inline void loud_kill(FSTR_P const lcd_msg, const heater_id_t heater_id) { marlin_state = MF_KILLED; thermalManager.disable_all_heaters(); #if HAS_BEEPER for (uint8_t i = 20; i--;) { hal.watchdog_refresh(); buzzer.click(25); delay(80); hal.watchdog_refresh(); } buzzer.on(); #endif #if ENABLED(NOZZLE_PARK_FEATURE) if (!homing_needed_error()) { nozzle.park(0); planner.synchronize(); } #endif #define _FSTR_BED(h) TERN(HAS_HEATED_BED, (h) == H_BED ? GET_TEXT_F(MSG_BED) :,) #define _FSTR_CHAMBER(h) TERN(HAS_HEATED_CHAMBER, (h) == H_CHAMBER ? GET_TEXT_F(MSG_CHAMBER) :,) #define _FSTR_COOLER(h) TERN(HAS_COOLER, (h) == H_COOLER ? GET_TEXT_F(MSG_COOLER) :,) #define _FSTR_E(h,N) TERN(HAS_HOTEND, ((h) == N && (HOTENDS) > N) ? F(STR_E##N) :,) #define HEATER_FSTR(h) _FSTR_BED(h) _FSTR_CHAMBER(h) _FSTR_COOLER(h) \ _FSTR_E(h,1) _FSTR_E(h,2) _FSTR_E(h,3) _FSTR_E(h,4) \ _FSTR_E(h,5) _FSTR_E(h,6) _FSTR_E(h,7) F(STR_E0) kill(lcd_msg, HEATER_FSTR(heater_id)); } void Temperature::_temp_error( const heater_id_t heater_id, FSTR_P const serial_msg, FSTR_P const lcd_msg OPTARG(ERR_INCLUDE_TEMP, const celsius_float_t deg) ) { static uint8_t killed = 0; if (IsRunning() && TERN1(BOGUS_TEMPERATURE_GRACE_PERIOD, killed == 2)) { SERIAL_ERROR_START(); SERIAL_ECHO(serial_msg); SERIAL_ECHOPGM(STR_STOPPED_HEATER); heater_id_t real_heater_id = heater_id; #if HAS_TEMP_REDUNDANT if (heater_id == H_REDUNDANT) { SERIAL_ECHOPGM(STR_REDUNDANT); // print redundant and cascade to print target, too. real_heater_id = (heater_id_t)HEATER_ID(TEMP_SENSOR_REDUNDANT_TARGET); } #endif switch (real_heater_id) { OPTCODE(HAS_TEMP_COOLER, case H_COOLER: SERIAL_ECHOPGM(STR_COOLER); break) OPTCODE(HAS_TEMP_PROBE, case H_PROBE: SERIAL_ECHOPGM(STR_PROBE); break) OPTCODE(HAS_TEMP_BOARD, case H_BOARD: SERIAL_ECHOPGM(STR_MOTHERBOARD); break) OPTCODE(HAS_TEMP_SOC, case H_SOC: SERIAL_ECHOPGM(STR_SOC); break) OPTCODE(HAS_TEMP_CHAMBER, case H_CHAMBER: SERIAL_ECHOPGM(STR_HEATER_CHAMBER); break) OPTCODE(HAS_TEMP_BED, case H_BED: SERIAL_ECHOPGM(STR_HEATER_BED); break) default: if (real_heater_id >= 0) SERIAL_ECHO(C('E'), real_heater_id); } #if ENABLED(ERR_INCLUDE_TEMP) SERIAL_ECHOLNPGM(STR_DETECTED_TEMP_B, deg, STR_DETECTED_TEMP_E); #else SERIAL_EOL(); #endif } disable_all_heaters(); // always disable (even for bogus temp) hal.watchdog_refresh(); #if BOGUS_TEMPERATURE_GRACE_PERIOD const millis_t ms = millis(); static millis_t expire_ms; switch (killed) { case 0: expire_ms = ms + BOGUS_TEMPERATURE_GRACE_PERIOD; ++killed; break; case 1: if (ELAPSED(ms, expire_ms)) ++killed; break; case 2: loud_kill(lcd_msg, heater_id); ++killed; break; } #elif defined(BOGUS_TEMPERATURE_GRACE_PERIOD) UNUSED(killed); #else if (!killed) { killed = 1; loud_kill(lcd_msg, heater_id); } #endif } void Temperature::maxtemp_error(const heater_id_t heater_id OPTARG(ERR_INCLUDE_TEMP, const celsius_float_t deg)) { #if HAS_HOTEND || HAS_HEATED_BED TERN_(DWIN_CREALITY_LCD, dwinPopupTemperature(1)); TERN_(EXTENSIBLE_UI, ExtUI::onMaxTempError(heater_id)); #endif _TEMP_ERROR(heater_id, F(STR_T_MAXTEMP), MSG_ERR_MAXTEMP, deg); } void Temperature::mintemp_error(const heater_id_t heater_id OPTARG(ERR_INCLUDE_TEMP, const celsius_float_t deg)) { #if HAS_HOTEND || HAS_HEATED_BED TERN_(DWIN_CREALITY_LCD, dwinPopupTemperature(0)); TERN_(EXTENSIBLE_UI, ExtUI::onMinTempError(heater_id)); #endif _TEMP_ERROR(heater_id, F(STR_T_MINTEMP), MSG_ERR_MINTEMP, deg); } #if HAS_PID_DEBUG bool Temperature::pid_debug_flag; // = false #endif #if HAS_PID_HEATING template<typename TT> class PIDRunner { public: TT &tempinfo; PIDRunner(TT &t) : tempinfo(t) { } float get_pid_output(const uint8_t extr=0) { #if ENABLED(PID_OPENLOOP) return constrain(tempinfo.target, 0, MAX_POW); #else // !PID_OPENLOOP float out = tempinfo.pid.get_pid_output(tempinfo.target, tempinfo.celsius); #if ENABLED(PID_FAN_SCALING) out += tempinfo.pid.get_fan_scale_output(thermalManager.fan_speed[extr]); #endif #if ENABLED(PID_EXTRUSION_SCALING) out += tempinfo.pid.get_extrusion_scale_output( extr == active_extruder, stepper.position(E_AXIS), planner.mm_per_step[E_AXIS], thermalManager.lpq_len ); #endif return constrain(out, tempinfo.pid.low(), tempinfo.pid.high()); #endif // !PID_OPENLOOP } FORCE_INLINE void debug(const_celsius_float_t c, const_float_t pid_out, FSTR_P const name=nullptr, const int8_t index=-1) { if (TERN0(HAS_PID_DEBUG, thermalManager.pid_debug_flag)) { SERIAL_ECHO_START(); if (name) SERIAL_ECHO(name); if (index >= 0) SERIAL_ECHO(index); SERIAL_ECHOLNPGM( STR_PID_DEBUG_INPUT, c, STR_PID_DEBUG_OUTPUT, pid_out #if DISABLED(PID_OPENLOOP) , " pTerm ", tempinfo.pid.pTerm(), " iTerm ", tempinfo.pid.iTerm(), " dTerm ", tempinfo.pid.dTerm() , " cTerm ", tempinfo.pid.cTerm(), " fTerm ", tempinfo.pid.fTerm() #endif ); } } }; #endif // HAS_PID_HEATING #if HAS_HOTEND float Temperature::get_pid_output_hotend(const uint8_t E_NAME) { const uint8_t ee = HOTEND_INDEX; const bool is_idling = TERN0(HEATER_IDLE_HANDLER, heater_idle[ee].timed_out); #if ENABLED(PIDTEMP) typedef PIDRunner<hotend_info_t> PIDRunnerHotend; static PIDRunnerHotend hotend_pid[HOTENDS] = { #define _HOTENDPID(E) temp_hotend[E], REPEAT(HOTENDS, _HOTENDPID) }; const float pid_output = is_idling ? 0 : hotend_pid[ee].get_pid_output(ee); #if ENABLED(PID_DEBUG) if (ee == active_extruder) hotend_pid[ee].debug(temp_hotend[ee].celsius, pid_output, F("E"), ee); #endif #elif ENABLED(MPCTEMP) MPCHeaterInfo &hotend = temp_hotend[ee]; MPC_t &mpc = hotend.mpc; // At startup, initialize modeled temperatures if (isnan(hotend.modeled_block_temp)) { hotend.modeled_ambient_temp = _MIN(30.0f, hotend.celsius); // Cap initial value at reasonable max room temperature of 30C hotend.modeled_block_temp = hotend.modeled_sensor_temp = hotend.celsius; } #if HOTENDS == 1 constexpr bool this_hotend = true; #else const bool this_hotend = (ee == active_extruder); #endif float ambient_xfer_coeff = mpc.ambient_xfer_coeff_fan0; #if ENABLED(MPC_INCLUDE_FAN) const uint8_t fan_index = TERN(SINGLEFAN, 0, ee); const float fan_fraction = TERN_(MPC_FAN_0_ACTIVE_HOTEND, !this_hotend ? 0.0f : ) fan_speed[fan_index] * RECIPROCAL(255); ambient_xfer_coeff += fan_fraction * mpc.fan255_adjustment; #endif if (this_hotend) { const int32_t e_position = stepper.position(E_AXIS); const float e_speed = (e_position - MPC::e_position) * planner.mm_per_step[E_AXIS] / MPC_dT; // The position can appear to make big jumps when, e.g., homing if (fabs(e_speed) > planner.settings.max_feedrate_mm_s[E_AXIS]) MPC::e_position = e_position; else if (e_speed > 0.0f) { // Ignore retract/recover moves if (!MPC::e_paused) ambient_xfer_coeff += e_speed * mpc.filament_heat_capacity_permm; MPC::e_position = e_position; } } // Update the modeled temperatures float blocktempdelta = hotend.soft_pwm_amount * mpc.heater_power * (MPC_dT / 127) / mpc.block_heat_capacity; blocktempdelta += (hotend.modeled_ambient_temp - hotend.modeled_block_temp) * ambient_xfer_coeff * MPC_dT / mpc.block_heat_capacity; hotend.modeled_block_temp += blocktempdelta; const float sensortempdelta = (hotend.modeled_block_temp - hotend.modeled_sensor_temp) * (mpc.sensor_responsiveness * MPC_dT); hotend.modeled_sensor_temp += sensortempdelta; // Any delta between hotend.modeled_sensor_temp and hotend.celsius is either model // error diverging slowly or (fast) noise. Slowly correct towards this temperature and noise will average out. const float delta_to_apply = (hotend.celsius - hotend.modeled_sensor_temp) * (MPC_SMOOTHING_FACTOR); hotend.modeled_block_temp += delta_to_apply; hotend.modeled_sensor_temp += delta_to_apply; // Only correct ambient when close to steady state (output power is not clipped or asymptotic temperature is reached) if (WITHIN(hotend.soft_pwm_amount, 1, 126) || fabs(blocktempdelta + delta_to_apply) < (MPC_STEADYSTATE * MPC_dT)) hotend.modeled_ambient_temp += delta_to_apply > 0.f ? _MAX(delta_to_apply, MPC_MIN_AMBIENT_CHANGE * MPC_dT) : _MIN(delta_to_apply, -MPC_MIN_AMBIENT_CHANGE * MPC_dT); float power = 0.0; if (hotend.target != 0 && !is_idling) { // Plan power level to get to target temperature in 2 seconds power = (hotend.target - hotend.modeled_block_temp) * mpc.block_heat_capacity / 2.0f; power -= (hotend.modeled_ambient_temp - hotend.modeled_block_temp) * ambient_xfer_coeff; } float pid_output = power * 254.0f / mpc.heater_power + 1.0f; // Ensure correct quantization into a range of 0 to 127 LIMIT(pid_output, 0, MPC_MAX); /* <-- add a slash to enable static uint32_t nexttime = millis() + 1000; if (ELAPSED(millis(), nexttime)) { nexttime += 1000; SERIAL_ECHOLNPGM("block temp ", hotend.modeled_block_temp, ", celsius ", hotend.celsius, ", blocktempdelta ", blocktempdelta, ", delta_to_apply ", delta_to_apply, ", ambient ", hotend.modeled_ambient_temp, ", power ", power, ", pid_output ", pid_output, ", pwm ", (int)pid_output >> 1); } //*/ #else // No PID or MPC enabled const float pid_output = (!is_idling && temp_hotend[ee].is_below_target()) ? BANG_MAX : 0; #endif return pid_output; } #endif // HAS_HOTEND #if ENABLED(PIDTEMPBED) float Temperature::get_pid_output_bed() { static PIDRunner<bed_info_t> bed_pid(temp_bed); const float pid_output = bed_pid.get_pid_output(); TERN_(PID_BED_DEBUG, bed_pid.debug(temp_bed.celsius, pid_output, F("(Bed)"))); return pid_output; } #endif // PIDTEMPBED #if ENABLED(PIDTEMPCHAMBER) float Temperature::get_pid_output_chamber() { static PIDRunner<chamber_info_t> chamber_pid(temp_chamber); const float pid_output = chamber_pid.get_pid_output(); TERN_(PID_CHAMBER_DEBUG, chamber_pid.debug(temp_chamber.celsius, pid_output, F("(Chamber)"))); return pid_output; } #endif // PIDTEMPCHAMBER #if HAS_HOTEND void Temperature::manage_hotends(const millis_t &ms) { HOTEND_LOOP() { #if ENABLED(THERMAL_PROTECTION_HOTENDS) { const auto deg = degHotend(e); if (deg > temp_range[e].maxtemp) MAXTEMP_ERROR(e, deg); } #endif TERN_(HEATER_IDLE_HANDLER, heater_idle[e].update(ms)); #if ENABLED(THERMAL_PROTECTION_HOTENDS) // Check for thermal runaway tr_state_machine[e].run(temp_hotend[e].celsius, temp_hotend[e].target, (heater_id_t)e, THERMAL_PROTECTION_PERIOD, THERMAL_PROTECTION_HYSTERESIS); #endif temp_hotend[e].soft_pwm_amount = (temp_hotend[e].celsius > temp_range[e].mintemp || is_hotend_preheating(e)) && temp_hotend[e].celsius < temp_range[e].maxtemp ? (int)get_pid_output_hotend(e) >> 1 : 0; #if WATCH_HOTENDS // Make sure temperature is increasing if (watch_hotend[e].elapsed(ms)) { // Enabled and time to check? auto temp = degHotend(e); if (watch_hotend[e].check(temp)) // Increased enough? start_watching_hotend(e); // If temp reached, turn off elapsed check else { TERN_(DWIN_CREALITY_LCD, dwinPopupTemperature(0)); TERN_(EXTENSIBLE_UI, ExtUI::onHeatingError(e)); _TEMP_ERROR(e, FPSTR(str_t_heating_failed), MSG_ERR_HEATING_FAILED, temp); } } #endif } // HOTEND_LOOP } #endif // HAS_HOTEND #if HAS_HEATED_BED void Temperature::manage_heated_bed(const millis_t &ms) { #if ENABLED(THERMAL_PROTECTION_BED) { const auto deg = degBed(); if (deg > BED_MAXTEMP) MAXTEMP_ERROR(H_BED, deg); } #endif #if WATCH_BED { // Make sure temperature is increasing if (watch_bed.elapsed(ms)) { // Time to check the bed? const auto deg = degBed(); if (watch_bed.check(deg)) // Increased enough? start_watching_bed(); // If temp reached, turn off elapsed check else { TERN_(DWIN_CREALITY_LCD, dwinPopupTemperature(0)); TERN_(EXTENSIBLE_UI, ExtUI::onHeatingError(H_BED)); _TEMP_ERROR(H_BED, FPSTR(str_t_heating_failed), MSG_ERR_HEATING_FAILED, deg); } } } #endif // WATCH_BED #if ALL(PROBING_HEATERS_OFF, BED_LIMIT_SWITCHING) #define PAUSE_CHANGE_REQD 1 #endif #if PAUSE_CHANGE_REQD static bool last_pause_state; #endif do { #if DISABLED(PIDTEMPBED) if (PENDING(ms, next_bed_check_ms) && TERN1(PAUSE_CHANGE_REQD, paused_for_probing == last_pause_state) ) break; next_bed_check_ms = ms + BED_CHECK_INTERVAL; TERN_(PAUSE_CHANGE_REQD, last_pause_state = paused_for_probing); #endif TERN_(HEATER_IDLE_HANDLER, heater_idle[IDLE_INDEX_BED].update(ms)); #if ENABLED(THERMAL_PROTECTION_BED) tr_state_machine[RUNAWAY_IND_BED].run(temp_bed.celsius, temp_bed.target, H_BED, THERMAL_PROTECTION_BED_PERIOD, THERMAL_PROTECTION_BED_HYSTERESIS); #endif #if HEATER_IDLE_HANDLER const bool bed_timed_out = heater_idle[IDLE_INDEX_BED].timed_out; if (bed_timed_out) { temp_bed.soft_pwm_amount = 0; if (DISABLED(PIDTEMPBED)) WRITE_HEATER_BED(LOW); } #else constexpr bool bed_timed_out = false; #endif if (!bed_timed_out) { if (is_bed_preheating()) { temp_bed.soft_pwm_amount = MAX_BED_POWER >> 1; } else { #if ENABLED(PIDTEMPBED) temp_bed.soft_pwm_amount = WITHIN(temp_bed.celsius, BED_MINTEMP, BED_MAXTEMP) ? (int)get_pid_output_bed() >> 1 : 0; #else // Check if temperature is within the correct band if (WITHIN(temp_bed.celsius, BED_MINTEMP, BED_MAXTEMP)) { #if ENABLED(BED_LIMIT_SWITCHING) // Range-limited "bang-bang" bed heating if (temp_bed.is_above_target(BED_HYSTERESIS)) temp_bed.soft_pwm_amount = 0; else if (temp_bed.is_below_target(BED_HYSTERESIS)) temp_bed.soft_pwm_amount = MAX_BED_POWER >> 1; #else // !PIDTEMPBED && !BED_LIMIT_SWITCHING // Simple (noisy) "bang-bang" bed heating temp_bed.soft_pwm_amount = temp_bed.is_below_target() ? MAX_BED_POWER >> 1 : 0; #endif } else { temp_bed.soft_pwm_amount = 0; WRITE_HEATER_BED(LOW); } #endif } } } while (false); } #endif // HAS_HEATED_BED #if HAS_HEATED_CHAMBER void Temperature::manage_heated_chamber(const millis_t &ms) { #ifndef CHAMBER_CHECK_INTERVAL #define CHAMBER_CHECK_INTERVAL 1000UL #endif #if ENABLED(THERMAL_PROTECTION_CHAMBER) { const auto deg = degChamber(); if (deg > CHAMBER_MAXTEMP) MAXTEMP_ERROR(H_CHAMBER, deg); } #endif #if WATCH_CHAMBER { // Make sure temperature is increasing if (watch_chamber.elapsed(ms)) { // Time to check the chamber? const auto deg = degChamber(); if (watch_chamber.check(deg)) // Increased enough? Error below. start_watching_chamber(); // If temp reached, turn off elapsed check. else _TEMP_ERROR(H_CHAMBER, FPSTR(str_t_heating_failed), MSG_ERR_HEATING_FAILED, deg); } } #endif #if ANY(CHAMBER_FAN, CHAMBER_VENT) || DISABLED(PIDTEMPCHAMBER) static bool flag_chamber_excess_heat; // = false; #endif #if ANY(CHAMBER_FAN, CHAMBER_VENT) static bool flag_chamber_off; // = false if (temp_chamber.target > CHAMBER_MINTEMP) { flag_chamber_off = false; #if ENABLED(CHAMBER_FAN) int16_t fan_chamber_pwm; #if CHAMBER_FAN_MODE == 0 fan_chamber_pwm = CHAMBER_FAN_BASE; #elif CHAMBER_FAN_MODE == 1 fan_chamber_pwm = temp_chamber.is_above_target() ? (CHAMBER_FAN_BASE) + (CHAMBER_FAN_FACTOR) * (temp_chamber.celsius - temp_chamber.target) : 0; #elif CHAMBER_FAN_MODE == 2 fan_chamber_pwm = (CHAMBER_FAN_BASE) + (CHAMBER_FAN_FACTOR) * ABS(temp_chamber.celsius - temp_chamber.target); if (temp_chamber.soft_pwm_amount) fan_chamber_pwm += (CHAMBER_FAN_FACTOR) * 2; #elif CHAMBER_FAN_MODE == 3 fan_chamber_pwm = (CHAMBER_FAN_BASE) + _MAX((CHAMBER_FAN_FACTOR) * (temp_chamber.celsius - temp_chamber.target), 0); #endif NOMORE(fan_chamber_pwm, 255); set_fan_speed(CHAMBER_FAN_INDEX, fan_chamber_pwm); #endif #if ENABLED(CHAMBER_VENT) #ifndef MIN_COOLING_SLOPE_TIME_CHAMBER_VENT #define MIN_COOLING_SLOPE_TIME_CHAMBER_VENT 20 #endif #ifndef MIN_COOLING_SLOPE_DEG_CHAMBER_VENT #define MIN_COOLING_SLOPE_DEG_CHAMBER_VENT 1.5 #endif if (!flag_chamber_excess_heat && temp_chamber.is_above_target(HIGH_EXCESS_HEAT_LIMIT)) { // Open vent after MIN_COOLING_SLOPE_TIME_CHAMBER_VENT seconds if the // temperature didn't drop at least MIN_COOLING_SLOPE_DEG_CHAMBER_VENT if (next_cool_check_ms == 0 || ELAPSED(ms, next_cool_check_ms)) { if (temp_chamber.celsius - old_temp > MIN_COOLING_SLOPE_DEG_CHAMBER_VENT) flag_chamber_excess_heat = true; // the bed is heating the chamber too much next_cool_check_ms = ms + SEC_TO_MS(MIN_COOLING_SLOPE_TIME_CHAMBER_VENT); old_temp = temp_chamber.celsius; } } else { next_cool_check_ms = 0; old_temp = 9999; } if (flag_chamber_excess_heat && temp_chamber.is_above_target(LOW_EXCESS_HEAT_LIMIT)) flag_chamber_excess_heat = false; #endif } else if (!flag_chamber_off) { #if ENABLED(CHAMBER_FAN) flag_chamber_off = true; set_fan_speed(CHAMBER_FAN_INDEX, 0); #endif #if ENABLED(CHAMBER_VENT) flag_chamber_excess_heat = false; servo[CHAMBER_VENT_SERVO_NR].move(90); #endif } #endif #if ENABLED(PIDTEMPCHAMBER) // PIDTEMPCHAMBER doesn't support a CHAMBER_VENT yet. temp_chamber.soft_pwm_amount = WITHIN(temp_chamber.celsius, CHAMBER_MINTEMP, CHAMBER_MAXTEMP) ? (int)get_pid_output_chamber() >> 1 : 0; #else if (ELAPSED(ms, next_chamber_check_ms)) { next_chamber_check_ms = ms + CHAMBER_CHECK_INTERVAL; if (WITHIN(temp_chamber.celsius, CHAMBER_MINTEMP, CHAMBER_MAXTEMP)) { if (flag_chamber_excess_heat) { temp_chamber.soft_pwm_amount = 0; #if ENABLED(CHAMBER_VENT) if (!flag_chamber_off) servo[CHAMBER_VENT_SERVO_NR].move(temp_chamber.is_below_target() ? 0 : 90); #endif } else { #if ENABLED(CHAMBER_LIMIT_SWITCHING) if (temp_chamber.is_above_target(TEMP_CHAMBER_HYSTERESIS)) temp_chamber.soft_pwm_amount = 0; else if (temp_chamber.is_below_target(TEMP_CHAMBER_HYSTERESIS)) temp_chamber.soft_pwm_amount = (MAX_CHAMBER_POWER) >> 1; #else temp_chamber.soft_pwm_amount = temp_chamber.is_below_target() ? (MAX_CHAMBER_POWER) >> 1 : 0; #endif #if ENABLED(CHAMBER_VENT) if (!flag_chamber_off) servo[CHAMBER_VENT_SERVO_NR].move(0); #endif } } else { temp_chamber.soft_pwm_amount = 0; WRITE_HEATER_CHAMBER(LOW); } } #if ENABLED(THERMAL_PROTECTION_CHAMBER) tr_state_machine[RUNAWAY_IND_CHAMBER].run(temp_chamber.celsius, temp_chamber.target, H_CHAMBER, THERMAL_PROTECTION_CHAMBER_PERIOD, THERMAL_PROTECTION_CHAMBER_HYSTERESIS); #endif #endif } #endif // HAS_HEATED_CHAMBER #if HAS_COOLER void Temperature::manage_cooler(const millis_t &ms) { #ifndef COOLER_CHECK_INTERVAL #define COOLER_CHECK_INTERVAL 2000UL #endif #if ENABLED(THERMAL_PROTECTION_COOLER) { const auto deg = degCooler(); if (deg > COOLER_MAXTEMP) MAXTEMP_ERROR(H_COOLER, deg); } #endif #if WATCH_COOLER // Make sure temperature is decreasing if (watch_cooler.elapsed(ms)) { // Time to check the cooler? const auto deg = degCooler(); if (deg > watch_cooler.target) // Failed to decrease enough? _TEMP_ERROR(H_COOLER, GET_TEXT_F(MSG_ERR_COOLING_FAILED), MSG_ERR_COOLING_FAILED, deg); else start_watching_cooler(); // Start again if the target is still far off } #endif static bool flag_cooler_state; // = false if (cooler.enabled) { flag_cooler_state = true; // used to allow M106 fan control when cooler is disabled if (temp_cooler.target == 0) temp_cooler.target = COOLER_MIN_TARGET; if (ELAPSED(ms, next_cooler_check_ms)) { next_cooler_check_ms = ms + COOLER_CHECK_INTERVAL; if (temp_cooler.is_above_target()) { // too warm? temp_cooler.soft_pwm_amount = MAX_COOLER_POWER; #if ENABLED(COOLER_FAN) const int16_t fan_cooler_pwm = (COOLER_FAN_BASE) + (COOLER_FAN_FACTOR) * ABS(temp_cooler.celsius - temp_cooler.target); set_fan_speed(COOLER_FAN_INDEX, _MIN(fan_cooler_pwm, 255)); // Set cooler fan pwm cooler_fan_flush_ms = ms + 5000; #endif } else { temp_cooler.soft_pwm_amount = 0; #if ENABLED(COOLER_FAN) set_fan_speed(COOLER_FAN_INDEX, temp_cooler.is_above_target(-2) ? COOLER_FAN_BASE : 0); #endif WRITE_HEATER_COOLER(LOW); } } } else { temp_cooler.soft_pwm_amount = 0; if (flag_cooler_state) { flag_cooler_state = false; thermalManager.set_fan_speed(COOLER_FAN_INDEX, 0); } WRITE_HEATER_COOLER(LOW); } #if ENABLED(THERMAL_PROTECTION_COOLER) tr_state_machine[RUNAWAY_IND_COOLER].run(temp_cooler.celsius, temp_cooler.target, H_COOLER, THERMAL_PROTECTION_COOLER_PERIOD, THERMAL_PROTECTION_COOLER_HYSTERESIS); #endif } #endif // HAS_COOLER /** * Manage heating activities for extruder hot-ends and a heated bed * - Acquire updated temperature readings * - Also resets the watchdog timer * - Invoke thermal runaway protection * - Manage extruder auto-fan * - Apply filament width to the extrusion rate (may move) * - Update the heated bed PID output value */ void Temperature::task() { if (marlin_state == MF_INITIALIZING) return hal.watchdog_refresh(); // If Marlin isn't started, at least reset the watchdog! static bool no_reentry = false; // Prevent recursion if (no_reentry) return; REMEMBER(mh, no_reentry, true); #if ENABLED(EMERGENCY_PARSER) if (emergency_parser.killed_by_M112) kill(FPSTR(M112_KILL_STR), nullptr, true); if (emergency_parser.quickstop_by_M410) { emergency_parser.quickstop_by_M410 = false; // quickstop_stepper may call idle so clear this now! quickstop_stepper(); } #if HAS_MEDIA if (emergency_parser.sd_abort_by_M524) { // abort SD print immediately emergency_parser.sd_abort_by_M524 = false; card.flag.abort_sd_printing = true; gcode.process_subcommands_now(F("M524")); } #endif #endif if (!updateTemperaturesIfReady()) return; // Will also reset the watchdog if temperatures are ready #if DISABLED(IGNORE_THERMOCOUPLE_ERRORS) #if TEMP_SENSOR_IS_MAX_TC(0) { const auto deg = degHotend(0); if (deg > _MIN(HEATER_0_MAXTEMP, TEMP_SENSOR_0_MAX_TC_TMAX - 1.00f)) MAXTEMP_ERROR(H_E0, deg); if (deg < _MAX(HEATER_0_MINTEMP, TEMP_SENSOR_0_MAX_TC_TMIN + 0.01f)) MINTEMP_ERROR(H_E0, deg); } #endif #if TEMP_SENSOR_IS_MAX_TC(1) { const auto deg = degHotend(1); if (deg > _MIN(HEATER_1_MAXTEMP, TEMP_SENSOR_1_MAX_TC_TMAX - 1.00f)) MAXTEMP_ERROR(H_E1, deg); if (deg < _MAX(HEATER_1_MINTEMP, TEMP_SENSOR_1_MAX_TC_TMIN + 0.01f)) MINTEMP_ERROR(H_E1, deg); } #endif #if TEMP_SENSOR_IS_MAX_TC(2) { const auto deg = degHotend(2); if (deg > _MIN(HEATER_2_MAXTEMP, TEMP_SENSOR_2_MAX_TC_TMAX - 1.00f)) MAXTEMP_ERROR(H_E2, deg); if (deg < _MAX(HEATER_2_MINTEMP, TEMP_SENSOR_2_MAX_TC_TMIN + 0.01f)) MINTEMP_ERROR(H_E2, deg); } #endif #if TEMP_SENSOR_IS_MAX_TC(REDUNDANT) { const auto deg = degRedundant(); if (deg > TEMP_SENSOR_REDUNDANT_MAX_TC_TMAX - 1.00f) MAXTEMP_ERROR(H_REDUNDANT, deg); if (deg < TEMP_SENSOR_REDUNDANT_MAX_TC_TMIN + 0.01f) MINTEMP_ERROR(H_REDUNDANT, deg); } #endif #if TEMP_SENSOR_IS_MAX_TC(BED) { const auto deg = degBed(); if (deg > _MIN(BED_MAXTEMP, TEMP_SENSOR_BED_MAX_TC_TMAX - 1.00f)) MAXTEMP_ERROR(H_BED, deg); if (deg < _MAX(BED_MINTEMP, TEMP_SENSOR_BED_MAX_TC_TMIN + 0.01f)) MINTEMP_ERROR(H_BED, deg); } #endif #endif const millis_t ms = millis(); // Handle Hotend Temp Errors, Heating Watch, etc. TERN_(HAS_HOTEND, manage_hotends(ms)); #if HAS_TEMP_REDUNDANT { const auto deg = degRedundant(); // Make sure measured temperatures are close together if (ABS(degRedundantTarget() - deg) > TEMP_SENSOR_REDUNDANT_MAX_DIFF) _TEMP_ERROR(HEATER_ID(TEMP_SENSOR_REDUNDANT_TARGET), F(STR_REDUNDANCY), MSG_ERR_REDUNDANT_TEMP, deg); } #endif // Manage extruder auto fans and/or read fan tachometers TERN_(HAS_FAN_LOGIC, manage_extruder_fans(ms)); /** * Dynamically set the volumetric multiplier based * on the delayed Filament Width measurement. */ TERN_(FILAMENT_WIDTH_SENSOR, filwidth.update_volumetric()); // Handle Bed Temp Errors, Heating Watch, etc. TERN_(HAS_HEATED_BED, manage_heated_bed(ms)); // Handle Heated Chamber Temp Errors, Heating Watch, etc. TERN_(HAS_HEATED_CHAMBER, manage_heated_chamber(ms)); // Handle Cooler Temp Errors, Cooling Watch, etc. TERN_(HAS_COOLER, manage_cooler(ms)); #if ENABLED(LASER_COOLANT_FLOW_METER) cooler.flowmeter_task(ms); #if ENABLED(FLOWMETER_SAFETY) if (cooler.check_flow_too_low()) { TERN_(HAS_DISPLAY, if (cutter.enabled()) ui.flow_fault()); cutter.disable(); cutter.cutter_mode = CUTTER_MODE_ERROR; // Immediately kill stepper inline power output } #endif #endif UNUSED(ms); } // For a 5V input the AD595 returns a value scaled with 10mV per °C. (Minimum input voltage is 5V.) #define TEMP_AD595(RAW) ((RAW) * (ADC_VREF_MV / 10) / float(HAL_ADC_RANGE) / (OVERSAMPLENR) * (TEMP_SENSOR_AD595_GAIN) + TEMP_SENSOR_AD595_OFFSET) // For a 5V input the AD8495 returns a value scaled with 5mV per °C. (Minimum input voltage is 2.7V.) #define TEMP_AD8495(RAW) ((RAW) * (ADC_VREF_MV / 5) / float(HAL_ADC_RANGE) / (OVERSAMPLENR) * (TEMP_SENSOR_AD8495_GAIN) + TEMP_SENSOR_AD8495_OFFSET) /** * Bisect search for the range of the 'raw' value, then interpolate * proportionally between the under and over values. */ #define SCAN_THERMISTOR_TABLE(TBL,LEN) do{ \ uint8_t l = 0, r = LEN, m; \ for (;;) { \ m = (l + r) >> 1; \ if (!m) return celsius_t(pgm_read_word(&TBL[0].celsius)); \ if (m == l || m == r) return celsius_t(pgm_read_word(&TBL[LEN-1].celsius)); \ raw_adc_t v00 = pgm_read_word(&TBL[m-1].value), \ v10 = pgm_read_word(&TBL[m-0].value); \ if (raw < v00) r = m; \ else if (raw > v10) l = m; \ else { \ const celsius_t v01 = celsius_t(pgm_read_word(&TBL[m-1].celsius)), \ v11 = celsius_t(pgm_read_word(&TBL[m-0].celsius)); \ return v01 + (raw - v00) * float(v11 - v01) / float(v10 - v00); \ } \ } \ }while(0) #if HAS_USER_THERMISTORS user_thermistor_t Temperature::user_thermistor[USER_THERMISTORS]; // Initialized by settings.load() void Temperature::reset_user_thermistors() { user_thermistor_t default_user_thermistor[USER_THERMISTORS] = { #if TEMP_SENSOR_0_IS_CUSTOM { true, HOTEND0_SH_C_COEFF, 0, HOTEND0_PULLUP_RESISTOR_OHMS, HOTEND0_RESISTANCE_25C_OHMS, 0, 0, HOTEND0_BETA, 0 }, #endif #if TEMP_SENSOR_1_IS_CUSTOM { true, HOTEND1_SH_C_COEFF, 0, HOTEND1_PULLUP_RESISTOR_OHMS, HOTEND1_RESISTANCE_25C_OHMS, 0, 0, HOTEND1_BETA, 0 }, #endif #if TEMP_SENSOR_2_IS_CUSTOM { true, HOTEND2_SH_C_COEFF, 0, HOTEND2_PULLUP_RESISTOR_OHMS, HOTEND2_RESISTANCE_25C_OHMS, 0, 0, HOTEND2_BETA, 0 }, #endif #if TEMP_SENSOR_3_IS_CUSTOM { true, HOTEND3_SH_C_COEFF, 0, HOTEND3_PULLUP_RESISTOR_OHMS, HOTEND3_RESISTANCE_25C_OHMS, 0, 0, HOTEND3_BETA, 0 }, #endif #if TEMP_SENSOR_4_IS_CUSTOM { true, HOTEND4_SH_C_COEFF, 0, HOTEND4_PULLUP_RESISTOR_OHMS, HOTEND4_RESISTANCE_25C_OHMS, 0, 0, HOTEND4_BETA, 0 }, #endif #if TEMP_SENSOR_5_IS_CUSTOM { true, HOTEND5_SH_C_COEFF, 0, HOTEND5_PULLUP_RESISTOR_OHMS, HOTEND5_RESISTANCE_25C_OHMS, 0, 0, HOTEND5_BETA, 0 }, #endif #if TEMP_SENSOR_6_IS_CUSTOM { true, HOTEND6_SH_C_COEFF, 0, HOTEND6_PULLUP_RESISTOR_OHMS, HOTEND6_RESISTANCE_25C_OHMS, 0, 0, HOTEND6_BETA, 0 }, #endif #if TEMP_SENSOR_7_IS_CUSTOM { true, HOTEND7_SH_C_COEFF, 0, HOTEND7_PULLUP_RESISTOR_OHMS, HOTEND7_RESISTANCE_25C_OHMS, 0, 0, HOTEND7_BETA, 0 }, #endif #if TEMP_SENSOR_BED_IS_CUSTOM { true, BED_SH_C_COEFF, 0, BED_PULLUP_RESISTOR_OHMS, BED_RESISTANCE_25C_OHMS, 0, 0, BED_BETA, 0 }, #endif #if TEMP_SENSOR_CHAMBER_IS_CUSTOM { true, CHAMBER_SH_C_COEFF, 0, CHAMBER_PULLUP_RESISTOR_OHMS, CHAMBER_RESISTANCE_25C_OHMS, 0, 0, CHAMBER_BETA, 0 }, #endif #if TEMP_SENSOR_COOLER_IS_CUSTOM { true, COOLER_SH_C_COEFF, 0, COOLER_PULLUP_RESISTOR_OHMS, COOLER_RESISTANCE_25C_OHMS, 0, 0, COOLER_BETA, 0 }, #endif #if TEMP_SENSOR_PROBE_IS_CUSTOM { true, PROBE_SH_C_COEFF, 0, PROBE_PULLUP_RESISTOR_OHMS, PROBE_RESISTANCE_25C_OHMS, 0, 0, PROBE_BETA, 0 }, #endif #if TEMP_SENSOR_BOARD_IS_CUSTOM { true, BOARD_SH_C_COEFF, 0, BOARD_PULLUP_RESISTOR_OHMS, BOARD_RESISTANCE_25C_OHMS, 0, 0, BOARD_BETA, 0 }, #endif #if TEMP_SENSOR_REDUNDANT_IS_CUSTOM { true, REDUNDANT_SH_C_COEFF, 0, REDUNDANT_PULLUP_RESISTOR_OHMS, REDUNDANT_RESISTANCE_25C_OHMS, 0, 0, REDUNDANT_BETA, 0 }, #endif }; COPY(user_thermistor, default_user_thermistor); } void Temperature::M305_report(const uint8_t t_index, const bool forReplay/*=true*/) { TERN_(MARLIN_SMALL_BUILD, return); gcode.report_heading_etc(forReplay, F(STR_USER_THERMISTORS)); SERIAL_ECHOPGM(" M305 P", AS_DIGIT(t_index)); const user_thermistor_t &t = user_thermistor[t_index]; SERIAL_ECHO( F(" R"), p_float_t(t.series_res, 1), FPSTR(SP_T_STR), p_float_t(t.res_25, 1), FPSTR(SP_B_STR), p_float_t(t.beta, 1), FPSTR(SP_C_STR), p_float_t(t.sh_c_coeff, 9), F(" ; ") ); SERIAL_ECHOLN( TERN_(TEMP_SENSOR_0_IS_CUSTOM, t_index == CTI_HOTEND_0 ? F("HOTEND 0") :) TERN_(TEMP_SENSOR_1_IS_CUSTOM, t_index == CTI_HOTEND_1 ? F("HOTEND 1") :) TERN_(TEMP_SENSOR_2_IS_CUSTOM, t_index == CTI_HOTEND_2 ? F("HOTEND 2") :) TERN_(TEMP_SENSOR_3_IS_CUSTOM, t_index == CTI_HOTEND_3 ? F("HOTEND 3") :) TERN_(TEMP_SENSOR_4_IS_CUSTOM, t_index == CTI_HOTEND_4 ? F("HOTEND 4") :) TERN_(TEMP_SENSOR_5_IS_CUSTOM, t_index == CTI_HOTEND_5 ? F("HOTEND 5") :) TERN_(TEMP_SENSOR_6_IS_CUSTOM, t_index == CTI_HOTEND_6 ? F("HOTEND 6") :) TERN_(TEMP_SENSOR_7_IS_CUSTOM, t_index == CTI_HOTEND_7 ? F("HOTEND 7") :) TERN_(TEMP_SENSOR_BED_IS_CUSTOM, t_index == CTI_BED ? F("BED") :) TERN_(TEMP_SENSOR_CHAMBER_IS_CUSTOM, t_index == CTI_CHAMBER ? F("CHAMBER") :) TERN_(TEMP_SENSOR_COOLER_IS_CUSTOM, t_index == CTI_COOLER ? F("COOLER") :) TERN_(TEMP_SENSOR_PROBE_IS_CUSTOM, t_index == CTI_PROBE ? F("PROBE") :) TERN_(TEMP_SENSOR_BOARD_IS_CUSTOM, t_index == CTI_BOARD ? F("BOARD") :) TERN_(TEMP_SENSOR_REDUNDANT_IS_CUSTOM, t_index == CTI_REDUNDANT ? F("REDUNDANT") :) FSTR_P(nullptr) ); } celsius_float_t Temperature::user_thermistor_to_deg_c(const uint8_t t_index, const raw_adc_t raw) { if (!WITHIN(t_index, 0, COUNT(user_thermistor) - 1)) return 25; user_thermistor_t &t = user_thermistor[t_index]; if (t.pre_calc) { // pre-calculate some variables t.pre_calc = false; t.res_25_recip = 1.0f / t.res_25; t.res_25_log = logf(t.res_25); t.beta_recip = 1.0f / t.beta; t.sh_alpha = RECIPROCAL(THERMISTOR_RESISTANCE_NOMINAL_C - (THERMISTOR_ABS_ZERO_C)) - (t.beta_recip * t.res_25_log) - (t.sh_c_coeff * cu(t.res_25_log)); } // Maximum ADC value .. take into account the over sampling constexpr raw_adc_t adc_max = MAX_RAW_THERMISTOR_VALUE; const raw_adc_t adc_raw = constrain(raw, 1, adc_max - 1); // constrain to prevent divide-by-zero const float adc_inverse = (adc_max - adc_raw) - 0.5f, resistance = t.series_res * (adc_raw + 0.5f) / adc_inverse, log_resistance = logf(resistance); float value = t.sh_alpha; value += log_resistance * t.beta_recip; if (t.sh_c_coeff != 0) value += t.sh_c_coeff * cu(log_resistance); value = 1.0f / value; // Return degrees C (up to 999, as the LCD only displays 3 digits) return _MIN(value + THERMISTOR_ABS_ZERO_C, 999); } #endif #if HAS_HOTEND // Derived from RepRap FiveD extruder::getTemperature() // For hot end temperature measurement. celsius_float_t Temperature::analog_to_celsius_hotend(const raw_adc_t raw, const uint8_t e) { if (e >= HOTENDS) { SERIAL_ERROR_START(); SERIAL_ECHO(e); SERIAL_ECHOLNPGM(STR_INVALID_EXTRUDER_NUM); kill(); return 0; } switch (e) { case 0: #if TEMP_SENSOR_0_IS_CUSTOM return user_thermistor_to_deg_c(CTI_HOTEND_0, raw); #elif TEMP_SENSOR_IS_MAX_TC(0) #if TEMP_SENSOR_0_IS_MAX31865 return TERN(LIB_INTERNAL_MAX31865, max31865_0.temperature(raw), max31865_0.temperature(MAX31865_SENSOR_OHMS_0, MAX31865_CALIBRATION_OHMS_0) ); #else return (int16_t)raw * 0.25f; #endif #elif TEMP_SENSOR_0_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_0_IS_AD8495 return TEMP_AD8495(raw); #else break; #endif case 1: #if TEMP_SENSOR_1_IS_CUSTOM return user_thermistor_to_deg_c(CTI_HOTEND_1, raw); #elif TEMP_SENSOR_IS_MAX_TC(1) #if TEMP_SENSOR_0_IS_MAX31865 return TERN(LIB_INTERNAL_MAX31865, max31865_1.temperature(raw), max31865_1.temperature(MAX31865_SENSOR_OHMS_1, MAX31865_CALIBRATION_OHMS_1) ); #else return (int16_t)raw * 0.25f; #endif #elif TEMP_SENSOR_1_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_1_IS_AD8495 return TEMP_AD8495(raw); #else break; #endif case 2: #if TEMP_SENSOR_2_IS_CUSTOM return user_thermistor_to_deg_c(CTI_HOTEND_2, raw); #elif TEMP_SENSOR_IS_MAX_TC(2) #if TEMP_SENSOR_0_IS_MAX31865 return TERN(LIB_INTERNAL_MAX31865, max31865_2.temperature(raw), max31865_2.temperature(MAX31865_SENSOR_OHMS_2, MAX31865_CALIBRATION_OHMS_2) ); #else return (int16_t)raw * 0.25f; #endif #elif TEMP_SENSOR_2_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_2_IS_AD8495 return TEMP_AD8495(raw); #else break; #endif case 3: #if TEMP_SENSOR_3_IS_CUSTOM return user_thermistor_to_deg_c(CTI_HOTEND_3, raw); #elif TEMP_SENSOR_3_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_3_IS_AD8495 return TEMP_AD8495(raw); #else break; #endif case 4: #if TEMP_SENSOR_4_IS_CUSTOM return user_thermistor_to_deg_c(CTI_HOTEND_4, raw); #elif TEMP_SENSOR_4_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_4_IS_AD8495 return TEMP_AD8495(raw); #else break; #endif case 5: #if TEMP_SENSOR_5_IS_CUSTOM return user_thermistor_to_deg_c(CTI_HOTEND_5, raw); #elif TEMP_SENSOR_5_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_5_IS_AD8495 return TEMP_AD8495(raw); #else break; #endif case 6: #if TEMP_SENSOR_6_IS_CUSTOM return user_thermistor_to_deg_c(CTI_HOTEND_6, raw); #elif TEMP_SENSOR_6_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_6_IS_AD8495 return TEMP_AD8495(raw); #else break; #endif case 7: #if TEMP_SENSOR_7_IS_CUSTOM return user_thermistor_to_deg_c(CTI_HOTEND_7, raw); #elif TEMP_SENSOR_7_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_7_IS_AD8495 return TEMP_AD8495(raw); #else break; #endif default: break; } #if HAS_HOTEND_THERMISTOR // Thermistor with conversion table? const temp_entry_t(*tt)[] = (temp_entry_t(*)[])(heater_ttbl_map[e]); SCAN_THERMISTOR_TABLE((*tt), heater_ttbllen_map[e]); #endif return 0; } #endif // HAS_HOTEND #if HAS_HEATED_BED // For bed temperature measurement. celsius_float_t Temperature::analog_to_celsius_bed(const raw_adc_t raw) { #if TEMP_SENSOR_BED_IS_CUSTOM return user_thermistor_to_deg_c(CTI_BED, raw); #elif TEMP_SENSOR_IS_MAX_TC(BED) #if TEMP_SENSOR_BED_IS_MAX31865 return TERN(LIB_INTERNAL_MAX31865, max31865_BED.temperature(raw), max31865_BED.temperature(MAX31865_SENSOR_OHMS_BED, MAX31865_CALIBRATION_OHMS_BED) ); #else return (int16_t)raw * 0.25f; #endif #elif TEMP_SENSOR_BED_IS_THERMISTOR SCAN_THERMISTOR_TABLE(TEMPTABLE_BED, TEMPTABLE_BED_LEN); #elif TEMP_SENSOR_BED_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_BED_IS_AD8495 return TEMP_AD8495(raw); #else UNUSED(raw); return 0; #endif } #endif // HAS_HEATED_BED #if HAS_TEMP_CHAMBER // For chamber temperature measurement. celsius_float_t Temperature::analog_to_celsius_chamber(const raw_adc_t raw) { #if TEMP_SENSOR_CHAMBER_IS_CUSTOM return user_thermistor_to_deg_c(CTI_CHAMBER, raw); #elif TEMP_SENSOR_CHAMBER_IS_THERMISTOR SCAN_THERMISTOR_TABLE(TEMPTABLE_CHAMBER, TEMPTABLE_CHAMBER_LEN); #elif TEMP_SENSOR_CHAMBER_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_CHAMBER_IS_AD8495 return TEMP_AD8495(raw); #else UNUSED(raw); return 0; #endif } #endif // HAS_TEMP_CHAMBER #if HAS_TEMP_COOLER // For cooler temperature measurement. celsius_float_t Temperature::analog_to_celsius_cooler(const raw_adc_t raw) { #if TEMP_SENSOR_COOLER_IS_CUSTOM return user_thermistor_to_deg_c(CTI_COOLER, raw); #elif TEMP_SENSOR_COOLER_IS_THERMISTOR SCAN_THERMISTOR_TABLE(TEMPTABLE_COOLER, TEMPTABLE_COOLER_LEN); #elif TEMP_SENSOR_COOLER_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_COOLER_IS_AD8495 return TEMP_AD8495(raw); #else UNUSED(raw); return 0; #endif } #endif // HAS_TEMP_COOLER #if HAS_TEMP_PROBE // For probe temperature measurement. celsius_float_t Temperature::analog_to_celsius_probe(const raw_adc_t raw) { #if TEMP_SENSOR_PROBE_IS_CUSTOM return user_thermistor_to_deg_c(CTI_PROBE, raw); #elif TEMP_SENSOR_PROBE_IS_THERMISTOR SCAN_THERMISTOR_TABLE(TEMPTABLE_PROBE, TEMPTABLE_PROBE_LEN); #elif TEMP_SENSOR_PROBE_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_PROBE_IS_AD8495 return TEMP_AD8495(raw); #else UNUSED(raw); return 0; #endif } #endif // HAS_TEMP_PROBE #if HAS_TEMP_BOARD // For motherboard temperature measurement. celsius_float_t Temperature::analog_to_celsius_board(const raw_adc_t raw) { #if TEMP_SENSOR_BOARD_IS_CUSTOM return user_thermistor_to_deg_c(CTI_BOARD, raw); #elif TEMP_SENSOR_BOARD_IS_THERMISTOR SCAN_THERMISTOR_TABLE(TEMPTABLE_BOARD, TEMPTABLE_BOARD_LEN); #elif TEMP_SENSOR_BOARD_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_BOARD_IS_AD8495 return TEMP_AD8495(raw); #else UNUSED(raw); return 0; #endif } #endif // HAS_TEMP_BOARD #if HAS_TEMP_SOC // For SoC temperature measurement. celsius_float_t Temperature::analog_to_celsius_soc(const raw_adc_t raw) { return ( #ifdef TEMP_SOC_SENSOR TEMP_SOC_SENSOR(raw) #else 0 #error "TEMP_SENSOR_SOC requires the TEMP_SOC_SENSOR(RAW) macro to be defined for your board." #endif ); } #endif #if HAS_TEMP_REDUNDANT // For redundant temperature measurement. celsius_float_t Temperature::analog_to_celsius_redundant(const raw_adc_t raw) { #if TEMP_SENSOR_REDUNDANT_IS_CUSTOM return user_thermistor_to_deg_c(CTI_REDUNDANT, raw); #elif TEMP_SENSOR_IS_MAX_TC(REDUNDANT) && REDUNDANT_TEMP_MATCH(SOURCE, E0) return TERN(TEMP_SENSOR_REDUNDANT_IS_MAX31865, max31865_0.temperature(raw), (int16_t)raw * 0.25f); #elif TEMP_SENSOR_IS_MAX_TC(REDUNDANT) && REDUNDANT_TEMP_MATCH(SOURCE, E1) return TERN(TEMP_SENSOR_REDUNDANT_IS_MAX31865, max31865_1.temperature(raw), (int16_t)raw * 0.25f); #elif TEMP_SENSOR_IS_MAX_TC(REDUNDANT) && REDUNDANT_TEMP_MATCH(SOURCE, E2) return TERN(TEMP_SENSOR_REDUNDANT_IS_MAX31865, max31865_2.temperature(raw), (int16_t)raw * 0.25f); #elif TEMP_SENSOR_REDUNDANT_IS_THERMISTOR SCAN_THERMISTOR_TABLE(TEMPTABLE_REDUNDANT, TEMPTABLE_REDUNDANT_LEN); #elif TEMP_SENSOR_REDUNDANT_IS_AD595 return TEMP_AD595(raw); #elif TEMP_SENSOR_REDUNDANT_IS_AD8495 return TEMP_AD8495(raw); #else UNUSED(raw); return 0; #endif } #endif // HAS_TEMP_REDUNDANT /** * Convert the raw sensor readings into actual Celsius temperatures and * validate raw temperatures. Bad readings generate min/maxtemp errors. * * The raw values are generated entirely in interrupt context, and this * method is called from normal context once 'raw_temps_ready' has been * set by update_raw_temperatures(). * * The watchdog is dependent on this method. If 'raw_temps_ready' stops * being set by the interrupt so that this method is not called for over * 4 seconds then something has gone afoul and the machine will be reset. */ void Temperature::updateTemperaturesFromRawValues() { hal.watchdog_refresh(); // Reset because raw_temps_ready was set by the interrupt #if TEMP_SENSOR_IS_MAX_TC(0) temp_hotend[0].setraw(READ_MAX_TC(0)); #endif #if TEMP_SENSOR_IS_MAX_TC(1) temp_hotend[1].setraw(READ_MAX_TC(1)); #endif #if TEMP_SENSOR_IS_MAX_TC(2) temp_hotend[2].setraw(READ_MAX_TC(2)); #endif #if TEMP_SENSOR_IS_MAX_TC(REDUNDANT) temp_redundant.setraw(READ_MAX_TC(HEATER_ID(TEMP_SENSOR_REDUNDANT_SOURCE))); #endif #if TEMP_SENSOR_IS_MAX_TC(BED) temp_bed.setraw(read_max_tc_bed()); #endif #if HAS_HOTEND HOTEND_LOOP() temp_hotend[e].celsius = analog_to_celsius_hotend(temp_hotend[e].getraw(), e); #endif TERN_(HAS_HEATED_BED, temp_bed.celsius = analog_to_celsius_bed(temp_bed.getraw())); TERN_(HAS_TEMP_CHAMBER, temp_chamber.celsius = analog_to_celsius_chamber(temp_chamber.getraw())); TERN_(HAS_TEMP_COOLER, temp_cooler.celsius = analog_to_celsius_cooler(temp_cooler.getraw())); TERN_(HAS_TEMP_PROBE, temp_probe.celsius = analog_to_celsius_probe(temp_probe.getraw())); TERN_(HAS_TEMP_BOARD, temp_board.celsius = analog_to_celsius_board(temp_board.getraw())); TERN_(HAS_TEMP_SOC, temp_soc.celsius = analog_to_celsius_soc(temp_soc.getraw())); TERN_(HAS_TEMP_REDUNDANT, temp_redundant.celsius = analog_to_celsius_redundant(temp_redundant.getraw())); TERN_(FILAMENT_WIDTH_SENSOR, filwidth.update_measured_mm()); TERN_(HAS_POWER_MONITOR, power_monitor.capture_values()); #if HAS_HOTEND #define _TEMPDIR(N) TEMP_SENSOR_IS_ANY_MAX_TC(N) ? 0 : TEMPDIR(N), static constexpr int8_t temp_dir[HOTENDS] = { REPEAT(HOTENDS, _TEMPDIR) }; HOTEND_LOOP() { const raw_adc_t r = temp_hotend[e].getraw(); const bool neg = temp_dir[e] < 0, pos = temp_dir[e] > 0; if ((neg && r < temp_range[e].raw_max) || (pos && r > temp_range[e].raw_max)) MAXTEMP_ERROR(e, temp_hotend[e].celsius); /** // DEBUG PREHEATING TIME SERIAL_ECHOLNPGM("\nExtruder = ", e, " Preheat On/Off = ", is_preheating(e)); const float test_is_preheating = (preheat_end_ms_hotend[HOTEND_INDEX] - millis()) * 0.001f; if (test_is_preheating < 31) SERIAL_ECHOLNPGM("Extruder = ", e, " Preheat remaining time = ", test_is_preheating, "s", "\n"); //*/ const bool heater_on = temp_hotend[e].target > 0; if (heater_on && !is_hotend_preheating(e) && ((neg && r > temp_range[e].raw_min) || (pos && r < temp_range[e].raw_min))) { if (TERN1(MULTI_MAX_CONSECUTIVE_LOW_TEMP_ERR, ++consecutive_low_temperature_error[e] >= MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED)) MINTEMP_ERROR(e, temp_hotend[e].celsius); } else { TERN_(MULTI_MAX_CONSECUTIVE_LOW_TEMP_ERR, consecutive_low_temperature_error[e] = 0); } } #endif // HAS_HOTEND #if ENABLED(THERMAL_PROTECTION_BED) if (TP_CMP(BED, temp_bed.getraw(), temp_sensor_range_bed.raw_max)) MAXTEMP_ERROR(H_BED, temp_bed.celsius); if (temp_bed.target > 0 && !is_bed_preheating() && TP_CMP(BED, temp_sensor_range_bed.raw_min, temp_bed.getraw())) MINTEMP_ERROR(H_BED, temp_bed.celsius); #endif #if ALL(HAS_HEATED_CHAMBER, THERMAL_PROTECTION_CHAMBER) if (TP_CMP(CHAMBER, temp_chamber.getraw(), temp_sensor_range_chamber.raw_max)) MAXTEMP_ERROR(H_CHAMBER, temp_chamber.celsius); if (temp_chamber.target > 0 && TP_CMP(CHAMBER, temp_sensor_range_chamber.raw_min, temp_chamber.getraw())) MINTEMP_ERROR(H_CHAMBER, temp_chamber.celsius); #endif #if ALL(HAS_COOLER, THERMAL_PROTECTION_COOLER) if (cutter.unitPower > 0 && TP_CMP(COOLER, temp_cooler.getraw(), temp_sensor_range_cooler.raw_max)) MAXTEMP_ERROR(H_COOLER, temp_cooler.celsius); if (TP_CMP(COOLER, temp_sensor_range_cooler.raw_min, temp_cooler.getraw())) MINTEMP_ERROR(H_COOLER, temp_cooler.celsius); #endif #if ALL(HAS_TEMP_BOARD, THERMAL_PROTECTION_BOARD) if (TP_CMP(BOARD, temp_board.getraw(), temp_sensor_range_board.raw_max)) MAXTEMP_ERROR(H_BOARD, temp_board.celsius); if (TP_CMP(BOARD, temp_sensor_range_board.raw_min, temp_board.getraw())) MINTEMP_ERROR(H_BOARD, temp_board.celsius); #endif #if ALL(HAS_TEMP_SOC, THERMAL_PROTECTION_SOC) if (TP_CMP(SOC, temp_soc.getraw(), maxtemp_raw_SOC)) MAXTEMP_ERROR(H_SOC, temp_soc.celsius); #endif } // Temperature::updateTemperaturesFromRawValues /** * Initialize the temperature manager * * The manager is implemented by periodic calls to task() * * - Init (and disable) SPI thermocouples like MAX6675 and MAX31865 * - Disable RUMBA JTAG to accommodate a thermocouple extension * - Read-enable thermistors with a read-enable pin * - Init HEATER and COOLER pins for OUTPUT in OFF state * - Init the FAN pins as PWM or OUTPUT * - Init the SPI interface for SPI thermocouples * - Init ADC according to the HAL * - Set thermistor pins to analog inputs according to the HAL * - Start the Temperature ISR timer * - Init the AUTO FAN pins as PWM or OUTPUT * - Wait 250ms for temperatures to settle * - Init temp_range[], used for catching min/maxtemp */ void Temperature::init() { TERN_(PROBING_HEATERS_OFF, paused_for_probing = false); // Init (and disable) SPI thermocouples #if TEMP_SENSOR_IS_ANY_MAX_TC(0) && PIN_EXISTS(TEMP_0_CS) OUT_WRITE(TEMP_0_CS_PIN, HIGH); #endif #if TEMP_SENSOR_IS_ANY_MAX_TC(1) && PIN_EXISTS(TEMP_1_CS) OUT_WRITE(TEMP_1_CS_PIN, HIGH); #endif #if TEMP_SENSOR_IS_ANY_MAX_TC(2) && PIN_EXISTS(TEMP_2_CS) OUT_WRITE(TEMP_2_CS_PIN, HIGH); #endif // Setup objects for library-based polling of MAX TCs #if HAS_MAXTC_LIBRARIES #define _MAX31865_WIRES(n) MAX31865_##n##WIRE #define MAX31865_WIRES(n) _MAX31865_WIRES(n) #if TEMP_SENSOR_IS_MAX(0, 6675) && HAS_MAX6675_LIBRARY max6675_0.begin(); #elif TEMP_SENSOR_IS_MAX(0, 31855) && HAS_MAX31855_LIBRARY max31855_0.begin(); #elif TEMP_SENSOR_IS_MAX(0, 31865) max31865_0.begin( MAX31865_WIRES(MAX31865_SENSOR_WIRES_0) // MAX31865_2WIRE, MAX31865_3WIRE, MAX31865_4WIRE OPTARG(LIB_INTERNAL_MAX31865, MAX31865_SENSOR_OHMS_0, MAX31865_CALIBRATION_OHMS_0, MAX31865_WIRE_OHMS_0) ); #endif #if TEMP_SENSOR_IS_MAX(1, 6675) && HAS_MAX6675_LIBRARY max6675_1.begin(); #elif TEMP_SENSOR_IS_MAX(1, 31855) && HAS_MAX31855_LIBRARY max31855_1.begin(); #elif TEMP_SENSOR_IS_MAX(1, 31865) max31865_1.begin( MAX31865_WIRES(MAX31865_SENSOR_WIRES_1) // MAX31865_2WIRE, MAX31865_3WIRE, MAX31865_4WIRE OPTARG(LIB_INTERNAL_MAX31865, MAX31865_SENSOR_OHMS_1, MAX31865_CALIBRATION_OHMS_1, MAX31865_WIRE_OHMS_1) ); #endif #if TEMP_SENSOR_IS_MAX(2, 6675) && HAS_MAX6675_LIBRARY max6675_2.begin(); #elif TEMP_SENSOR_IS_MAX(2, 31855) && HAS_MAX31855_LIBRARY max31855_2.begin(); #elif TEMP_SENSOR_IS_MAX(2, 31865) max31865_2.begin( MAX31865_WIRES(MAX31865_SENSOR_WIRES_2) // MAX31865_2WIRE, MAX31865_3WIRE, MAX31865_4WIRE OPTARG(LIB_INTERNAL_MAX31865, MAX31865_SENSOR_OHMS_2, MAX31865_CALIBRATION_OHMS_2, MAX31865_WIRE_OHMS_2) ); #endif #if TEMP_SENSOR_IS_MAX(BED, 6675) && HAS_MAX6675_LIBRARY max6675_BED.begin(); #elif TEMP_SENSOR_IS_MAX(BED, 31855) && HAS_MAX31855_LIBRARY max31855_BED.begin(); #elif TEMP_SENSOR_IS_MAX(BED, 31865) max31865_BED.begin( MAX31865_WIRES(MAX31865_SENSOR_WIRES_BED) // MAX31865_BEDWIRE, MAX31865_3WIRE, MAX31865_4WIRE OPTARG(LIB_INTERNAL_MAX31865, MAX31865_SENSOR_OHMS_BED, MAX31865_CALIBRATION_OHMS_BED, MAX31865_WIRE_OHMS_BED) ); #endif #undef MAX31865_WIRES #undef _MAX31865_WIRES #endif #if MB(RUMBA) // Disable RUMBA JTAG in case the thermocouple extension is plugged on top of JTAG connector #define _AD(N) (TEMP_SENSOR_##N##_IS_AD595 || TEMP_SENSOR_##N##_IS_AD8495) #if _AD(0) || _AD(1) || _AD(2) || _AD(BED) || _AD(CHAMBER) || _AD(REDUNDANT) MCUCR = _BV(JTD); MCUCR = _BV(JTD); #endif #endif // Thermistor activation by MCU pin #if PIN_EXISTS(TEMP_0_TR_ENABLE) OUT_WRITE(TEMP_0_TR_ENABLE_PIN, ( #if TEMP_SENSOR_IS_ANY_MAX_TC(0) HIGH #else LOW #endif )); #endif #if PIN_EXISTS(TEMP_1_TR_ENABLE) OUT_WRITE(TEMP_1_TR_ENABLE_PIN, ( #if TEMP_SENSOR_IS_ANY_MAX_TC(1) HIGH #else LOW #endif )); #endif #if PIN_EXISTS(TEMP_2_TR_ENABLE) OUT_WRITE(TEMP_2_TR_ENABLE_PIN, ( #if TEMP_SENSOR_IS_ANY_MAX_TC(2) HIGH #else LOW #endif )); #endif #if ENABLED(MPCTEMP) HOTEND_LOOP() temp_hotend[e].modeled_block_temp = NAN; #endif #if HAS_HEATER_0 #ifdef BOARD_OPENDRAIN_MOSFETS OUT_WRITE_OD(HEATER_0_PIN, ENABLED(HEATER_0_INVERTING)); #else OUT_WRITE(HEATER_0_PIN, ENABLED(HEATER_0_INVERTING)); #endif #endif #if HAS_HEATER_1 OUT_WRITE(HEATER_1_PIN, ENABLED(HEATER_1_INVERTING)); #endif #if HAS_HEATER_2 OUT_WRITE(HEATER_2_PIN, ENABLED(HEATER_2_INVERTING)); #endif #if HAS_HEATER_3 OUT_WRITE(HEATER_3_PIN, ENABLED(HEATER_3_INVERTING)); #endif #if HAS_HEATER_4 OUT_WRITE(HEATER_4_PIN, ENABLED(HEATER_4_INVERTING)); #endif #if HAS_HEATER_5 OUT_WRITE(HEATER_5_PIN, ENABLED(HEATER_5_INVERTING)); #endif #if HAS_HEATER_6 OUT_WRITE(HEATER_6_PIN, ENABLED(HEATER_6_INVERTING)); #endif #if HAS_HEATER_7 OUT_WRITE(HEATER_7_PIN, ENABLED(HEATER_7_INVERTING)); #endif #if HAS_HEATED_BED #ifdef BOARD_OPENDRAIN_MOSFETS OUT_WRITE_OD(HEATER_BED_PIN, ENABLED(HEATER_BED_INVERTING)); #else OUT_WRITE(HEATER_BED_PIN, ENABLED(HEATER_BED_INVERTING)); #endif #endif #if HAS_HEATED_CHAMBER OUT_WRITE(HEATER_CHAMBER_PIN, ENABLED(HEATER_CHAMBER_INVERTING)); #endif #if HAS_COOLER OUT_WRITE(COOLER_PIN, ENABLED(COOLER_INVERTING)); #endif #if HAS_FAN0 INIT_FAN_PIN(FAN0_PIN); #endif #if HAS_FAN1 INIT_FAN_PIN(FAN1_PIN); #endif #if HAS_FAN2 INIT_FAN_PIN(FAN2_PIN); #endif #if HAS_FAN3 INIT_FAN_PIN(FAN3_PIN); #endif #if HAS_FAN4 INIT_FAN_PIN(FAN4_PIN); #endif #if HAS_FAN5 INIT_FAN_PIN(FAN5_PIN); #endif #if HAS_FAN6 INIT_FAN_PIN(FAN6_PIN); #endif #if HAS_FAN7 INIT_FAN_PIN(FAN7_PIN); #endif #if ENABLED(USE_CONTROLLER_FAN) INIT_FAN_PIN(CONTROLLER_FAN_PIN); #endif TERN_(HAS_MAXTC_SW_SPI, max_tc_spi.init()); hal.adc_init(); TERN_(HAS_TEMP_ADC_0, hal.adc_enable(TEMP_0_PIN)); TERN_(HAS_TEMP_ADC_1, hal.adc_enable(TEMP_1_PIN)); TERN_(HAS_TEMP_ADC_2, hal.adc_enable(TEMP_2_PIN)); TERN_(HAS_TEMP_ADC_3, hal.adc_enable(TEMP_3_PIN)); TERN_(HAS_TEMP_ADC_4, hal.adc_enable(TEMP_4_PIN)); TERN_(HAS_TEMP_ADC_5, hal.adc_enable(TEMP_5_PIN)); TERN_(HAS_TEMP_ADC_6, hal.adc_enable(TEMP_6_PIN)); TERN_(HAS_TEMP_ADC_7, hal.adc_enable(TEMP_7_PIN)); TERN_(HAS_JOY_ADC_X, hal.adc_enable(JOY_X_PIN)); TERN_(HAS_JOY_ADC_Y, hal.adc_enable(JOY_Y_PIN)); TERN_(HAS_JOY_ADC_Z, hal.adc_enable(JOY_Z_PIN)); TERN_(HAS_TEMP_ADC_BED, hal.adc_enable(TEMP_BED_PIN)); TERN_(HAS_TEMP_ADC_CHAMBER, hal.adc_enable(TEMP_CHAMBER_PIN)); TERN_(HAS_TEMP_ADC_PROBE, hal.adc_enable(TEMP_PROBE_PIN)); TERN_(HAS_TEMP_ADC_COOLER, hal.adc_enable(TEMP_COOLER_PIN)); TERN_(HAS_TEMP_ADC_BOARD, hal.adc_enable(TEMP_BOARD_PIN)); TERN_(HAS_TEMP_ADC_SOC, hal.adc_enable(TEMP_SOC_PIN)); TERN_(HAS_TEMP_ADC_REDUNDANT, hal.adc_enable(TEMP_REDUNDANT_PIN)); TERN_(FILAMENT_WIDTH_SENSOR, hal.adc_enable(FILWIDTH_PIN)); TERN_(HAS_ADC_BUTTONS, hal.adc_enable(ADC_KEYPAD_PIN)); TERN_(POWER_MONITOR_CURRENT, hal.adc_enable(POWER_MONITOR_CURRENT_PIN)); TERN_(POWER_MONITOR_VOLTAGE, hal.adc_enable(POWER_MONITOR_VOLTAGE_PIN)); #if HAS_JOY_ADC_EN SET_INPUT_PULLUP(JOY_EN_PIN); #endif HAL_timer_start(MF_TIMER_TEMP, TEMP_TIMER_FREQUENCY); ENABLE_TEMPERATURE_INTERRUPT(); #if HAS_AUTO_FAN #define _OREFAN(I,N) || _EFANOVERLAP(I,N) #if HAS_AUTO_FAN_0 INIT_E_AUTO_FAN_PIN(E0_AUTO_FAN_PIN); #endif #if HAS_AUTO_FAN_1 && !_EFANOVERLAP(0,1) INIT_E_AUTO_FAN_PIN(E1_AUTO_FAN_PIN); #endif #if HAS_AUTO_FAN_2 && !(0 REPEAT2(2, _OREFAN, 2)) INIT_E_AUTO_FAN_PIN(E2_AUTO_FAN_PIN); #endif #if HAS_AUTO_FAN_3 && !(0 REPEAT2(3, _OREFAN, 3)) INIT_E_AUTO_FAN_PIN(E3_AUTO_FAN_PIN); #endif #if HAS_AUTO_FAN_4 && !(0 REPEAT2(4, _OREFAN, 4)) INIT_E_AUTO_FAN_PIN(E4_AUTO_FAN_PIN); #endif #if HAS_AUTO_FAN_5 && !(0 REPEAT2(5, _OREFAN, 5)) INIT_E_AUTO_FAN_PIN(E5_AUTO_FAN_PIN); #endif #if HAS_AUTO_FAN_6 && !(0 REPEAT2(6, _OREFAN, 6)) INIT_E_AUTO_FAN_PIN(E6_AUTO_FAN_PIN); #endif #if HAS_AUTO_FAN_7 && !(0 REPEAT2(7, _OREFAN, 7)) INIT_E_AUTO_FAN_PIN(E7_AUTO_FAN_PIN); #endif #if HAS_AUTO_CHAMBER_FAN && !AUTO_CHAMBER_IS_E INIT_CHAMBER_AUTO_FAN_PIN(CHAMBER_AUTO_FAN_PIN); #endif #if HAS_AUTO_COOLER_FAN && !AUTO_COOLER_IS_E INIT_COOLER_AUTO_FAN_PIN(COOLER_AUTO_FAN_PIN); #endif #endif // HAS_AUTO_FAN #if HAS_HOTEND #define _TEMP_MIN_E(NR) do{ \ const celsius_t tmin_tmp = TERN(TEMP_SENSOR_##NR##_IS_CUSTOM, 0, int16_t(pgm_read_word(&TEMPTABLE_##NR [TEMP_SENSOR_##NR##_MINTEMP_IND].celsius))), \ tmin = _MAX(HEATER_##NR##_MINTEMP, tmin_tmp); \ temp_range[NR].mintemp = tmin; \ while (analog_to_celsius_hotend(temp_range[NR].raw_min, NR) < tmin) \ temp_range[NR].raw_min += TEMPDIR(NR) * (OVERSAMPLENR); \ }while(0) #define _TEMP_MAX_E(NR) do{ \ const celsius_t tmax_tmp = TERN(TEMP_SENSOR_##NR##_IS_CUSTOM, 2000, int16_t(pgm_read_word(&TEMPTABLE_##NR [TEMP_SENSOR_##NR##_MAXTEMP_IND].celsius)) - 1), \ tmax = _MIN(HEATER_##NR##_MAXTEMP, tmax_tmp); \ temp_range[NR].maxtemp = tmax; \ while (analog_to_celsius_hotend(temp_range[NR].raw_max, NR) > tmax) \ temp_range[NR].raw_max -= TEMPDIR(NR) * (OVERSAMPLENR); \ }while(0) #define _MINMAX_TEST(N,M) (!TEMP_SENSOR_##N##_IS_DUMMY && HOTENDS > (N) && TEMP_SENSOR_##N##_IS_THERMISTOR && defined(HEATER_##N##_##M##TEMP)) #if _MINMAX_TEST(0, MIN) _TEMP_MIN_E(0); #endif #if _MINMAX_TEST(0, MAX) _TEMP_MAX_E(0); #endif #if _MINMAX_TEST(1, MIN) _TEMP_MIN_E(1); #endif #if _MINMAX_TEST(1, MAX) _TEMP_MAX_E(1); #endif #if _MINMAX_TEST(2, MIN) _TEMP_MIN_E(2); #endif #if _MINMAX_TEST(2, MAX) _TEMP_MAX_E(2); #endif #if _MINMAX_TEST(3, MIN) _TEMP_MIN_E(3); #endif #if _MINMAX_TEST(3, MAX) _TEMP_MAX_E(3); #endif #if _MINMAX_TEST(4, MIN) _TEMP_MIN_E(4); #endif #if _MINMAX_TEST(4, MAX) _TEMP_MAX_E(4); #endif #if _MINMAX_TEST(5, MIN) _TEMP_MIN_E(5); #endif #if _MINMAX_TEST(5, MAX) _TEMP_MAX_E(5); #endif #if _MINMAX_TEST(6, MIN) _TEMP_MIN_E(6); #endif #if _MINMAX_TEST(6, MAX) _TEMP_MAX_E(6); #endif #if _MINMAX_TEST(7, MIN) _TEMP_MIN_E(7); #endif #if _MINMAX_TEST(7, MAX) _TEMP_MAX_E(7); #endif #endif // HAS_HOTEND // TODO: combine these into the macros above #if HAS_HEATED_BED while (analog_to_celsius_bed(temp_sensor_range_bed.raw_min) < BED_MINTEMP) temp_sensor_range_bed.raw_min += TEMPDIR(BED) * (OVERSAMPLENR); while (analog_to_celsius_bed(temp_sensor_range_bed.raw_max) > BED_MAXTEMP) temp_sensor_range_bed.raw_max -= TEMPDIR(BED) * (OVERSAMPLENR); #endif #if HAS_HEATED_CHAMBER while (analog_to_celsius_chamber(temp_sensor_range_chamber.raw_min) < CHAMBER_MINTEMP) temp_sensor_range_chamber.raw_min += TEMPDIR(CHAMBER) * (OVERSAMPLENR); while (analog_to_celsius_chamber(temp_sensor_range_chamber.raw_max) > CHAMBER_MAXTEMP) temp_sensor_range_chamber.raw_max -= TEMPDIR(CHAMBER) * (OVERSAMPLENR); #endif #if HAS_COOLER while (analog_to_celsius_cooler(temp_sensor_range_cooler.raw_min) > COOLER_MINTEMP) temp_sensor_range_cooler.raw_min += TEMPDIR(COOLER) * (OVERSAMPLENR); while (analog_to_celsius_cooler(temp_sensor_range_cooler.raw_max) < COOLER_MAXTEMP) temp_sensor_range_cooler.raw_max -= TEMPDIR(COOLER) * (OVERSAMPLENR); #endif #if ALL(HAS_TEMP_BOARD, THERMAL_PROTECTION_BOARD) while (analog_to_celsius_board(temp_sensor_range_board.raw_min) < BOARD_MINTEMP) temp_sensor_range_board.raw_min += TEMPDIR(BOARD) * (OVERSAMPLENR); while (analog_to_celsius_board(temp_sensor_range_board.raw_max) > BOARD_MAXTEMP) temp_sensor_range_board.raw_max -= TEMPDIR(BOARD) * (OVERSAMPLENR); #endif #if ALL(HAS_TEMP_SOC, THERMAL_PROTECTION_SOC) while (analog_to_celsius_soc(maxtemp_raw_SOC) > SOC_MAXTEMP) maxtemp_raw_SOC -= OVERSAMPLENR; #endif #if HAS_TEMP_REDUNDANT temp_redundant.target = &( #if REDUNDANT_TEMP_MATCH(TARGET, COOLER) && HAS_TEMP_COOLER temp_cooler #elif REDUNDANT_TEMP_MATCH(TARGET, PROBE) && HAS_TEMP_PROBE temp_probe #elif REDUNDANT_TEMP_MATCH(TARGET, BOARD) && HAS_TEMP_BOARD temp_board #elif REDUNDANT_TEMP_MATCH(TARGET, CHAMBER) && HAS_TEMP_CHAMBER temp_chamber #elif REDUNDANT_TEMP_MATCH(TARGET, BED) && HAS_TEMP_BED temp_bed #else temp_hotend[HEATER_ID(TEMP_SENSOR_REDUNDANT_TARGET)] #endif ); #endif } #if HAS_THERMAL_PROTECTION #pragma GCC diagnostic push #if __has_cpp_attribute(fallthrough) #pragma GCC diagnostic ignored "-Wimplicit-fallthrough" #endif Temperature::tr_state_machine_t Temperature::tr_state_machine[NR_HEATER_RUNAWAY]; // = { { TRInactive, 0 } }; /** * @brief Thermal Runaway state machine for a single heater * @param current current measured temperature * @param target current target temperature * @param heater_id extruder index * @param period_seconds missed temperature allowed time * @param hysteresis_degc allowed distance from target * * TODO: Embed the last 3 parameters during init, if not less optimal */ void Temperature::tr_state_machine_t::run(const_celsius_float_t current, const_celsius_float_t target, const heater_id_t heater_id, const uint16_t period_seconds, const celsius_float_t hysteresis_degc) { #if HEATER_IDLE_HANDLER // Convert the given heater_id_t to an idle array index const IdleIndex idle_index = idle_index_for_id(heater_id); #endif /** SERIAL_ECHO_START(); SERIAL_ECHOPGM("Thermal Runaway Running. Heater ID: "); switch (heater_id) { case H_BED: SERIAL_ECHOPGM("bed"); break; case H_CHAMBER: SERIAL_ECHOPGM("chamber"); break; default: SERIAL_ECHO(heater_id); } SERIAL_ECHOLNPGM( " ; sizeof(running_temp):", sizeof(running_temp), " ; State:", state, " ; Timer:", timer, " ; Temperature:", current, " ; Target Temp:", target #if HEATER_IDLE_HANDLER , " ; Idle Timeout:", heater_idle[idle_index].timed_out #endif ); */ #if ENABLED(THERMAL_PROTECTION_VARIANCE_MONITOR) #ifdef THERMAL_PROTECTION_VARIANCE_MONITOR_PERIOD #define VARIANCE_WINDOW THERMAL_PROTECTION_VARIANCE_MONITOR_PERIOD #else #define VARIANCE_WINDOW period_seconds #endif if (state == TRMalfunction) { // temperature invariance may continue, regardless of heater state variance += ABS(current - last_temp); // no need for detection window now, a single change in variance is enough last_temp = current; if (!NEAR_ZERO(variance)) { variance_timer = millis() + SEC_TO_MS(VARIANCE_WINDOW); variance = 0.0; state = TRStable; // resume from where we detected the problem } } #endif if (TERN1(THERMAL_PROTECTION_VARIANCE_MONITOR, state != TRMalfunction)) { // If the heater idle timeout expires, restart if (TERN0(HEATER_IDLE_HANDLER, heater_idle[idle_index].timed_out)) { state = TRInactive; running_temp = 0; TERN_(THERMAL_PROTECTION_VARIANCE_MONITOR, variance_timer = 0); } else if (running_temp != target) { // If the target temperature changes, restart running_temp = target; state = target > 0 ? TRFirstHeating : TRInactive; TERN_(THERMAL_PROTECTION_VARIANCE_MONITOR, variance_timer = 0); } } switch (state) { // Inactive state waits for a target temperature to be set case TRInactive: break; // When first heating, wait for the temperature to be reached then go to Stable state case TRFirstHeating: if (current < running_temp) break; state = TRStable; // While the temperature is stable watch for a bad temperature case TRStable: { const celsius_float_t rdiff = running_temp - current; #if ENABLED(ADAPTIVE_FAN_SLOWING) if (adaptive_fan_slowing && heater_id >= 0) { const int_fast8_t fan_index = _MIN(heater_id, FAN_COUNT - 1); uint8_t scale; if (fan_speed[fan_index] == 0 || rdiff <= hysteresis_degc * 0.25f) scale = 128; else if (rdiff <= hysteresis_degc * 0.3335f) scale = 96; else if (rdiff <= hysteresis_degc * 0.5f) scale = 64; else if (rdiff <= hysteresis_degc * 0.8f) scale = 32; else scale = 0; if (TERN0(REPORT_ADAPTIVE_FAN_SLOWING, DEBUGGING(INFO))) { const uint8_t fss7 = fan_speed_scaler[fan_index] & 0x80; if (fss7 ^ (scale & 0x80)) serial_ternary(F("Adaptive Fan Slowing "), fss7, nullptr, F("de"), F("activated.\n")); } fan_speed_scaler[fan_index] = scale; } #endif // ADAPTIVE_FAN_SLOWING const millis_t now = millis(); #if ENABLED(THERMAL_PROTECTION_VARIANCE_MONITOR) if (PENDING(now, variance_timer)) { variance += ABS(current - last_temp); last_temp = current; } else { if (NEAR_ZERO(variance) && variance_timer) { // valid variance monitoring window state = TRMalfunction; break; } variance_timer = now + SEC_TO_MS(VARIANCE_WINDOW); variance = 0.0; last_temp = current; } #endif if (rdiff <= hysteresis_degc) { timer = now + SEC_TO_MS(period_seconds); break; } else if (PENDING(now, timer)) break; state = TRRunaway; } // fall through case TRRunaway: TERN_(DWIN_CREALITY_LCD, dwinPopupTemperature(0)); TERN_(EXTENSIBLE_UI, ExtUI::onHeatingError(heater_id)); _TEMP_ERROR(heater_id, FPSTR(str_t_thermal_runaway), MSG_ERR_THERMAL_RUNAWAY, current); break; #if ENABLED(THERMAL_PROTECTION_VARIANCE_MONITOR) case TRMalfunction: TERN_(DWIN_CREALITY_LCD, dwinPopupTemperature(0)); TERN_(EXTENSIBLE_UI, ExtUI::onHeatingError(heater_id)); _TEMP_ERROR(heater_id, F(STR_T_THERMAL_MALFUNCTION), MSG_ERR_TEMP_MALFUNCTION, current); break; #endif } } #pragma GCC diagnostic pop #endif // HAS_THERMAL_PROTECTION void Temperature::disable_all_heaters() { // Disable autotemp, unpause and reset everything TERN_(AUTOTEMP, planner.autotemp.enabled = false); TERN_(PROBING_HEATERS_OFF, pause_heaters(false)); #if HAS_HOTEND HOTEND_LOOP() { setTargetHotend(0, e); temp_hotend[e].soft_pwm_amount = 0; } #endif #if HAS_TEMP_HOTEND #define DISABLE_HEATER(N) WRITE_HEATER_##N(LOW); REPEAT(HOTENDS, DISABLE_HEATER); #endif #if HAS_HEATED_BED setTargetBed(0); temp_bed.soft_pwm_amount = 0; WRITE_HEATER_BED(LOW); #endif #if HAS_HEATED_CHAMBER setTargetChamber(0); temp_chamber.soft_pwm_amount = 0; WRITE_HEATER_CHAMBER(LOW); #endif #if HAS_COOLER setTargetCooler(0); temp_cooler.soft_pwm_amount = 0; WRITE_HEATER_COOLER(LOW); #endif } #if ENABLED(PRINTJOB_TIMER_AUTOSTART) bool Temperature::auto_job_over_threshold() { #if HAS_HOTEND HOTEND_LOOP() if (degTargetHotend(e) > (EXTRUDE_MINTEMP) / 2) return true; #endif return TERN0(HAS_HEATED_BED, degTargetBed() > BED_MINTEMP) || TERN0(HAS_HEATED_CHAMBER, degTargetChamber() > CHAMBER_MINTEMP); } void Temperature::auto_job_check_timer(const bool can_start, const bool can_stop) { if (auto_job_over_threshold()) { if (can_start) startOrResumeJob(); } else if (can_stop) { print_job_timer.stop(); ui.reset_status(); } } #endif // PRINTJOB_TIMER_AUTOSTART #if ENABLED(PROBING_HEATERS_OFF) void Temperature::pause_heaters(const bool p) { if (p != paused_for_probing) { paused_for_probing = p; if (p) { HOTEND_LOOP() heater_idle[e].expire(); // Timeout immediately TERN_(HAS_HEATED_BED, heater_idle[IDLE_INDEX_BED].expire()); // Timeout immediately } else { HOTEND_LOOP() reset_hotend_idle_timer(e); TERN_(HAS_HEATED_BED, reset_bed_idle_timer()); } } } #endif // PROBING_HEATERS_OFF #if ANY(SINGLENOZZLE_STANDBY_TEMP, SINGLENOZZLE_STANDBY_FAN) void Temperature::singlenozzle_change(const uint8_t old_tool, const uint8_t new_tool) { #if ENABLED(SINGLENOZZLE_STANDBY_FAN) singlenozzle_fan_speed[old_tool] = fan_speed[0]; fan_speed[0] = singlenozzle_fan_speed[new_tool]; #endif #if ENABLED(SINGLENOZZLE_STANDBY_TEMP) singlenozzle_temp[old_tool] = temp_hotend[0].target; if (singlenozzle_temp[new_tool] && singlenozzle_temp[new_tool] != singlenozzle_temp[old_tool]) { setTargetHotend(singlenozzle_temp[new_tool], 0); TERN_(AUTOTEMP, planner.autotemp_update()); set_heating_message(0); (void)wait_for_hotend(0, false); // Wait for heating or cooling } #endif } #endif // SINGLENOZZLE_STANDBY_TEMP || SINGLENOZZLE_STANDBY_FAN #if HAS_MAX_TC typedef TERN(HAS_MAX31855, uint32_t, uint16_t) max_tc_temp_t; #ifndef THERMOCOUPLE_MAX_ERRORS #define THERMOCOUPLE_MAX_ERRORS 15 #endif /** * @brief Read MAX Thermocouple temperature. * * Reads the thermocouple board via HW or SW SPI, using a library (LIB_USR_x) or raw SPI reads. * Doesn't strictly return a temperature; returns an "ADC Value" (i.e. raw register content). * * @param hindex the hotend we're referencing (if MULTI_MAX_TC) * @return integer representing the board's buffer, to be converted later if needed */ raw_adc_t Temperature::read_max_tc(TERN_(HAS_MULTI_MAX_TC, const uint8_t hindex/*=0*/)) { #define MAXTC_HEAT_INTERVAL 250UL #if HAS_MAX31855 #define MAX_TC_ERROR_MASK 7 // D2-0: SCV, SCG, OC #define MAX_TC_DISCARD_BITS 18 // Data D31-18; sign bit D31 #define MAX_TC_SPEED_BITS 3 // ~1MHz #elif HAS_MAX31865 #define MAX_TC_ERROR_MASK 1 // D0 Bit on fault only #define MAX_TC_DISCARD_BITS 1 // Data is in D15-D1 #define MAX_TC_SPEED_BITS 3 // ~1MHz #else // MAX6675 #define MAX_TC_ERROR_MASK 3 // D2 only; 1 = open circuit #define MAX_TC_DISCARD_BITS 3 // Data D15-D1 #define MAX_TC_SPEED_BITS 2 // ~2MHz #endif #if HAS_MULTI_MAX_TC // Needed to return the correct temp when this is called between readings static raw_adc_t max_tc_temp_previous[MAX_TC_COUNT] = { 0 }; #define THERMO_TEMP(I) max_tc_temp_previous[I] #if MAX_TC_COUNT > 2 #define THERMO_SEL(A,B,C) (hindex > 1 ? (C) : hindex == 1 ? (B) : (A)) #define MAXTC_CS_WRITE(V) do{ switch (hindex) { case 1: WRITE(TEMP_1_CS_PIN, V); break; case 2: WRITE(TEMP_2_CS_PIN, V); break; default: WRITE(TEMP_0_CS_PIN, V); } }while(0) #elif MAX_TC_COUNT > 1 #define THERMO_SEL(A,B,C) ( hindex == 1 ? (B) : (A)) #define MAXTC_CS_WRITE(V) do{ switch (hindex) { case 1: WRITE(TEMP_1_CS_PIN, V); break; default: WRITE(TEMP_0_CS_PIN, V); } }while(0) #endif #else // When we have only 1 max tc, THERMO_SEL will pick the appropriate sensor // variable, and MAXTC_*() macros will be hardcoded to the correct CS pin. constexpr uint8_t hindex = 0; #define THERMO_TEMP(I) max_tc_temp #if TEMP_SENSOR_IS_ANY_MAX_TC(0) #define THERMO_SEL(A,B,C) A #define MAXTC_CS_WRITE(V) WRITE(TEMP_0_CS_PIN, V) #elif TEMP_SENSOR_IS_ANY_MAX_TC(1) #define THERMO_SEL(A,B,C) B #define MAXTC_CS_WRITE(V) WRITE(TEMP_1_CS_PIN, V) #elif TEMP_SENSOR_IS_ANY_MAX_TC(2) #define THERMO_SEL(A,B,C) C #define MAXTC_CS_WRITE(V) WRITE(TEMP_2_CS_PIN, V) #endif #endif static TERN(HAS_MAX31855, uint32_t, uint16_t) max_tc_temp = THERMO_SEL( TEMP_SENSOR_0_MAX_TC_TMAX, TEMP_SENSOR_1_MAX_TC_TMAX, TEMP_SENSOR_2_MAX_TC_TMAX ); static uint8_t max_tc_errors[MAX_TC_COUNT] = { 0 }; static millis_t next_max_tc_ms[MAX_TC_COUNT] = { 0 }; // Return last-read value between readings const millis_t ms = millis(); if (PENDING(ms, next_max_tc_ms[hindex])) return THERMO_TEMP(hindex); next_max_tc_ms[hindex] = ms + MAXTC_HEAT_INTERVAL; #if !HAS_MAXTC_LIBRARIES max_tc_temp = 0; #if !HAS_MAXTC_SW_SPI // Initialize SPI using the default Hardware SPI bus. // FIXME: spiBegin, spiRec and spiInit doesn't work when soft spi is used. spiBegin(); spiInit(MAX_TC_SPEED_BITS); #endif MAXTC_CS_WRITE(LOW); // Enable MAXTC DELAY_NS(100); // Ensure 100ns delay // Read a big-endian temperature value without using a library for (uint8_t i = sizeof(max_tc_temp); i--;) { max_tc_temp |= TERN(HAS_MAXTC_SW_SPI, max_tc_spi.receive(), spiRec()); if (i > 0) max_tc_temp <<= 8; // shift left if not the last byte } MAXTC_CS_WRITE(HIGH); // Disable MAXTC #else #if HAS_MAX6675_LIBRARY MAX6675 &max6675ref = THERMO_SEL(max6675_0, max6675_1, max6675_2); max_tc_temp = max6675ref.readRaw16(); #endif #if HAS_MAX31855_LIBRARY MAX31855 &max855ref = THERMO_SEL(max31855_0, max31855_1, max31855_2); max_tc_temp = max855ref.readRaw32(); #endif #if HAS_MAX31865 MAX31865 &max865ref = THERMO_SEL(max31865_0, max31865_1, max31865_2); max_tc_temp = TERN(LIB_INTERNAL_MAX31865, max865ref.readRaw(), max865ref.readRTD_with_Fault()); #endif #endif // Handle an error. If there have been more than THERMOCOUPLE_MAX_ERRORS, send an error over serial. // Either way, return the TMAX for the thermocouple to trigger a maxtemp_error() if (max_tc_temp & MAX_TC_ERROR_MASK) { max_tc_errors[hindex]++; if (max_tc_errors[hindex] > THERMOCOUPLE_MAX_ERRORS) { SERIAL_ERROR_START(); SERIAL_ECHOPGM("Temp measurement error! "); #if HAS_MAX31855 SERIAL_ECHOPGM("MAX31855 Fault: (", max_tc_temp & 0x7, ") >> "); if (max_tc_temp & 0x1) SERIAL_ECHOLNPGM("Open Circuit"); else if (max_tc_temp & 0x2) SERIAL_ECHOLNPGM("Short to GND"); else if (max_tc_temp & 0x4) SERIAL_ECHOLNPGM("Short to VCC"); #elif HAS_MAX31865 const uint8_t fault_31865 = max865ref.readFault(); max865ref.clearFault(); if (fault_31865) { SERIAL_EOL(); SERIAL_ECHOLNPGM("\nMAX31865 Fault: (", fault_31865, ") >>"); if (fault_31865 & MAX31865_FAULT_HIGHTHRESH) SERIAL_ECHOLNPGM("RTD High Threshold"); if (fault_31865 & MAX31865_FAULT_LOWTHRESH) SERIAL_ECHOLNPGM("RTD Low Threshold"); if (fault_31865 & MAX31865_FAULT_REFINLOW) SERIAL_ECHOLNPGM("REFIN- > 0.85 x V bias"); if (fault_31865 & MAX31865_FAULT_REFINHIGH) SERIAL_ECHOLNPGM("REFIN- < 0.85 x V bias (FORCE- open)"); if (fault_31865 & MAX31865_FAULT_RTDINLOW) SERIAL_ECHOLNPGM("REFIN- < 0.85 x V bias (FORCE- open)"); if (fault_31865 & MAX31865_FAULT_OVUV) SERIAL_ECHOLNPGM("Under/Over voltage"); } #else // MAX6675 SERIAL_ECHOLNPGM("MAX6675 Fault: Open Circuit"); #endif // Set thermocouple above max temperature (TMAX) max_tc_temp = THERMO_SEL(TEMP_SENSOR_0_MAX_TC_TMAX, TEMP_SENSOR_1_MAX_TC_TMAX, TEMP_SENSOR_2_MAX_TC_TMAX) << (MAX_TC_DISCARD_BITS + 1); } } else { max_tc_errors[hindex] = 0; // No error bit, reset error count } max_tc_temp >>= MAX_TC_DISCARD_BITS; #if HAS_MAX31855 // Support negative temperature for MAX38155 if (max_tc_temp & 0x00002000) max_tc_temp |= 0xFFFFC000; #endif THERMO_TEMP(hindex) = max_tc_temp; return max_tc_temp; } #endif // HAS_MAX_TC #if TEMP_SENSOR_IS_MAX_TC(BED) /** * @brief Read MAX Thermocouple temperature. * * Reads the thermocouple board via HW or SW SPI, using a library (LIB_USR_x) or raw SPI reads. * Doesn't strictly return a temperature; returns an "ADC Value" (i.e. raw register content). * * @return integer representing the board's buffer, to be converted later if needed */ raw_adc_t Temperature::read_max_tc_bed() { #define MAXTC_HEAT_INTERVAL 250UL #if TEMP_SENSOR_BED_IS_MAX31855 #define BED_MAX_TC_ERROR_MASK 7 // D2-0: SCV, SCG, OC #define BED_MAX_TC_DISCARD_BITS 18 // Data D31-18; sign bit D31 #define BED_MAX_TC_SPEED_BITS 3 // ~1MHz #elif TEMP_SENSOR_BED_IS_MAX31865 #define BED_MAX_TC_ERROR_MASK 1 // D0 Bit on fault only #define BED_MAX_TC_DISCARD_BITS 1 // Data is in D15-D1 #define BED_MAX_TC_SPEED_BITS 3 // ~1MHz #else // MAX6675 #define BED_MAX_TC_ERROR_MASK 3 // D2 only; 1 = open circuit #define BED_MAX_TC_DISCARD_BITS 3 // Data D15-D1 #define BED_MAX_TC_SPEED_BITS 2 // ~2MHz #endif static max_tc_temp_t max_tc_temp = TEMP_SENSOR_BED_MAX_TC_TMAX; static uint8_t max_tc_errors = 0; static millis_t next_max_tc_ms = 0; // Return last-read value between readings const millis_t ms = millis(); if (PENDING(ms, next_max_tc_ms)) return max_tc_temp; next_max_tc_ms = ms + MAXTC_HEAT_INTERVAL; #if !HAS_MAXTC_LIBRARIES max_tc_temp = 0; #if !HAS_MAXTC_SW_SPI // Initialize SPI using the default Hardware SPI bus. // FIXME: spiBegin, spiRec and spiInit doesn't work when soft spi is used. spiBegin(); spiInit(BED_MAX_TC_SPEED_BITS); #endif WRITE(TEMP_BED_CS_PIN, LOW); // Enable MAXTC DELAY_NS(100); // Ensure 100ns delay // Read a big-endian temperature value without using a library for (uint8_t i = sizeof(max_tc_temp); i--;) { max_tc_temp |= TERN(HAS_MAXTC_SW_SPI, max_tc_spi.receive(), spiRec()); if (i > 0) max_tc_temp <<= 8; // shift left if not the last byte } WRITE(TEMP_BED_CS_PIN, HIGH); // Disable MAXTC #elif ALL(TEMP_SENSOR_BED_IS_MAX6675, HAS_MAX6675_LIBRARY) MAX6675 &max6675ref = max6675_BED; max_tc_temp = max6675ref.readRaw16(); #elif ALL(TEMP_SENSOR_BED_IS_MAX31855, HAS_MAX31855_LIBRARY) MAX31855 &max855ref = max31855_BED; max_tc_temp = max855ref.readRaw32(); #elif TEMP_SENSOR_BED_IS_MAX31865 MAX31865 &max865ref = max31865_BED; max_tc_temp = TERN(LIB_INTERNAL_MAX31865, max865ref.readRaw(), max865ref.readRTD_with_Fault()); #endif // Handle an error. If there have been more than THERMOCOUPLE_MAX_ERRORS, send an error over serial. // Either way, return the TMAX for the thermocouple to trigger a maxtemp_error() if (max_tc_temp & BED_MAX_TC_ERROR_MASK) { max_tc_errors++; if (max_tc_errors > THERMOCOUPLE_MAX_ERRORS) { SERIAL_ERROR_START(); SERIAL_ECHOPGM("Bed temp measurement error! "); #if TEMP_SENSOR_BED_IS_MAX31855 SERIAL_ECHOPGM("MAX31855 Fault: (", max_tc_temp & 0x7, ") >> "); if (max_tc_temp & 0x1) SERIAL_ECHOLNPGM("Open Circuit"); else if (max_tc_temp & 0x2) SERIAL_ECHOLNPGM("Short to GND"); else if (max_tc_temp & 0x4) SERIAL_ECHOLNPGM("Short to VCC"); #elif TEMP_SENSOR_BED_IS_MAX31865 const uint8_t fault_31865 = max865ref.readFault(); max865ref.clearFault(); if (fault_31865) { SERIAL_EOL(); SERIAL_ECHOLNPGM("\nMAX31865 Fault: (", fault_31865, ") >>"); if (fault_31865 & MAX31865_FAULT_HIGHTHRESH) SERIAL_ECHOLNPGM("RTD High Threshold"); if (fault_31865 & MAX31865_FAULT_LOWTHRESH) SERIAL_ECHOLNPGM("RTD Low Threshold"); if (fault_31865 & MAX31865_FAULT_REFINLOW) SERIAL_ECHOLNPGM("REFIN- > 0.85 x V bias"); if (fault_31865 & MAX31865_FAULT_REFINHIGH) SERIAL_ECHOLNPGM("REFIN- < 0.85 x V bias (FORCE- open)"); if (fault_31865 & MAX31865_FAULT_RTDINLOW) SERIAL_ECHOLNPGM("REFIN- < 0.85 x V bias (FORCE- open)"); if (fault_31865 & MAX31865_FAULT_OVUV) SERIAL_ECHOLNPGM("Under/Over voltage"); } #else // MAX6675 SERIAL_ECHOLNPGM("MAX6675 Fault: Open Circuit"); #endif // Set thermocouple above max temperature (TMAX) max_tc_temp = TEMP_SENSOR_BED_MAX_TC_TMAX << (BED_MAX_TC_DISCARD_BITS + 1); } } else { max_tc_errors = 0; // No error bit, reset error count } max_tc_temp >>= BED_MAX_TC_DISCARD_BITS; #if TEMP_SENSOR_BED_IS_MAX31855 // Support negative temperature for MAX38155 if (max_tc_temp & 0x00002000) max_tc_temp |= 0xFFFFC000; #endif return max_tc_temp; } #endif // TEMP_SENSOR_IS_MAX_TC(BED) /** * Update raw temperatures * * Called by ISR => readings_ready when new temperatures have been set by updateTemperaturesFromRawValues. * Applies all the accumulators to the current raw temperatures. */ void Temperature::update_raw_temperatures() { // TODO: can this be collapsed into a HOTEND_LOOP()? #if HAS_TEMP_ADC_0 && !TEMP_SENSOR_IS_MAX_TC(0) temp_hotend[0].update(); #endif #if HAS_TEMP_ADC_1 && !TEMP_SENSOR_IS_MAX_TC(1) temp_hotend[1].update(); #endif #if HAS_TEMP_ADC_2 && !TEMP_SENSOR_IS_MAX_TC(2) temp_hotend[2].update(); #endif #if HAS_TEMP_ADC_REDUNDANT && !TEMP_SENSOR_IS_MAX_TC(REDUNDANT) temp_redundant.update(); #endif #if HAS_TEMP_ADC_BED && !TEMP_SENSOR_IS_MAX_TC(BED) temp_bed.update(); #endif TERN_(HAS_TEMP_ADC_2, temp_hotend[2].update()); TERN_(HAS_TEMP_ADC_3, temp_hotend[3].update()); TERN_(HAS_TEMP_ADC_4, temp_hotend[4].update()); TERN_(HAS_TEMP_ADC_5, temp_hotend[5].update()); TERN_(HAS_TEMP_ADC_6, temp_hotend[6].update()); TERN_(HAS_TEMP_ADC_7, temp_hotend[7].update()); TERN_(HAS_TEMP_ADC_CHAMBER, temp_chamber.update()); TERN_(HAS_TEMP_ADC_PROBE, temp_probe.update()); TERN_(HAS_TEMP_ADC_COOLER, temp_cooler.update()); TERN_(HAS_TEMP_ADC_BOARD, temp_board.update()); TERN_(HAS_TEMP_ADC_SOC, temp_soc.update()); TERN_(HAS_JOY_ADC_X, joystick.x.update()); TERN_(HAS_JOY_ADC_Y, joystick.y.update()); TERN_(HAS_JOY_ADC_Z, joystick.z.update()); } /** * Called by the Temperature ISR when all the ADCs have been processed. * Reset all the ADC accumulators for another round of updates. */ void Temperature::readings_ready() { // Update raw values only if they're not already set. if (!raw_temps_ready) { update_raw_temperatures(); raw_temps_ready = true; } // Filament Sensor - can be read any time since IIR filtering is used TERN_(FILAMENT_WIDTH_SENSOR, filwidth.reading_ready()); #if HAS_HOTEND HOTEND_LOOP() temp_hotend[e].reset(); #endif TERN_(HAS_HEATED_BED, temp_bed.reset()); TERN_(HAS_TEMP_CHAMBER, temp_chamber.reset()); TERN_(HAS_TEMP_PROBE, temp_probe.reset()); TERN_(HAS_TEMP_COOLER, temp_cooler.reset()); TERN_(HAS_TEMP_BOARD, temp_board.reset()); TERN_(HAS_TEMP_SOC, temp_soc.reset()); TERN_(HAS_TEMP_REDUNDANT, temp_redundant.reset()); TERN_(HAS_JOY_ADC_X, joystick.x.reset()); TERN_(HAS_JOY_ADC_Y, joystick.y.reset()); TERN_(HAS_JOY_ADC_Z, joystick.z.reset()); } /** * Timer 0 is shared with millies so don't change the prescaler. * * On AVR this ISR uses the compare method so it runs at the base * frequency (16 MHz / 64 / 256 = 976.5625 Hz), but at the TCNT0 set * in OCR0B above (128 or halfway between OVFs). * * - Manage PWM to all the heaters and fan * - Prepare or Measure one of the raw ADC sensor values * - Check new temperature values for MIN/MAX errors (kill on error) * - Step the babysteps value for each axis towards 0 * - For PINS_DEBUGGING, monitor and report endstop pins * - For ENDSTOP_INTERRUPTS_FEATURE check endstops if flagged * - Call planner.isr to count down its "ignore" time */ HAL_TEMP_TIMER_ISR() { HAL_timer_isr_prologue(MF_TIMER_TEMP); Temperature::isr(); HAL_timer_isr_epilogue(MF_TIMER_TEMP); } #if ENABLED(SLOW_PWM_HEATERS) && !defined(MIN_STATE_TIME) #define MIN_STATE_TIME 16 // MIN_STATE_TIME * 65.5 = time in milliseconds #endif class SoftPWM { public: uint8_t count; inline bool add(const uint8_t mask, const uint8_t amount) { count = (count & mask) + amount; return (count > mask); } #if ENABLED(SLOW_PWM_HEATERS) bool state_heater; uint8_t state_timer_heater; inline void dec() { if (state_timer_heater > 0) state_timer_heater--; } inline bool ready(const bool v) { const bool rdy = !state_timer_heater; if (rdy && state_heater != v) { state_heater = v; state_timer_heater = MIN_STATE_TIME; } return rdy; } #endif }; /** * Handle various ~1kHz tasks associated with temperature * - Check laser safety timeout * - Heater PWM (~1kHz with scaler) * - LCD Button polling (~500Hz) * - Start / Read one ADC sensor * - Advance Babysteps * - Endstop polling * - Planner clean buffer */ void Temperature::isr() { // Shut down the laser if steppers are inactive for > LASER_SAFETY_TIMEOUT_MS ms #if LASER_SAFETY_TIMEOUT_MS > 0 if (cutter.last_power_applied && ELAPSED(millis(), gcode.previous_move_ms + (LASER_SAFETY_TIMEOUT_MS))) { cutter.power = 0; // Prevent planner idle from re-enabling power cutter.apply_power(0); } #endif static int8_t temp_count = -1; static ADCSensorState adc_sensor_state = StartupDelay; #ifndef SOFT_PWM_SCALE #define SOFT_PWM_SCALE 0 #endif static uint8_t pwm_count = _BV(SOFT_PWM_SCALE); // Avoid multiple loads of pwm_count uint8_t pwm_count_tmp = pwm_count; #if HAS_ADC_BUTTONS static raw_adc_t raw_ADCKey_value = 0; static bool ADCKey_pressed = false; #endif #if HAS_HOTEND static SoftPWM soft_pwm_hotend[HOTENDS]; #endif #if HAS_HEATED_BED static SoftPWM soft_pwm_bed; #endif #if HAS_HEATED_CHAMBER static SoftPWM soft_pwm_chamber; #endif #if HAS_COOLER static SoftPWM soft_pwm_cooler; #endif #if ALL(FAN_SOFT_PWM, USE_CONTROLLER_FAN) static SoftPWM soft_pwm_controller; #endif #define WRITE_FAN(n, v) WRITE(FAN##n##_PIN, (v) ^ ENABLED(FAN_INVERTING)) #if DISABLED(SLOW_PWM_HEATERS) #if ANY(HAS_HOTEND, HAS_HEATED_BED, HAS_HEATED_CHAMBER, HAS_COOLER, FAN_SOFT_PWM) constexpr uint8_t pwm_mask = TERN0(SOFT_PWM_DITHER, _BV(SOFT_PWM_SCALE) - 1); #define _PWM_MOD(N,S,T) do{ \ const bool on = S.add(pwm_mask, T.soft_pwm_amount); \ WRITE_HEATER_##N(on); \ }while(0) #endif /** * Standard heater PWM modulation */ if (pwm_count_tmp >= 127) { pwm_count_tmp -= 127; #if HAS_HOTEND #define _PWM_MOD_E(N) _PWM_MOD(N,soft_pwm_hotend[N],temp_hotend[N]); REPEAT(HOTENDS, _PWM_MOD_E); #endif #if HAS_HEATED_BED _PWM_MOD(BED, soft_pwm_bed, temp_bed); #endif #if HAS_HEATED_CHAMBER _PWM_MOD(CHAMBER, soft_pwm_chamber, temp_chamber); #endif #if HAS_COOLER _PWM_MOD(COOLER, soft_pwm_cooler, temp_cooler); #endif #if ENABLED(FAN_SOFT_PWM) #if ENABLED(USE_CONTROLLER_FAN) WRITE(CONTROLLER_FAN_PIN, soft_pwm_controller.add(pwm_mask, controllerFan.soft_pwm_speed)); #endif #define _FAN_PWM(N) do{ \ uint8_t &spcf = soft_pwm_count_fan[N]; \ spcf = (spcf & pwm_mask) + (soft_pwm_amount_fan[N] >> 1); \ WRITE_FAN(N, spcf > pwm_mask ? HIGH : LOW); \ }while(0) #if HAS_FAN0 _FAN_PWM(0); #endif #if HAS_FAN1 _FAN_PWM(1); #endif #if HAS_FAN2 _FAN_PWM(2); #endif #if HAS_FAN3 _FAN_PWM(3); #endif #if HAS_FAN4 _FAN_PWM(4); #endif #if HAS_FAN5 _FAN_PWM(5); #endif #if HAS_FAN6 _FAN_PWM(6); #endif #if HAS_FAN7 _FAN_PWM(7); #endif #endif } else { #define _PWM_LOW(N,S) do{ if (S.count <= pwm_count_tmp) WRITE_HEATER_##N(LOW); }while(0) #if HAS_HOTEND #define _PWM_LOW_E(N) _PWM_LOW(N, soft_pwm_hotend[N]); REPEAT(HOTENDS, _PWM_LOW_E); #endif #if HAS_HEATED_BED _PWM_LOW(BED, soft_pwm_bed); #endif #if HAS_HEATED_CHAMBER _PWM_LOW(CHAMBER, soft_pwm_chamber); #endif #if HAS_COOLER _PWM_LOW(COOLER, soft_pwm_cooler); #endif #if ENABLED(FAN_SOFT_PWM) #if HAS_FAN0 if (soft_pwm_count_fan[0] <= pwm_count_tmp) WRITE_FAN(0, LOW); #endif #if HAS_FAN1 if (soft_pwm_count_fan[1] <= pwm_count_tmp) WRITE_FAN(1, LOW); #endif #if HAS_FAN2 if (soft_pwm_count_fan[2] <= pwm_count_tmp) WRITE_FAN(2, LOW); #endif #if HAS_FAN3 if (soft_pwm_count_fan[3] <= pwm_count_tmp) WRITE_FAN(3, LOW); #endif #if HAS_FAN4 if (soft_pwm_count_fan[4] <= pwm_count_tmp) WRITE_FAN(4, LOW); #endif #if HAS_FAN5 if (soft_pwm_count_fan[5] <= pwm_count_tmp) WRITE_FAN(5, LOW); #endif #if HAS_FAN6 if (soft_pwm_count_fan[6] <= pwm_count_tmp) WRITE_FAN(6, LOW); #endif #if HAS_FAN7 if (soft_pwm_count_fan[7] <= pwm_count_tmp) WRITE_FAN(7, LOW); #endif #if ENABLED(USE_CONTROLLER_FAN) if (soft_pwm_controller.count <= pwm_count_tmp) WRITE(CONTROLLER_FAN_PIN, LOW); #endif #endif } // SOFT_PWM_SCALE to frequency: // // 0: 16000000/64/256/128 = 7.6294 Hz // 1: / 64 = 15.2588 Hz // 2: / 32 = 30.5176 Hz // 3: / 16 = 61.0352 Hz // 4: / 8 = 122.0703 Hz // 5: / 4 = 244.1406 Hz pwm_count = pwm_count_tmp + _BV(SOFT_PWM_SCALE); #else // SLOW_PWM_HEATERS /** * SLOW PWM HEATERS * * For relay-driven heaters */ #define _SLOW_SET(NR,PWM,V) do{ if (PWM.ready(V)) WRITE_HEATER_##NR(V); }while(0) #define _SLOW_PWM(NR,PWM,SRC) do{ PWM.count = SRC.soft_pwm_amount; _SLOW_SET(NR,PWM,(PWM.count > 0)); }while(0) #define _PWM_OFF(NR,PWM) do{ if (PWM.count < slow_pwm_count) _SLOW_SET(NR,PWM,0); }while(0) static uint8_t slow_pwm_count = 0; if (slow_pwm_count == 0) { #if HAS_HOTEND #define _SLOW_PWM_E(N) _SLOW_PWM(N, soft_pwm_hotend[N], temp_hotend[N]); REPEAT(HOTENDS, _SLOW_PWM_E); #endif #if HAS_HEATED_BED _SLOW_PWM(BED, soft_pwm_bed, temp_bed); #endif #if HAS_HEATED_CHAMBER _SLOW_PWM(CHAMBER, soft_pwm_chamber, temp_chamber); #endif #if HAS_COOLER _SLOW_PWM(COOLER, soft_pwm_cooler, temp_cooler); #endif } // slow_pwm_count == 0 #if HAS_HOTEND #define _PWM_OFF_E(N) _PWM_OFF(N, soft_pwm_hotend[N]); REPEAT(HOTENDS, _PWM_OFF_E); #endif #if HAS_HEATED_BED _PWM_OFF(BED, soft_pwm_bed); #endif #if HAS_HEATED_CHAMBER _PWM_OFF(CHAMBER, soft_pwm_chamber); #endif #if HAS_COOLER _PWM_OFF(COOLER, soft_pwm_cooler, temp_cooler); #endif #if ENABLED(FAN_SOFT_PWM) if (pwm_count_tmp >= 127) { pwm_count_tmp = 0; #define _PWM_FAN(N) do{ \ soft_pwm_count_fan[N] = soft_pwm_amount_fan[N] >> 1; \ WRITE_FAN(N, soft_pwm_count_fan[N] > 0 ? HIGH : LOW); \ }while(0) #if HAS_FAN0 _PWM_FAN(0); #endif #if HAS_FAN1 _PWM_FAN(1); #endif #if HAS_FAN2 _PWM_FAN(2); #endif #if HAS_FAN3 _FAN_PWM(3); #endif #if HAS_FAN4 _FAN_PWM(4); #endif #if HAS_FAN5 _FAN_PWM(5); #endif #if HAS_FAN6 _FAN_PWM(6); #endif #if HAS_FAN7 _FAN_PWM(7); #endif } #if HAS_FAN0 if (soft_pwm_count_fan[0] <= pwm_count_tmp) WRITE_FAN(0, LOW); #endif #if HAS_FAN1 if (soft_pwm_count_fan[1] <= pwm_count_tmp) WRITE_FAN(1, LOW); #endif #if HAS_FAN2 if (soft_pwm_count_fan[2] <= pwm_count_tmp) WRITE_FAN(2, LOW); #endif #if HAS_FAN3 if (soft_pwm_count_fan[3] <= pwm_count_tmp) WRITE_FAN(3, LOW); #endif #if HAS_FAN4 if (soft_pwm_count_fan[4] <= pwm_count_tmp) WRITE_FAN(4, LOW); #endif #if HAS_FAN5 if (soft_pwm_count_fan[5] <= pwm_count_tmp) WRITE_FAN(5, LOW); #endif #if HAS_FAN6 if (soft_pwm_count_fan[6] <= pwm_count_tmp) WRITE_FAN(6, LOW); #endif #if HAS_FAN7 if (soft_pwm_count_fan[7] <= pwm_count_tmp) WRITE_FAN(7, LOW); #endif #endif // FAN_SOFT_PWM // SOFT_PWM_SCALE to frequency: // // 0: 16000000/64/256/128 = 7.6294 Hz // 1: / 64 = 15.2588 Hz // 2: / 32 = 30.5176 Hz // 3: / 16 = 61.0352 Hz // 4: / 8 = 122.0703 Hz // 5: / 4 = 244.1406 Hz pwm_count = pwm_count_tmp + _BV(SOFT_PWM_SCALE); // Increment slow_pwm_count only every 64th pwm_count, // i.e., yielding a PWM frequency of 16/128 Hz (8s). if (((pwm_count >> SOFT_PWM_SCALE) & 0x3F) == 0) { slow_pwm_count++; slow_pwm_count &= 0x7F; #if HAS_HOTEND HOTEND_LOOP() soft_pwm_hotend[e].dec(); #endif TERN_(HAS_HEATED_BED, soft_pwm_bed.dec()); TERN_(HAS_HEATED_CHAMBER, soft_pwm_chamber.dec()); TERN_(HAS_COOLER, soft_pwm_cooler.dec()); } #endif // SLOW_PWM_HEATERS // // Update lcd buttons 488 times per second // static bool do_buttons; if ((do_buttons ^= true)) ui.update_buttons(); /** * One sensor is sampled on every other call of the ISR. * Each sensor is read 16 (OVERSAMPLENR) times, taking the average. * * On each Prepare pass, ADC is started for a sensor pin. * On the next pass, the ADC value is read and accumulated. * * This gives each ADC 0.9765ms to charge up. */ #define ACCUMULATE_ADC(obj) do{ \ if (!hal.adc_ready()) next_sensor_state = adc_sensor_state; \ else obj.sample(hal.adc_value()); \ }while(0) ADCSensorState next_sensor_state = adc_sensor_state < SensorsReady ? (ADCSensorState)(int(adc_sensor_state) + 1) : StartSampling; switch (adc_sensor_state) { #pragma GCC diagnostic push #if __has_cpp_attribute(fallthrough) #pragma GCC diagnostic ignored "-Wimplicit-fallthrough" #endif case SensorsReady: { // All sensors have been read. Stay in this state for a few // ISRs to save on calls to temp update/checking code below. constexpr int8_t extra_loops = MIN_ADC_ISR_LOOPS - (int8_t)SensorsReady; static uint8_t delay_count = 0; if (extra_loops > 0) { if (delay_count == 0) delay_count = extra_loops; // Init this delay if (--delay_count) // While delaying... next_sensor_state = SensorsReady; // retain this state (else, next state will be 0) break; } else { adc_sensor_state = StartSampling; // Fall-through to start sampling next_sensor_state = (ADCSensorState)(int(StartSampling) + 1); } } #pragma GCC diagnostic pop case StartSampling: // Start of sampling loops. Do updates/checks. if (++temp_count >= OVERSAMPLENR) { // 10 * 16 * 1/(16000000/64/256) = 164ms. temp_count = 0; readings_ready(); } break; #if HAS_TEMP_ADC_0 case PrepareTemp_0: hal.adc_start(TEMP_0_PIN); break; case MeasureTemp_0: ACCUMULATE_ADC(temp_hotend[0]); break; #endif #if HAS_TEMP_ADC_BED case PrepareTemp_BED: hal.adc_start(TEMP_BED_PIN); break; case MeasureTemp_BED: ACCUMULATE_ADC(temp_bed); break; #endif #if HAS_TEMP_ADC_CHAMBER case PrepareTemp_CHAMBER: hal.adc_start(TEMP_CHAMBER_PIN); break; case MeasureTemp_CHAMBER: ACCUMULATE_ADC(temp_chamber); break; #endif #if HAS_TEMP_ADC_COOLER case PrepareTemp_COOLER: hal.adc_start(TEMP_COOLER_PIN); break; case MeasureTemp_COOLER: ACCUMULATE_ADC(temp_cooler); break; #endif #if HAS_TEMP_ADC_PROBE case PrepareTemp_PROBE: hal.adc_start(TEMP_PROBE_PIN); break; case MeasureTemp_PROBE: ACCUMULATE_ADC(temp_probe); break; #endif #if HAS_TEMP_ADC_BOARD case PrepareTemp_BOARD: hal.adc_start(TEMP_BOARD_PIN); break; case MeasureTemp_BOARD: ACCUMULATE_ADC(temp_board); break; #endif #if HAS_TEMP_ADC_SOC case PrepareTemp_SOC: hal.adc_start(TEMP_SOC_PIN); break; case MeasureTemp_SOC: ACCUMULATE_ADC(temp_soc); break; #endif #if HAS_TEMP_ADC_REDUNDANT case PrepareTemp_REDUNDANT: hal.adc_start(TEMP_REDUNDANT_PIN); break; case MeasureTemp_REDUNDANT: ACCUMULATE_ADC(temp_redundant); break; #endif #if HAS_TEMP_ADC_1 case PrepareTemp_1: hal.adc_start(TEMP_1_PIN); break; case MeasureTemp_1: ACCUMULATE_ADC(temp_hotend[1]); break; #endif #if HAS_TEMP_ADC_2 case PrepareTemp_2: hal.adc_start(TEMP_2_PIN); break; case MeasureTemp_2: ACCUMULATE_ADC(temp_hotend[2]); break; #endif #if HAS_TEMP_ADC_3 case PrepareTemp_3: hal.adc_start(TEMP_3_PIN); break; case MeasureTemp_3: ACCUMULATE_ADC(temp_hotend[3]); break; #endif #if HAS_TEMP_ADC_4 case PrepareTemp_4: hal.adc_start(TEMP_4_PIN); break; case MeasureTemp_4: ACCUMULATE_ADC(temp_hotend[4]); break; #endif #if HAS_TEMP_ADC_5 case PrepareTemp_5: hal.adc_start(TEMP_5_PIN); break; case MeasureTemp_5: ACCUMULATE_ADC(temp_hotend[5]); break; #endif #if HAS_TEMP_ADC_6 case PrepareTemp_6: hal.adc_start(TEMP_6_PIN); break; case MeasureTemp_6: ACCUMULATE_ADC(temp_hotend[6]); break; #endif #if HAS_TEMP_ADC_7 case PrepareTemp_7: hal.adc_start(TEMP_7_PIN); break; case MeasureTemp_7: ACCUMULATE_ADC(temp_hotend[7]); break; #endif #if ENABLED(FILAMENT_WIDTH_SENSOR) case Prepare_FILWIDTH: hal.adc_start(FILWIDTH_PIN); break; case Measure_FILWIDTH: if (!hal.adc_ready()) next_sensor_state = adc_sensor_state; // Redo this state else filwidth.accumulate(hal.adc_value()); break; #endif #if ENABLED(POWER_MONITOR_CURRENT) case Prepare_POWER_MONITOR_CURRENT: hal.adc_start(POWER_MONITOR_CURRENT_PIN); break; case Measure_POWER_MONITOR_CURRENT: if (!hal.adc_ready()) next_sensor_state = adc_sensor_state; // Redo this state else power_monitor.add_current_sample(hal.adc_value()); break; #endif #if ENABLED(POWER_MONITOR_VOLTAGE) case Prepare_POWER_MONITOR_VOLTAGE: hal.adc_start(POWER_MONITOR_VOLTAGE_PIN); break; case Measure_POWER_MONITOR_VOLTAGE: if (!hal.adc_ready()) next_sensor_state = adc_sensor_state; // Redo this state else power_monitor.add_voltage_sample(hal.adc_value()); break; #endif #if HAS_JOY_ADC_X case PrepareJoy_X: hal.adc_start(JOY_X_PIN); break; case MeasureJoy_X: ACCUMULATE_ADC(joystick.x); break; #endif #if HAS_JOY_ADC_Y case PrepareJoy_Y: hal.adc_start(JOY_Y_PIN); break; case MeasureJoy_Y: ACCUMULATE_ADC(joystick.y); break; #endif #if HAS_JOY_ADC_Z case PrepareJoy_Z: hal.adc_start(JOY_Z_PIN); break; case MeasureJoy_Z: ACCUMULATE_ADC(joystick.z); break; #endif #if HAS_ADC_BUTTONS #ifndef ADC_BUTTON_DEBOUNCE_DELAY #define ADC_BUTTON_DEBOUNCE_DELAY 16 #endif case Prepare_ADC_KEY: hal.adc_start(ADC_KEYPAD_PIN); break; case Measure_ADC_KEY: if (!hal.adc_ready()) next_sensor_state = adc_sensor_state; // redo this state else if (ADCKey_count < ADC_BUTTON_DEBOUNCE_DELAY) { raw_ADCKey_value = hal.adc_value(); if (raw_ADCKey_value <= 900UL * HAL_ADC_RANGE / 1024UL) { NOMORE(current_ADCKey_raw, raw_ADCKey_value); ADCKey_count++; } else { //ADC Key release if (ADCKey_count > 0) ADCKey_count++; else ADCKey_pressed = false; if (ADCKey_pressed) { ADCKey_count = 0; current_ADCKey_raw = HAL_ADC_RANGE; } } } if (ADCKey_count == ADC_BUTTON_DEBOUNCE_DELAY) ADCKey_pressed = true; break; #endif // HAS_ADC_BUTTONS case StartupDelay: break; } // switch(adc_sensor_state) // Go to the next state adc_sensor_state = next_sensor_state; // // Additional ~1kHz Tasks // // Check fan tachometers TERN_(HAS_FANCHECK, fan_check.update_tachometers()); // Poll endstops state, if required endstops.poll(); // Periodically call the planner timer service routine planner.isr(); } #if HAS_TEMP_SENSOR /** * Print a single heater state in the form: * Bed: " B:nnn.nn /nnn.nn" * Chamber: " C:nnn.nn /nnn.nn" * Probe: " P:nnn.nn" * Cooler: " L:nnn.nn /nnn.nn" * Board: " M:nnn.nn" * SoC: " S:nnn.nn" * Redundant: " R:nnn.nn /nnn.nn" * Extruder: " T0:nnn.nn /nnn.nn" * With ADC: " T0:nnn.nn /nnn.nn (nnn.nn)" */ static void print_heater_state(const heater_id_t e, const_celsius_float_t c, const_celsius_float_t t OPTARG(SHOW_TEMP_ADC_VALUES, const float r) ) { char k; bool show_t = true; switch (e) { default: #if HAS_TEMP_HOTEND k = 'T'; break; #endif #if HAS_TEMP_BED case H_BED: k = 'B'; break; #endif #if HAS_TEMP_CHAMBER case H_CHAMBER: k = 'C'; break; #endif #if HAS_TEMP_PROBE case H_PROBE: k = 'P'; show_t = false; break; #endif #if HAS_TEMP_COOLER case H_COOLER: k = 'L'; break; #endif #if HAS_TEMP_BOARD case H_BOARD: k = 'M'; show_t = false; break; #endif #if HAS_TEMP_SOC case H_SOC: k = 'S'; show_t = false; break; #endif #if HAS_TEMP_REDUNDANT case H_REDUNDANT: k = 'R'; break; #endif } #ifndef HEATER_STATE_FLOAT_PRECISION #define HEATER_STATE_FLOAT_PRECISION _MIN(SERIAL_FLOAT_PRECISION, 2) #endif SString<50> s(' ', k); if (TERN0(HAS_MULTI_HOTEND, e >= 0)) s += char('0' + e); s += ':'; s += p_float_t(c, HEATER_STATE_FLOAT_PRECISION); if (show_t) { s += F(" /"); s += p_float_t(t, HEATER_STATE_FLOAT_PRECISION); } #if ENABLED(SHOW_TEMP_ADC_VALUES) // Temperature MAX SPI boards do not have an OVERSAMPLENR defined s.append(F(" ("), TERN(HAS_MAXTC_LIBRARIES, k == 'T', false) ? r : r * RECIPROCAL(OVERSAMPLENR), ')'); #endif s.echo(); delay(2); } void Temperature::print_heater_states(const int8_t target_extruder OPTARG(HAS_TEMP_REDUNDANT, const bool include_r/*=false*/) ) { #if HAS_TEMP_HOTEND print_heater_state(H_NONE, degHotend(target_extruder), degTargetHotend(target_extruder) OPTARG(SHOW_TEMP_ADC_VALUES, rawHotendTemp(target_extruder))); #endif #if HAS_HEATED_BED print_heater_state(H_BED, degBed(), degTargetBed() OPTARG(SHOW_TEMP_ADC_VALUES, rawBedTemp())); #endif #if HAS_TEMP_CHAMBER print_heater_state(H_CHAMBER, degChamber(), TERN0(HAS_HEATED_CHAMBER, degTargetChamber()) OPTARG(SHOW_TEMP_ADC_VALUES, rawChamberTemp())); #endif #if HAS_TEMP_COOLER print_heater_state(H_COOLER, degCooler(), TERN0(HAS_COOLER, degTargetCooler()) OPTARG(SHOW_TEMP_ADC_VALUES, rawCoolerTemp())); #endif #if HAS_TEMP_PROBE print_heater_state(H_PROBE, degProbe(), 0 OPTARG(SHOW_TEMP_ADC_VALUES, rawProbeTemp())); #endif #if HAS_TEMP_BOARD print_heater_state(H_BOARD, degBoard(), 0 OPTARG(SHOW_TEMP_ADC_VALUES, rawBoardTemp())); #endif #if HAS_TEMP_SOC print_heater_state(H_SOC, degSoc(), 0 OPTARG(SHOW_TEMP_ADC_VALUES, rawSocTemp())); #endif #if HAS_TEMP_REDUNDANT if (include_r) print_heater_state(H_REDUNDANT, degRedundant(), degRedundantTarget() OPTARG(SHOW_TEMP_ADC_VALUES, rawRedundantTemp())); #endif #if HAS_MULTI_HOTEND HOTEND_LOOP() print_heater_state((heater_id_t)e, degHotend(e), degTargetHotend(e) OPTARG(SHOW_TEMP_ADC_VALUES, rawHotendTemp(e))); #endif SString<100> s(F(" @:"), getHeaterPower((heater_id_t)target_extruder)); #if HAS_HEATED_BED s.append(" B@:", getHeaterPower(H_BED)); #endif #if HAS_HEATED_CHAMBER s.append(" C@:", getHeaterPower(H_CHAMBER)); #endif #if HAS_COOLER s.append(" C@:", getHeaterPower(H_COOLER)); #endif #if HAS_MULTI_HOTEND HOTEND_LOOP() s.append(F(" @"), e, ':', getHeaterPower((heater_id_t)e)); #endif s.echo(); } #if ENABLED(AUTO_REPORT_TEMPERATURES) AutoReporter<Temperature::AutoReportTemp> Temperature::auto_reporter; void Temperature::AutoReportTemp::report() { if (wait_for_heatup) return; print_heater_states(active_extruder OPTARG(HAS_TEMP_REDUNDANT, ENABLED(AUTO_REPORT_REDUNDANT))); SERIAL_EOL(); } #endif #if HAS_HOTEND && HAS_STATUS_MESSAGE void Temperature::set_heating_message(const uint8_t e, const bool isM104/*=false*/) { const bool heating = isHeatingHotend(e); ui.status_printf(0, #if HAS_MULTI_HOTEND F("E%c " S_FMT), '1' + e #else F("E1 " S_FMT) #endif , heating ? GET_TEXT_F(MSG_HEATING) : GET_TEXT_F(MSG_COOLING) ); if (isM104) { static uint8_t wait_e; wait_e = e; ui.set_status_reset_fn([]{ const celsius_t c = degTargetHotend(wait_e); return c < 30 || degHotendNear(wait_e, c); }); } } #endif #if HAS_TEMP_HOTEND #ifndef MIN_COOLING_SLOPE_DEG #define MIN_COOLING_SLOPE_DEG 1.50 #endif #ifndef MIN_COOLING_SLOPE_TIME #define MIN_COOLING_SLOPE_TIME 60 #endif bool Temperature::wait_for_hotend(const uint8_t target_extruder, const bool no_wait_for_cooling/*=true*/ OPTARG(G26_CLICK_CAN_CANCEL, const bool click_to_cancel/*=false*/) ) { #if ENABLED(AUTOTEMP) REMEMBER(1, planner.autotemp.enabled, false); #endif #if TEMP_RESIDENCY_TIME > 0 millis_t residency_start_ms = 0; bool first_loop = true; // Loop until the temperature has stabilized #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + SEC_TO_MS(TEMP_RESIDENCY_TIME))) #else // Loop until the temperature is very close target #define TEMP_CONDITIONS (wants_to_cool ? isCoolingHotend(target_extruder) : isHeatingHotend(target_extruder)) #endif #if DISABLED(BUSY_WHILE_HEATING) && ENABLED(HOST_KEEPALIVE_FEATURE) KEEPALIVE_STATE(NOT_BUSY); #endif #if ENABLED(PRINTER_EVENT_LEDS) const celsius_float_t start_temp = degHotend(target_extruder); printerEventLEDs.onHotendHeatingStart(); #endif bool wants_to_cool = false; celsius_float_t target_temp = -1.0, old_temp = 9999.0; millis_t now, next_temp_ms = 0, cool_check_ms = 0; wait_for_heatup = true; do { // Target temperature might be changed during the loop if (target_temp != degTargetHotend(target_extruder)) { wants_to_cool = isCoolingHotend(target_extruder); target_temp = degTargetHotend(target_extruder); // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher> if (no_wait_for_cooling && wants_to_cool) break; } now = millis(); if (ELAPSED(now, next_temp_ms)) { // Print temp & remaining time every 1s while waiting next_temp_ms = now + 1000UL; print_heater_states(target_extruder); #if TEMP_RESIDENCY_TIME > 0 SString<20> s(F(" W:")); if (residency_start_ms) s += long((SEC_TO_MS(TEMP_RESIDENCY_TIME) - (now - residency_start_ms)) / 1000UL); else s += '?'; s.echo(); #endif SERIAL_EOL(); } idle(); gcode.reset_stepper_timeout(); // Keep steppers powered const celsius_float_t temp = degHotend(target_extruder); #if ENABLED(PRINTER_EVENT_LEDS) // Gradually change LED strip from violet to red as nozzle heats up if (!wants_to_cool) printerEventLEDs.onHotendHeating(start_temp, temp, target_temp); #endif #if TEMP_RESIDENCY_TIME > 0 const celsius_float_t temp_diff = ABS(target_temp - temp); if (!residency_start_ms) { // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time. if (temp_diff < TEMP_WINDOW) residency_start_ms = now + (first_loop ? SEC_TO_MS(TEMP_RESIDENCY_TIME) / 3 : 0); } else if (temp_diff > TEMP_HYSTERESIS) { // Restart the timer whenever the temperature falls outside the hysteresis. residency_start_ms = now; } first_loop = false; #endif // Prevent a wait-forever situation if R is misused i.e. M109 R0 if (wants_to_cool) { // Break after MIN_COOLING_SLOPE_TIME seconds // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG if (!cool_check_ms || ELAPSED(now, cool_check_ms)) { if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG)) break; cool_check_ms = now + SEC_TO_MS(MIN_COOLING_SLOPE_TIME); old_temp = temp; } } #if G26_CLICK_CAN_CANCEL if (click_to_cancel && ui.use_click()) { wait_for_heatup = false; TERN_(HAS_MARLINUI_MENU, ui.quick_feedback()); } #endif } while (wait_for_heatup && TEMP_CONDITIONS); // If wait_for_heatup is set, temperature was reached, no cancel if (wait_for_heatup) { wait_for_heatup = false; #if ENABLED(DWIN_CREALITY_LCD) hmiFlag.heat_flag = 0; duration_t elapsed = print_job_timer.duration(); // Print timer dwin_heat_time = elapsed.value; #else ui.reset_status(); #endif TERN_(PRINTER_EVENT_LEDS, printerEventLEDs.onHeatingDone()); return true; } return false; } #if ENABLED(WAIT_FOR_HOTEND) void Temperature::wait_for_hotend_heating(const uint8_t target_extruder) { if (isHeatingHotend(target_extruder)) { SERIAL_ECHOLNPGM("Wait for hotend heating..."); LCD_MESSAGE(MSG_HEATING); wait_for_hotend(target_extruder); ui.reset_status(); } } #endif #endif // HAS_TEMP_HOTEND #if HAS_HEATED_BED #ifndef MIN_COOLING_SLOPE_DEG_BED #define MIN_COOLING_SLOPE_DEG_BED 1.00 #endif #ifndef MIN_COOLING_SLOPE_TIME_BED #define MIN_COOLING_SLOPE_TIME_BED 60 #endif bool Temperature::wait_for_bed(const bool no_wait_for_cooling/*=true*/ OPTARG(G26_CLICK_CAN_CANCEL, const bool click_to_cancel/*=false*/) ) { #if TEMP_BED_RESIDENCY_TIME > 0 millis_t residency_start_ms = 0; bool first_loop = true; // Loop until the temperature has stabilized #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + SEC_TO_MS(TEMP_BED_RESIDENCY_TIME))) #else // Loop until the temperature is very close target #define TEMP_BED_CONDITIONS (wants_to_cool ? isCoolingBed() : isHeatingBed()) #endif #if DISABLED(BUSY_WHILE_HEATING) && ENABLED(HOST_KEEPALIVE_FEATURE) KEEPALIVE_STATE(NOT_BUSY); #endif #if ENABLED(PRINTER_EVENT_LEDS) const celsius_float_t start_temp = degBed(); printerEventLEDs.onBedHeatingStart(); #endif bool wants_to_cool = false; celsius_float_t target_temp = -1, old_temp = 9999; millis_t now, next_temp_ms = 0, cool_check_ms = 0; wait_for_heatup = true; do { // Target temperature might be changed during the loop if (target_temp != degTargetBed()) { wants_to_cool = isCoolingBed(); target_temp = degTargetBed(); // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher> if (no_wait_for_cooling && wants_to_cool) break; } now = millis(); if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up. next_temp_ms = now + 1000UL; print_heater_states(active_extruder); #if TEMP_BED_RESIDENCY_TIME > 0 SString<20> s(F(" W:")); if (residency_start_ms) s += long((SEC_TO_MS(TEMP_BED_RESIDENCY_TIME) - (now - residency_start_ms)) / 1000UL); else s += '?'; s.echo(); #endif SERIAL_EOL(); } idle(); gcode.reset_stepper_timeout(); // Keep steppers powered const celsius_float_t temp = degBed(); #if ENABLED(PRINTER_EVENT_LEDS) // Gradually change LED strip from blue to violet as bed heats up if (!wants_to_cool) printerEventLEDs.onBedHeating(start_temp, temp, target_temp); #endif #if TEMP_BED_RESIDENCY_TIME > 0 const celsius_float_t temp_diff = ABS(target_temp - temp); if (!residency_start_ms) { // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now + (first_loop ? SEC_TO_MS(TEMP_BED_RESIDENCY_TIME) / 3 : 0); } else if (temp_diff > TEMP_BED_HYSTERESIS) { // Restart the timer whenever the temperature falls outside the hysteresis. residency_start_ms = now; } #endif // TEMP_BED_RESIDENCY_TIME > 0 // Prevent a wait-forever situation if R is misused i.e. M190 R0 if (wants_to_cool) { // Break after MIN_COOLING_SLOPE_TIME_BED seconds // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED if (!cool_check_ms || ELAPSED(now, cool_check_ms)) { if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG_BED)) break; cool_check_ms = now + SEC_TO_MS(MIN_COOLING_SLOPE_TIME_BED); old_temp = temp; } } #if G26_CLICK_CAN_CANCEL if (click_to_cancel && ui.use_click()) { wait_for_heatup = false; TERN_(HAS_MARLINUI_MENU, ui.quick_feedback()); } #endif #if TEMP_BED_RESIDENCY_TIME > 0 first_loop = false; #endif } while (wait_for_heatup && TEMP_BED_CONDITIONS); // If wait_for_heatup is set, temperature was reached, no cancel if (wait_for_heatup) { wait_for_heatup = false; ui.reset_status(); return true; } return false; } void Temperature::wait_for_bed_heating() { if (isHeatingBed()) { SERIAL_ECHOLNPGM("Wait for bed heating..."); LCD_MESSAGE(MSG_BED_HEATING); wait_for_bed(); ui.reset_status(); } } #endif // HAS_HEATED_BED #if HAS_TEMP_PROBE #ifndef MIN_DELTA_SLOPE_DEG_PROBE #define MIN_DELTA_SLOPE_DEG_PROBE 1.0 #endif #ifndef MIN_DELTA_SLOPE_TIME_PROBE #define MIN_DELTA_SLOPE_TIME_PROBE 600 #endif bool Temperature::wait_for_probe(const celsius_t target_temp, bool no_wait_for_cooling/*=true*/) { const bool wants_to_cool = isProbeAboveTemp(target_temp), will_wait = !(wants_to_cool && no_wait_for_cooling); if (will_wait) SString<60>(F("Waiting for probe to "), wants_to_cool ? F("cool down") : F("heat up"), F(" to "), target_temp, F(" degrees.")).echoln(); #if DISABLED(BUSY_WHILE_HEATING) && ENABLED(HOST_KEEPALIVE_FEATURE) KEEPALIVE_STATE(NOT_BUSY); #endif float old_temp = 9999; millis_t next_temp_ms = 0, next_delta_check_ms = 0; wait_for_heatup = true; while (will_wait && wait_for_heatup) { // Print Temp Reading every 10 seconds while heating up. millis_t now = millis(); if (!next_temp_ms || ELAPSED(now, next_temp_ms)) { next_temp_ms = now + 10000UL; print_heater_states(active_extruder); SERIAL_EOL(); } idle(); gcode.reset_stepper_timeout(); // Keep steppers powered // Break after MIN_DELTA_SLOPE_TIME_PROBE seconds if the temperature // did not drop at least MIN_DELTA_SLOPE_DEG_PROBE. This avoids waiting // forever as the probe is not actively heated. if (!next_delta_check_ms || ELAPSED(now, next_delta_check_ms)) { const float temp = degProbe(), delta_temp = old_temp > temp ? old_temp - temp : temp - old_temp; if (delta_temp < float(MIN_DELTA_SLOPE_DEG_PROBE)) { SERIAL_ECHOLNPGM("Timed out waiting for probe temperature."); break; } next_delta_check_ms = now + SEC_TO_MS(MIN_DELTA_SLOPE_TIME_PROBE); old_temp = temp; } // Loop until the temperature is very close target if (!(wants_to_cool ? isProbeAboveTemp(target_temp) : isProbeBelowTemp(target_temp))) { SString<60>(wants_to_cool ? F("Cooldown") : F("Heatup"), F(" complete, target probe temperature reached.")).echoln(); break; } } // If wait_for_heatup is set, temperature was reached, no cancel if (wait_for_heatup) { wait_for_heatup = false; ui.reset_status(); return true; } else if (will_wait) SERIAL_ECHOLNPGM("Canceled wait for probe temperature."); return false; } #endif // HAS_TEMP_PROBE #if HAS_HEATED_CHAMBER #ifndef MIN_COOLING_SLOPE_DEG_CHAMBER #define MIN_COOLING_SLOPE_DEG_CHAMBER 1.50 #endif #ifndef MIN_COOLING_SLOPE_TIME_CHAMBER #define MIN_COOLING_SLOPE_TIME_CHAMBER 120 #endif bool Temperature::wait_for_chamber(const bool no_wait_for_cooling/*=true*/) { #if TEMP_CHAMBER_RESIDENCY_TIME > 0 millis_t residency_start_ms = 0; bool first_loop = true; // Loop until the temperature has stabilized #define TEMP_CHAMBER_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + SEC_TO_MS(TEMP_CHAMBER_RESIDENCY_TIME))) #else // Loop until the temperature is very close target #define TEMP_CHAMBER_CONDITIONS (wants_to_cool ? isCoolingChamber() : isHeatingChamber()) #endif #if DISABLED(BUSY_WHILE_HEATING) && ENABLED(HOST_KEEPALIVE_FEATURE) KEEPALIVE_STATE(NOT_BUSY); #endif bool wants_to_cool = false; float target_temp = -1, old_temp = 9999; millis_t now, next_temp_ms = 0, cool_check_ms = 0; wait_for_heatup = true; do { // Target temperature might be changed during the loop if (target_temp != degTargetChamber()) { wants_to_cool = isCoolingChamber(); target_temp = degTargetChamber(); // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher> if (no_wait_for_cooling && wants_to_cool) break; } now = millis(); if (ELAPSED(now, next_temp_ms)) { // Print Temp Reading every 1 second while heating up. next_temp_ms = now + 1000UL; print_heater_states(active_extruder); #if TEMP_CHAMBER_RESIDENCY_TIME > 0 SString<20> s(F(" W:")); if (residency_start_ms) s += long((SEC_TO_MS(TEMP_CHAMBER_RESIDENCY_TIME) - (now - residency_start_ms)) / 1000UL); else s += '?'; s.echo(); #endif SERIAL_EOL(); } idle(); gcode.reset_stepper_timeout(); // Keep steppers powered const float temp = degChamber(); #if TEMP_CHAMBER_RESIDENCY_TIME > 0 const float temp_diff = ABS(target_temp - temp); if (!residency_start_ms) { // Start the TEMP_CHAMBER_RESIDENCY_TIME timer when we reach target temp for the first time. if (temp_diff < TEMP_CHAMBER_WINDOW) residency_start_ms = now + (first_loop ? SEC_TO_MS(TEMP_CHAMBER_RESIDENCY_TIME) / 3 : 0); } else if (temp_diff > TEMP_CHAMBER_HYSTERESIS) { // Restart the timer whenever the temperature falls outside the hysteresis. residency_start_ms = now; } first_loop = false; #endif // TEMP_CHAMBER_RESIDENCY_TIME > 0 // Prevent a wait-forever situation if R is misused i.e. M191 R0 if (wants_to_cool) { // Break after MIN_COOLING_SLOPE_TIME_CHAMBER seconds // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_CHAMBER if (!cool_check_ms || ELAPSED(now, cool_check_ms)) { if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG_CHAMBER)) break; cool_check_ms = now + SEC_TO_MS(MIN_COOLING_SLOPE_TIME_CHAMBER); old_temp = temp; } } } while (wait_for_heatup && TEMP_CHAMBER_CONDITIONS); // If wait_for_heatup is set, temperature was reached, no cancel if (wait_for_heatup) { wait_for_heatup = false; ui.reset_status(); return true; } return false; } #endif // HAS_HEATED_CHAMBER #if HAS_COOLER #ifndef MIN_COOLING_SLOPE_DEG_COOLER #define MIN_COOLING_SLOPE_DEG_COOLER 1.50 #endif #ifndef MIN_COOLING_SLOPE_TIME_COOLER #define MIN_COOLING_SLOPE_TIME_COOLER 120 #endif bool Temperature::wait_for_cooler(const bool no_wait_for_cooling/*=true*/) { #if TEMP_COOLER_RESIDENCY_TIME > 0 millis_t residency_start_ms = 0; bool first_loop = true; // Loop until the temperature has stabilized #define TEMP_COOLER_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + SEC_TO_MS(TEMP_COOLER_RESIDENCY_TIME))) #else // Loop until the temperature is very close target #define TEMP_COOLER_CONDITIONS (wants_to_cool ? isLaserHeating() : isLaserCooling()) #endif #if DISABLED(BUSY_WHILE_HEATING) && ENABLED(HOST_KEEPALIVE_FEATURE) KEEPALIVE_STATE(NOT_BUSY); #endif bool wants_to_cool = false; float target_temp = -1, previous_temp = 9999; millis_t now, next_temp_ms = 0, next_cooling_check_ms = 0; wait_for_heatup = true; do { // Target temperature might be changed during the loop if (target_temp != degTargetCooler()) { wants_to_cool = isLaserHeating(); target_temp = degTargetCooler(); // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher> if (no_wait_for_cooling && wants_to_cool) break; } now = millis(); if (ELAPSED(now, next_temp_ms)) { // Print Temp Reading every 1 second while heating up. next_temp_ms = now + 1000UL; print_heater_states(active_extruder); #if TEMP_COOLER_RESIDENCY_TIME > 0 SString<20> s(F(" W:")); if (residency_start_ms) s += long((SEC_TO_MS(TEMP_COOLER_RESIDENCY_TIME) - (now - residency_start_ms)) / 1000UL); else s += '?'; s.echo(); #endif SERIAL_EOL(); } idle(); gcode.reset_stepper_timeout(); // Keep steppers powered const celsius_float_t current_temp = degCooler(); #if TEMP_COOLER_RESIDENCY_TIME > 0 const celsius_float_t temp_diff = ABS(target_temp - temp); if (!residency_start_ms) { // Start the TEMP_COOLER_RESIDENCY_TIME timer when we reach target temp for the first time. if (temp_diff < TEMP_COOLER_WINDOW) residency_start_ms = now + (first_loop ? SEC_TO_MS(TEMP_COOLER_RESIDENCY_TIME) / 3 : 0); } else if (temp_diff > TEMP_COOLER_HYSTERESIS) { // Restart the timer whenever the temperature falls outside the hysteresis. residency_start_ms = now; } first_loop = false; #endif // TEMP_COOLER_RESIDENCY_TIME > 0 // Prevent a wait-forever situation if R is misused i.e. M191 R0 if (wants_to_cool) { // Break after MIN_COOLING_SLOPE_TIME_CHAMBER seconds // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_CHAMBER if (!next_cooling_check_ms || ELAPSED(now, next_cooling_check_ms)) { if (previous_temp - current_temp < float(MIN_COOLING_SLOPE_DEG_COOLER)) break; next_cooling_check_ms = now + SEC_TO_MS(MIN_COOLING_SLOPE_TIME_COOLER); previous_temp = current_temp; } } } while (wait_for_heatup && TEMP_COOLER_CONDITIONS); // If wait_for_heatup is set, temperature was reached, no cancel if (wait_for_heatup) { wait_for_heatup = false; ui.reset_status(); return true; } return false; } #endif // HAS_COOLER #endif // HAS_TEMP_SENSOR
2301_81045437/Marlin
Marlin/src/module/temperature.cpp
C++
agpl-3.0
178,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 /** * temperature.h - temperature controller */ #include "thermistor/thermistors.h" #include "../inc/MarlinConfig.h" #if ENABLED(AUTO_POWER_CONTROL) #include "../feature/power.h" #endif #if ENABLED(AUTO_REPORT_TEMPERATURES) #include "../libs/autoreport.h" #endif #if HAS_FANCHECK #include "../feature/fancheck.h" #endif //#define ERR_INCLUDE_TEMP #define HOTEND_INDEX TERN(HAS_MULTI_HOTEND, e, 0) #define E_NAME TERN_(HAS_MULTI_HOTEND, e) #if HAS_FAN #if NUM_REDUNDANT_FANS #define FAN_IS_REDUNDANT(Q) WITHIN(Q, REDUNDANT_PART_COOLING_FAN, REDUNDANT_PART_COOLING_FAN + NUM_REDUNDANT_FANS - 1) #else #define FAN_IS_REDUNDANT(Q) false #endif #define FAN_IS_M106ABLE(Q) (HAS_FAN##Q && !FAN_IS_REDUNDANT(Q)) #else #define FAN_IS_M106ABLE(Q) false #endif typedef int_fast8_t heater_id_t; /** * States for ADC reading in the ISR */ enum ADCSensorState : char { StartSampling, #if HAS_TEMP_ADC_0 PrepareTemp_0, MeasureTemp_0, #endif #if HAS_TEMP_ADC_BED PrepareTemp_BED, MeasureTemp_BED, #endif #if HAS_TEMP_ADC_CHAMBER PrepareTemp_CHAMBER, MeasureTemp_CHAMBER, #endif #if HAS_TEMP_ADC_COOLER PrepareTemp_COOLER, MeasureTemp_COOLER, #endif #if HAS_TEMP_ADC_PROBE PrepareTemp_PROBE, MeasureTemp_PROBE, #endif #if HAS_TEMP_ADC_BOARD PrepareTemp_BOARD, MeasureTemp_BOARD, #endif #if HAS_TEMP_ADC_SOC PrepareTemp_SOC, MeasureTemp_SOC, #endif #if HAS_TEMP_ADC_REDUNDANT PrepareTemp_REDUNDANT, MeasureTemp_REDUNDANT, #endif #if HAS_TEMP_ADC_1 PrepareTemp_1, MeasureTemp_1, #endif #if HAS_TEMP_ADC_2 PrepareTemp_2, MeasureTemp_2, #endif #if HAS_TEMP_ADC_3 PrepareTemp_3, MeasureTemp_3, #endif #if HAS_TEMP_ADC_4 PrepareTemp_4, MeasureTemp_4, #endif #if HAS_TEMP_ADC_5 PrepareTemp_5, MeasureTemp_5, #endif #if HAS_TEMP_ADC_6 PrepareTemp_6, MeasureTemp_6, #endif #if HAS_TEMP_ADC_7 PrepareTemp_7, MeasureTemp_7, #endif #if HAS_JOY_ADC_X PrepareJoy_X, MeasureJoy_X, #endif #if HAS_JOY_ADC_Y PrepareJoy_Y, MeasureJoy_Y, #endif #if HAS_JOY_ADC_Z PrepareJoy_Z, MeasureJoy_Z, #endif #if ENABLED(FILAMENT_WIDTH_SENSOR) Prepare_FILWIDTH, Measure_FILWIDTH, #endif #if ENABLED(POWER_MONITOR_CURRENT) Prepare_POWER_MONITOR_CURRENT, Measure_POWER_MONITOR_CURRENT, #endif #if ENABLED(POWER_MONITOR_VOLTAGE) Prepare_POWER_MONITOR_VOLTAGE, Measure_POWER_MONITOR_VOLTAGE, #endif #if HAS_ADC_BUTTONS Prepare_ADC_KEY, Measure_ADC_KEY, #endif SensorsReady, // Temperatures ready. Delay the next round of readings to let ADC pins settle. StartupDelay // Startup, delay initial temp reading a tiny bit so the hardware can settle }; // Minimum number of Temperature::ISR loops between sensor readings. // Multiplied by 16 (OVERSAMPLENR) to obtain the total time to // get all oversampled sensor readings #define MIN_ADC_ISR_LOOPS 10 #define ACTUAL_ADC_SAMPLES _MAX(int(MIN_ADC_ISR_LOOPS), int(SensorsReady)) // // PID // typedef struct { float p, i, d; } raw_pid_t; typedef struct { float p, i, d, c, f; } raw_pidcf_t; #if HAS_PID_HEATING #define PID_K2 (1.0f - float(PID_K1)) #define PID_dT ((OVERSAMPLENR * float(ACTUAL_ADC_SAMPLES)) / (TEMP_TIMER_FREQUENCY)) // Apply the scale factors to the PID values #define scalePID_i(i) ( float(i) * PID_dT ) #define unscalePID_i(i) ( float(i) / PID_dT ) #define scalePID_d(d) ( float(d) / PID_dT ) #define unscalePID_d(d) ( float(d) * PID_dT ) /// @brief The default PID class, only has Kp, Ki, Kd, other classes extend this one /// @tparam MIN_POW output when current is above target by functional_range /// @tparam MAX_POW output when current is below target by functional_range /// @details This class has methods for Kc and Kf terms, but returns constant default values /// PID classes that implement these features are expected to override these methods /// Since the finally used PID class is typedef-d, there is no need to use virtual functions template<int MIN_POW, int MAX_POW> struct PID_t { protected: bool pid_reset = true; float temp_iState = 0.0f, temp_dState = 0.0f; float work_p = 0, work_i = 0, work_d = 0; public: float Kp = 0, Ki = 0, Kd = 0; float p() const { return Kp; } float i() const { return unscalePID_i(Ki); } float d() const { return unscalePID_d(Kd); } float c() const { return 1; } float f() const { return 0; } float pTerm() const { return work_p; } float iTerm() const { return work_i; } float dTerm() const { return work_d; } float cTerm() const { return 0; } float fTerm() const { return 0; } void set_Kp(float p) { Kp = p; } void set_Ki(float i) { Ki = scalePID_i(i); } void set_Kd(float d) { Kd = scalePID_d(d); } void set_Kc(float) {} void set_Kf(float) {} int low() const { return MIN_POW; } int high() const { return MAX_POW; } void reset() { pid_reset = true; } void set(float p, float i, float d, float c=1, float f=0) { set_Kp(p); set_Ki(i); set_Kd(d); set_Kc(c); set_Kf(f); } void set(const raw_pid_t &raw) { set(raw.p, raw.i, raw.d); } void set(const raw_pidcf_t &raw) { set(raw.p, raw.i, raw.d, raw.c, raw.f); } float get_fan_scale_output(const uint8_t) { return 0; } float get_extrusion_scale_output(const bool, const int32_t, const float, const int16_t) { return 0; } float get_pid_output(const float target, const float current) { const float pid_error = target - current; float output_pow; if (!target || pid_error < -(PID_FUNCTIONAL_RANGE)) { pid_reset = true; output_pow = 0; } else if (pid_error > PID_FUNCTIONAL_RANGE) { pid_reset = true; output_pow = MAX_POW; } else { if (pid_reset) { pid_reset = false; temp_iState = 0.0; work_d = 0.0; } const float max_power_over_i_gain = float(MAX_POW) / Ki - float(MIN_POW); temp_iState = constrain(temp_iState + pid_error, 0, max_power_over_i_gain); work_p = Kp * pid_error; work_i = Ki * temp_iState; work_d = work_d + PID_K2 * (Kd * (temp_dState - current) - work_d); output_pow = constrain(work_p + work_i + work_d + float(MIN_POW), 0, MAX_POW); } temp_dState = current; return output_pow; } }; #endif // HAS_PID_HEATING #if ENABLED(PIDTEMP) /// @brief Extrusion scaled PID class template<int MIN_POW, int MAX_POW, int LPQ_ARR_SZ> struct PIDC_t : public PID_t<MIN_POW, MAX_POW> { private: using base = PID_t<MIN_POW, MAX_POW>; float work_c = 0; float prev_e_pos = 0; int32_t lpq[LPQ_ARR_SZ] = {}; int16_t lpq_ptr = 0; public: float Kc = 0; float c() const { return Kc; } void set_Kc(float c) { Kc = c; } float cTerm() const { return work_c; } void set(float p, float i, float d, float c=1, float f=0) { base::set_Kp(p); base::set_Ki(i); base::set_Kd(d); set_Kc(c); base::set_Kf(f); } void set(const raw_pid_t &raw) { set(raw.p, raw.i, raw.d); } void set(const raw_pidcf_t &raw) { set(raw.p, raw.i, raw.d, raw.c, raw.f); } void reset() { base::reset(); prev_e_pos = 0; lpq_ptr = 0; for (uint8_t i = 0; i < LPQ_ARR_SZ; ++i) lpq[i] = 0; } float get_extrusion_scale_output(const bool is_active, const int32_t e_position, const float e_mm_per_step, const int16_t lpq_len) { work_c = 0; if (!is_active) return work_c; if (e_position > prev_e_pos) { lpq[lpq_ptr] = e_position - prev_e_pos; prev_e_pos = e_position; } else lpq[lpq_ptr] = 0; ++lpq_ptr; if (lpq_ptr >= LPQ_ARR_SZ || lpq_ptr >= lpq_len) lpq_ptr = 0; work_c = (lpq[lpq_ptr] * e_mm_per_step) * Kc; return work_c; } }; /// @brief Fan scaled PID, this class implements the get_fan_scale_output() method /// @tparam MIN_POW @see PID_t /// @tparam MAX_POW @see PID_t /// @tparam SCALE_MIN_SPEED parameter from Configuration_adv.h /// @tparam SCALE_LIN_FACTOR parameter from Configuration_adv.h template<int MIN_POW, int MAX_POW, int SCALE_MIN_SPEED, int SCALE_LIN_FACTOR> struct PIDF_t : public PID_t<MIN_POW, MAX_POW> { private: using base = PID_t<MIN_POW, MAX_POW>; float work_f = 0; public: float Kf = 0; float f() const { return Kf; } void set_Kf(float f) { Kf = f; } float fTerm() const { return work_f; } void set(float p, float i, float d, float c=1, float f=0) { base::set_Kp(p); base::set_Ki(i); base::set_Kd(d); base::set_Kc(c); set_Kf(f); } void set(const raw_pid_t &raw) { set(raw.p, raw.i, raw.d); } void set(const raw_pidcf_t &raw) { set(raw.p, raw.i, raw.d, raw.c, raw.f); } float get_fan_scale_output(const uint8_t fan_speed) { work_f = 0; if (fan_speed > SCALE_MIN_SPEED) work_f = Kf + (SCALE_LIN_FACTOR) * fan_speed; return work_f; } }; /// @brief Inherits PID and PIDC - can't use proper diamond inheritance w/o virtual template<int MIN_POW, int MAX_POW, int LPQ_ARR_SZ, int SCALE_MIN_SPEED, int SCALE_LIN_FACTOR> struct PIDCF_t : public PIDC_t<MIN_POW, MAX_POW, LPQ_ARR_SZ> { private: using base = PID_t<MIN_POW, MAX_POW>; using cPID = PIDC_t<MIN_POW, MAX_POW, LPQ_ARR_SZ>; float work_f = 0; public: float Kf = 0; float c() const { return cPID::c(); } float f() const { return Kf; } void set_Kc(float c) { cPID::set_Kc(c); } void set_Kf(float f) { Kf = f; } float cTerm() const { return cPID::cTerm(); } float fTerm() const { return work_f; } void set(float p, float i, float d, float c=1, float f=0) { base::set_Kp(p); base::set_Ki(i); base::set_Kd(d); cPID::set_Kc(c); set_Kf(f); } void set(const raw_pid_t &raw) { set(raw.p, raw.i, raw.d); } void set(const raw_pidcf_t &raw) { set(raw.p, raw.i, raw.d, raw.c, raw.f); } void reset() { cPID::reset(); } float get_fan_scale_output(const uint8_t fan_speed) { work_f = fan_speed > (SCALE_MIN_SPEED) ? Kf + (SCALE_LIN_FACTOR) * fan_speed : 0; return work_f; } float get_extrusion_scale_output(const bool is_active, const int32_t e_position, const float e_mm_per_step, const int16_t lpq_len) { return cPID::get_extrusion_scale_output(is_active, e_position, e_mm_per_step, lpq_len); } }; typedef #if ALL(PID_EXTRUSION_SCALING, PID_FAN_SCALING) PIDCF_t<0, PID_MAX, LPQ_MAX_LEN, PID_FAN_SCALING_MIN_SPEED, PID_FAN_SCALING_LIN_FACTOR> #elif ENABLED(PID_EXTRUSION_SCALING) PIDC_t<0, PID_MAX, LPQ_MAX_LEN> #elif ENABLED(PID_FAN_SCALING) PIDF_t<0, PID_MAX, PID_FAN_SCALING_MIN_SPEED, PID_FAN_SCALING_LIN_FACTOR> #else PID_t<0, PID_MAX> #endif hotend_pid_t; #if ENABLED(PID_PARAMS_PER_HOTEND) #define SET_HOTEND_PID(F,H,V) thermalManager.temp_hotend[H].pid.set_##F(V) #else #define SET_HOTEND_PID(F,_,V) do{ HOTEND_LOOP() thermalManager.temp_hotend[e].pid.set_##F(V); }while(0) #endif #elif ENABLED(MPCTEMP) typedef struct MPC { static bool e_paused; // Pause E filament permm tracking static int32_t e_position; // For E tracking float heater_power; // M306 P float block_heat_capacity; // M306 C float sensor_responsiveness; // M306 R float ambient_xfer_coeff_fan0; // M306 A float filament_heat_capacity_permm; // M306 H #if ENABLED(MPC_INCLUDE_FAN) float fan255_adjustment; // M306 F void applyFanAdjustment(const_float_t cf) { fan255_adjustment = cf - ambient_xfer_coeff_fan0; } #else void applyFanAdjustment(const_float_t) {} #endif float fanCoefficient() { return SUM_TERN(MPC_INCLUDE_FAN, ambient_xfer_coeff_fan0, fan255_adjustment); } } MPC_t; #define MPC_dT ((OVERSAMPLENR * float(ACTUAL_ADC_SAMPLES)) / (TEMP_TIMER_FREQUENCY)) #endif #if ENABLED(G26_MESH_VALIDATION) && ANY(HAS_MARLINUI_MENU, EXTENSIBLE_UI) #define G26_CLICK_CAN_CANCEL 1 #endif // A temperature sensor typedef struct TempInfo { private: raw_adc_t acc; raw_adc_t raw; public: celsius_float_t celsius; inline void reset() { acc = 0; } inline void sample(const raw_adc_t s) { acc += s; } inline void update() { raw = acc; } void setraw(const raw_adc_t r) { raw = r; } raw_adc_t getraw() const { return raw; } } temp_info_t; #if HAS_TEMP_REDUNDANT // A redundant temperature sensor typedef struct RedundantTempInfo : public TempInfo { temp_info_t* target; } redundant_info_t; #endif // A PWM heater with temperature sensor typedef struct HeaterInfo : public TempInfo { celsius_t target; uint8_t soft_pwm_amount; bool is_below_target(const celsius_t offs=0) const { return (target - celsius > offs); } // celsius < target - offs bool is_above_target(const celsius_t offs=0) const { return (celsius - target > offs); } // celsius > target + offs } heater_info_t; // A heater with PID stabilization template<typename T> struct PIDHeaterInfo : public HeaterInfo { T pid; // Initialized by settings.load() }; #if ENABLED(MPCTEMP) struct MPCHeaterInfo : public HeaterInfo { MPC_t mpc; float modeled_ambient_temp, modeled_block_temp, modeled_sensor_temp; float fanCoefficient() { return mpc.fanCoefficient(); } void applyFanAdjustment(const_float_t cf) { mpc.applyFanAdjustment(cf); } }; #endif #if ENABLED(PIDTEMP) typedef struct PIDHeaterInfo<hotend_pid_t> hotend_info_t; #elif ENABLED(MPCTEMP) typedef struct MPCHeaterInfo hotend_info_t; #else typedef heater_info_t hotend_info_t; #endif #if HAS_HEATED_BED #if ENABLED(PIDTEMPBED) typedef struct PIDHeaterInfo<PID_t<MIN_BED_POWER, MAX_BED_POWER>> bed_info_t; #else typedef heater_info_t bed_info_t; #endif #endif #if HAS_HEATED_CHAMBER #if ENABLED(PIDTEMPCHAMBER) typedef struct PIDHeaterInfo<PID_t<MIN_CHAMBER_POWER, MAX_CHAMBER_POWER>> chamber_info_t; #else typedef heater_info_t chamber_info_t; #endif #elif HAS_TEMP_CHAMBER typedef temp_info_t chamber_info_t; #endif #if HAS_TEMP_PROBE typedef temp_info_t probe_info_t; #endif #if ANY(HAS_COOLER, HAS_TEMP_COOLER) typedef heater_info_t cooler_info_t; #endif #if HAS_TEMP_BOARD typedef temp_info_t board_info_t; #endif #if HAS_TEMP_SOC typedef temp_info_t soc_info_t; #endif // Heater watch handling template <int INCREASE, int HYSTERESIS, millis_t PERIOD> struct HeaterWatch { celsius_t target; millis_t next_ms; inline bool elapsed(const millis_t &ms) { return next_ms && ELAPSED(ms, next_ms); } inline bool elapsed() { return elapsed(millis()); } inline bool check(const celsius_t curr) { return curr >= target; } inline void restart(const celsius_t curr, const celsius_t tgt) { if (tgt) { const celsius_t newtarget = curr + INCREASE; if (newtarget < tgt - HYSTERESIS - 1) { target = newtarget; next_ms = millis() + SEC_TO_MS(PERIOD); return; } } next_ms = 0; } }; #if WATCH_HOTENDS typedef struct HeaterWatch<WATCH_TEMP_INCREASE, TEMP_HYSTERESIS, WATCH_TEMP_PERIOD> hotend_watch_t; #endif #if WATCH_BED typedef struct HeaterWatch<WATCH_BED_TEMP_INCREASE, TEMP_BED_HYSTERESIS, WATCH_BED_TEMP_PERIOD> bed_watch_t; #endif #if WATCH_CHAMBER typedef struct HeaterWatch<WATCH_CHAMBER_TEMP_INCREASE, TEMP_CHAMBER_HYSTERESIS, WATCH_CHAMBER_TEMP_PERIOD> chamber_watch_t; #endif #if WATCH_COOLER typedef struct HeaterWatch<WATCH_COOLER_TEMP_INCREASE, TEMP_COOLER_HYSTERESIS, WATCH_COOLER_TEMP_PERIOD> cooler_watch_t; #endif // Just raw temperature sensor ranges typedef struct { raw_adc_t raw_min, raw_max; } temp_raw_range_t; // Temperature sensor read value ranges typedef struct { raw_adc_t raw_min, raw_max; celsius_t mintemp, maxtemp; } temp_range_t; #define THERMISTOR_ABS_ZERO_C -273.15f // bbbbrrrrr cold ! #define THERMISTOR_RESISTANCE_NOMINAL_C 25.0f // mmmmm comfortable #if HAS_USER_THERMISTORS enum CustomThermistorIndex : uint8_t { #if TEMP_SENSOR_0_IS_CUSTOM CTI_HOTEND_0, #endif #if TEMP_SENSOR_1_IS_CUSTOM CTI_HOTEND_1, #endif #if TEMP_SENSOR_2_IS_CUSTOM CTI_HOTEND_2, #endif #if TEMP_SENSOR_3_IS_CUSTOM CTI_HOTEND_3, #endif #if TEMP_SENSOR_4_IS_CUSTOM CTI_HOTEND_4, #endif #if TEMP_SENSOR_5_IS_CUSTOM CTI_HOTEND_5, #endif #if TEMP_SENSOR_BED_IS_CUSTOM CTI_BED, #endif #if TEMP_SENSOR_CHAMBER_IS_CUSTOM CTI_CHAMBER, #endif #if TEMP_SENSOR_PROBE_IS_CUSTOM CTI_PROBE, #endif #if TEMP_SENSOR_COOLER_IS_CUSTOM CTI_COOLER, #endif #if TEMP_SENSOR_BOARD_IS_CUSTOM CTI_BOARD, #endif #if TEMP_SENSOR_REDUNDANT_IS_CUSTOM CTI_REDUNDANT, #endif USER_THERMISTORS }; // User-defined thermistor typedef struct { bool pre_calc; // true if pre-calculations update needed float sh_c_coeff, // Steinhart-Hart C coefficient .. defaults to '0.0' sh_alpha, series_res, res_25, res_25_recip, res_25_log, beta, beta_recip; } user_thermistor_t; #endif #if HAS_AUTO_FAN || HAS_FANCHECK #define HAS_FAN_LOGIC 1 #endif class Temperature { public: #if HAS_HOTEND static hotend_info_t temp_hotend[HOTENDS]; static constexpr celsius_t hotend_maxtemp[HOTENDS] = ARRAY_BY_HOTENDS(HEATER_0_MAXTEMP, HEATER_1_MAXTEMP, HEATER_2_MAXTEMP, HEATER_3_MAXTEMP, HEATER_4_MAXTEMP, HEATER_5_MAXTEMP, HEATER_6_MAXTEMP, HEATER_7_MAXTEMP); static constexpr celsius_t hotend_max_target(const uint8_t e) { return hotend_maxtemp[e] - (HOTEND_OVERSHOOT); } #endif #if HAS_HEATED_BED static bed_info_t temp_bed; #endif #if HAS_TEMP_PROBE static probe_info_t temp_probe; #endif #if HAS_TEMP_CHAMBER static chamber_info_t temp_chamber; #endif #if HAS_TEMP_COOLER static cooler_info_t temp_cooler; #endif #if HAS_TEMP_BOARD static board_info_t temp_board; #endif #if HAS_TEMP_SOC static soc_info_t temp_soc; #endif #if HAS_TEMP_REDUNDANT static redundant_info_t temp_redundant; #endif #if ANY(AUTO_POWER_E_FANS, HAS_FANCHECK) static uint8_t autofan_speed[HOTENDS]; #endif #if ENABLED(AUTO_POWER_CHAMBER_FAN) static uint8_t chamberfan_speed; #endif #if ENABLED(AUTO_POWER_COOLER_FAN) static uint8_t coolerfan_speed; #endif #if ENABLED(FAN_SOFT_PWM) static uint8_t soft_pwm_amount_fan[FAN_COUNT], soft_pwm_count_fan[FAN_COUNT]; #endif #if ALL(FAN_SOFT_PWM, USE_CONTROLLER_FAN) static uint8_t soft_pwm_controller_speed; #endif #if ALL(HAS_MARLINUI_MENU, PREVENT_COLD_EXTRUSION) && E_MANUAL > 0 static bool allow_cold_extrude_override; static void set_menu_cold_override(const bool allow) { allow_cold_extrude_override = allow; } #else static constexpr bool allow_cold_extrude_override = false; static void set_menu_cold_override(const bool) {} #endif #if ENABLED(PREVENT_COLD_EXTRUSION) static bool allow_cold_extrude; static celsius_t extrude_min_temp; static bool tooCold(const celsius_t temp) { return !allow_cold_extrude && !allow_cold_extrude_override && temp < extrude_min_temp - (TEMP_WINDOW); } static bool tooColdToExtrude(const uint8_t E_NAME) { return tooCold(wholeDegHotend(HOTEND_INDEX)); } static bool targetTooColdToExtrude(const uint8_t E_NAME) { return tooCold(degTargetHotend(HOTEND_INDEX)); } #else static constexpr bool allow_cold_extrude = true; static constexpr celsius_t extrude_min_temp = 0; static bool tooColdToExtrude(const uint8_t) { return false; } static bool targetTooColdToExtrude(const uint8_t) { return false; } #endif static bool hotEnoughToExtrude(const uint8_t e) { return !tooColdToExtrude(e); } static bool targetHotEnoughToExtrude(const uint8_t e) { return !targetTooColdToExtrude(e); } #if ANY(SINGLENOZZLE_STANDBY_TEMP, SINGLENOZZLE_STANDBY_FAN) #if ENABLED(SINGLENOZZLE_STANDBY_TEMP) static celsius_t singlenozzle_temp[EXTRUDERS]; #endif #if ENABLED(SINGLENOZZLE_STANDBY_FAN) static uint8_t singlenozzle_fan_speed[EXTRUDERS]; #endif static void singlenozzle_change(const uint8_t old_tool, const uint8_t new_tool); #endif #if HEATER_IDLE_HANDLER // Heater idle handling. Marlin creates one per hotend and one for the heated bed. typedef struct { millis_t timeout_ms; bool timed_out; inline void update(const millis_t &ms) { if (!timed_out && timeout_ms && ELAPSED(ms, timeout_ms)) timed_out = true; } inline void start(const millis_t &ms) { timeout_ms = millis() + ms; timed_out = false; } inline void reset() { timeout_ms = 0; timed_out = false; } inline void expire() { start(0); } } heater_idle_t; // Indices and size for the heater_idle array enum IdleIndex : int8_t { _II = -1 #define _IDLE_INDEX_E(N) ,IDLE_INDEX_E##N REPEAT(HOTENDS, _IDLE_INDEX_E) #undef _IDLE_INDEX_E OPTARG(HAS_HEATED_BED, IDLE_INDEX_BED) , NR_HEATER_IDLE }; // Convert the given heater_id_t to idle array index static IdleIndex idle_index_for_id(const int8_t heater_id) { OPTCODE(HAS_HEATED_BED, if (heater_id == H_BED) return IDLE_INDEX_BED) return (IdleIndex)_MAX(heater_id, 0); } static heater_idle_t heater_idle[NR_HEATER_IDLE]; #endif // HEATER_IDLE_TIMER #if HAS_ADC_BUTTONS static uint32_t current_ADCKey_raw; static uint16_t ADCKey_count; #endif #if ENABLED(PID_EXTRUSION_SCALING) static int16_t lpq_len; #endif #if HAS_FAN_LOGIC static constexpr millis_t fan_update_interval_ms = TERN(HAS_PWMFANCHECK, 5000, TERN(HAS_FANCHECK, 1000, 2500)); #endif private: #if ENABLED(WATCH_HOTENDS) static hotend_watch_t watch_hotend[HOTENDS]; #endif #if HAS_HOTEND // Sensor ranges, not user-configured static temp_range_t temp_range[HOTENDS]; #endif #if HAS_HEATED_BED #if WATCH_BED static bed_watch_t watch_bed; #endif #if DISABLED(PIDTEMPBED) static millis_t next_bed_check_ms; #endif static temp_raw_range_t temp_sensor_range_bed; #endif #if HAS_HEATED_CHAMBER #if WATCH_CHAMBER static chamber_watch_t watch_chamber; #endif #if DISABLED(PIDTEMPCHAMBER) static millis_t next_chamber_check_ms; #endif static temp_raw_range_t temp_sensor_range_chamber; #endif #if HAS_COOLER #if WATCH_COOLER static cooler_watch_t watch_cooler; #endif static millis_t next_cooler_check_ms, cooler_fan_flush_ms; static temp_raw_range_t temp_sensor_range_cooler; #endif #if ALL(HAS_TEMP_BOARD, THERMAL_PROTECTION_BOARD) static temp_raw_range_t temp_sensor_range_board; #endif #if ALL(HAS_TEMP_SOC, THERMAL_PROTECTION_SOC) static raw_adc_t maxtemp_raw_SOC; #endif #if MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED > 1 static uint8_t consecutive_low_temperature_error[HOTENDS]; #endif #if HAS_FAN_LOGIC static millis_t fan_update_ms; static void manage_extruder_fans(millis_t ms) { if (ELAPSED(ms, fan_update_ms)) { // only need to check fan state very infrequently const millis_t next_ms = ms + fan_update_interval_ms; #if HAS_PWMFANCHECK #define FAN_CHECK_DURATION 100 if (fan_check.is_measuring()) { fan_check.compute_speed(ms + FAN_CHECK_DURATION - fan_update_ms); fan_update_ms = next_ms; } else fan_update_ms = ms + FAN_CHECK_DURATION; fan_check.toggle_measuring(); #else TERN_(HAS_FANCHECK, fan_check.compute_speed(next_ms - fan_update_ms)); fan_update_ms = next_ms; #endif TERN_(HAS_AUTO_FAN, update_autofans()); // Needed as last when HAS_PWMFANCHECK to properly force fan speed } } #endif #if ENABLED(PROBING_HEATERS_OFF) static bool paused_for_probing; #endif public: /** * Instance Methods */ void init(); /** * Static (class) methods */ #if HAS_USER_THERMISTORS static user_thermistor_t user_thermistor[USER_THERMISTORS]; static void M305_report(const uint8_t t_index, const bool forReplay=true); static void reset_user_thermistors(); static celsius_float_t user_thermistor_to_deg_c(const uint8_t t_index, const raw_adc_t raw); static bool set_pull_up_res(int8_t t_index, float value) { //if (!WITHIN(t_index, 0, USER_THERMISTORS - 1)) return false; if (!WITHIN(value, 1, 1000000)) return false; user_thermistor[t_index].series_res = value; return true; } static bool set_res25(int8_t t_index, float value) { if (!WITHIN(value, 1, 10000000)) return false; user_thermistor[t_index].res_25 = value; user_thermistor[t_index].pre_calc = true; return true; } static bool set_beta(int8_t t_index, float value) { if (!WITHIN(value, 1, 1000000)) return false; user_thermistor[t_index].beta = value; user_thermistor[t_index].pre_calc = true; return true; } static bool set_sh_coeff(int8_t t_index, float value) { if (!WITHIN(value, -0.01f, 0.01f)) return false; user_thermistor[t_index].sh_c_coeff = value; user_thermistor[t_index].pre_calc = true; return true; } #endif #if HAS_HOTEND static celsius_float_t analog_to_celsius_hotend(const raw_adc_t raw, const uint8_t e); #endif #if HAS_HEATED_BED static celsius_float_t analog_to_celsius_bed(const raw_adc_t raw); #endif #if HAS_TEMP_CHAMBER static celsius_float_t analog_to_celsius_chamber(const raw_adc_t raw); #endif #if HAS_TEMP_PROBE static celsius_float_t analog_to_celsius_probe(const raw_adc_t raw); #endif #if HAS_TEMP_COOLER static celsius_float_t analog_to_celsius_cooler(const raw_adc_t raw); #endif #if HAS_TEMP_BOARD static celsius_float_t analog_to_celsius_board(const raw_adc_t raw); #endif #if HAS_TEMP_SOC static celsius_float_t analog_to_celsius_soc(const raw_adc_t raw); #endif #if HAS_TEMP_REDUNDANT static celsius_float_t analog_to_celsius_redundant(const raw_adc_t raw); #endif #if HAS_FAN static uint8_t fan_speed[FAN_COUNT]; #define FANS_LOOP(I) for (uint8_t I = 0; I < FAN_COUNT; ++I) static void set_fan_speed(const uint8_t fan, const uint16_t speed); #if ENABLED(REPORT_FAN_CHANGE) static void report_fan_speed(const uint8_t fan); #endif #if ANY(PROBING_FANS_OFF, ADVANCED_PAUSE_FANS_PAUSE) static bool fans_paused; static uint8_t saved_fan_speed[FAN_COUNT]; #endif #if ENABLED(ADAPTIVE_FAN_SLOWING) static uint8_t fan_speed_scaler[FAN_COUNT]; #endif static uint8_t scaledFanSpeed(const uint8_t fan, const uint8_t fs) { UNUSED(fan); // Potentially unused! return (fs * uint16_t(TERN(ADAPTIVE_FAN_SLOWING, fan_speed_scaler[fan], 128))) >> 7; } static uint8_t scaledFanSpeed(const uint8_t fan) { return scaledFanSpeed(fan, fan_speed[fan]); } static constexpr inline uint8_t pwmToPercent(const uint8_t speed) { return ui8_to_percent(speed); } static uint8_t fanSpeedPercent(const uint8_t fan) { return ui8_to_percent(fan_speed[fan]); } static uint8_t scaledFanSpeedPercent(const uint8_t fan) { return ui8_to_percent(scaledFanSpeed(fan)); } #if ENABLED(EXTRA_FAN_SPEED) typedef struct { uint8_t saved, speed; } extra_fan_t; static extra_fan_t extra_fan_speed[FAN_COUNT]; static void set_temp_fan_speed(const uint8_t fan, const uint16_t command_or_speed); #endif #if ANY(PROBING_FANS_OFF, ADVANCED_PAUSE_FANS_PAUSE) void set_fans_paused(const bool p); #endif #endif // HAS_FAN static void zero_fan_speeds() { #if HAS_FAN FANS_LOOP(i) set_fan_speed(i, 0); #endif } /** * Called from the Temperature ISR */ static void isr(); static void readings_ready(); /** * Call periodically to manage heaters and keep the watchdog fed */ static void task(); /** * Preheating hotends & bed */ #if PREHEAT_TIME_HOTEND_MS > 0 static millis_t preheat_end_ms_hotend[HOTENDS]; static bool is_hotend_preheating(const uint8_t E_NAME) { return preheat_end_ms_hotend[HOTEND_INDEX] && PENDING(millis(), preheat_end_ms_hotend[HOTEND_INDEX]); } static void start_hotend_preheat_time(const uint8_t E_NAME) { preheat_end_ms_hotend[HOTEND_INDEX] = millis() + PREHEAT_TIME_HOTEND_MS; } static void reset_hotend_preheat_time(const uint8_t E_NAME) { preheat_end_ms_hotend[HOTEND_INDEX] = 0; } #else static bool is_hotend_preheating(const uint8_t) { return false; } #endif #if HAS_HEATED_BED #if PREHEAT_TIME_BED_MS > 0 static millis_t preheat_end_ms_bed; static bool is_bed_preheating() { return preheat_end_ms_bed && PENDING(millis(), preheat_end_ms_bed); } static void start_bed_preheat_time() { preheat_end_ms_bed = millis() + PREHEAT_TIME_BED_MS; } static void reset_bed_preheat_time() { preheat_end_ms_bed = 0; } #else static bool is_bed_preheating() { return false; } #endif #endif //high level conversion routines, for use outside of temperature.cpp //inline so that there is no performance decrease. //deg=degreeCelsius static celsius_float_t degHotend(const uint8_t E_NAME) { return TERN0(HAS_HOTEND, temp_hotend[HOTEND_INDEX].celsius); } static celsius_t wholeDegHotend(const uint8_t E_NAME) { return TERN0(HAS_HOTEND, static_cast<celsius_t>(temp_hotend[HOTEND_INDEX].celsius + 0.5f)); } #if ENABLED(SHOW_TEMP_ADC_VALUES) static raw_adc_t rawHotendTemp(const uint8_t E_NAME) { return TERN0(HAS_HOTEND, temp_hotend[HOTEND_INDEX].getraw()); } #endif static celsius_t degTargetHotend(const uint8_t E_NAME) { return TERN0(HAS_HOTEND, temp_hotend[HOTEND_INDEX].target); } #if HAS_HOTEND static void setTargetHotend(const celsius_t celsius, const uint8_t E_NAME) { const uint8_t ee = HOTEND_INDEX; #if PREHEAT_TIME_HOTEND_MS > 0 if (celsius == 0) reset_hotend_preheat_time(ee); else if (temp_hotend[ee].target == 0) start_hotend_preheat_time(ee); #endif TERN_(AUTO_POWER_CONTROL, if (celsius) powerManager.power_on()); temp_hotend[ee].target = _MIN(celsius, hotend_max_target(ee)); start_watching_hotend(ee); } static bool isHeatingHotend(const uint8_t E_NAME) { return temp_hotend[HOTEND_INDEX].target > temp_hotend[HOTEND_INDEX].celsius; } static bool isCoolingHotend(const uint8_t E_NAME) { return temp_hotend[HOTEND_INDEX].target < temp_hotend[HOTEND_INDEX].celsius; } #if HAS_TEMP_HOTEND static bool wait_for_hotend(const uint8_t target_extruder, const bool no_wait_for_cooling=true OPTARG(G26_CLICK_CAN_CANCEL, const bool click_to_cancel=false) ); #if ENABLED(WAIT_FOR_HOTEND) static void wait_for_hotend_heating(const uint8_t target_extruder); #endif #endif static bool still_heating(const uint8_t e) { return degTargetHotend(e) > TEMP_HYSTERESIS && ABS(wholeDegHotend(e) - degTargetHotend(e)) > TEMP_HYSTERESIS; } static bool degHotendNear(const uint8_t e, const celsius_t temp) { return ABS(wholeDegHotend(e) - temp) < (TEMP_HYSTERESIS); } // Start watching a Hotend to make sure it's really heating up static void start_watching_hotend(const uint8_t E_NAME) { UNUSED(HOTEND_INDEX); #if WATCH_HOTENDS watch_hotend[HOTEND_INDEX].restart(degHotend(HOTEND_INDEX), degTargetHotend(HOTEND_INDEX)); #endif } static void manage_hotends(const millis_t &ms); #endif // HAS_HOTEND #if HAS_HEATED_BED #if ENABLED(SHOW_TEMP_ADC_VALUES) static raw_adc_t rawBedTemp() { return temp_bed.getraw(); } #endif static celsius_float_t degBed() { return temp_bed.celsius; } static celsius_t wholeDegBed() { return static_cast<celsius_t>(degBed() + 0.5f); } static celsius_t degTargetBed() { return temp_bed.target; } static bool isHeatingBed() { return temp_bed.target > temp_bed.celsius; } static bool isCoolingBed() { return temp_bed.target < temp_bed.celsius; } static bool degBedNear(const celsius_t temp) { return ABS(wholeDegBed() - temp) < (TEMP_BED_HYSTERESIS); } // Start watching the Bed to make sure it's really heating up static void start_watching_bed() { OPTCODE(WATCH_BED, watch_bed.restart(degBed(), degTargetBed())) } static void setTargetBed(const celsius_t celsius) { #if PREHEAT_TIME_BED_MS > 0 if (celsius == 0) reset_bed_preheat_time(); else if (temp_bed.target == 0) start_bed_preheat_time(); #endif TERN_(AUTO_POWER_CONTROL, if (celsius) powerManager.power_on()); temp_bed.target = _MIN(celsius, BED_MAX_TARGET); start_watching_bed(); } static bool wait_for_bed(const bool no_wait_for_cooling=true OPTARG(G26_CLICK_CAN_CANCEL, const bool click_to_cancel=false) ); static void wait_for_bed_heating(); static void manage_heated_bed(const millis_t &ms); #endif // HAS_HEATED_BED #if HAS_TEMP_PROBE #if ENABLED(SHOW_TEMP_ADC_VALUES) static raw_adc_t rawProbeTemp() { return temp_probe.getraw(); } #endif static celsius_float_t degProbe() { return temp_probe.celsius; } static celsius_t wholeDegProbe() { return static_cast<celsius_t>(degProbe() + 0.5f); } static bool isProbeBelowTemp(const celsius_t target_temp) { return wholeDegProbe() < target_temp; } static bool isProbeAboveTemp(const celsius_t target_temp) { return wholeDegProbe() > target_temp; } static bool wait_for_probe(const celsius_t target_temp, bool no_wait_for_cooling=true); #endif #if HAS_TEMP_CHAMBER #if ENABLED(SHOW_TEMP_ADC_VALUES) static raw_adc_t rawChamberTemp() { return temp_chamber.getraw(); } #endif static celsius_float_t degChamber() { return temp_chamber.celsius; } static celsius_t wholeDegChamber() { return static_cast<celsius_t>(degChamber() + 0.5f); } #if HAS_HEATED_CHAMBER static celsius_t degTargetChamber() { return temp_chamber.target; } static bool isHeatingChamber() { return temp_chamber.target > temp_chamber.celsius; } static bool isCoolingChamber() { return temp_chamber.target < temp_chamber.celsius; } static bool wait_for_chamber(const bool no_wait_for_cooling=true); static void manage_heated_chamber(const millis_t &ms); #endif #endif #if HAS_HEATED_CHAMBER static void setTargetChamber(const celsius_t celsius) { temp_chamber.target = _MIN(celsius, CHAMBER_MAX_TARGET); start_watching_chamber(); } // Start watching the Chamber to make sure it's really heating up static void start_watching_chamber() { OPTCODE(WATCH_CHAMBER, watch_chamber.restart(degChamber(), degTargetChamber())) } #endif #if HAS_TEMP_COOLER #if ENABLED(SHOW_TEMP_ADC_VALUES) static raw_adc_t rawCoolerTemp() { return temp_cooler.getraw(); } #endif static celsius_float_t degCooler() { return temp_cooler.celsius; } static celsius_t wholeDegCooler() { return static_cast<celsius_t>(temp_cooler.celsius + 0.5f); } #if HAS_COOLER static celsius_t degTargetCooler() { return temp_cooler.target; } static bool isLaserHeating() { return temp_cooler.target > temp_cooler.celsius; } static bool isLaserCooling() { return temp_cooler.target < temp_cooler.celsius; } static bool wait_for_cooler(const bool no_wait_for_cooling=true); static void manage_cooler(const millis_t &ms); #endif #endif #if HAS_TEMP_BOARD #if ENABLED(SHOW_TEMP_ADC_VALUES) static raw_adc_t rawBoardTemp() { return temp_board.getraw(); } #endif static celsius_float_t degBoard() { return temp_board.celsius; } static celsius_t wholeDegBoard() { return static_cast<celsius_t>(temp_board.celsius + 0.5f); } #endif #if HAS_TEMP_SOC #if ENABLED(SHOW_TEMP_ADC_VALUES) static raw_adc_t rawSocTemp() { return temp_soc.getraw(); } #endif static celsius_float_t degSoc() { return temp_soc.celsius; } static celsius_t wholeDegSoc() { return static_cast<celsius_t>(temp_soc.celsius + 0.5f); } #endif #if HAS_TEMP_REDUNDANT #if ENABLED(SHOW_TEMP_ADC_VALUES) static raw_adc_t rawRedundantTemp() { return temp_redundant.getraw(); } #endif static celsius_float_t degRedundant() { return temp_redundant.celsius; } static celsius_float_t degRedundantTarget() { return (*temp_redundant.target).celsius; } static celsius_t wholeDegRedundant() { return static_cast<celsius_t>(temp_redundant.celsius + 0.5f); } static celsius_t wholeDegRedundantTarget() { return static_cast<celsius_t>((*temp_redundant.target).celsius + 0.5f); } #endif #if HAS_COOLER static void setTargetCooler(const celsius_t celsius) { temp_cooler.target = constrain(celsius, COOLER_MIN_TARGET, COOLER_MAX_TARGET); start_watching_cooler(); } // Start watching the Cooler to make sure it's really cooling down static void start_watching_cooler() { OPTCODE(WATCH_COOLER, watch_cooler.restart(degCooler(), degTargetCooler())) } #endif /** * The software PWM power for a heater */ static int16_t getHeaterPower(const heater_id_t heater_id); /** * Switch off all heaters, set all target temperatures to 0 */ static void disable_all_heaters(); /** * Cooldown, as from the LCD. Disables all heaters and fans. */ static void cooldown() { zero_fan_speeds(); disable_all_heaters(); } #if ENABLED(PRINTJOB_TIMER_AUTOSTART) /** * Methods to check if heaters are enabled, indicating an active job */ static bool auto_job_over_threshold(); static void auto_job_check_timer(const bool can_start, const bool can_stop); #endif #if ENABLED(TEMP_TUNING_MAINTAIN_FAN) static bool adaptive_fan_slowing; #elif ENABLED(ADAPTIVE_FAN_SLOWING) static constexpr bool adaptive_fan_slowing = true; #endif static bool tuning_idle(const millis_t &ms); /** * M303 PID auto-tuning for hotends or bed */ #if HAS_PID_HEATING #if HAS_PID_DEBUG static bool pid_debug_flag; #endif static void PID_autotune(const celsius_t target, const heater_id_t heater_id, const int8_t ncycles, const bool set_result=false); // Update the temp manager when PID values change #if ENABLED(PIDTEMP) static void updatePID() { HOTEND_LOOP() temp_hotend[e].pid.reset(); } static void setPID(const uint8_t hotend, const_float_t p, const_float_t i, const_float_t d) { #if ENABLED(PID_PARAMS_PER_HOTEND) temp_hotend[hotend].pid.set(p, i, d); #else HOTEND_LOOP() temp_hotend[e].pid.set(p, i, d); #endif updatePID(); } #endif #endif // HAS_PID_HEATING /** * M306 MPC auto-tuning for hotends */ #if ENABLED(MPC_AUTOTUNE) // Utility class to perform MPCTEMP auto tuning measurements class MPC_autotuner { public: enum MeasurementState { CANCELLED, FAILED, SUCCESS }; MPC_autotuner(const uint8_t extruderIdx); ~MPC_autotuner(); MeasurementState measure_ambient_temp(); MeasurementState measure_heatup(); MeasurementState measure_transfer(); celsius_float_t get_ambient_temp() { return ambient_temp; } celsius_float_t get_last_measured_temp() { return current_temp; } float get_elapsed_heating_time() { return elapsed_heating_time; } float get_sample_1_time() { return t1_time; } static float get_sample_1_temp() { return temp_samples[0]; } static float get_sample_2_temp() { return temp_samples[(sample_count - 1) >> 1]; } static float get_sample_3_temp() { return temp_samples[sample_count - 1]; } static float get_sample_interval() { return sample_distance * (sample_count >> 1); } static celsius_float_t get_temp_fastest() { return temp_fastest; } float get_time_fastest() { return time_fastest; } float get_rate_fastest() { return rate_fastest; } float get_power_fan0() { return power_fan0; } #if HAS_FAN static float get_power_fan255() { return power_fan255; } #endif protected: static void init_timers() { curr_time_ms = next_report_ms = millis(); } MeasurementState housekeeping(); uint8_t e; float elapsed_heating_time; celsius_float_t ambient_temp, current_temp; float t1_time; static millis_t curr_time_ms, next_report_ms; static celsius_float_t temp_samples[16]; static uint8_t sample_count; static uint16_t sample_distance; // Parameters from differential analysis static celsius_float_t temp_fastest; float time_fastest, rate_fastest; float power_fan0; #if HAS_FAN static float power_fan255; #endif }; enum MPCTuningType { AUTO, FORCE_ASYMPTOTIC, FORCE_DIFFERENTIAL }; static void MPC_autotune(const uint8_t e, MPCTuningType tuning_type); #endif // MPC_AUTOTUNE #if ENABLED(PROBING_HEATERS_OFF) static void pause_heaters(const bool p); #endif #if HEATER_IDLE_HANDLER static void reset_hotend_idle_timer(const uint8_t E_NAME) { heater_idle[HOTEND_INDEX].reset(); start_watching_hotend(HOTEND_INDEX); } #if HAS_HEATED_BED static void reset_bed_idle_timer() { heater_idle[IDLE_INDEX_BED].reset(); start_watching_bed(); } #endif #endif // HEATER_IDLE_HANDLER #if HAS_TEMP_SENSOR static void print_heater_states(const int8_t target_extruder OPTARG(HAS_TEMP_REDUNDANT, const bool include_r=false) ); #if ENABLED(AUTO_REPORT_TEMPERATURES) struct AutoReportTemp { static void report(); }; static AutoReporter<AutoReportTemp> auto_reporter; #endif #endif #if HAS_HOTEND && HAS_STATUS_MESSAGE static void set_heating_message(const uint8_t e, const bool isM104=false); #else static void set_heating_message(const uint8_t, const bool=false) {} #endif #if HAS_MARLINUI_MENU && HAS_TEMPERATURE && HAS_PREHEAT static void lcd_preheat(const uint8_t e, const int8_t indh, const int8_t indb); #endif private: // Reading raw temperatures and converting to Celsius when ready static volatile bool raw_temps_ready; static void update_raw_temperatures(); static void updateTemperaturesFromRawValues(); static bool updateTemperaturesIfReady() { if (!raw_temps_ready) return false; updateTemperaturesFromRawValues(); raw_temps_ready = false; return true; } // MAX Thermocouples #if HAS_MAX_TC #define MAX_TC_COUNT TEMP_SENSOR_IS_MAX_TC(0) + TEMP_SENSOR_IS_MAX_TC(1) + TEMP_SENSOR_IS_MAX_TC(2) + TEMP_SENSOR_IS_MAX_TC(REDUNDANT) #if MAX_TC_COUNT > 1 #define HAS_MULTI_MAX_TC 1 #endif #define READ_MAX_TC(N) read_max_tc(TERN_(HAS_MULTI_MAX_TC, N)) static raw_adc_t read_max_tc(TERN_(HAS_MULTI_MAX_TC, const uint8_t hindex=0)); #endif #if TEMP_SENSOR_IS_MAX_TC(BED) static raw_adc_t read_max_tc_bed(); #endif #if HAS_AUTO_FAN #if ENABLED(POWER_OFF_WAIT_FOR_COOLDOWN) static bool autofans_on; #endif static void update_autofans(); #endif #if HAS_HOTEND static float get_pid_output_hotend(const uint8_t e); #endif #if ENABLED(PIDTEMPBED) static float get_pid_output_bed(); #endif #if ENABLED(PIDTEMPCHAMBER) static float get_pid_output_chamber(); #endif static void _temp_error(const heater_id_t e, FSTR_P const serial_msg, FSTR_P const lcd_msg OPTARG(ERR_INCLUDE_TEMP, const celsius_float_t deg)); static void mintemp_error(const heater_id_t e OPTARG(ERR_INCLUDE_TEMP, const celsius_float_t deg)); static void maxtemp_error(const heater_id_t e OPTARG(ERR_INCLUDE_TEMP, const celsius_float_t deg)); #define _TEMP_ERROR(e, m, l, d) _temp_error(heater_id_t(e), m, GET_TEXT_F(l) OPTARG(ERR_INCLUDE_TEMP, d)) #define MINTEMP_ERROR(e, d) mintemp_error(heater_id_t(e) OPTARG(ERR_INCLUDE_TEMP, d)) #define MAXTEMP_ERROR(e, d) maxtemp_error(heater_id_t(e) OPTARG(ERR_INCLUDE_TEMP, d)) #define HAS_THERMAL_PROTECTION ANY(THERMAL_PROTECTION_HOTENDS, THERMAL_PROTECTION_CHAMBER, THERMAL_PROTECTION_BED, THERMAL_PROTECTION_COOLER) #if HAS_THERMAL_PROTECTION // Indices and size for the tr_state_machine array. One for each protected heater. enum RunawayIndex : int8_t { _RI = -1 #if ENABLED(THERMAL_PROTECTION_HOTENDS) #define _RUNAWAY_IND_E(N) ,RUNAWAY_IND_E##N REPEAT(HOTENDS, _RUNAWAY_IND_E) #undef _RUNAWAY_IND_E #endif OPTARG(THERMAL_PROTECTION_BED, RUNAWAY_IND_BED) OPTARG(THERMAL_PROTECTION_CHAMBER, RUNAWAY_IND_CHAMBER) OPTARG(THERMAL_PROTECTION_COOLER, RUNAWAY_IND_COOLER) , NR_HEATER_RUNAWAY }; // Convert the given heater_id_t to runaway state array index static RunawayIndex runaway_index_for_id(const int8_t heater_id) { OPTCODE(THERMAL_PROTECTION_CHAMBER, if (heater_id == H_CHAMBER) return RUNAWAY_IND_CHAMBER) OPTCODE(THERMAL_PROTECTION_COOLER, if (heater_id == H_COOLER) return RUNAWAY_IND_COOLER) OPTCODE(THERMAL_PROTECTION_BED, if (heater_id == H_BED) return RUNAWAY_IND_BED) return (RunawayIndex)_MAX(heater_id, 0); } enum TRState : char { TRInactive, TRFirstHeating, TRStable, TRRunaway OPTARG(THERMAL_PROTECTION_VARIANCE_MONITOR, TRMalfunction) }; typedef struct { millis_t timer = 0; TRState state = TRInactive; celsius_float_t running_temp; #if ENABLED(THERMAL_PROTECTION_VARIANCE_MONITOR) millis_t variance_timer = 0; celsius_float_t last_temp = 0.0, variance = 0.0; #endif void run(const_celsius_float_t current, const_celsius_float_t target, const heater_id_t heater_id, const uint16_t period_seconds, const celsius_float_t hysteresis_degc); } tr_state_machine_t; static tr_state_machine_t tr_state_machine[NR_HEATER_RUNAWAY]; #endif // HAS_THERMAL_PROTECTION }; extern Temperature thermalManager;
2301_81045437/Marlin
Marlin/src/module/temperature.h
C++
agpl-3.0
49,166
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // R25 = 100 kOhm, beta25 = 4092 K, 4.7 kOhm pull-up, bed thermistor constexpr temp_entry_t temptable_1[] PROGMEM = { { OV( 18), 320 }, { OV( 19), 315 }, { OV( 20), 310 }, { OV( 22), 305 }, { OV( 23), 300 }, { OV( 25), 295 }, { OV( 27), 290 }, { OV( 28), 285 }, { OV( 31), 280 }, { OV( 33), 275 }, { OV( 35), 270 }, { OV( 38), 265 }, { OV( 41), 260 }, { OV( 44), 255 }, { OV( 48), 250 }, { OV( 52), 245 }, { OV( 56), 240 }, { OV( 61), 235 }, { OV( 66), 230 }, { OV( 71), 225 }, { OV( 78), 220 }, { OV( 84), 215 }, { OV( 92), 210 }, { OV( 100), 205 }, { OV( 109), 200 }, { OV( 120), 195 }, { OV( 131), 190 }, { OV( 143), 185 }, { OV( 156), 180 }, { OV( 171), 175 }, { OV( 187), 170 }, { OV( 205), 165 }, { OV( 224), 160 }, { OV( 245), 155 }, { OV( 268), 150 }, { OV( 293), 145 }, { OV( 320), 140 }, { OV( 348), 135 }, { OV( 379), 130 }, { OV( 411), 125 }, { OV( 445), 120 }, { OV( 480), 115 }, { OV( 516), 110 }, { OV( 553), 105 }, { OV( 591), 100 }, { OV( 628), 95 }, { OV( 665), 90 }, { OV( 702), 85 }, { OV( 737), 80 }, { OV( 770), 75 }, { OV( 801), 70 }, { OV( 830), 65 }, { OV( 857), 60 }, { OV( 881), 55 }, { OV( 903), 50 }, { OV( 922), 45 }, { OV( 939), 40 }, { OV( 954), 35 }, { OV( 966), 30 }, { OV( 977), 25 }, { OV( 985), 20 }, { OV( 993), 15 }, { OV( 999), 10 }, { OV(1004), 5 }, { OV(1008), 0 }, { OV(1012), -5 }, { OV(1016), -10 }, { OV(1020), -15 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_1.h
C++
agpl-3.0
2,424
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // R25 = 100 kOhm, beta25 = 3960 K, 4.7 kOhm pull-up, RS thermistor 198-961 constexpr temp_entry_t temptable_10[] PROGMEM = { { OV( 1), 929 }, { OV( 36), 299 }, { OV( 71), 246 }, { OV( 106), 217 }, { OV( 141), 198 }, { OV( 176), 184 }, { OV( 211), 173 }, { OV( 246), 163 }, { OV( 281), 154 }, { OV( 316), 147 }, { OV( 351), 140 }, { OV( 386), 134 }, { OV( 421), 128 }, { OV( 456), 122 }, { OV( 491), 117 }, { OV( 526), 112 }, { OV( 561), 107 }, { OV( 596), 102 }, { OV( 631), 97 }, { OV( 666), 91 }, { OV( 701), 86 }, { OV( 736), 81 }, { OV( 771), 76 }, { OV( 806), 70 }, { OV( 841), 63 }, { OV( 876), 56 }, { OV( 911), 48 }, { OV( 946), 38 }, { OV( 981), 23 }, { OV(1005), 5 }, { OV(1016), 0 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_10.h
C++
agpl-3.0
1,655
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #define REVERSE_TEMP_SENSOR_RANGE_1010 1 // Pt1000 with 1k0 pullup constexpr temp_entry_t temptable_1010[] PROGMEM = { PtLine( 0, 1000, 1000), PtLine( 25, 1000, 1000), PtLine( 50, 1000, 1000), PtLine( 75, 1000, 1000), PtLine(100, 1000, 1000), PtLine(125, 1000, 1000), PtLine(150, 1000, 1000), PtLine(175, 1000, 1000), PtLine(200, 1000, 1000), PtLine(225, 1000, 1000), PtLine(250, 1000, 1000), PtLine(275, 1000, 1000), PtLine(300, 1000, 1000) };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_1010.h
C++
agpl-3.0
1,349
/** * Marlin 3D Printer Firmware * Copyright (c) 2022 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #define REVERSE_TEMP_SENSOR_RANGE_1022 1 // Pt1000 with 1k0 pullup constexpr temp_entry_t temptable_1022[] PROGMEM = { PtLine( 0, 1000, 2200), PtLine( 25, 1000, 2200), PtLine( 50, 1000, 2200), PtLine( 75, 1000, 2200), PtLine(100, 1000, 2200), PtLine(125, 1000, 2200), PtLine(150, 1000, 2200), PtLine(175, 1000, 2200), PtLine(200, 1000, 2200), PtLine(225, 1000, 2200), PtLine(250, 1000, 2200), PtLine(275, 1000, 2200), PtLine(300, 1000, 2200), PtLine(350, 1000, 2200), PtLine(400, 1000, 2200), PtLine(450, 1000, 2200), PtLine(500, 1000, 2200) };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_1022.h
C++
agpl-3.0
1,457
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #define REVERSE_TEMP_SENSOR_RANGE_1047 1 // Pt1000 with 4k7 pullup constexpr temp_entry_t temptable_1047[] PROGMEM = { // only a few values are needed as the curve is very flat PtLine( 0, 1000, 4700), PtLine( 50, 1000, 4700), PtLine(100, 1000, 4700), PtLine(150, 1000, 4700), PtLine(200, 1000, 4700), PtLine(250, 1000, 4700), PtLine(300, 1000, 4700), PtLine(350, 1000, 4700), PtLine(400, 1000, 4700), PtLine(450, 1000, 4700), PtLine(500, 1000, 4700) };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_1047.h
C++
agpl-3.0
1,355
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // R25 = 100 kOhm, beta25 = 3950 K, 4.7 kOhm pull-up, QU-BD silicone bed QWG-104F-3950 thermistor constexpr temp_entry_t temptable_11[] PROGMEM = { { OV( 1), 938 }, { OV( 31), 314 }, { OV( 41), 290 }, { OV( 51), 272 }, { OV( 61), 258 }, { OV( 71), 247 }, { OV( 81), 237 }, { OV( 91), 229 }, { OV( 101), 221 }, { OV( 111), 215 }, { OV( 121), 209 }, { OV( 131), 204 }, { OV( 141), 199 }, { OV( 151), 195 }, { OV( 161), 190 }, { OV( 171), 187 }, { OV( 181), 183 }, { OV( 191), 179 }, { OV( 201), 176 }, { OV( 221), 170 }, { OV( 241), 165 }, { OV( 261), 160 }, { OV( 281), 155 }, { OV( 301), 150 }, { OV( 331), 144 }, { OV( 361), 139 }, { OV( 391), 133 }, { OV( 421), 128 }, { OV( 451), 123 }, { OV( 491), 117 }, { OV( 531), 111 }, { OV( 571), 105 }, { OV( 611), 100 }, { OV( 641), 95 }, { OV( 681), 90 }, { OV( 711), 85 }, { OV( 751), 79 }, { OV( 791), 72 }, { OV( 811), 69 }, { OV( 831), 65 }, { OV( 871), 57 }, { OV( 881), 55 }, { OV( 901), 51 }, { OV( 921), 45 }, { OV( 941), 39 }, { OV( 971), 28 }, { OV( 981), 23 }, { OV( 991), 17 }, { OV(1001), 9 }, { OV(1021), -27 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_11.h
C++
agpl-3.0
2,076
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #define REVERSE_TEMP_SENSOR_RANGE_110 1 // Pt100 with 1k0 pullup constexpr temp_entry_t temptable_110[] PROGMEM = { // only a few values are needed as the curve is very flat PtLine( 0, 100, 1000), PtLine( 50, 100, 1000), PtLine(100, 100, 1000), PtLine(150, 100, 1000), PtLine(200, 100, 1000), PtLine(250, 100, 1000), PtLine(300, 100, 1000) };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_110.h
C++
agpl-3.0
1,237
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once // R25 = 100 kOhm, beta25 = 4700 K, 4.7 kOhm pull-up, (personal calibration for Makibox hot bed) constexpr temp_entry_t temptable_12[] PROGMEM = { { OV( 35), 180 }, // top rating 180C { OV( 211), 140 }, { OV( 233), 135 }, { OV( 261), 130 }, { OV( 290), 125 }, { OV( 328), 120 }, { OV( 362), 115 }, { OV( 406), 110 }, { OV( 446), 105 }, { OV( 496), 100 }, { OV( 539), 95 }, { OV( 585), 90 }, { OV( 629), 85 }, { OV( 675), 80 }, { OV( 718), 75 }, { OV( 758), 70 }, { OV( 793), 65 }, { OV( 822), 60 }, { OV( 841), 55 }, { OV( 875), 50 }, { OV( 899), 45 }, { OV( 926), 40 }, { OV( 946), 35 }, { OV( 962), 30 }, { OV( 977), 25 }, { OV( 987), 20 }, { OV( 995), 15 }, { OV(1001), 10 }, { OV(1010), 0 }, { OV(1023), -40 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_12.h
C++
agpl-3.0
1,674
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // R25 = 100 kOhm, beta25 = 4100 K, 4.7 kOhm pull-up, Hisens thermistor constexpr temp_entry_t temptable_13[] PROGMEM = { { OV( 20.04), 300 }, { OV( 23.19), 290 }, { OV( 26.71), 280 }, { OV( 31.23), 270 }, { OV( 36.52), 260 }, { OV( 42.75), 250 }, { OV( 50.68), 240 }, { OV( 60.22), 230 }, { OV( 72.03), 220 }, { OV( 86.84), 210 }, { OV(102.79), 200 }, { OV(124.46), 190 }, { OV(151.02), 180 }, { OV(182.86), 170 }, { OV(220.72), 160 }, { OV(316.96), 140 }, { OV(447.17), 120 }, { OV(590.61), 100 }, { OV(737.31), 80 }, { OV(857.77), 60 }, { OV(939.52), 40 }, { OV(986.03), 20 }, { OV(1008.7), 0 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_13.h
C++
agpl-3.0
1,529
/** * Marlin 3D Printer Firmware * Copyright (c) 2023 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once // R25 = 100 kOhm, beta25 = 4092 K, 4.7 kOhm pull-up, bed thermistor constexpr temp_entry_t temptable_14[] PROGMEM = { { OV( 23), 275 }, { OV( 25), 270 }, { OV( 27), 265 }, { OV( 28), 260 }, { OV( 31), 255 }, { OV( 33), 250 }, { OV( 35), 245 }, { OV( 38), 240 }, { OV( 41), 235 }, { OV( 44), 230 }, { OV( 47), 225 }, { OV( 52), 220 }, { OV( 56), 215 }, { OV( 62), 210 }, { OV( 68), 205 }, { OV( 74), 200 }, { OV( 81), 195 }, { OV( 90), 190 }, { OV( 99), 185 }, { OV( 108), 180 }, { OV( 121), 175 }, { OV( 133), 170 }, { OV( 147), 165 }, { OV( 162), 160 }, { OV( 180), 155 }, { OV( 199), 150 }, { OV( 219), 145 }, { OV( 243), 140 }, { OV( 268), 135 }, { OV( 296), 130 }, { OV( 326), 125 }, { OV( 358), 120 }, { OV( 398), 115 }, { OV( 435), 110 }, { OV( 476), 105 }, { OV( 519), 100 }, { OV( 566), 95 }, { OV( 610), 90 }, { OV( 658), 85 }, { OV( 703), 80 }, { OV( 742), 75 }, { OV( 773), 70 }, { OV( 807), 65 }, { OV( 841), 60 }, { OV( 871), 55 }, { OV( 895), 50 }, { OV( 918), 45 }, { OV( 937), 40 }, { OV( 954), 35 }, { OV( 968), 30 }, { OV( 978), 25 }, { OV( 985), 20 }, { OV( 993), 15 }, { OV( 999), 10 }, { OV(1004), 5 }, { OV(1008), 0 }, { OV(1012), -5 }, { OV(1016), -10 }, { OV(1020), -15 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_14.h
C++
agpl-3.0
2,236
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #define REVERSE_TEMP_SENSOR_RANGE_147 1 // Pt100 with 4k7 pullup constexpr temp_entry_t temptable_147[] PROGMEM = { // only a few values are needed as the curve is very flat PtLine( 0, 100, 4700), PtLine( 50, 100, 4700), PtLine(100, 100, 4700), PtLine(150, 100, 4700), PtLine(200, 100, 4700), PtLine(250, 100, 4700), PtLine(300, 100, 4700) };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_147.h
C++
agpl-3.0
1,237
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once // 100k bed thermistor in JGAurora A5. Calibrated by Sam Pinches 21st Jan 2018 using cheap k-type thermocouple inserted into heater block, using TM-902C meter. constexpr temp_entry_t temptable_15[] PROGMEM = { { OV( 31), 275 }, { OV( 33), 270 }, { OV( 35), 260 }, { OV( 38), 253 }, { OV( 41), 248 }, { OV( 48), 239 }, { OV( 56), 232 }, { OV( 66), 222 }, { OV( 78), 212 }, { OV( 93), 206 }, { OV( 106), 199 }, { OV( 118), 191 }, { OV( 130), 186 }, { OV( 158), 176 }, { OV( 187), 167 }, { OV( 224), 158 }, { OV( 270), 148 }, { OV( 321), 137 }, { OV( 379), 127 }, { OV( 446), 117 }, { OV( 518), 106 }, { OV( 593), 96 }, { OV( 668), 86 }, { OV( 739), 76 }, { OV( 767), 72 }, { OV( 830), 62 }, { OV( 902), 48 }, { OV( 926), 45 }, { OV( 955), 35 }, { OV( 966), 30 }, { OV( 977), 25 }, { OV( 985), 20 }, { OV( 993), 15 }, { OV( 999), 10 }, { OV(1004), 5 }, { OV(1008), 0 }, { OV(1012), -5 }, { OV(1016), -10 }, { OV(1020), -15 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_15.h
C++
agpl-3.0
1,908
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // Dagoma NTC 100k white thermistor constexpr temp_entry_t temptable_17[] PROGMEM = { { OV( 16), 309 }, { OV( 18), 307 }, { OV( 20), 300 }, { OV( 22), 293 }, { OV( 26), 284 }, { OV( 29), 272 }, { OV( 33), 266 }, { OV( 36), 260 }, { OV( 42), 252 }, { OV( 46), 247 }, { OV( 48), 244 }, { OV( 51), 241 }, { OV( 62), 231 }, { OV( 73), 222 }, { OV( 78), 219 }, { OV( 87), 212 }, { OV( 98), 207 }, { OV( 109), 201 }, { OV( 118), 197 }, { OV( 131), 191 }, { OV( 145), 186 }, { OV( 160), 181 }, { OV( 177), 175 }, { OV( 203), 169 }, { OV( 222), 164 }, { OV( 256), 156 }, { OV( 283), 151 }, { OV( 312), 145 }, { OV( 343), 140 }, { OV( 377), 131 }, { OV( 413), 125 }, { OV( 454), 119 }, { OV( 496), 113 }, { OV( 537), 108 }, { OV( 578), 102 }, { OV( 619), 97 }, { OV( 658), 92 }, { OV( 695), 87 }, { OV( 735), 81 }, { OV( 773), 75 }, { OV( 808), 70 }, { OV( 844), 64 }, { OV( 868), 59 }, { OV( 892), 54 }, { OV( 914), 49 }, { OV( 935), 42 }, { OV( 951), 38 }, { OV( 967), 32 }, { OV( 975), 28 }, { OV(1000), 20 }, { OV(1010), 10 }, { OV(1024), -273 } // for safety };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_17.h
C++
agpl-3.0
2,122
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // ATC Semitec 204GT-2 (4.7k pullup) Dagoma.Fr - MKS_Base_DKU001327 - version (measured/tested/approved) constexpr temp_entry_t temptable_18[] PROGMEM = { { OV( 1), 713 }, { OV( 17), 284 }, { OV( 20), 275 }, { OV( 23), 267 }, { OV( 27), 257 }, { OV( 31), 250 }, { OV( 37), 240 }, { OV( 43), 232 }, { OV( 51), 222 }, { OV( 61), 213 }, { OV( 73), 204 }, { OV( 87), 195 }, { OV( 106), 185 }, { OV( 128), 175 }, { OV( 155), 166 }, { OV( 189), 156 }, { OV( 230), 146 }, { OV( 278), 137 }, { OV( 336), 127 }, { OV( 402), 117 }, { OV( 476), 107 }, { OV( 554), 97 }, { OV( 635), 87 }, { OV( 713), 78 }, { OV( 784), 68 }, { OV( 846), 58 }, { OV( 897), 49 }, { OV( 937), 39 }, { OV( 966), 30 }, { OV( 986), 20 }, { OV(1000), 10 }, { OV(1010), 0 }, { OV(1024),-273 } // for safety };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_18.h
C++
agpl-3.0
1,740
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // // R25 = 200 kOhm, beta25 = 4338 K, 4.7 kOhm pull-up, ATC Semitec 204GT-2 // Verified by linagee. Source: https://www.mouser.com/datasheet/2/362/semitec%20usa%20corporation_gtthermistor-1202937.pdf // Calculated using 4.7kohm pullup, voltage divider math, and manufacturer provided temp/resistance // constexpr temp_entry_t temptable_2[] PROGMEM = { { OV( 1), 848 }, { OV( 30), 300 }, // top rating 300C { OV( 34), 290 }, { OV( 39), 280 }, { OV( 46), 270 }, { OV( 53), 260 }, { OV( 63), 250 }, { OV( 74), 240 }, { OV( 87), 230 }, { OV( 104), 220 }, { OV( 124), 210 }, { OV( 148), 200 }, { OV( 176), 190 }, { OV( 211), 180 }, { OV( 252), 170 }, { OV( 301), 160 }, { OV( 357), 150 }, { OV( 420), 140 }, { OV( 489), 130 }, { OV( 562), 120 }, { OV( 636), 110 }, { OV( 708), 100 }, { OV( 775), 90 }, { OV( 835), 80 }, { OV( 884), 70 }, { OV( 924), 60 }, { OV( 955), 50 }, { OV( 977), 40 }, { OV( 993), 30 }, { OV(1004), 20 }, { OV(1012), 10 }, { OV(1016), 0 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_2.h
C++
agpl-3.0
1,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/>. * */ #pragma once #define REVERSE_TEMP_SENSOR_RANGE_20 1 // Pt100 with INA826 amp on Ultimaker v2.0 electronics constexpr temp_entry_t temptable_20[] PROGMEM = { { OV( 0), 0 }, { OV(227), 1 }, { OV(236), 10 }, { OV(245), 20 }, { OV(253), 30 }, { OV(262), 40 }, { OV(270), 50 }, { OV(279), 60 }, { OV(287), 70 }, { OV(295), 80 }, { OV(304), 90 }, { OV(312), 100 }, { OV(320), 110 }, { OV(329), 120 }, { OV(337), 130 }, { OV(345), 140 }, { OV(353), 150 }, { OV(361), 160 }, { OV(369), 170 }, { OV(377), 180 }, { OV(385), 190 }, { OV(393), 200 }, { OV(401), 210 }, { OV(409), 220 }, { OV(417), 230 }, { OV(424), 240 }, { OV(432), 250 }, { OV(440), 260 }, { OV(447), 270 }, { OV(455), 280 }, { OV(463), 290 }, { OV(470), 300 }, { OV(478), 310 }, { OV(485), 320 }, { OV(493), 330 }, { OV(500), 340 }, { OV(507), 350 }, { OV(515), 360 }, { OV(522), 370 }, { OV(529), 380 }, { OV(537), 390 }, { OV(544), 400 }, { OV(614), 500 }, { OV(681), 600 }, { OV(744), 700 }, { OV(805), 800 }, { OV(862), 900 }, { OV(917), 1000 }, { OV(968), 1100 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_20.h
C++
agpl-3.0
2,052
/** * 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 // R25 = 100 KOhm, beta25 = 4550 K, 4.7 kOhm pull-up, TDK NTCG104LH104KT1 https://product.tdk.com/en/search/sensor/ntc/chip-ntc-thermistor/info?part_no=NTCG104LH104KT1 constexpr temp_entry_t temptable_2000[] PROGMEM = { { OV(313), 125 }, { OV(347), 120 }, { OV(383), 115 }, { OV(422), 110 }, { OV(463), 105 }, { OV(506), 100 }, { OV(549), 95 }, { OV(594), 90 }, { OV(638), 85 }, { OV(681), 80 }, { OV(722), 75 }, { OV(762), 70 }, { OV(799), 65 }, { OV(833), 60 }, { OV(863), 55 }, { OV(890), 50 }, { OV(914), 45 }, { OV(934), 40 }, { OV(951), 35 }, { OV(966), 30 }, { OV(978), 25 }, { OV(988), 20 }, { OV(996), 15 }, { OV(1002), 10 }, { OV(1007), 5 }, { OV(1012), 0 }, { OV(1015), -5 }, { OV(1017), -10 }, { OV(1019), -15 }, { OV(1020), -20 }, { OV(1021), -25 }, { OV(1022), -30 }, { OV(1023), -35 }, { OV(1023), -40 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_2000.h
C++
agpl-3.0
1,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/>. * */ #pragma once #define REVERSE_TEMP_SENSOR_RANGE_201 1 // Pt100 with LMV324 amp on Overlord v1.1 electronics constexpr temp_entry_t temptable_201[] PROGMEM = { { OV( 0), 0 }, { OV( 8), 1 }, { OV( 23), 6 }, { OV( 41), 15 }, { OV( 51), 20 }, { OV( 68), 28 }, { OV( 74), 30 }, { OV( 88), 35 }, { OV( 99), 40 }, { OV( 123), 50 }, { OV( 148), 60 }, { OV( 173), 70 }, { OV( 198), 80 }, { OV( 221), 90 }, { OV( 245), 100 }, { OV( 269), 110 }, { OV( 294), 120 }, { OV( 316), 130 }, { OV( 342), 140 }, { OV( 364), 150 }, { OV( 387), 160 }, { OV( 412), 170 }, { OV( 433), 180 }, { OV( 456), 190 }, { OV( 480), 200 }, { OV( 500), 210 }, { OV( 548), 224 }, { OV( 572), 233 }, { OV(1155), 490 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_201.h
C++
agpl-3.0
1,633
// // Unknown 200K thermistor on a Copymaster 3D hotend // Temptable sent from dealer technologyoutlet.co.uk // constexpr temp_entry_t temptable_202[] PROGMEM = { { OV( 1), 864 }, { OV( 35), 300 }, { OV( 38), 295 }, { OV( 41), 290 }, { OV( 44), 285 }, { OV( 47), 280 }, { OV( 51), 275 }, { OV( 55), 270 }, { OV( 60), 265 }, { OV( 65), 260 }, { OV( 70), 255 }, { OV( 76), 250 }, { OV( 83), 245 }, { OV( 90), 240 }, { OV( 98), 235 }, { OV( 107), 230 }, { OV( 116), 225 }, { OV( 127), 220 }, { OV( 138), 215 }, { OV( 151), 210 }, { OV( 164), 205 }, { OV( 179), 200 }, { OV( 195), 195 }, { OV( 213), 190 }, { OV( 232), 185 }, { OV( 253), 180 }, { OV( 275), 175 }, { OV( 299), 170 }, { OV( 325), 165 }, { OV( 352), 160 }, { OV( 381), 155 }, { OV( 411), 150 }, { OV( 443), 145 }, { OV( 476), 140 }, { OV( 511), 135 }, { OV( 546), 130 }, { OV( 581), 125 }, { OV( 617), 120 }, { OV( 652), 115 }, { OV( 687), 110 }, { OV( 720), 105 }, { OV( 753), 100 }, { OV( 783), 95 }, { OV( 812), 90 }, { OV( 839), 85 }, { OV( 864), 80 }, { OV( 886), 75 }, { OV( 906), 70 }, { OV( 924), 65 }, { OV( 940), 60 }, { OV( 954), 55 }, { OV( 966), 50 }, { OV( 976), 45 }, { OV( 985), 40 }, { OV( 992), 35 }, { OV( 998), 30 }, { OV(1003), 25 }, { OV(1007), 20 }, { OV(1011), 15 }, { OV(1014), 10 }, { OV(1016), 5 }, { OV(1018), 0 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_202.h
C++
agpl-3.0
1,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 #define REVERSE_TEMP_SENSOR_RANGE_21 1 #undef OV_SCALE #define OV_SCALE(N) (float((N) * 5) / 3.3f) // Pt100 with INA826 amplifier board with 5v supply based on Thermistor 20, with 3v3 ADC reference on the mainboard. // If the ADC reference and INA826 board supply voltage are identical, Thermistor 20 instead. constexpr temp_entry_t temptable_21[] PROGMEM = { { OV( 0), 0 }, { OV(227), 1 }, { OV(236), 10 }, { OV(245), 20 }, { OV(253), 30 }, { OV(262), 40 }, { OV(270), 50 }, { OV(279), 60 }, { OV(287), 70 }, { OV(295), 80 }, { OV(304), 90 }, { OV(312), 100 }, { OV(320), 110 }, { OV(329), 120 }, { OV(337), 130 }, { OV(345), 140 }, { OV(353), 150 }, { OV(361), 160 }, { OV(369), 170 }, { OV(377), 180 }, { OV(385), 190 }, { OV(393), 200 }, { OV(401), 210 }, { OV(409), 220 }, { OV(417), 230 }, { OV(424), 240 }, { OV(432), 250 }, { OV(440), 260 }, { OV(447), 270 }, { OV(455), 280 }, { OV(463), 290 }, { OV(470), 300 }, { OV(478), 310 }, { OV(485), 320 }, { OV(493), 330 }, { OV(500), 340 }, { OV(507), 350 }, { OV(515), 360 }, { OV(522), 370 }, { OV(529), 380 }, { OV(537), 390 }, { OV(544), 400 }, { OV(614), 500 } }; #undef OV_SCALE #define OV_SCALE(N) (N)
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_21.h
C++
agpl-3.0
2,184
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ // 100k hotend thermistor with 4.7k pull up to 3.3v and 220R to analog input as in GTM32 Pro vB constexpr temp_entry_t temptable_22[] PROGMEM = { { OV( 1), 352 }, { OV( 6), 341 }, { OV( 11), 330 }, { OV( 16), 319 }, { OV( 20), 307 }, { OV( 26), 296 }, { OV( 31), 285 }, { OV( 40), 274 }, { OV( 51), 263 }, { OV( 61), 251 }, { OV( 72), 245 }, { OV( 77), 240 }, { OV( 82), 237 }, { OV( 87), 232 }, { OV( 91), 229 }, { OV( 94), 227 }, { OV( 97), 225 }, { OV( 100), 223 }, { OV( 104), 221 }, { OV( 108), 219 }, { OV( 115), 214 }, { OV( 126), 209 }, { OV( 137), 204 }, { OV( 147), 200 }, { OV( 158), 193 }, { OV( 167), 192 }, { OV( 177), 189 }, { OV( 197), 163 }, { OV( 230), 174 }, { OV( 267), 165 }, { OV( 310), 158 }, { OV( 336), 151 }, { OV( 379), 143 }, { OV( 413), 138 }, { OV( 480), 127 }, { OV( 580), 110 }, { OV( 646), 100 }, { OV( 731), 88 }, { OV( 768), 84 }, { OV( 861), 69 }, { OV( 935), 50 }, { OV( 975), 38 }, { OV(1001), 27 }, { OV(1011), 22 }, { OV(1015), 13 }, { OV(1020), 6 }, { OV(1023), 0 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_22.h
C++
agpl-3.0
1,998
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ // 100k hotbed thermistor with 4.7k pull up to 3.3v and 220R to analog input as in GTM32 Pro vB constexpr temp_entry_t temptable_23[] PROGMEM = { { OV( 1), 938 }, { OV( 11), 423 }, { OV( 21), 351 }, { OV( 31), 314 }, { OV( 41), 290 }, { OV( 51), 272 }, { OV( 61), 258 }, { OV( 71), 247 }, { OV( 81), 237 }, { OV( 91), 229 }, { OV( 101), 221 }, { OV( 111), 215 }, { OV( 121), 209 }, { OV( 131), 204 }, { OV( 141), 199 }, { OV( 151), 195 }, { OV( 161), 190 }, { OV( 171), 187 }, { OV( 181), 183 }, { OV( 191), 179 }, { OV( 201), 176 }, { OV( 211), 173 }, { OV( 221), 170 }, { OV( 231), 167 }, { OV( 241), 165 }, { OV( 251), 162 }, { OV( 261), 160 }, { OV( 271), 157 }, { OV( 281), 155 }, { OV( 291), 153 }, { OV( 301), 150 }, { OV( 311), 148 }, { OV( 321), 146 }, { OV( 331), 144 }, { OV( 341), 142 }, { OV( 351), 140 }, { OV( 361), 139 }, { OV( 371), 137 }, { OV( 381), 135 }, { OV( 391), 133 }, { OV( 401), 131 }, { OV( 411), 130 }, { OV( 421), 128 }, { OV( 431), 126 }, { OV( 441), 125 }, { OV( 451), 123 }, { OV( 461), 122 }, { OV( 471), 120 }, { OV( 481), 119 }, { OV( 491), 117 }, { OV( 501), 116 }, { OV( 511), 114 }, { OV( 521), 113 }, { OV( 531), 111 }, { OV( 541), 110 }, { OV( 551), 108 }, { OV( 561), 107 }, { OV( 571), 105 }, { OV( 581), 104 }, { OV( 591), 102 }, { OV( 601), 101 }, { OV( 611), 100 }, { OV( 621), 98 }, { OV( 631), 97 }, { OV( 641), 95 }, { OV( 651), 94 }, { OV( 661), 92 }, { OV( 671), 91 }, { OV( 681), 90 }, { OV( 691), 88 }, { OV( 701), 87 }, { OV( 711), 85 }, { OV( 721), 84 }, { OV( 731), 82 }, { OV( 741), 81 }, { OV( 751), 79 }, { OV( 761), 77 }, { OV( 771), 76 }, { OV( 781), 74 }, { OV( 791), 72 }, { OV( 801), 71 }, { OV( 811), 69 }, { OV( 821), 67 }, { OV( 831), 65 }, { OV( 841), 63 }, { OV( 851), 62 }, { OV( 861), 60 }, { OV( 871), 57 }, { OV( 881), 55 }, { OV( 891), 53 }, { OV( 901), 51 }, { OV( 911), 48 }, { OV( 921), 45 }, { OV( 931), 42 }, { OV( 941), 39 }, { OV( 951), 36 }, { OV( 961), 32 }, { OV( 971), 28 }, { OV( 981), 25 }, { OV( 991), 23 }, { OV(1001), 21 }, { OV(1011), 19 }, { OV(1021), 5 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_23.h
C++
agpl-3.0
3,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/>. * */ #pragma once // R25 = 100 kOhm, beta25 = 4120 K, 4.7 kOhm pull-up, mendel-parts constexpr temp_entry_t temptable_3[] PROGMEM = { { OV( 1), 864 }, { OV( 21), 300 }, { OV( 25), 290 }, { OV( 29), 280 }, { OV( 33), 270 }, { OV( 39), 260 }, { OV( 46), 250 }, { OV( 54), 240 }, { OV( 64), 230 }, { OV( 75), 220 }, { OV( 90), 210 }, { OV( 107), 200 }, { OV( 128), 190 }, { OV( 154), 180 }, { OV( 184), 170 }, { OV( 221), 160 }, { OV( 265), 150 }, { OV( 316), 140 }, { OV( 375), 130 }, { OV( 441), 120 }, { OV( 513), 110 }, { OV( 588), 100 }, { OV( 734), 80 }, { OV( 856), 60 }, { OV( 938), 40 }, { OV( 986), 20 }, { OV(1008), 0 }, { OV(1018), -20 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_3.h
C++
agpl-3.0
1,582
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // R25 = 100 kOhm, beta25 = 3950 K, 4.7 kOhm pull-up // Resistance 100k Ohms at 25deg. C // Resistance Tolerance + / -1% // B Value 3950K at 25/50 deg. C // B Value Tolerance + / - 1% // Kis3d Silicone Heater 24V 200W/300W with 6mm Precision cast plate (EN AW 5083) // Temperature setting time 10 min to determine the 12Bit ADC value on the surface. (le3tspeak) constexpr temp_entry_t temptable_30[] PROGMEM = { { OV( 1), 938 }, { OV( 298), 125 }, // 1193 - 125° { OV( 321), 121 }, // 1285 - 121° { OV( 348), 117 }, // 1392 - 117° { OV( 387), 113 }, // 1550 - 113° { OV( 411), 110 }, // 1644 - 110° { OV( 445), 106 }, // 1780 - 106° { OV( 480), 101 }, // 1920 - 101° { OV( 516), 97 }, // 2064 - 97° { OV( 553), 92 }, // 2212 - 92° { OV( 591), 88 }, // 2364 - 88° { OV( 628), 84 }, // 2512 - 84° { OV( 665), 79 }, // 2660 - 79° { OV( 702), 75 }, // 2808 - 75° { OV( 736), 71 }, // 2945 - 71° { OV( 770), 67 }, // 3080 - 67° { OV( 801), 63 }, // 3204 - 63° { OV( 830), 59 }, // 3320 - 59° { OV( 857), 55 }, // 3428 - 55° { OV( 881), 51 }, // 3524 - 51° { OV( 902), 47 }, // 3611 - 47° { OV( 922), 42 }, // 3688 - 42° { OV( 938), 38 }, // 3754 - 38° { OV( 952), 34 }, // 3811 - 34° { OV( 964), 29 }, // 3857 - 29° { OV( 975), 25 }, // 3900 - 25° { OV( 980), 23 }, // 3920 - 23° { OV( 991), 17 }, // 3964 - 17° { OV(1001), 9 }, // Calculated { OV(1004), 5 }, // Calculated { OV(1008), 0 }, // Calculated { OV(1012), -5 }, // Calculated { OV(1016), -10 }, // Calculated { OV(1020), -15 } // Calculated };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_30.h
C++
agpl-3.0
2,533
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #define OVM(V) OV((V)*(0.327/0.5)) // R25 = 100 kOhm, beta25 = 4092 K, 4.7 kOhm pull-up, bed thermistor constexpr temp_entry_t temptable_331[] PROGMEM = { { OVM( 23), 300 }, { OVM( 25), 295 }, { OVM( 27), 290 }, { OVM( 28), 285 }, { OVM( 31), 280 }, { OVM( 33), 275 }, { OVM( 35), 270 }, { OVM( 38), 265 }, { OVM( 41), 260 }, { OVM( 44), 255 }, { OVM( 48), 250 }, { OVM( 52), 245 }, { OVM( 56), 240 }, { OVM( 61), 235 }, { OVM( 66), 230 }, { OVM( 71), 225 }, { OVM( 78), 220 }, { OVM( 84), 215 }, { OVM( 92), 210 }, { OVM( 100), 205 }, { OVM( 109), 200 }, { OVM( 120), 195 }, { OVM( 131), 190 }, { OVM( 143), 185 }, { OVM( 156), 180 }, { OVM( 171), 175 }, { OVM( 187), 170 }, { OVM( 205), 165 }, { OVM( 224), 160 }, { OVM( 245), 155 }, { OVM( 268), 150 }, { OVM( 293), 145 }, { OVM( 320), 140 }, { OVM( 348), 135 }, { OVM( 379), 130 }, { OVM( 411), 125 }, { OVM( 445), 120 }, { OVM( 480), 115 }, { OVM( 516), 110 }, { OVM( 553), 105 }, { OVM( 591), 100 }, { OVM( 628), 95 }, { OVM( 665), 90 }, { OVM( 702), 85 }, { OVM( 737), 80 }, { OVM( 770), 75 }, { OVM( 801), 70 }, { OVM( 830), 65 }, { OVM( 857), 60 }, { OVM( 881), 55 }, { OVM( 903), 50 }, { OVM( 922), 45 }, { OVM( 939), 40 }, { OVM( 954), 35 }, { OVM( 966), 30 }, { OVM( 977), 25 }, { OVM( 985), 20 }, { OVM( 993), 15 }, { OVM( 999), 10 }, { OVM(1004), 5 }, { OVM(1008), 0 }, { OVM(1012), -5 }, { OVM(1016), -10 }, { OVM(1020), -15 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_331.h
C++
agpl-3.0
2,442
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once #define OVM(V) OV((V)*(0.327/0.327)) // R25 = 100 kOhm, beta25 = 4092 K, 4.7 kOhm pull-up, bed thermistor constexpr temp_entry_t temptable_332[] PROGMEM = { { OVM( 268), 150 }, { OVM( 293), 145 }, { OVM( 320), 141 }, { OVM( 379), 133 }, { OVM( 445), 122 }, { OVM( 516), 108 }, { OVM( 591), 98 }, { OVM( 665), 88 }, { OVM( 737), 79 }, { OVM( 801), 70 }, { OVM( 857), 55 }, { OVM( 903), 46 }, { OVM( 939), 39 }, { OVM( 954), 33 }, { OVM( 966), 27 }, { OVM( 977), 22 }, { OVM( 999), 15 }, { OVM(1004), 5 }, { OVM(1008), 0 }, { OVM(1012), -5 }, { OVM(1016), -10 }, { OVM(1020), -15 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_332.h
C++
agpl-3.0
1,520
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // R25 = 10 kOhm, beta25 = 3950 K, 4.7 kOhm pull-up, Generic 10k thermistor constexpr temp_entry_t temptable_4[] PROGMEM = { { OV( 1), 430 }, { OV( 54), 137 }, { OV( 107), 107 }, { OV( 160), 91 }, { OV( 213), 80 }, { OV( 266), 71 }, { OV( 319), 64 }, { OV( 372), 57 }, { OV( 425), 51 }, { OV( 478), 46 }, { OV( 531), 41 }, { OV( 584), 35 }, { OV( 637), 30 }, { OV( 690), 25 }, { OV( 743), 20 }, { OV( 796), 14 }, { OV( 849), 7 }, { OV( 902), 0 }, { OV( 955), -11 }, { OV(1008), -35 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_4.h
C++
agpl-3.0
1,423
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // R25 = 100 kOhm, beta25 = 4267 K, 4.7 kOhm pull-up // 100k ParCan thermistor (104GT-2) // ATC Semitec 104GT-2/104NT-4-R025H42G (Used in ParCan) // Verified by linagee. Source: https://www.mouser.com/datasheet/2/362/semitec%20usa%20corporation_gtthermistor-1202937.pdf // Calculated using 4.7kohm pullup, voltage divider math, and manufacturer provided temp/resistance constexpr temp_entry_t temptable_5[] PROGMEM = { { OV( 1), 713 }, { OV( 17), 300 }, // top rating 300C { OV( 20), 290 }, { OV( 23), 280 }, { OV( 27), 270 }, { OV( 31), 260 }, { OV( 37), 250 }, { OV( 43), 240 }, { OV( 51), 230 }, { OV( 61), 220 }, { OV( 73), 210 }, { OV( 87), 200 }, { OV( 106), 190 }, { OV( 128), 180 }, { OV( 155), 170 }, { OV( 189), 160 }, { OV( 230), 150 }, { OV( 278), 140 }, { OV( 336), 130 }, { OV( 402), 120 }, { OV( 476), 110 }, { OV( 554), 100 }, { OV( 635), 90 }, { OV( 713), 80 }, { OV( 784), 70 }, { OV( 846), 60 }, { OV( 897), 50 }, { OV( 937), 40 }, { OV( 966), 30 }, { OV( 986), 20 }, { OV(1000), 10 }, { OV(1010), 0 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_5.h
C++
agpl-3.0
1,988
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // 100k Zonestar thermistor. Adjusted By Hally constexpr temp_entry_t temptable_501[] PROGMEM = { { OV( 1), 713 }, { OV( 14), 300 }, // Top rating 300C { OV( 16), 290 }, { OV( 19), 280 }, { OV( 23), 270 }, { OV( 27), 260 }, { OV( 31), 250 }, { OV( 37), 240 }, { OV( 47), 230 }, { OV( 57), 220 }, { OV( 68), 210 }, { OV( 84), 200 }, { OV( 100), 190 }, { OV( 128), 180 }, { OV( 155), 170 }, { OV( 189), 160 }, { OV( 230), 150 }, { OV( 278), 140 }, { OV( 336), 130 }, { OV( 402), 120 }, { OV( 476), 110 }, { OV( 554), 100 }, { OV( 635), 90 }, { OV( 713), 80 }, { OV( 784), 70 }, { OV( 846), 60 }, { OV( 897), 50 }, { OV( 937), 40 }, { OV( 966), 30 }, { OV( 986), 20 }, { OV(1000), 10 }, { OV(1010), 0 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_501.h
C++
agpl-3.0
1,699
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // Unknown thermistor for the Zonestar P802M hot bed. Adjusted By Nerseth // These were the shipped settings from Zonestar in original firmware: P802M_8_Repetier_V1.6_Zonestar.zip constexpr temp_entry_t temptable_502[] PROGMEM = { { OV( 56.0 / 4), 300 }, { OV( 187.0 / 4), 250 }, { OV( 615.0 / 4), 190 }, { OV( 690.0 / 4), 185 }, { OV( 750.0 / 4), 180 }, { OV( 830.0 / 4), 175 }, { OV( 920.0 / 4), 170 }, { OV(1010.0 / 4), 165 }, { OV(1118.0 / 4), 160 }, { OV(1215.0 / 4), 155 }, { OV(1330.0 / 4), 145 }, { OV(1460.0 / 4), 140 }, { OV(1594.0 / 4), 135 }, { OV(1752.0 / 4), 130 }, { OV(1900.0 / 4), 125 }, { OV(2040.0 / 4), 120 }, { OV(2200.0 / 4), 115 }, { OV(2350.0 / 4), 110 }, { OV(2516.0 / 4), 105 }, { OV(2671.0 / 4), 98 }, { OV(2831.0 / 4), 92 }, { OV(2975.0 / 4), 85 }, { OV(3115.0 / 4), 76 }, { OV(3251.0 / 4), 72 }, { OV(3480.0 / 4), 62 }, { OV(3580.0 / 4), 52 }, { OV(3660.0 / 4), 46 }, { OV(3740.0 / 4), 40 }, { OV(3869.0 / 4), 30 }, { OV(3912.0 / 4), 25 }, { OV(3948.0 / 4), 20 }, { OV(4077.0 / 4), -20 }, { OV(4094.0 / 4), -55 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_502.h
C++
agpl-3.0
2,033
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // Zonestar (Z8XM2) Heated Bed thermistor. Added By AvanOsch // These are taken from the Zonestar settings in original Repetier firmware: Z8XM2_ZRIB_LCD12864_V51.zip constexpr temp_entry_t temptable_503[] PROGMEM = { { OV( 12), 300 }, { OV( 27), 270 }, { OV( 47), 250 }, { OV( 68), 230 }, { OV( 99), 210 }, { OV( 120), 200 }, { OV( 141), 190 }, { OV( 171), 180 }, { OV( 201), 170 }, { OV( 261), 160 }, { OV( 321), 150 }, { OV( 401), 140 }, { OV( 451), 130 }, { OV( 551), 120 }, { OV( 596), 110 }, { OV( 626), 105 }, { OV( 666), 100 }, { OV( 697), 90 }, { OV( 717), 85 }, { OV( 798), 69 }, { OV( 819), 65 }, { OV( 870), 55 }, { OV( 891), 51 }, { OV( 922), 39 }, { OV( 968), 28 }, { OV( 980), 23 }, { OV( 991), 17 }, { OV( 1001), 9 }, { OV(1021), -27 }, { OV(1023), -200} };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_503.h
C++
agpl-3.0
1,744
/** * Marlin 3D Printer Firmware * Copyright (c) 2022 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once // QWG 104F B3950 thermistor constexpr temp_entry_t temptable_504[] PROGMEM = { { OV( 15), 330 }, { OV( 17), 315 }, { OV( 19), 300 }, { OV( 20), 295 }, { OV( 21), 290 }, { OV( 23), 285 }, { OV( 25), 280 }, { OV( 27), 275 }, { OV( 28), 270 }, { OV( 31), 265 }, { OV( 33), 260 }, { OV( 35), 255 }, { OV( 38), 250 }, { OV( 41), 245 }, { OV( 44), 240 }, { OV( 48), 235 }, { OV( 52), 230 }, { OV( 56), 225 }, { OV( 61), 220 }, { OV( 66), 215 }, { OV( 78), 210 }, { OV( 92), 205 }, { OV( 100), 200 }, { OV( 109), 195 }, { OV( 120), 190 }, { OV( 143), 185 }, { OV( 148), 180 }, { OV( 156), 175 }, { OV( 171), 170 }, { OV( 187), 165 }, { OV( 205), 160 }, { OV( 224), 155 }, { OV( 268), 150 }, { OV( 293), 145 }, { OV( 320), 140 }, { OV( 348), 135 }, { OV( 379), 130 }, { OV( 411), 125 }, { OV( 445), 120 }, { OV( 480), 115 }, { OV( 516), 110 }, { OV( 553), 105 }, { OV( 591), 100 }, { OV( 628), 95 }, { OV( 665), 90 }, { OV( 702), 85 }, { OV( 737), 80 }, { OV( 770), 75 }, { OV( 801), 70 }, { OV( 830), 65 }, { OV( 857), 60 }, { OV( 881), 55 }, { OV( 903), 50 }, { OV( 922), 45 }, { OV( 939), 40 }, { OV( 954), 35 }, { OV( 966), 30 }, { OV( 977), 25 }, { OV( 985), 23 }, { OV( 993), 20 }, { OV( 999), 18 }, { OV(1004), 15 }, { OV(1008), 12 }, { OV(1012), 8 }, { OV(1016), 5 }, { OV(1020), 0 }, { OV(1023), -5 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_504.h
C++
agpl-3.0
2,365
/** * Marlin 3D Printer Firmware * Copyright (c) 2022 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #pragma once // ZONESTAR hotbed QWG-104F-3950 thermistor constexpr temp_entry_t temptable_505[] PROGMEM = { { OV( 1), 938 }, { OV( 8), 320 }, { OV( 16), 300 }, { OV( 27), 290 }, { OV( 36), 272 }, { OV( 47), 258 }, { OV( 56), 248 }, { OV( 68), 245 }, { OV( 78), 237 }, { OV( 89), 228 }, { OV( 99), 221 }, { OV( 110), 215 }, { OV( 120), 209 }, { OV( 131), 204 }, { OV( 141), 199 }, { OV( 151), 195 }, { OV( 161), 190 }, { OV( 171), 187 }, { OV( 181), 183 }, { OV( 201), 179 }, { OV( 221), 170 }, { OV( 251), 165 }, { OV( 261), 160 }, { OV( 321), 150 }, { OV( 361), 144 }, { OV( 401), 140 }, { OV( 421), 133 }, { OV( 451), 130 }, { OV( 551), 120 }, { OV( 571), 117 }, { OV( 596), 110 }, { OV( 626), 105 }, { OV( 666), 100 }, { OV( 677), 95 }, { OV( 697), 90 }, { OV( 717), 85 }, { OV( 727), 79 }, { OV( 750), 72 }, { OV( 789), 69 }, { OV( 819), 65 }, { OV( 861), 57 }, { OV( 870), 55 }, { OV( 881), 51 }, { OV( 911), 45 }, { OV( 922), 39 }, { OV( 968), 28 }, { OV( 977), 25 }, { OV( 985), 23 }, { OV( 993), 20 }, { OV( 999), 18 }, { OV(1004), 15 }, { OV(1008), 12 }, { OV(1012), 8 }, { OV(1016), 5 }, { OV(1020), 0 }, { OV(1023), -5 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_505.h
C++
agpl-3.0
2,149
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 // R25 = 100 kOhm, beta25 = 4092 K, 1 kOhm pull-up, // 100k EPCOS (WITH 1kohm RESISTOR FOR PULLUP, R9 ON SANGUINOLOLU! NOT FOR 4.7kohm PULLUP! THIS IS NOT NORMAL!) // Verified by linagee. // Calculated using 1kohm pullup, voltage divider math, and manufacturer provided temp/resistance // Advantage: Twice the resolution and better linearity from 150C to 200C constexpr temp_entry_t temptable_51[] PROGMEM = { { OV( 1), 350 }, { OV( 190), 250 }, // top rating 250C { OV( 203), 245 }, { OV( 217), 240 }, { OV( 232), 235 }, { OV( 248), 230 }, { OV( 265), 225 }, { OV( 283), 220 }, { OV( 302), 215 }, { OV( 322), 210 }, { OV( 344), 205 }, { OV( 366), 200 }, { OV( 390), 195 }, { OV( 415), 190 }, { OV( 440), 185 }, { OV( 467), 180 }, { OV( 494), 175 }, { OV( 522), 170 }, { OV( 551), 165 }, { OV( 580), 160 }, { OV( 609), 155 }, { OV( 638), 150 }, { OV( 666), 145 }, { OV( 695), 140 }, { OV( 722), 135 }, { OV( 749), 130 }, { OV( 775), 125 }, { OV( 800), 120 }, { OV( 823), 115 }, { OV( 845), 110 }, { OV( 865), 105 }, { OV( 884), 100 }, { OV( 901), 95 }, { OV( 917), 90 }, { OV( 932), 85 }, { OV( 944), 80 }, { OV( 956), 75 }, { OV( 966), 70 }, { OV( 975), 65 }, { OV( 982), 60 }, { OV( 989), 55 }, { OV( 995), 50 }, { OV(1000), 45 }, { OV(1004), 40 }, { OV(1007), 35 }, { OV(1010), 30 }, { OV(1013), 25 }, { OV(1015), 20 }, { OV(1017), 15 }, { OV(1018), 10 }, { OV(1019), 5 }, { OV(1020), 0 }, { OV(1021), -5 } };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_51.h
C++
agpl-3.0
2,420
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ // 100k thermistor supplied with RPW-Ultra hotend, 4.7k pullup constexpr temp_entry_t temptable_512[] PROGMEM = { { OV(26), 300 }, { OV(28), 295 }, { OV(30), 290 }, { OV(32), 285 }, { OV(34), 280 }, { OV(37), 275 }, { OV(39), 270 }, { OV(42), 265 }, { OV(46), 260 }, { OV(49), 255 }, { OV(53), 250 }, // 256.5 { OV(57), 245 }, { OV(62), 240 }, { OV(67), 235 }, { OV(73), 230 }, { OV(79), 225 }, { OV(86), 220 }, { OV(94), 215 }, { OV(103), 210 }, { OV(112), 205 }, { OV(123), 200 }, { OV(135), 195 }, { OV(148), 190 }, { OV(162), 185 }, { OV(178), 180 }, { OV(195), 175 }, { OV(215), 170 }, { OV(235), 165 }, { OV(258), 160 }, { OV(283), 155 }, { OV(310), 150 }, // 2040.6 { OV(338), 145 }, { OV(369), 140 }, { OV(401), 135 }, { OV(435), 130 }, { OV(470), 125 }, { OV(505), 120 }, { OV(542), 115 }, { OV(579), 110 }, { OV(615), 105 }, { OV(651), 100 }, { OV(686), 95 }, { OV(720), 90 }, { OV(751), 85 }, { OV(781), 80 }, { OV(809), 75 }, { OV(835), 70 }, { OV(858), 65 }, { OV(880), 60 }, { OV(899), 55 }, { OV(915), 50 }, { OV(930), 45 }, { OV(944), 40 }, { OV(955), 35 }, { OV(965), 30 }, // 78279.3 { OV(974), 25 }, { OV(981), 20 }, { OV(988), 15 }, { OV(993), 10 }, { OV(998), 5 }, { OV(1002), 0 }, };
2301_81045437/Marlin
Marlin/src/module/thermistor/thermistor_512.h
C++
agpl-3.0
2,231