From dc34b7cae2d4de2fa50221a4e6c193f41663c9dd Mon Sep 17 00:00:00 2001 From: trankilloman Date: Mon, 8 Jun 2015 22:42:57 +0200 Subject: [PATCH] Ajout Marlin --- Marlin/BlinkM.cpp | 22 + Marlin/BlinkM.h | 13 + Marlin/Conditionals.h | 492 ++ Marlin/Configuration.h | 821 +++ Marlin/Configuration.h.bak | 817 +++ Marlin/Configuration.h~ | 821 +++ Marlin/ConfigurationStore.cpp | 810 +++ Marlin/ConfigurationStore.h | 22 + Marlin/Configuration_adv.h | 550 ++ Marlin/Configuration_adv.h.bak | 549 ++ Marlin/DOGMbitmaps.h | 237 + Marlin/Makefile | 493 ++ Marlin/Marlin.h | 325 + Marlin/Marlin.ino | 56 + Marlin/MarlinSerial.cpp | 292 + Marlin/MarlinSerial.h | 160 + Marlin/Marlin_main.cpp | 6052 +++++++++++++++++ Marlin/SanityCheck.h | 316 + Marlin/Sd2Card.cpp | 723 ++ Marlin/Sd2Card.h | 243 + Marlin/Sd2PinMap.h | 436 ++ Marlin/SdBaseFile.cpp | 1825 +++++ Marlin/SdBaseFile.h | 483 ++ Marlin/SdFatConfig.h | 125 + Marlin/SdFatStructs.h | 646 ++ Marlin/SdFatUtil.cpp | 82 + Marlin/SdFatUtil.h | 48 + Marlin/SdFile.cpp | 95 + Marlin/SdFile.h | 54 + Marlin/SdInfo.h | 280 + Marlin/SdVolume.cpp | 405 ++ Marlin/SdVolume.h | 214 + Marlin/Servo.cpp | 304 + Marlin/Servo.h | 135 + Marlin/boards.h | 62 + Marlin/cardreader.cpp | 517 ++ Marlin/cardreader.h | 97 + Marlin/configurator/config/Configuration.h | 816 +++ .../configurator/config/Configuration_adv.h | 549 ++ Marlin/configurator/config/_htaccess | 1 + Marlin/configurator/config/boards.h | 62 + Marlin/configurator/config/language.h | 238 + Marlin/configurator/css/configurator.css | 344 + Marlin/configurator/css/logo.png | Bin 0 -> 1266 bytes Marlin/configurator/index.html | 129 + Marlin/configurator/js/FileSaver.min.js | 2 + Marlin/configurator/js/binaryfileuploader.js | 79 + Marlin/configurator/js/binarystring.js | 168 + Marlin/configurator/js/configurator.js | 1432 ++++ Marlin/configurator/js/jcanvas.js | 524 ++ Marlin/configurator/js/jquery-2.1.3.min.js | 4 + Marlin/configurator/js/jstepper.js | 220 + Marlin/configurator/js/jszip.min.js | 14 + Marlin/digipot_mcp4451.cpp | 58 + Marlin/dogm_font_data_6x9_marlin.h | 157 + Marlin/dogm_font_data_HD44780_C.h | 171 + Marlin/dogm_font_data_HD44780_J.h | 169 + Marlin/dogm_font_data_HD44780_W.h | 203 + Marlin/dogm_font_data_ISO10646_1.h | 176 + Marlin/dogm_font_data_ISO10646_5_Cyrillic.h | 174 + Marlin/dogm_font_data_ISO10646_Kana.h | 173 + Marlin/dogm_font_data_Marlin_symbols.h | 22 + Marlin/dogm_lcd_implementation.h | 488 ++ .../Felix/Configuration.h | 748 ++ .../Felix/Configuration_DUAL.h | 744 ++ .../Felix/Configuration_adv.h | 549 ++ Marlin/example_configurations/Felix/README.md | 60 + .../Hephestos/Configuration.h | 768 +++ .../Hephestos/Configuration_adv.h | 549 ++ .../K8200/Configuration.h | 776 +++ .../K8200/Configuration_adv.h | 549 ++ Marlin/example_configurations/K8200/readme.md | 13 + .../SCARA/Configuration.h | 799 +++ .../SCARA/Configuration_adv.h | 549 ++ .../WITBOX/Configuration.h | 767 +++ .../WITBOX/Configuration_adv.h | 549 ++ .../delta/generic/Configuration.h | 823 +++ .../delta/generic/Configuration_adv.h | 550 ++ .../delta/kossel_mini/Configuration.h | 827 +++ .../delta/kossel_mini/Configuration_adv.h | 549 ++ .../makibox/Configuration.h | 767 +++ .../makibox/Configuration_adv.h | 549 ++ .../tvrrug/Round2/Configuration.h | 773 +++ .../tvrrug/Round2/Configuration_adv.h | 549 ++ Marlin/fastio.h | 4022 +++++++++++ Marlin/fonts/HD44780_C.fon | Bin 0 -> 4176 bytes Marlin/fonts/HD44780_J.fon | Bin 0 -> 4176 bytes Marlin/fonts/HD44780_W.fon | Bin 0 -> 4432 bytes Marlin/fonts/ISO10646-1.fon | Bin 0 -> 4192 bytes Marlin/fonts/ISO10646-5_Cyrillic.fon | Bin 0 -> 4224 bytes Marlin/fonts/ISO10646_Kana.fon | Bin 0 -> 4208 bytes Marlin/fonts/Marlin_symbols.fon | Bin 0 -> 784 bytes Marlin/fonts/README.fonts | 6 + Marlin/fonts/bdf2u8g.exe | Bin 0 -> 56515 bytes Marlin/fonts/make_fonts.bat | 7 + Marlin/language.h | 238 + Marlin/language_an.h | 137 + Marlin/language_ca.h | 138 + Marlin/language_de.h | 136 + Marlin/language_en.h | 445 ++ Marlin/language_es.h | 137 + Marlin/language_eu.h | 137 + Marlin/language_fi.h | 137 + Marlin/language_fr.h | 138 + Marlin/language_it.h | 138 + Marlin/language_kana.h | 149 + Marlin/language_kana_utf8.h | 144 + Marlin/language_nl.h | 137 + Marlin/language_pl.h | 138 + Marlin/language_pt-br.h | 137 + Marlin/language_pt.h | 137 + Marlin/language_ru.h | 138 + Marlin/language_test.h | 215 + Marlin/mesh_bed_leveling.cpp | 16 + Marlin/mesh_bed_leveling.h | 57 + Marlin/motion_control.cpp | 145 + Marlin/motion_control.h | 32 + Marlin/pins.h | 235 + Marlin/pins_3DRAG.h | 61 + Marlin/pins_5DPRINT.h | 84 + Marlin/pins_99.h | 38 + Marlin/pins_AZTEEG_X1.h | 7 + Marlin/pins_AZTEEG_X3.h | 36 + Marlin/pins_AZTEEG_X3_PRO.h | 120 + Marlin/pins_BAM_DICE_DUE.h | 16 + Marlin/pins_BRAINWAVE.h | 61 + Marlin/pins_CHEAPTRONIC.h | 89 + Marlin/pins_DUEMILANOVE_328P.h | 43 + Marlin/pins_ELEFU_3.h | 110 + Marlin/pins_FELIX2.h | 49 + Marlin/pins_GEN3_MONOLITHIC.h | 61 + Marlin/pins_GEN3_PLUS.h | 45 + Marlin/pins_GEN6.h | 62 + Marlin/pins_GEN6_DELUXE.h | 5 + Marlin/pins_GEN7_12.h | 72 + Marlin/pins_GEN7_13.h | 8 + Marlin/pins_GEN7_14.h | 60 + Marlin/pins_GEN7_CUSTOM.h | 76 + Marlin/pins_HEPHESTOS.h | 11 + Marlin/pins_K8200.h | 6 + Marlin/pins_LEAPFROG.h | 62 + Marlin/pins_MEGATRONICS.h | 86 + Marlin/pins_MEGATRONICS_1.h | 82 + Marlin/pins_MEGATRONICS_2.h | 97 + Marlin/pins_MEGATRONICS_3.h | 97 + Marlin/pins_MELZI.h | 11 + Marlin/pins_MELZI_1284.h | 15 + Marlin/pins_OMCA.h | 91 + Marlin/pins_OMCA_A.h | 78 + Marlin/pins_PRINTRBOARD.h | 111 + Marlin/pins_RAMBO.h | 186 + Marlin/pins_RAMPS_13.h | 240 + Marlin/pins_RAMPS_OLD.h | 69 + Marlin/pins_RUMBA.h | 117 + Marlin/pins_SANGUINOLOLU_11.h | 172 + Marlin/pins_SANGUINOLOLU_12.h | 19 + Marlin/pins_SAV_MKI.h | 88 + Marlin/pins_SETHI.h | 71 + Marlin/pins_STB_11.h | 11 + Marlin/pins_TEENSY2.h | 115 + Marlin/pins_TEENSYLU.h | 85 + Marlin/pins_ULTIMAIN_2.h | 80 + Marlin/pins_ULTIMAKER.h | 100 + Marlin/pins_ULTIMAKER_OLD.h | 62 + Marlin/pins_WITBOX.h | 11 + Marlin/planner.cpp | 1004 +++ Marlin/planner.h | 166 + Marlin/qr_solve.cpp | 1929 ++++++ Marlin/qr_solve.h | 22 + Marlin/scripts/createSpeedLookupTable.py | 50 + .../scripts/createTemperatureLookupMarlin.py | 156 + Marlin/scripts/g29_auto.py | 186 + Marlin/speed_lookuptable.h | 152 + Marlin/stepper.cpp | 1333 ++++ Marlin/stepper.h | 110 + Marlin/stepper_indirection.cpp | 224 + Marlin/stepper_indirection.h | 492 ++ Marlin/temperature.cpp | 1606 +++++ Marlin/temperature.h | 151 + Marlin/thermistortables.h | 1236 ++++ Marlin/ultralcd.cpp | 1869 +++++ Marlin/ultralcd.h | 132 + .../ultralcd_implementation_hitachi_HD44780.h | 768 +++ Marlin/ultralcd_st7920_u8glib_rrd.h | 134 + Marlin/utf_mapper.h | 252 + Marlin/vector_3.cpp | 138 + Marlin/vector_3.h | 62 + Marlin/watchdog.cpp | 56 + Marlin/watchdog.h | 17 + 189 files changed, 61819 insertions(+) create mode 100644 Marlin/BlinkM.cpp create mode 100644 Marlin/BlinkM.h create mode 100644 Marlin/Conditionals.h create mode 100644 Marlin/Configuration.h create mode 100644 Marlin/Configuration.h.bak create mode 100644 Marlin/Configuration.h~ create mode 100644 Marlin/ConfigurationStore.cpp create mode 100644 Marlin/ConfigurationStore.h create mode 100644 Marlin/Configuration_adv.h create mode 100644 Marlin/Configuration_adv.h.bak create mode 100644 Marlin/DOGMbitmaps.h create mode 100644 Marlin/Makefile create mode 100644 Marlin/Marlin.h create mode 100644 Marlin/Marlin.ino create mode 100644 Marlin/MarlinSerial.cpp create mode 100644 Marlin/MarlinSerial.h create mode 100644 Marlin/Marlin_main.cpp create mode 100644 Marlin/SanityCheck.h create mode 100644 Marlin/Sd2Card.cpp create mode 100644 Marlin/Sd2Card.h create mode 100644 Marlin/Sd2PinMap.h create mode 100644 Marlin/SdBaseFile.cpp create mode 100644 Marlin/SdBaseFile.h create mode 100644 Marlin/SdFatConfig.h create mode 100644 Marlin/SdFatStructs.h create mode 100644 Marlin/SdFatUtil.cpp create mode 100644 Marlin/SdFatUtil.h create mode 100644 Marlin/SdFile.cpp create mode 100644 Marlin/SdFile.h create mode 100644 Marlin/SdInfo.h create mode 100644 Marlin/SdVolume.cpp create mode 100644 Marlin/SdVolume.h create mode 100644 Marlin/Servo.cpp create mode 100644 Marlin/Servo.h create mode 100644 Marlin/boards.h create mode 100644 Marlin/cardreader.cpp create mode 100644 Marlin/cardreader.h create mode 100644 Marlin/configurator/config/Configuration.h create mode 100644 Marlin/configurator/config/Configuration_adv.h create mode 100644 Marlin/configurator/config/_htaccess create mode 100644 Marlin/configurator/config/boards.h create mode 100644 Marlin/configurator/config/language.h create mode 100644 Marlin/configurator/css/configurator.css create mode 100644 Marlin/configurator/css/logo.png create mode 100644 Marlin/configurator/index.html create mode 100644 Marlin/configurator/js/FileSaver.min.js create mode 100644 Marlin/configurator/js/binaryfileuploader.js create mode 100644 Marlin/configurator/js/binarystring.js create mode 100644 Marlin/configurator/js/configurator.js create mode 100644 Marlin/configurator/js/jcanvas.js create mode 100644 Marlin/configurator/js/jquery-2.1.3.min.js create mode 100644 Marlin/configurator/js/jstepper.js create mode 100644 Marlin/configurator/js/jszip.min.js create mode 100644 Marlin/digipot_mcp4451.cpp create mode 100644 Marlin/dogm_font_data_6x9_marlin.h create mode 100644 Marlin/dogm_font_data_HD44780_C.h create mode 100644 Marlin/dogm_font_data_HD44780_J.h create mode 100644 Marlin/dogm_font_data_HD44780_W.h create mode 100644 Marlin/dogm_font_data_ISO10646_1.h create mode 100644 Marlin/dogm_font_data_ISO10646_5_Cyrillic.h create mode 100644 Marlin/dogm_font_data_ISO10646_Kana.h create mode 100644 Marlin/dogm_font_data_Marlin_symbols.h create mode 100644 Marlin/dogm_lcd_implementation.h create mode 100644 Marlin/example_configurations/Felix/Configuration.h create mode 100644 Marlin/example_configurations/Felix/Configuration_DUAL.h create mode 100644 Marlin/example_configurations/Felix/Configuration_adv.h create mode 100644 Marlin/example_configurations/Felix/README.md create mode 100644 Marlin/example_configurations/Hephestos/Configuration.h create mode 100644 Marlin/example_configurations/Hephestos/Configuration_adv.h create mode 100644 Marlin/example_configurations/K8200/Configuration.h create mode 100644 Marlin/example_configurations/K8200/Configuration_adv.h create mode 100644 Marlin/example_configurations/K8200/readme.md create mode 100644 Marlin/example_configurations/SCARA/Configuration.h create mode 100644 Marlin/example_configurations/SCARA/Configuration_adv.h create mode 100644 Marlin/example_configurations/WITBOX/Configuration.h create mode 100644 Marlin/example_configurations/WITBOX/Configuration_adv.h create mode 100644 Marlin/example_configurations/delta/generic/Configuration.h create mode 100644 Marlin/example_configurations/delta/generic/Configuration_adv.h create mode 100644 Marlin/example_configurations/delta/kossel_mini/Configuration.h create mode 100644 Marlin/example_configurations/delta/kossel_mini/Configuration_adv.h create mode 100644 Marlin/example_configurations/makibox/Configuration.h create mode 100644 Marlin/example_configurations/makibox/Configuration_adv.h create mode 100644 Marlin/example_configurations/tvrrug/Round2/Configuration.h create mode 100644 Marlin/example_configurations/tvrrug/Round2/Configuration_adv.h create mode 100644 Marlin/fastio.h create mode 100644 Marlin/fonts/HD44780_C.fon create mode 100644 Marlin/fonts/HD44780_J.fon create mode 100644 Marlin/fonts/HD44780_W.fon create mode 100644 Marlin/fonts/ISO10646-1.fon create mode 100644 Marlin/fonts/ISO10646-5_Cyrillic.fon create mode 100644 Marlin/fonts/ISO10646_Kana.fon create mode 100644 Marlin/fonts/Marlin_symbols.fon create mode 100644 Marlin/fonts/README.fonts create mode 100644 Marlin/fonts/bdf2u8g.exe create mode 100644 Marlin/fonts/make_fonts.bat create mode 100644 Marlin/language.h create mode 100644 Marlin/language_an.h create mode 100644 Marlin/language_ca.h create mode 100644 Marlin/language_de.h create mode 100644 Marlin/language_en.h create mode 100644 Marlin/language_es.h create mode 100644 Marlin/language_eu.h create mode 100644 Marlin/language_fi.h create mode 100644 Marlin/language_fr.h create mode 100644 Marlin/language_it.h create mode 100644 Marlin/language_kana.h create mode 100644 Marlin/language_kana_utf8.h create mode 100644 Marlin/language_nl.h create mode 100644 Marlin/language_pl.h create mode 100644 Marlin/language_pt-br.h create mode 100644 Marlin/language_pt.h create mode 100644 Marlin/language_ru.h create mode 100644 Marlin/language_test.h create mode 100644 Marlin/mesh_bed_leveling.cpp create mode 100644 Marlin/mesh_bed_leveling.h create mode 100644 Marlin/motion_control.cpp create mode 100644 Marlin/motion_control.h create mode 100644 Marlin/pins.h create mode 100644 Marlin/pins_3DRAG.h create mode 100644 Marlin/pins_5DPRINT.h create mode 100644 Marlin/pins_99.h create mode 100644 Marlin/pins_AZTEEG_X1.h create mode 100644 Marlin/pins_AZTEEG_X3.h create mode 100644 Marlin/pins_AZTEEG_X3_PRO.h create mode 100644 Marlin/pins_BAM_DICE_DUE.h create mode 100644 Marlin/pins_BRAINWAVE.h create mode 100644 Marlin/pins_CHEAPTRONIC.h create mode 100644 Marlin/pins_DUEMILANOVE_328P.h create mode 100644 Marlin/pins_ELEFU_3.h create mode 100644 Marlin/pins_FELIX2.h create mode 100644 Marlin/pins_GEN3_MONOLITHIC.h create mode 100644 Marlin/pins_GEN3_PLUS.h create mode 100644 Marlin/pins_GEN6.h create mode 100644 Marlin/pins_GEN6_DELUXE.h create mode 100644 Marlin/pins_GEN7_12.h create mode 100644 Marlin/pins_GEN7_13.h create mode 100644 Marlin/pins_GEN7_14.h create mode 100644 Marlin/pins_GEN7_CUSTOM.h create mode 100644 Marlin/pins_HEPHESTOS.h create mode 100644 Marlin/pins_K8200.h create mode 100644 Marlin/pins_LEAPFROG.h create mode 100644 Marlin/pins_MEGATRONICS.h create mode 100644 Marlin/pins_MEGATRONICS_1.h create mode 100644 Marlin/pins_MEGATRONICS_2.h create mode 100644 Marlin/pins_MEGATRONICS_3.h create mode 100644 Marlin/pins_MELZI.h create mode 100644 Marlin/pins_MELZI_1284.h create mode 100644 Marlin/pins_OMCA.h create mode 100644 Marlin/pins_OMCA_A.h create mode 100644 Marlin/pins_PRINTRBOARD.h create mode 100644 Marlin/pins_RAMBO.h create mode 100644 Marlin/pins_RAMPS_13.h create mode 100644 Marlin/pins_RAMPS_OLD.h create mode 100644 Marlin/pins_RUMBA.h create mode 100644 Marlin/pins_SANGUINOLOLU_11.h create mode 100644 Marlin/pins_SANGUINOLOLU_12.h create mode 100644 Marlin/pins_SAV_MKI.h create mode 100644 Marlin/pins_SETHI.h create mode 100644 Marlin/pins_STB_11.h create mode 100644 Marlin/pins_TEENSY2.h create mode 100644 Marlin/pins_TEENSYLU.h create mode 100644 Marlin/pins_ULTIMAIN_2.h create mode 100644 Marlin/pins_ULTIMAKER.h create mode 100644 Marlin/pins_ULTIMAKER_OLD.h create mode 100644 Marlin/pins_WITBOX.h create mode 100644 Marlin/planner.cpp create mode 100644 Marlin/planner.h create mode 100644 Marlin/qr_solve.cpp create mode 100644 Marlin/qr_solve.h create mode 100644 Marlin/scripts/createSpeedLookupTable.py create mode 100644 Marlin/scripts/createTemperatureLookupMarlin.py create mode 100644 Marlin/scripts/g29_auto.py create mode 100644 Marlin/speed_lookuptable.h create mode 100644 Marlin/stepper.cpp create mode 100644 Marlin/stepper.h create mode 100644 Marlin/stepper_indirection.cpp create mode 100644 Marlin/stepper_indirection.h create mode 100644 Marlin/temperature.cpp create mode 100644 Marlin/temperature.h create mode 100644 Marlin/thermistortables.h create mode 100644 Marlin/ultralcd.cpp create mode 100644 Marlin/ultralcd.h create mode 100644 Marlin/ultralcd_implementation_hitachi_HD44780.h create mode 100644 Marlin/ultralcd_st7920_u8glib_rrd.h create mode 100644 Marlin/utf_mapper.h create mode 100644 Marlin/vector_3.cpp create mode 100644 Marlin/vector_3.h create mode 100644 Marlin/watchdog.cpp create mode 100644 Marlin/watchdog.h diff --git a/Marlin/BlinkM.cpp b/Marlin/BlinkM.cpp new file mode 100644 index 0000000..b340f96 --- /dev/null +++ b/Marlin/BlinkM.cpp @@ -0,0 +1,22 @@ +/* + BlinkM.cpp - Library for controlling a BlinkM over i2c + Created by Tim Koster, August 21 2013. +*/ +#include "Marlin.h" +#ifdef BLINKM + +#include "BlinkM.h" + +void SendColors(byte red, byte grn, byte blu) { + Wire.begin(); + Wire.beginTransmission(0x09); + Wire.write('o'); //to disable ongoing script, only needs to be used once + Wire.write('n'); + Wire.write(red); + Wire.write(grn); + Wire.write(blu); + Wire.endTransmission(); +} + +#endif //BLINKM + diff --git a/Marlin/BlinkM.h b/Marlin/BlinkM.h new file mode 100644 index 0000000..5b802b7 --- /dev/null +++ b/Marlin/BlinkM.h @@ -0,0 +1,13 @@ +/* + BlinkM.h + Library header file for BlinkM library + */ +#if ARDUINO >= 100 + #include "Arduino.h" +#else + #include "WProgram.h" +#endif + +#include "Wire.h" + +void SendColors(byte red, byte grn, byte blu); diff --git a/Marlin/Conditionals.h b/Marlin/Conditionals.h new file mode 100644 index 0000000..fa57408 --- /dev/null +++ b/Marlin/Conditionals.h @@ -0,0 +1,492 @@ +/** + * Conditionals.h + * Defines that depend on configuration but are not editable. + */ +#ifndef CONDITIONALS_H + +#ifndef M_PI + #define M_PI 3.1415926536 +#endif + +#ifndef CONFIGURATION_LCD // Get the LCD defines which are needed first + + #define PIN_EXISTS(PN) (defined(PN##_PIN) && PN##_PIN >= 0) + + #define CONFIGURATION_LCD + + #if defined(MAKRPANEL) + #define DOGLCD + #define SDSUPPORT + #define DEFAULT_LCD_CONTRAST 17 + #define ULTIPANEL + #define NEWPANEL + #endif + + #if defined(miniVIKI) || defined(VIKI2) + #define ULTRA_LCD //general LCD support, also 16x2 + #define DOGLCD // Support for SPI LCD 128x64 (Controller ST7565R graphic Display Family) + #define ULTIMAKERCONTROLLER //as available from the Ultimaker online store. + + #ifdef miniVIKI + #define DEFAULT_LCD_CONTRAST 95 + #else + #define DEFAULT_LCD_CONTRAST 40 + #endif + + #define ENCODER_PULSES_PER_STEP 4 + #define ENCODER_STEPS_PER_MENU_ITEM 1 + #endif + + #ifdef PANEL_ONE + #define SDSUPPORT + #define ULTIMAKERCONTROLLER + #endif + + #ifdef REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER + #define DOGLCD + #define U8GLIB_ST7920 + #define REPRAP_DISCOUNT_SMART_CONTROLLER + #endif + + #if defined(ULTIMAKERCONTROLLER) || defined(REPRAP_DISCOUNT_SMART_CONTROLLER) || defined(G3D_PANEL) + #define ULTIPANEL + #define NEWPANEL + #endif + + #ifdef REPRAPWORLD_KEYPAD + #define ULTIPANEL + #define NEWPANEL + #endif + + #ifdef RA_CONTROL_PANEL + #define LCD_I2C_TYPE_PCA8574 + #define LCD_I2C_ADDRESS 0x27 // I2C Address of the port expander + #define ULTIPANEL + #define NEWPANEL + #endif + + /** + * I2C PANELS + */ + + #ifdef LCD_I2C_SAINSMART_YWROBOT + // This uses the LiquidCrystal_I2C library ( https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home ) + // Make sure it is placed in the Arduino libraries directory. + #define LCD_I2C_TYPE_PCF8575 + #define LCD_I2C_ADDRESS 0x27 // I2C Address of the port expander + #define ULTIPANEL + #define NEWPANEL + #endif + + // PANELOLU2 LCD with status LEDs, separate encoder and click inputs + #ifdef LCD_I2C_PANELOLU2 + // This uses the LiquidTWI2 library v1.2.3 or later ( https://github.com/lincomatic/LiquidTWI2 ) + // Make sure the LiquidTWI2 directory is placed in the Arduino or Sketchbook libraries subdirectory. + // (v1.2.3 no longer requires you to define PANELOLU in the LiquidTWI2.h library header file) + // Note: The PANELOLU2 encoder click input can either be directly connected to a pin + // (if BTN_ENC defined to != -1) or read through I2C (when BTN_ENC == -1). + #define LCD_I2C_TYPE_MCP23017 + #define LCD_I2C_ADDRESS 0x20 // I2C Address of the port expander + #define LCD_USE_I2C_BUZZER //comment out to disable buzzer on LCD + + #ifndef ENCODER_PULSES_PER_STEP + #define ENCODER_PULSES_PER_STEP 4 + #endif + + #ifndef ENCODER_STEPS_PER_MENU_ITEM + #define ENCODER_STEPS_PER_MENU_ITEM 1 + #endif + + #ifdef LCD_USE_I2C_BUZZER + #define LCD_FEEDBACK_FREQUENCY_HZ 1000 + #define LCD_FEEDBACK_FREQUENCY_DURATION_MS 100 + #endif + + #define ULTIPANEL + #define NEWPANEL + #endif + + // Panucatt VIKI LCD with status LEDs, integrated click & L/R/U/P buttons, separate encoder inputs + #ifdef LCD_I2C_VIKI + // This uses the LiquidTWI2 library v1.2.3 or later ( https://github.com/lincomatic/LiquidTWI2 ) + // Make sure the LiquidTWI2 directory is placed in the Arduino or Sketchbook libraries subdirectory. + // Note: The pause/stop/resume LCD button pin should be connected to the Arduino + // BTN_ENC pin (or set BTN_ENC to -1 if not used) + #define LCD_I2C_TYPE_MCP23017 + #define LCD_I2C_ADDRESS 0x20 // I2C Address of the port expander + #define LCD_USE_I2C_BUZZER //comment out to disable buzzer on LCD (requires LiquidTWI2 v1.2.3 or later) + #define ULTIPANEL + #define NEWPANEL + #endif + + // Shift register panels + // --------------------- + // 2 wire Non-latching LCD SR from: + // https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/schematics#!shiftregister-connection + + #ifdef SAV_3DLCD + #define SR_LCD_2W_NL // Non latching 2 wire shiftregister + #define ULTIPANEL + #define NEWPANEL + #endif + + #ifdef ULTIPANEL + #define NEWPANEL //enable this if you have a click-encoder panel + #define SDSUPPORT + #define ULTRA_LCD + #ifdef DOGLCD // Change number of lines to match the DOG graphic display + #define LCD_WIDTH 22 + #define LCD_HEIGHT 5 + #else + #define LCD_WIDTH 20 + #define LCD_HEIGHT 4 + #endif + #else //no panel but just LCD + #ifdef ULTRA_LCD + #ifdef DOGLCD // Change number of lines to match the 128x64 graphics display + #define LCD_WIDTH 22 + #define LCD_HEIGHT 5 + #else + #define LCD_WIDTH 16 + #define LCD_HEIGHT 2 + #endif + #endif + #endif + + #ifdef DOGLCD + /* Custom characters defined in font font_6x10_marlin_symbols */ + // \x00 intentionally skipped to avoid problems in strings + #define LCD_STR_REFRESH "\x01" + #define LCD_STR_FOLDER "\x02" + #define LCD_STR_ARROW_RIGHT "\x03" + #define LCD_STR_UPLEVEL "\x04" + #define LCD_STR_CLOCK "\x05" + #define LCD_STR_FEEDRATE "\x06" + #define LCD_STR_BEDTEMP "\x07" + #define LCD_STR_THERMOMETER "\x08" + #define LCD_STR_DEGREE "\x09" + + #define LCD_STR_SPECIAL_MAX '\x09' + // Maximum here is 0x1f because 0x20 is ' ' (space) and the normal charsets begin. + // Better stay below 0x10 because DISPLAY_CHARSET_HD44780_WESTERN begins here. + #else + /* Custom characters defined in the first 8 characters of the LCD */ + #define LCD_STR_BEDTEMP "\x00" // this will have 'unexpected' results when used in a string! + #define LCD_STR_DEGREE "\x01" + #define LCD_STR_THERMOMETER "\x02" + #define LCD_STR_UPLEVEL "\x03" + #define LCD_STR_REFRESH "\x04" + #define LCD_STR_FOLDER "\x05" + #define LCD_STR_FEEDRATE "\x06" + #define LCD_STR_CLOCK "\x07" + #define LCD_STR_ARROW_RIGHT ">" /* from the default character set */ + #endif + + /** + * Default LCD contrast for dogm-like LCD displays + */ + #if defined(DOGLCD) && !defined(DEFAULT_LCD_CONTRAST) + #define DEFAULT_LCD_CONTRAST 32 + #endif + + #ifdef DOGLCD + #define HAS_LCD_CONTRAST + #ifdef U8GLIB_ST7920 + #undef HAS_LCD_CONTRAST + #endif + #endif + +#else // CONFIGURATION_LCD + + #define CONDITIONALS_H + + #ifndef AT90USB + #define HardwareSerial_h // trick to disable the standard HWserial + #endif + + #if (ARDUINO >= 100) + #include "Arduino.h" + #else + #include "WProgram.h" + #endif + + #include "pins.h" + + /** + * ENDSTOPPULLUPS + */ + #ifdef ENDSTOPPULLUPS + #ifndef DISABLE_MAX_ENDSTOPS + #define ENDSTOPPULLUP_XMAX + #define ENDSTOPPULLUP_YMAX + #define ENDSTOPPULLUP_ZMAX + #endif + #ifndef DISABLE_MIN_ENDSTOPS + #define ENDSTOPPULLUP_XMIN + #define ENDSTOPPULLUP_YMIN + #define ENDSTOPPULLUP_ZMIN + #endif + #ifndef DISABLE_Z_PROBE_ENDSTOP + #define ENDSTOPPULLUP_ZPROBE + #endif + #endif + + /** + * Axis lengths + */ + #define X_MAX_LENGTH (X_MAX_POS - X_MIN_POS) + #define Y_MAX_LENGTH (Y_MAX_POS - Y_MIN_POS) + #define Z_MAX_LENGTH (Z_MAX_POS - Z_MIN_POS) + + /** + * SCARA + */ + #ifdef SCARA + #undef SLOWDOWN + #define QUICK_HOME //SCARA needs Quickhome + #endif + + /** + * AUTOSET LOCATIONS OF LIMIT SWITCHES + * Added by ZetaPhoenix 09-15-2012 + */ + #ifdef MANUAL_HOME_POSITIONS // Use manual limit switch locations + #define X_HOME_POS MANUAL_X_HOME_POS + #define Y_HOME_POS MANUAL_Y_HOME_POS + #define Z_HOME_POS MANUAL_Z_HOME_POS + #else //!MANUAL_HOME_POSITIONS – Use home switch positions based on homing direction and travel limits + #ifdef BED_CENTER_AT_0_0 + #define X_HOME_POS X_MAX_LENGTH * X_HOME_DIR * 0.5 + #define Y_HOME_POS Y_MAX_LENGTH * Y_HOME_DIR * 0.5 + #else + #define X_HOME_POS (X_HOME_DIR < 0 ? X_MIN_POS : X_MAX_POS) + #define Y_HOME_POS (Y_HOME_DIR < 0 ? Y_MIN_POS : Y_MAX_POS) + #endif + #define Z_HOME_POS (Z_HOME_DIR < 0 ? Z_MIN_POS : Z_MAX_POS) + #endif //!MANUAL_HOME_POSITIONS + + /** + * Auto Bed Leveling + */ + #ifdef ENABLE_AUTO_BED_LEVELING + // Boundaries for probing based on set limits + #define MIN_PROBE_X (max(X_MIN_POS, X_MIN_POS + X_PROBE_OFFSET_FROM_EXTRUDER)) + #define MAX_PROBE_X (min(X_MAX_POS, X_MAX_POS + X_PROBE_OFFSET_FROM_EXTRUDER)) + #define MIN_PROBE_Y (max(Y_MIN_POS, Y_MIN_POS + Y_PROBE_OFFSET_FROM_EXTRUDER)) + #define MAX_PROBE_Y (min(Y_MAX_POS, Y_MAX_POS + Y_PROBE_OFFSET_FROM_EXTRUDER)) + #endif + + /** + * MAX_STEP_FREQUENCY differs for TOSHIBA + */ + #ifdef CONFIG_STEPPERS_TOSHIBA + #define MAX_STEP_FREQUENCY 10000 // Max step frequency for Toshiba Stepper Controllers + #else + #define MAX_STEP_FREQUENCY 40000 // Max step frequency for Ultimaker (5000 pps / half step) + #endif + + // MS1 MS2 Stepper Driver Microstepping mode table + #define MICROSTEP1 LOW,LOW + #define MICROSTEP2 HIGH,LOW + #define MICROSTEP4 LOW,HIGH + #define MICROSTEP8 HIGH,HIGH + #define MICROSTEP16 HIGH,HIGH + + /** + * Advance calculated values + */ + #ifdef ADVANCE + #define EXTRUSION_AREA (0.25 * D_FILAMENT * D_FILAMENT * M_PI) + #define STEPS_PER_CUBIC_MM_E (axis_steps_per_unit[E_AXIS] / EXTRUSION_AREA) + #endif + + #ifdef ULTIPANEL + #undef SDCARDDETECTINVERTED + #endif + + // Power Signal Control Definitions + // By default use ATX definition + #ifndef POWER_SUPPLY + #define POWER_SUPPLY 1 + #endif + #if (POWER_SUPPLY == 1) // 1 = ATX + #define PS_ON_AWAKE LOW + #define PS_ON_ASLEEP HIGH + #elif (POWER_SUPPLY == 2) // 2 = X-Box 360 203W + #define PS_ON_AWAKE HIGH + #define PS_ON_ASLEEP LOW + #endif + #define HAS_POWER_SWITCH (POWER_SUPPLY > 0 && PIN_EXISTS(PS_ON)) + + /** + * Temp Sensor defines + */ + #if TEMP_SENSOR_0 == -2 + #define HEATER_0_USES_MAX6675 + #elif TEMP_SENSOR_0 == -1 + #define HEATER_0_USES_AD595 + #elif TEMP_SENSOR_0 == 0 + #undef HEATER_0_MINTEMP + #undef HEATER_0_MAXTEMP + #elif TEMP_SENSOR_0 > 0 + #define THERMISTORHEATER_0 TEMP_SENSOR_0 + #define HEATER_0_USES_THERMISTOR + #endif + + #if TEMP_SENSOR_1 == -1 + #define HEATER_1_USES_AD595 + #elif TEMP_SENSOR_1 == 0 + #undef HEATER_1_MINTEMP + #undef HEATER_1_MAXTEMP + #elif TEMP_SENSOR_1 > 0 + #define THERMISTORHEATER_1 TEMP_SENSOR_1 + #define HEATER_1_USES_THERMISTOR + #endif + + #if TEMP_SENSOR_2 == -1 + #define HEATER_2_USES_AD595 + #elif TEMP_SENSOR_2 == 0 + #undef HEATER_2_MINTEMP + #undef HEATER_2_MAXTEMP + #elif TEMP_SENSOR_2 > 0 + #define THERMISTORHEATER_2 TEMP_SENSOR_2 + #define HEATER_2_USES_THERMISTOR + #endif + + #if TEMP_SENSOR_3 == -1 + #define HEATER_3_USES_AD595 + #elif TEMP_SENSOR_3 == 0 + #undef HEATER_3_MINTEMP + #undef HEATER_3_MAXTEMP + #elif TEMP_SENSOR_3 > 0 + #define THERMISTORHEATER_3 TEMP_SENSOR_3 + #define HEATER_3_USES_THERMISTOR + #endif + + #if TEMP_SENSOR_BED == -1 + #define BED_USES_AD595 + #elif TEMP_SENSOR_BED == 0 + #undef BED_MINTEMP + #undef BED_MAXTEMP + #elif TEMP_SENSOR_BED > 0 + #define THERMISTORBED TEMP_SENSOR_BED + #define BED_USES_THERMISTOR + #endif + + /** + * ARRAY_BY_EXTRUDERS based on EXTRUDERS + */ + #if EXTRUDERS > 3 + #define ARRAY_BY_EXTRUDERS(v1, v2, v3, v4) { v1, v2, v3, v4 } + #elif EXTRUDERS > 2 + #define ARRAY_BY_EXTRUDERS(v1, v2, v3, v4) { v1, v2, v3 } + #elif EXTRUDERS > 1 + #define ARRAY_BY_EXTRUDERS(v1, v2, v3, v4) { v1, v2 } + #else + #define ARRAY_BY_EXTRUDERS(v1, v2, v3, v4) { v1 } + #endif + + /** + * Shorthand for pin tests, used wherever needed + */ + #define HAS_TEMP_0 (PIN_EXISTS(TEMP_0) && TEMP_SENSOR_0 != 0 && TEMP_SENSOR_0 != -2) + #define HAS_TEMP_1 (PIN_EXISTS(TEMP_1) && TEMP_SENSOR_1 != 0) + #define HAS_TEMP_2 (PIN_EXISTS(TEMP_2) && TEMP_SENSOR_2 != 0) + #define HAS_TEMP_3 (PIN_EXISTS(TEMP_3) && TEMP_SENSOR_3 != 0) + #define HAS_TEMP_BED (PIN_EXISTS(TEMP_BED) && TEMP_SENSOR_BED != 0) + #define HAS_HEATER_0 (PIN_EXISTS(HEATER_0)) + #define HAS_HEATER_1 (PIN_EXISTS(HEATER_1)) + #define HAS_HEATER_2 (PIN_EXISTS(HEATER_2)) + #define HAS_HEATER_3 (PIN_EXISTS(HEATER_3)) + #define HAS_HEATER_BED (PIN_EXISTS(HEATER_BED)) + #define HAS_AUTO_FAN_0 (PIN_EXISTS(EXTRUDER_0_AUTO_FAN)) + #define HAS_AUTO_FAN_1 (PIN_EXISTS(EXTRUDER_1_AUTO_FAN)) + #define HAS_AUTO_FAN_2 (PIN_EXISTS(EXTRUDER_2_AUTO_FAN)) + #define HAS_AUTO_FAN_3 (PIN_EXISTS(EXTRUDER_3_AUTO_FAN)) + #define HAS_AUTO_FAN (HAS_AUTO_FAN_0 || HAS_AUTO_FAN_1 || HAS_AUTO_FAN_2 || HAS_AUTO_FAN_3) + #define HAS_FAN (PIN_EXISTS(FAN)) + #define HAS_CONTROLLERFAN (PIN_EXISTS(CONTROLLERFAN)) + #define HAS_SERVO_0 (PIN_EXISTS(SERVO0)) + #define HAS_SERVO_1 (PIN_EXISTS(SERVO1)) + #define HAS_SERVO_2 (PIN_EXISTS(SERVO2)) + #define HAS_SERVO_3 (PIN_EXISTS(SERVO3)) + #define HAS_FILAMENT_SENSOR (defined(FILAMENT_SENSOR) && PIN_EXISTS(FILWIDTH)) + #define HAS_FILRUNOUT (PIN_EXISTS(FILRUNOUT)) + #define HAS_HOME (PIN_EXISTS(HOME)) + #define HAS_KILL (PIN_EXISTS(KILL)) + #define HAS_SUICIDE (PIN_EXISTS(SUICIDE)) + #define HAS_PHOTOGRAPH (PIN_EXISTS(PHOTOGRAPH)) + #define HAS_X_MIN (PIN_EXISTS(X_MIN)) + #define HAS_X_MAX (PIN_EXISTS(X_MAX)) + #define HAS_Y_MIN (PIN_EXISTS(Y_MIN)) + #define HAS_Y_MAX (PIN_EXISTS(Y_MAX)) + #define HAS_Z_MIN (PIN_EXISTS(Z_MIN)) + #define HAS_Z_MAX (PIN_EXISTS(Z_MAX)) + #define HAS_Z2_MIN (PIN_EXISTS(Z2_MIN)) + #define HAS_Z2_MAX (PIN_EXISTS(Z2_MAX)) + #define HAS_Z_PROBE (PIN_EXISTS(Z_PROBE)) + #define HAS_SOLENOID_1 (PIN_EXISTS(SOL1)) + #define HAS_SOLENOID_2 (PIN_EXISTS(SOL2)) + #define HAS_SOLENOID_3 (PIN_EXISTS(SOL3)) + #define HAS_MICROSTEPS (PIN_EXISTS(X_MS1)) + #define HAS_MICROSTEPS_E0 (PIN_EXISTS(E0_MS1)) + #define HAS_MICROSTEPS_E1 (PIN_EXISTS(E1_MS1)) + #define HAS_MICROSTEPS_E2 (PIN_EXISTS(E2_MS1)) + #define HAS_X_ENABLE (PIN_EXISTS(X_ENABLE)) + #define HAS_X2_ENABLE (PIN_EXISTS(X2_ENABLE)) + #define HAS_Y_ENABLE (PIN_EXISTS(Y_ENABLE)) + #define HAS_Y2_ENABLE (PIN_EXISTS(Y2_ENABLE)) + #define HAS_Z_ENABLE (PIN_EXISTS(Z_ENABLE)) + #define HAS_Z2_ENABLE (PIN_EXISTS(Z2_ENABLE)) + #define HAS_E0_ENABLE (PIN_EXISTS(E0_ENABLE)) + #define HAS_E1_ENABLE (PIN_EXISTS(E1_ENABLE)) + #define HAS_E2_ENABLE (PIN_EXISTS(E2_ENABLE)) + #define HAS_E3_ENABLE (PIN_EXISTS(E3_ENABLE)) + #define HAS_X_DIR (PIN_EXISTS(X_DIR)) + #define HAS_X2_DIR (PIN_EXISTS(X2_DIR)) + #define HAS_Y_DIR (PIN_EXISTS(Y_DIR)) + #define HAS_Y2_DIR (PIN_EXISTS(Y2_DIR)) + #define HAS_Z_DIR (PIN_EXISTS(Z_DIR)) + #define HAS_Z2_DIR (PIN_EXISTS(Z2_DIR)) + #define HAS_E0_DIR (PIN_EXISTS(E0_DIR)) + #define HAS_E1_DIR (PIN_EXISTS(E1_DIR)) + #define HAS_E2_DIR (PIN_EXISTS(E2_DIR)) + #define HAS_E3_DIR (PIN_EXISTS(E3_DIR)) + #define HAS_X_STEP (PIN_EXISTS(X_STEP)) + #define HAS_X2_STEP (PIN_EXISTS(X2_STEP)) + #define HAS_Y_STEP (PIN_EXISTS(Y_STEP)) + #define HAS_Y2_STEP (PIN_EXISTS(Y2_STEP)) + #define HAS_Z_STEP (PIN_EXISTS(Z_STEP)) + #define HAS_Z2_STEP (PIN_EXISTS(Z2_STEP)) + #define HAS_E0_STEP (PIN_EXISTS(E0_STEP)) + #define HAS_E1_STEP (PIN_EXISTS(E1_STEP)) + #define HAS_E2_STEP (PIN_EXISTS(E2_STEP)) + #define HAS_E3_STEP (PIN_EXISTS(E3_STEP)) + + /** + * Helper Macros for heaters and extruder fan + */ + #define WRITE_HEATER_0P(v) WRITE(HEATER_0_PIN, v) + #if EXTRUDERS > 1 || defined(HEATERS_PARALLEL) + #define WRITE_HEATER_1(v) WRITE(HEATER_1_PIN, v) + #if EXTRUDERS > 2 + #define WRITE_HEATER_2(v) WRITE(HEATER_2_PIN, v) + #if EXTRUDERS > 3 + #define WRITE_HEATER_3(v) WRITE(HEATER_3_PIN, v) + #endif + #endif + #endif + #ifdef HEATERS_PARALLEL + #define WRITE_HEATER_0(v) { WRITE_HEATER_0P(v); WRITE_HEATER_1(v); } + #else + #define WRITE_HEATER_0(v) WRITE_HEATER_0P(v) + #endif + #if HAS_HEATER_BED + #define WRITE_HEATER_BED(v) WRITE(HEATER_BED_PIN, v) + #endif + #if HAS_FAN + #define WRITE_FAN(v) WRITE(FAN_PIN, v) + #endif + +#endif //CONFIGURATION_LCD +#endif //CONDITIONALS_H diff --git a/Marlin/Configuration.h b/Marlin/Configuration.h new file mode 100644 index 0000000..ed2b066 --- /dev/null +++ b/Marlin/Configuration.h @@ -0,0 +1,821 @@ +#ifndef CONFIGURATION_H +#define CONFIGURATION_H + +#include "boards.h" + +//=========================================================================== +//============================= Getting Started ============================= +//=========================================================================== +/* +Here are some standard links for getting your machine calibrated: + * http://reprap.org/wiki/Calibration + * http://youtu.be/wAL9d7FgInk + * http://calculator.josefprusa.cz + * http://reprap.org/wiki/Triffid_Hunter%27s_Calibration_Guide + * http://www.thingiverse.com/thing:5573 + * https://sites.google.com/site/repraplogphase/calibration-of-your-reprap + * http://www.thingiverse.com/thing:298812 +*/ + +// This configuration file contains the basic settings. +// Advanced settings can be found in Configuration_adv.h +// BASIC SETTINGS: select your board type, temperature sensor type, axis scaling, and endstop configuration + +//=========================================================================== +//============================= DELTA Printer =============================== +//=========================================================================== +// For a Delta printer replace the configuration files with the files in the +// example_configurations/delta directory. +// + +//=========================================================================== +//============================= SCARA Printer =============================== +//=========================================================================== +// For a Delta printer replace the configuration files with the files in the +// example_configurations/SCARA directory. +// + +// User-specified version info of this build to display in [Pronterface, etc] terminal window during +// startup. Implementation of an idea by Prof Braino to inform user that any changes made to this +// build by the user have been successfully uploaded into firmware. +#define STRING_VERSION "1.0.3 dev" +#define STRING_URL "reprap.org" +#define STRING_VERSION_CONFIG_H __DATE__ " " __TIME__ // build date and time +#define STRING_CONFIG_H_AUTHOR "(none, default config)" // Who made the changes. +#define STRING_SPLASH_LINE1 "v" STRING_VERSION // will be shown during bootup in line 1 +//#define STRING_SPLASH_LINE2 STRING_VERSION_CONFIG_H // will be shown during bootup in line2 + +// SERIAL_PORT selects which serial port should be used for communication with the host. +// This allows the connection of wireless adapters (for instance) to non-default port pins. +// Serial port 0 is still used by the Arduino bootloader regardless of this setting. +#define SERIAL_PORT 0 + +// This determines the communication speed of the printer +#define BAUDRATE 115200 + +// This enables the serial port associated to the Bluetooth interface +//#define BTENABLED // Enable BT interface on AT90USB devices + +// The following define selects which electronics board you have. +// Please choose the name from boards.h that matches your setup +#ifndef MOTHERBOARD + #define MOTHERBOARD BOARD_RAMPS_13_EFB +#endif + +// Optional custom name for your RepStrap or other custom machine +// Displayed in the LCD "Ready" message +#define CUSTOM_MACHINE_NAME "ReprapJeanne" + +// Define this to set a unique identifier for this printer, (Used by some programs to differentiate between machines) +// You can use an online service to generate a random UUID. (eg http://www.uuidgenerator.net/version4) +// #define MACHINE_UUID "00000000-0000-0000-0000-000000000000" + +// This defines the number of extruders +#define EXTRUDERS 1 + +//// The following define selects which power supply you have. Please choose the one that matches your setup +// 1 = ATX +// 2 = X-Box 360 203Watts (the blue wire connected to PS_ON and the red wire to VCC) + +#define POWER_SUPPLY 1 +// Define this to have the electronics keep the power supply off on startup. If you don't know what this is leave it. +// #define PS_DEFAULT_OFF + +//=========================================================================== +//============================== Delta Settings ============================= +//=========================================================================== +// Enable DELTA kinematics and most of the default configuration for Deltas +#define DELTA + +// Make delta curves from many straight lines (linear interpolation). +// This is a trade-off between visible corners (not enough segments) +// and processor overload (too many expensive sqrt calls). +#define DELTA_SEGMENTS_PER_SECOND 200 + +// NOTE NB all values for DELTA_* values MUST be floating point, so always have a decimal point in them + +// Center-to-center distance of the holes in the diagonal push rods. +#define DELTA_DIAGONAL_ROD 615.0 // mm + +// Horizontal offset from middle of printer to smooth rod center. +#define DELTA_SMOOTH_ROD_OFFSET 315.0 // mm + +// Horizontal offset of the universal joints on the end effector. +#define DELTA_EFFECTOR_OFFSET 33.0 // mm + +// Horizontal offset of the universal joints on the carriages. +#define DELTA_CARRIAGE_OFFSET 18.0 // mm + +// Horizontal distance bridged by diagonal push rods when effector is centered. +#define DELTA_RADIUS (DELTA_SMOOTH_ROD_OFFSET-DELTA_EFFECTOR_OFFSET-DELTA_CARRIAGE_OFFSET) + +// Print surface diameter/2 minus unreachable space (avoid collisions with vertical towers). +#define DELTA_PRINTABLE_RADIUS 300 + + +//=========================================================================== +//============================= Thermal Settings ============================ +//=========================================================================== +// +//--NORMAL IS 4.7kohm PULLUP!-- 1kohm pullup can be used on hotend sensor, using correct resistor and table +// +//// Temperature sensor settings: +// -2 is thermocouple with MAX6675 (only for sensor 0) +// -1 is thermocouple with AD595 +// 0 is not used +// 1 is 100k thermistor - best choice for EPCOS 100k (4.7k pullup) +// 2 is 200k thermistor - ATC Semitec 204GT-2 (4.7k pullup) +// 3 is Mendel-parts thermistor (4.7k pullup) +// 4 is 10k thermistor !! do not use it for a hotend. It gives bad resolution at high temp. !! +// 5 is 100K thermistor - ATC Semitec 104GT-2 (Used in ParCan & J-Head) (4.7k pullup) +// 6 is 100k EPCOS - Not as accurate as table 1 (created using a fluke thermocouple) (4.7k pullup) +// 7 is 100k Honeywell thermistor 135-104LAG-J01 (4.7k pullup) +// 71 is 100k Honeywell thermistor 135-104LAF-J01 (4.7k pullup) +// 8 is 100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) +// 9 is 100k GE Sensing AL03006-58.2K-97-G1 (4.7k pullup) +// 10 is 100k RS thermistor 198-961 (4.7k pullup) +// 11 is 100k beta 3950 1% thermistor (4.7k pullup) +// 12 is 100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) (calibrated for Makibox hot bed) +// 13 is 100k Hisens 3950 1% up to 300°C for hotend "Simple ONE " & "Hotend "All In ONE" +// 20 is the PT100 circuit found in the Ultimainboard V2.x +// 60 is 100k Maker's Tool Works Kapton Bed Thermistor beta=3950 +// +// 1k ohm pullup tables - This is not normal, you would have to have changed out your 4.7k for 1k +// (but gives greater accuracy and more stable PID) +// 51 is 100k thermistor - EPCOS (1k pullup) +// 52 is 200k thermistor - ATC Semitec 204GT-2 (1k pullup) +// 55 is 100k thermistor - ATC Semitec 104GT-2 (Used in ParCan & J-Head) (1k pullup) +// +// 1047 is Pt1000 with 4k7 pullup +// 1010 is Pt1000 with 1k pullup (non standard) +// 147 is Pt100 with 4k7 pullup +// 110 is Pt100 with 1k pullup (non standard) +// 998 and 999 are Dummy Tables. They will ALWAYS read 25°C or the temperature defined below. +// Use it for Testing or Development purposes. NEVER for production machine. +// #define DUMMY_THERMISTOR_998_VALUE 25 +// #define DUMMY_THERMISTOR_999_VALUE 100 +// :{ '0': "Not used", '4': "10k !! do not use for a hotend. Bad resolution at high temp. !!", '1': "100k / 4.7k - EPCOS", '51': "100k / 1k - EPCOS", '6': "100k / 4.7k EPCOS - Not as accurate as Table 1", '5': "100K / 4.7k - ATC Semitec 104GT-2 (Used in ParCan & J-Head)", '7': "100k / 4.7k Honeywell 135-104LAG-J01", '71': "100k / 4.7k Honeywell 135-104LAF-J01", '8': "100k / 4.7k 0603 SMD Vishay NTCS0603E3104FXT", '9': "100k / 4.7k GE Sensing AL03006-58.2K-97-G1", '10': "100k / 4.7k RS 198-961", '11': "100k / 4.7k beta 3950 1%", '12': "100k / 4.7k 0603 SMD Vishay NTCS0603E3104FXT (calibrated for Makibox hot bed)", '13': "100k Hisens 3950 1% up to 300°C for hotend 'Simple ONE ' & hotend 'All In ONE'", '60': "100k Maker's Tool Works Kapton Bed Thermistor beta=3950", '55': "100k / 1k - ATC Semitec 104GT-2 (Used in ParCan & J-Head)", '2': "200k / 4.7k - ATC Semitec 204GT-2", '52': "200k / 1k - ATC Semitec 204GT-2", '-2': "Thermocouple + MAX6675 (only for sensor 0)", '-1': "Thermocouple + AD595", '3': "Mendel-parts / 4.7k", '1047': "Pt1000 / 4.7k", '1010': "Pt1000 / 1k (non standard)", '20': "PT100 (Ultimainboard V2.x)", '147': "Pt100 / 4.7k", '110': "Pt100 / 1k (non-standard)", '998': "Dummy 1", '999': "Dummy 2" } +#define TEMP_SENSOR_0 -1 +#define TEMP_SENSOR_1 -1 +#define TEMP_SENSOR_2 0 +#define TEMP_SENSOR_3 0 +#define TEMP_SENSOR_BED 0 + +// This makes temp sensor 1 a redundant sensor for sensor 0. If the temperatures difference between these sensors is to high the print will be aborted. +//#define TEMP_SENSOR_1_AS_REDUNDANT +#define MAX_REDUNDANT_TEMP_SENSOR_DIFF 10 + +// Actual temperature must be close to target for this long before M109 returns success +#define TEMP_RESIDENCY_TIME 10 // (seconds) +#define TEMP_HYSTERESIS 3 // (degC) range of +/- temperatures considered "close" to the target one +#define TEMP_WINDOW 1 // (degC) Window around target to start the residency timer x degC early. + +// The minimal temperature defines the temperature below which the heater will not be enabled It is used +// to check that the wiring to the thermistor is not broken. +// Otherwise this would lead to the heater being powered on all the time. +#define HEATER_0_MINTEMP 5 +#define HEATER_1_MINTEMP 5 +#define HEATER_2_MINTEMP 5 +#define HEATER_3_MINTEMP 5 +#define BED_MINTEMP 5 + +// When temperature exceeds max temp, your heater will be switched off. +// This feature exists to protect your hotend from overheating accidentally, but *NOT* from thermistor short/failure! +// You should use MINTEMP for thermistor short/failure protection. +#define HEATER_0_MAXTEMP 275 +#define HEATER_1_MAXTEMP 275 +#define HEATER_2_MAXTEMP 275 +#define HEATER_3_MAXTEMP 275 +#define BED_MAXTEMP 500 + +// If your bed has low resistance e.g. .6 ohm and throws the fuse you can duty cycle it to reduce the +// average current. The value should be an integer and the heat bed will be turned on for 1 interval of +// HEATER_BED_DUTY_CYCLE_DIVIDER intervals. +//#define HEATER_BED_DUTY_CYCLE_DIVIDER 4 + +// If you want the M105 heater power reported in watts, define the BED_WATTS, and (shared for all extruders) EXTRUDER_WATTS +//#define EXTRUDER_WATTS (12.0*12.0/6.7) // P=I^2/R +//#define BED_WATTS (12.0*12.0/1.1) // P=I^2/R + +//=========================================================================== +//============================= PID Settings ================================ +//=========================================================================== +// PID Tuning Guide here: http://reprap.org/wiki/PID_Tuning + +// Comment the following line to disable PID and enable bang-bang. +#define PIDTEMP +#define BANG_MAX 255 // limits current to nozzle while in bang-bang mode; 255=full current +#define PID_MAX BANG_MAX // limits current to nozzle while PID is active (see PID_FUNCTIONAL_RANGE below); 255=full current +#ifdef PIDTEMP + //#define PID_DEBUG // Sends debug data to the serial port. + //#define PID_OPENLOOP 1 // Puts PID in open loop. M104/M140 sets the output power from 0 to PID_MAX + //#define SLOW_PWM_HEATERS // PWM with very low frequency (roughly 0.125Hz=8s) and minimum state time of approximately 1s useful for heaters driven by a relay + //#define PID_PARAMS_PER_EXTRUDER // Uses separate PID parameters for each extruder (useful for mismatched extruders) + // Set/get with gcode: M301 E[extruder number, 0-2] + #define PID_FUNCTIONAL_RANGE 10 // If the temperature difference between the target temperature and the actual temperature + // is more then PID_FUNCTIONAL_RANGE then the PID will be shut off and the heater will be set to min/max. + #define PID_INTEGRAL_DRIVE_MAX PID_MAX //limit for the integral term + #define K1 0.95 //smoothing factor within the PID + +// If you are using a pre-configured hotend then you can use one of the value sets by uncommenting it +// Ultimaker + #define DEFAULT_Kp 22.2 + #define DEFAULT_Ki 1.08 + #define DEFAULT_Kd 114 + +// MakerGear +// #define DEFAULT_Kp 7.0 +// #define DEFAULT_Ki 0.1 +// #define DEFAULT_Kd 12 + +// Mendel Parts V9 on 12V +// #define DEFAULT_Kp 63.0 +// #define DEFAULT_Ki 2.25 +// #define DEFAULT_Kd 440 +#endif // PIDTEMP + +//=========================================================================== +//============================= PID > Bed Temperature Control =============== +//=========================================================================== +// Select PID or bang-bang with PIDTEMPBED. If bang-bang, BED_LIMIT_SWITCHING will enable hysteresis +// +// Uncomment this to enable PID on the bed. It uses the same frequency PWM as the extruder. +// If your PID_dT is the default, and correct for your hardware/configuration, that means 7.689Hz, +// which is fine for driving a square wave into a resistive load and does not significantly impact you FET heating. +// This also works fine on a Fotek SSR-10DA Solid State Relay into a 250W heater. +// If your configuration is significantly different than this and you don't understand the issues involved, you probably +// shouldn't use bed PID until someone else verifies your hardware works. +// If this is enabled, find your own PID constants below. +//#define PIDTEMPBED +// +//#define BED_LIMIT_SWITCHING + +// This sets the max power delivered to the bed, and replaces the HEATER_BED_DUTY_CYCLE_DIVIDER option. +// all forms of bed control obey this (PID, bang-bang, bang-bang with hysteresis) +// setting this to anything other than 255 enables a form of PWM to the bed just like HEATER_BED_DUTY_CYCLE_DIVIDER did, +// so you shouldn't use it unless you are OK with PWM on your bed. (see the comment on enabling PIDTEMPBED) +#define MAX_BED_POWER 255 // limits duty cycle to bed; 255=full current + +//#define PID_BED_DEBUG // Sends debug data to the serial port. + +#ifdef PIDTEMPBED +//120v 250W silicone heater into 4mm borosilicate (MendelMax 1.5+) +//from FOPDT model - kp=.39 Tp=405 Tdead=66, Tc set to 79.2, aggressive factor of .15 (vs .1, 1, 10) + #define DEFAULT_bedKp 10.00 + #define DEFAULT_bedKi .023 + #define DEFAULT_bedKd 305.4 + +//120v 250W silicone heater into 4mm borosilicate (MendelMax 1.5+) +//from pidautotune +// #define DEFAULT_bedKp 97.1 +// #define DEFAULT_bedKi 1.41 +// #define DEFAULT_bedKd 1675.16 + +// FIND YOUR OWN: "M303 E-1 C8 S90" to run autotune on the bed at 90 degreesC for 8 cycles. +#endif // PIDTEMPBED + + +//this prevents dangerous Extruder moves, i.e. if the temperature is under the limit +//can be software-disabled for whatever purposes by +#define PREVENT_DANGEROUS_EXTRUDE +//if PREVENT_DANGEROUS_EXTRUDE is on, you can still disable (uncomment) very long bits of extrusion separately. +#define PREVENT_LENGTHY_EXTRUDE + +#define EXTRUDE_MINTEMP 170 +#define EXTRUDE_MAXLENGTH (X_MAX_LENGTH+Y_MAX_LENGTH) //prevent extrusion of very large distances. + +//=========================================================================== +//============================= Thermal Runaway Protection ================== +//=========================================================================== +/* +This is a feature to protect your printer from burn up in flames if it has +a thermistor coming off place (this happened to a friend of mine recently and +motivated me writing this feature). + +The issue: If a thermistor come off, it will read a lower temperature than actual. +The system will turn the heater on forever, burning up the filament and anything +else around. + +After the temperature reaches the target for the first time, this feature will +start measuring for how long the current temperature stays below the target +minus _HYSTERESIS (set_temperature - THERMAL_RUNAWAY_PROTECTION_HYSTERESIS). + +If it stays longer than _PERIOD, it means the thermistor temperature +cannot catch up with the target, so something *may be* wrong. Then, to be on the +safe side, the system will he halt. + +Bear in mind the count down will just start AFTER the first time the +thermistor temperature is over the target, so you will have no problem if +your extruder heater takes 2 minutes to hit the target on heating. + +*/ +// If you want to enable this feature for all your extruder heaters, +// uncomment the 2 defines below: + +// Parameters for all extruder heaters +//#define THERMAL_RUNAWAY_PROTECTION_PERIOD 40 //in seconds +//#define THERMAL_RUNAWAY_PROTECTION_HYSTERESIS 4 // in degree Celsius + +// If you want to enable this feature for your bed heater, +// uncomment the 2 defines below: + +// Parameters for the bed heater +//#define THERMAL_RUNAWAY_PROTECTION_BED_PERIOD 20 //in seconds +//#define THERMAL_RUNAWAY_PROTECTION_BED_HYSTERESIS 2 // in degree Celsius + + +//=========================================================================== +//============================= Mechanical Settings ========================= +//=========================================================================== + +// Uncomment this option to enable CoreXY kinematics +// #define COREXY + +// Enable this option for Toshiba steppers +// #define CONFIG_STEPPERS_TOSHIBA + +// coarse Endstop Settings +#define ENDSTOPPULLUPS // Comment this out (using // at the start of the line) to disable the endstop pullup resistors + +#ifndef ENDSTOPPULLUPS + // fine endstop settings: Individual pullups. will be ignored if ENDSTOPPULLUPS is defined + // #define ENDSTOPPULLUP_XMAX + // #define ENDSTOPPULLUP_YMAX + // #define ENDSTOPPULLUP_ZMAX + // #define ENDSTOPPULLUP_XMIN + // #define ENDSTOPPULLUP_YMIN + // #define ENDSTOPPULLUP_ZMIN +#endif + +// Mechanical endstop with COM to ground and NC to Signal uses "false" here (most common setup). +const bool X_MIN_ENDSTOP_INVERTING = true; // set to true to invert the logic of the endstop. +const bool Y_MIN_ENDSTOP_INVERTING = true; // set to true to invert the logic of the endstop. +const bool Z_MIN_ENDSTOP_INVERTING = true; // set to true to invert the logic of the endstop. +const bool X_MAX_ENDSTOP_INVERTING = true; // set to true to invert the logic of the endstop. +const bool Y_MAX_ENDSTOP_INVERTING = true; // set to true to invert the logic of the endstop. +const bool Z_MAX_ENDSTOP_INVERTING = true; // set to true to invert the logic of the endstop. +const bool Z_PROBE_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +//#define DISABLE_MAX_ENDSTOPS +#define DISABLE_MIN_ENDSTOPS // Deltas only use min endstops for probing + +// For Inverting Stepper Enable Pins (Active Low) use 0, Non Inverting (Active High) use 1 +#define X_ENABLE_ON 0 +#define Y_ENABLE_ON 0 +#define Z_ENABLE_ON 0 +#define E_ENABLE_ON 0 // For all extruders + +// Disables axis when it's not being used. +#define DISABLE_X false +#define DISABLE_Y false +#define DISABLE_Z false +#define DISABLE_E false // For all extruders +#define DISABLE_INACTIVE_EXTRUDER true //disable only inactive extruders and keep active extruder enabled + +// Invert the stepper direction. Change (or reverse the motor connector) if an axis goes the wrong way. +#define INVERT_X_DIR true // DELTA does not invert +#define INVERT_Y_DIR false +#define INVERT_Z_DIR true +#define INVERT_E0_DIR false +#define INVERT_E1_DIR false +#define INVERT_E2_DIR false +#define INVERT_E3_DIR false + +// ENDSTOP SETTINGS: +// Sets direction of endstops when homing; 1=MAX, -1=MIN +#define X_HOME_DIR 1 // deltas always home to max +#define Y_HOME_DIR 1 +#define Z_HOME_DIR 1 + +#define min_software_endstops true // If true, axis won't move to coordinates less than HOME_POS. +#define max_software_endstops true // If true, axis won't move to coordinates greater than the defined lengths below. + +// Travel limits after homing (units are in mm) +#define X_MIN_POS -DELTA_PRINTABLE_RADIUS +#define Y_MIN_POS -DELTA_PRINTABLE_RADIUS +#define Z_MIN_POS 0 +#define X_MAX_POS DELTA_PRINTABLE_RADIUS +#define Y_MAX_POS DELTA_PRINTABLE_RADIUS +#define Z_MAX_POS MANUAL_Z_HOME_POS + +//=========================================================================== +//============================= Filament Runout Sensor ====================== +//=========================================================================== +//#define FILAMENT_RUNOUT_SENSOR // Uncomment for defining a filament runout sensor such as a mechanical or opto endstop to check the existence of filament + // In RAMPS uses servo pin 2. Can be changed in pins file. For other boards pin definition should be made. + // It is assumed that when logic high = filament available + // when logic low = filament ran out +//const bool FIL_RUNOUT_INVERTING = true; // Should be uncommented and true or false should assigned +//#define ENDSTOPPULLUP_FIL_RUNOUT // Uncomment to use internal pullup for filament runout pins if the sensor is defined. + +//=========================================================================== +//============================ Manual Bed Leveling ========================== +//=========================================================================== + +// #define MANUAL_BED_LEVELING // Add display menu option for bed leveling +// #define MESH_BED_LEVELING // Enable mesh bed leveling + +#ifdef MANUAL_BED_LEVELING + #define MBL_Z_STEP 0.025 +#endif // MANUAL_BED_LEVELING + +#ifdef MESH_BED_LEVELING + #define MESH_MIN_X 10 + #define MESH_MAX_X (X_MAX_POS - MESH_MIN_X) + #define MESH_MIN_Y 10 + #define MESH_MAX_Y (Y_MAX_POS - MESH_MIN_Y) + #define MESH_NUM_X_POINTS 3 // Don't use more than 7 points per axis, implementation limited + #define MESH_NUM_Y_POINTS 3 + #define MESH_HOME_SEARCH_Z 4 // Z after Home, bed somewhere below but above 0.0 +#endif // MESH_BED_LEVELING + +//=========================================================================== +//============================= Bed Auto Leveling =========================== +//=========================================================================== + +//#define ENABLE_AUTO_BED_LEVELING // Delete the comment to enable (remove // at the start of the line) +//#define Z_PROBE_REPEATABILITY_TEST // Z-Probe Repeatability test is not supported in Deltas yet. + +#ifdef ENABLE_AUTO_BED_LEVELING + + // There are 2 different ways to specify probing locations + // + // - "grid" mode + // Probe several points in a rectangular grid. + // You specify the rectangle and the density of sample points. + // This mode is preferred because there are more measurements. + // + // - "3-point" mode + // Probe 3 arbitrary points on the bed (that aren't colinear) + // You specify the XY coordinates of all 3 points. + + // Enable this to sample the bed in a grid (least squares solution) + // Note: this feature generates 10KB extra code size + #define AUTO_BED_LEVELING_GRID // Deltas only support grid mode + + #ifdef AUTO_BED_LEVELING_GRID + + #define DELTA_PROBABLE_RADIUS (DELTA_PRINTABLE_RADIUS - 10) + + #define LEFT_PROBE_BED_POSITION -DELTA_PROBABLE_RADIUS + #define RIGHT_PROBE_BED_POSITION DELTA_PROBABLE_RADIUS + #define FRONT_PROBE_BED_POSITION -DELTA_PROBABLE_RADIUS + #define BACK_PROBE_BED_POSITION DELTA_PROBABLE_RADIUS + + #define MIN_PROBE_EDGE 10 // The probe square sides can be no smaller than this + + // Non-linear bed leveling will be used. + // Compensate by interpolating between the nearest four Z probe values for each point. + // Useful for deltas where the print surface may appear like a bowl or dome shape. + // Works best with ACCURATE_BED_LEVELING_POINTS 5 or higher. + #define AUTO_BED_LEVELING_GRID_POINTS 9 + + #else // !AUTO_BED_LEVELING_GRID + + // Arbitrary points to probe. A simple cross-product + // is used to estimate the plane of the bed. + #define ABL_PROBE_PT_1_X 15 + #define ABL_PROBE_PT_1_Y 180 + #define ABL_PROBE_PT_2_X 15 + #define ABL_PROBE_PT_2_Y 20 + #define ABL_PROBE_PT_3_X 170 + #define ABL_PROBE_PT_3_Y 20 + + #endif // AUTO_BED_LEVELING_GRID + + // Offsets to the probe relative to the extruder tip (Hotend - Probe) + // X and Y offsets must be integers + #define X_PROBE_OFFSET_FROM_EXTRUDER 0 // Probe on: -left +right + #define Y_PROBE_OFFSET_FROM_EXTRUDER -10 // Probe on: -front +behind + #define Z_PROBE_OFFSET_FROM_EXTRUDER -3.5 // -below (always!) + + #define Z_RAISE_BEFORE_HOMING 4 // (in mm) Raise Z before homing (G28) for Probe Clearance. + // Be sure you have this distance over your Z_MAX_POS in case + + #define XY_TRAVEL_SPEED 4000 // X and Y axis travel speed between probes, in mm/min + + #define Z_RAISE_BEFORE_PROBING 15 //How much the extruder will be raised before traveling to the first probing point. + #define Z_RAISE_BETWEEN_PROBINGS 5 //How much the extruder will be raised when traveling from between next probing points + #define Z_RAISE_AFTER_PROBING 50 //How much the extruder will be raised after the last probing point. + +// #define Z_PROBE_END_SCRIPT "G1 Z10 F12000\nG1 X15 Y330\nG1 Z0.5\nG1 Z10" //These commands will be executed in the end of G29 routine. + //Useful to retract a deployable probe. + + //#define Z_PROBE_SLED // turn on if you have a z-probe mounted on a sled like those designed by Charles Bell + //#define SLED_DOCKING_OFFSET 5 // the extra distance the X axis must travel to pickup the sled. 0 should be fine but you can push it further if you'd like. + + // Allen key retractable z-probe as seen on many Kossel delta printers - http://reprap.org/wiki/Kossel#Automatic_bed_leveling_probe + // Deploys by touching z-axis belt. Retracts by pushing the probe down. Uses Z_MIN_PIN. + //#define Z_PROBE_ALLEN_KEY + #ifdef Z_PROBE_ALLEN_KEY + #define Z_PROBE_ALLEN_KEY_DEPLOY_X 30 + #define Z_PROBE_ALLEN_KEY_DEPLOY_Y DELTA_PRINTABLE_RADIUS + #define Z_PROBE_ALLEN_KEY_DEPLOY_Z 100 + + #define Z_PROBE_ALLEN_KEY_STOW_X -64 + #define Z_PROBE_ALLEN_KEY_STOW_Y 56 + #define Z_PROBE_ALLEN_KEY_STOW_Z 23 + #define Z_PROBE_ALLEN_KEY_STOW_DEPTH 20 + #endif + + //If defined, the Probe servo will be turned on only during movement and then turned off to avoid jerk + //The value is the delay to turn the servo off after powered on - depends on the servo speed; 300ms is good value, but you can try lower it. + // You MUST HAVE the SERVO_ENDSTOPS defined to use here a value higher than zero otherwise your code will not compile. + +// #define PROBE_SERVO_DEACTIVATION_DELAY 300 + + +//If you have enabled the Bed Auto Leveling and are using the same Z Probe for Z Homing, +//it is highly recommended you let this Z_SAFE_HOMING enabled!!! + + #define Z_SAFE_HOMING // This feature is meant to avoid Z homing with probe outside the bed area. + // When defined, it will: + // - Allow Z homing only after X and Y homing AND stepper drivers still enabled + // - If stepper drivers timeout, it will need X and Y homing again before Z homing + // - Position the probe in a defined XY point before Z Homing when homing all axis (G28) + // - Block Z homing only when the probe is outside bed area. + + #ifdef Z_SAFE_HOMING + + #define Z_SAFE_HOMING_X_POINT (X_MAX_LENGTH/2) // X point for Z homing when homing all axis (G28) + #define Z_SAFE_HOMING_Y_POINT (Y_MAX_LENGTH/2) // Y point for Z homing when homing all axis (G28) + + #endif + + // Support for a dedicated Z PROBE endstop separate from the Z MIN endstop. + // If you would like to use both a Z PROBE and a Z MIN endstop together or just a Z PROBE with a custom pin, uncomment #define Z_PROBE_ENDSTOP and read the instructions below. + // If you want to still use the Z min endstop for homing, disable Z_SAFE_HOMING above. Eg; to park the head outside the bed area when homing with G28. + // WARNING: The Z MIN endstop will need to set properly as it would without a Z PROBE to prevent head crashes and premature stopping during a print. + // To use a separate Z PROBE endstop, you must have a Z_PROBE_PIN defined in the pins.h file for your control board. + // If you are using a servo based Z PROBE, you will need to enable NUM_SERVOS, SERVO_ENDSTOPS and SERVO_ENDSTOPS_ANGLES in the R/C Servo below. + // RAMPS 1.3/1.4 boards may be able to use the 5V, Ground and the D32 pin in the Aux 4 section of the RAMPS board. Use 5V for powered sensors, otherwise connect to ground and D32 + // for normally closed configuration and 5V and D32 for normally open configurations. Normally closed configuration is advised and assumed. + // The D32 pin in Aux 4 on RAMPS maps to the Arduino D32 pin. Z_PROBE_PIN is setting the pin to use on the Arduino. Since the D32 pin on the RAMPS maps to D32 on Arduino, this works. + // D32 is currently selected in the RAMPS 1.3/1.4 pin file. All other boards will need changes to the respective pins_XXXXX.h file. + // WARNING: Setting the wrong pin may have unexpected and potentially disastrous outcomes. Use with caution and do your homework. + + //#define Z_PROBE_ENDSTOP + +#endif // ENABLE_AUTO_BED_LEVELING + + +// The position of the homing switches +#define MANUAL_HOME_POSITIONS // If defined, MANUAL_*_HOME_POS below will be used +//#define BED_CENTER_AT_0_0 // If defined, the center of the bed is at (X=0, Y=0) + +// Manual homing switch locations: +// For deltabots this means top and center of the Cartesian print volume. +#ifdef MANUAL_HOME_POSITIONS + #define MANUAL_X_HOME_POS 0 + #define MANUAL_Y_HOME_POS 0 + #define MANUAL_Z_HOME_POS 250 // For delta: Distance between nozzle and print surface after homing. +#endif + +/** + * MOVEMENT SETTINGS + */ + + +// delta homing speeds must be the same on xyz +#define HOMING_FEEDRATE {100*60, 100*60, 100*60, 0} // set the homing speeds (mm/min) + +// default settings +// delta speeds must be the same on xyz +#define DEFAULT_AXIS_STEPS_PER_UNIT {80, 80, 80, 760*1.1} // default steps per unit for Kossel (GT2, 20 tooth) +#define DEFAULT_MAX_FEEDRATE {500, 500, 500, 25} // (mm/sec) +#define DEFAULT_MAX_ACCELERATION {9000,9000,9000,10000} // X, Y, Z, E maximum start speed for accelerated moves. E default values are good for skeinforge 40+, for older versions raise them a lot. + +#define DEFAULT_ACCELERATION 3000 // X, Y, Z and E acceleration in mm/s^2 for printing moves +#define DEFAULT_RETRACT_ACCELERATION 3000 // E acceleration in mm/s^2 for retracts +#define DEFAULT_TRAVEL_ACCELERATION 3000 // X, Y, Z acceleration in mm/s^2 for travel (non printing) moves + +// Offset of the extruders (uncomment if using more than one and relying on firmware to position when changing). +// The offset has to be X=0, Y=0 for the extruder 0 hotend (default extruder). +// For the other hotends it is their distance from the extruder 0 hotend. +// #define EXTRUDER_OFFSET_X {0.0, 20.00} // (in mm) for each extruder, offset of the hotend on the X axis +// #define EXTRUDER_OFFSET_Y {0.0, 5.00} // (in mm) for each extruder, offset of the hotend on the Y axis + +// The speed change that does not require acceleration (i.e. the software might assume it can be done instantaneously) +#define DEFAULT_XYJERK 20.0 // (mm/sec) +#define DEFAULT_ZJERK 20.0 // (mm/sec) Must be same as XY for delta +#define DEFAULT_EJERK 5.0 // (mm/sec) + + +//============================================================================= +//============================= Additional Features =========================== +//============================================================================= + +// Custom M code points +#define CUSTOM_M_CODES +#ifdef CUSTOM_M_CODES + #ifdef ENABLE_AUTO_BED_LEVELING + #define CUSTOM_M_CODE_SET_Z_PROBE_OFFSET 851 + #define Z_PROBE_OFFSET_RANGE_MIN -20 + #define Z_PROBE_OFFSET_RANGE_MAX 20 + #endif +#endif + + +// EEPROM +// The microcontroller can store settings in the EEPROM, e.g. max velocity... +// M500 - stores parameters in EEPROM +// M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily). +// M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to. +//define this to enable EEPROM support +//#define EEPROM_SETTINGS + +#ifdef EEPROM_SETTINGS + // To disable EEPROM Serial responses and decrease program space by ~1700 byte: comment this out: + #define EEPROM_CHITCHAT // please keep turned on if you can. +#endif + +// Preheat Constants +#define PLA_PREHEAT_HOTEND_TEMP 180 +#define PLA_PREHEAT_HPB_TEMP 70 +#define PLA_PREHEAT_FAN_SPEED 255 // Insert Value between 0 and 255 + +#define ABS_PREHEAT_HOTEND_TEMP 240 +#define ABS_PREHEAT_HPB_TEMP 100 +#define ABS_PREHEAT_FAN_SPEED 255 // Insert Value between 0 and 255 + +//==============================LCD and SD support============================= + +// Define your display language below. Replace (en) with your language code and uncomment. +// en, pl, fr, de, es, ru, it, pt, pt-br, fi, an, nl, ca, eu, kana, kana_utf8, test +// See also language.h +#define LANGUAGE_INCLUDE GENERATE_LANGUAGE_INCLUDE(en) + +// Choose ONE of these 3 charsets. This has to match your hardware. Ignored for full graphic display. +// To find out what type you have - compile with (test) - upload - click to get the menu. You'll see two typical lines from the upper half of the charset. +// See also documentation/LCDLanguageFont.md + #define DISPLAY_CHARSET_HD44780_JAPAN // this is the most common hardware + //#define DISPLAY_CHARSET_HD44780_WESTERN + //#define DISPLAY_CHARSET_HD44780_CYRILLIC + +//#define ULTRA_LCD //general LCD support, also 16x2 +//#define DOGLCD // Support for SPI LCD 128x64 (Controller ST7565R graphic Display Family) +//#define SDSUPPORT // Enable SD Card Support in Hardware Console +//#define SDSLOW // Use slower SD transfer mode (not normally needed - uncomment if you're getting volume init error) +//#define SD_CHECK_AND_RETRY // Use CRC checks and retries on the SD communication +//#define ENCODER_PULSES_PER_STEP 1 // Increase if you have a high resolution encoder +//#define ENCODER_STEPS_PER_MENU_ITEM 5 // Set according to ENCODER_PULSES_PER_STEP or your liking +//#define ULTIMAKERCONTROLLER //as available from the Ultimaker online store. +//#define ULTIPANEL //the UltiPanel as on Thingiverse +//#define LCD_FEEDBACK_FREQUENCY_HZ 1000 // this is the tone frequency the buzzer plays when on UI feedback. ie Screen Click +//#define LCD_FEEDBACK_FREQUENCY_DURATION_MS 100 // the duration the buzzer plays the UI feedback sound. ie Screen Click + // 0 to disable buzzer feedback + +// PanelOne from T3P3 (via RAMPS 1.4 AUX2/AUX3) +// http://reprap.org/wiki/PanelOne +//#define PANEL_ONE + +// The MaKr3d Makr-Panel with graphic controller and SD support +// http://reprap.org/wiki/MaKr3d_MaKrPanel +//#define MAKRPANEL + +// The Panucatt Devices Viki 2.0 and mini Viki with Graphic LCD +// http://panucatt.com +// ==> REMEMBER TO INSTALL U8glib to your ARDUINO library folder: http://code.google.com/p/u8glib/wiki/u8glib +//#define VIKI2 +//#define miniVIKI + +// The RepRapDiscount Smart Controller (white PCB) +// http://reprap.org/wiki/RepRapDiscount_Smart_Controller +//#define REPRAP_DISCOUNT_SMART_CONTROLLER + +// The GADGETS3D G3D LCD/SD Controller (blue PCB) +// http://reprap.org/wiki/RAMPS_1.3/1.4_GADGETS3D_Shield_with_Panel +//#define G3D_PANEL + +// The RepRapDiscount FULL GRAPHIC Smart Controller (quadratic white PCB) +// http://reprap.org/wiki/RepRapDiscount_Full_Graphic_Smart_Controller +// +// ==> REMEMBER TO INSTALL U8glib to your ARDUINO library folder: http://code.google.com/p/u8glib/wiki/u8glib +//#define REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER + +// The RepRapWorld REPRAPWORLD_KEYPAD v1.1 +// http://reprapworld.com/?products_details&products_id=202&cPath=1591_1626 +//#define REPRAPWORLD_KEYPAD +//#define REPRAPWORLD_KEYPAD_MOVE_STEP 10.0 // how much should be moved when a key is pressed, eg 10.0 means 10mm per click + +// The Elefu RA Board Control Panel +// http://www.elefu.com/index.php?route=product/product&product_id=53 +// REMEMBER TO INSTALL LiquidCrystal_I2C.h in your ARDUINO library folder: https://github.com/kiyoshigawa/LiquidCrystal_I2C +//#define RA_CONTROL_PANEL + +// Delta calibration menu +// uncomment to add three points calibration menu option. +// See http://minow.blogspot.com/index.html#4918805519571907051 +// If needed, adjust the X, Y, Z calibration coordinates +// in ultralcd.cpp@lcd_delta_calibrate_menu() +// #define DELTA_CALIBRATION_MENU + +/** + * I2C Panels + */ + +//#define LCD_I2C_SAINSMART_YWROBOT + +// PANELOLU2 LCD with status LEDs, separate encoder and click inputs +//#define LCD_I2C_PANELOLU2 + +// Panucatt VIKI LCD with status LEDs, integrated click & L/R/U/P buttons, separate encoder inputs +//#define LCD_I2C_VIKI + +// Shift register panels +// --------------------- +// 2 wire Non-latching LCD SR from: +// https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/schematics#!shiftregister-connection + +//#define SAV_3DLCD + +// Increase the FAN pwm frequency. Removes the PWM noise but increases heating in the FET/Arduino +//#define FAST_PWM_FAN + +// Use software PWM to drive the fan, as for the heaters. This uses a very low frequency +// which is not as annoying as with the hardware PWM. On the other hand, if this frequency +// is too low, you should also increment SOFT_PWM_SCALE. +//#define FAN_SOFT_PWM + +// Incrementing this by 1 will double the software PWM frequency, +// affecting heaters, and the fan if FAN_SOFT_PWM is enabled. +// However, control resolution will be halved for each increment; +// at zero value, there are 128 effective control positions. +#define SOFT_PWM_SCALE 0 + +// Temperature status LEDs that display the hotend and bet temperature. +// If all hotends and bed temperature and temperature setpoint are < 54C then the BLUE led is on. +// Otherwise the RED led is on. There is 1C hysteresis. +//#define TEMP_STAT_LEDS + +// M240 Triggers a camera by emulating a Canon RC-1 Remote +// Data from: http://www.doc-diy.net/photo/rc-1_hacked/ +// #define PHOTOGRAPH_PIN 23 + +// SF send wrong arc g-codes when using Arc Point as fillet procedure +//#define SF_ARC_FIX + +// Support for the BariCUDA Paste Extruder. +//#define BARICUDA + +//define BlinkM/CyzRgb Support +//#define BLINKM + +/*********************************************************************\ +* R/C SERVO support +* Sponsored by TrinityLabs, Reworked by codexmas +**********************************************************************/ + +// Number of servos +// +// If you select a configuration below, this will receive a default value and does not need to be set manually +// set it manually if you have more servos than extruders and wish to manually control some +// leaving it undefined or defining as 0 will disable the servo subsystem +// If unsure, leave commented / disabled +// +//#define NUM_SERVOS 3 // Servo index starts with 0 for M280 command + +// Servo Endstops +// +// This allows for servo actuated endstops, primary usage is for the Z Axis to eliminate calibration or bed height changes. +// Use M851 to set the z-probe vertical offset from the nozzle. Store that setting with M500. +// +//#define SERVO_ENDSTOPS {-1, -1, 0} // Servo index for X, Y, Z. Disable with -1 +//#define SERVO_ENDSTOP_ANGLES {0,0, 0,0, 70,0} // X,Y,Z Axis Extend and Retract angles + +/**********************************************************************\ + * Support for a filament diameter sensor + * Also allows adjustment of diameter at print time (vs at slicing) + * Single extruder only at this point (extruder 0) + * + * Motherboards + * 34 - RAMPS1.4 - uses Analog input 5 on the AUX2 connector + * 81 - Printrboard - Uses Analog input 2 on the Exp1 connector (version B,C,D,E) + * 301 - Rambo - uses Analog input 3 + * Note may require analog pins to be defined for different motherboards + **********************************************************************/ +// Uncomment below to enable +//#define FILAMENT_SENSOR + +#define FILAMENT_SENSOR_EXTRUDER_NUM 0 //The number of the extruder that has the filament sensor (0,1,2) +#define MEASUREMENT_DELAY_CM 14 //measurement delay in cm. This is the distance from filament sensor to middle of barrel + +#define DEFAULT_NOMINAL_FILAMENT_DIA 3.0 //Enter the diameter (in mm) of the filament generally used (3.0 mm or 1.75 mm) - this is then used in the slicer software. Used for sensor reading validation +#define MEASURED_UPPER_LIMIT 3.30 //upper limit factor used for sensor reading validation in mm +#define MEASURED_LOWER_LIMIT 1.90 //lower limit factor for sensor reading validation in mm +#define MAX_MEASUREMENT_DELAY 20 //delay buffer size in bytes (1 byte = 1cm)- limits maximum measurement delay allowable (must be larger than MEASUREMENT_DELAY_CM and lower number saves RAM) + +//defines used in the code +#define DEFAULT_MEASURED_FILAMENT_DIA DEFAULT_NOMINAL_FILAMENT_DIA //set measured to nominal initially + +//When using an LCD, uncomment the line below to display the Filament sensor data on the last line instead of status. Status will appear for 5 sec. +//#define FILAMENT_LCD_DISPLAY + + + + + + +#include "Configuration_adv.h" +#include "thermistortables.h" + +#endif //CONFIGURATION_H diff --git a/Marlin/Configuration.h.bak b/Marlin/Configuration.h.bak new file mode 100644 index 0000000..f48646a --- /dev/null +++ b/Marlin/Configuration.h.bak @@ -0,0 +1,817 @@ +#ifndef CONFIGURATION_H +#define CONFIGURATION_H + +#include "boards.h" + +//=========================================================================== +//============================= Getting Started ============================= +//=========================================================================== +/* +Here are some standard links for getting your machine calibrated: + * http://reprap.org/wiki/Calibration + * http://youtu.be/wAL9d7FgInk + * http://calculator.josefprusa.cz + * http://reprap.org/wiki/Triffid_Hunter%27s_Calibration_Guide + * http://www.thingiverse.com/thing:5573 + * https://sites.google.com/site/repraplogphase/calibration-of-your-reprap + * http://www.thingiverse.com/thing:298812 +*/ + +// This configuration file contains the basic settings. +// Advanced settings can be found in Configuration_adv.h +// BASIC SETTINGS: select your board type, temperature sensor type, axis scaling, and endstop configuration + +//=========================================================================== +//============================= DELTA Printer =============================== +//=========================================================================== +// For a Delta printer replace the configuration files with the files in the +// example_configurations/delta directory. +// + +//=========================================================================== +//============================= SCARA Printer =============================== +//=========================================================================== +// For a Scara printer replace the configuration files with the files in the +// example_configurations/SCARA directory. +// + +// @section info + +// User-specified version info of this build to display in [Pronterface, etc] terminal window during +// startup. Implementation of an idea by Prof Braino to inform user that any changes made to this +// build by the user have been successfully uploaded into firmware. +#define STRING_VERSION "1.0.3 dev" +#define STRING_URL "reprap.org" +#define STRING_VERSION_CONFIG_H __DATE__ " " __TIME__ // build date and time +#define STRING_CONFIG_H_AUTHOR "(none, default config)" // Who made the changes. +#define STRING_SPLASH_LINE1 "v" STRING_VERSION // will be shown during bootup in line 1 +//#define STRING_SPLASH_LINE2 STRING_VERSION_CONFIG_H // will be shown during bootup in line2 + +// @section machine + +// SERIAL_PORT selects which serial port should be used for communication with the host. +// This allows the connection of wireless adapters (for instance) to non-default port pins. +// Serial port 0 is still used by the Arduino bootloader regardless of this setting. +// :[0,1,2,3,4,5,6,7] +#define SERIAL_PORT 0 + +// This determines the communication speed of the printer +// :[2400,9600,19200,38400,57600,115200,250000] +#define BAUDRATE 250000 + +// This enables the serial port associated to the Bluetooth interface +//#define BTENABLED // Enable BT interface on AT90USB devices + +// The following define selects which electronics board you have. +// Please choose the name from boards.h that matches your setup +#ifndef MOTHERBOARD + #define MOTHERBOARD BOARD_RAMPS_13_EFB +#endif + +// Optional custom name for your RepStrap or other custom machine +// Displayed in the LCD "Ready" message +// #define CUSTOM_MACHINE_NAME "3D Printer" + +// Define this to set a unique identifier for this printer, (Used by some programs to differentiate between machines) +// You can use an online service to generate a random UUID. (eg http://www.uuidgenerator.net/version4) +// #define MACHINE_UUID "00000000-0000-0000-0000-000000000000" + +// This defines the number of extruders +// :[1,2,3,4] +#define EXTRUDERS 1 + +// Offset of the extruders (uncomment if using more than one and relying on firmware to position when changing). +// The offset has to be X=0, Y=0 for the extruder 0 hotend (default extruder). +// For the other hotends it is their distance from the extruder 0 hotend. +//#define EXTRUDER_OFFSET_X {0.0, 20.00} // (in mm) for each extruder, offset of the hotend on the X axis +//#define EXTRUDER_OFFSET_Y {0.0, 5.00} // (in mm) for each extruder, offset of the hotend on the Y axis + +//// The following define selects which power supply you have. Please choose the one that matches your setup +// 1 = ATX +// 2 = X-Box 360 203Watts (the blue wire connected to PS_ON and the red wire to VCC) +// :{1:'ATX',2:'X-Box 360'} + +#define POWER_SUPPLY 1 + +// Define this to have the electronics keep the power supply off on startup. If you don't know what this is leave it. +// #define PS_DEFAULT_OFF + +// @section temperature + +//=========================================================================== +//============================= Thermal Settings ============================ +//=========================================================================== +// +//--NORMAL IS 4.7kohm PULLUP!-- 1kohm pullup can be used on hotend sensor, using correct resistor and table +// +//// Temperature sensor settings: +// -2 is thermocouple with MAX6675 (only for sensor 0) +// -1 is thermocouple with AD595 +// 0 is not used +// 1 is 100k thermistor - best choice for EPCOS 100k (4.7k pullup) +// 2 is 200k thermistor - ATC Semitec 204GT-2 (4.7k pullup) +// 3 is Mendel-parts thermistor (4.7k pullup) +// 4 is 10k thermistor !! do not use it for a hotend. It gives bad resolution at high temp. !! +// 5 is 100K thermistor - ATC Semitec 104GT-2 (Used in ParCan & J-Head) (4.7k pullup) +// 6 is 100k EPCOS - Not as accurate as table 1 (created using a fluke thermocouple) (4.7k pullup) +// 7 is 100k Honeywell thermistor 135-104LAG-J01 (4.7k pullup) +// 71 is 100k Honeywell thermistor 135-104LAF-J01 (4.7k pullup) +// 8 is 100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) +// 9 is 100k GE Sensing AL03006-58.2K-97-G1 (4.7k pullup) +// 10 is 100k RS thermistor 198-961 (4.7k pullup) +// 11 is 100k beta 3950 1% thermistor (4.7k pullup) +// 12 is 100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) (calibrated for Makibox hot bed) +// 13 is 100k Hisens 3950 1% up to 300°C for hotend "Simple ONE " & "Hotend "All In ONE" +// 20 is the PT100 circuit found in the Ultimainboard V2.x +// 60 is 100k Maker's Tool Works Kapton Bed Thermistor beta=3950 +// +// 1k ohm pullup tables - This is not normal, you would have to have changed out your 4.7k for 1k +// (but gives greater accuracy and more stable PID) +// 51 is 100k thermistor - EPCOS (1k pullup) +// 52 is 200k thermistor - ATC Semitec 204GT-2 (1k pullup) +// 55 is 100k thermistor - ATC Semitec 104GT-2 (Used in ParCan & J-Head) (1k pullup) +// +// 1047 is Pt1000 with 4k7 pullup +// 1010 is Pt1000 with 1k pullup (non standard) +// 147 is Pt100 with 4k7 pullup +// 110 is Pt100 with 1k pullup (non standard) +// 998 and 999 are Dummy Tables. They will ALWAYS read 25°C or the temperature defined below. +// Use it for Testing or Development purposes. NEVER for production machine. +// #define DUMMY_THERMISTOR_998_VALUE 25 +// #define DUMMY_THERMISTOR_999_VALUE 100 +// :{ '0': "Not used", '4': "10k !! do not use for a hotend. Bad resolution at high temp. !!", '1': "100k / 4.7k - EPCOS", '51': "100k / 1k - EPCOS", '6': "100k / 4.7k EPCOS - Not as accurate as Table 1", '5': "100K / 4.7k - ATC Semitec 104GT-2 (Used in ParCan & J-Head)", '7': "100k / 4.7k Honeywell 135-104LAG-J01", '71': "100k / 4.7k Honeywell 135-104LAF-J01", '8': "100k / 4.7k 0603 SMD Vishay NTCS0603E3104FXT", '9': "100k / 4.7k GE Sensing AL03006-58.2K-97-G1", '10': "100k / 4.7k RS 198-961", '11': "100k / 4.7k beta 3950 1%", '12': "100k / 4.7k 0603 SMD Vishay NTCS0603E3104FXT (calibrated for Makibox hot bed)", '13': "100k Hisens 3950 1% up to 300°C for hotend 'Simple ONE ' & hotend 'All In ONE'", '60': "100k Maker's Tool Works Kapton Bed Thermistor beta=3950", '55': "100k / 1k - ATC Semitec 104GT-2 (Used in ParCan & J-Head)", '2': "200k / 4.7k - ATC Semitec 204GT-2", '52': "200k / 1k - ATC Semitec 204GT-2", '-2': "Thermocouple + MAX6675 (only for sensor 0)", '-1': "Thermocouple + AD595", '3': "Mendel-parts / 4.7k", '1047': "Pt1000 / 4.7k", '1010': "Pt1000 / 1k (non standard)", '20': "PT100 (Ultimainboard V2.x)", '147': "Pt100 / 4.7k", '110': "Pt100 / 1k (non-standard)", '998': "Dummy 1", '999': "Dummy 2" } +#define TEMP_SENSOR_0 1 +#define TEMP_SENSOR_1 0 +#define TEMP_SENSOR_2 0 +#define TEMP_SENSOR_3 0 +#define TEMP_SENSOR_BED 0 + +// This makes temp sensor 1 a redundant sensor for sensor 0. If the temperatures difference between these sensors is to high the print will be aborted. +//#define TEMP_SENSOR_1_AS_REDUNDANT +#define MAX_REDUNDANT_TEMP_SENSOR_DIFF 10 + +// Actual temperature must be close to target for this long before M109 returns success +#define TEMP_RESIDENCY_TIME 10 // (seconds) +#define TEMP_HYSTERESIS 3 // (degC) range of +/- temperatures considered "close" to the target one +#define TEMP_WINDOW 1 // (degC) Window around target to start the residency timer x degC early. + +// The minimal temperature defines the temperature below which the heater will not be enabled It is used +// to check that the wiring to the thermistor is not broken. +// Otherwise this would lead to the heater being powered on all the time. +#define HEATER_0_MINTEMP 5 +#define HEATER_1_MINTEMP 5 +#define HEATER_2_MINTEMP 5 +#define HEATER_3_MINTEMP 5 +#define BED_MINTEMP 5 + +// When temperature exceeds max temp, your heater will be switched off. +// This feature exists to protect your hotend from overheating accidentally, but *NOT* from thermistor short/failure! +// You should use MINTEMP for thermistor short/failure protection. +#define HEATER_0_MAXTEMP 275 +#define HEATER_1_MAXTEMP 275 +#define HEATER_2_MAXTEMP 275 +#define HEATER_3_MAXTEMP 275 +#define BED_MAXTEMP 150 + +// If your bed has low resistance e.g. .6 ohm and throws the fuse you can duty cycle it to reduce the +// average current. The value should be an integer and the heat bed will be turned on for 1 interval of +// HEATER_BED_DUTY_CYCLE_DIVIDER intervals. +//#define HEATER_BED_DUTY_CYCLE_DIVIDER 4 + +// If you want the M105 heater power reported in watts, define the BED_WATTS, and (shared for all extruders) EXTRUDER_WATTS +//#define EXTRUDER_WATTS (12.0*12.0/6.7) // P=I^2/R +//#define BED_WATTS (12.0*12.0/1.1) // P=I^2/R + +//=========================================================================== +//============================= PID Settings ================================ +//=========================================================================== +// PID Tuning Guide here: http://reprap.org/wiki/PID_Tuning + +// Comment the following line to disable PID and enable bang-bang. +#define PIDTEMP +#define BANG_MAX 255 // limits current to nozzle while in bang-bang mode; 255=full current +#define PID_MAX BANG_MAX // limits current to nozzle while PID is active (see PID_FUNCTIONAL_RANGE below); 255=full current +#ifdef PIDTEMP + //#define PID_DEBUG // Sends debug data to the serial port. + //#define PID_OPENLOOP 1 // Puts PID in open loop. M104/M140 sets the output power from 0 to PID_MAX + //#define SLOW_PWM_HEATERS // PWM with very low frequency (roughly 0.125Hz=8s) and minimum state time of approximately 1s useful for heaters driven by a relay + //#define PID_PARAMS_PER_EXTRUDER // Uses separate PID parameters for each extruder (useful for mismatched extruders) + // Set/get with gcode: M301 E[extruder number, 0-2] + #define PID_FUNCTIONAL_RANGE 10 // If the temperature difference between the target temperature and the actual temperature + // is more then PID_FUNCTIONAL_RANGE then the PID will be shut off and the heater will be set to min/max. + #define PID_INTEGRAL_DRIVE_MAX PID_MAX //limit for the integral term + #define K1 0.95 //smoothing factor within the PID + +// If you are using a pre-configured hotend then you can use one of the value sets by uncommenting it +// Ultimaker + #define DEFAULT_Kp 22.2 + #define DEFAULT_Ki 1.08 + #define DEFAULT_Kd 114 + +// MakerGear +// #define DEFAULT_Kp 7.0 +// #define DEFAULT_Ki 0.1 +// #define DEFAULT_Kd 12 + +// Mendel Parts V9 on 12V +// #define DEFAULT_Kp 63.0 +// #define DEFAULT_Ki 2.25 +// #define DEFAULT_Kd 440 +#endif // PIDTEMP + +//=========================================================================== +//============================= PID > Bed Temperature Control =============== +//=========================================================================== +// Select PID or bang-bang with PIDTEMPBED. If bang-bang, BED_LIMIT_SWITCHING will enable hysteresis +// +// Uncomment this to enable PID on the bed. It uses the same frequency PWM as the extruder. +// If your PID_dT is the default, and correct for your hardware/configuration, that means 7.689Hz, +// which is fine for driving a square wave into a resistive load and does not significantly impact you FET heating. +// This also works fine on a Fotek SSR-10DA Solid State Relay into a 250W heater. +// If your configuration is significantly different than this and you don't understand the issues involved, you probably +// shouldn't use bed PID until someone else verifies your hardware works. +// If this is enabled, find your own PID constants below. +//#define PIDTEMPBED +// +//#define BED_LIMIT_SWITCHING + +// This sets the max power delivered to the bed, and replaces the HEATER_BED_DUTY_CYCLE_DIVIDER option. +// all forms of bed control obey this (PID, bang-bang, bang-bang with hysteresis) +// setting this to anything other than 255 enables a form of PWM to the bed just like HEATER_BED_DUTY_CYCLE_DIVIDER did, +// so you shouldn't use it unless you are OK with PWM on your bed. (see the comment on enabling PIDTEMPBED) +#define MAX_BED_POWER 255 // limits duty cycle to bed; 255=full current + +//#define PID_BED_DEBUG // Sends debug data to the serial port. + +#ifdef PIDTEMPBED +//120v 250W silicone heater into 4mm borosilicate (MendelMax 1.5+) +//from FOPDT model - kp=.39 Tp=405 Tdead=66, Tc set to 79.2, aggressive factor of .15 (vs .1, 1, 10) + #define DEFAULT_bedKp 10.00 + #define DEFAULT_bedKi .023 + #define DEFAULT_bedKd 305.4 + +//120v 250W silicone heater into 4mm borosilicate (MendelMax 1.5+) +//from pidautotune +// #define DEFAULT_bedKp 97.1 +// #define DEFAULT_bedKi 1.41 +// #define DEFAULT_bedKd 1675.16 + +// FIND YOUR OWN: "M303 E-1 C8 S90" to run autotune on the bed at 90 degreesC for 8 cycles. +#endif // PIDTEMPBED + +// @section extruder + +//this prevents dangerous Extruder moves, i.e. if the temperature is under the limit +//can be software-disabled for whatever purposes by +#define PREVENT_DANGEROUS_EXTRUDE +//if PREVENT_DANGEROUS_EXTRUDE is on, you can still disable (uncomment) very long bits of extrusion separately. +#define PREVENT_LENGTHY_EXTRUDE + +#define EXTRUDE_MINTEMP 170 +#define EXTRUDE_MAXLENGTH (X_MAX_LENGTH+Y_MAX_LENGTH) //prevent extrusion of very large distances. + +//=========================================================================== +//============================= Thermal Runaway Protection ================== +//=========================================================================== +/* +This is a feature to protect your printer from burn up in flames if it has +a thermistor coming off place (this happened to a friend of mine recently and +motivated me writing this feature). + +The issue: If a thermistor come off, it will read a lower temperature than actual. +The system will turn the heater on forever, burning up the filament and anything +else around. + +After the temperature reaches the target for the first time, this feature will +start measuring for how long the current temperature stays below the target +minus _HYSTERESIS (set_temperature - THERMAL_RUNAWAY_PROTECTION_HYSTERESIS). + +If it stays longer than _PERIOD, it means the thermistor temperature +cannot catch up with the target, so something *may be* wrong. Then, to be on the +safe side, the system will he halt. + +Bear in mind the count down will just start AFTER the first time the +thermistor temperature is over the target, so you will have no problem if +your extruder heater takes 2 minutes to hit the target on heating. + +*/ +// If you want to enable this feature for all your extruder heaters, +// uncomment the 2 defines below: + +// Parameters for all extruder heaters +//#define THERMAL_RUNAWAY_PROTECTION_PERIOD 40 //in seconds +//#define THERMAL_RUNAWAY_PROTECTION_HYSTERESIS 4 // in degree Celsius + +// If you want to enable this feature for your bed heater, +// uncomment the 2 defines below: + +// Parameters for the bed heater +//#define THERMAL_RUNAWAY_PROTECTION_BED_PERIOD 20 //in seconds +//#define THERMAL_RUNAWAY_PROTECTION_BED_HYSTERESIS 2 // in degree Celsius + + +//=========================================================================== +//============================= Mechanical Settings ========================= +//=========================================================================== + +// @section machine + +// Uncomment this option to enable CoreXY kinematics +// #define COREXY + +// Enable this option for Toshiba steppers +// #define CONFIG_STEPPERS_TOSHIBA + +// @section homing + +// coarse Endstop Settings +#define ENDSTOPPULLUPS // Comment this out (using // at the start of the line) to disable the endstop pullup resistors + +#ifndef ENDSTOPPULLUPS + // fine endstop settings: Individual pullups. will be ignored if ENDSTOPPULLUPS is defined + // #define ENDSTOPPULLUP_XMAX + // #define ENDSTOPPULLUP_YMAX + // #define ENDSTOPPULLUP_ZMAX + // #define ENDSTOPPULLUP_XMIN + // #define ENDSTOPPULLUP_YMIN + // #define ENDSTOPPULLUP_ZMIN + // #define ENDSTOPPULLUP_ZPROBE +#endif + +// Mechanical endstop with COM to ground and NC to Signal uses "false" here (most common setup). +const bool X_MIN_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Y_MIN_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Z_MIN_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool X_MAX_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Y_MAX_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Z_MAX_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Z_PROBE_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +//#define DISABLE_MAX_ENDSTOPS +//#define DISABLE_MIN_ENDSTOPS + +// @section machine +// If you want to enable the Z Probe pin, but disable its use, uncomment the line below. +// This only affects a Z Probe Endstop if you have separate Z min endstop as well and have +// activated Z_PROBE_ENDSTOP below. If you are using the Z Min endstop on your Z Probe, +// this has no effect. +//#define DISABLE_Z_PROBE_ENDSTOP + +// For Inverting Stepper Enable Pins (Active Low) use 0, Non Inverting (Active High) use 1 +// :{0:'Low',1:'High'} +#define X_ENABLE_ON 0 +#define Y_ENABLE_ON 0 +#define Z_ENABLE_ON 0 +#define E_ENABLE_ON 0 // For all extruders + +// Disables axis when it's not being used. +#define DISABLE_X false +#define DISABLE_Y false +#define DISABLE_Z false + +// @section extruder + +#define DISABLE_E false // For all extruders +#define DISABLE_INACTIVE_EXTRUDER true //disable only inactive extruders and keep active extruder enabled + +// @section machine + +// Invert the stepper direction. Change (or reverse the motor connector) if an axis goes the wrong way. +#define INVERT_X_DIR false +#define INVERT_Y_DIR false +#define INVERT_Z_DIR false + +// @section extruder + +// For direct drive extruder v9 set to true, for geared extruder set to false. +#define INVERT_E0_DIR false +#define INVERT_E1_DIR false +#define INVERT_E2_DIR false +#define INVERT_E3_DIR false + +// @section homing + +// ENDSTOP SETTINGS: +// Sets direction of endstops when homing; 1=MAX, -1=MIN +// :[-1,1] +#define X_HOME_DIR -1 +#define Y_HOME_DIR -1 +#define Z_HOME_DIR -1 + +#define min_software_endstops true // If true, axis won't move to coordinates less than HOME_POS. +#define max_software_endstops true // If true, axis won't move to coordinates greater than the defined lengths below. + +// @section machine + +// Travel limits after homing (units are in mm) +#define X_MIN_POS 0 +#define Y_MIN_POS 0 +#define Z_MIN_POS 0 +#define X_MAX_POS 200 +#define Y_MAX_POS 200 +#define Z_MAX_POS 200 + +//=========================================================================== +//============================= Filament Runout Sensor ====================== +//=========================================================================== +//#define FILAMENT_RUNOUT_SENSOR // Uncomment for defining a filament runout sensor such as a mechanical or opto endstop to check the existence of filament + // In RAMPS uses servo pin 2. Can be changed in pins file. For other boards pin definition should be made. + // It is assumed that when logic high = filament available + // when logic low = filament ran out +//const bool FIL_RUNOUT_INVERTING = true; // Should be uncommented and true or false should assigned +//#define ENDSTOPPULLUP_FIL_RUNOUT // Uncomment to use internal pullup for filament runout pins if the sensor is defined. + +//=========================================================================== +//============================ Mesh Bed Leveling ============================ +//=========================================================================== + +// #define MANUAL_BED_LEVELING // Add display menu option for bed leveling +// #define MESH_BED_LEVELING // Enable mesh bed leveling + +#ifdef MANUAL_BED_LEVELING + #define MBL_Z_STEP 0.025 // Step size while manually probing Z axis +#endif // MANUAL_BED_LEVELING + +#ifdef MESH_BED_LEVELING + #define MESH_MIN_X 10 + #define MESH_MAX_X (X_MAX_POS - MESH_MIN_X) + #define MESH_MIN_Y 10 + #define MESH_MAX_Y (Y_MAX_POS - MESH_MIN_Y) + #define MESH_NUM_X_POINTS 3 // Don't use more than 7 points per axis, implementation limited + #define MESH_NUM_Y_POINTS 3 + #define MESH_HOME_SEARCH_Z 4 // Z after Home, bed somewhere below but above 0.0 +#endif // MESH_BED_LEVELING + +//=========================================================================== +//============================= Bed Auto Leveling =========================== +//=========================================================================== + +// @section bedlevel + +//#define ENABLE_AUTO_BED_LEVELING // Delete the comment to enable (remove // at the start of the line) +#define Z_PROBE_REPEATABILITY_TEST // If not commented out, Z-Probe Repeatability test will be included if Auto Bed Leveling is Enabled. + +#ifdef ENABLE_AUTO_BED_LEVELING + + // There are 2 different ways to specify probing locations + // + // - "grid" mode + // Probe several points in a rectangular grid. + // You specify the rectangle and the density of sample points. + // This mode is preferred because there are more measurements. + // + // - "3-point" mode + // Probe 3 arbitrary points on the bed (that aren't colinear) + // You specify the XY coordinates of all 3 points. + + // Enable this to sample the bed in a grid (least squares solution) + // Note: this feature generates 10KB extra code size + #define AUTO_BED_LEVELING_GRID + + #ifdef AUTO_BED_LEVELING_GRID + + #define LEFT_PROBE_BED_POSITION 15 + #define RIGHT_PROBE_BED_POSITION 170 + #define FRONT_PROBE_BED_POSITION 20 + #define BACK_PROBE_BED_POSITION 170 + + #define MIN_PROBE_EDGE 10 // The probe square sides can be no smaller than this + + // Set the number of grid points per dimension + // You probably don't need more than 3 (squared=9) + #define AUTO_BED_LEVELING_GRID_POINTS 2 + + #else // !AUTO_BED_LEVELING_GRID + + // Arbitrary points to probe. A simple cross-product + // is used to estimate the plane of the bed. + #define ABL_PROBE_PT_1_X 15 + #define ABL_PROBE_PT_1_Y 180 + #define ABL_PROBE_PT_2_X 15 + #define ABL_PROBE_PT_2_Y 20 + #define ABL_PROBE_PT_3_X 170 + #define ABL_PROBE_PT_3_Y 20 + + #endif // AUTO_BED_LEVELING_GRID + + // Offsets to the probe relative to the extruder tip (Hotend - Probe) + // X and Y offsets must be integers + #define X_PROBE_OFFSET_FROM_EXTRUDER -25 // Probe on: -left +right + #define Y_PROBE_OFFSET_FROM_EXTRUDER -29 // Probe on: -front +behind + #define Z_PROBE_OFFSET_FROM_EXTRUDER -12.35 // -below (always!) + + #define Z_RAISE_BEFORE_HOMING 4 // (in mm) Raise Z before homing (G28) for Probe Clearance. + // Be sure you have this distance over your Z_MAX_POS in case + + #define XY_TRAVEL_SPEED 8000 // X and Y axis travel speed between probes, in mm/min + + #define Z_RAISE_BEFORE_PROBING 15 //How much the extruder will be raised before traveling to the first probing point. + #define Z_RAISE_BETWEEN_PROBINGS 5 //How much the extruder will be raised when traveling from between next probing points + #define Z_RAISE_AFTER_PROBING 15 //How much the extruder will be raised after the last probing point. + +// #define Z_PROBE_END_SCRIPT "G1 Z10 F12000\nG1 X15 Y330\nG1 Z0.5\nG1 Z10" //These commands will be executed in the end of G29 routine. + //Useful to retract a deployable probe. + + //#define Z_PROBE_SLED // turn on if you have a z-probe mounted on a sled like those designed by Charles Bell + //#define SLED_DOCKING_OFFSET 5 // the extra distance the X axis must travel to pickup the sled. 0 should be fine but you can push it further if you'd like. + + //If defined, the Probe servo will be turned on only during movement and then turned off to avoid jerk + //The value is the delay to turn the servo off after powered on - depends on the servo speed; 300ms is good value, but you can try lower it. + // You MUST HAVE the SERVO_ENDSTOPS defined to use here a value higher than zero otherwise your code will not compile. + +// #define PROBE_SERVO_DEACTIVATION_DELAY 300 + + +//If you have enabled the Bed Auto Leveling and are using the same Z Probe for Z Homing, +//it is highly recommended you let this Z_SAFE_HOMING enabled!!! + + #define Z_SAFE_HOMING // This feature is meant to avoid Z homing with probe outside the bed area. + // When defined, it will: + // - Allow Z homing only after X and Y homing AND stepper drivers still enabled + // - If stepper drivers timeout, it will need X and Y homing again before Z homing + // - Position the probe in a defined XY point before Z Homing when homing all axis (G28) + // - Block Z homing only when the probe is outside bed area. + + #ifdef Z_SAFE_HOMING + + #define Z_SAFE_HOMING_X_POINT (X_MAX_LENGTH/2) // X point for Z homing when homing all axis (G28) + #define Z_SAFE_HOMING_Y_POINT (Y_MAX_LENGTH/2) // Y point for Z homing when homing all axis (G28) + + #endif + + // Support for a dedicated Z PROBE endstop separate from the Z MIN endstop. + // If you would like to use both a Z PROBE and a Z MIN endstop together or just a Z PROBE with a custom pin, uncomment #define Z_PROBE_ENDSTOP and read the instructions below. + // If you want to still use the Z min endstop for homing, disable Z_SAFE_HOMING above. Eg; to park the head outside the bed area when homing with G28. + // WARNING: The Z MIN endstop will need to set properly as it would without a Z PROBE to prevent head crashes and premature stopping during a print. + // To use a separate Z PROBE endstop, you must have a Z_PROBE_PIN defined in the pins.h file for your control board. + // If you are using a servo based Z PROBE, you will need to enable NUM_SERVOS, SERVO_ENDSTOPS and SERVO_ENDSTOPS_ANGLES in the R/C Servo below. + // RAMPS 1.3/1.4 boards may be able to use the 5V, Ground and the D32 pin in the Aux 4 section of the RAMPS board. Use 5V for powered sensors, otherwise connect to ground and D32 + // for normally closed configuration and 5V and D32 for normally open configurations. Normally closed configuration is advised and assumed. + // The D32 pin in Aux 4 on RAMPS maps to the Arduino D32 pin. Z_PROBE_PIN is setting the pin to use on the Arduino. Since the D32 pin on the RAMPS maps to D32 on Arduino, this works. + // D32 is currently selected in the RAMPS 1.3/1.4 pin file. All other boards will need changes to the respective pins_XXXXX.h file. + // WARNING: Setting the wrong pin may have unexpected and potentially disastrous outcomes. Use with caution and do your homework. + + //#define Z_PROBE_ENDSTOP + +#endif // ENABLE_AUTO_BED_LEVELING + + +// @section homing + +// The position of the homing switches +//#define MANUAL_HOME_POSITIONS // If defined, MANUAL_*_HOME_POS below will be used +//#define BED_CENTER_AT_0_0 // If defined, the center of the bed is at (X=0, Y=0) + +// Manual homing switch locations: +// For deltabots this means top and center of the Cartesian print volume. +#ifdef MANUAL_HOME_POSITIONS + #define MANUAL_X_HOME_POS 0 + #define MANUAL_Y_HOME_POS 0 + #define MANUAL_Z_HOME_POS 0 + //#define MANUAL_Z_HOME_POS 402 // For delta: Distance between nozzle and print surface after homing. +#endif + +// @section movement + +/** + * MOVEMENT SETTINGS + */ + +#define HOMING_FEEDRATE {50*60, 50*60, 4*60, 0} // set the homing speeds (mm/min) + +// default settings + +#define DEFAULT_AXIS_STEPS_PER_UNIT {80,80,4000,500} // default steps per unit for Ultimaker +#define DEFAULT_MAX_FEEDRATE {300, 300, 5, 25} // (mm/sec) +#define DEFAULT_MAX_ACCELERATION {3000,3000,100,10000} // X, Y, Z, E maximum start speed for accelerated moves. E default values are good for Skeinforge 40+, for older versions raise them a lot. + +#define DEFAULT_ACCELERATION 3000 // X, Y, Z and E acceleration in mm/s^2 for printing moves +#define DEFAULT_RETRACT_ACCELERATION 3000 // E acceleration in mm/s^2 for retracts +#define DEFAULT_TRAVEL_ACCELERATION 3000 // X, Y, Z acceleration in mm/s^2 for travel (non printing) moves + +// The speed change that does not require acceleration (i.e. the software might assume it can be done instantaneously) +#define DEFAULT_XYJERK 20.0 // (mm/sec) +#define DEFAULT_ZJERK 0.4 // (mm/sec) +#define DEFAULT_EJERK 5.0 // (mm/sec) + + +//============================================================================= +//============================= Additional Features =========================== +//============================================================================= + +// @section more + +// Custom M code points +#define CUSTOM_M_CODES +#ifdef CUSTOM_M_CODES + #ifdef ENABLE_AUTO_BED_LEVELING + #define CUSTOM_M_CODE_SET_Z_PROBE_OFFSET 851 + #define Z_PROBE_OFFSET_RANGE_MIN -20 + #define Z_PROBE_OFFSET_RANGE_MAX 20 + #endif +#endif + +// @section extras + +// EEPROM +// The microcontroller can store settings in the EEPROM, e.g. max velocity... +// M500 - stores parameters in EEPROM +// M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily). +// M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to. +//define this to enable EEPROM support +//#define EEPROM_SETTINGS + +#ifdef EEPROM_SETTINGS + // To disable EEPROM Serial responses and decrease program space by ~1700 byte: comment this out: + #define EEPROM_CHITCHAT // please keep turned on if you can. +#endif + + +// @section temperature + +// Preheat Constants +#define PLA_PREHEAT_HOTEND_TEMP 180 +#define PLA_PREHEAT_HPB_TEMP 70 +#define PLA_PREHEAT_FAN_SPEED 0 // Insert Value between 0 and 255 + +#define ABS_PREHEAT_HOTEND_TEMP 240 +#define ABS_PREHEAT_HPB_TEMP 110 +#define ABS_PREHEAT_FAN_SPEED 0 // Insert Value between 0 and 255 + +//==============================LCD and SD support============================= +// @section lcd + +// Define your display language below. Replace (en) with your language code and uncomment. +// en, pl, fr, de, es, ru, it, pt, pt-br, fi, an, nl, ca, eu, kana, kana_utf8, test +// See also language.h +#define LANGUAGE_INCLUDE GENERATE_LANGUAGE_INCLUDE(en) + +// Choose ONE of these 3 charsets. This has to match your hardware. Ignored for full graphic display. +// To find out what type you have - compile with (test) - upload - click to get the menu. You'll see two typical lines from the upper half of the charset. +// See also documentation/LCDLanguageFont.md + #define DISPLAY_CHARSET_HD44780_JAPAN // this is the most common hardware + //#define DISPLAY_CHARSET_HD44780_WESTERN + //#define DISPLAY_CHARSET_HD44780_CYRILLIC + +//#define ULTRA_LCD //general LCD support, also 16x2 +//#define DOGLCD // Support for SPI LCD 128x64 (Controller ST7565R graphic Display Family) +//#define SDSUPPORT // Enable SD Card Support in Hardware Console +//#define SDSLOW // Use slower SD transfer mode (not normally needed - uncomment if you're getting volume init error) +//#define SD_CHECK_AND_RETRY // Use CRC checks and retries on the SD communication +//#define ENCODER_PULSES_PER_STEP 1 // Increase if you have a high resolution encoder +//#define ENCODER_STEPS_PER_MENU_ITEM 5 // Set according to ENCODER_PULSES_PER_STEP or your liking +//#define ULTIMAKERCONTROLLER //as available from the Ultimaker online store. +//#define ULTIPANEL //the UltiPanel as on Thingiverse +//#define LCD_FEEDBACK_FREQUENCY_HZ 1000 // this is the tone frequency the buzzer plays when on UI feedback. ie Screen Click +//#define LCD_FEEDBACK_FREQUENCY_DURATION_MS 100 // the duration the buzzer plays the UI feedback sound. ie Screen Click + // 0 to disable buzzer feedback + +// PanelOne from T3P3 (via RAMPS 1.4 AUX2/AUX3) +// http://reprap.org/wiki/PanelOne +//#define PANEL_ONE + +// The MaKr3d Makr-Panel with graphic controller and SD support +// http://reprap.org/wiki/MaKr3d_MaKrPanel +//#define MAKRPANEL + +// The Panucatt Devices Viki 2.0 and mini Viki with Graphic LCD +// http://panucatt.com +// ==> REMEMBER TO INSTALL U8glib to your ARDUINO library folder: http://code.google.com/p/u8glib/wiki/u8glib +//#define VIKI2 +//#define miniVIKI + +// The RepRapDiscount Smart Controller (white PCB) +// http://reprap.org/wiki/RepRapDiscount_Smart_Controller +//#define REPRAP_DISCOUNT_SMART_CONTROLLER + +// The GADGETS3D G3D LCD/SD Controller (blue PCB) +// http://reprap.org/wiki/RAMPS_1.3/1.4_GADGETS3D_Shield_with_Panel +//#define G3D_PANEL + +// The RepRapDiscount FULL GRAPHIC Smart Controller (quadratic white PCB) +// http://reprap.org/wiki/RepRapDiscount_Full_Graphic_Smart_Controller +// +// ==> REMEMBER TO INSTALL U8glib to your ARDUINO library folder: http://code.google.com/p/u8glib/wiki/u8glib +//#define REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER + +// The RepRapWorld REPRAPWORLD_KEYPAD v1.1 +// http://reprapworld.com/?products_details&products_id=202&cPath=1591_1626 +//#define REPRAPWORLD_KEYPAD +//#define REPRAPWORLD_KEYPAD_MOVE_STEP 10.0 // how much should be moved when a key is pressed, eg 10.0 means 10mm per click + +// The Elefu RA Board Control Panel +// http://www.elefu.com/index.php?route=product/product&product_id=53 +// REMEMBER TO INSTALL LiquidCrystal_I2C.h in your ARDUINO library folder: https://github.com/kiyoshigawa/LiquidCrystal_I2C +//#define RA_CONTROL_PANEL + +/** + * I2C Panels + */ + +//#define LCD_I2C_SAINSMART_YWROBOT + +// PANELOLU2 LCD with status LEDs, separate encoder and click inputs +//#define LCD_I2C_PANELOLU2 + +// Panucatt VIKI LCD with status LEDs, integrated click & L/R/U/P buttons, separate encoder inputs +//#define LCD_I2C_VIKI + +// Shift register panels +// --------------------- +// 2 wire Non-latching LCD SR from: +// https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/schematics#!shiftregister-connection + +//#define SAV_3DLCD + +// @section extras + +// Increase the FAN pwm frequency. Removes the PWM noise but increases heating in the FET/Arduino +//#define FAST_PWM_FAN + +// Use software PWM to drive the fan, as for the heaters. This uses a very low frequency +// which is not as annoying as with the hardware PWM. On the other hand, if this frequency +// is too low, you should also increment SOFT_PWM_SCALE. +//#define FAN_SOFT_PWM + +// Incrementing this by 1 will double the software PWM frequency, +// affecting heaters, and the fan if FAN_SOFT_PWM is enabled. +// However, control resolution will be halved for each increment; +// at zero value, there are 128 effective control positions. +#define SOFT_PWM_SCALE 0 + +// Temperature status LEDs that display the hotend and bet temperature. +// If all hotends and bed temperature and temperature setpoint are < 54C then the BLUE led is on. +// Otherwise the RED led is on. There is 1C hysteresis. +//#define TEMP_STAT_LEDS + +// M240 Triggers a camera by emulating a Canon RC-1 Remote +// Data from: http://www.doc-diy.net/photo/rc-1_hacked/ +// #define PHOTOGRAPH_PIN 23 + +// SkeinForge sends the wrong arc g-codes when using Arc Point as fillet procedure +//#define SF_ARC_FIX + +// Support for the BariCUDA Paste Extruder. +//#define BARICUDA + +//define BlinkM/CyzRgb Support +//#define BLINKM + +/*********************************************************************\ +* R/C SERVO support +* Sponsored by TrinityLabs, Reworked by codexmas +**********************************************************************/ + +// Number of servos +// +// If you select a configuration below, this will receive a default value and does not need to be set manually +// set it manually if you have more servos than extruders and wish to manually control some +// leaving it undefined or defining as 0 will disable the servo subsystem +// If unsure, leave commented / disabled +// +//#define NUM_SERVOS 3 // Servo index starts with 0 for M280 command + +// Servo Endstops +// +// This allows for servo actuated endstops, primary usage is for the Z Axis to eliminate calibration or bed height changes. +// Use M851 to set the z-probe vertical offset from the nozzle. Store that setting with M500. +// +//#define SERVO_ENDSTOPS {-1, -1, 0} // Servo index for X, Y, Z. Disable with -1 +//#define SERVO_ENDSTOP_ANGLES {0,0, 0,0, 70,0} // X,Y,Z Axis Extend and Retract angles + +/**********************************************************************\ + * Support for a filament diameter sensor + * Also allows adjustment of diameter at print time (vs at slicing) + * Single extruder only at this point (extruder 0) + * + * Motherboards + * 34 - RAMPS1.4 - uses Analog input 5 on the AUX2 connector + * 81 - Printrboard - Uses Analog input 2 on the Exp1 connector (version B,C,D,E) + * 301 - Rambo - uses Analog input 3 + * Note may require analog pins to be defined for different motherboards + **********************************************************************/ +// Uncomment below to enable +//#define FILAMENT_SENSOR + +#define FILAMENT_SENSOR_EXTRUDER_NUM 0 //The number of the extruder that has the filament sensor (0,1,2) +#define MEASUREMENT_DELAY_CM 14 //measurement delay in cm. This is the distance from filament sensor to middle of barrel + +#define DEFAULT_NOMINAL_FILAMENT_DIA 3.0 //Enter the diameter (in mm) of the filament generally used (3.0 mm or 1.75 mm) - this is then used in the slicer software. Used for sensor reading validation +#define MEASURED_UPPER_LIMIT 3.30 //upper limit factor used for sensor reading validation in mm +#define MEASURED_LOWER_LIMIT 1.90 //lower limit factor for sensor reading validation in mm +#define MAX_MEASUREMENT_DELAY 20 //delay buffer size in bytes (1 byte = 1cm)- limits maximum measurement delay allowable (must be larger than MEASUREMENT_DELAY_CM and lower number saves RAM) + +//defines used in the code +#define DEFAULT_MEASURED_FILAMENT_DIA DEFAULT_NOMINAL_FILAMENT_DIA //set measured to nominal initially + +//When using an LCD, uncomment the line below to display the Filament sensor data on the last line instead of status. Status will appear for 5 sec. +//#define FILAMENT_LCD_DISPLAY + + + + + + +#include "Configuration_adv.h" +#include "thermistortables.h" + +#endif //CONFIGURATION_H diff --git a/Marlin/Configuration.h~ b/Marlin/Configuration.h~ new file mode 100644 index 0000000..eda4241 --- /dev/null +++ b/Marlin/Configuration.h~ @@ -0,0 +1,821 @@ +#ifndef CONFIGURATION_H +#define CONFIGURATION_H + +#include "boards.h" + +//=========================================================================== +//============================= Getting Started ============================= +//=========================================================================== +/* +Here are some standard links for getting your machine calibrated: + * http://reprap.org/wiki/Calibration + * http://youtu.be/wAL9d7FgInk + * http://calculator.josefprusa.cz + * http://reprap.org/wiki/Triffid_Hunter%27s_Calibration_Guide + * http://www.thingiverse.com/thing:5573 + * https://sites.google.com/site/repraplogphase/calibration-of-your-reprap + * http://www.thingiverse.com/thing:298812 +*/ + +// This configuration file contains the basic settings. +// Advanced settings can be found in Configuration_adv.h +// BASIC SETTINGS: select your board type, temperature sensor type, axis scaling, and endstop configuration + +//=========================================================================== +//============================= DELTA Printer =============================== +//=========================================================================== +// For a Delta printer replace the configuration files with the files in the +// example_configurations/delta directory. +// + +//=========================================================================== +//============================= SCARA Printer =============================== +//=========================================================================== +// For a Delta printer replace the configuration files with the files in the +// example_configurations/SCARA directory. +// + +// User-specified version info of this build to display in [Pronterface, etc] terminal window during +// startup. Implementation of an idea by Prof Braino to inform user that any changes made to this +// build by the user have been successfully uploaded into firmware. +#define STRING_VERSION "1.0.3 dev" +#define STRING_URL "reprap.org" +#define STRING_VERSION_CONFIG_H __DATE__ " " __TIME__ // build date and time +#define STRING_CONFIG_H_AUTHOR "(none, default config)" // Who made the changes. +#define STRING_SPLASH_LINE1 "v" STRING_VERSION // will be shown during bootup in line 1 +//#define STRING_SPLASH_LINE2 STRING_VERSION_CONFIG_H // will be shown during bootup in line2 + +// SERIAL_PORT selects which serial port should be used for communication with the host. +// This allows the connection of wireless adapters (for instance) to non-default port pins. +// Serial port 0 is still used by the Arduino bootloader regardless of this setting. +#define SERIAL_PORT 0 + +// This determines the communication speed of the printer +#define BAUDRATE 115200 + +// This enables the serial port associated to the Bluetooth interface +//#define BTENABLED // Enable BT interface on AT90USB devices + +// The following define selects which electronics board you have. +// Please choose the name from boards.h that matches your setup +#ifndef MOTHERBOARD + #define MOTHERBOARD BOARD_RAMPS_13_EFB +#endif + +// Optional custom name for your RepStrap or other custom machine +// Displayed in the LCD "Ready" message +#define CUSTOM_MACHINE_NAME "ReprapJeanne" + +// Define this to set a unique identifier for this printer, (Used by some programs to differentiate between machines) +// You can use an online service to generate a random UUID. (eg http://www.uuidgenerator.net/version4) +// #define MACHINE_UUID "00000000-0000-0000-0000-000000000000" + +// This defines the number of extruders +#define EXTRUDERS 1 + +//// The following define selects which power supply you have. Please choose the one that matches your setup +// 1 = ATX +// 2 = X-Box 360 203Watts (the blue wire connected to PS_ON and the red wire to VCC) + +#define POWER_SUPPLY 1 +// Define this to have the electronics keep the power supply off on startup. If you don't know what this is leave it. +// #define PS_DEFAULT_OFF + +//=========================================================================== +//============================== Delta Settings ============================= +//=========================================================================== +// Enable DELTA kinematics and most of the default configuration for Deltas +#define DELTA + +// Make delta curves from many straight lines (linear interpolation). +// This is a trade-off between visible corners (not enough segments) +// and processor overload (too many expensive sqrt calls). +#define DELTA_SEGMENTS_PER_SECOND 200 + +// NOTE NB all values for DELTA_* values MUST be floating point, so always have a decimal point in them + +// Center-to-center distance of the holes in the diagonal push rods. +#define DELTA_DIAGONAL_ROD 615.0 // mm + +// Horizontal offset from middle of printer to smooth rod center. +#define DELTA_SMOOTH_ROD_OFFSET 315.0 // mm + +// Horizontal offset of the universal joints on the end effector. +#define DELTA_EFFECTOR_OFFSET 33.0 // mm + +// Horizontal offset of the universal joints on the carriages. +#define DELTA_CARRIAGE_OFFSET 18.0 // mm + +// Horizontal distance bridged by diagonal push rods when effector is centered. +#define DELTA_RADIUS (DELTA_SMOOTH_ROD_OFFSET-DELTA_EFFECTOR_OFFSET-DELTA_CARRIAGE_OFFSET) + +// Print surface diameter/2 minus unreachable space (avoid collisions with vertical towers). +#define DELTA_PRINTABLE_RADIUS 300 + + +//=========================================================================== +//============================= Thermal Settings ============================ +//=========================================================================== +// +//--NORMAL IS 4.7kohm PULLUP!-- 1kohm pullup can be used on hotend sensor, using correct resistor and table +// +//// Temperature sensor settings: +// -2 is thermocouple with MAX6675 (only for sensor 0) +// -1 is thermocouple with AD595 +// 0 is not used +// 1 is 100k thermistor - best choice for EPCOS 100k (4.7k pullup) +// 2 is 200k thermistor - ATC Semitec 204GT-2 (4.7k pullup) +// 3 is Mendel-parts thermistor (4.7k pullup) +// 4 is 10k thermistor !! do not use it for a hotend. It gives bad resolution at high temp. !! +// 5 is 100K thermistor - ATC Semitec 104GT-2 (Used in ParCan & J-Head) (4.7k pullup) +// 6 is 100k EPCOS - Not as accurate as table 1 (created using a fluke thermocouple) (4.7k pullup) +// 7 is 100k Honeywell thermistor 135-104LAG-J01 (4.7k pullup) +// 71 is 100k Honeywell thermistor 135-104LAF-J01 (4.7k pullup) +// 8 is 100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) +// 9 is 100k GE Sensing AL03006-58.2K-97-G1 (4.7k pullup) +// 10 is 100k RS thermistor 198-961 (4.7k pullup) +// 11 is 100k beta 3950 1% thermistor (4.7k pullup) +// 12 is 100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) (calibrated for Makibox hot bed) +// 13 is 100k Hisens 3950 1% up to 300°C for hotend "Simple ONE " & "Hotend "All In ONE" +// 20 is the PT100 circuit found in the Ultimainboard V2.x +// 60 is 100k Maker's Tool Works Kapton Bed Thermistor beta=3950 +// +// 1k ohm pullup tables - This is not normal, you would have to have changed out your 4.7k for 1k +// (but gives greater accuracy and more stable PID) +// 51 is 100k thermistor - EPCOS (1k pullup) +// 52 is 200k thermistor - ATC Semitec 204GT-2 (1k pullup) +// 55 is 100k thermistor - ATC Semitec 104GT-2 (Used in ParCan & J-Head) (1k pullup) +// +// 1047 is Pt1000 with 4k7 pullup +// 1010 is Pt1000 with 1k pullup (non standard) +// 147 is Pt100 with 4k7 pullup +// 110 is Pt100 with 1k pullup (non standard) +// 998 and 999 are Dummy Tables. They will ALWAYS read 25°C or the temperature defined below. +// Use it for Testing or Development purposes. NEVER for production machine. +// #define DUMMY_THERMISTOR_998_VALUE 25 +// #define DUMMY_THERMISTOR_999_VALUE 100 +// :{ '0': "Not used", '4': "10k !! do not use for a hotend. Bad resolution at high temp. !!", '1': "100k / 4.7k - EPCOS", '51': "100k / 1k - EPCOS", '6': "100k / 4.7k EPCOS - Not as accurate as Table 1", '5': "100K / 4.7k - ATC Semitec 104GT-2 (Used in ParCan & J-Head)", '7': "100k / 4.7k Honeywell 135-104LAG-J01", '71': "100k / 4.7k Honeywell 135-104LAF-J01", '8': "100k / 4.7k 0603 SMD Vishay NTCS0603E3104FXT", '9': "100k / 4.7k GE Sensing AL03006-58.2K-97-G1", '10': "100k / 4.7k RS 198-961", '11': "100k / 4.7k beta 3950 1%", '12': "100k / 4.7k 0603 SMD Vishay NTCS0603E3104FXT (calibrated for Makibox hot bed)", '13': "100k Hisens 3950 1% up to 300°C for hotend 'Simple ONE ' & hotend 'All In ONE'", '60': "100k Maker's Tool Works Kapton Bed Thermistor beta=3950", '55': "100k / 1k - ATC Semitec 104GT-2 (Used in ParCan & J-Head)", '2': "200k / 4.7k - ATC Semitec 204GT-2", '52': "200k / 1k - ATC Semitec 204GT-2", '-2': "Thermocouple + MAX6675 (only for sensor 0)", '-1': "Thermocouple + AD595", '3': "Mendel-parts / 4.7k", '1047': "Pt1000 / 4.7k", '1010': "Pt1000 / 1k (non standard)", '20': "PT100 (Ultimainboard V2.x)", '147': "Pt100 / 4.7k", '110': "Pt100 / 1k (non-standard)", '998': "Dummy 1", '999': "Dummy 2" } +#define TEMP_SENSOR_0 -1 +#define TEMP_SENSOR_1 -1 +#define TEMP_SENSOR_2 0 +#define TEMP_SENSOR_3 0 +#define TEMP_SENSOR_BED 0 + +// This makes temp sensor 1 a redundant sensor for sensor 0. If the temperatures difference between these sensors is to high the print will be aborted. +//#define TEMP_SENSOR_1_AS_REDUNDANT +#define MAX_REDUNDANT_TEMP_SENSOR_DIFF 10 + +// Actual temperature must be close to target for this long before M109 returns success +#define TEMP_RESIDENCY_TIME 10 // (seconds) +#define TEMP_HYSTERESIS 3 // (degC) range of +/- temperatures considered "close" to the target one +#define TEMP_WINDOW 1 // (degC) Window around target to start the residency timer x degC early. + +// The minimal temperature defines the temperature below which the heater will not be enabled It is used +// to check that the wiring to the thermistor is not broken. +// Otherwise this would lead to the heater being powered on all the time. +#define HEATER_0_MINTEMP 5 +#define HEATER_1_MINTEMP 5 +#define HEATER_2_MINTEMP 5 +#define HEATER_3_MINTEMP 5 +#define BED_MINTEMP 5 + +// When temperature exceeds max temp, your heater will be switched off. +// This feature exists to protect your hotend from overheating accidentally, but *NOT* from thermistor short/failure! +// You should use MINTEMP for thermistor short/failure protection. +#define HEATER_0_MAXTEMP 275 +#define HEATER_1_MAXTEMP 275 +#define HEATER_2_MAXTEMP 275 +#define HEATER_3_MAXTEMP 275 +#define BED_MAXTEMP 150 + +// If your bed has low resistance e.g. .6 ohm and throws the fuse you can duty cycle it to reduce the +// average current. The value should be an integer and the heat bed will be turned on for 1 interval of +// HEATER_BED_DUTY_CYCLE_DIVIDER intervals. +//#define HEATER_BED_DUTY_CYCLE_DIVIDER 4 + +// If you want the M105 heater power reported in watts, define the BED_WATTS, and (shared for all extruders) EXTRUDER_WATTS +//#define EXTRUDER_WATTS (12.0*12.0/6.7) // P=I^2/R +//#define BED_WATTS (12.0*12.0/1.1) // P=I^2/R + +//=========================================================================== +//============================= PID Settings ================================ +//=========================================================================== +// PID Tuning Guide here: http://reprap.org/wiki/PID_Tuning + +// Comment the following line to disable PID and enable bang-bang. +#define PIDTEMP +#define BANG_MAX 255 // limits current to nozzle while in bang-bang mode; 255=full current +#define PID_MAX BANG_MAX // limits current to nozzle while PID is active (see PID_FUNCTIONAL_RANGE below); 255=full current +#ifdef PIDTEMP + //#define PID_DEBUG // Sends debug data to the serial port. + //#define PID_OPENLOOP 1 // Puts PID in open loop. M104/M140 sets the output power from 0 to PID_MAX + //#define SLOW_PWM_HEATERS // PWM with very low frequency (roughly 0.125Hz=8s) and minimum state time of approximately 1s useful for heaters driven by a relay + //#define PID_PARAMS_PER_EXTRUDER // Uses separate PID parameters for each extruder (useful for mismatched extruders) + // Set/get with gcode: M301 E[extruder number, 0-2] + #define PID_FUNCTIONAL_RANGE 10 // If the temperature difference between the target temperature and the actual temperature + // is more then PID_FUNCTIONAL_RANGE then the PID will be shut off and the heater will be set to min/max. + #define PID_INTEGRAL_DRIVE_MAX PID_MAX //limit for the integral term + #define K1 0.95 //smoothing factor within the PID + +// If you are using a pre-configured hotend then you can use one of the value sets by uncommenting it +// Ultimaker + #define DEFAULT_Kp 22.2 + #define DEFAULT_Ki 1.08 + #define DEFAULT_Kd 114 + +// MakerGear +// #define DEFAULT_Kp 7.0 +// #define DEFAULT_Ki 0.1 +// #define DEFAULT_Kd 12 + +// Mendel Parts V9 on 12V +// #define DEFAULT_Kp 63.0 +// #define DEFAULT_Ki 2.25 +// #define DEFAULT_Kd 440 +#endif // PIDTEMP + +//=========================================================================== +//============================= PID > Bed Temperature Control =============== +//=========================================================================== +// Select PID or bang-bang with PIDTEMPBED. If bang-bang, BED_LIMIT_SWITCHING will enable hysteresis +// +// Uncomment this to enable PID on the bed. It uses the same frequency PWM as the extruder. +// If your PID_dT is the default, and correct for your hardware/configuration, that means 7.689Hz, +// which is fine for driving a square wave into a resistive load and does not significantly impact you FET heating. +// This also works fine on a Fotek SSR-10DA Solid State Relay into a 250W heater. +// If your configuration is significantly different than this and you don't understand the issues involved, you probably +// shouldn't use bed PID until someone else verifies your hardware works. +// If this is enabled, find your own PID constants below. +//#define PIDTEMPBED +// +//#define BED_LIMIT_SWITCHING + +// This sets the max power delivered to the bed, and replaces the HEATER_BED_DUTY_CYCLE_DIVIDER option. +// all forms of bed control obey this (PID, bang-bang, bang-bang with hysteresis) +// setting this to anything other than 255 enables a form of PWM to the bed just like HEATER_BED_DUTY_CYCLE_DIVIDER did, +// so you shouldn't use it unless you are OK with PWM on your bed. (see the comment on enabling PIDTEMPBED) +#define MAX_BED_POWER 255 // limits duty cycle to bed; 255=full current + +//#define PID_BED_DEBUG // Sends debug data to the serial port. + +#ifdef PIDTEMPBED +//120v 250W silicone heater into 4mm borosilicate (MendelMax 1.5+) +//from FOPDT model - kp=.39 Tp=405 Tdead=66, Tc set to 79.2, aggressive factor of .15 (vs .1, 1, 10) + #define DEFAULT_bedKp 10.00 + #define DEFAULT_bedKi .023 + #define DEFAULT_bedKd 305.4 + +//120v 250W silicone heater into 4mm borosilicate (MendelMax 1.5+) +//from pidautotune +// #define DEFAULT_bedKp 97.1 +// #define DEFAULT_bedKi 1.41 +// #define DEFAULT_bedKd 1675.16 + +// FIND YOUR OWN: "M303 E-1 C8 S90" to run autotune on the bed at 90 degreesC for 8 cycles. +#endif // PIDTEMPBED + + +//this prevents dangerous Extruder moves, i.e. if the temperature is under the limit +//can be software-disabled for whatever purposes by +#define PREVENT_DANGEROUS_EXTRUDE +//if PREVENT_DANGEROUS_EXTRUDE is on, you can still disable (uncomment) very long bits of extrusion separately. +#define PREVENT_LENGTHY_EXTRUDE + +#define EXTRUDE_MINTEMP 170 +#define EXTRUDE_MAXLENGTH (X_MAX_LENGTH+Y_MAX_LENGTH) //prevent extrusion of very large distances. + +//=========================================================================== +//============================= Thermal Runaway Protection ================== +//=========================================================================== +/* +This is a feature to protect your printer from burn up in flames if it has +a thermistor coming off place (this happened to a friend of mine recently and +motivated me writing this feature). + +The issue: If a thermistor come off, it will read a lower temperature than actual. +The system will turn the heater on forever, burning up the filament and anything +else around. + +After the temperature reaches the target for the first time, this feature will +start measuring for how long the current temperature stays below the target +minus _HYSTERESIS (set_temperature - THERMAL_RUNAWAY_PROTECTION_HYSTERESIS). + +If it stays longer than _PERIOD, it means the thermistor temperature +cannot catch up with the target, so something *may be* wrong. Then, to be on the +safe side, the system will he halt. + +Bear in mind the count down will just start AFTER the first time the +thermistor temperature is over the target, so you will have no problem if +your extruder heater takes 2 minutes to hit the target on heating. + +*/ +// If you want to enable this feature for all your extruder heaters, +// uncomment the 2 defines below: + +// Parameters for all extruder heaters +//#define THERMAL_RUNAWAY_PROTECTION_PERIOD 40 //in seconds +//#define THERMAL_RUNAWAY_PROTECTION_HYSTERESIS 4 // in degree Celsius + +// If you want to enable this feature for your bed heater, +// uncomment the 2 defines below: + +// Parameters for the bed heater +//#define THERMAL_RUNAWAY_PROTECTION_BED_PERIOD 20 //in seconds +//#define THERMAL_RUNAWAY_PROTECTION_BED_HYSTERESIS 2 // in degree Celsius + + +//=========================================================================== +//============================= Mechanical Settings ========================= +//=========================================================================== + +// Uncomment this option to enable CoreXY kinematics +// #define COREXY + +// Enable this option for Toshiba steppers +// #define CONFIG_STEPPERS_TOSHIBA + +// coarse Endstop Settings +#define ENDSTOPPULLUPS // Comment this out (using // at the start of the line) to disable the endstop pullup resistors + +#ifndef ENDSTOPPULLUPS + // fine endstop settings: Individual pullups. will be ignored if ENDSTOPPULLUPS is defined + // #define ENDSTOPPULLUP_XMAX + // #define ENDSTOPPULLUP_YMAX + // #define ENDSTOPPULLUP_ZMAX + // #define ENDSTOPPULLUP_XMIN + // #define ENDSTOPPULLUP_YMIN + // #define ENDSTOPPULLUP_ZMIN +#endif + +// Mechanical endstop with COM to ground and NC to Signal uses "false" here (most common setup). +const bool X_MIN_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Y_MIN_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Z_MIN_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool X_MAX_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Y_MAX_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Z_MAX_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Z_PROBE_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +//#define DISABLE_MAX_ENDSTOPS +#define DISABLE_MIN_ENDSTOPS // Deltas only use min endstops for probing + +// For Inverting Stepper Enable Pins (Active Low) use 0, Non Inverting (Active High) use 1 +#define X_ENABLE_ON 0 +#define Y_ENABLE_ON 0 +#define Z_ENABLE_ON 0 +#define E_ENABLE_ON 0 // For all extruders + +// Disables axis when it's not being used. +#define DISABLE_X false +#define DISABLE_Y false +#define DISABLE_Z false +#define DISABLE_E false // For all extruders +#define DISABLE_INACTIVE_EXTRUDER true //disable only inactive extruders and keep active extruder enabled + +// Invert the stepper direction. Change (or reverse the motor connector) if an axis goes the wrong way. +#define INVERT_X_DIR true // DELTA does not invert +#define INVERT_Y_DIR false +#define INVERT_Z_DIR true +#define INVERT_E0_DIR false +#define INVERT_E1_DIR false +#define INVERT_E2_DIR false +#define INVERT_E3_DIR false + +// ENDSTOP SETTINGS: +// Sets direction of endstops when homing; 1=MAX, -1=MIN +#define X_HOME_DIR 1 // deltas always home to max +#define Y_HOME_DIR 1 +#define Z_HOME_DIR 1 + +#define min_software_endstops true // If true, axis won't move to coordinates less than HOME_POS. +#define max_software_endstops true // If true, axis won't move to coordinates greater than the defined lengths below. + +// Travel limits after homing (units are in mm) +#define X_MIN_POS -DELTA_PRINTABLE_RADIUS +#define Y_MIN_POS -DELTA_PRINTABLE_RADIUS +#define Z_MIN_POS 0 +#define X_MAX_POS DELTA_PRINTABLE_RADIUS +#define Y_MAX_POS DELTA_PRINTABLE_RADIUS +#define Z_MAX_POS MANUAL_Z_HOME_POS + +//=========================================================================== +//============================= Filament Runout Sensor ====================== +//=========================================================================== +//#define FILAMENT_RUNOUT_SENSOR // Uncomment for defining a filament runout sensor such as a mechanical or opto endstop to check the existence of filament + // In RAMPS uses servo pin 2. Can be changed in pins file. For other boards pin definition should be made. + // It is assumed that when logic high = filament available + // when logic low = filament ran out +//const bool FIL_RUNOUT_INVERTING = true; // Should be uncommented and true or false should assigned +//#define ENDSTOPPULLUP_FIL_RUNOUT // Uncomment to use internal pullup for filament runout pins if the sensor is defined. + +//=========================================================================== +//============================ Manual Bed Leveling ========================== +//=========================================================================== + +// #define MANUAL_BED_LEVELING // Add display menu option for bed leveling +// #define MESH_BED_LEVELING // Enable mesh bed leveling + +#ifdef MANUAL_BED_LEVELING + #define MBL_Z_STEP 0.025 +#endif // MANUAL_BED_LEVELING + +#ifdef MESH_BED_LEVELING + #define MESH_MIN_X 10 + #define MESH_MAX_X (X_MAX_POS - MESH_MIN_X) + #define MESH_MIN_Y 10 + #define MESH_MAX_Y (Y_MAX_POS - MESH_MIN_Y) + #define MESH_NUM_X_POINTS 3 // Don't use more than 7 points per axis, implementation limited + #define MESH_NUM_Y_POINTS 3 + #define MESH_HOME_SEARCH_Z 4 // Z after Home, bed somewhere below but above 0.0 +#endif // MESH_BED_LEVELING + +//=========================================================================== +//============================= Bed Auto Leveling =========================== +//=========================================================================== + +//#define ENABLE_AUTO_BED_LEVELING // Delete the comment to enable (remove // at the start of the line) +//#define Z_PROBE_REPEATABILITY_TEST // Z-Probe Repeatability test is not supported in Deltas yet. + +#ifdef ENABLE_AUTO_BED_LEVELING + + // There are 2 different ways to specify probing locations + // + // - "grid" mode + // Probe several points in a rectangular grid. + // You specify the rectangle and the density of sample points. + // This mode is preferred because there are more measurements. + // + // - "3-point" mode + // Probe 3 arbitrary points on the bed (that aren't colinear) + // You specify the XY coordinates of all 3 points. + + // Enable this to sample the bed in a grid (least squares solution) + // Note: this feature generates 10KB extra code size + #define AUTO_BED_LEVELING_GRID // Deltas only support grid mode + + #ifdef AUTO_BED_LEVELING_GRID + + #define DELTA_PROBABLE_RADIUS (DELTA_PRINTABLE_RADIUS - 10) + + #define LEFT_PROBE_BED_POSITION -DELTA_PROBABLE_RADIUS + #define RIGHT_PROBE_BED_POSITION DELTA_PROBABLE_RADIUS + #define FRONT_PROBE_BED_POSITION -DELTA_PROBABLE_RADIUS + #define BACK_PROBE_BED_POSITION DELTA_PROBABLE_RADIUS + + #define MIN_PROBE_EDGE 10 // The probe square sides can be no smaller than this + + // Non-linear bed leveling will be used. + // Compensate by interpolating between the nearest four Z probe values for each point. + // Useful for deltas where the print surface may appear like a bowl or dome shape. + // Works best with ACCURATE_BED_LEVELING_POINTS 5 or higher. + #define AUTO_BED_LEVELING_GRID_POINTS 9 + + #else // !AUTO_BED_LEVELING_GRID + + // Arbitrary points to probe. A simple cross-product + // is used to estimate the plane of the bed. + #define ABL_PROBE_PT_1_X 15 + #define ABL_PROBE_PT_1_Y 180 + #define ABL_PROBE_PT_2_X 15 + #define ABL_PROBE_PT_2_Y 20 + #define ABL_PROBE_PT_3_X 170 + #define ABL_PROBE_PT_3_Y 20 + + #endif // AUTO_BED_LEVELING_GRID + + // Offsets to the probe relative to the extruder tip (Hotend - Probe) + // X and Y offsets must be integers + #define X_PROBE_OFFSET_FROM_EXTRUDER 0 // Probe on: -left +right + #define Y_PROBE_OFFSET_FROM_EXTRUDER -10 // Probe on: -front +behind + #define Z_PROBE_OFFSET_FROM_EXTRUDER -3.5 // -below (always!) + + #define Z_RAISE_BEFORE_HOMING 4 // (in mm) Raise Z before homing (G28) for Probe Clearance. + // Be sure you have this distance over your Z_MAX_POS in case + + #define XY_TRAVEL_SPEED 4000 // X and Y axis travel speed between probes, in mm/min + + #define Z_RAISE_BEFORE_PROBING 15 //How much the extruder will be raised before traveling to the first probing point. + #define Z_RAISE_BETWEEN_PROBINGS 5 //How much the extruder will be raised when traveling from between next probing points + #define Z_RAISE_AFTER_PROBING 50 //How much the extruder will be raised after the last probing point. + +// #define Z_PROBE_END_SCRIPT "G1 Z10 F12000\nG1 X15 Y330\nG1 Z0.5\nG1 Z10" //These commands will be executed in the end of G29 routine. + //Useful to retract a deployable probe. + + //#define Z_PROBE_SLED // turn on if you have a z-probe mounted on a sled like those designed by Charles Bell + //#define SLED_DOCKING_OFFSET 5 // the extra distance the X axis must travel to pickup the sled. 0 should be fine but you can push it further if you'd like. + + // Allen key retractable z-probe as seen on many Kossel delta printers - http://reprap.org/wiki/Kossel#Automatic_bed_leveling_probe + // Deploys by touching z-axis belt. Retracts by pushing the probe down. Uses Z_MIN_PIN. + //#define Z_PROBE_ALLEN_KEY + #ifdef Z_PROBE_ALLEN_KEY + #define Z_PROBE_ALLEN_KEY_DEPLOY_X 30 + #define Z_PROBE_ALLEN_KEY_DEPLOY_Y DELTA_PRINTABLE_RADIUS + #define Z_PROBE_ALLEN_KEY_DEPLOY_Z 100 + + #define Z_PROBE_ALLEN_KEY_STOW_X -64 + #define Z_PROBE_ALLEN_KEY_STOW_Y 56 + #define Z_PROBE_ALLEN_KEY_STOW_Z 23 + #define Z_PROBE_ALLEN_KEY_STOW_DEPTH 20 + #endif + + //If defined, the Probe servo will be turned on only during movement and then turned off to avoid jerk + //The value is the delay to turn the servo off after powered on - depends on the servo speed; 300ms is good value, but you can try lower it. + // You MUST HAVE the SERVO_ENDSTOPS defined to use here a value higher than zero otherwise your code will not compile. + +// #define PROBE_SERVO_DEACTIVATION_DELAY 300 + + +//If you have enabled the Bed Auto Leveling and are using the same Z Probe for Z Homing, +//it is highly recommended you let this Z_SAFE_HOMING enabled!!! + + #define Z_SAFE_HOMING // This feature is meant to avoid Z homing with probe outside the bed area. + // When defined, it will: + // - Allow Z homing only after X and Y homing AND stepper drivers still enabled + // - If stepper drivers timeout, it will need X and Y homing again before Z homing + // - Position the probe in a defined XY point before Z Homing when homing all axis (G28) + // - Block Z homing only when the probe is outside bed area. + + #ifdef Z_SAFE_HOMING + + #define Z_SAFE_HOMING_X_POINT (X_MAX_LENGTH/2) // X point for Z homing when homing all axis (G28) + #define Z_SAFE_HOMING_Y_POINT (Y_MAX_LENGTH/2) // Y point for Z homing when homing all axis (G28) + + #endif + + // Support for a dedicated Z PROBE endstop separate from the Z MIN endstop. + // If you would like to use both a Z PROBE and a Z MIN endstop together or just a Z PROBE with a custom pin, uncomment #define Z_PROBE_ENDSTOP and read the instructions below. + // If you want to still use the Z min endstop for homing, disable Z_SAFE_HOMING above. Eg; to park the head outside the bed area when homing with G28. + // WARNING: The Z MIN endstop will need to set properly as it would without a Z PROBE to prevent head crashes and premature stopping during a print. + // To use a separate Z PROBE endstop, you must have a Z_PROBE_PIN defined in the pins.h file for your control board. + // If you are using a servo based Z PROBE, you will need to enable NUM_SERVOS, SERVO_ENDSTOPS and SERVO_ENDSTOPS_ANGLES in the R/C Servo below. + // RAMPS 1.3/1.4 boards may be able to use the 5V, Ground and the D32 pin in the Aux 4 section of the RAMPS board. Use 5V for powered sensors, otherwise connect to ground and D32 + // for normally closed configuration and 5V and D32 for normally open configurations. Normally closed configuration is advised and assumed. + // The D32 pin in Aux 4 on RAMPS maps to the Arduino D32 pin. Z_PROBE_PIN is setting the pin to use on the Arduino. Since the D32 pin on the RAMPS maps to D32 on Arduino, this works. + // D32 is currently selected in the RAMPS 1.3/1.4 pin file. All other boards will need changes to the respective pins_XXXXX.h file. + // WARNING: Setting the wrong pin may have unexpected and potentially disastrous outcomes. Use with caution and do your homework. + + //#define Z_PROBE_ENDSTOP + +#endif // ENABLE_AUTO_BED_LEVELING + + +// The position of the homing switches +#define MANUAL_HOME_POSITIONS // If defined, MANUAL_*_HOME_POS below will be used +//#define BED_CENTER_AT_0_0 // If defined, the center of the bed is at (X=0, Y=0) + +// Manual homing switch locations: +// For deltabots this means top and center of the Cartesian print volume. +#ifdef MANUAL_HOME_POSITIONS + #define MANUAL_X_HOME_POS 0 + #define MANUAL_Y_HOME_POS 0 + #define MANUAL_Z_HOME_POS 250 // For delta: Distance between nozzle and print surface after homing. +#endif + +/** + * MOVEMENT SETTINGS + */ + + +// delta homing speeds must be the same on xyz +#define HOMING_FEEDRATE {200*60, 200*60, 200*60, 0} // set the homing speeds (mm/min) + +// default settings +// delta speeds must be the same on xyz +#define DEFAULT_AXIS_STEPS_PER_UNIT {80, 80, 80, 760*1.1} // default steps per unit for Kossel (GT2, 20 tooth) +#define DEFAULT_MAX_FEEDRATE {500, 500, 500, 25} // (mm/sec) +#define DEFAULT_MAX_ACCELERATION {9000,9000,9000,10000} // X, Y, Z, E maximum start speed for accelerated moves. E default values are good for skeinforge 40+, for older versions raise them a lot. + +#define DEFAULT_ACCELERATION 3000 // X, Y, Z and E acceleration in mm/s^2 for printing moves +#define DEFAULT_RETRACT_ACCELERATION 3000 // E acceleration in mm/s^2 for retracts +#define DEFAULT_TRAVEL_ACCELERATION 3000 // X, Y, Z acceleration in mm/s^2 for travel (non printing) moves + +// Offset of the extruders (uncomment if using more than one and relying on firmware to position when changing). +// The offset has to be X=0, Y=0 for the extruder 0 hotend (default extruder). +// For the other hotends it is their distance from the extruder 0 hotend. +// #define EXTRUDER_OFFSET_X {0.0, 20.00} // (in mm) for each extruder, offset of the hotend on the X axis +// #define EXTRUDER_OFFSET_Y {0.0, 5.00} // (in mm) for each extruder, offset of the hotend on the Y axis + +// The speed change that does not require acceleration (i.e. the software might assume it can be done instantaneously) +#define DEFAULT_XYJERK 20.0 // (mm/sec) +#define DEFAULT_ZJERK 20.0 // (mm/sec) Must be same as XY for delta +#define DEFAULT_EJERK 5.0 // (mm/sec) + + +//============================================================================= +//============================= Additional Features =========================== +//============================================================================= + +// Custom M code points +#define CUSTOM_M_CODES +#ifdef CUSTOM_M_CODES + #ifdef ENABLE_AUTO_BED_LEVELING + #define CUSTOM_M_CODE_SET_Z_PROBE_OFFSET 851 + #define Z_PROBE_OFFSET_RANGE_MIN -20 + #define Z_PROBE_OFFSET_RANGE_MAX 20 + #endif +#endif + + +// EEPROM +// The microcontroller can store settings in the EEPROM, e.g. max velocity... +// M500 - stores parameters in EEPROM +// M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily). +// M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to. +//define this to enable EEPROM support +//#define EEPROM_SETTINGS + +#ifdef EEPROM_SETTINGS + // To disable EEPROM Serial responses and decrease program space by ~1700 byte: comment this out: + #define EEPROM_CHITCHAT // please keep turned on if you can. +#endif + +// Preheat Constants +#define PLA_PREHEAT_HOTEND_TEMP 180 +#define PLA_PREHEAT_HPB_TEMP 70 +#define PLA_PREHEAT_FAN_SPEED 255 // Insert Value between 0 and 255 + +#define ABS_PREHEAT_HOTEND_TEMP 240 +#define ABS_PREHEAT_HPB_TEMP 100 +#define ABS_PREHEAT_FAN_SPEED 255 // Insert Value between 0 and 255 + +//==============================LCD and SD support============================= + +// Define your display language below. Replace (en) with your language code and uncomment. +// en, pl, fr, de, es, ru, it, pt, pt-br, fi, an, nl, ca, eu, kana, kana_utf8, test +// See also language.h +#define LANGUAGE_INCLUDE GENERATE_LANGUAGE_INCLUDE(en) + +// Choose ONE of these 3 charsets. This has to match your hardware. Ignored for full graphic display. +// To find out what type you have - compile with (test) - upload - click to get the menu. You'll see two typical lines from the upper half of the charset. +// See also documentation/LCDLanguageFont.md + #define DISPLAY_CHARSET_HD44780_JAPAN // this is the most common hardware + //#define DISPLAY_CHARSET_HD44780_WESTERN + //#define DISPLAY_CHARSET_HD44780_CYRILLIC + +//#define ULTRA_LCD //general LCD support, also 16x2 +//#define DOGLCD // Support for SPI LCD 128x64 (Controller ST7565R graphic Display Family) +//#define SDSUPPORT // Enable SD Card Support in Hardware Console +//#define SDSLOW // Use slower SD transfer mode (not normally needed - uncomment if you're getting volume init error) +//#define SD_CHECK_AND_RETRY // Use CRC checks and retries on the SD communication +//#define ENCODER_PULSES_PER_STEP 1 // Increase if you have a high resolution encoder +//#define ENCODER_STEPS_PER_MENU_ITEM 5 // Set according to ENCODER_PULSES_PER_STEP or your liking +//#define ULTIMAKERCONTROLLER //as available from the Ultimaker online store. +//#define ULTIPANEL //the UltiPanel as on Thingiverse +//#define LCD_FEEDBACK_FREQUENCY_HZ 1000 // this is the tone frequency the buzzer plays when on UI feedback. ie Screen Click +//#define LCD_FEEDBACK_FREQUENCY_DURATION_MS 100 // the duration the buzzer plays the UI feedback sound. ie Screen Click + // 0 to disable buzzer feedback + +// PanelOne from T3P3 (via RAMPS 1.4 AUX2/AUX3) +// http://reprap.org/wiki/PanelOne +//#define PANEL_ONE + +// The MaKr3d Makr-Panel with graphic controller and SD support +// http://reprap.org/wiki/MaKr3d_MaKrPanel +//#define MAKRPANEL + +// The Panucatt Devices Viki 2.0 and mini Viki with Graphic LCD +// http://panucatt.com +// ==> REMEMBER TO INSTALL U8glib to your ARDUINO library folder: http://code.google.com/p/u8glib/wiki/u8glib +//#define VIKI2 +//#define miniVIKI + +// The RepRapDiscount Smart Controller (white PCB) +// http://reprap.org/wiki/RepRapDiscount_Smart_Controller +//#define REPRAP_DISCOUNT_SMART_CONTROLLER + +// The GADGETS3D G3D LCD/SD Controller (blue PCB) +// http://reprap.org/wiki/RAMPS_1.3/1.4_GADGETS3D_Shield_with_Panel +//#define G3D_PANEL + +// The RepRapDiscount FULL GRAPHIC Smart Controller (quadratic white PCB) +// http://reprap.org/wiki/RepRapDiscount_Full_Graphic_Smart_Controller +// +// ==> REMEMBER TO INSTALL U8glib to your ARDUINO library folder: http://code.google.com/p/u8glib/wiki/u8glib +//#define REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER + +// The RepRapWorld REPRAPWORLD_KEYPAD v1.1 +// http://reprapworld.com/?products_details&products_id=202&cPath=1591_1626 +//#define REPRAPWORLD_KEYPAD +//#define REPRAPWORLD_KEYPAD_MOVE_STEP 10.0 // how much should be moved when a key is pressed, eg 10.0 means 10mm per click + +// The Elefu RA Board Control Panel +// http://www.elefu.com/index.php?route=product/product&product_id=53 +// REMEMBER TO INSTALL LiquidCrystal_I2C.h in your ARDUINO library folder: https://github.com/kiyoshigawa/LiquidCrystal_I2C +//#define RA_CONTROL_PANEL + +// Delta calibration menu +// uncomment to add three points calibration menu option. +// See http://minow.blogspot.com/index.html#4918805519571907051 +// If needed, adjust the X, Y, Z calibration coordinates +// in ultralcd.cpp@lcd_delta_calibrate_menu() +// #define DELTA_CALIBRATION_MENU + +/** + * I2C Panels + */ + +//#define LCD_I2C_SAINSMART_YWROBOT + +// PANELOLU2 LCD with status LEDs, separate encoder and click inputs +//#define LCD_I2C_PANELOLU2 + +// Panucatt VIKI LCD with status LEDs, integrated click & L/R/U/P buttons, separate encoder inputs +//#define LCD_I2C_VIKI + +// Shift register panels +// --------------------- +// 2 wire Non-latching LCD SR from: +// https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/schematics#!shiftregister-connection + +//#define SAV_3DLCD + +// Increase the FAN pwm frequency. Removes the PWM noise but increases heating in the FET/Arduino +//#define FAST_PWM_FAN + +// Use software PWM to drive the fan, as for the heaters. This uses a very low frequency +// which is not as annoying as with the hardware PWM. On the other hand, if this frequency +// is too low, you should also increment SOFT_PWM_SCALE. +//#define FAN_SOFT_PWM + +// Incrementing this by 1 will double the software PWM frequency, +// affecting heaters, and the fan if FAN_SOFT_PWM is enabled. +// However, control resolution will be halved for each increment; +// at zero value, there are 128 effective control positions. +#define SOFT_PWM_SCALE 0 + +// Temperature status LEDs that display the hotend and bet temperature. +// If all hotends and bed temperature and temperature setpoint are < 54C then the BLUE led is on. +// Otherwise the RED led is on. There is 1C hysteresis. +//#define TEMP_STAT_LEDS + +// M240 Triggers a camera by emulating a Canon RC-1 Remote +// Data from: http://www.doc-diy.net/photo/rc-1_hacked/ +// #define PHOTOGRAPH_PIN 23 + +// SF send wrong arc g-codes when using Arc Point as fillet procedure +//#define SF_ARC_FIX + +// Support for the BariCUDA Paste Extruder. +//#define BARICUDA + +//define BlinkM/CyzRgb Support +//#define BLINKM + +/*********************************************************************\ +* R/C SERVO support +* Sponsored by TrinityLabs, Reworked by codexmas +**********************************************************************/ + +// Number of servos +// +// If you select a configuration below, this will receive a default value and does not need to be set manually +// set it manually if you have more servos than extruders and wish to manually control some +// leaving it undefined or defining as 0 will disable the servo subsystem +// If unsure, leave commented / disabled +// +//#define NUM_SERVOS 3 // Servo index starts with 0 for M280 command + +// Servo Endstops +// +// This allows for servo actuated endstops, primary usage is for the Z Axis to eliminate calibration or bed height changes. +// Use M851 to set the z-probe vertical offset from the nozzle. Store that setting with M500. +// +//#define SERVO_ENDSTOPS {-1, -1, 0} // Servo index for X, Y, Z. Disable with -1 +//#define SERVO_ENDSTOP_ANGLES {0,0, 0,0, 70,0} // X,Y,Z Axis Extend and Retract angles + +/**********************************************************************\ + * Support for a filament diameter sensor + * Also allows adjustment of diameter at print time (vs at slicing) + * Single extruder only at this point (extruder 0) + * + * Motherboards + * 34 - RAMPS1.4 - uses Analog input 5 on the AUX2 connector + * 81 - Printrboard - Uses Analog input 2 on the Exp1 connector (version B,C,D,E) + * 301 - Rambo - uses Analog input 3 + * Note may require analog pins to be defined for different motherboards + **********************************************************************/ +// Uncomment below to enable +//#define FILAMENT_SENSOR + +#define FILAMENT_SENSOR_EXTRUDER_NUM 0 //The number of the extruder that has the filament sensor (0,1,2) +#define MEASUREMENT_DELAY_CM 14 //measurement delay in cm. This is the distance from filament sensor to middle of barrel + +#define DEFAULT_NOMINAL_FILAMENT_DIA 3.0 //Enter the diameter (in mm) of the filament generally used (3.0 mm or 1.75 mm) - this is then used in the slicer software. Used for sensor reading validation +#define MEASURED_UPPER_LIMIT 3.30 //upper limit factor used for sensor reading validation in mm +#define MEASURED_LOWER_LIMIT 1.90 //lower limit factor for sensor reading validation in mm +#define MAX_MEASUREMENT_DELAY 20 //delay buffer size in bytes (1 byte = 1cm)- limits maximum measurement delay allowable (must be larger than MEASUREMENT_DELAY_CM and lower number saves RAM) + +//defines used in the code +#define DEFAULT_MEASURED_FILAMENT_DIA DEFAULT_NOMINAL_FILAMENT_DIA //set measured to nominal initially + +//When using an LCD, uncomment the line below to display the Filament sensor data on the last line instead of status. Status will appear for 5 sec. +//#define FILAMENT_LCD_DISPLAY + + + + + + +#include "Configuration_adv.h" +#include "thermistortables.h" + +#endif //CONFIGURATION_H diff --git a/Marlin/ConfigurationStore.cpp b/Marlin/ConfigurationStore.cpp new file mode 100644 index 0000000..0154691 --- /dev/null +++ b/Marlin/ConfigurationStore.cpp @@ -0,0 +1,810 @@ +/** + * ConfigurationStore.cpp + * + * Configuration 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. + * + */ + +#define EEPROM_VERSION "V19" + +/** + * V19 EEPROM Layout: + * + * ver + * axis_steps_per_unit (x4) + * max_feedrate (x4) + * max_acceleration_units_per_sq_second (x4) + * acceleration + * retract_acceleration + * travel_acceleration + * minimumfeedrate + * mintravelfeedrate + * minsegmenttime + * max_xy_jerk + * max_z_jerk + * max_e_jerk + * home_offset (x3) + * + * Mesh bed leveling: + * active + * mesh_num_x + * mesh_num_y + * z_values[][] + * zprobe_zoffset + * + * DELTA: + * endstop_adj (x3) + * delta_radius + * delta_diagonal_rod + * delta_segments_per_second + * + * ULTIPANEL: + * plaPreheatHotendTemp + * plaPreheatHPBTemp + * plaPreheatFanSpeed + * absPreheatHotendTemp + * absPreheatHPBTemp + * absPreheatFanSpeed + * + * PIDTEMP: + * Kp[0], Ki[0], Kd[0], Kc[0] + * Kp[1], Ki[1], Kd[1], Kc[1] + * Kp[2], Ki[2], Kd[2], Kc[2] + * Kp[3], Ki[3], Kd[3], Kc[3] + * + * PIDTEMPBED: + * bedKp, bedKi, bedKd + * + * DOGLCD: + * lcd_contrast + * + * SCARA: + * axis_scaling (x3) + * + * FWRETRACT: + * autoretract_enabled + * retract_length + * retract_length_swap + * retract_feedrate + * retract_zlift + * retract_recover_length + * retract_recover_length_swap + * retract_recover_feedrate + * + * volumetric_enabled + * + * filament_size (x4) + * + * Z_DUAL_ENDSTOPS + * z_endstop_adj + * + */ +#include "Marlin.h" +#include "language.h" +#include "planner.h" +#include "temperature.h" +#include "ultralcd.h" +#include "ConfigurationStore.h" + +#ifdef MESH_BED_LEVELING + #include "mesh_bed_leveling.h" +#endif // MESH_BED_LEVELING + +void _EEPROM_writeData(int &pos, uint8_t* value, uint8_t size) { + uint8_t c; + while(size--) { + eeprom_write_byte((unsigned char*)pos, *value); + c = eeprom_read_byte((unsigned char*)pos); + if (c != *value) { + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM(MSG_ERR_EEPROM_WRITE); + } + pos++; + value++; + }; +} +void _EEPROM_readData(int &pos, uint8_t* value, uint8_t size) { + do { + *value = eeprom_read_byte((unsigned char*)pos); + pos++; + value++; + } while (--size); +} +#define EEPROM_WRITE_VAR(pos, value) _EEPROM_writeData(pos, (uint8_t*)&value, sizeof(value)) +#define EEPROM_READ_VAR(pos, value) _EEPROM_readData(pos, (uint8_t*)&value, sizeof(value)) + +//====================================================================================== + +#define DUMMY_PID_VALUE 3000.0f + +#define EEPROM_OFFSET 100 + +#ifdef EEPROM_SETTINGS + +void Config_StoreSettings() { + float dummy = 0.0f; + char ver[4] = "000"; + int i = EEPROM_OFFSET; + EEPROM_WRITE_VAR(i, ver); // invalidate data first + EEPROM_WRITE_VAR(i, axis_steps_per_unit); + EEPROM_WRITE_VAR(i, max_feedrate); + EEPROM_WRITE_VAR(i, max_acceleration_units_per_sq_second); + EEPROM_WRITE_VAR(i, acceleration); + EEPROM_WRITE_VAR(i, retract_acceleration); + EEPROM_WRITE_VAR(i, travel_acceleration); + EEPROM_WRITE_VAR(i, minimumfeedrate); + EEPROM_WRITE_VAR(i, mintravelfeedrate); + EEPROM_WRITE_VAR(i, minsegmenttime); + EEPROM_WRITE_VAR(i, max_xy_jerk); + EEPROM_WRITE_VAR(i, max_z_jerk); + EEPROM_WRITE_VAR(i, max_e_jerk); + EEPROM_WRITE_VAR(i, home_offset); + + uint8_t mesh_num_x = 3; + uint8_t mesh_num_y = 3; + #ifdef MESH_BED_LEVELING + // Compile time test that sizeof(mbl.z_values) is as expected + typedef char c_assert[(sizeof(mbl.z_values) == MESH_NUM_X_POINTS*MESH_NUM_Y_POINTS*sizeof(dummy)) ? 1 : -1]; + mesh_num_x = MESH_NUM_X_POINTS; + mesh_num_y = MESH_NUM_Y_POINTS; + EEPROM_WRITE_VAR(i, mbl.active); + EEPROM_WRITE_VAR(i, mesh_num_x); + EEPROM_WRITE_VAR(i, mesh_num_y); + EEPROM_WRITE_VAR(i, mbl.z_values); + #else + uint8_t dummy_uint8 = 0; + EEPROM_WRITE_VAR(i, dummy_uint8); + EEPROM_WRITE_VAR(i, mesh_num_x); + EEPROM_WRITE_VAR(i, mesh_num_y); + dummy = 0.0f; + for (int q=0; q 1 + EEPROM_WRITE_VAR(i, retract_length_swap); + #else + dummy = 0.0f; + EEPROM_WRITE_VAR(i, dummy); + #endif + EEPROM_WRITE_VAR(i, retract_feedrate); + EEPROM_WRITE_VAR(i, retract_zlift); + EEPROM_WRITE_VAR(i, retract_recover_length); + #if EXTRUDERS > 1 + EEPROM_WRITE_VAR(i, retract_recover_length_swap); + #else + dummy = 0.0f; + EEPROM_WRITE_VAR(i, dummy); + #endif + EEPROM_WRITE_VAR(i, retract_recover_feedrate); + #endif // FWRETRACT + + EEPROM_WRITE_VAR(i, volumetric_enabled); + + // Save filament sizes + for (int q = 0; q < 4; q++) { + if (q < EXTRUDERS) dummy = filament_size[q]; + EEPROM_WRITE_VAR(i, dummy); + } + + char ver2[4] = EEPROM_VERSION; + int j = EEPROM_OFFSET; + EEPROM_WRITE_VAR(j, ver2); // validate data + + // Report storage size + SERIAL_ECHO_START; + SERIAL_ECHOPAIR("Settings Stored (", (unsigned long)i); + SERIAL_ECHOLNPGM(" bytes)"); +} + +void Config_RetrieveSettings() { + + int i = EEPROM_OFFSET; + char stored_ver[4]; + char ver[4] = EEPROM_VERSION; + EEPROM_READ_VAR(i, stored_ver); //read stored version + // SERIAL_ECHOLN("Version: [" << ver << "] Stored version: [" << stored_ver << "]"); + + if (strncmp(ver, stored_ver, 3) != 0) { + Config_ResetDefault(); + } + else { + float dummy = 0; + + // version number match + EEPROM_READ_VAR(i, axis_steps_per_unit); + EEPROM_READ_VAR(i, max_feedrate); + EEPROM_READ_VAR(i, max_acceleration_units_per_sq_second); + + // steps per sq second need to be updated to agree with the units per sq second (as they are what is used in the planner) + reset_acceleration_rates(); + + EEPROM_READ_VAR(i, acceleration); + EEPROM_READ_VAR(i, retract_acceleration); + EEPROM_READ_VAR(i, travel_acceleration); + EEPROM_READ_VAR(i, minimumfeedrate); + EEPROM_READ_VAR(i, mintravelfeedrate); + EEPROM_READ_VAR(i, minsegmenttime); + EEPROM_READ_VAR(i, max_xy_jerk); + EEPROM_READ_VAR(i, max_z_jerk); + EEPROM_READ_VAR(i, max_e_jerk); + EEPROM_READ_VAR(i, home_offset); + + uint8_t mesh_num_x = 0; + uint8_t mesh_num_y = 0; + #ifdef MESH_BED_LEVELING + EEPROM_READ_VAR(i, mbl.active); + EEPROM_READ_VAR(i, mesh_num_x); + EEPROM_READ_VAR(i, mesh_num_y); + if (mesh_num_x != MESH_NUM_X_POINTS || + mesh_num_y != MESH_NUM_Y_POINTS) { + mbl.reset(); + for (int q=0; q 1 + EEPROM_READ_VAR(i, retract_length_swap); + #else + EEPROM_READ_VAR(i, dummy); + #endif + EEPROM_READ_VAR(i, retract_feedrate); + EEPROM_READ_VAR(i, retract_zlift); + EEPROM_READ_VAR(i, retract_recover_length); + #if EXTRUDERS > 1 + EEPROM_READ_VAR(i, retract_recover_length_swap); + #else + EEPROM_READ_VAR(i, dummy); + #endif + EEPROM_READ_VAR(i, retract_recover_feedrate); + #endif // FWRETRACT + + EEPROM_READ_VAR(i, volumetric_enabled); + + for (int q = 0; q < 4; q++) { + EEPROM_READ_VAR(i, dummy); + if (q < EXTRUDERS) filament_size[q] = dummy; + } + + calculate_volumetric_multipliers(); + // Call updatePID (similar to when we have processed M301) + updatePID(); + + // Report settings retrieved and length + SERIAL_ECHO_START; + SERIAL_ECHO(ver); + SERIAL_ECHOPAIR(" stored settings retrieved (", (unsigned long)i); + SERIAL_ECHOLNPGM(" bytes)"); + } + + #ifdef EEPROM_CHITCHAT + Config_PrintSettings(); + #endif +} + +#endif // EEPROM_SETTINGS + +void Config_ResetDefault() { + float tmp1[] = DEFAULT_AXIS_STEPS_PER_UNIT; + float tmp2[] = DEFAULT_MAX_FEEDRATE; + long tmp3[] = DEFAULT_MAX_ACCELERATION; + for (uint16_t i = 0; i < NUM_AXIS; i++) { + axis_steps_per_unit[i] = tmp1[i]; + max_feedrate[i] = tmp2[i]; + max_acceleration_units_per_sq_second[i] = tmp3[i]; + #ifdef SCARA + if (i < sizeof(axis_scaling) / sizeof(*axis_scaling)) + axis_scaling[i] = 1; + #endif + } + + // steps per sq second need to be updated to agree with the units per sq second + reset_acceleration_rates(); + + acceleration = DEFAULT_ACCELERATION; + retract_acceleration = DEFAULT_RETRACT_ACCELERATION; + travel_acceleration = DEFAULT_TRAVEL_ACCELERATION; + minimumfeedrate = DEFAULT_MINIMUMFEEDRATE; + minsegmenttime = DEFAULT_MINSEGMENTTIME; + mintravelfeedrate = DEFAULT_MINTRAVELFEEDRATE; + max_xy_jerk = DEFAULT_XYJERK; + max_z_jerk = DEFAULT_ZJERK; + max_e_jerk = DEFAULT_EJERK; + home_offset[X_AXIS] = home_offset[Y_AXIS] = home_offset[Z_AXIS] = 0; + + #ifdef MESH_BED_LEVELING + mbl.active = 0; + #endif + + #ifdef ENABLE_AUTO_BED_LEVELING + zprobe_zoffset = -Z_PROBE_OFFSET_FROM_EXTRUDER; + #endif + + #ifdef DELTA + endstop_adj[X_AXIS] = endstop_adj[Y_AXIS] = endstop_adj[Z_AXIS] = 0; + delta_radius = DELTA_RADIUS; + delta_diagonal_rod = DELTA_DIAGONAL_ROD; + delta_segments_per_second = DELTA_SEGMENTS_PER_SECOND; + recalc_delta_settings(delta_radius, delta_diagonal_rod); + #elif defined(Z_DUAL_ENDSTOPS) + z_endstop_adj = 0; + #endif + + #ifdef ULTIPANEL + plaPreheatHotendTemp = PLA_PREHEAT_HOTEND_TEMP; + plaPreheatHPBTemp = PLA_PREHEAT_HPB_TEMP; + plaPreheatFanSpeed = PLA_PREHEAT_FAN_SPEED; + absPreheatHotendTemp = ABS_PREHEAT_HOTEND_TEMP; + absPreheatHPBTemp = ABS_PREHEAT_HPB_TEMP; + absPreheatFanSpeed = ABS_PREHEAT_FAN_SPEED; + #endif + + #ifdef DOGLCD + lcd_contrast = DEFAULT_LCD_CONTRAST; + #endif + + #ifdef PIDTEMP + #ifdef PID_PARAMS_PER_EXTRUDER + for (int e = 0; e < EXTRUDERS; e++) + #else + int e = 0; // only need to write once + #endif + { + PID_PARAM(Kp, e) = DEFAULT_Kp; + PID_PARAM(Ki, e) = scalePID_i(DEFAULT_Ki); + PID_PARAM(Kd, e) = scalePID_d(DEFAULT_Kd); + #ifdef PID_ADD_EXTRUSION_RATE + PID_PARAM(Kc, e) = DEFAULT_Kc; + #endif + } + // call updatePID (similar to when we have processed M301) + updatePID(); + #endif // PIDTEMP + + #ifdef PIDTEMPBED + bedKp = DEFAULT_bedKp; + bedKi = scalePID_i(DEFAULT_bedKi); + bedKd = scalePID_d(DEFAULT_bedKd); + #endif + + #ifdef FWRETRACT + autoretract_enabled = false; + retract_length = RETRACT_LENGTH; + #if EXTRUDERS > 1 + retract_length_swap = RETRACT_LENGTH_SWAP; + #endif + retract_feedrate = RETRACT_FEEDRATE; + retract_zlift = RETRACT_ZLIFT; + retract_recover_length = RETRACT_RECOVER_LENGTH; + #if EXTRUDERS > 1 + retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP; + #endif + retract_recover_feedrate = RETRACT_RECOVER_FEEDRATE; + #endif + + volumetric_enabled = false; + filament_size[0] = DEFAULT_NOMINAL_FILAMENT_DIA; + #if EXTRUDERS > 1 + filament_size[1] = DEFAULT_NOMINAL_FILAMENT_DIA; + #if EXTRUDERS > 2 + filament_size[2] = DEFAULT_NOMINAL_FILAMENT_DIA; + #if EXTRUDERS > 3 + filament_size[3] = DEFAULT_NOMINAL_FILAMENT_DIA; + #endif + #endif + #endif + calculate_volumetric_multipliers(); + + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM("Hardcoded Default Settings Loaded"); +} + +#ifndef DISABLE_M503 + +void Config_PrintSettings(bool forReplay) { + // Always have this function, even with EEPROM_SETTINGS disabled, the current values will be shown + + SERIAL_ECHO_START; + + if (!forReplay) { + SERIAL_ECHOLNPGM("Steps per unit:"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M92 X", axis_steps_per_unit[X_AXIS]); + SERIAL_ECHOPAIR(" Y", axis_steps_per_unit[Y_AXIS]); + SERIAL_ECHOPAIR(" Z", axis_steps_per_unit[Z_AXIS]); + SERIAL_ECHOPAIR(" E", axis_steps_per_unit[E_AXIS]); + SERIAL_EOL; + + SERIAL_ECHO_START; + + #ifdef SCARA + if (!forReplay) { + SERIAL_ECHOLNPGM("Scaling factors:"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M365 X", axis_scaling[X_AXIS]); + SERIAL_ECHOPAIR(" Y", axis_scaling[Y_AXIS]); + SERIAL_ECHOPAIR(" Z", axis_scaling[Z_AXIS]); + SERIAL_EOL; + SERIAL_ECHO_START; + #endif // SCARA + + if (!forReplay) { + SERIAL_ECHOLNPGM("Maximum feedrates (mm/s):"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M203 X", max_feedrate[X_AXIS]); + SERIAL_ECHOPAIR(" Y", max_feedrate[Y_AXIS]); + SERIAL_ECHOPAIR(" Z", max_feedrate[Z_AXIS]); + SERIAL_ECHOPAIR(" E", max_feedrate[E_AXIS]); + SERIAL_EOL; + + SERIAL_ECHO_START; + if (!forReplay) { + SERIAL_ECHOLNPGM("Maximum Acceleration (mm/s2):"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M201 X", max_acceleration_units_per_sq_second[X_AXIS] ); + SERIAL_ECHOPAIR(" Y", max_acceleration_units_per_sq_second[Y_AXIS] ); + SERIAL_ECHOPAIR(" Z", max_acceleration_units_per_sq_second[Z_AXIS] ); + SERIAL_ECHOPAIR(" E", max_acceleration_units_per_sq_second[E_AXIS]); + SERIAL_EOL; + SERIAL_ECHO_START; + if (!forReplay) { + SERIAL_ECHOLNPGM("Accelerations: P=printing, R=retract and T=travel"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M204 P", acceleration ); + SERIAL_ECHOPAIR(" R", retract_acceleration); + SERIAL_ECHOPAIR(" T", travel_acceleration); + SERIAL_EOL; + + SERIAL_ECHO_START; + if (!forReplay) { + SERIAL_ECHOLNPGM("Advanced variables: S=Min feedrate (mm/s), T=Min travel feedrate (mm/s), B=minimum segment time (ms), X=maximum XY jerk (mm/s), Z=maximum Z jerk (mm/s), E=maximum E jerk (mm/s)"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M205 S", minimumfeedrate ); + SERIAL_ECHOPAIR(" T", mintravelfeedrate ); + SERIAL_ECHOPAIR(" B", minsegmenttime ); + SERIAL_ECHOPAIR(" X", max_xy_jerk ); + SERIAL_ECHOPAIR(" Z", max_z_jerk); + SERIAL_ECHOPAIR(" E", max_e_jerk); + SERIAL_EOL; + + SERIAL_ECHO_START; + if (!forReplay) { + SERIAL_ECHOLNPGM("Home offset (mm):"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M206 X", home_offset[X_AXIS] ); + SERIAL_ECHOPAIR(" Y", home_offset[Y_AXIS] ); + SERIAL_ECHOPAIR(" Z", home_offset[Z_AXIS] ); + SERIAL_EOL; + + #ifdef DELTA + SERIAL_ECHO_START; + if (!forReplay) { + SERIAL_ECHOLNPGM("Endstop adjustment (mm):"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M666 X", endstop_adj[X_AXIS] ); + SERIAL_ECHOPAIR(" Y", endstop_adj[Y_AXIS] ); + SERIAL_ECHOPAIR(" Z", endstop_adj[Z_AXIS] ); + SERIAL_EOL; + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM("Delta settings: L=delta_diagonal_rod, R=delta_radius, S=delta_segments_per_second"); + SERIAL_ECHO_START; + SERIAL_ECHOPAIR(" M665 L", delta_diagonal_rod ); + SERIAL_ECHOPAIR(" R", delta_radius ); + SERIAL_ECHOPAIR(" S", delta_segments_per_second ); + SERIAL_EOL; + #elif defined(Z_DUAL_ENDSTOPS) + SERIAL_ECHO_START; + if (!forReplay) { + SERIAL_ECHOLNPGM("Z2 Endstop adjustment (mm):"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M666 Z", z_endstop_adj ); + SERIAL_EOL; + #endif // DELTA + + #if defined(PIDTEMP) || defined(PIDTEMPBED) + SERIAL_ECHO_START; + if (!forReplay) { + SERIAL_ECHOLNPGM("PID settings:"); + SERIAL_ECHO_START; + } + #if defined(PIDTEMP) && defined(PIDTEMPBED) + SERIAL_EOL; + #endif + #ifdef PIDTEMP + SERIAL_ECHOPAIR(" M301 P", PID_PARAM(Kp, 0)); // for compatibility with hosts, only echos values for E0 + SERIAL_ECHOPAIR(" I", unscalePID_i(PID_PARAM(Ki, 0))); + SERIAL_ECHOPAIR(" D", unscalePID_d(PID_PARAM(Kd, 0))); + SERIAL_EOL; + #endif + #ifdef PIDTEMPBED + SERIAL_ECHOPAIR(" M304 P", bedKp); // for compatibility with hosts, only echos values for E0 + SERIAL_ECHOPAIR(" I", unscalePID_i(bedKi)); + SERIAL_ECHOPAIR(" D", unscalePID_d(bedKd)); + SERIAL_EOL; + #endif + #endif + + #ifdef FWRETRACT + + SERIAL_ECHO_START; + if (!forReplay) { + SERIAL_ECHOLNPGM("Retract: S=Length (mm) F:Speed (mm/m) Z: ZLift (mm)"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M207 S", retract_length); + SERIAL_ECHOPAIR(" F", retract_feedrate*60); + SERIAL_ECHOPAIR(" Z", retract_zlift); + SERIAL_EOL; + SERIAL_ECHO_START; + if (!forReplay) { + SERIAL_ECHOLNPGM("Recover: S=Extra length (mm) F:Speed (mm/m)"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M208 S", retract_recover_length); + SERIAL_ECHOPAIR(" F", retract_recover_feedrate*60); + SERIAL_EOL; + SERIAL_ECHO_START; + if (!forReplay) { + SERIAL_ECHOLNPGM("Auto-Retract: S=0 to disable, 1 to interpret extrude-only moves as retracts or recoveries"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M209 S", (unsigned long)(autoretract_enabled ? 1 : 0)); + SERIAL_EOL; + + #if EXTRUDERS > 1 + if (!forReplay) { + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM("Multi-extruder settings:"); + SERIAL_ECHO_START; + SERIAL_ECHOPAIR(" Swap retract length (mm): ", retract_length_swap); + SERIAL_EOL; + SERIAL_ECHO_START; + SERIAL_ECHOPAIR(" Swap rec. addl. length (mm): ", retract_recover_length_swap); + SERIAL_EOL; + } + #endif // EXTRUDERS > 1 + + #endif // FWRETRACT + + SERIAL_ECHO_START; + if (volumetric_enabled) { + if (!forReplay) { + SERIAL_ECHOLNPGM("Filament settings:"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M200 D", filament_size[0]); + SERIAL_EOL; + + #if EXTRUDERS > 1 + SERIAL_ECHO_START; + SERIAL_ECHOPAIR(" M200 T1 D", filament_size[1]); + SERIAL_EOL; + #if EXTRUDERS > 2 + SERIAL_ECHO_START; + SERIAL_ECHOPAIR(" M200 T2 D", filament_size[2]); + SERIAL_EOL; + #if EXTRUDERS > 3 + SERIAL_ECHO_START; + SERIAL_ECHOPAIR(" M200 T3 D", filament_size[3]); + SERIAL_EOL; + #endif + #endif + #endif + + } else { + if (!forReplay) { + SERIAL_ECHOLNPGM("Filament settings: Disabled"); + } + } + + #ifdef ENABLE_AUTO_BED_LEVELING + SERIAL_ECHO_START; + #ifdef CUSTOM_M_CODES + if (!forReplay) { + SERIAL_ECHOLNPGM("Z-Probe Offset (mm):"); + SERIAL_ECHO_START; + } + SERIAL_ECHOPAIR(" M", (unsigned long)CUSTOM_M_CODE_SET_Z_PROBE_OFFSET); + SERIAL_ECHOPAIR(" Z", -zprobe_zoffset); + #else + if (!forReplay) { + SERIAL_ECHOPAIR("Z-Probe Offset (mm):", -zprobe_zoffset); + } + #endif + SERIAL_EOL; + #endif +} + +#endif // !DISABLE_M503 diff --git a/Marlin/ConfigurationStore.h b/Marlin/ConfigurationStore.h new file mode 100644 index 0000000..3dc4a92 --- /dev/null +++ b/Marlin/ConfigurationStore.h @@ -0,0 +1,22 @@ +#ifndef CONFIGURATIONSTORE_H +#define CONFIGURATIONSTORE_H + +#include "Configuration.h" + +void Config_ResetDefault(); + +#ifndef DISABLE_M503 + void Config_PrintSettings(bool forReplay=false); +#else + FORCE_INLINE void Config_PrintSettings(bool forReplay=false) {} +#endif + +#ifdef EEPROM_SETTINGS + void Config_StoreSettings(); + void Config_RetrieveSettings(); +#else + FORCE_INLINE void Config_StoreSettings() {} + FORCE_INLINE void Config_RetrieveSettings() { Config_ResetDefault(); Config_PrintSettings(); } +#endif + +#endif //CONFIGURATIONSTORE_H diff --git a/Marlin/Configuration_adv.h b/Marlin/Configuration_adv.h new file mode 100644 index 0000000..88b76c6 --- /dev/null +++ b/Marlin/Configuration_adv.h @@ -0,0 +1,550 @@ +#ifndef CONFIGURATION_ADV_H +#define CONFIGURATION_ADV_H + +#include "Conditionals.h" + +// @section temperature + +//=========================================================================== +//=============================Thermal Settings ============================ +//=========================================================================== + +#ifdef BED_LIMIT_SWITCHING + #define BED_HYSTERESIS 2 //only disable heating if T>target+BED_HYSTERESIS and enable heating if T>target-BED_HYSTERESIS +#endif +#define BED_CHECK_INTERVAL 5000 //ms between checks in bang-bang control + +//// Heating sanity check: +// This waits for the watch period in milliseconds whenever an M104 or M109 increases the target temperature +// If the temperature has not increased at the end of that period, the target temperature is set to zero. +// It can be reset with another M104/M109. This check is also only triggered if the target temperature and the current temperature +// differ by at least 2x WATCH_TEMP_INCREASE +//#define WATCH_TEMP_PERIOD 40000 //40 seconds +//#define WATCH_TEMP_INCREASE 10 //Heat up at least 10 degree in 20 seconds + +#ifdef PIDTEMP + // this adds an experimental additional term to the heating power, proportional to the extrusion speed. + // if Kc is chosen well, the additional required power due to increased melting should be compensated. + #define PID_ADD_EXTRUSION_RATE + #ifdef PID_ADD_EXTRUSION_RATE + #define DEFAULT_Kc (1) //heating power=Kc*(e_speed) + #endif +#endif + + +//automatic temperature: The hot end target temperature is calculated by all the buffered lines of gcode. +//The maximum buffered steps/sec of the extruder motor are called "se". +//You enter the autotemp mode by a M109 S B F +// the target temperature is set to mintemp+factor*se[steps/sec] and limited by mintemp and maxtemp +// you exit the value by any M109 without F* +// Also, if the temperature is set to a value Z2 (yes, it is.. think about it) and the Z adjust would be positive. + // Play a little bit with small adjustments (0.5mm) and check the behaviour. + // The M119 (endstops report) will start reporting the Z2 Endstop as well. + + #define Z_DUAL_ENDSTOPS + + #ifdef Z_DUAL_ENDSTOPS + #define Z2_STEP_PIN E2_STEP_PIN // Stepper to be used to Z2 axis. + #define Z2_DIR_PIN E2_DIR_PIN + #define Z2_ENABLE_PIN E2_ENABLE_PIN + #define Z2_MAX_PIN 36 //Endstop used for Z2 axis. In this case I'm using XMAX in a Rumba Board (pin 36) + const bool Z2_MAX_ENDSTOP_INVERTING = false; + #define DISABLE_XMAX_ENDSTOP //Better to disable the XMAX to avoid conflict. Just rename "XMAX_ENDSTOP" by the endstop you are using for Z2 axis. + #endif + +#endif // Z_DUAL_STEPPER_DRIVERS + +// Same again but for Y Axis. +//#define Y_DUAL_STEPPER_DRIVERS + +// Define if the two Y drives need to rotate in opposite directions +#define INVERT_Y2_VS_Y_DIR true + +// Enable this for dual x-carriage printers. +// A dual x-carriage design has the advantage that the inactive extruder can be parked which +// prevents hot-end ooze contaminating the print. It also reduces the weight of each x-carriage +// allowing faster printing speeds. +//#define DUAL_X_CARRIAGE +#ifdef DUAL_X_CARRIAGE + // Configuration for second X-carriage + // Note: the first x-carriage is defined as the x-carriage which homes to the minimum endstop; + // the second x-carriage always homes to the maximum endstop. + #define X2_MIN_POS 80 // set minimum to ensure second x-carriage doesn't hit the parked first X-carriage + #define X2_MAX_POS 353 // set maximum to the distance between toolheads when both heads are homed + #define X2_HOME_DIR 1 // the second X-carriage always homes to the maximum endstop position + #define X2_HOME_POS X2_MAX_POS // default home position is the maximum carriage position + // However: In this mode the EXTRUDER_OFFSET_X value for the second extruder provides a software + // override for X2_HOME_POS. This also allow recalibration of the distance between the two endstops + // without modifying the firmware (through the "M218 T1 X???" command). + // Remember: you should set the second extruder x-offset to 0 in your slicer. + + // Pins for second x-carriage stepper driver (defined here to avoid further complicating pins.h) + #define X2_ENABLE_PIN 29 + #define X2_STEP_PIN 25 + #define X2_DIR_PIN 23 + + // There are a few selectable movement modes for dual x-carriages using M605 S + // Mode 0: Full control. The slicer has full control over both x-carriages and can achieve optimal travel results + // as long as it supports dual x-carriages. (M605 S0) + // Mode 1: Auto-park mode. The firmware will automatically park and unpark the x-carriages on tool changes so + // that additional slicer support is not required. (M605 S1) + // Mode 2: Duplication mode. The firmware will transparently make the second x-carriage and extruder copy all + // actions of the first x-carriage. This allows the printer to print 2 arbitrary items at + // once. (2nd extruder x offset and temp offset are set using: M605 S2 [Xnnn] [Rmmm]) + + // This is the default power-up mode which can be later using M605. + #define DEFAULT_DUAL_X_CARRIAGE_MODE 0 + + // Default settings in "Auto-park Mode" + #define TOOLCHANGE_PARK_ZLIFT 0.2 // the distance to raise Z axis when parking an extruder + #define TOOLCHANGE_UNPARK_ZLIFT 1 // the distance to raise Z axis when unparking an extruder + + // Default x offset in duplication mode (typically set to half print bed width) + #define DEFAULT_DUPLICATION_X_OFFSET 100 + +#endif //DUAL_X_CARRIAGE + +// @section homing + +//homing hits the endstop, then retracts by this distance, before it tries to slowly bump again: +#define X_HOME_BUMP_MM 5 +#define Y_HOME_BUMP_MM 5 +#define Z_HOME_BUMP_MM 5 // deltas need the same for all three axis +#define HOMING_BUMP_DIVISOR {10, 10, 20} // Re-Bump Speed Divisor (Divides the Homing Feedrate) +//#define QUICK_HOME //if this is defined, if both x and y are to be homed, a diagonal move will be performed initially. + +// @section machine + +#define AXIS_RELATIVE_MODES {false, false, false, false} + +// @section machine + +//By default pololu step drivers require an active high signal. However, some high power drivers require an active low signal as step. +#define INVERT_X_STEP_PIN false +#define INVERT_Y_STEP_PIN false +#define INVERT_Z_STEP_PIN false +#define INVERT_E_STEP_PIN false + +// Default stepper release if idle. Set to 0 to deactivate. +#define DEFAULT_STEPPER_DEACTIVE_TIME 60 + +#define DEFAULT_MINIMUMFEEDRATE 0.0 // minimum feedrate +#define DEFAULT_MINTRAVELFEEDRATE 0.0 + +// @section lcd + +#ifdef ULTIPANEL + #define MANUAL_FEEDRATE {50*60, 50*60, 4*60, 60} // Feedrates for manual moves along X, Y, Z, E from panel + #define ULTIPANEL_FEEDMULTIPLY // Comment to disable setting feedrate multiplier via encoder +#endif + +// @section extras + +// minimum time in microseconds that a movement needs to take if the buffer is emptied. +#define DEFAULT_MINSEGMENTTIME 20000 + +// If defined the movements slow down when the look ahead buffer is only half full +// (don't use SLOWDOWN with DELTA because DELTA generates hundreds of segments per second) +//#define SLOWDOWN + +// Frequency limit +// See nophead's blog for more info +// Not working O +//#define XY_FREQUENCY_LIMIT 15 + +// Minimum planner junction speed. Sets the default minimum speed the planner plans for at the end +// of the buffer and all stops. This should not be much greater than zero and should only be changed +// if unwanted behavior is observed on a user's machine when running at very slow speeds. +#define MINIMUM_PLANNER_SPEED 0.05// (mm/sec) + +// Microstep setting (Only functional when stepper driver microstep pins are connected to MCU. +#define MICROSTEP_MODES {16,16,16,16,16} // [1,2,4,8,16] + +// Motor Current setting (Only functional when motor driver current ref pins are connected to a digital trimpot on supported boards) +#define DIGIPOT_MOTOR_CURRENT {135,135,135,135,135} // Values 0-255 (RAMBO 135 = ~0.75A, 185 = ~1A) + +// uncomment to enable an I2C based DIGIPOT like on the Azteeg X3 Pro +//#define DIGIPOT_I2C +// Number of channels available for I2C digipot, For Azteeg X3 Pro we have 8 +#define DIGIPOT_I2C_NUM_CHANNELS 8 +// actual motor currents in Amps, need as many here as DIGIPOT_I2C_NUM_CHANNELS +#define DIGIPOT_I2C_MOTOR_CURRENTS {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0} + +//=========================================================================== +//=============================Additional Features=========================== +//=========================================================================== + +#define ENCODER_RATE_MULTIPLIER // If defined, certain menu edit operations automatically multiply the steps when the encoder is moved quickly +#define ENCODER_10X_STEPS_PER_SEC 75 // If the encoder steps per sec exceeds this value, multiply steps moved x10 to quickly advance the value +#define ENCODER_100X_STEPS_PER_SEC 160 // If the encoder steps per sec exceeds this value, multiply steps moved x100 to really quickly advance the value +//#define ENCODER_RATE_MULTIPLIER_DEBUG // If defined, output the encoder steps per second value + +//#define CHDK 4 //Pin for triggering CHDK to take a picture see how to use it here http://captain-slow.dk/2014/03/09/3d-printing-timelapses/ +#define CHDK_DELAY 50 //How long in ms the pin should stay HIGH before going LOW again + +// @section lcd + +#ifdef SDSUPPORT + + // If you are using a RAMPS board or cheap E-bay purchased boards that do not detect when an SD card is inserted + // You can get round this by connecting a push button or single throw switch to the pin defined as SDCARDCARDDETECT + // in the pins.h file. When using a push button pulling the pin to ground this will need inverted. This setting should + // be commented out otherwise + #define SDCARDDETECTINVERTED + + #define SD_FINISHED_STEPPERRELEASE true //if sd support and the file is finished: disable steppers? + #define SD_FINISHED_RELEASECOMMAND "M84 X Y Z E" // You might want to keep the z enabled so your bed stays in place. + + #define SDCARD_RATHERRECENTFIRST //reverse file order of sd card menu display. Its sorted practically after the file system block order. + // if a file is deleted, it frees a block. hence, the order is not purely chronological. To still have auto0.g accessible, there is again the option to do that. + // using: + //#define MENU_ADDAUTOSTART + + // Show a progress bar on HD44780 LCDs for SD printing + //#define LCD_PROGRESS_BAR + + #ifdef LCD_PROGRESS_BAR + // Amount of time (ms) to show the bar + #define PROGRESS_BAR_BAR_TIME 2000 + // Amount of time (ms) to show the status message + #define PROGRESS_BAR_MSG_TIME 3000 + // Amount of time (ms) to retain the status message (0=forever) + #define PROGRESS_MSG_EXPIRE 0 + // Enable this to show messages for MSG_TIME then hide them + //#define PROGRESS_MSG_ONCE + #endif + +#endif // SDSUPPORT + +// @section more + +// The hardware watchdog should reset the microcontroller disabling all outputs, in case the firmware gets stuck and doesn't do temperature regulation. +//#define USE_WATCHDOG + +#ifdef USE_WATCHDOG +// If you have a watchdog reboot in an ArduinoMega2560 then the device will hang forever, as a watchdog reset will leave the watchdog on. +// The "WATCHDOG_RESET_MANUAL" goes around this by not using the hardware reset. +// However, THIS FEATURE IS UNSAFE!, as it will only work if interrupts are disabled. And the code could hang in an interrupt routine with interrupts disabled. +//#define WATCHDOG_RESET_MANUAL +#endif + +// Enable the option to stop SD printing when hitting and endstops, needs to be enabled from the LCD menu when this option is enabled. +//#define ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED + +// @section lcd + +// Babystepping enables the user to control the axis in tiny amounts, independently from the normal printing process +// it can e.g. be used to change z-positions in the print startup phase in real-time +// does not respect endstops! +//#define BABYSTEPPING +#ifdef BABYSTEPPING + #define BABYSTEP_XY //not only z, but also XY in the menu. more clutter, more functions + #define BABYSTEP_INVERT_Z false //true for inverse movements in Z + #define BABYSTEP_Z_MULTIPLICATOR 2 //faster z movements +#endif + +// @section extruder + +// extruder advance constant (s2/mm3) +// +// advance (steps) = STEPS_PER_CUBIC_MM_E * EXTRUDER_ADVANCE_K * cubic mm per second ^ 2 +// +// Hooke's law says: force = k * distance +// Bernoulli's principle says: v ^ 2 / 2 + g . h + pressure / density = constant +// so: v ^ 2 is proportional to number of steps we advance the extruder +//#define ADVANCE + +#ifdef ADVANCE + #define EXTRUDER_ADVANCE_K .0 + #define D_FILAMENT 2.85 + #define STEPS_MM_E 836 +#endif + +// @section extras + +// Arc interpretation settings: +#define MM_PER_ARC_SEGMENT 1 +#define N_ARC_CORRECTION 25 + +const unsigned int dropsegments=5; //everything with less than this number of steps will be ignored as move and joined with the next movement + +// @section temperature + +// Control heater 0 and heater 1 in parallel. +//#define HEATERS_PARALLEL + +//=========================================================================== +//=============================Buffers ============================ +//=========================================================================== + +// @section hidden + +// The number of linear motions that can be in the plan at any give time. +// THE BLOCK_BUFFER_SIZE NEEDS TO BE A POWER OF 2, i.g. 8,16,32 because shifts and ors are used to do the ring-buffering. +#ifdef SDSUPPORT + #define BLOCK_BUFFER_SIZE 16 // SD,LCD,Buttons take more memory, block buffer needs to be smaller +#else + #define BLOCK_BUFFER_SIZE 16 // maximize block buffer +#endif + +// @section more + +//The ASCII buffer for receiving from the serial: +#define MAX_CMD_SIZE 96 +#define BUFSIZE 4 + +// @section fwretract + +// Firmware based and LCD controlled retract +// M207 and M208 can be used to define parameters for the retraction. +// The retraction can be called by the slicer using G10 and G11 +// until then, intended retractions can be detected by moves that only extrude and the direction. +// the moves are than replaced by the firmware controlled ones. + +// #define FWRETRACT //ONLY PARTIALLY TESTED +#ifdef FWRETRACT + #define MIN_RETRACT 0.1 //minimum extruded mm to accept a automatic gcode retraction attempt + #define RETRACT_LENGTH 3 //default retract length (positive mm) + #define RETRACT_LENGTH_SWAP 13 //default swap retract length (positive mm), for extruder change + #define RETRACT_FEEDRATE 45 //default feedrate for retracting (mm/s) + #define RETRACT_ZLIFT 0 //default retract Z-lift + #define RETRACT_RECOVER_LENGTH 0 //default additional recover length (mm, added to retract length when recovering) + #define RETRACT_RECOVER_LENGTH_SWAP 0 //default additional swap recover length (mm, added to retract length when recovering from extruder change) + #define RETRACT_RECOVER_FEEDRATE 8 //default feedrate for recovering from retraction (mm/s) +#endif + +// Add support for experimental filament exchange support M600; requires display +#ifdef ULTIPANEL + //#define FILAMENTCHANGEENABLE + #ifdef FILAMENTCHANGEENABLE + #define FILAMENTCHANGE_XPOS 3 + #define FILAMENTCHANGE_YPOS 3 + #define FILAMENTCHANGE_ZADD 10 + #define FILAMENTCHANGE_FIRSTRETRACT -2 + #define FILAMENTCHANGE_FINALRETRACT -100 + #endif +#endif + +/******************************************************************************\ + * enable this section if you have TMC26X motor drivers. + * you need to import the TMC26XStepper library into the arduino IDE for this + ******************************************************************************/ + +// @section tmc + +//#define HAVE_TMCDRIVER +#ifdef HAVE_TMCDRIVER + +// #define X_IS_TMC + #define X_MAX_CURRENT 1000 //in mA + #define X_SENSE_RESISTOR 91 //in mOhms + #define X_MICROSTEPS 16 //number of microsteps + +// #define X2_IS_TMC + #define X2_MAX_CURRENT 1000 //in mA + #define X2_SENSE_RESISTOR 91 //in mOhms + #define X2_MICROSTEPS 16 //number of microsteps + +// #define Y_IS_TMC + #define Y_MAX_CURRENT 1000 //in mA + #define Y_SENSE_RESISTOR 91 //in mOhms + #define Y_MICROSTEPS 16 //number of microsteps + +// #define Y2_IS_TMC + #define Y2_MAX_CURRENT 1000 //in mA + #define Y2_SENSE_RESISTOR 91 //in mOhms + #define Y2_MICROSTEPS 16 //number of microsteps + +// #define Z_IS_TMC + #define Z_MAX_CURRENT 1000 //in mA + #define Z_SENSE_RESISTOR 91 //in mOhms + #define Z_MICROSTEPS 16 //number of microsteps + +// #define Z2_IS_TMC + #define Z2_MAX_CURRENT 1000 //in mA + #define Z2_SENSE_RESISTOR 91 //in mOhms + #define Z2_MICROSTEPS 16 //number of microsteps + +// #define E0_IS_TMC + #define E0_MAX_CURRENT 1000 //in mA + #define E0_SENSE_RESISTOR 91 //in mOhms + #define E0_MICROSTEPS 16 //number of microsteps + +// #define E1_IS_TMC + #define E1_MAX_CURRENT 1000 //in mA + #define E1_SENSE_RESISTOR 91 //in mOhms + #define E1_MICROSTEPS 16 //number of microsteps + +// #define E2_IS_TMC + #define E2_MAX_CURRENT 1000 //in mA + #define E2_SENSE_RESISTOR 91 //in mOhms + #define E2_MICROSTEPS 16 //number of microsteps + +// #define E3_IS_TMC + #define E3_MAX_CURRENT 1000 //in mA + #define E3_SENSE_RESISTOR 91 //in mOhms + #define E3_MICROSTEPS 16 //number of microsteps + +#endif + +/******************************************************************************\ + * enable this section if you have L6470 motor drivers. + * you need to import the L6470 library into the arduino IDE for this + ******************************************************************************/ + +// @section l6470 + +//#define HAVE_L6470DRIVER +#ifdef HAVE_L6470DRIVER + +// #define X_IS_L6470 + #define X_MICROSTEPS 16 //number of microsteps + #define X_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define X_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define X_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define X2_IS_L6470 + #define X2_MICROSTEPS 16 //number of microsteps + #define X2_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define X2_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define X2_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define Y_IS_L6470 + #define Y_MICROSTEPS 16 //number of microsteps + #define Y_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define Y_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define Y_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define Y2_IS_L6470 + #define Y2_MICROSTEPS 16 //number of microsteps + #define Y2_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define Y2_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define Y2_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define Z_IS_L6470 + #define Z_MICROSTEPS 16 //number of microsteps + #define Z_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define Z_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define Z_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define Z2_IS_L6470 + #define Z2_MICROSTEPS 16 //number of microsteps + #define Z2_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define Z2_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define Z2_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define E0_IS_L6470 + #define E0_MICROSTEPS 16 //number of microsteps + #define E0_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define E0_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define E0_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define E1_IS_L6470 + #define E1_MICROSTEPS 16 //number of microsteps + #define E1_MICROSTEPS 16 //number of microsteps + #define E1_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define E1_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define E1_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define E2_IS_L6470 + #define E2_MICROSTEPS 16 //number of microsteps + #define E2_MICROSTEPS 16 //number of microsteps + #define E2_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define E2_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define E2_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define E3_IS_L6470 + #define E3_MICROSTEPS 16 //number of microsteps + #define E3_MICROSTEPS 16 //number of microsteps + #define E3_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define E3_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define E3_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +#endif + +#include "Conditionals.h" +#include "SanityCheck.h" + +#endif //CONFIGURATION_ADV_H diff --git a/Marlin/Configuration_adv.h.bak b/Marlin/Configuration_adv.h.bak new file mode 100644 index 0000000..6478eb9 --- /dev/null +++ b/Marlin/Configuration_adv.h.bak @@ -0,0 +1,549 @@ +#ifndef CONFIGURATION_ADV_H +#define CONFIGURATION_ADV_H + +#include "Conditionals.h" + +// @section temperature + +//=========================================================================== +//=============================Thermal Settings ============================ +//=========================================================================== + +#ifdef BED_LIMIT_SWITCHING + #define BED_HYSTERESIS 2 //only disable heating if T>target+BED_HYSTERESIS and enable heating if T>target-BED_HYSTERESIS +#endif +#define BED_CHECK_INTERVAL 5000 //ms between checks in bang-bang control + +//// Heating sanity check: +// This waits for the watch period in milliseconds whenever an M104 or M109 increases the target temperature +// If the temperature has not increased at the end of that period, the target temperature is set to zero. +// It can be reset with another M104/M109. This check is also only triggered if the target temperature and the current temperature +// differ by at least 2x WATCH_TEMP_INCREASE +//#define WATCH_TEMP_PERIOD 40000 //40 seconds +//#define WATCH_TEMP_INCREASE 10 //Heat up at least 10 degree in 20 seconds + +#ifdef PIDTEMP + // this adds an experimental additional term to the heating power, proportional to the extrusion speed. + // if Kc is chosen well, the additional required power due to increased melting should be compensated. + #define PID_ADD_EXTRUSION_RATE + #ifdef PID_ADD_EXTRUSION_RATE + #define DEFAULT_Kc (1) //heating power=Kc*(e_speed) + #endif +#endif + + +//automatic temperature: The hot end target temperature is calculated by all the buffered lines of gcode. +//The maximum buffered steps/sec of the extruder motor are called "se". +//You enter the autotemp mode by a M109 S B F +// the target temperature is set to mintemp+factor*se[steps/sec] and limited by mintemp and maxtemp +// you exit the value by any M109 without F* +// Also, if the temperature is set to a value Z2 (yes, it is.. think about it) and the Z adjust would be positive. + // Play a little bit with small adjustments (0.5mm) and check the behaviour. + // The M119 (endstops report) will start reporting the Z2 Endstop as well. + + #define Z_DUAL_ENDSTOPS + + #ifdef Z_DUAL_ENDSTOPS + #define Z2_STEP_PIN E2_STEP_PIN // Stepper to be used to Z2 axis. + #define Z2_DIR_PIN E2_DIR_PIN + #define Z2_ENABLE_PIN E2_ENABLE_PIN + #define Z2_MAX_PIN 36 //Endstop used for Z2 axis. In this case I'm using XMAX in a Rumba Board (pin 36) + const bool Z2_MAX_ENDSTOP_INVERTING = false; + #define DISABLE_XMAX_ENDSTOP //Better to disable the XMAX to avoid conflict. Just rename "XMAX_ENDSTOP" by the endstop you are using for Z2 axis. + #endif + +#endif // Z_DUAL_STEPPER_DRIVERS + +// Same again but for Y Axis. +//#define Y_DUAL_STEPPER_DRIVERS + +// Define if the two Y drives need to rotate in opposite directions +#define INVERT_Y2_VS_Y_DIR true + +// Enable this for dual x-carriage printers. +// A dual x-carriage design has the advantage that the inactive extruder can be parked which +// prevents hot-end ooze contaminating the print. It also reduces the weight of each x-carriage +// allowing faster printing speeds. +//#define DUAL_X_CARRIAGE +#ifdef DUAL_X_CARRIAGE + // Configuration for second X-carriage + // Note: the first x-carriage is defined as the x-carriage which homes to the minimum endstop; + // the second x-carriage always homes to the maximum endstop. + #define X2_MIN_POS 80 // set minimum to ensure second x-carriage doesn't hit the parked first X-carriage + #define X2_MAX_POS 353 // set maximum to the distance between toolheads when both heads are homed + #define X2_HOME_DIR 1 // the second X-carriage always homes to the maximum endstop position + #define X2_HOME_POS X2_MAX_POS // default home position is the maximum carriage position + // However: In this mode the EXTRUDER_OFFSET_X value for the second extruder provides a software + // override for X2_HOME_POS. This also allow recalibration of the distance between the two endstops + // without modifying the firmware (through the "M218 T1 X???" command). + // Remember: you should set the second extruder x-offset to 0 in your slicer. + + // Pins for second x-carriage stepper driver (defined here to avoid further complicating pins.h) + #define X2_ENABLE_PIN 29 + #define X2_STEP_PIN 25 + #define X2_DIR_PIN 23 + + // There are a few selectable movement modes for dual x-carriages using M605 S + // Mode 0: Full control. The slicer has full control over both x-carriages and can achieve optimal travel results + // as long as it supports dual x-carriages. (M605 S0) + // Mode 1: Auto-park mode. The firmware will automatically park and unpark the x-carriages on tool changes so + // that additional slicer support is not required. (M605 S1) + // Mode 2: Duplication mode. The firmware will transparently make the second x-carriage and extruder copy all + // actions of the first x-carriage. This allows the printer to print 2 arbitrary items at + // once. (2nd extruder x offset and temp offset are set using: M605 S2 [Xnnn] [Rmmm]) + + // This is the default power-up mode which can be later using M605. + #define DEFAULT_DUAL_X_CARRIAGE_MODE 0 + + // Default settings in "Auto-park Mode" + #define TOOLCHANGE_PARK_ZLIFT 0.2 // the distance to raise Z axis when parking an extruder + #define TOOLCHANGE_UNPARK_ZLIFT 1 // the distance to raise Z axis when unparking an extruder + + // Default x offset in duplication mode (typically set to half print bed width) + #define DEFAULT_DUPLICATION_X_OFFSET 100 + +#endif //DUAL_X_CARRIAGE + +// @section homing + +//homing hits the endstop, then retracts by this distance, before it tries to slowly bump again: +#define X_HOME_BUMP_MM 5 +#define Y_HOME_BUMP_MM 5 +#define Z_HOME_BUMP_MM 2 +#define HOMING_BUMP_DIVISOR {2, 2, 4} // Re-Bump Speed Divisor (Divides the Homing Feedrate) +//#define QUICK_HOME //if this is defined, if both x and y are to be homed, a diagonal move will be performed initially. + +// @section machine + +#define AXIS_RELATIVE_MODES {false, false, false, false} + +// @section machine + +//By default pololu step drivers require an active high signal. However, some high power drivers require an active low signal as step. +#define INVERT_X_STEP_PIN false +#define INVERT_Y_STEP_PIN false +#define INVERT_Z_STEP_PIN false +#define INVERT_E_STEP_PIN false + +// Default stepper release if idle. Set to 0 to deactivate. +#define DEFAULT_STEPPER_DEACTIVE_TIME 60 + +#define DEFAULT_MINIMUMFEEDRATE 0.0 // minimum feedrate +#define DEFAULT_MINTRAVELFEEDRATE 0.0 + +// @section lcd + +#ifdef ULTIPANEL + #define MANUAL_FEEDRATE {50*60, 50*60, 4*60, 60} // Feedrates for manual moves along X, Y, Z, E from panel + #define ULTIPANEL_FEEDMULTIPLY // Comment to disable setting feedrate multiplier via encoder +#endif + +// @section extras + +// minimum time in microseconds that a movement needs to take if the buffer is emptied. +#define DEFAULT_MINSEGMENTTIME 20000 + +// If defined the movements slow down when the look ahead buffer is only half full +#define SLOWDOWN + +// Frequency limit +// See nophead's blog for more info +// Not working O +//#define XY_FREQUENCY_LIMIT 15 + +// Minimum planner junction speed. Sets the default minimum speed the planner plans for at the end +// of the buffer and all stops. This should not be much greater than zero and should only be changed +// if unwanted behavior is observed on a user's machine when running at very slow speeds. +#define MINIMUM_PLANNER_SPEED 0.05// (mm/sec) + +// Microstep setting (Only functional when stepper driver microstep pins are connected to MCU. +#define MICROSTEP_MODES {16,16,16,16,16} // [1,2,4,8,16] + +// Motor Current setting (Only functional when motor driver current ref pins are connected to a digital trimpot on supported boards) +#define DIGIPOT_MOTOR_CURRENT {135,135,135,135,135} // Values 0-255 (RAMBO 135 = ~0.75A, 185 = ~1A) + +// uncomment to enable an I2C based DIGIPOT like on the Azteeg X3 Pro +//#define DIGIPOT_I2C +// Number of channels available for I2C digipot, For Azteeg X3 Pro we have 8 +#define DIGIPOT_I2C_NUM_CHANNELS 8 +// actual motor currents in Amps, need as many here as DIGIPOT_I2C_NUM_CHANNELS +#define DIGIPOT_I2C_MOTOR_CURRENTS {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0} + +//=========================================================================== +//=============================Additional Features=========================== +//=========================================================================== + +#define ENCODER_RATE_MULTIPLIER // If defined, certain menu edit operations automatically multiply the steps when the encoder is moved quickly +#define ENCODER_10X_STEPS_PER_SEC 75 // If the encoder steps per sec exceeds this value, multiply steps moved x10 to quickly advance the value +#define ENCODER_100X_STEPS_PER_SEC 160 // If the encoder steps per sec exceeds this value, multiply steps moved x100 to really quickly advance the value +//#define ENCODER_RATE_MULTIPLIER_DEBUG // If defined, output the encoder steps per second value + +//#define CHDK 4 //Pin for triggering CHDK to take a picture see how to use it here http://captain-slow.dk/2014/03/09/3d-printing-timelapses/ +#define CHDK_DELAY 50 //How long in ms the pin should stay HIGH before going LOW again + +// @section lcd + +#ifdef SDSUPPORT + + // If you are using a RAMPS board or cheap E-bay purchased boards that do not detect when an SD card is inserted + // You can get round this by connecting a push button or single throw switch to the pin defined as SDCARDCARDDETECT + // in the pins.h file. When using a push button pulling the pin to ground this will need inverted. This setting should + // be commented out otherwise + #define SDCARDDETECTINVERTED + + #define SD_FINISHED_STEPPERRELEASE true //if sd support and the file is finished: disable steppers? + #define SD_FINISHED_RELEASECOMMAND "M84 X Y Z E" // You might want to keep the z enabled so your bed stays in place. + + #define SDCARD_RATHERRECENTFIRST //reverse file order of sd card menu display. Its sorted practically after the file system block order. + // if a file is deleted, it frees a block. hence, the order is not purely chronological. To still have auto0.g accessible, there is again the option to do that. + // using: + //#define MENU_ADDAUTOSTART + + // Show a progress bar on HD44780 LCDs for SD printing + //#define LCD_PROGRESS_BAR + + #ifdef LCD_PROGRESS_BAR + // Amount of time (ms) to show the bar + #define PROGRESS_BAR_BAR_TIME 2000 + // Amount of time (ms) to show the status message + #define PROGRESS_BAR_MSG_TIME 3000 + // Amount of time (ms) to retain the status message (0=forever) + #define PROGRESS_MSG_EXPIRE 0 + // Enable this to show messages for MSG_TIME then hide them + //#define PROGRESS_MSG_ONCE + #endif + +#endif // SDSUPPORT + +// @section more + +// The hardware watchdog should reset the microcontroller disabling all outputs, in case the firmware gets stuck and doesn't do temperature regulation. +//#define USE_WATCHDOG + +#ifdef USE_WATCHDOG +// If you have a watchdog reboot in an ArduinoMega2560 then the device will hang forever, as a watchdog reset will leave the watchdog on. +// The "WATCHDOG_RESET_MANUAL" goes around this by not using the hardware reset. +// However, THIS FEATURE IS UNSAFE!, as it will only work if interrupts are disabled. And the code could hang in an interrupt routine with interrupts disabled. +//#define WATCHDOG_RESET_MANUAL +#endif + +// Enable the option to stop SD printing when hitting and endstops, needs to be enabled from the LCD menu when this option is enabled. +//#define ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED + +// @section lcd + +// Babystepping enables the user to control the axis in tiny amounts, independently from the normal printing process +// it can e.g. be used to change z-positions in the print startup phase in real-time +// does not respect endstops! +//#define BABYSTEPPING +#ifdef BABYSTEPPING + #define BABYSTEP_XY //not only z, but also XY in the menu. more clutter, more functions + #define BABYSTEP_INVERT_Z false //true for inverse movements in Z + #define BABYSTEP_Z_MULTIPLICATOR 2 //faster z movements +#endif + +// @section extruder + +// extruder advance constant (s2/mm3) +// +// advance (steps) = STEPS_PER_CUBIC_MM_E * EXTRUDER_ADVANCE_K * cubic mm per second ^ 2 +// +// Hooke's law says: force = k * distance +// Bernoulli's principle says: v ^ 2 / 2 + g . h + pressure / density = constant +// so: v ^ 2 is proportional to number of steps we advance the extruder +//#define ADVANCE + +#ifdef ADVANCE + #define EXTRUDER_ADVANCE_K .0 + #define D_FILAMENT 2.85 + #define STEPS_MM_E 836 +#endif + +// @section extras + +// Arc interpretation settings: +#define MM_PER_ARC_SEGMENT 1 +#define N_ARC_CORRECTION 25 + +const unsigned int dropsegments=5; //everything with less than this number of steps will be ignored as move and joined with the next movement + +// @section temperature + +// Control heater 0 and heater 1 in parallel. +//#define HEATERS_PARALLEL + +//=========================================================================== +//=============================Buffers ============================ +//=========================================================================== + +// @section hidden + +// The number of linear motions that can be in the plan at any give time. +// THE BLOCK_BUFFER_SIZE NEEDS TO BE A POWER OF 2, i.g. 8,16,32 because shifts and ors are used to do the ring-buffering. +#ifdef SDSUPPORT + #define BLOCK_BUFFER_SIZE 16 // SD,LCD,Buttons take more memory, block buffer needs to be smaller +#else + #define BLOCK_BUFFER_SIZE 16 // maximize block buffer +#endif + +// @section more + +//The ASCII buffer for receiving from the serial: +#define MAX_CMD_SIZE 96 +#define BUFSIZE 4 + +// @section fwretract + +// Firmware based and LCD controlled retract +// M207 and M208 can be used to define parameters for the retraction. +// The retraction can be called by the slicer using G10 and G11 +// until then, intended retractions can be detected by moves that only extrude and the direction. +// the moves are than replaced by the firmware controlled ones. + +// #define FWRETRACT //ONLY PARTIALLY TESTED +#ifdef FWRETRACT + #define MIN_RETRACT 0.1 //minimum extruded mm to accept a automatic gcode retraction attempt + #define RETRACT_LENGTH 3 //default retract length (positive mm) + #define RETRACT_LENGTH_SWAP 13 //default swap retract length (positive mm), for extruder change + #define RETRACT_FEEDRATE 45 //default feedrate for retracting (mm/s) + #define RETRACT_ZLIFT 0 //default retract Z-lift + #define RETRACT_RECOVER_LENGTH 0 //default additional recover length (mm, added to retract length when recovering) + #define RETRACT_RECOVER_LENGTH_SWAP 0 //default additional swap recover length (mm, added to retract length when recovering from extruder change) + #define RETRACT_RECOVER_FEEDRATE 8 //default feedrate for recovering from retraction (mm/s) +#endif + +// Add support for experimental filament exchange support M600; requires display +#ifdef ULTIPANEL + //#define FILAMENTCHANGEENABLE + #ifdef FILAMENTCHANGEENABLE + #define FILAMENTCHANGE_XPOS 3 + #define FILAMENTCHANGE_YPOS 3 + #define FILAMENTCHANGE_ZADD 10 + #define FILAMENTCHANGE_FIRSTRETRACT -2 + #define FILAMENTCHANGE_FINALRETRACT -100 + #endif +#endif + +/******************************************************************************\ + * enable this section if you have TMC26X motor drivers. + * you need to import the TMC26XStepper library into the arduino IDE for this + ******************************************************************************/ + +// @section tmc + +//#define HAVE_TMCDRIVER +#ifdef HAVE_TMCDRIVER + +// #define X_IS_TMC + #define X_MAX_CURRENT 1000 //in mA + #define X_SENSE_RESISTOR 91 //in mOhms + #define X_MICROSTEPS 16 //number of microsteps + +// #define X2_IS_TMC + #define X2_MAX_CURRENT 1000 //in mA + #define X2_SENSE_RESISTOR 91 //in mOhms + #define X2_MICROSTEPS 16 //number of microsteps + +// #define Y_IS_TMC + #define Y_MAX_CURRENT 1000 //in mA + #define Y_SENSE_RESISTOR 91 //in mOhms + #define Y_MICROSTEPS 16 //number of microsteps + +// #define Y2_IS_TMC + #define Y2_MAX_CURRENT 1000 //in mA + #define Y2_SENSE_RESISTOR 91 //in mOhms + #define Y2_MICROSTEPS 16 //number of microsteps + +// #define Z_IS_TMC + #define Z_MAX_CURRENT 1000 //in mA + #define Z_SENSE_RESISTOR 91 //in mOhms + #define Z_MICROSTEPS 16 //number of microsteps + +// #define Z2_IS_TMC + #define Z2_MAX_CURRENT 1000 //in mA + #define Z2_SENSE_RESISTOR 91 //in mOhms + #define Z2_MICROSTEPS 16 //number of microsteps + +// #define E0_IS_TMC + #define E0_MAX_CURRENT 1000 //in mA + #define E0_SENSE_RESISTOR 91 //in mOhms + #define E0_MICROSTEPS 16 //number of microsteps + +// #define E1_IS_TMC + #define E1_MAX_CURRENT 1000 //in mA + #define E1_SENSE_RESISTOR 91 //in mOhms + #define E1_MICROSTEPS 16 //number of microsteps + +// #define E2_IS_TMC + #define E2_MAX_CURRENT 1000 //in mA + #define E2_SENSE_RESISTOR 91 //in mOhms + #define E2_MICROSTEPS 16 //number of microsteps + +// #define E3_IS_TMC + #define E3_MAX_CURRENT 1000 //in mA + #define E3_SENSE_RESISTOR 91 //in mOhms + #define E3_MICROSTEPS 16 //number of microsteps + +#endif + +/******************************************************************************\ + * enable this section if you have L6470 motor drivers. + * you need to import the L6470 library into the arduino IDE for this + ******************************************************************************/ + +// @section l6470 + +//#define HAVE_L6470DRIVER +#ifdef HAVE_L6470DRIVER + +// #define X_IS_L6470 + #define X_MICROSTEPS 16 //number of microsteps + #define X_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define X_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define X_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define X2_IS_L6470 + #define X2_MICROSTEPS 16 //number of microsteps + #define X2_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define X2_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define X2_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define Y_IS_L6470 + #define Y_MICROSTEPS 16 //number of microsteps + #define Y_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define Y_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define Y_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define Y2_IS_L6470 + #define Y2_MICROSTEPS 16 //number of microsteps + #define Y2_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define Y2_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define Y2_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define Z_IS_L6470 + #define Z_MICROSTEPS 16 //number of microsteps + #define Z_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define Z_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define Z_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define Z2_IS_L6470 + #define Z2_MICROSTEPS 16 //number of microsteps + #define Z2_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define Z2_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define Z2_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define E0_IS_L6470 + #define E0_MICROSTEPS 16 //number of microsteps + #define E0_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define E0_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define E0_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define E1_IS_L6470 + #define E1_MICROSTEPS 16 //number of microsteps + #define E1_MICROSTEPS 16 //number of microsteps + #define E1_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define E1_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define E1_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define E2_IS_L6470 + #define E2_MICROSTEPS 16 //number of microsteps + #define E2_MICROSTEPS 16 //number of microsteps + #define E2_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define E2_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define E2_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define E3_IS_L6470 + #define E3_MICROSTEPS 16 //number of microsteps + #define E3_MICROSTEPS 16 //number of microsteps + #define E3_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define E3_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define E3_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +#endif + +#include "Conditionals.h" +#include "SanityCheck.h" + +#endif //CONFIGURATION_ADV_H diff --git a/Marlin/DOGMbitmaps.h b/Marlin/DOGMbitmaps.h new file mode 100644 index 0000000..8c83567 --- /dev/null +++ b/Marlin/DOGMbitmaps.h @@ -0,0 +1,237 @@ +// BitMap for splashscreen +// Generated with: http://www.digole.com/tools/PicturetoC_Hex_converter.php +// Please note that using the high-res version takes 402Bytes of PROGMEM. +//#define START_BMPHIGH + +#ifdef START_BMPHIGH + #define START_BMPWIDTH 112 + #define START_BMPHEIGHT 38 + #define START_BMPBYTEWIDTH 14 + #define START_BMPBYTES 532 // START_BMPWIDTH * START_BMPHEIGHT / 8 + + const unsigned char start_bmp[START_BMPBYTES] PROGMEM = { + 0x01,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff + ,0x0f,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff + ,0x1e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0xff,0xff + ,0x38,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0xff,0xff + ,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0xff,0xff + ,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff + ,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0xff + ,0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x78,0x00,0x00,0x3f,0xff + ,0xc0,0x0f,0xc0,0xfc,0x00,0x00,0x00,0x00,0x00,0x78,0x18,0x00,0x1f,0xff + ,0xc0,0x3f,0xe1,0xff,0x00,0x00,0x00,0x00,0x00,0x78,0x3c,0x00,0x0f,0xff + ,0xc0,0x7f,0xf3,0xff,0x80,0x00,0x00,0x00,0x00,0x78,0x3c,0x00,0x07,0xff + ,0xc0,0xff,0xff,0xff,0xc0,0x00,0x00,0x00,0x00,0x78,0x3c,0x00,0x03,0xff + ,0xc1,0xf8,0x7f,0x87,0xe0,0x00,0x00,0x00,0x00,0x78,0x00,0x00,0x01,0xff + ,0xc1,0xf0,0x3f,0x03,0xe0,0x00,0x00,0x00,0x00,0x78,0x00,0x00,0x00,0xff + ,0xc1,0xe0,0x1e,0x01,0xe0,0x1f,0x00,0x03,0xe0,0x78,0x3c,0x03,0xf0,0x7f + ,0xc1,0xe0,0x1e,0x01,0xe0,0x7f,0xc0,0x0f,0xf8,0x78,0x3c,0x07,0xfc,0x3f + ,0xc1,0xe0,0x1e,0x01,0xe1,0xff,0xe0,0x1f,0xfc,0x78,0x3c,0x0f,0xfe,0x1f + ,0xc1,0xe0,0x1e,0x01,0xe3,0xff,0xf0,0x3f,0xfe,0x78,0x3c,0x1f,0xfe,0x0f + ,0xc1,0xe0,0x1e,0x01,0xe3,0xf3,0xf8,0x3f,0x3e,0x78,0x3c,0x3f,0x3f,0x07 + ,0xc1,0xe0,0x1e,0x01,0xe7,0xe0,0xfc,0x7c,0x1f,0x78,0x3c,0x3e,0x1f,0x07 + ,0xc1,0xe0,0x1e,0x01,0xe7,0xc0,0x7c,0x7c,0x0f,0x78,0x3c,0x3c,0x0f,0x03 + ,0xc1,0xe0,0x1e,0x01,0xe7,0x80,0x7c,0x78,0x0f,0x78,0x3c,0x3c,0x0f,0x03 + ,0xc1,0xe0,0x1e,0x01,0xe7,0x80,0x3c,0x78,0x00,0x78,0x3c,0x3c,0x0f,0x03 + ,0xc1,0xe0,0x1e,0x01,0xe7,0x80,0x3c,0x78,0x00,0x78,0x3c,0x3c,0x0f,0x03 + ,0xc1,0xe0,0x1e,0x01,0xe7,0x80,0x3c,0x78,0x00,0x78,0x3c,0x3c,0x0f,0x03 + ,0xc1,0xe0,0x1e,0x01,0xe7,0xc0,0x3c,0x78,0x00,0x78,0x3c,0x3c,0x0f,0x03 + ,0xc1,0xe0,0x1e,0x01,0xe3,0xe0,0x3c,0x78,0x00,0x7c,0x3c,0x3c,0x0f,0x03 + ,0xc1,0xe0,0x1e,0x01,0xe3,0xff,0x3f,0xf8,0x00,0x7f,0xbc,0x3c,0x0f,0x03 + ,0xc1,0xe0,0x1e,0x01,0xe1,0xff,0x3f,0xf8,0x00,0x3f,0xbf,0xfc,0x0f,0x03 + ,0xc1,0xe0,0x1e,0x01,0xe0,0xff,0x3f,0xf8,0x00,0x1f,0xbf,0xfc,0x0f,0x03 + ,0xc1,0xe0,0x1e,0x01,0xe0,0x7f,0x3f,0xf8,0x00,0x0f,0xbf,0xfc,0x0f,0x03 + ,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07 + ,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06 + ,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0e + ,0x38,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1c + ,0x1e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x78 + ,0x0f,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xf0 + ,0x01,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x80 }; +#else + #define START_BMPWIDTH 56 + #define START_BMPHEIGHT 19 + #define START_BMPBYTEWIDTH 7 + #define START_BMPBYTES 133 // START_BMPWIDTH * START_BMPHEIGHT / 8 + + const unsigned char start_bmp[START_BMPBYTES] PROGMEM = { + 0x1f,0xff,0xff,0xff,0xff,0xff,0xff + ,0x60,0x00,0x00,0x00,0x00,0x01,0xff + ,0x40,0x00,0x00,0x00,0x00,0x00,0xff + ,0x80,0x00,0x00,0x00,0x00,0x00,0x7f + ,0x83,0xcf,0x00,0x00,0x0c,0x30,0x3f + ,0x87,0xff,0x80,0x00,0x0c,0x30,0x1f + ,0x86,0x79,0x80,0x00,0x0c,0x00,0x0f + ,0x8c,0x30,0xc7,0x83,0x8c,0x30,0xe7 + ,0x8c,0x30,0xcf,0xc7,0xcc,0x31,0xf3 + ,0x8c,0x30,0xdc,0xec,0xec,0x33,0xb9 + ,0x8c,0x30,0xd8,0x6c,0x6c,0x33,0x19 + ,0x8c,0x30,0xd0,0x6c,0x0c,0x33,0x19 + ,0x8c,0x30,0xd8,0x6c,0x0c,0x33,0x19 + ,0x8c,0x30,0xdc,0x6c,0x0e,0x3b,0x19 + ,0x8c,0x30,0xcf,0x7c,0x07,0x9f,0x19 + ,0x8c,0x30,0xc7,0x7c,0x03,0x8f,0x19 + ,0x40,0x00,0x00,0x00,0x00,0x00,0x02 + ,0x60,0x00,0x00,0x00,0x00,0x00,0x06 + ,0x1f,0xff,0xff,0xff,0xff,0xff,0xf8 }; +#endif + +// Here comes a compile-time operation to match the extruder symbols +// on the info screen to the set number of extruders in configuration.h +// +// When only one extruder is selected, the "1" on the symbol will not +// be displayed. + +#if EXTRUDERS == 1 + #define STATUS_SCREENWIDTH 115 //Width in pixels + #define STATUS_SCREENHEIGHT 19 //Height in pixels + #define STATUS_SCREENBYTEWIDTH 15 //Width in bytes + const unsigned char status_screen0_bmp[] PROGMEM = { //AVR-GCC, WinAVR + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0xFF,0xE0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0xE0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x63,0x0C,0x60, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x47,0x0E,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4F,0x0F,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x5F,0x0F,0xA0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x5E,0x07,0xA0, + 0x7F,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x41,0x04,0x00,0x40,0x60,0x20, + 0xFF,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x82,0x00,0x40,0xF0,0x20, + 0xFF,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x82,0x00,0x40,0xF0,0x20, + 0xFF,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x41,0x04,0x00,0x40,0x60,0x20, + 0x7F,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x82,0x08,0x00,0x5E,0x07,0xA0, + 0x7F,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x04,0x10,0x00,0x5F,0x0F,0xA0, + 0xFF,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x04,0x10,0x00,0x4F,0x0F,0x20, + 0xFF,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x82,0x08,0x00,0x47,0x0E,0x20, + 0xFF,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x41,0x04,0x00,0x63,0x0C,0x60, + 0x3F,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0xE0, + 0x1E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0x80,0x7F,0xFF,0xE0, + 0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0x80,0x00,0x00,0x00 + }; + + #define STATUS_SCREENWIDTH 115 //Width in pixels + #define STATUS_SCREENHEIGHT 19 //Height in pixels + #define STATUS_SCREENBYTEWIDTH 15 //Width in bytes + const unsigned char status_screen1_bmp[] PROGMEM = { //AVR-GCC, WinAVR + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0xFF,0xE0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0xE0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x61,0xF8,0x60, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x41,0xF8,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0xF0,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x60,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x58,0x01,0xA0, + 0x7F,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x41,0x04,0x00,0x5C,0x63,0xA0, + 0xFF,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x82,0x00,0x5E,0xF7,0xA0, + 0xFF,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x82,0x00,0x5E,0xF7,0xA0, + 0xFF,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x41,0x04,0x00,0x5C,0x63,0xA0, + 0x7F,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x82,0x08,0x00,0x58,0x01,0xA0, + 0x7F,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x04,0x10,0x00,0x40,0x60,0x20, + 0xFF,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x04,0x10,0x00,0x40,0xF0,0x20, + 0xFF,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x82,0x08,0x00,0x41,0xF8,0x20, + 0xFF,0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x41,0x04,0x00,0x61,0xF8,0x60, + 0x3F,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0xE0, + 0x1E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0x80,0x7F,0xFF,0xE0, + 0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0x80,0x00,0x00,0x00 + }; +#elif EXTRUDERS == 2 + #define STATUS_SCREENWIDTH 115 //Width in pixels + #define STATUS_SCREENHEIGHT 19 //Height in pixels + #define STATUS_SCREENBYTEWIDTH 15 //Width in bytes + const unsigned char status_screen0_bmp[] PROGMEM = { //AVR-GCC, WinAVR + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0xFF,0xE0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0xE0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x63,0x0C,0x60, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x47,0x0E,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4F,0x0F,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x5F,0x0F,0xA0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x5E,0x07,0xA0, + 0x7F,0x80,0x00,0x3F,0xC0,0x00,0x00,0x00,0x00,0x41,0x04,0x00,0x40,0x60,0x20, + 0xFB,0xC0,0x00,0x79,0xE0,0x00,0x00,0x00,0x00,0x20,0x82,0x00,0x40,0xF0,0x20, + 0xF3,0xC0,0x00,0x76,0xE0,0x00,0x00,0x00,0x00,0x20,0x82,0x00,0x40,0xF0,0x20, + 0xEB,0xC0,0x00,0x7E,0xE0,0x00,0x00,0x00,0x00,0x41,0x04,0x00,0x40,0x60,0x20, + 0x7B,0x80,0x00,0x3D,0xC0,0x00,0x00,0x00,0x00,0x82,0x08,0x00,0x5E,0x07,0xA0, + 0x7B,0x80,0x00,0x3B,0xC0,0x00,0x00,0x00,0x01,0x04,0x10,0x00,0x5F,0x0F,0xA0, + 0xFB,0xC0,0x00,0x77,0xE0,0x00,0x00,0x00,0x01,0x04,0x10,0x00,0x4F,0x0F,0x20, + 0xFB,0xC0,0x00,0x70,0xE0,0x00,0x00,0x00,0x00,0x82,0x08,0x00,0x47,0x0E,0x20, + 0xFF,0xC0,0x00,0x7F,0xE0,0x00,0x00,0x00,0x00,0x41,0x04,0x00,0x63,0x0C,0x60, + 0x3F,0x00,0x00,0x1F,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0xE0, + 0x1E,0x00,0x00,0x0F,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0x80,0x7F,0xFF,0xE0, + 0x0C,0x00,0x00,0x06,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0x80,0x00,0x00,0x00 + }; + + #define STATUS_SCREENWIDTH 115 //Width in pixels + #define STATUS_SCREENHEIGHT 19 //Height in pixels + #define STATUS_SCREENBYTEWIDTH 15 //Width in bytes + const unsigned char status_screen1_bmp[] PROGMEM = { //AVR-GCC, WinAVR + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0xFF,0xE0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0xE0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x61,0xF8,0x60, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x41,0xF8,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0xF0,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x60,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x58,0x01,0xA0, + 0x7F,0x80,0x00,0x3F,0xC0,0x00,0x00,0x00,0x00,0x41,0x04,0x00,0x5C,0x63,0xA0, + 0xFB,0xC0,0x00,0x79,0xE0,0x00,0x00,0x00,0x00,0x20,0x82,0x00,0x5E,0xF7,0xA0, + 0xF3,0xC0,0x00,0x76,0xE0,0x00,0x00,0x00,0x00,0x20,0x82,0x00,0x5E,0xF7,0xA0, + 0xEB,0xC0,0x00,0x7E,0xE0,0x00,0x00,0x00,0x00,0x41,0x04,0x00,0x5C,0x63,0xA0, + 0x7B,0x80,0x00,0x3D,0xC0,0x00,0x00,0x00,0x00,0x82,0x08,0x00,0x58,0x01,0xA0, + 0x7B,0x80,0x00,0x3B,0xC0,0x00,0x00,0x00,0x01,0x04,0x10,0x00,0x40,0x60,0x20, + 0xFB,0xC0,0x00,0x77,0xE0,0x00,0x00,0x00,0x01,0x04,0x10,0x00,0x40,0xF0,0x20, + 0xFB,0xC0,0x00,0x70,0xE0,0x00,0x00,0x00,0x00,0x82,0x08,0x00,0x41,0xF8,0x20, + 0xFF,0xC0,0x00,0x7F,0xE0,0x00,0x00,0x00,0x00,0x41,0x04,0x00,0x61,0xF8,0x60, + 0x3F,0x00,0x00,0x1F,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0xE0, + 0x1E,0x00,0x00,0x0F,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0x80,0x7F,0xFF,0xE0, + 0x0C,0x00,0x00,0x06,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0x80,0x00,0x00,0x00 + }; +#else + #define STATUS_SCREENWIDTH 115 //Width in pixels + #define STATUS_SCREENHEIGHT 19 //Height in pixels + #define STATUS_SCREENBYTEWIDTH 15 //Width in bytes + const unsigned char status_screen0_bmp[] PROGMEM = { //AVR-GCC, WinAVR + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0xFF,0xE0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0xE0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x63,0x0C,0x60, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x47,0x0E,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4F,0x0F,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x5F,0x0F,0xA0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x5E,0x07,0xA0, + 0x7F,0x80,0x00,0x3F,0xC0,0x00,0x3F,0xC0,0x00,0x41,0x04,0x00,0x40,0x60,0x20, + 0xFB,0xC0,0x00,0x79,0xE0,0x00,0x79,0xE0,0x00,0x20,0x82,0x00,0x40,0xF0,0x20, + 0xF3,0xC0,0x00,0x76,0xE0,0x00,0x76,0xE0,0x00,0x20,0x82,0x00,0x40,0xF0,0x20, + 0xEB,0xC0,0x00,0x7E,0xE0,0x00,0x7E,0xE0,0x00,0x41,0x04,0x00,0x40,0x60,0x20, + 0x7B,0x80,0x00,0x3D,0xC0,0x00,0x39,0xC0,0x00,0x82,0x08,0x00,0x5E,0x07,0xA0, + 0x7B,0x80,0x00,0x3B,0xC0,0x00,0x3E,0xC0,0x01,0x04,0x10,0x00,0x5F,0x0F,0xA0, + 0xFB,0xC0,0x00,0x77,0xE0,0x00,0x76,0xE0,0x01,0x04,0x10,0x00,0x4F,0x0F,0x20, + 0xFB,0xC0,0x00,0x70,0xE0,0x00,0x79,0xE0,0x00,0x82,0x08,0x00,0x47,0x0E,0x20, + 0xFF,0xC0,0x00,0x7F,0xE0,0x00,0x7F,0xE0,0x00,0x41,0x04,0x00,0x63,0x0C,0x60, + 0x3F,0x00,0x00,0x1F,0x80,0x00,0x1F,0x80,0x00,0x00,0x00,0x00,0x70,0x00,0xE0, + 0x1E,0x00,0x00,0x0F,0x00,0x00,0x0F,0x00,0x01,0xFF,0xFF,0x80,0x7F,0xFF,0xE0, + 0x0C,0x00,0x00,0x06,0x00,0x00,0x06,0x00,0x01,0xFF,0xFF,0x80,0x00,0x00,0x00 + }; + + #define STATUS_SCREENWIDTH 115 //Width in pixels + #define STATUS_SCREENHEIGHT 19 //Height in pixels + #define STATUS_SCREENBYTEWIDTH 15 //Width in bytes + const unsigned char status_screen1_bmp[] PROGMEM = { //AVR-GCC, WinAVR + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0xFF,0xE0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0x00,0xE0, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x61,0xF8,0x60, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x41,0xF8,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0xF0,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x60,0x20, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x58,0x01,0xA0, + 0x7F,0x80,0x00,0x3F,0xC0,0x00,0x3F,0xC0,0x00,0x41,0x04,0x00,0x5C,0x63,0xA0, + 0xFB,0xC0,0x00,0x79,0xE0,0x00,0x79,0xE0,0x00,0x20,0x82,0x00,0x5E,0xF7,0xA0, + 0xF3,0xC0,0x00,0x76,0xE0,0x00,0x76,0xE0,0x00,0x20,0x82,0x00,0x5E,0xF7,0xA0, + 0xEB,0xC0,0x00,0x7E,0xE0,0x00,0x7E,0xE0,0x00,0x41,0x04,0x00,0x5C,0x63,0xA0, + 0x7B,0x80,0x00,0x3D,0xC0,0x00,0x39,0xC0,0x00,0x82,0x08,0x00,0x58,0x01,0xA0, + 0x7B,0x80,0x00,0x3B,0xC0,0x00,0x3E,0xC0,0x01,0x04,0x10,0x00,0x40,0x60,0x20, + 0xFB,0xC0,0x00,0x77,0xE0,0x00,0x76,0xE0,0x01,0x04,0x10,0x00,0x40,0xF0,0x20, + 0xFB,0xC0,0x00,0x70,0xE0,0x00,0x79,0xE0,0x00,0x82,0x08,0x00,0x41,0xF8,0x20, + 0xFF,0xC0,0x00,0x7F,0xE0,0x00,0x7F,0xE0,0x00,0x41,0x04,0x00,0x61,0xF8,0x60, + 0x3F,0x00,0x00,0x1F,0x80,0x00,0x1F,0x80,0x00,0x00,0x00,0x00,0x70,0x00,0xE0, + 0x1E,0x00,0x00,0x0F,0x00,0x00,0x0F,0x00,0x01,0xFF,0xFF,0x80,0x7F,0xFF,0xE0, + 0x0C,0x00,0x00,0x06,0x00,0x00,0x06,0x00,0x01,0xFF,0xFF,0x80,0x00,0x00,0x00 + }; +#endif // Extruders + + diff --git a/Marlin/Makefile b/Marlin/Makefile new file mode 100644 index 0000000..56e5dda --- /dev/null +++ b/Marlin/Makefile @@ -0,0 +1,493 @@ +# Sprinter Arduino Project Makefile +# +# Makefile Based on: +# Arduino 0011 Makefile +# Arduino adaptation by mellis, eighthave, oli.keller +# Marlin adaption by Daid +# +# This has been tested with Arduino 0022. +# +# This makefile allows you to build sketches from the command line +# without the Arduino environment (or Java). +# +# Detailed instructions for using the makefile: +# +# 1. Modify the line containg "ARDUINO_INSTALL_DIR" to point to the directory that +# contains the Arduino installation (for example, under Mac OS X, this +# might be /Applications/Arduino.app/Contents/Resources/Java). +# +# 2. Modify the line containing "UPLOAD_PORT" to refer to the filename +# representing the USB or serial connection to your Arduino board +# (e.g. UPLOAD_PORT = /dev/tty.USB0). If the exact name of this file +# changes, you can use * as a wildcard (e.g. UPLOAD_PORT = /dev/tty.usb*). +# +# 3. Set the line containing "MCU" to match your board's processor. +# Older one's are atmega8 based, newer ones like Arduino Mini, Bluetooth +# or Diecimila have the atmega168. If you're using a LilyPad Arduino, +# change F_CPU to 8000000. If you are using Gen7 electronics, you +# probably need to use 20000000. Either way, you must regenerate +# the speed lookup table with create_speed_lookuptable.py. +# +# 4. Type "make" and press enter to compile/verify your program. +# +# 5. Type "make upload", reset your Arduino board, and press enter to +# upload your program to the Arduino board. +# +# Note that all settings are set with ?=, this means you can override them +# from the commandline with "make HARDWARE_MOTHERBOARD=71" for example + +# This defined the board you are compiling for (see boards.h for the options) +HARDWARE_MOTHERBOARD ?= 11 + +# Arduino source install directory, and version number +# On most linuxes this will be /usr/share/arduino +ARDUINO_INSTALL_DIR ?= /usr/share/arduino +ARDUINO_VERSION ?= 105 + +# You can optionally set a path to the avr-gcc tools. Requires a trailing slash. (ex: /usr/local/avr-gcc/bin) +AVR_TOOLS_PATH ?= + +#Programmer configuration +UPLOAD_RATE ?= 115200 +AVRDUDE_PROGRAMMER ?= wiring +# on most linuxes this will be /dev/ttyACM0 or /dev/ttyACM1 +UPLOAD_PORT ?= /dev/arduino + +#Directory used to build files in, contains all the build files, from object files to the final hex file +#on linux it is best to put an absolute path like /home/username/tmp . +BUILD_DIR ?= applet + +# This defines whether Liquid_TWI2 support will be built +LIQUID_TWI2 ?= 0 + +# this defines if Wire is needed +WIRE ?= 0 + +############################################################################ +# Below here nothing should be changed... + +# Here the Arduino variant is selected by the board type +# HARDWARE_VARIANT = "arduino", "Sanguino", "Gen7", ... +# MCU = "atmega1280", "Mega2560", "atmega2560", "atmega644p", ... + +#Gen7 +ifeq ($(HARDWARE_MOTHERBOARD),10) +HARDWARE_VARIANT ?= Gen7 +MCU ?= atmega644 +F_CPU ?= 20000000 +else ifeq ($(HARDWARE_MOTHERBOARD),11) +HARDWARE_VARIANT ?= Gen7 +MCU ?= atmega644p +F_CPU ?= 20000000 +else ifeq ($(HARDWARE_MOTHERBOARD),12) +HARDWARE_VARIANT ?= Gen7 +MCU ?= atmega644p +F_CPU ?= 20000000 +else ifeq ($(HARDWARE_MOTHERBOARD),13) +HARDWARE_VARIANT ?= Gen7 +MCU ?= atmega1284p +F_CPU ?= 20000000 + +#RAMPS +else ifeq ($(HARDWARE_MOTHERBOARD),3) +HARDWARE_VARIANT ?= arduino +MCU ?= atmega2560 +else ifeq ($(HARDWARE_MOTHERBOARD),33) +HARDWARE_VARIANT ?= arduino +MCU ?= atmega2560 +else ifeq ($(HARDWARE_MOTHERBOARD),34) +HARDWARE_VARIANT ?= arduino +MCU ?= atmega2560 + +#Duemilanove w/ ATMega328P pin assignment +else ifeq ($(HARDWARE_MOTHERBOARD),4) +HARDWARE_VARIANT ?= arduino +HARDWARE_SUB_VARIANT ?= standard +MCU ?= atmega328p + +#Gen6 +else ifeq ($(HARDWARE_MOTHERBOARD),5) +HARDWARE_VARIANT ?= Gen6 +MCU ?= atmega644p +else ifeq ($(HARDWARE_MOTHERBOARD),51) +HARDWARE_VARIANT ?= Gen6 +MCU ?= atmega644p + +#Sanguinololu +else ifeq ($(HARDWARE_MOTHERBOARD),6) +HARDWARE_VARIANT ?= Sanguino +MCU ?= atmega644p +else ifeq ($(HARDWARE_MOTHERBOARD),62) +HARDWARE_VARIANT ?= Sanguino +MCU ?= atmega644p +else ifeq ($(HARDWARE_MOTHERBOARD),63) +HARDWARE_VARIANT ?= Sanguino +MCU ?= atmega644p +else ifeq ($(HARDWARE_MOTHERBOARD),65) +HARDWARE_VARIANT ?= Sanguino +MCU ?= atmega1284p +else ifeq ($(HARDWARE_MOTHERBOARD),66) +HARDWARE_VARIANT ?= Sanguino +MCU ?= atmega1284p + +#Ultimaker +else ifeq ($(HARDWARE_MOTHERBOARD),7) +HARDWARE_VARIANT ?= arduino +MCU ?= atmega2560 +else ifeq ($(HARDWARE_MOTHERBOARD),71) +HARDWARE_VARIANT ?= arduino +MCU ?= atmega1280 + +#Teensylu +else ifeq ($(HARDWARE_MOTHERBOARD),8) +HARDWARE_VARIANT ?= Teensy +MCU ?= at90usb1286 +else ifeq ($(HARDWARE_MOTHERBOARD),81) +HARDWARE_VARIANT ?= Teensy +MCU ?= at90usb1286 +else ifeq ($(HARDWARE_MOTHERBOARD),82) +HARDWARE_VARIANT ?= Teensy +MCU ?= at90usb646 +else ifeq ($(HARDWARE_MOTHERBOARD),83) +HARDWARE_VARIANT ?= Teensy +MCU ?= at90usb1286 +else ifeq ($(HARDWARE_MOTHERBOARD),84) +HARDWARE_VARIANT ?= Teensy +MCU ?= at90usb1286 + +#Gen3+ +else ifeq ($(HARDWARE_MOTHERBOARD),9) +HARDWARE_VARIANT ?= Sanguino +MCU ?= atmega644p + +#Gen3 Monolithic Electronics +else ifeq ($(HARDWARE_MOTHERBOARD),22) +HARDWARE_VARIANT ?= Sanguino +MCU ?= atmega644p + +#Megatronics +else ifeq ($(HARDWARE_MOTHERBOARD),70) +HARDWARE_VARIANT ?= arduino +MCU ?= atmega2560 + +#Alpha OMCA board +else ifeq ($(HARDWARE_MOTHERBOARD),90) +HARDWARE_VARIANT ?= SanguinoA +MCU ?= atmega644 + +#Final OMCA board +else ifeq ($(HARDWARE_MOTHERBOARD),91) +HARDWARE_VARIANT ?= Sanguino +MCU ?= atmega644p + +#Rambo +else ifeq ($(HARDWARE_MOTHERBOARD),301) +HARDWARE_VARIANT ?= arduino +MCU ?= atmega2560 + +# Azteeg +else ifeq ($(HARDWARE_MOTHERBOARD),67) +HARDWARE_VARIANT ?= arduino +MCU ?= atmega2560 +else ifeq ($(HARDWARE_MOTHERBOARD),68) +HARDWARE_VARIANT ?= arduino +MCU ?= atmega2560 + +endif + +# Be sure to regenerate speed_lookuptable.h with create_speed_lookuptable.py +# if you are setting this to something other than 16MHz +# Set to 16Mhz if not yet set. +F_CPU ?= 16000000 + +# Arduino containd the main source code for the Arduino +# Libraries, the "hardware variant" are for boards +# that derives from that, and their source are present in +# the main Marlin source directory +ifeq ($(HARDWARE_VARIANT), arduino) +HARDWARE_DIR = $(ARDUINO_INSTALL_DIR)/hardware +else +ifeq ($(shell [ $(ARDUINO_VERSION) -ge 100 ] && echo true), true) +HARDWARE_DIR = ../ArduinoAddons/Arduino_1.x.x +else +HARDWARE_DIR = ../ArduinoAddons/Arduino_0.xx +endif +endif +HARDWARE_SRC = $(HARDWARE_DIR)/$(HARDWARE_VARIANT)/cores/arduino + +TARGET = $(notdir $(CURDIR)) + +# VPATH tells make to look into these directory for source files, +# there is no need to specify explicit pathnames as long as the +# directory is added here + +VPATH = . +VPATH += $(BUILD_DIR) +VPATH += $(HARDWARE_SRC) +ifeq ($(HARDWARE_VARIANT), $(filter $(HARDWARE_VARIANT),arduino Teensy)) +VPATH += $(ARDUINO_INSTALL_DIR)/libraries/LiquidCrystal +VPATH += $(ARDUINO_INSTALL_DIR)/libraries/SPI +ifeq ($(LIQUID_TWI2), 1) +VPATH += $(ARDUINO_INSTALL_DIR)/libraries/Wire +VPATH += $(ARDUINO_INSTALL_DIR)/libraries/Wire/utility +VPATH += $(ARDUINO_INSTALL_DIR)/libraries/LiquidTWI2 +endif +ifeq ($(WIRE), 1) +VPATH += $(ARDUINO_INSTALL_DIR)/libraries/Wire +VPATH += $(ARDUINO_INSTALL_DIR)/libraries/Wire/utility +endif +else +VPATH += $(HARDWARE_DIR)/libraries/LiquidCrystal +VPATH += $(HARDWARE_DIR)/libraries/SPI +ifeq ($(LIQUID_TWI2), 1) +VPATH += $(HARDWARE_DIR)/libraries/Wire +VPATH += $(HARDWARE_DIR)/libraries/Wire/utility +VPATH += $(HARDWARE_DIR)/libraries/LiquidTWI2 +endif +ifeq ($(WIRE), 1) +VPATH += $(HARDWARE_DIR)/libraries/Wire +VPATH += $(HARDWARE_DIR)/libraries/Wire/utility +endif +endif +ifeq ($(HARDWARE_VARIANT), arduino) +HARDWARE_SUB_VARIANT ?= mega +VPATH += $(ARDUINO_INSTALL_DIR)/hardware/arduino/variants/$(HARDWARE_SUB_VARIANT) +else +HARDWARE_SUB_VARIANT ?= standard +VPATH += $(HARDWARE_DIR)/$(HARDWARE_VARIANT)/variants/$(HARDWARE_SUB_VARIANT) +endif +SRC = wiring.c \ + wiring_analog.c wiring_digital.c \ + wiring_pulse.c \ + wiring_shift.c WInterrupts.c +ifeq ($(HARDWARE_VARIANT), Teensy) +SRC = wiring.c +VPATH += $(ARDUINO_INSTALL_DIR)/hardware/teensy/cores/teensy +endif +CXXSRC = WMath.cpp WString.cpp Print.cpp Marlin_main.cpp \ + MarlinSerial.cpp Sd2Card.cpp SdBaseFile.cpp SdFatUtil.cpp \ + SdFile.cpp SdVolume.cpp motion_control.cpp planner.cpp \ + stepper.cpp temperature.cpp cardreader.cpp ConfigurationStore.cpp \ + watchdog.cpp SPI.cpp Servo.cpp Tone.cpp ultralcd.cpp digipot_mcp4451.cpp \ + vector_3.cpp qr_solve.cpp +ifeq ($(LIQUID_TWI2), 0) +CXXSRC += LiquidCrystal.cpp +else +SRC += twi.c +CXXSRC += Wire.cpp LiquidTWI2.cpp +endif + +ifeq ($(WIRE), 1) +SRC += twi.c +CXXSRC += Wire.cpp +endif + +#Check for Arduino 1.0.0 or higher and use the correct sourcefiles for that version +ifeq ($(shell [ $(ARDUINO_VERSION) -ge 100 ] && echo true), true) +CXXSRC += main.cpp +else +SRC += pins_arduino.c main.c +endif + +FORMAT = ihex + +# Name of this Makefile (used for "make depend"). +MAKEFILE = Makefile + +# Debugging format. +# Native formats for AVR-GCC's -g are stabs [default], or dwarf-2. +# AVR (extended) COFF requires stabs, plus an avr-objcopy run. +DEBUG = stabs + +OPT = s + +DEFINES ?= + +# Program settings +CC = $(AVR_TOOLS_PATH)avr-gcc +CXX = $(AVR_TOOLS_PATH)avr-g++ +OBJCOPY = $(AVR_TOOLS_PATH)avr-objcopy +OBJDUMP = $(AVR_TOOLS_PATH)avr-objdump +AR = $(AVR_TOOLS_PATH)avr-ar +SIZE = $(AVR_TOOLS_PATH)avr-size +NM = $(AVR_TOOLS_PATH)avr-nm +AVRDUDE = avrdude +REMOVE = rm -f +MV = mv -f + +# Place -D or -U options here +CDEFS = -DF_CPU=$(F_CPU) ${addprefix -D , $(DEFINES)} +CXXDEFS = $(CDEFS) + +ifeq ($(HARDWARE_VARIANT), Teensy) +CDEFS += -DUSB_SERIAL +SRC += usb.c pins_teensy.c +CXXSRC += usb_api.cpp +endif + +# Add all the source directories as include directories too +CINCS = ${addprefix -I ,${VPATH}} +CXXINCS = ${addprefix -I ,${VPATH}} + +# Compiler flag to set the C Standard level. +# c89 - "ANSI" C +# gnu89 - c89 plus GCC extensions +# c99 - ISO C99 standard (not yet fully implemented) +# gnu99 - c99 plus GCC extensions +#CSTANDARD = -std=gnu99 +CDEBUG = -g$(DEBUG) +CWARN = -Wall -Wstrict-prototypes +CTUNING = -funsigned-char -funsigned-bitfields -fpack-struct \ + -fshort-enums -w -ffunction-sections -fdata-sections \ + -DARDUINO=$(ARDUINO_VERSION) +ifneq ($(HARDWARE_MOTHERBOARD),) +CTUNING += -DMOTHERBOARD=${HARDWARE_MOTHERBOARD} +endif +#CEXTRA = -Wa,-adhlns=$(<:.c=.lst) +CEXTRA = -fno-use-cxa-atexit + +CFLAGS := $(CDEBUG) $(CDEFS) $(CINCS) -O$(OPT) $(CWARN) $(CEXTRA) $(CTUNING) +CXXFLAGS := $(CDEFS) $(CINCS) -O$(OPT) -Wall $(CEXTRA) $(CTUNING) +#ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs +LDFLAGS = -lm + + +# Programming support using avrdude. Settings and variables. +AVRDUDE_PORT = $(UPLOAD_PORT) +AVRDUDE_WRITE_FLASH = -Uflash:w:$(BUILD_DIR)/$(TARGET).hex:i +ifeq ($(shell uname -s), Linux) +AVRDUDE_CONF = $(ARDUINO_INSTALL_DIR)/hardware/tools/avrdude.conf +else +AVRDUDE_CONF = $(ARDUINO_INSTALL_DIR)/hardware/tools/avr/etc/avrdude.conf +endif +AVRDUDE_FLAGS = -q -q -D -C$(AVRDUDE_CONF) \ + -p$(MCU) -P$(AVRDUDE_PORT) -c$(AVRDUDE_PROGRAMMER) \ + -b$(UPLOAD_RATE) + +# Define all object files. +OBJ = ${patsubst %.c, $(BUILD_DIR)/%.o, ${SRC}} +OBJ += ${patsubst %.cpp, $(BUILD_DIR)/%.o, ${CXXSRC}} +OBJ += ${patsubst %.S, $(BUILD_DIR)/%.o, ${ASRC}} + +# Define all listing files. +LST = $(ASRC:.S=.lst) $(CXXSRC:.cpp=.lst) $(SRC:.c=.lst) + +# Combine all necessary flags and optional flags. +# Add target processor to flags. +ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) +ALL_CXXFLAGS = -mmcu=$(MCU) $(CXXFLAGS) +ALL_ASFLAGS = -mmcu=$(MCU) -x assembler-with-cpp $(ASFLAGS) + +# set V=1 (eg, "make V=1") to print the full commands etc. +ifneq ($V,1) + Pecho=@echo + P=@ +else + Pecho=@: + P= +endif + +# Default target. +all: sizeafter + +build: $(BUILD_DIR) elf hex + +# Creates the object directory +$(BUILD_DIR): + $P mkdir -p $(BUILD_DIR) + +elf: $(BUILD_DIR)/$(TARGET).elf +hex: $(BUILD_DIR)/$(TARGET).hex +eep: $(BUILD_DIR)/$(TARGET).eep +lss: $(BUILD_DIR)/$(TARGET).lss +sym: $(BUILD_DIR)/$(TARGET).sym + +# Program the device. +# Do not try to reset an arduino if it's not one +upload: $(BUILD_DIR)/$(TARGET).hex +ifeq (${AVRDUDE_PROGRAMMER}, arduino) + stty hup < $(UPLOAD_PORT); true +endif + $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) +ifeq (${AVRDUDE_PROGRAMMER}, arduino) + stty -hup < $(UPLOAD_PORT); true +endif + + # Display size of file. +HEXSIZE = $(SIZE) --target=$(FORMAT) $(BUILD_DIR)/$(TARGET).hex +ELFSIZE = $(SIZE) --mcu=$(MCU) -C $(BUILD_DIR)/$(TARGET).elf; \ + $(SIZE) $(BUILD_DIR)/$(TARGET).elf +sizebefore: + $P if [ -f $(BUILD_DIR)/$(TARGET).elf ]; then echo; echo $(MSG_SIZE_BEFORE); $(HEXSIZE); echo; fi + +sizeafter: build + $P if [ -f $(BUILD_DIR)/$(TARGET).elf ]; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); echo; fi + + +# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB. +COFFCONVERT=$(OBJCOPY) --debugging \ + --change-section-address .data-0x800000 \ + --change-section-address .bss-0x800000 \ + --change-section-address .noinit-0x800000 \ + --change-section-address .eeprom-0x810000 + + +coff: $(BUILD_DIR)/$(TARGET).elf + $(COFFCONVERT) -O coff-avr $(BUILD_DIR)/$(TARGET).elf $(TARGET).cof + + +extcoff: $(TARGET).elf + $(COFFCONVERT) -O coff-ext-avr $(BUILD_DIR)/$(TARGET).elf $(TARGET).cof + + +.SUFFIXES: .elf .hex .eep .lss .sym +.PRECIOUS: .o + +.elf.hex: + $(Pecho) " COPY $@" + $P $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ + +.elf.eep: + -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ + --change-section-lma .eeprom=0 -O $(FORMAT) $< $@ + +# Create extended listing file from ELF output file. +.elf.lss: + $(OBJDUMP) -h -S $< > $@ + +# Create a symbol table from ELF output file. +.elf.sym: + $(NM) -n $< > $@ + + # Link: create ELF output file from library. +$(BUILD_DIR)/$(TARGET).elf: $(OBJ) Configuration.h + $(Pecho) " CXX $@" + $P $(CC) $(ALL_CXXFLAGS) -Wl,--gc-sections -o $@ -L. $(OBJ) $(LDFLAGS) + +$(BUILD_DIR)/%.o: %.c Configuration.h Configuration_adv.h $(MAKEFILE) + $(Pecho) " CC $<" + $P $(CC) -MMD -c $(ALL_CFLAGS) $< -o $@ + +$(BUILD_DIR)/%.o: $(BUILD_DIR)/%.cpp Configuration.h Configuration_adv.h $(MAKEFILE) + $(Pecho) " CXX $<" + $P $(CXX) -MMD -c $(ALL_CXXFLAGS) $< -o $@ + +$(BUILD_DIR)/%.o: %.cpp Configuration.h Configuration_adv.h $(MAKEFILE) + $(Pecho) " CXX $<" + $P $(CXX) -MMD -c $(ALL_CXXFLAGS) $< -o $@ + + +# Target: clean project. +clean: + $(Pecho) " RM $(BUILD_DIR)/*" + $P $(REMOVE) $(BUILD_DIR)/$(TARGET).hex $(BUILD_DIR)/$(TARGET).eep $(BUILD_DIR)/$(TARGET).cof $(BUILD_DIR)/$(TARGET).elf \ + $(BUILD_DIR)/$(TARGET).map $(BUILD_DIR)/$(TARGET).sym $(BUILD_DIR)/$(TARGET).lss $(BUILD_DIR)/$(TARGET).cpp \ + $(OBJ) $(LST) $(SRC:.c=.s) $(SRC:.c=.d) $(CXXSRC:.cpp=.s) $(CXXSRC:.cpp=.d) + $(Pecho) " RMDIR $(BUILD_DIR)/" + $P rm -rf $(BUILD_DIR) + + +.PHONY: all build elf hex eep lss sym program coff extcoff clean depend sizebefore sizeafter + +# Automaticaly include the dependency files created by gcc +-include ${wildcard $(BUILD_DIR)/*.d} diff --git a/Marlin/Marlin.h b/Marlin/Marlin.h new file mode 100644 index 0000000..ad4f82b --- /dev/null +++ b/Marlin/Marlin.h @@ -0,0 +1,325 @@ +// Tonokip RepRap firmware rewrite based off of Hydra-mmm firmware. +// License: GPL + +#ifndef MARLIN_H +#define MARLIN_H + +#define FORCE_INLINE __attribute__((always_inline)) inline + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + + +#include "fastio.h" +#include "Configuration.h" + +#if (ARDUINO >= 100) + #include "Arduino.h" +#else + #include "WProgram.h" +#endif + +#define BIT(b) (1<<(b)) +#define TEST(n,b) (((n)&BIT(b))!=0) +#define RADIANS(d) ((d)*M_PI/180.0) +#define DEGREES(r) ((d)*180.0/M_PI) +#define NOLESS(v,n) do{ if (v < n) v = n; }while(0) +#define NOMORE(v,n) do{ if (v > n) v = n; }while(0) + +typedef unsigned long millis_t; + +// Arduino < 1.0.0 does not define this, so we need to do it ourselves +#ifndef analogInputToDigitalPin + #define analogInputToDigitalPin(p) ((p) + 0xA0) +#endif + +#ifdef AT90USB + #include "HardwareSerial.h" +#endif + +#include "MarlinSerial.h" + +#ifndef cbi + #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) +#endif +#ifndef sbi + #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) +#endif + +#include "WString.h" + +#ifdef AT90USB + #ifdef BTENABLED + #define MYSERIAL bt + #else + #define MYSERIAL Serial + #endif // BTENABLED +#else + #define MYSERIAL MSerial +#endif + +#define SERIAL_CHAR(x) MYSERIAL.write(x) +#define SERIAL_EOL SERIAL_CHAR('\n') + +#define SERIAL_PROTOCOLCHAR(x) SERIAL_CHAR(x) +#define SERIAL_PROTOCOL(x) MYSERIAL.print(x) +#define SERIAL_PROTOCOL_F(x,y) MYSERIAL.print(x,y) +#define SERIAL_PROTOCOLPGM(x) serialprintPGM(PSTR(x)) +#define SERIAL_PROTOCOLLN(x) do{ MYSERIAL.print(x),MYSERIAL.write('\n'); }while(0) +#define SERIAL_PROTOCOLLNPGM(x) do{ serialprintPGM(PSTR(x)),MYSERIAL.write('\n'); }while(0) + + +extern const char errormagic[] PROGMEM; +extern const char echomagic[] PROGMEM; + +#define SERIAL_ERROR_START serialprintPGM(errormagic) +#define SERIAL_ERROR(x) SERIAL_PROTOCOL(x) +#define SERIAL_ERRORPGM(x) SERIAL_PROTOCOLPGM(x) +#define SERIAL_ERRORLN(x) SERIAL_PROTOCOLLN(x) +#define SERIAL_ERRORLNPGM(x) SERIAL_PROTOCOLLNPGM(x) + +#define SERIAL_ECHO_START serialprintPGM(echomagic) +#define SERIAL_ECHO(x) SERIAL_PROTOCOL(x) +#define SERIAL_ECHOPGM(x) SERIAL_PROTOCOLPGM(x) +#define SERIAL_ECHOLN(x) SERIAL_PROTOCOLLN(x) +#define SERIAL_ECHOLNPGM(x) SERIAL_PROTOCOLLNPGM(x) + +#define SERIAL_ECHOPAIR(name,value) do{ serial_echopair_P(PSTR(name),(value)); }while(0) + +void serial_echopair_P(const char *s_P, float v); +void serial_echopair_P(const char *s_P, double v); +void serial_echopair_P(const char *s_P, unsigned long v); + + +// Things to write to serial from Program memory. Saves 400 to 2k of RAM. +FORCE_INLINE void serialprintPGM(const char *str) { + char ch; + while ((ch = pgm_read_byte(str))) { + MYSERIAL.write(ch); + str++; + } +} + +void get_command(); +void process_commands(); + +void manage_inactivity(bool ignore_stepper_queue=false); + +#if defined(DUAL_X_CARRIAGE) && HAS_X_ENABLE && HAS_X2_ENABLE + #define enable_x() do { X_ENABLE_WRITE( X_ENABLE_ON); X2_ENABLE_WRITE( X_ENABLE_ON); } while (0) + #define disable_x() do { X_ENABLE_WRITE(!X_ENABLE_ON); X2_ENABLE_WRITE(!X_ENABLE_ON); axis_known_position[X_AXIS] = false; } while (0) +#elif HAS_X_ENABLE + #define enable_x() X_ENABLE_WRITE( X_ENABLE_ON) + #define disable_x() { X_ENABLE_WRITE(!X_ENABLE_ON); axis_known_position[X_AXIS] = false; } +#else + #define enable_x() ; + #define disable_x() ; +#endif + +#if HAS_Y_ENABLE + #ifdef Y_DUAL_STEPPER_DRIVERS + #define enable_y() { Y_ENABLE_WRITE( Y_ENABLE_ON); Y2_ENABLE_WRITE(Y_ENABLE_ON); } + #define disable_y() { Y_ENABLE_WRITE(!Y_ENABLE_ON); Y2_ENABLE_WRITE(!Y_ENABLE_ON); axis_known_position[Y_AXIS] = false; } + #else + #define enable_y() Y_ENABLE_WRITE( Y_ENABLE_ON) + #define disable_y() { Y_ENABLE_WRITE(!Y_ENABLE_ON); axis_known_position[Y_AXIS] = false; } + #endif +#else + #define enable_y() ; + #define disable_y() ; +#endif + +#if HAS_Z_ENABLE + #ifdef Z_DUAL_STEPPER_DRIVERS + #define enable_z() { Z_ENABLE_WRITE( Z_ENABLE_ON); Z2_ENABLE_WRITE(Z_ENABLE_ON); } + #define disable_z() { Z_ENABLE_WRITE(!Z_ENABLE_ON); Z2_ENABLE_WRITE(!Z_ENABLE_ON); axis_known_position[Z_AXIS] = false; } + #else + #define enable_z() Z_ENABLE_WRITE( Z_ENABLE_ON) + #define disable_z() { Z_ENABLE_WRITE(!Z_ENABLE_ON); axis_known_position[Z_AXIS] = false; } + #endif +#else + #define enable_z() ; + #define disable_z() ; +#endif + +#if HAS_E0_ENABLE + #define enable_e0() E0_ENABLE_WRITE( E_ENABLE_ON) + #define disable_e0() E0_ENABLE_WRITE(!E_ENABLE_ON) +#else + #define enable_e0() /* nothing */ + #define disable_e0() /* nothing */ +#endif + +#if (EXTRUDERS > 1) && HAS_E1_ENABLE + #define enable_e1() E1_ENABLE_WRITE( E_ENABLE_ON) + #define disable_e1() E1_ENABLE_WRITE(!E_ENABLE_ON) +#else + #define enable_e1() /* nothing */ + #define disable_e1() /* nothing */ +#endif + +#if (EXTRUDERS > 2) && HAS_E2_ENABLE + #define enable_e2() E2_ENABLE_WRITE( E_ENABLE_ON) + #define disable_e2() E2_ENABLE_WRITE(!E_ENABLE_ON) +#else + #define enable_e2() /* nothing */ + #define disable_e2() /* nothing */ +#endif + +#if (EXTRUDERS > 3) && HAS_E3_ENABLE + #define enable_e3() E3_ENABLE_WRITE( E_ENABLE_ON) + #define disable_e3() E3_ENABLE_WRITE(!E_ENABLE_ON) +#else + #define enable_e3() /* nothing */ + #define disable_e3() /* nothing */ +#endif + +/** + * The axis order in all axis related arrays is X, Y, Z, E + */ +#define NUM_AXIS 4 + +/** + * Axis indices as enumerated constants + * + * A_AXIS and B_AXIS are used by COREXY printers + * X_HEAD and Y_HEAD is used for systems that don't have a 1:1 relationship between X_AXIS and X Head movement, like CoreXY bots. + */ +enum AxisEnum {X_AXIS=0, Y_AXIS=1, A_AXIS=0, B_AXIS=1, Z_AXIS=2, E_AXIS=3, X_HEAD=4, Y_HEAD=5}; + +void enable_all_steppers(); +void disable_all_steppers(); + +void FlushSerialRequestResend(); +void ClearToSend(); + +void get_coordinates(); +#ifdef DELTA + void calculate_delta(float cartesian[3]); + #ifdef ENABLE_AUTO_BED_LEVELING + extern int delta_grid_spacing[2]; + void adjust_delta(float cartesian[3]); + #endif + extern float delta[3]; +#endif +#ifdef SCARA + void calculate_delta(float cartesian[3]); + void calculate_SCARA_forward_Transform(float f_scara[3]); +#endif +void reset_bed_level(); +void prepare_move(); +void kill(); +void Stop(); + +#ifdef FILAMENT_RUNOUT_SENSOR + void filrunout(); +#endif + +extern bool Running; +inline bool IsRunning() { return Running; } +inline bool IsStopped() { return !Running; } + +bool enqueuecommand(const char *cmd); //put a single ASCII command at the end of the current buffer or return false when it is full +void enqueuecommands_P(const char *cmd); //put one or many ASCII commands at the end of the current buffer, read from flash + +void prepare_arc_move(char isclockwise); +void clamp_to_software_endstops(float target[3]); + +extern millis_t previous_cmd_ms; +inline void refresh_cmd_timeout() { previous_cmd_ms = millis(); } + +#ifdef FAST_PWM_FAN + void setPwmFrequency(uint8_t pin, int val); +#endif + +#ifndef CRITICAL_SECTION_START + #define CRITICAL_SECTION_START unsigned char _sreg = SREG; cli(); + #define CRITICAL_SECTION_END SREG = _sreg; +#endif + +extern float homing_feedrate[]; +extern bool axis_relative_modes[]; +extern int feedmultiply; +extern bool volumetric_enabled; +extern int extruder_multiply[EXTRUDERS]; // sets extrude multiply factor (in percent) for each extruder individually +extern float filament_size[EXTRUDERS]; // cross-sectional area of filament (in millimeters), typically around 1.75 or 2.85, 0 disables the volumetric calculations for the extruder. +extern float volumetric_multiplier[EXTRUDERS]; // reciprocal of cross-sectional area of filament (in square millimeters), stored this way to reduce computational burden in planner +extern float current_position[NUM_AXIS]; +extern float home_offset[3]; + +#ifdef DELTA + extern float endstop_adj[3]; + extern float delta_radius; + extern float delta_diagonal_rod; + extern float delta_segments_per_second; + void recalc_delta_settings(float radius, float diagonal_rod); +#elif defined(Z_DUAL_ENDSTOPS) + extern float z_endstop_adj; +#endif + +#ifdef SCARA + extern float axis_scaling[3]; // Build size scaling +#endif + +extern float min_pos[3]; +extern float max_pos[3]; +extern bool axis_known_position[3]; + +#ifdef ENABLE_AUTO_BED_LEVELING + extern float zprobe_zoffset; +#endif + +#ifdef PREVENT_DANGEROUS_EXTRUDE + extern float extrude_min_temp; +#endif + +extern int fanSpeed; + +#ifdef BARICUDA + extern int ValvePressure; + extern int EtoPPressure; +#endif + +#ifdef FAN_SOFT_PWM + extern unsigned char fanSpeedSoftPwm; +#endif + +#ifdef FILAMENT_SENSOR + extern float filament_width_nominal; //holds the theoretical filament diameter ie., 3.00 or 1.75 + extern bool filament_sensor; //indicates that filament sensor readings should control extrusion + extern float filament_width_meas; //holds the filament diameter as accurately measured + extern signed char measurement_delay[]; //ring buffer to delay measurement + extern int delay_index1, delay_index2; //ring buffer index. used by planner, temperature, and main code + extern float delay_dist; //delay distance counter + extern int meas_delay_cm; //delay distance +#endif + +#ifdef FWRETRACT + extern bool autoretract_enabled; + extern bool retracted[EXTRUDERS]; + extern float retract_length, retract_length_swap, retract_feedrate, retract_zlift; + extern float retract_recover_length, retract_recover_length_swap, retract_recover_feedrate; +#endif + +extern millis_t starttime; +extern millis_t stoptime; + +// Handling multiple extruders pins +extern uint8_t active_extruder; + +#ifdef DIGIPOT_I2C + extern void digipot_i2c_set_current( int channel, float current ); + extern void digipot_i2c_init(); +#endif + +extern void calculate_volumetric_multipliers(); + +#endif //MARLIN_H diff --git a/Marlin/Marlin.ino b/Marlin/Marlin.ino new file mode 100644 index 0000000..9eae6d4 --- /dev/null +++ b/Marlin/Marlin.ino @@ -0,0 +1,56 @@ +/* -*- c++ -*- */ + +/* + Reprap firmware based on Sprinter and grbl. + Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + */ + +/* + This firmware is a mashup between Sprinter and grbl. + (https://github.com/kliment/Sprinter) + (https://github.com/simen/grbl/tree) + + It has preliminary support for Matthew Roberts advance algorithm + http://reprap.org/pipermail/reprap-dev/2011-May/003323.html + */ + +/* All the implementation is done in *.cpp files to get better compatibility with avr-gcc without the Arduino IDE */ +/* Use this file to help the Arduino IDE find which Arduino libraries are needed and to keep documentation on GCode */ + +#include "Configuration.h" +#include "pins.h" + +#ifdef ULTRA_LCD + #if defined(LCD_I2C_TYPE_PCF8575) + #include + #include + #elif defined(LCD_I2C_TYPE_MCP23017) || defined(LCD_I2C_TYPE_MCP23008) + #include + #include + #elif defined(DOGLCD) + #include // library for graphics LCD by Oli Kraus (https://code.google.com/p/u8glib/) + #else + #include // library for character LCD + #endif +#endif + +#if HAS_DIGIPOTSS + #include +#endif + +#if defined(DIGIPOT_I2C) + #include +#endif diff --git a/Marlin/MarlinSerial.cpp b/Marlin/MarlinSerial.cpp new file mode 100644 index 0000000..dc36e14 --- /dev/null +++ b/Marlin/MarlinSerial.cpp @@ -0,0 +1,292 @@ +/* + HardwareSerial.cpp - Hardware serial library for Wiring + Copyright (c) 2006 Nicholas Zambetti. 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 + + Modified 23 November 2006 by David A. Mellis + Modified 28 September 2010 by Mark Sproul +*/ + +#include "Marlin.h" +#include "MarlinSerial.h" + +#ifndef AT90USB +// this next line disables the entire HardwareSerial.cpp, +// this is so I can support Attiny series and any other chip without a UART +#if defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H) + +#if UART_PRESENT(SERIAL_PORT) + ring_buffer rx_buffer = { { 0 }, 0, 0 }; +#endif + +FORCE_INLINE void store_char(unsigned char c) { + int i = (unsigned int)(rx_buffer.head + 1) % RX_BUFFER_SIZE; + + // if we should be storing the received character into the location + // just before the tail (meaning that the head would advance to the + // current location of the tail), we're about to overflow the buffer + // and so we don't write the character or advance the head. + if (i != rx_buffer.tail) { + rx_buffer.buffer[rx_buffer.head] = c; + rx_buffer.head = i; + } +} + + +//#elif defined(SIG_USART_RECV) +#if defined(M_USARTx_RX_vect) + // fixed by Mark Sproul this is on the 644/644p + //SIGNAL(SIG_USART_RECV) + SIGNAL(M_USARTx_RX_vect) { + unsigned char c = M_UDRx; + store_char(c); + } +#endif + +// Constructors //////////////////////////////////////////////////////////////// + +MarlinSerial::MarlinSerial() { } + +// Public Methods ////////////////////////////////////////////////////////////// + +void MarlinSerial::begin(long baud) { + uint16_t baud_setting; + bool useU2X = true; + + #if F_CPU == 16000000UL && SERIAL_PORT == 0 + // hard-coded exception for compatibility with the bootloader shipped + // with the Duemilanove and previous boards and the firmware on the 8U2 + // on the Uno and Mega 2560. + if (baud == 57600) { + useU2X = false; + } + #endif + + if (useU2X) { + M_UCSRxA = BIT(M_U2Xx); + baud_setting = (F_CPU / 4 / baud - 1) / 2; + } else { + M_UCSRxA = 0; + baud_setting = (F_CPU / 8 / baud - 1) / 2; + } + + // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) + M_UBRRxH = baud_setting >> 8; + M_UBRRxL = baud_setting; + + sbi(M_UCSRxB, M_RXENx); + sbi(M_UCSRxB, M_TXENx); + sbi(M_UCSRxB, M_RXCIEx); +} + +void MarlinSerial::end() { + cbi(M_UCSRxB, M_RXENx); + cbi(M_UCSRxB, M_TXENx); + cbi(M_UCSRxB, M_RXCIEx); +} + + +int MarlinSerial::peek(void) { + if (rx_buffer.head == rx_buffer.tail) { + return -1; + } else { + return rx_buffer.buffer[rx_buffer.tail]; + } +} + +int MarlinSerial::read(void) { + // if the head isn't ahead of the tail, we don't have any characters + if (rx_buffer.head == rx_buffer.tail) { + return -1; + } + else { + unsigned char c = rx_buffer.buffer[rx_buffer.tail]; + rx_buffer.tail = (unsigned int)(rx_buffer.tail + 1) % RX_BUFFER_SIZE; + return c; + } +} + +void MarlinSerial::flush() { + // don't reverse this or there may be problems if the RX interrupt + // occurs after reading the value of rx_buffer_head but before writing + // the value to rx_buffer_tail; the previous value of rx_buffer_head + // may be written to rx_buffer_tail, making it appear as if the buffer + // don't reverse this or there may be problems if the RX interrupt + // occurs after reading the value of rx_buffer_head but before writing + // the value to rx_buffer_tail; the previous value of rx_buffer_head + // may be written to rx_buffer_tail, making it appear as if the buffer + // were full, not empty. + rx_buffer.head = rx_buffer.tail; +} + + +/// imports from print.h + + +void MarlinSerial::print(char c, int base) { + print((long) c, base); +} + +void MarlinSerial::print(unsigned char b, int base) { + print((unsigned long) b, base); +} + +void MarlinSerial::print(int n, int base) { + print((long) n, base); +} + +void MarlinSerial::print(unsigned int n, int base) { + print((unsigned long) n, base); +} + +void MarlinSerial::print(long n, int base) { + if (base == 0) { + write(n); + } + else if (base == 10) { + if (n < 0) { + print('-'); + n = -n; + } + printNumber(n, 10); + } else { + printNumber(n, base); + } +} + +void MarlinSerial::print(unsigned long n, int base) { + if (base == 0) write(n); + else printNumber(n, base); +} + +void MarlinSerial::print(double n, int digits) { + printFloat(n, digits); +} + +void MarlinSerial::println(void) { + print('\r'); + print('\n'); +} + +void MarlinSerial::println(const String &s) { + print(s); + println(); +} + +void MarlinSerial::println(const char c[]) { + print(c); + println(); +} + +void MarlinSerial::println(char c, int base) { + print(c, base); + println(); +} + +void MarlinSerial::println(unsigned char b, int base) { + print(b, base); + println(); +} + +void MarlinSerial::println(int n, int base) { + print(n, base); + println(); +} + +void MarlinSerial::println(unsigned int n, int base) { + print(n, base); + println(); +} + +void MarlinSerial::println(long n, int base) { + print(n, base); + println(); +} + +void MarlinSerial::println(unsigned long n, int base) { + print(n, base); + println(); +} + +void MarlinSerial::println(double n, int digits) { + print(n, digits); + println(); +} + +// Private Methods ///////////////////////////////////////////////////////////// + +void MarlinSerial::printNumber(unsigned long n, uint8_t base) { + unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars. + unsigned long i = 0; + + if (n == 0) { + print('0'); + return; + } + + while (n > 0) { + buf[i++] = n % base; + n /= base; + } + + for (; i > 0; i--) + print((char) (buf[i - 1] < 10 ? + '0' + buf[i - 1] : + 'A' + buf[i - 1] - 10)); +} + +void MarlinSerial::printFloat(double number, uint8_t digits) { + // Handle negative numbers + if (number < 0.0) { + print('-'); + number = -number; + } + + // Round correctly so that print(1.999, 2) prints as "2.00" + double rounding = 0.5; + for (uint8_t i = 0; i < digits; ++i) + rounding /= 10.0; + + number += rounding; + + // Extract the integer part of the number and print it + unsigned long int_part = (unsigned long)number; + double remainder = number - (double)int_part; + print(int_part); + + // Print the decimal point, but only if there are digits beyond + if (digits > 0) print('.'); + + // Extract digits from the remainder one at a time + while (digits-- > 0) { + remainder *= 10.0; + int toPrint = int(remainder); + print(toPrint); + remainder -= toPrint; + } +} +// Preinstantiate Objects ////////////////////////////////////////////////////// + + +MarlinSerial MSerial; + +#endif // whole file +#endif // !AT90USB + +// For AT90USB targets use the UART for BT interfacing +#if defined(AT90USB) && defined(BTENABLED) + HardwareSerial bt; +#endif diff --git a/Marlin/MarlinSerial.h b/Marlin/MarlinSerial.h new file mode 100644 index 0000000..dbad3fd --- /dev/null +++ b/Marlin/MarlinSerial.h @@ -0,0 +1,160 @@ +/* + HardwareSerial.h - Hardware serial library for Wiring + Copyright (c) 2006 Nicholas Zambetti. 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 + + Modified 28 September 2010 by Mark Sproul +*/ + +#ifndef MarlinSerial_h +#define MarlinSerial_h +#include "Marlin.h" + +#ifndef SERIAL_PORT + #define SERIAL_PORT 0 +#endif + +// The presence of the UBRRH register is used to detect a UART. +#define UART_PRESENT(port) ((port == 0 && (defined(UBRRH) || defined(UBRR0H))) || \ + (port == 1 && defined(UBRR1H)) || (port == 2 && defined(UBRR2H)) || \ + (port == 3 && defined(UBRR3H))) + +// These are macros to build serial port register names for the selected SERIAL_PORT (C preprocessor +// requires two levels of indirection to expand macro values properly) +#define SERIAL_REGNAME(registerbase,number,suffix) SERIAL_REGNAME_INTERNAL(registerbase,number,suffix) +#if SERIAL_PORT == 0 && (!defined(UBRR0H) || !defined(UDR0)) // use un-numbered registers if necessary + #define SERIAL_REGNAME_INTERNAL(registerbase,number,suffix) registerbase##suffix +#else + #define SERIAL_REGNAME_INTERNAL(registerbase,number,suffix) registerbase##number##suffix +#endif + +// Registers used by MarlinSerial class (these are expanded +// depending on selected serial port +#define M_UCSRxA SERIAL_REGNAME(UCSR,SERIAL_PORT,A) // defines M_UCSRxA to be UCSRnA where n is the serial port number +#define M_UCSRxB SERIAL_REGNAME(UCSR,SERIAL_PORT,B) +#define M_RXENx SERIAL_REGNAME(RXEN,SERIAL_PORT,) +#define M_TXENx SERIAL_REGNAME(TXEN,SERIAL_PORT,) +#define M_RXCIEx SERIAL_REGNAME(RXCIE,SERIAL_PORT,) +#define M_UDREx SERIAL_REGNAME(UDRE,SERIAL_PORT,) +#define M_UDRx SERIAL_REGNAME(UDR,SERIAL_PORT,) +#define M_UBRRxH SERIAL_REGNAME(UBRR,SERIAL_PORT,H) +#define M_UBRRxL SERIAL_REGNAME(UBRR,SERIAL_PORT,L) +#define M_RXCx SERIAL_REGNAME(RXC,SERIAL_PORT,) +#define M_USARTx_RX_vect SERIAL_REGNAME(USART,SERIAL_PORT,_RX_vect) +#define M_U2Xx SERIAL_REGNAME(U2X,SERIAL_PORT,) + + +#define DEC 10 +#define HEX 16 +#define OCT 8 +#define BIN 2 +#define BYTE 0 + + +#ifndef AT90USB +// Define constants and variables for buffering incoming serial data. We're +// using a ring buffer (I think), in which rx_buffer_head is the index of the +// location to which to write the next incoming character and rx_buffer_tail +// is the index of the location from which to read. +#define RX_BUFFER_SIZE 128 + + +struct ring_buffer { + unsigned char buffer[RX_BUFFER_SIZE]; + int head; + int tail; +}; + +#if UART_PRESENT(SERIAL_PORT) + extern ring_buffer rx_buffer; +#endif + +class MarlinSerial { //: public Stream + + public: + MarlinSerial(); + void begin(long); + void end(); + int peek(void); + int read(void); + void flush(void); + + FORCE_INLINE int available(void) { + return (unsigned int)(RX_BUFFER_SIZE + rx_buffer.head - rx_buffer.tail) % RX_BUFFER_SIZE; + } + + FORCE_INLINE void write(uint8_t c) { + while (!TEST(M_UCSRxA, M_UDREx)) + ; + + M_UDRx = c; + } + + FORCE_INLINE void checkRx(void) { + if (TEST(M_UCSRxA, M_RXCx)) { + unsigned char c = M_UDRx; + int i = (unsigned int)(rx_buffer.head + 1) % RX_BUFFER_SIZE; + + // if we should be storing the received character into the location + // just before the tail (meaning that the head would advance to the + // current location of the tail), we're about to overflow the buffer + // and so we don't write the character or advance the head. + if (i != rx_buffer.tail) { + rx_buffer.buffer[rx_buffer.head] = c; + rx_buffer.head = i; + } + } + } + + private: + void printNumber(unsigned long, uint8_t); + void printFloat(double, uint8_t); + + public: + FORCE_INLINE void write(const char *str) { while (*str) write(*str++); } + FORCE_INLINE void write(const uint8_t *buffer, size_t size) { while (size--) write(*buffer++); } + FORCE_INLINE void print(const String &s) { for (int i = 0; i < (int)s.length(); i++) write(s[i]); } + FORCE_INLINE void print(const char *str) { write(str); } + + void print(char, int = BYTE); + void print(unsigned char, int = BYTE); + void print(int, int = DEC); + void print(unsigned int, int = DEC); + void print(long, int = DEC); + void print(unsigned long, int = DEC); + void print(double, int = 2); + + void println(const String &s); + void println(const char[]); + void println(char, int = BYTE); + void println(unsigned char, int = BYTE); + void println(int, int = DEC); + void println(unsigned int, int = DEC); + void println(long, int = DEC); + void println(unsigned long, int = DEC); + void println(double, int = 2); + void println(void); +}; + +extern MarlinSerial MSerial; +#endif // !AT90USB + +// Use the UART for BT in AT90USB configurations +#if defined(AT90USB) && defined(BTENABLED) + extern HardwareSerial bt; +#endif + +#endif diff --git a/Marlin/Marlin_main.cpp b/Marlin/Marlin_main.cpp new file mode 100644 index 0000000..94c4c7b --- /dev/null +++ b/Marlin/Marlin_main.cpp @@ -0,0 +1,6052 @@ +/* -*- c++ -*- */ + +/* + Reprap firmware based on Sprinter and grbl. + Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + */ + +/* + This firmware is a mashup between Sprinter and grbl. + (https://github.com/kliment/Sprinter) + (https://github.com/simen/grbl/tree) + + It has preliminary support for Matthew Roberts advance algorithm + http://reprap.org/pipermail/reprap-dev/2011-May/003323.html + */ + +#include "Marlin.h" + +#ifdef ENABLE_AUTO_BED_LEVELING + #include "vector_3.h" + #ifdef AUTO_BED_LEVELING_GRID + #include "qr_solve.h" + #endif +#endif // ENABLE_AUTO_BED_LEVELING + +#define SERVO_LEVELING (defined(ENABLE_AUTO_BED_LEVELING) && PROBE_SERVO_DEACTIVATION_DELAY > 0) + +#ifdef MESH_BED_LEVELING + #include "mesh_bed_leveling.h" +#endif + +#include "ultralcd.h" +#include "planner.h" +#include "stepper.h" +#include "temperature.h" +#include "motion_control.h" +#include "cardreader.h" +#include "watchdog.h" +#include "ConfigurationStore.h" +#include "language.h" +#include "pins_arduino.h" +#include "math.h" + +#ifdef BLINKM + #include "BlinkM.h" + #include "Wire.h" +#endif + +#if NUM_SERVOS > 0 + #include "Servo.h" +#endif + +#if HAS_DIGIPOTSS + #include +#endif + +// look here for descriptions of G-codes: http://linuxcnc.org/handbook/gcode/g-code.html +// http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes + +//Implemented Codes +//------------------- +// G0 -> G1 +// G1 - Coordinated Movement X Y Z E +// G2 - CW ARC +// G3 - CCW ARC +// G4 - Dwell S or P +// G10 - retract filament according to settings of M207 +// G11 - retract recover filament according to settings of M208 +// G28 - Home one or more axes +// G29 - Detailed Z-Probe, probes the bed at 3 or more points. Will fail if you haven't homed yet. +// G30 - Single Z Probe, probes bed at current XY location. +// G31 - Dock sled (Z_PROBE_SLED only) +// G32 - Undock sled (Z_PROBE_SLED only) +// G90 - Use Absolute Coordinates +// G91 - Use Relative Coordinates +// G92 - Set current position to coordinates given + +// M Codes +// M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled) +// M1 - Same as M0 +// M17 - Enable/Power all stepper motors +// M18 - Disable all stepper motors; same as M84 +// M20 - List SD card +// M21 - Init SD card +// M22 - Release SD card +// M23 - Select SD file (M23 filename.g) +// M24 - Start/resume SD print +// M25 - Pause SD print +// M26 - Set SD position in bytes (M26 S12345) +// M27 - Report SD print status +// M28 - Start SD write (M28 filename.g) +// M29 - Stop SD write +// M30 - Delete file from SD (M30 filename.g) +// M31 - Output time since last M109 or SD card start to serial +// M32 - Select file and start SD print (Can be used _while_ printing from SD card files): +// syntax "M32 /path/filename#", or "M32 S !filename#" +// Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include). +// The '#' is necessary when calling from within sd files, as it stops buffer prereading +// M42 - Change pin status via gcode Use M42 Px Sy to set pin x to value y, when omitting Px the onboard led will be used. +// M48 - Measure Z_Probe repeatability. M48 [n # of points] [X position] [Y position] [V_erboseness #] [E_ngage Probe] [L # of legs of travel] +// M80 - Turn on Power Supply +// M81 - Turn off Power Supply +// M82 - Set E codes absolute (default) +// M83 - Set E codes relative while in Absolute Coordinates (G90) mode +// M84 - Disable steppers until next move, +// or use S to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout. +// M85 - Set inactivity shutdown timer with parameter S. To disable set zero (default) +// M92 - Set axis_steps_per_unit - same syntax as G92 +// M104 - Set extruder target temp +// M105 - Read current temp +// M106 - Fan on +// M107 - Fan off +// M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating +// Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling +// IF AUTOTEMP is enabled, S B F. Exit autotemp by any M109 without F +// M112 - Emergency stop +// M114 - Output current position to serial port +// M115 - Capabilities string +// M117 - display message +// M119 - Output Endstop status to serial port +// M120 - Enable endstop detection +// M121 - Disable endstop detection +// M126 - Solenoid Air Valve Open (BariCUDA support by jmil) +// M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil) +// M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil) +// M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil) +// M140 - Set bed target temp +// M150 - Set BlinkM Color Output R: Red<0-255> U(!): Green<0-255> B: Blue<0-255> over i2c, G for green does not work. +// M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating +// Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling +// M200 - set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters).:D- +// M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000) +// M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!! +// M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec +// M204 - Set default acceleration: P for Printing moves, R for Retract only (no X, Y, Z) moves and T for Travel (non printing) moves (ex. M204 P800 T3000 R9000) in mm/sec^2 +// M205 - advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk, E=maximum E jerk +// M206 - Set additional homing offset +// M207 - Set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop], stays in mm regardless of M200 setting +// M208 - Set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec] +// M209 - S<1=true/0=false> enable automatic retract detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction. +// M218 - Set hotend offset (in mm): T X Y +// M220 - Set speed factor override percentage: S +// M221 - Set extrude factor override percentage: S +// M226 - Wait until the specified pin reaches the state required: P S +// M240 - Trigger a camera to take a photograph +// M250 - Set LCD contrast C (value 0..63) +// M280 - Set servo position absolute. P: servo index, S: angle or microseconds +// M300 - Play beep sound S P +// M301 - Set PID parameters P I and D +// M302 - Allow cold extrudes, or set the minimum extrude S. +// M303 - PID relay autotune S sets the target temperature. (default target temperature = 150C) +// M304 - Set bed PID parameters P I and D +// M380 - Activate solenoid on active extruder +// M381 - Disable all solenoids +// M400 - Finish all moves +// M401 - Lower z-probe if present +// M402 - Raise z-probe if present +// M404 - N Enter the nominal filament width (3mm, 1.75mm ) or will display nominal filament width without parameters +// M405 - Turn on Filament Sensor extrusion control. Optional D to set delay in centimeters between sensor and extruder +// M406 - Turn off Filament Sensor extrusion control +// M407 - Display measured filament diameter +// M500 - Store parameters in EEPROM +// M501 - Read parameters from EEPROM (if you need reset them after you changed them temporarily). +// M502 - Revert to the default "factory settings". You still need to store them in EEPROM afterwards if you want to. +// M503 - Print the current settings (from memory not from EEPROM). Use S0 to leave off headings. +// M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED) +// M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal] +// M665 - Set delta configurations: L R S +// M666 - Set delta endstop adjustment +// M605 - Set dual x-carriage movement mode: S [ X R ] +// M907 - Set digital trimpot motor current using axis codes. +// M908 - Control digital trimpot directly. +// M350 - Set microstepping mode. +// M351 - Toggle MS1 MS2 pins directly. + +// ************ SCARA Specific - This can change to suit future G-code regulations +// M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration) +// M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree) +// M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration) +// M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree) +// M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position) +// M365 - SCARA calibration: Scaling factor, X, Y, Z axis +//************* SCARA End *************** + +// M928 - Start SD logging (M928 filename.g) - ended by M29 +// M999 - Restart after being stopped by error + +#ifdef SDSUPPORT + CardReader card; +#endif + +bool Running = true; + +static float feedrate = 1500.0, next_feedrate, saved_feedrate; +float current_position[NUM_AXIS] = { 0.0 }; +static float destination[NUM_AXIS] = { 0.0 }; +bool axis_known_position[3] = { false }; + +static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0; +static char cmdbuffer[BUFSIZE][MAX_CMD_SIZE]; + +float homing_feedrate[] = HOMING_FEEDRATE; +bool axis_relative_modes[] = AXIS_RELATIVE_MODES; +int feedmultiply = 100; //100->1 200->2 +int saved_feedmultiply; +int extruder_multiply[EXTRUDERS] = ARRAY_BY_EXTRUDERS(100, 100, 100, 100); +bool volumetric_enabled = false; +float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS(DEFAULT_NOMINAL_FILAMENT_DIA, DEFAULT_NOMINAL_FILAMENT_DIA, DEFAULT_NOMINAL_FILAMENT_DIA, DEFAULT_NOMINAL_FILAMENT_DIA); +float volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS(1.0, 1.0, 1.0, 1.0); +float home_offset[3] = { 0 }; +float min_pos[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS }; +float max_pos[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS }; + +uint8_t active_extruder = 0; +int fanSpeed = 0; +bool cancel_heatup = false; + +const char errormagic[] PROGMEM = "Error:"; +const char echomagic[] PROGMEM = "echo:"; +const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'}; + +static float offset[3] = { 0 }; +static bool relative_mode = false; //Determines Absolute or Relative Coordinates +static int bufindr = 0; +static int bufindw = 0; +static int buflen = 0; +static char serial_char; +static int serial_count = 0; +static boolean comment_mode = false; +static char *strchr_pointer; ///< A pointer to find chars in the command string (X, Y, Z, E, etc.) +const char* queued_commands_P= NULL; /* pointer to the current line in the active sequence of commands, or NULL when none */ +const int sensitive_pins[] = SENSITIVE_PINS; ///< Sensitive pin list for M42 +// Inactivity shutdown +millis_t previous_cmd_ms = 0; +static millis_t max_inactive_time = 0; +static millis_t stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME * 1000L; +millis_t starttime = 0; ///< Print job start time +millis_t stoptime = 0; ///< Print job stop time +static uint8_t target_extruder; +bool CooldownNoWait = true; +bool target_direction; + +#ifdef ENABLE_AUTO_BED_LEVELING + int xy_travel_speed = XY_TRAVEL_SPEED; + float zprobe_zoffset = -Z_PROBE_OFFSET_FROM_EXTRUDER; +#endif + +#if defined(Z_DUAL_ENDSTOPS) && !defined(DELTA) + float z_endstop_adj = 0; +#endif + +// Extruder offsets +#if EXTRUDERS > 1 + #ifndef EXTRUDER_OFFSET_X + #define EXTRUDER_OFFSET_X { 0 } + #endif + #ifndef EXTRUDER_OFFSET_Y + #define EXTRUDER_OFFSET_Y { 0 } + #endif + float extruder_offset[][EXTRUDERS] = { + EXTRUDER_OFFSET_X, + EXTRUDER_OFFSET_Y + #ifdef DUAL_X_CARRIAGE + , { 0 } // supports offsets in XYZ plane + #endif + }; +#endif + +#ifdef SERVO_ENDSTOPS + int servo_endstops[] = SERVO_ENDSTOPS; + int servo_endstop_angles[] = SERVO_ENDSTOP_ANGLES; +#endif + +#ifdef BARICUDA + int ValvePressure = 0; + int EtoPPressure = 0; +#endif + +#ifdef FWRETRACT + + bool autoretract_enabled = false; + bool retracted[EXTRUDERS] = { false }; + bool retracted_swap[EXTRUDERS] = { false }; + + float retract_length = RETRACT_LENGTH; + float retract_length_swap = RETRACT_LENGTH_SWAP; + float retract_feedrate = RETRACT_FEEDRATE; + float retract_zlift = RETRACT_ZLIFT; + float retract_recover_length = RETRACT_RECOVER_LENGTH; + float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP; + float retract_recover_feedrate = RETRACT_RECOVER_FEEDRATE; + +#endif // FWRETRACT + +#if defined(ULTIPANEL) && HAS_POWER_SWITCH + bool powersupply = + #ifdef PS_DEFAULT_OFF + false + #else + true + #endif + ; +#endif + +#ifdef DELTA + float delta[3] = { 0 }; + #define SIN_60 0.8660254037844386 + #define COS_60 0.5 + float endstop_adj[3] = { 0 }; + // these are the default values, can be overriden with M665 + float delta_radius = DELTA_RADIUS; + float delta_tower1_x = -SIN_60 * delta_radius; // front left tower + float delta_tower1_y = -COS_60 * delta_radius; + float delta_tower2_x = SIN_60 * delta_radius; // front right tower + float delta_tower2_y = -COS_60 * delta_radius; + float delta_tower3_x = 0; // back middle tower + float delta_tower3_y = delta_radius; + float delta_diagonal_rod = DELTA_DIAGONAL_ROD; + float delta_diagonal_rod_2 = sq(delta_diagonal_rod); + float delta_segments_per_second = DELTA_SEGMENTS_PER_SECOND; + #ifdef ENABLE_AUTO_BED_LEVELING + int delta_grid_spacing[2] = { 0, 0 }; + float bed_level[AUTO_BED_LEVELING_GRID_POINTS][AUTO_BED_LEVELING_GRID_POINTS]; + #endif +#else + static bool home_all_axis = true; +#endif + +#ifdef SCARA + static float delta[3] = { 0 }; + float axis_scaling[3] = { 1, 1, 1 }; // Build size scaling, default to 1 +#endif + +#ifdef FILAMENT_SENSOR + //Variables for Filament Sensor input + float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA; //Set nominal filament width, can be changed with M404 + bool filament_sensor = false; //M405 turns on filament_sensor control, M406 turns it off + float filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; //Stores the measured filament diameter + signed char measurement_delay[MAX_MEASUREMENT_DELAY+1]; //ring buffer to delay measurement store extruder factor after subtracting 100 + int delay_index1 = 0; //index into ring buffer + int delay_index2 = -1; //index into ring buffer - set to -1 on startup to indicate ring buffer needs to be initialized + float delay_dist = 0; //delay distance counter + int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting +#endif + +#ifdef FILAMENT_RUNOUT_SENSOR + static bool filrunoutEnqued = false; +#endif + +#ifdef SDSUPPORT + static bool fromsd[BUFSIZE]; +#endif + +#if NUM_SERVOS > 0 + Servo servos[NUM_SERVOS]; +#endif + +#ifdef CHDK + unsigned long chdkHigh = 0; + boolean chdkActive = false; +#endif + +//=========================================================================== +//================================ Functions ================================ +//=========================================================================== + +void get_arc_coordinates(); +bool setTargetedHotend(int code); + +void serial_echopair_P(const char *s_P, float v) { serialprintPGM(s_P); SERIAL_ECHO(v); } +void serial_echopair_P(const char *s_P, double v) { serialprintPGM(s_P); SERIAL_ECHO(v); } +void serial_echopair_P(const char *s_P, unsigned long v) { serialprintPGM(s_P); SERIAL_ECHO(v); } + +#ifdef PREVENT_DANGEROUS_EXTRUDE + float extrude_min_temp = EXTRUDE_MINTEMP; +#endif + +#ifdef SDSUPPORT + #include "SdFatUtil.h" + int freeMemory() { return SdFatUtil::FreeRam(); } +#else + extern "C" { + extern unsigned int __bss_end; + extern unsigned int __heap_start; + extern void *__brkval; + + int freeMemory() { + int free_memory; + + if ((int)__brkval == 0) + free_memory = ((int)&free_memory) - ((int)&__bss_end); + else + free_memory = ((int)&free_memory) - ((int)__brkval); + + return free_memory; + } + } +#endif //!SDSUPPORT + +//Injects the next command from the pending sequence of commands, when possible +//Return false if and only if no command was pending +static bool drain_queued_commands_P() { + if (!queued_commands_P) return false; + + // Get the next 30 chars from the sequence of gcodes to run + char cmd[30]; + strncpy_P(cmd, queued_commands_P, sizeof(cmd) - 1); + cmd[sizeof(cmd) - 1] = '\0'; + + // Look for the end of line, or the end of sequence + size_t i = 0; + char c; + while((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command + cmd[i] = '\0'; + if (enqueuecommand(cmd)) { // buffer was not full (else we will retry later) + if (c) + queued_commands_P += i + 1; // move to next command + else + queued_commands_P = NULL; // will have no more commands in the sequence + } + return true; +} + +//Record one or many commands to run from program memory. +//Aborts the current queue, if any. +//Note: drain_queued_commands_P() must be called repeatedly to drain the commands afterwards +void enqueuecommands_P(const char* pgcode) { + queued_commands_P = pgcode; + drain_queued_commands_P(); // first command executed asap (when possible) +} + +//adds a single command to the main command buffer, from RAM +//that is really done in a non-safe way. +//needs overworking someday +//Returns false if it failed to do so +bool enqueuecommand(const char *cmd) +{ + if(*cmd==';') + return false; + if(buflen >= BUFSIZE) + return false; + //this is dangerous if a mixing of serial and this happens + strcpy(&(cmdbuffer[bufindw][0]),cmd); + SERIAL_ECHO_START; + SERIAL_ECHOPGM(MSG_Enqueing); + SERIAL_ECHO(cmdbuffer[bufindw]); + SERIAL_ECHOLNPGM("\""); + bufindw= (bufindw + 1)%BUFSIZE; + buflen += 1; + return true; +} + +void setup_killpin() +{ + #if HAS_KILL + SET_INPUT(KILL_PIN); + WRITE(KILL_PIN, HIGH); + #endif +} + +void setup_filrunoutpin() +{ + #if HAS_FILRUNOUT + pinMode(FILRUNOUT_PIN, INPUT); + #ifdef ENDSTOPPULLUP_FIL_RUNOUT + WRITE(FILLRUNOUT_PIN, HIGH); + #endif + #endif +} + +// Set home pin +void setup_homepin(void) +{ + #if HAS_HOME + SET_INPUT(HOME_PIN); + WRITE(HOME_PIN, HIGH); + #endif +} + + +void setup_photpin() +{ + #if HAS_PHOTOGRAPH + OUT_WRITE(PHOTOGRAPH_PIN, LOW); + #endif +} + +void setup_powerhold() +{ + #if HAS_SUICIDE + OUT_WRITE(SUICIDE_PIN, HIGH); + #endif + #if HAS_POWER_SWITCH + #ifdef PS_DEFAULT_OFF + OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP); + #else + OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); + #endif + #endif +} + +void suicide() +{ + #if HAS_SUICIDE + OUT_WRITE(SUICIDE_PIN, LOW); + #endif +} + +void servo_init() +{ + #if NUM_SERVOS >= 1 && HAS_SERVO_0 + servos[0].attach(SERVO0_PIN); + #endif + #if NUM_SERVOS >= 2 && HAS_SERVO_1 + servos[1].attach(SERVO1_PIN); + #endif + #if NUM_SERVOS >= 3 && HAS_SERVO_2 + servos[2].attach(SERVO2_PIN); + #endif + #if NUM_SERVOS >= 4 && HAS_SERVO_3 + servos[3].attach(SERVO3_PIN); + #endif + + // Set position of Servo Endstops that are defined + #ifdef SERVO_ENDSTOPS + for (int i = 0; i < 3; i++) + if (servo_endstops[i] >= 0) + servos[servo_endstops[i]].write(servo_endstop_angles[i * 2 + 1]); + #endif + + #if SERVO_LEVELING + delay(PROBE_SERVO_DEACTIVATION_DELAY); + servos[servo_endstops[Z_AXIS]].detach(); + #endif +} + +void setup() { + setup_killpin(); + setup_filrunoutpin(); + setup_powerhold(); + MYSERIAL.begin(BAUDRATE); + SERIAL_PROTOCOLLNPGM("start"); + SERIAL_ECHO_START; + + // Check startup - does nothing if bootloader sets MCUSR to 0 + byte mcu = MCUSR; + if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP); + if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET); + if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET); + if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET); + if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET); + MCUSR = 0; + + SERIAL_ECHOPGM(MSG_MARLIN); + SERIAL_ECHOLNPGM(" " STRING_VERSION); + + #ifdef STRING_VERSION_CONFIG_H + #ifdef STRING_CONFIG_H_AUTHOR + SERIAL_ECHO_START; + SERIAL_ECHOPGM(MSG_CONFIGURATION_VER); + SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H); + SERIAL_ECHOPGM(MSG_AUTHOR); + SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR); + SERIAL_ECHOPGM("Compiled: "); + SERIAL_ECHOLNPGM(__DATE__); + #endif // STRING_CONFIG_H_AUTHOR + #endif // STRING_VERSION_CONFIG_H + + SERIAL_ECHO_START; + SERIAL_ECHOPGM(MSG_FREE_MEMORY); + SERIAL_ECHO(freeMemory()); + SERIAL_ECHOPGM(MSG_PLANNER_BUFFER_BYTES); + SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE); + + #ifdef SDSUPPORT + for (int8_t i = 0; i < BUFSIZE; i++) fromsd[i] = false; + #endif // !SDSUPPORT + + // loads data from EEPROM if available else uses defaults (and resets step acceleration rate) + Config_RetrieveSettings(); + + tp_init(); // Initialize temperature loop + plan_init(); // Initialize planner; + watchdog_init(); + st_init(); // Initialize stepper, this enables interrupts! + setup_photpin(); + servo_init(); + + lcd_init(); + _delay_ms(1000); // wait 1sec to display the splash screen + + #if HAS_CONTROLLERFAN + SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan + #endif + + #ifdef DIGIPOT_I2C + digipot_i2c_init(); + #endif + + #ifdef Z_PROBE_SLED + pinMode(SERVO0_PIN, OUTPUT); + digitalWrite(SERVO0_PIN, LOW); // turn it off + #endif // Z_PROBE_SLED + + setup_homepin(); + + #ifdef STAT_LED_RED + pinMode(STAT_LED_RED, OUTPUT); + digitalWrite(STAT_LED_RED, LOW); // turn it off + #endif + + #ifdef STAT_LED_BLUE + pinMode(STAT_LED_BLUE, OUTPUT); + digitalWrite(STAT_LED_BLUE, LOW); // turn it off + #endif +} + + +void loop() { + if (buflen < BUFSIZE - 1) get_command(); + + #ifdef SDSUPPORT + card.checkautostart(false); + #endif + + if (buflen) { + #ifdef SDSUPPORT + if (card.saving) { + if (strstr_P(cmdbuffer[bufindr], PSTR("M29")) == NULL) { + card.write_command(cmdbuffer[bufindr]); + if (card.logging) + process_commands(); + else + SERIAL_PROTOCOLLNPGM(MSG_OK); + } + else { + card.closefile(); + SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED); + } + } + else + process_commands(); + #else + process_commands(); + #endif // SDSUPPORT + buflen--; + bufindr = (bufindr + 1) % BUFSIZE; + } + // Check heater every n milliseconds + manage_heater(); + manage_inactivity(); + checkHitEndstops(); + lcd_update(); +} + +void get_command() { + + if (drain_queued_commands_P()) return; // priority is given to non-serial commands + + while (MYSERIAL.available() > 0 && buflen < BUFSIZE) { + serial_char = MYSERIAL.read(); + if (serial_char == '\n' || serial_char == '\r' || + serial_count >= (MAX_CMD_SIZE - 1) + ) { + // end of line == end of comment + comment_mode = false; + + if (!serial_count) return; // shortcut for empty lines + + cmdbuffer[bufindw][serial_count] = 0; // terminate string + + #ifdef SDSUPPORT + fromsd[bufindw] = false; + #endif + + if (strchr(cmdbuffer[bufindw], 'N') != NULL) { + strchr_pointer = strchr(cmdbuffer[bufindw], 'N'); + gcode_N = (strtol(strchr_pointer + 1, NULL, 10)); + if (gcode_N != gcode_LastN + 1 && strstr_P(cmdbuffer[bufindw], PSTR("M110")) == NULL) { + SERIAL_ERROR_START; + SERIAL_ERRORPGM(MSG_ERR_LINE_NO); + SERIAL_ERRORLN(gcode_LastN); + //Serial.println(gcode_N); + FlushSerialRequestResend(); + serial_count = 0; + return; + } + + if (strchr(cmdbuffer[bufindw], '*') != NULL) { + byte checksum = 0; + byte count = 0; + while (cmdbuffer[bufindw][count] != '*') checksum ^= cmdbuffer[bufindw][count++]; + strchr_pointer = strchr(cmdbuffer[bufindw], '*'); + + if (strtol(strchr_pointer + 1, NULL, 10) != checksum) { + SERIAL_ERROR_START; + SERIAL_ERRORPGM(MSG_ERR_CHECKSUM_MISMATCH); + SERIAL_ERRORLN(gcode_LastN); + FlushSerialRequestResend(); + serial_count = 0; + return; + } + //if no errors, continue parsing + } + else { + SERIAL_ERROR_START; + SERIAL_ERRORPGM(MSG_ERR_NO_CHECKSUM); + SERIAL_ERRORLN(gcode_LastN); + FlushSerialRequestResend(); + serial_count = 0; + return; + } + + gcode_LastN = gcode_N; + //if no errors, continue parsing + } + else { // if we don't receive 'N' but still see '*' + if ((strchr(cmdbuffer[bufindw], '*') != NULL)) { + SERIAL_ERROR_START; + SERIAL_ERRORPGM(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM); + SERIAL_ERRORLN(gcode_LastN); + serial_count = 0; + return; + } + } + + if (strchr(cmdbuffer[bufindw], 'G') != NULL) { + strchr_pointer = strchr(cmdbuffer[bufindw], 'G'); + switch (strtol(strchr_pointer + 1, NULL, 10)) { + case 0: + case 1: + case 2: + case 3: + if (IsStopped()) { + SERIAL_ERRORLNPGM(MSG_ERR_STOPPED); + LCD_MESSAGEPGM(MSG_STOPPED); + } + break; + default: + break; + } + } + + // If command was e-stop process now + if (strcmp(cmdbuffer[bufindw], "M112") == 0) kill(); + + bufindw = (bufindw + 1) % BUFSIZE; + buflen += 1; + + serial_count = 0; //clear buffer + } + else if (serial_char == '\\') { // Handle escapes + if (MYSERIAL.available() > 0 && buflen < BUFSIZE) { + // if we have one more character, copy it over + serial_char = MYSERIAL.read(); + cmdbuffer[bufindw][serial_count++] = serial_char; + } + // otherwise do nothing + } + else { // its not a newline, carriage return or escape char + if (serial_char == ';') comment_mode = true; + if (!comment_mode) cmdbuffer[bufindw][serial_count++] = serial_char; + } + } + + #ifdef SDSUPPORT + + if (!card.sdprinting || serial_count) return; + + // '#' stops reading from SD to the buffer prematurely, so procedural macro calls are possible + // if it occurs, stop_buffering is triggered and the buffer is ran dry. + // this character _can_ occur in serial com, due to checksums. however, no checksums are used in SD printing + + static bool stop_buffering = false; + if (buflen == 0) stop_buffering = false; + + while (!card.eof() && buflen < BUFSIZE && !stop_buffering) { + int16_t n = card.get(); + serial_char = (char)n; + if (serial_char == '\n' || serial_char == '\r' || + ((serial_char == '#' || serial_char == ':') && !comment_mode) || + serial_count >= (MAX_CMD_SIZE - 1) || n == -1 + ) { + if (card.eof()) { + SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED); + stoptime = millis(); + char time[30]; + millis_t t = (stoptime - starttime) / 1000; + int hours = t / 60 / 60, minutes = (t / 60) % 60; + sprintf_P(time, PSTR("%i " MSG_END_HOUR " %i " MSG_END_MINUTE), hours, minutes); + SERIAL_ECHO_START; + SERIAL_ECHOLN(time); + lcd_setstatus(time, true); + card.printingHasFinished(); + card.checkautostart(true); + } + if (serial_char == '#') stop_buffering = true; + + if (!serial_count) { + comment_mode = false; //for new command + return; //if empty line + } + cmdbuffer[bufindw][serial_count] = 0; //terminate string + // if (!comment_mode) { + fromsd[bufindw] = true; + buflen += 1; + bufindw = (bufindw + 1)%BUFSIZE; + // } + comment_mode = false; //for new command + serial_count = 0; //clear buffer + } + else { + if (serial_char == ';') comment_mode = true; + if (!comment_mode) cmdbuffer[bufindw][serial_count++] = serial_char; + } + } + + #endif // SDSUPPORT +} + +float code_has_value() { + char c = *(strchr_pointer + 1); + return (c >= '0' && c <= '9') || c == '-' || c == '+' || c == '.'; +} + +float code_value() { + float ret; + char *e = strchr(strchr_pointer, 'E'); + if (e) { + *e = 0; + ret = strtod(strchr_pointer+1, NULL); + *e = 'E'; + } + else + ret = strtod(strchr_pointer+1, NULL); + return ret; +} + +long code_value_long() { return strtol(strchr_pointer + 1, NULL, 10); } + +int16_t code_value_short() { return (int16_t)strtol(strchr_pointer + 1, NULL, 10); } + +bool code_seen(char code) { + strchr_pointer = strchr(cmdbuffer[bufindr], code); + return (strchr_pointer != NULL); //Return True if a character was found +} + +#define DEFINE_PGM_READ_ANY(type, reader) \ + static inline type pgm_read_any(const type *p) \ + { return pgm_read_##reader##_near(p); } + +DEFINE_PGM_READ_ANY(float, float); +DEFINE_PGM_READ_ANY(signed char, byte); + +#define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \ +static const PROGMEM type array##_P[3] = \ + { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \ +static inline type array(int axis) \ + { return pgm_read_any(&array##_P[axis]); } + +XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS); +XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS); +XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS); +XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH); +XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM); +XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR); + +#ifdef DUAL_X_CARRIAGE + + #define DXC_FULL_CONTROL_MODE 0 + #define DXC_AUTO_PARK_MODE 1 + #define DXC_DUPLICATION_MODE 2 + + static int dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE; + + static float x_home_pos(int extruder) { + if (extruder == 0) + return base_home_pos(X_AXIS) + home_offset[X_AXIS]; + else + // In dual carriage mode the extruder offset provides an override of the + // second X-carriage offset when homed - otherwise X2_HOME_POS is used. + // This allow soft recalibration of the second extruder offset position without firmware reflash + // (through the M218 command). + return (extruder_offset[X_AXIS][1] > 0) ? extruder_offset[X_AXIS][1] : X2_HOME_POS; + } + + static int x_home_dir(int extruder) { + return (extruder == 0) ? X_HOME_DIR : X2_HOME_DIR; + } + + static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1 + static bool active_extruder_parked = false; // used in mode 1 & 2 + static float raised_parked_position[NUM_AXIS]; // used in mode 1 + static millis_t delayed_move_time = 0; // used in mode 1 + static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2 + static float duplicate_extruder_temp_offset = 0; // used in mode 2 + bool extruder_duplication_enabled = false; // used in mode 2 + +#endif //DUAL_X_CARRIAGE + +static void axis_is_at_home(int axis) { + + #ifdef DUAL_X_CARRIAGE + if (axis == X_AXIS) { + if (active_extruder != 0) { + current_position[X_AXIS] = x_home_pos(active_extruder); + min_pos[X_AXIS] = X2_MIN_POS; + max_pos[X_AXIS] = max(extruder_offset[X_AXIS][1], X2_MAX_POS); + return; + } + else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) { + float xoff = home_offset[X_AXIS]; + current_position[X_AXIS] = base_home_pos(X_AXIS) + xoff; + min_pos[X_AXIS] = base_min_pos(X_AXIS) + xoff; + max_pos[X_AXIS] = min(base_max_pos(X_AXIS) + xoff, max(extruder_offset[X_AXIS][1], X2_MAX_POS) - duplicate_extruder_x_offset); + return; + } + } + #endif + + #ifdef SCARA + float homeposition[3]; + + if (axis < 2) { + + for (int i = 0; i < 3; i++) homeposition[i] = base_home_pos(i); + + // SERIAL_ECHOPGM("homeposition[x]= "); SERIAL_ECHO(homeposition[0]); + // SERIAL_ECHOPGM("homeposition[y]= "); SERIAL_ECHOLN(homeposition[1]); + // Works out real Homeposition angles using inverse kinematics, + // and calculates homing offset using forward kinematics + calculate_delta(homeposition); + + // SERIAL_ECHOPGM("base Theta= "); SERIAL_ECHO(delta[X_AXIS]); + // SERIAL_ECHOPGM(" base Psi+Theta="); SERIAL_ECHOLN(delta[Y_AXIS]); + + for (int i = 0; i < 2; i++) delta[i] -= home_offset[i]; + + // SERIAL_ECHOPGM("addhome X="); SERIAL_ECHO(home_offset[X_AXIS]); + // SERIAL_ECHOPGM(" addhome Y="); SERIAL_ECHO(home_offset[Y_AXIS]); + // SERIAL_ECHOPGM(" addhome Theta="); SERIAL_ECHO(delta[X_AXIS]); + // SERIAL_ECHOPGM(" addhome Psi+Theta="); SERIAL_ECHOLN(delta[Y_AXIS]); + + calculate_SCARA_forward_Transform(delta); + + // SERIAL_ECHOPGM("Delta X="); SERIAL_ECHO(delta[X_AXIS]); + // SERIAL_ECHOPGM(" Delta Y="); SERIAL_ECHOLN(delta[Y_AXIS]); + + current_position[axis] = delta[axis]; + + // SCARA home positions are based on configuration since the actual limits are determined by the + // inverse kinematic transform. + min_pos[axis] = base_min_pos(axis); // + (delta[axis] - base_home_pos(axis)); + max_pos[axis] = base_max_pos(axis); // + (delta[axis] - base_home_pos(axis)); + } + else { + current_position[axis] = base_home_pos(axis) + home_offset[axis]; + min_pos[axis] = base_min_pos(axis) + home_offset[axis]; + max_pos[axis] = base_max_pos(axis) + home_offset[axis]; + } + #else + current_position[axis] = base_home_pos(axis) + home_offset[axis]; + min_pos[axis] = base_min_pos(axis) + home_offset[axis]; + max_pos[axis] = base_max_pos(axis) + home_offset[axis]; + #endif +} + +/** + * Some planner shorthand inline functions + */ +inline void set_homing_bump_feedrate(AxisEnum axis) { + const int homing_bump_divisor[] = HOMING_BUMP_DIVISOR; + if (homing_bump_divisor[axis] >= 1) + feedrate = homing_feedrate[axis] / homing_bump_divisor[axis]; + else { + feedrate = homing_feedrate[axis] / 10; + SERIAL_ECHOLN("Warning: The Homing Bump Feedrate Divisor cannot be less than 1"); + } +} +inline void line_to_current_position() { + plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate/60, active_extruder); +} +inline void line_to_z(float zPosition) { + plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate/60, active_extruder); +} +inline void line_to_destination(float mm_m) { + plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], mm_m/60, active_extruder); +} +inline void line_to_destination() { + line_to_destination(feedrate); +} +inline void sync_plan_position() { + plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); +} +#if defined(DELTA) || defined(SCARA) + inline void sync_plan_position_delta() { + calculate_delta(current_position); + plan_set_position(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], current_position[E_AXIS]); + } +#endif +inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); } +inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); } + +#ifdef ENABLE_AUTO_BED_LEVELING + + #ifdef DELTA + /** + * Calculate delta, start a line, and set current_position to destination + */ + void prepare_move_raw() { + refresh_cmd_timeout(); + calculate_delta(destination); + plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], (feedrate/60)*(feedmultiply/100.0), active_extruder); + set_current_to_destination(); + } + #endif + + #ifdef AUTO_BED_LEVELING_GRID + + #ifndef DELTA + + static void set_bed_level_equation_lsq(double *plane_equation_coefficients) { + vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1); + planeNormal.debug("planeNormal"); + plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal); + //bedLevel.debug("bedLevel"); + + //plan_bed_level_matrix.debug("bed level before"); + //vector_3 uncorrected_position = plan_get_position_mm(); + //uncorrected_position.debug("position before"); + + vector_3 corrected_position = plan_get_position(); + //corrected_position.debug("position after"); + current_position[X_AXIS] = corrected_position.x; + current_position[Y_AXIS] = corrected_position.y; + current_position[Z_AXIS] = corrected_position.z; + + sync_plan_position(); + } + + #endif // !DELTA + + #else // !AUTO_BED_LEVELING_GRID + + static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) { + + plan_bed_level_matrix.set_to_identity(); + + vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1); + vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2); + vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3); + vector_3 planeNormal = vector_3::cross(pt1 - pt2, pt3 - pt2).get_normal(); + + if (planeNormal.z < 0) { + planeNormal.x = -planeNormal.x; + planeNormal.y = -planeNormal.y; + planeNormal.z = -planeNormal.z; + } + + plan_bed_level_matrix = matrix_3x3::create_look_at(planeNormal); + + vector_3 corrected_position = plan_get_position(); + current_position[X_AXIS] = corrected_position.x; + current_position[Y_AXIS] = corrected_position.y; + current_position[Z_AXIS] = corrected_position.z; + + sync_plan_position(); + } + + #endif // !AUTO_BED_LEVELING_GRID + + static void run_z_probe() { + + #ifdef DELTA + + float start_z = current_position[Z_AXIS]; + long start_steps = st_get_position(Z_AXIS); + + // move down slowly until you find the bed + feedrate = homing_feedrate[Z_AXIS] / 4; + destination[Z_AXIS] = -10; + prepare_move_raw(); // this will also set_current_to_destination + st_synchronize(); + endstops_hit_on_purpose(); // clear endstop hit flags + + // we have to let the planner know where we are right now as it is not where we said to go. + long stop_steps = st_get_position(Z_AXIS); + float mm = start_z - float(start_steps - stop_steps) / axis_steps_per_unit[Z_AXIS]; + current_position[Z_AXIS] = mm; + sync_plan_position_delta(); + + #else // !DELTA + + plan_bed_level_matrix.set_to_identity(); + feedrate = homing_feedrate[Z_AXIS]; + + // move down until you find the bed + float zPosition = -10; + line_to_z(zPosition); + st_synchronize(); + + // we have to let the planner know where we are right now as it is not where we said to go. + zPosition = st_get_position_mm(Z_AXIS); + plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS]); + + // move up the retract distance + zPosition += home_bump_mm(Z_AXIS); + line_to_z(zPosition); + st_synchronize(); + endstops_hit_on_purpose(); // clear endstop hit flags + + // move back down slowly to find bed + set_homing_bump_feedrate(Z_AXIS); + + zPosition -= home_bump_mm(Z_AXIS) * 2; + line_to_z(zPosition); + st_synchronize(); + endstops_hit_on_purpose(); // clear endstop hit flags + + current_position[Z_AXIS] = st_get_position_mm(Z_AXIS); + // make sure the planner knows where we are as it may be a bit different than we last said to move to + sync_plan_position(); + + #endif // !DELTA + } + + /** + * Plan a move to (X, Y, Z) and set the current_position + * The final current_position may not be the one that was requested + */ + static void do_blocking_move_to(float x, float y, float z) { + float oldFeedRate = feedrate; + + #ifdef DELTA + + feedrate = XY_TRAVEL_SPEED; + + destination[X_AXIS] = x; + destination[Y_AXIS] = y; + destination[Z_AXIS] = z; + prepare_move_raw(); // this will also set_current_to_destination + st_synchronize(); + + #else + + feedrate = homing_feedrate[Z_AXIS]; + + current_position[Z_AXIS] = z; + line_to_current_position(); + st_synchronize(); + + feedrate = xy_travel_speed; + + current_position[X_AXIS] = x; + current_position[Y_AXIS] = y; + line_to_current_position(); + st_synchronize(); + + #endif + + feedrate = oldFeedRate; + } + + static void setup_for_endstop_move() { + saved_feedrate = feedrate; + saved_feedmultiply = feedmultiply; + feedmultiply = 100; + refresh_cmd_timeout(); + enable_endstops(true); + } + + static void clean_up_after_endstop_move() { + #ifdef ENDSTOPS_ONLY_FOR_HOMING + enable_endstops(false); + #endif + feedrate = saved_feedrate; + feedmultiply = saved_feedmultiply; + refresh_cmd_timeout(); + } + + static void deploy_z_probe() { + + #ifdef SERVO_ENDSTOPS + + // Engage Z Servo endstop if enabled + if (servo_endstops[Z_AXIS] >= 0) { + #if SERVO_LEVELING + servos[servo_endstops[Z_AXIS]].attach(0); + #endif + servos[servo_endstops[Z_AXIS]].write(servo_endstop_angles[Z_AXIS * 2]); + #if SERVO_LEVELING + delay(PROBE_SERVO_DEACTIVATION_DELAY); + servos[servo_endstops[Z_AXIS]].detach(); + #endif + } + + #elif defined(Z_PROBE_ALLEN_KEY) + + feedrate = homing_feedrate[X_AXIS]; + + // Move to the start position to initiate deployment + destination[X_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_X; + destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_Y; + destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_DEPLOY_Z; + prepare_move_raw(); // this will also set_current_to_destination + + // Home X to touch the belt + feedrate = homing_feedrate[X_AXIS]/10; + destination[X_AXIS] = 0; + prepare_move_raw(); // this will also set_current_to_destination + + // Home Y for safety + feedrate = homing_feedrate[X_AXIS]/2; + destination[Y_AXIS] = 0; + prepare_move_raw(); // this will also set_current_to_destination + + st_synchronize(); + + #ifdef Z_PROBE_ENDSTOP + bool z_probe_endstop = (READ(Z_PROBE_PIN) != Z_PROBE_ENDSTOP_INVERTING); + if (z_probe_endstop) + #else + bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING); + if (z_min_endstop) + #endif + { + if (IsRunning()) { + SERIAL_ERROR_START; + SERIAL_ERRORLNPGM("Z-Probe failed to engage!"); + LCD_ALERTMESSAGEPGM("Err: ZPROBE"); + } + Stop(); + } + + #endif // Z_PROBE_ALLEN_KEY + + } + + static void stow_z_probe() { + + #ifdef SERVO_ENDSTOPS + + // Retract Z Servo endstop if enabled + if (servo_endstops[Z_AXIS] >= 0) { + + #if Z_RAISE_AFTER_PROBING > 0 + do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + Z_RAISE_AFTER_PROBING); // this also updates current_position + st_synchronize(); + #endif + + #if SERVO_LEVELING + servos[servo_endstops[Z_AXIS]].attach(0); + #endif + + servos[servo_endstops[Z_AXIS]].write(servo_endstop_angles[Z_AXIS * 2 + 1]); + + #if SERVO_LEVELING + delay(PROBE_SERVO_DEACTIVATION_DELAY); + servos[servo_endstops[Z_AXIS]].detach(); + #endif + } + + #elif defined(Z_PROBE_ALLEN_KEY) + + // Move up for safety + feedrate = homing_feedrate[X_AXIS]; + destination[Z_AXIS] = current_position[Z_AXIS] + Z_RAISE_AFTER_PROBING; + prepare_move_raw(); // this will also set_current_to_destination + + // Move to the start position to initiate retraction + destination[X_AXIS] = Z_PROBE_ALLEN_KEY_STOW_X; + destination[Y_AXIS] = Z_PROBE_ALLEN_KEY_STOW_Y; + destination[Z_AXIS] = Z_PROBE_ALLEN_KEY_STOW_Z; + prepare_move_raw(); // this will also set_current_to_destination + + // Move the nozzle down to push the probe into retracted position + feedrate = homing_feedrate[Z_AXIS]/10; + destination[Z_AXIS] = current_position[Z_AXIS] - Z_PROBE_ALLEN_KEY_STOW_DEPTH; + prepare_move_raw(); // this will also set_current_to_destination + + // Move up for safety + feedrate = homing_feedrate[Z_AXIS]/2; + destination[Z_AXIS] = current_position[Z_AXIS] + Z_PROBE_ALLEN_KEY_STOW_DEPTH * 2; + prepare_move_raw(); // this will also set_current_to_destination + + // Home XY for safety + feedrate = homing_feedrate[X_AXIS]/2; + destination[X_AXIS] = 0; + destination[Y_AXIS] = 0; + prepare_move_raw(); // this will also set_current_to_destination + + st_synchronize(); + + #ifdef Z_PROBE_ENDSTOP + bool z_probe_endstop = (READ(Z_PROBE_PIN) != Z_PROBE_ENDSTOP_INVERTING); + if (!z_probe_endstop) + #else + bool z_min_endstop = (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING); + if (!z_min_endstop) + #endif + { + if (IsRunning()) { + SERIAL_ERROR_START; + SERIAL_ERRORLNPGM("Z-Probe failed to retract!"); + LCD_ALERTMESSAGEPGM("Err: ZPROBE"); + } + Stop(); + } + + #endif + + } + + enum ProbeAction { + ProbeStay = 0, + ProbeDeploy = BIT(0), + ProbeStow = BIT(1), + ProbeDeployAndStow = (ProbeDeploy | ProbeStow) + }; + + // Probe bed height at position (x,y), returns the measured z value + static float probe_pt(float x, float y, float z_before, ProbeAction retract_action=ProbeDeployAndStow, int verbose_level=1) { + // move to right place + do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z_before); // this also updates current_position + do_blocking_move_to(x - X_PROBE_OFFSET_FROM_EXTRUDER, y - Y_PROBE_OFFSET_FROM_EXTRUDER, current_position[Z_AXIS]); // this also updates current_position + + #if !defined(Z_PROBE_SLED) && !defined(Z_PROBE_ALLEN_KEY) + if (retract_action & ProbeDeploy) deploy_z_probe(); + #endif + + run_z_probe(); + float measured_z = current_position[Z_AXIS]; + + #if Z_RAISE_BETWEEN_PROBINGS > 0 + if (retract_action == ProbeStay) { + do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS); // this also updates current_position + st_synchronize(); + } + #endif + + #if !defined(Z_PROBE_SLED) && !defined(Z_PROBE_ALLEN_KEY) + if (retract_action & ProbeStow) stow_z_probe(); + #endif + + if (verbose_level > 2) { + SERIAL_PROTOCOLPGM("Bed"); + SERIAL_PROTOCOLPGM(" X: "); + SERIAL_PROTOCOL_F(x, 3); + SERIAL_PROTOCOLPGM(" Y: "); + SERIAL_PROTOCOL_F(y, 3); + SERIAL_PROTOCOLPGM(" Z: "); + SERIAL_PROTOCOL_F(measured_z, 3); + SERIAL_EOL; + } + return measured_z; + } + + #ifdef DELTA + + /** + * All DELTA leveling in the Marlin uses NONLINEAR_BED_LEVELING + */ + + static void extrapolate_one_point(int x, int y, int xdir, int ydir) { + if (bed_level[x][y] != 0.0) { + return; // Don't overwrite good values. + } + float a = 2*bed_level[x+xdir][y] - bed_level[x+xdir*2][y]; // Left to right. + float b = 2*bed_level[x][y+ydir] - bed_level[x][y+ydir*2]; // Front to back. + float c = 2*bed_level[x+xdir][y+ydir] - bed_level[x+xdir*2][y+ydir*2]; // Diagonal. + float median = c; // Median is robust (ignores outliers). + if (a < b) { + if (b < c) median = b; + if (c < a) median = a; + } else { // b <= a + if (c < b) median = b; + if (a < c) median = a; + } + bed_level[x][y] = median; + } + + // Fill in the unprobed points (corners of circular print surface) + // using linear extrapolation, away from the center. + static void extrapolate_unprobed_bed_level() { + int half = (AUTO_BED_LEVELING_GRID_POINTS-1)/2; + for (int y = 0; y <= half; y++) { + for (int x = 0; x <= half; x++) { + if (x + y < 3) continue; + extrapolate_one_point(half-x, half-y, x>1?+1:0, y>1?+1:0); + extrapolate_one_point(half+x, half-y, x>1?-1:0, y>1?+1:0); + extrapolate_one_point(half-x, half+y, x>1?+1:0, y>1?-1:0); + extrapolate_one_point(half+x, half+y, x>1?-1:0, y>1?-1:0); + } + } + } + + // Print calibration results for plotting or manual frame adjustment. + static void print_bed_level() { + for (int y = 0; y < AUTO_BED_LEVELING_GRID_POINTS; y++) { + for (int x = 0; x < AUTO_BED_LEVELING_GRID_POINTS; x++) { + SERIAL_PROTOCOL_F(bed_level[x][y], 2); + SERIAL_PROTOCOLCHAR(' '); + } + SERIAL_EOL; + } + } + + // Reset calibration results to zero. + void reset_bed_level() { + for (int y = 0; y < AUTO_BED_LEVELING_GRID_POINTS; y++) { + for (int x = 0; x < AUTO_BED_LEVELING_GRID_POINTS; x++) { + bed_level[x][y] = 0.0; + } + } + } + + #endif // DELTA + +#endif // ENABLE_AUTO_BED_LEVELING + +/** + * Home an individual axis + */ + +#define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS) + +static void homeaxis(AxisEnum axis) { + #define HOMEAXIS_DO(LETTER) \ + ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1)) + + if (axis == X_AXIS ? HOMEAXIS_DO(X) : axis == Y_AXIS ? HOMEAXIS_DO(Y) : axis == Z_AXIS ? HOMEAXIS_DO(Z) : 0) { + + int axis_home_dir; + + #ifdef DUAL_X_CARRIAGE + if (axis == X_AXIS) axis_home_dir = x_home_dir(active_extruder); + #else + axis_home_dir = home_dir(axis); + #endif + + // Set the axis position as setup for the move + current_position[axis] = 0; + sync_plan_position(); + + // Engage Servo endstop if enabled + #if defined(SERVO_ENDSTOPS) && !defined(Z_PROBE_SLED) + + #if SERVO_LEVELING + if (axis == Z_AXIS) deploy_z_probe(); else + #endif + { + if (servo_endstops[axis] > -1) + servos[servo_endstops[axis]].write(servo_endstop_angles[axis * 2]); + } + + #endif // SERVO_ENDSTOPS && !Z_PROBE_SLED + + #ifdef Z_DUAL_ENDSTOPS + if (axis == Z_AXIS) In_Homing_Process(true); + #endif + + // Move towards the endstop until an endstop is triggered + destination[axis] = 1.5 * max_length(axis) * axis_home_dir; + feedrate = homing_feedrate[axis]; + line_to_destination(); + st_synchronize(); + + // Set the axis position as setup for the move + current_position[axis] = 0; + sync_plan_position(); + + // Move away from the endstop by the axis HOME_BUMP_MM + destination[axis] = -home_bump_mm(axis) * axis_home_dir; + line_to_destination(); + st_synchronize(); + + // Slow down the feedrate for the next move + set_homing_bump_feedrate(axis); + + // Move slowly towards the endstop until triggered + destination[axis] = 2 * home_bump_mm(axis) * axis_home_dir; + line_to_destination(); + st_synchronize(); + + #ifdef Z_DUAL_ENDSTOPS + if (axis == Z_AXIS) { + float adj = fabs(z_endstop_adj); + bool lockZ1; + if (axis_home_dir > 0) { + adj = -adj; + lockZ1 = (z_endstop_adj > 0); + } + else + lockZ1 = (z_endstop_adj < 0); + + if (lockZ1) Lock_z_motor(true); else Lock_z2_motor(true); + sync_plan_position(); + + // Move to the adjusted endstop height + feedrate = homing_feedrate[axis]; + destination[Z_AXIS] = adj; + line_to_destination(); + st_synchronize(); + + if (lockZ1) Lock_z_motor(false); else Lock_z2_motor(false); + In_Homing_Process(false); + } // Z_AXIS + #endif + + #ifdef DELTA + // retrace by the amount specified in endstop_adj + if (endstop_adj[axis] * axis_home_dir < 0) { + sync_plan_position(); + destination[axis] = endstop_adj[axis]; + line_to_destination(); + st_synchronize(); + } + #endif + + // Set the axis position to its home position (plus home offsets) + axis_is_at_home(axis); + + destination[axis] = current_position[axis]; + feedrate = 0.0; + endstops_hit_on_purpose(); // clear endstop hit flags + axis_known_position[axis] = true; + + // Retract Servo endstop if enabled + #ifdef SERVO_ENDSTOPS + if (servo_endstops[axis] > -1) + servos[servo_endstops[axis]].write(servo_endstop_angles[axis * 2 + 1]); + #endif + + #if SERVO_LEVELING && !defined(Z_PROBE_SLED) + if (axis == Z_AXIS) stow_z_probe(); + #endif + + } +} + +#ifdef FWRETRACT + + void retract(bool retracting, bool swapretract = false) { + + if (retracting == retracted[active_extruder]) return; + + float oldFeedrate = feedrate; + + set_destination_to_current(); + + if (retracting) { + + feedrate = retract_feedrate * 60; + current_position[E_AXIS] += (swapretract ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder]; + plan_set_e_position(current_position[E_AXIS]); + prepare_move(); + + if (retract_zlift > 0.01) { + current_position[Z_AXIS] -= retract_zlift; + #ifdef DELTA + sync_plan_position_delta(); + #else + sync_plan_position(); + #endif + prepare_move(); + } + } + else { + + if (retract_zlift > 0.01) { + current_position[Z_AXIS] += retract_zlift; + #ifdef DELTA + sync_plan_position_delta(); + #else + sync_plan_position(); + #endif + //prepare_move(); + } + + feedrate = retract_recover_feedrate * 60; + float move_e = swapretract ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length; + current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder]; + plan_set_e_position(current_position[E_AXIS]); + prepare_move(); + } + + feedrate = oldFeedrate; + retracted[active_extruder] = retracting; + + } // retract() + +#endif // FWRETRACT + +#ifdef Z_PROBE_SLED + + #ifndef SLED_DOCKING_OFFSET + #define SLED_DOCKING_OFFSET 0 + #endif + + // + // Method to dock/undock a sled designed by Charles Bell. + // + // dock[in] If true, move to MAX_X and engage the electromagnet + // offset[in] The additional distance to move to adjust docking location + // + static void dock_sled(bool dock, int offset=0) { + if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) { + LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN); + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN); + return; + } + + if (dock) { + do_blocking_move_to(X_MAX_POS + SLED_DOCKING_OFFSET + offset, current_position[Y_AXIS], current_position[Z_AXIS]); // this also updates current_position + digitalWrite(SERVO0_PIN, LOW); // turn off magnet + } else { + float z_loc = current_position[Z_AXIS]; + if (z_loc < Z_RAISE_BEFORE_PROBING + 5) z_loc = Z_RAISE_BEFORE_PROBING; + do_blocking_move_to(X_MAX_POS + SLED_DOCKING_OFFSET + offset, Y_PROBE_OFFSET_FROM_EXTRUDER, z_loc); // this also updates current_position + digitalWrite(SERVO0_PIN, HIGH); // turn on magnet + } + } + +#endif // Z_PROBE_SLED + +/** + * + * G-Code Handler functions + * + */ + +/** + * G0, G1: Coordinated movement of X Y Z E axes + */ +inline void gcode_G0_G1() { + if (IsRunning()) { + get_coordinates(); // For X Y Z E F + #ifdef FWRETRACT + if (autoretract_enabled) + if (!(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) { + float echange = destination[E_AXIS] - current_position[E_AXIS]; + // Is this move an attempt to retract or recover? + if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) { + current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations + plan_set_e_position(current_position[E_AXIS]); // AND from the planner + retract(!retracted[active_extruder]); + return; + } + } + #endif //FWRETRACT + prepare_move(); + //ClearToSend(); + } +} + +/** + * G2: Clockwise Arc + * G3: Counterclockwise Arc + */ +inline void gcode_G2_G3(bool clockwise) { + if (IsRunning()) { + get_arc_coordinates(); + prepare_arc_move(clockwise); + } +} + +/** + * G4: Dwell S or P + */ +inline void gcode_G4() { + millis_t codenum = 0; + + LCD_MESSAGEPGM(MSG_DWELL); + + if (code_seen('P')) codenum = code_value_long(); // milliseconds to wait + if (code_seen('S')) codenum = code_value_long() * 1000; // seconds to wait + + st_synchronize(); + refresh_cmd_timeout(); + codenum += previous_cmd_ms; // keep track of when we started waiting + while (millis() < codenum) { + manage_heater(); + manage_inactivity(); + lcd_update(); + } +} + +#ifdef FWRETRACT + + /** + * G10 - Retract filament according to settings of M207 + * G11 - Recover filament according to settings of M208 + */ + inline void gcode_G10_G11(bool doRetract=false) { + #if EXTRUDERS > 1 + if (doRetract) { + retracted_swap[active_extruder] = (code_seen('S') && code_value_short() == 1); // checks for swap retract argument + } + #endif + retract(doRetract + #if EXTRUDERS > 1 + , retracted_swap[active_extruder] + #endif + ); + } + +#endif //FWRETRACT + +/** + * G28: Home all axes according to settings + * + * Parameters + * + * None Home to all axes with no parameters. + * With QUICK_HOME enabled XY will home together, then Z. + * + * Cartesian parameters + * + * X Home to the X endstop + * Y Home to the Y endstop + * Z Home to the Z endstop + * + * If numbers are included with XYZ set the position as with G92 + * Currently adds the home_offset, which may be wrong and removed soon. + * + * Xn Home X, setting X to n + home_offset[X_AXIS] + * Yn Home Y, setting Y to n + home_offset[Y_AXIS] + * Zn Home Z, setting Z to n + home_offset[Z_AXIS] + */ +inline void gcode_G28() { + + // For auto bed leveling, clear the level matrix + #ifdef ENABLE_AUTO_BED_LEVELING + plan_bed_level_matrix.set_to_identity(); + #ifdef DELTA + reset_bed_level(); + #endif + #endif + + // For manual bed leveling deactivate the matrix temporarily + #ifdef MESH_BED_LEVELING + uint8_t mbl_was_active = mbl.active; + mbl.active = 0; + #endif + + saved_feedrate = feedrate; + saved_feedmultiply = feedmultiply; + feedmultiply = 100; + refresh_cmd_timeout(); + + enable_endstops(true); + + set_destination_to_current(); + + feedrate = 0.0; + + #ifdef DELTA + // A delta can only safely home all axis at the same time + // all axis have to home at the same time + + // Pretend the current position is 0,0,0 + for (int i = X_AXIS; i <= Z_AXIS; i++) current_position[i] = 0; + sync_plan_position(); + + // Move all carriages up together until the first endstop is hit. + for (int i = X_AXIS; i <= Z_AXIS; i++) destination[i] = 3 * Z_MAX_LENGTH; + feedrate = 1.732 * homing_feedrate[X_AXIS]; + line_to_destination(); + st_synchronize(); + endstops_hit_on_purpose(); // clear endstop hit flags + + // Destination reached + for (int i = X_AXIS; i <= Z_AXIS; i++) current_position[i] = destination[i]; + + // take care of back off and rehome now we are all at the top + HOMEAXIS(X); + HOMEAXIS(Y); + HOMEAXIS(Z); + + sync_plan_position_delta(); + + #else // NOT DELTA + + bool homeX = code_seen(axis_codes[X_AXIS]), + homeY = code_seen(axis_codes[Y_AXIS]), + homeZ = code_seen(axis_codes[Z_AXIS]); + + home_all_axis = !(homeX || homeY || homeZ) || (homeX && homeY && homeZ); + + if (home_all_axis || homeZ) { + + #if Z_HOME_DIR > 0 // If homing away from BED do Z first + + HOMEAXIS(Z); + + #elif !defined(Z_SAFE_HOMING) && defined(Z_RAISE_BEFORE_HOMING) && Z_RAISE_BEFORE_HOMING > 0 + + // Raise Z before homing any other axes + // (Does this need to be "negative home direction?" Why not just use Z_RAISE_BEFORE_HOMING?) + destination[Z_AXIS] = -Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS); + feedrate = max_feedrate[Z_AXIS] * 60; + line_to_destination(); + st_synchronize(); + + #endif + + } // home_all_axis || homeZ + + #ifdef QUICK_HOME + + if (home_all_axis || (homeX && homeY)) { // First diagonal move + + current_position[X_AXIS] = current_position[Y_AXIS] = 0; + + #ifdef DUAL_X_CARRIAGE + int x_axis_home_dir = x_home_dir(active_extruder); + extruder_duplication_enabled = false; + #else + int x_axis_home_dir = home_dir(X_AXIS); + #endif + + sync_plan_position(); + + float mlx = max_length(X_AXIS), mly = max_length(Y_AXIS), + mlratio = mlx>mly ? mly/mlx : mlx/mly; + + destination[X_AXIS] = 1.5 * mlx * x_axis_home_dir; + destination[Y_AXIS] = 1.5 * mly * home_dir(Y_AXIS); + feedrate = min(homing_feedrate[X_AXIS], homing_feedrate[Y_AXIS]) * sqrt(mlratio * mlratio + 1); + line_to_destination(); + st_synchronize(); + + axis_is_at_home(X_AXIS); + axis_is_at_home(Y_AXIS); + sync_plan_position(); + + destination[X_AXIS] = current_position[X_AXIS]; + destination[Y_AXIS] = current_position[Y_AXIS]; + line_to_destination(); + feedrate = 0.0; + st_synchronize(); + endstops_hit_on_purpose(); // clear endstop hit flags + + current_position[X_AXIS] = destination[X_AXIS]; + current_position[Y_AXIS] = destination[Y_AXIS]; + #ifndef SCARA + current_position[Z_AXIS] = destination[Z_AXIS]; + #endif + } + + #endif // QUICK_HOME + + // Home X + if (home_all_axis || homeX) { + #ifdef DUAL_X_CARRIAGE + int tmp_extruder = active_extruder; + extruder_duplication_enabled = false; + active_extruder = !active_extruder; + HOMEAXIS(X); + inactive_extruder_x_pos = current_position[X_AXIS]; + active_extruder = tmp_extruder; + HOMEAXIS(X); + // reset state used by the different modes + memcpy(raised_parked_position, current_position, sizeof(raised_parked_position)); + delayed_move_time = 0; + active_extruder_parked = true; + #else + HOMEAXIS(X); + #endif + } + + // Home Y + if (home_all_axis || homeY) HOMEAXIS(Y); + + // Set the X position, if included + if (code_seen(axis_codes[X_AXIS]) && code_has_value()) + current_position[X_AXIS] = code_value(); + + // Set the Y position, if included + if (code_seen(axis_codes[Y_AXIS]) && code_has_value()) + current_position[Y_AXIS] = code_value(); + + // Home Z last if homing towards the bed + #if Z_HOME_DIR < 0 + + if (home_all_axis || homeZ) { + + #ifdef Z_SAFE_HOMING + + if (home_all_axis) { + + current_position[Z_AXIS] = 0; + sync_plan_position(); + + // + // Set the probe (or just the nozzle) destination to the safe homing point + // + // NOTE: If current_position[X_AXIS] or current_position[Y_AXIS] were set above + // then this may not work as expected. + destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - X_PROBE_OFFSET_FROM_EXTRUDER); + destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - Y_PROBE_OFFSET_FROM_EXTRUDER); + destination[Z_AXIS] = -Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS); // Set destination away from bed + feedrate = XY_TRAVEL_SPEED; + // This could potentially move X, Y, Z all together + line_to_destination(); + st_synchronize(); + + // Set current X, Y is the Z_SAFE_HOMING_POINT minus PROBE_OFFSET_FROM_EXTRUDER + current_position[X_AXIS] = destination[X_AXIS]; + current_position[Y_AXIS] = destination[Y_AXIS]; + + // Home the Z axis + HOMEAXIS(Z); + } + + else if (homeZ) { // Don't need to Home Z twice + + // Let's see if X and Y are homed + if (axis_known_position[X_AXIS] && axis_known_position[Y_AXIS]) { + + // Make sure the probe is within the physical limits + // NOTE: This doesn't necessarily ensure the probe is also within the bed! + float cpx = current_position[X_AXIS], cpy = current_position[Y_AXIS]; + if ( cpx >= X_MIN_POS - X_PROBE_OFFSET_FROM_EXTRUDER + && cpx <= X_MAX_POS - X_PROBE_OFFSET_FROM_EXTRUDER + && cpy >= Y_MIN_POS - Y_PROBE_OFFSET_FROM_EXTRUDER + && cpy <= Y_MAX_POS - Y_PROBE_OFFSET_FROM_EXTRUDER) { + // Set the plan current position to X, Y, 0 + current_position[Z_AXIS] = 0; + plan_set_position(cpx, cpy, 0, current_position[E_AXIS]); // = sync_plan_position + + // Set Z destination away from bed and raise the axis + // NOTE: This should always just be Z_RAISE_BEFORE_HOMING unless...??? + destination[Z_AXIS] = -Z_RAISE_BEFORE_HOMING * home_dir(Z_AXIS); + feedrate = max_feedrate[Z_AXIS] * 60; // feedrate (mm/m) = max_feedrate (mm/s) + line_to_destination(); + st_synchronize(); + + // Home the Z axis + HOMEAXIS(Z); + } + else { + LCD_MESSAGEPGM(MSG_ZPROBE_OUT); + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT); + } + } + else { + LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN); + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN); + } + + } // !home_all_axes && homeZ + + #else // !Z_SAFE_HOMING + + HOMEAXIS(Z); + + #endif // !Z_SAFE_HOMING + + } // home_all_axis || homeZ + + #endif // Z_HOME_DIR < 0 + + // Set the Z position, if included + if (code_seen(axis_codes[Z_AXIS]) && code_has_value()) + current_position[Z_AXIS] = code_value(); + + #if defined(ENABLE_AUTO_BED_LEVELING) && (Z_HOME_DIR < 0) + if (home_all_axis || homeZ) current_position[Z_AXIS] += zprobe_zoffset; // Add Z_Probe offset (the distance is negative) + #endif + + sync_plan_position(); + + #endif // else DELTA + + #ifdef SCARA + sync_plan_position_delta(); + #endif + + #ifdef ENDSTOPS_ONLY_FOR_HOMING + enable_endstops(false); + #endif + + // For manual leveling move back to 0,0 + #ifdef MESH_BED_LEVELING + if (mbl_was_active) { + current_position[X_AXIS] = mbl.get_x(0); + current_position[Y_AXIS] = mbl.get_y(0); + set_destination_to_current(); + feedrate = homing_feedrate[X_AXIS]; + line_to_destination(); + st_synchronize(); + current_position[Z_AXIS] = MESH_HOME_SEARCH_Z; + sync_plan_position(); + mbl.active = 1; + } + #endif + + feedrate = saved_feedrate; + feedmultiply = saved_feedmultiply; + refresh_cmd_timeout(); + endstops_hit_on_purpose(); // clear endstop hit flags +} + +#ifdef MESH_BED_LEVELING + + enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet }; + + /** + * G29: Mesh-based Z-Probe, probes a grid and produces a + * mesh to compensate for variable bed height + * + * Parameters With MESH_BED_LEVELING: + * + * S0 Produce a mesh report + * S1 Start probing mesh points + * S2 Probe the next mesh point + * S3 Xn Yn Zn.nn Manually modify a single point + * + * The S0 report the points as below + * + * +----> X-axis + * | + * | + * v Y-axis + * + */ + inline void gcode_G29() { + + static int probe_point = -1; + MeshLevelingState state = code_seen('S') || code_seen('s') ? (MeshLevelingState)code_value_short() : MeshReport; + if (state < 0 || state > 3) { + SERIAL_PROTOCOLLNPGM("S out of range (0-3)."); + return; + } + + int ix, iy; + float z; + + switch(state) { + case MeshReport: + if (mbl.active) { + SERIAL_PROTOCOLPGM("Num X,Y: "); + SERIAL_PROTOCOL(MESH_NUM_X_POINTS); + SERIAL_PROTOCOLCHAR(','); + SERIAL_PROTOCOL(MESH_NUM_Y_POINTS); + SERIAL_PROTOCOLPGM("\nZ search height: "); + SERIAL_PROTOCOL(MESH_HOME_SEARCH_Z); + SERIAL_PROTOCOLLNPGM("\nMeasured points:"); + for (int y = 0; y < MESH_NUM_Y_POINTS; y++) { + for (int x = 0; x < MESH_NUM_X_POINTS; x++) { + SERIAL_PROTOCOLPGM(" "); + SERIAL_PROTOCOL_F(mbl.z_values[y][x], 5); + } + SERIAL_EOL; + } + } + else + SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active."); + break; + + case MeshStart: + mbl.reset(); + probe_point = 0; + enqueuecommands_P(PSTR("G28\nG29 S2")); + break; + + case MeshNext: + if (probe_point < 0) { + SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first."); + return; + } + if (probe_point == 0) { + // Set Z to a positive value before recording the first Z. + current_position[Z_AXIS] = MESH_HOME_SEARCH_Z; + sync_plan_position(); + } + else { + // For others, save the Z of the previous point, then raise Z again. + ix = (probe_point - 1) % MESH_NUM_X_POINTS; + iy = (probe_point - 1) / MESH_NUM_X_POINTS; + if (iy & 1) ix = (MESH_NUM_X_POINTS - 1) - ix; // zig-zag + mbl.set_z(ix, iy, current_position[Z_AXIS]); + current_position[Z_AXIS] = MESH_HOME_SEARCH_Z; + plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[X_AXIS]/60, active_extruder); + st_synchronize(); + } + // Is there another point to sample? Move there. + if (probe_point < MESH_NUM_X_POINTS * MESH_NUM_Y_POINTS) { + ix = probe_point % MESH_NUM_X_POINTS; + iy = probe_point / MESH_NUM_X_POINTS; + if (iy & 1) ix = (MESH_NUM_X_POINTS - 1) - ix; // zig-zag + current_position[X_AXIS] = mbl.get_x(ix); + current_position[Y_AXIS] = mbl.get_y(iy); + plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], homing_feedrate[X_AXIS]/60, active_extruder); + st_synchronize(); + probe_point++; + } + else { + // After recording the last point, activate the mbl and home + SERIAL_PROTOCOLLNPGM("Mesh probing done."); + probe_point = -1; + mbl.active = 1; + enqueuecommands_P(PSTR("G28")); + } + break; + + case MeshSet: + if (code_seen('X') || code_seen('x')) { + ix = code_value_long()-1; + if (ix < 0 || ix >= MESH_NUM_X_POINTS) { + SERIAL_PROTOCOLPGM("X out of range (1-" STRINGIFY(MESH_NUM_X_POINTS) ").\n"); + return; + } + } else { + SERIAL_PROTOCOLPGM("X not entered.\n"); + return; + } + if (code_seen('Y') || code_seen('y')) { + iy = code_value_long()-1; + if (iy < 0 || iy >= MESH_NUM_Y_POINTS) { + SERIAL_PROTOCOLPGM("Y out of range (1-" STRINGIFY(MESH_NUM_Y_POINTS) ").\n"); + return; + } + } else { + SERIAL_PROTOCOLPGM("Y not entered.\n"); + return; + } + if (code_seen('Z') || code_seen('z')) { + z = code_value(); + } else { + SERIAL_PROTOCOLPGM("Z not entered.\n"); + return; + } + mbl.z_values[iy][ix] = z; + + } // switch(state) + } + +#elif defined(ENABLE_AUTO_BED_LEVELING) + + /** + * G29: Detailed Z-Probe, probes the bed at 3 or more points. + * Will fail if the printer has not been homed with G28. + * + * Enhanced G29 Auto Bed Leveling Probe Routine + * + * Parameters With AUTO_BED_LEVELING_GRID: + * + * P Set the size of the grid that will be probed (P x P points). + * Not supported by non-linear delta printer bed leveling. + * Example: "G29 P4" + * + * S Set the XY travel speed between probe points (in mm/min) + * + * D Dry-Run mode. Just evaluate the bed Topology - Don't apply + * or clean the rotation Matrix. Useful to check the topology + * after a first run of G29. + * + * V Set the verbose level (0-4). Example: "G29 V3" + * + * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report. + * This is useful for manual bed leveling and finding flaws in the bed (to + * assist with part placement). + * Not supported by non-linear delta printer bed leveling. + * + * F Set the Front limit of the probing grid + * B Set the Back limit of the probing grid + * L Set the Left limit of the probing grid + * R Set the Right limit of the probing grid + * + * Global Parameters: + * + * E/e By default G29 will engage the probe, test the bed, then disengage. + * Include "E" to engage/disengage the probe for each sample. + * There's no extra effect if you have a fixed probe. + * Usage: "G29 E" or "G29 e" + * + */ + inline void gcode_G29() { + + // Don't allow auto-leveling without homing first + if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) { + LCD_MESSAGEPGM(MSG_POSITION_UNKNOWN); + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM(MSG_POSITION_UNKNOWN); + return; + } + + int verbose_level = code_seen('V') || code_seen('v') ? code_value_short() : 1; + if (verbose_level < 0 || verbose_level > 4) { + SERIAL_ECHOLNPGM("?(V)erbose Level is implausible (0-4)."); + return; + } + + bool dryrun = code_seen('D') || code_seen('d'), + deploy_probe_for_each_reading = code_seen('E') || code_seen('e'); + + #ifdef AUTO_BED_LEVELING_GRID + + #ifndef DELTA + bool do_topography_map = verbose_level > 2 || code_seen('T') || code_seen('t'); + #endif + + if (verbose_level > 0) { + SERIAL_PROTOCOLPGM("G29 Auto Bed Leveling\n"); + if (dryrun) SERIAL_ECHOLNPGM("Running in DRY-RUN mode"); + } + + int auto_bed_leveling_grid_points = AUTO_BED_LEVELING_GRID_POINTS; + #ifndef DELTA + if (code_seen('P')) auto_bed_leveling_grid_points = code_value_short(); + if (auto_bed_leveling_grid_points < 2) { + SERIAL_PROTOCOLPGM("?Number of probed (P)oints is implausible (2 minimum).\n"); + return; + } + #endif + + xy_travel_speed = code_seen('S') ? code_value_short() : XY_TRAVEL_SPEED; + + int left_probe_bed_position = code_seen('L') ? code_value_short() : LEFT_PROBE_BED_POSITION, + right_probe_bed_position = code_seen('R') ? code_value_short() : RIGHT_PROBE_BED_POSITION, + front_probe_bed_position = code_seen('F') ? code_value_short() : FRONT_PROBE_BED_POSITION, + back_probe_bed_position = code_seen('B') ? code_value_short() : BACK_PROBE_BED_POSITION; + + bool left_out_l = left_probe_bed_position < MIN_PROBE_X, + left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - MIN_PROBE_EDGE, + right_out_r = right_probe_bed_position > MAX_PROBE_X, + right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE, + front_out_f = front_probe_bed_position < MIN_PROBE_Y, + front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - MIN_PROBE_EDGE, + back_out_b = back_probe_bed_position > MAX_PROBE_Y, + back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE; + + if (left_out || right_out || front_out || back_out) { + if (left_out) { + SERIAL_PROTOCOLPGM("?Probe (L)eft position out of range.\n"); + left_probe_bed_position = left_out_l ? MIN_PROBE_X : right_probe_bed_position - MIN_PROBE_EDGE; + } + if (right_out) { + SERIAL_PROTOCOLPGM("?Probe (R)ight position out of range.\n"); + right_probe_bed_position = right_out_r ? MAX_PROBE_X : left_probe_bed_position + MIN_PROBE_EDGE; + } + if (front_out) { + SERIAL_PROTOCOLPGM("?Probe (F)ront position out of range.\n"); + front_probe_bed_position = front_out_f ? MIN_PROBE_Y : back_probe_bed_position - MIN_PROBE_EDGE; + } + if (back_out) { + SERIAL_PROTOCOLPGM("?Probe (B)ack position out of range.\n"); + back_probe_bed_position = back_out_b ? MAX_PROBE_Y : front_probe_bed_position + MIN_PROBE_EDGE; + } + return; + } + + #endif // AUTO_BED_LEVELING_GRID + + #ifdef Z_PROBE_SLED + dock_sled(false); // engage (un-dock) the probe + #elif defined(Z_PROBE_ALLEN_KEY) //|| defined(SERVO_LEVELING) + deploy_z_probe(); + #endif + + st_synchronize(); + + if (!dryrun) { + // make sure the bed_level_rotation_matrix is identity or the planner will get it wrong + plan_bed_level_matrix.set_to_identity(); + + #ifdef DELTA + reset_bed_level(); + #else //!DELTA + //vector_3 corrected_position = plan_get_position_mm(); + //corrected_position.debug("position before G29"); + vector_3 uncorrected_position = plan_get_position(); + //uncorrected_position.debug("position during G29"); + current_position[X_AXIS] = uncorrected_position.x; + current_position[Y_AXIS] = uncorrected_position.y; + current_position[Z_AXIS] = uncorrected_position.z; + sync_plan_position(); + #endif // !DELTA + } + + setup_for_endstop_move(); + + feedrate = homing_feedrate[Z_AXIS]; + + #ifdef AUTO_BED_LEVELING_GRID + + // probe at the points of a lattice grid + const int xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (auto_bed_leveling_grid_points - 1), + yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (auto_bed_leveling_grid_points - 1); + + #ifdef DELTA + delta_grid_spacing[0] = xGridSpacing; + delta_grid_spacing[1] = yGridSpacing; + float z_offset = Z_PROBE_OFFSET_FROM_EXTRUDER; + if (code_seen(axis_codes[Z_AXIS])) z_offset += code_value(); + #else // !DELTA + // solve the plane equation ax + by + d = z + // A is the matrix with rows [x y 1] for all the probed points + // B is the vector of the Z positions + // the normal vector to the plane is formed by the coefficients of the plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0 + // so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z + + int abl2 = auto_bed_leveling_grid_points * auto_bed_leveling_grid_points; + + double eqnAMatrix[abl2 * 3], // "A" matrix of the linear system of equations + eqnBVector[abl2], // "B" vector of Z points + mean = 0.0; + #endif // !DELTA + + int probePointCounter = 0; + bool zig = true; + + for (int yCount = 0; yCount < auto_bed_leveling_grid_points; yCount++) { + double yProbe = front_probe_bed_position + yGridSpacing * yCount; + int xStart, xStop, xInc; + + if (zig) { + xStart = 0; + xStop = auto_bed_leveling_grid_points; + xInc = 1; + } + else { + xStart = auto_bed_leveling_grid_points - 1; + xStop = -1; + xInc = -1; + } + + #ifndef DELTA + // If do_topography_map is set then don't zig-zag. Just scan in one direction. + // This gets the probe points in more readable order. + if (!do_topography_map) zig = !zig; + #endif + + for (int xCount = xStart; xCount != xStop; xCount += xInc) { + double xProbe = left_probe_bed_position + xGridSpacing * xCount; + + // raise extruder + float measured_z, + z_before = probePointCounter ? Z_RAISE_BETWEEN_PROBINGS + current_position[Z_AXIS] : Z_RAISE_BEFORE_PROBING; + + #ifdef DELTA + // Avoid probing the corners (outside the round or hexagon print surface) on a delta printer. + float distance_from_center = sqrt(xProbe*xProbe + yProbe*yProbe); + if (distance_from_center > DELTA_PROBABLE_RADIUS) continue; + #endif //DELTA + + ProbeAction act; + if (deploy_probe_for_each_reading) // G29 E - Stow between probes + act = ProbeDeployAndStow; + else if (yCount == 0 && xCount == xStart) + act = ProbeDeploy; + else if (yCount == auto_bed_leveling_grid_points - 1 && xCount == xStop - xInc) + act = ProbeStow; + else + act = ProbeStay; + + measured_z = probe_pt(xProbe, yProbe, z_before, act, verbose_level); + + #ifndef DELTA + mean += measured_z; + + eqnBVector[probePointCounter] = measured_z; + eqnAMatrix[probePointCounter + 0 * abl2] = xProbe; + eqnAMatrix[probePointCounter + 1 * abl2] = yProbe; + eqnAMatrix[probePointCounter + 2 * abl2] = 1; + #else + bed_level[xCount][yCount] = measured_z + z_offset; + #endif + + probePointCounter++; + + manage_heater(); + manage_inactivity(); + lcd_update(); + + } //xProbe + } //yProbe + + clean_up_after_endstop_move(); + + #ifdef DELTA + + if (!dryrun) extrapolate_unprobed_bed_level(); + print_bed_level(); + + #else // !DELTA + + // solve lsq problem + double *plane_equation_coefficients = qr_solve(abl2, 3, eqnAMatrix, eqnBVector); + + mean /= abl2; + + if (verbose_level) { + SERIAL_PROTOCOLPGM("Eqn coefficients: a: "); + SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8); + SERIAL_PROTOCOLPGM(" b: "); + SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8); + SERIAL_PROTOCOLPGM(" d: "); + SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8); + SERIAL_EOL; + if (verbose_level > 2) { + SERIAL_PROTOCOLPGM("Mean of sampled points: "); + SERIAL_PROTOCOL_F(mean, 8); + SERIAL_EOL; + } + } + + // Show the Topography map if enabled + if (do_topography_map) { + + SERIAL_PROTOCOLPGM(" \nBed Height Topography: \n"); + SERIAL_PROTOCOLPGM("+-----------+\n"); + SERIAL_PROTOCOLPGM("|...Back....|\n"); + SERIAL_PROTOCOLPGM("|Left..Right|\n"); + SERIAL_PROTOCOLPGM("|...Front...|\n"); + SERIAL_PROTOCOLPGM("+-----------+\n"); + + for (int yy = auto_bed_leveling_grid_points - 1; yy >= 0; yy--) { + for (int xx = 0; xx < auto_bed_leveling_grid_points; xx++) { + int ind = yy * auto_bed_leveling_grid_points + xx; + float diff = eqnBVector[ind] - mean; + if (diff >= 0.0) + SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment + else + SERIAL_PROTOCOLCHAR(' '); + SERIAL_PROTOCOL_F(diff, 5); + } // xx + SERIAL_EOL; + } // yy + SERIAL_EOL; + + } //do_topography_map + + + if (!dryrun) set_bed_level_equation_lsq(plane_equation_coefficients); + free(plane_equation_coefficients); + + #endif //!DELTA + + #else // !AUTO_BED_LEVELING_GRID + + // Actions for each probe + ProbeAction p1, p2, p3; + if (deploy_probe_for_each_reading) + p1 = p2 = p3 = ProbeDeployAndStow; + else + p1 = ProbeDeploy, p2 = ProbeStay, p3 = ProbeStow; + + // Probe at 3 arbitrary points + float z_at_pt_1 = probe_pt(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, Z_RAISE_BEFORE_PROBING, p1, verbose_level), + z_at_pt_2 = probe_pt(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS, p2, verbose_level), + z_at_pt_3 = probe_pt(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, current_position[Z_AXIS] + Z_RAISE_BETWEEN_PROBINGS, p3, verbose_level); + clean_up_after_endstop_move(); + if (!dryrun) set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3); + + #endif // !AUTO_BED_LEVELING_GRID + + #ifndef DELTA + if (verbose_level > 0) + plan_bed_level_matrix.debug(" \n\nBed Level Correction Matrix:"); + + if (!dryrun) { + // Correct the Z height difference from z-probe position and hotend tip position. + // The Z height on homing is measured by Z-Probe, but the probe is quite far from the hotend. + // When the bed is uneven, this height must be corrected. + float x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER, + y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER, + z_tmp = current_position[Z_AXIS], + real_z = (float)st_get_position(Z_AXIS) / axis_steps_per_unit[Z_AXIS]; //get the real Z (since the auto bed leveling is already correcting the plane) + + apply_rotation_xyz(plan_bed_level_matrix, x_tmp, y_tmp, z_tmp); //Apply the correction sending the probe offset + current_position[Z_AXIS] = z_tmp - real_z + current_position[Z_AXIS]; //The difference is added to current position and sent to planner. + sync_plan_position(); + } + #endif // !DELTA + + #ifdef Z_PROBE_SLED + dock_sled(true, -SLED_DOCKING_OFFSET); // dock the probe, correcting for over-travel + #elif defined(Z_PROBE_ALLEN_KEY) //|| defined(SERVO_LEVELING) + stow_z_probe(); + #endif + + #ifdef Z_PROBE_END_SCRIPT + enqueuecommands_P(PSTR(Z_PROBE_END_SCRIPT)); + st_synchronize(); + #endif + } + + #ifndef Z_PROBE_SLED + + inline void gcode_G30() { + deploy_z_probe(); // Engage Z Servo endstop if available + st_synchronize(); + // TODO: make sure the bed_level_rotation_matrix is identity or the planner will get set incorectly + setup_for_endstop_move(); + + feedrate = homing_feedrate[Z_AXIS]; + + run_z_probe(); + SERIAL_PROTOCOLPGM("Bed"); + SERIAL_PROTOCOLPGM(" X: "); + SERIAL_PROTOCOL(current_position[X_AXIS] + 0.0001); + SERIAL_PROTOCOLPGM(" Y: "); + SERIAL_PROTOCOL(current_position[Y_AXIS] + 0.0001); + SERIAL_PROTOCOLPGM(" Z: "); + SERIAL_PROTOCOL(current_position[Z_AXIS] + 0.0001); + SERIAL_EOL; + + clean_up_after_endstop_move(); + stow_z_probe(); // Retract Z Servo endstop if available + } + + #endif //!Z_PROBE_SLED + +#endif //ENABLE_AUTO_BED_LEVELING + +/** + * G92: Set current position to given X Y Z E + */ +inline void gcode_G92() { + if (!code_seen(axis_codes[E_AXIS])) + st_synchronize(); + + bool didXYZ = false; + for (int i = 0; i < NUM_AXIS; i++) { + if (code_seen(axis_codes[i])) { + float v = current_position[i] = code_value(); + if (i == E_AXIS) + plan_set_e_position(v); + else + didXYZ = true; + } + } + if (didXYZ) sync_plan_position(); +} + +#ifdef ULTIPANEL + + /** + * M0: // M0 - Unconditional stop - Wait for user button press on LCD + * M1: // M1 - Conditional stop - Wait for user button press on LCD + */ + inline void gcode_M0_M1() { + char *src = strchr_pointer + 2; + + millis_t codenum = 0; + bool hasP = false, hasS = false; + if (code_seen('P')) { + codenum = code_value_short(); // milliseconds to wait + hasP = codenum > 0; + } + if (code_seen('S')) { + codenum = code_value_short() * 1000UL; // seconds to wait + hasS = codenum > 0; + } + char* starpos = strchr(src, '*'); + if (starpos != NULL) *(starpos) = '\0'; + while (*src == ' ') ++src; + if (!hasP && !hasS && *src != '\0') + lcd_setstatus(src, true); + else { + LCD_MESSAGEPGM(MSG_USERWAIT); + #if defined(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0 + dontExpireStatus(); + #endif + } + + lcd_ignore_click(); + st_synchronize(); + refresh_cmd_timeout(); + if (codenum > 0) { + codenum += previous_cmd_ms; // keep track of when we started waiting + while(millis() < codenum && !lcd_clicked()) { + manage_heater(); + manage_inactivity(); + lcd_update(); + } + lcd_ignore_click(false); + } + else { + if (!lcd_detected()) return; + while (!lcd_clicked()) { + manage_heater(); + manage_inactivity(); + lcd_update(); + } + } + if (IS_SD_PRINTING) + LCD_MESSAGEPGM(MSG_RESUMING); + else + LCD_MESSAGEPGM(WELCOME_MSG); + } + +#endif // ULTIPANEL + +/** + * M17: Enable power on all stepper motors + */ +inline void gcode_M17() { + LCD_MESSAGEPGM(MSG_NO_MOVE); + enable_all_steppers(); +} + +#ifdef SDSUPPORT + + /** + * M20: List SD card to serial output + */ + inline void gcode_M20() { + SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST); + card.ls(); + SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST); + } + + /** + * M21: Init SD Card + */ + inline void gcode_M21() { + card.initsd(); + } + + /** + * M22: Release SD Card + */ + inline void gcode_M22() { + card.release(); + } + + /** + * M23: Select a file + */ + inline void gcode_M23() { + char* codepos = strchr_pointer + 4; + char* starpos = strchr(codepos, '*'); + if (starpos) *starpos = '\0'; + card.openFile(codepos, true); + } + + /** + * M24: Start SD Print + */ + inline void gcode_M24() { + card.startFileprint(); + starttime = millis(); + } + + /** + * M25: Pause SD Print + */ + inline void gcode_M25() { + card.pauseSDPrint(); + } + + /** + * M26: Set SD Card file index + */ + inline void gcode_M26() { + if (card.cardOK && code_seen('S')) + card.setIndex(code_value_short()); + } + + /** + * M27: Get SD Card status + */ + inline void gcode_M27() { + card.getStatus(); + } + + /** + * M28: Start SD Write + */ + inline void gcode_M28() { + char* codepos = strchr_pointer + 4; + char* starpos = strchr(codepos, '*'); + if (starpos) { + char* npos = strchr(cmdbuffer[bufindr], 'N'); + strchr_pointer = strchr(npos, ' ') + 1; + *(starpos) = '\0'; + } + card.openFile(codepos, false); + } + + /** + * M29: Stop SD Write + * Processed in write to file routine above + */ + inline void gcode_M29() { + // card.saving = false; + } + + /** + * M30 : Delete SD Card file + */ + inline void gcode_M30() { + if (card.cardOK) { + card.closefile(); + char* starpos = strchr(strchr_pointer + 4, '*'); + if (starpos) { + char* npos = strchr(cmdbuffer[bufindr], 'N'); + strchr_pointer = strchr(npos, ' ') + 1; + *(starpos) = '\0'; + } + card.removeFile(strchr_pointer + 4); + } + } + +#endif + +/** + * M31: Get the time since the start of SD Print (or last M109) + */ +inline void gcode_M31() { + stoptime = millis(); + millis_t t = (stoptime - starttime) / 1000; + int min = t / 60, sec = t % 60; + char time[30]; + sprintf_P(time, PSTR("%i min, %i sec"), min, sec); + SERIAL_ECHO_START; + SERIAL_ECHOLN(time); + lcd_setstatus(time); + autotempShutdown(); +} + +#ifdef SDSUPPORT + + /** + * M32: Select file and start SD Print + */ + inline void gcode_M32() { + if (card.sdprinting) + st_synchronize(); + + char* codepos = strchr_pointer + 4; + + char* namestartpos = strchr(codepos, '!'); //find ! to indicate filename string start. + if (! namestartpos) + namestartpos = codepos; //default name position, 4 letters after the M + else + namestartpos++; //to skip the '!' + + char* starpos = strchr(codepos, '*'); + if (starpos) *(starpos) = '\0'; + + bool call_procedure = code_seen('P') && (strchr_pointer < namestartpos); + + if (card.cardOK) { + card.openFile(namestartpos, true, !call_procedure); + + if (code_seen('S') && strchr_pointer < namestartpos) // "S" (must occur _before_ the filename!) + card.setIndex(code_value_short()); + + card.startFileprint(); + if (!call_procedure) + starttime = millis(); //procedure calls count as normal print time. + } + } + + /** + * M928: Start SD Write + */ + inline void gcode_M928() { + char* starpos = strchr(strchr_pointer + 5, '*'); + if (starpos) { + char* npos = strchr(cmdbuffer[bufindr], 'N'); + strchr_pointer = strchr(npos, ' ') + 1; + *(starpos) = '\0'; + } + card.openLogFile(strchr_pointer + 5); + } + +#endif // SDSUPPORT + +/** + * M42: Change pin status via GCode + */ +inline void gcode_M42() { + if (code_seen('S')) { + int pin_status = code_value_short(), + pin_number = LED_PIN; + + if (code_seen('P') && pin_status >= 0 && pin_status <= 255) + pin_number = code_value_short(); + + for (int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins) / sizeof(*sensitive_pins)); i++) { + if (sensitive_pins[i] == pin_number) { + pin_number = -1; + break; + } + } + + #if HAS_FAN + if (pin_number == FAN_PIN) fanSpeed = pin_status; + #endif + + if (pin_number > -1) { + pinMode(pin_number, OUTPUT); + digitalWrite(pin_number, pin_status); + analogWrite(pin_number, pin_status); + } + } // code_seen('S') +} + +#if defined(ENABLE_AUTO_BED_LEVELING) && defined(Z_PROBE_REPEATABILITY_TEST) + + // This is redundant since the SanityCheck.h already checks for a valid Z_PROBE_PIN, but here for clarity. + #ifdef Z_PROBE_ENDSTOP + #if !HAS_Z_PROBE + #error You must define Z_PROBE_PIN to enable Z-Probe repeatability calculation. + #endif + #elif !HAS_Z_MIN + #error You must define Z_MIN_PIN to enable Z-Probe repeatability calculation. + #endif + + /** + * M48: Z-Probe repeatability measurement function. + * + * Usage: + * M48 + * P = Number of sampled points (4-50, default 10) + * X = Sample X position + * Y = Sample Y position + * V = Verbose level (0-4, default=1) + * E = Engage probe for each reading + * L = Number of legs of movement before probe + * + * This function assumes the bed has been homed. Specifically, that a G28 command + * as been issued prior to invoking the M48 Z-Probe repeatability measurement function. + * Any information generated by a prior G29 Bed leveling command will be lost and need to be + * regenerated. + * + * The number of samples will default to 10 if not specified. You can use upper or lower case + * letters for any of the options EXCEPT n. n must be in lower case because Marlin uses a capital + * N for its communication protocol and will get horribly confused if you send it a capital N. + */ + inline void gcode_M48() { + + double sum = 0.0, mean = 0.0, sigma = 0.0, sample_set[50]; + uint8_t verbose_level = 1, n_samples = 10, n_legs = 0; + + if (code_seen('V') || code_seen('v')) { + verbose_level = code_value_short(); + if (verbose_level < 0 || verbose_level > 4 ) { + SERIAL_PROTOCOLPGM("?Verbose Level not plausible (0-4).\n"); + return; + } + } + + if (verbose_level > 0) + SERIAL_PROTOCOLPGM("M48 Z-Probe Repeatability test\n"); + + if (code_seen('P') || code_seen('p') || code_seen('n')) { // `n` for legacy support only - please use `P`! + n_samples = code_value_short(); + if (n_samples < 4 || n_samples > 50) { + SERIAL_PROTOCOLPGM("?Sample size not plausible (4-50).\n"); + return; + } + } + + double X_probe_location, Y_probe_location, + X_current = X_probe_location = st_get_position_mm(X_AXIS), + Y_current = Y_probe_location = st_get_position_mm(Y_AXIS), + Z_current = st_get_position_mm(Z_AXIS), + Z_start_location = Z_current + Z_RAISE_BEFORE_PROBING, + ext_position = st_get_position_mm(E_AXIS); + + bool deploy_probe_for_each_reading = code_seen('E') || code_seen('e'); + + if (code_seen('X') || code_seen('x')) { + X_probe_location = code_value() - X_PROBE_OFFSET_FROM_EXTRUDER; + if (X_probe_location < X_MIN_POS || X_probe_location > X_MAX_POS) { + SERIAL_PROTOCOLPGM("?X position out of range.\n"); + return; + } + } + + if (code_seen('Y') || code_seen('y')) { + Y_probe_location = code_value() - Y_PROBE_OFFSET_FROM_EXTRUDER; + if (Y_probe_location < Y_MIN_POS || Y_probe_location > Y_MAX_POS) { + SERIAL_PROTOCOLPGM("?Y position out of range.\n"); + return; + } + } + + if (code_seen('L') || code_seen('l')) { + n_legs = code_value_short(); + if (n_legs == 1) n_legs = 2; + if (n_legs < 0 || n_legs > 15) { + SERIAL_PROTOCOLPGM("?Number of legs in movement not plausible (0-15).\n"); + return; + } + } + + // + // Do all the preliminary setup work. First raise the probe. + // + + st_synchronize(); + plan_bed_level_matrix.set_to_identity(); + plan_buffer_line(X_current, Y_current, Z_start_location, + ext_position, + homing_feedrate[Z_AXIS] / 60, + active_extruder); + st_synchronize(); + + // + // Now get everything to the specified probe point So we can safely do a probe to + // get us close to the bed. If the Z-Axis is far from the bed, we don't want to + // use that as a starting point for each probe. + // + if (verbose_level > 2) + SERIAL_PROTOCOLPGM("Positioning the probe...\n"); + + plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location, + ext_position, + homing_feedrate[X_AXIS]/60, + active_extruder); + st_synchronize(); + + current_position[X_AXIS] = X_current = st_get_position_mm(X_AXIS); + current_position[Y_AXIS] = Y_current = st_get_position_mm(Y_AXIS); + current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS); + current_position[E_AXIS] = ext_position = st_get_position_mm(E_AXIS); + + // + // OK, do the inital probe to get us close to the bed. + // Then retrace the right amount and use that in subsequent probes + // + + deploy_z_probe(); + + setup_for_endstop_move(); + run_z_probe(); + + current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS); + Z_start_location = st_get_position_mm(Z_AXIS) + Z_RAISE_BEFORE_PROBING; + + plan_buffer_line( X_probe_location, Y_probe_location, Z_start_location, + ext_position, + homing_feedrate[X_AXIS]/60, + active_extruder); + st_synchronize(); + current_position[Z_AXIS] = Z_current = st_get_position_mm(Z_AXIS); + + if (deploy_probe_for_each_reading) stow_z_probe(); + + for (uint8_t n=0; n < n_samples; n++) { + // Make sure we are at the probe location + do_blocking_move_to(X_probe_location, Y_probe_location, Z_start_location); // this also updates current_position + + if (n_legs) { + millis_t ms = millis(); + double radius = ms % (X_MAX_LENGTH / 4), // limit how far out to go + theta = RADIANS(ms % 360L); + float dir = (ms & 0x0001) ? 1 : -1; // clockwise or counter clockwise + + //SERIAL_ECHOPAIR("starting radius: ",radius); + //SERIAL_ECHOPAIR(" theta: ",theta); + //SERIAL_ECHOPAIR(" direction: ",dir); + //SERIAL_EOL; + + for (uint8_t l = 0; l < n_legs - 1; l++) { + ms = millis(); + theta += RADIANS(dir * (ms % 20L)); + radius += (ms % 10L) - 5L; + if (radius < 0.0) radius = -radius; + + X_current = X_probe_location + cos(theta) * radius; + Y_current = Y_probe_location + sin(theta) * radius; + X_current = constrain(X_current, X_MIN_POS, X_MAX_POS); + Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS); + + if (verbose_level > 3) { + SERIAL_ECHOPAIR("x: ", X_current); + SERIAL_ECHOPAIR("y: ", Y_current); + SERIAL_EOL; + } + + do_blocking_move_to(X_current, Y_current, Z_current); // this also updates current_position + + } // n_legs loop + + // Go back to the probe location + do_blocking_move_to(X_probe_location, Y_probe_location, Z_start_location); // this also updates current_position + + } // n_legs + + if (deploy_probe_for_each_reading) { + deploy_z_probe(); + delay(1000); + } + + setup_for_endstop_move(); + run_z_probe(); + + sample_set[n] = current_position[Z_AXIS]; + + // + // Get the current mean for the data points we have so far + // + sum = 0.0; + for (uint8_t j = 0; j <= n; j++) sum += sample_set[j]; + mean = sum / (n + 1); + + // + // Now, use that mean to calculate the standard deviation for the + // data points we have so far + // + sum = 0.0; + for (uint8_t j = 0; j <= n; j++) { + float ss = sample_set[j] - mean; + sum += ss * ss; + } + sigma = sqrt(sum / (n + 1)); + + if (verbose_level > 1) { + SERIAL_PROTOCOL(n+1); + SERIAL_PROTOCOLPGM(" of "); + SERIAL_PROTOCOL(n_samples); + SERIAL_PROTOCOLPGM(" z: "); + SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6); + if (verbose_level > 2) { + SERIAL_PROTOCOLPGM(" mean: "); + SERIAL_PROTOCOL_F(mean,6); + SERIAL_PROTOCOLPGM(" sigma: "); + SERIAL_PROTOCOL_F(sigma,6); + } + } + + if (verbose_level > 0) SERIAL_EOL; + + plan_buffer_line(X_probe_location, Y_probe_location, Z_start_location, current_position[E_AXIS], homing_feedrate[Z_AXIS]/60, active_extruder); + st_synchronize(); + + if (deploy_probe_for_each_reading) { + stow_z_probe(); + delay(1000); + } + } + + if (!deploy_probe_for_each_reading) { + stow_z_probe(); + delay(1000); + } + + clean_up_after_endstop_move(); + + // enable_endstops(true); + + if (verbose_level > 0) { + SERIAL_PROTOCOLPGM("Mean: "); + SERIAL_PROTOCOL_F(mean, 6); + SERIAL_EOL; + } + + SERIAL_PROTOCOLPGM("Standard Deviation: "); + SERIAL_PROTOCOL_F(sigma, 6); + SERIAL_EOL; SERIAL_EOL; + } + +#endif // ENABLE_AUTO_BED_LEVELING && Z_PROBE_REPEATABILITY_TEST + +/** + * M104: Set hot end temperature + */ +inline void gcode_M104() { + if (setTargetedHotend(104)) return; + + if (code_seen('S')) { + float temp = code_value(); + setTargetHotend(temp, target_extruder); + #ifdef DUAL_X_CARRIAGE + if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0) + setTargetHotend1(temp == 0.0 ? 0.0 : temp + duplicate_extruder_temp_offset); + #endif + setWatch(); + } +} + +/** + * M105: Read hot end and bed temperature + */ +inline void gcode_M105() { + if (setTargetedHotend(105)) return; + + #if HAS_TEMP_0 || HAS_TEMP_BED + SERIAL_PROTOCOLPGM("ok"); + #if HAS_TEMP_0 + SERIAL_PROTOCOLPGM(" T:"); + SERIAL_PROTOCOL_F(degHotend(target_extruder), 1); + SERIAL_PROTOCOLPGM(" /"); + SERIAL_PROTOCOL_F(degTargetHotend(target_extruder), 1); + #endif + #if HAS_TEMP_BED + SERIAL_PROTOCOLPGM(" B:"); + SERIAL_PROTOCOL_F(degBed(), 1); + SERIAL_PROTOCOLPGM(" /"); + SERIAL_PROTOCOL_F(degTargetBed(), 1); + #endif + for (int8_t e = 0; e < EXTRUDERS; ++e) { + SERIAL_PROTOCOLPGM(" T"); + SERIAL_PROTOCOL(e); + SERIAL_PROTOCOLCHAR(':'); + SERIAL_PROTOCOL_F(degHotend(e), 1); + SERIAL_PROTOCOLPGM(" /"); + SERIAL_PROTOCOL_F(degTargetHotend(e), 1); + } + #else // !HAS_TEMP_0 && !HAS_TEMP_BED + SERIAL_ERROR_START; + SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS); + #endif + + SERIAL_PROTOCOLPGM(" @:"); + #ifdef EXTRUDER_WATTS + SERIAL_PROTOCOL((EXTRUDER_WATTS * getHeaterPower(target_extruder))/127); + SERIAL_PROTOCOLCHAR('W'); + #else + SERIAL_PROTOCOL(getHeaterPower(target_extruder)); + #endif + + SERIAL_PROTOCOLPGM(" B@:"); + #ifdef BED_WATTS + SERIAL_PROTOCOL((BED_WATTS * getHeaterPower(-1))/127); + SERIAL_PROTOCOLCHAR('W'); + #else + SERIAL_PROTOCOL(getHeaterPower(-1)); + #endif + + #ifdef SHOW_TEMP_ADC_VALUES + #if HAS_TEMP_BED + SERIAL_PROTOCOLPGM(" ADC B:"); + SERIAL_PROTOCOL_F(degBed(),1); + SERIAL_PROTOCOLPGM("C->"); + SERIAL_PROTOCOL_F(rawBedTemp()/OVERSAMPLENR,0); + #endif + for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) { + SERIAL_PROTOCOLPGM(" T"); + SERIAL_PROTOCOL(cur_extruder); + SERIAL_PROTOCOLCHAR(':'); + SERIAL_PROTOCOL_F(degHotend(cur_extruder),1); + SERIAL_PROTOCOLPGM("C->"); + SERIAL_PROTOCOL_F(rawHotendTemp(cur_extruder)/OVERSAMPLENR,0); + } + #endif + + SERIAL_EOL; +} + +#if HAS_FAN + + /** + * M106: Set Fan Speed + */ + inline void gcode_M106() { fanSpeed = code_seen('S') ? constrain(code_value_short(), 0, 255) : 255; } + + /** + * M107: Fan Off + */ + inline void gcode_M107() { fanSpeed = 0; } + +#endif // HAS_FAN + +/** + * M109: Wait for extruder(s) to reach temperature + */ +inline void gcode_M109() { + if (setTargetedHotend(109)) return; + + LCD_MESSAGEPGM(MSG_HEATING); + + CooldownNoWait = code_seen('S'); + if (CooldownNoWait || code_seen('R')) { + float temp = code_value(); + setTargetHotend(temp, target_extruder); + #ifdef DUAL_X_CARRIAGE + if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0) + setTargetHotend1(temp == 0.0 ? 0.0 : temp + duplicate_extruder_temp_offset); + #endif + } + + #ifdef AUTOTEMP + autotemp_enabled = code_seen('F'); + if (autotemp_enabled) autotemp_factor = code_value(); + if (code_seen('S')) autotemp_min = code_value(); + if (code_seen('B')) autotemp_max = code_value(); + #endif + + setWatch(); + + millis_t temp_ms = millis(); + + /* See if we are heating up or cooling down */ + target_direction = isHeatingHotend(target_extruder); // true if heating, false if cooling + + cancel_heatup = false; + + #ifdef TEMP_RESIDENCY_TIME + long residency_start_ms = -1; + /* continue to loop until we have reached the target temp + _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */ + while((!cancel_heatup)&&((residency_start_ms == -1) || + (residency_start_ms >= 0 && (((unsigned int) (millis() - residency_start_ms)) < (TEMP_RESIDENCY_TIME * 1000UL)))) ) + #else + while ( target_direction ? (isHeatingHotend(target_extruder)) : (isCoolingHotend(target_extruder)&&(CooldownNoWait==false)) ) + #endif //TEMP_RESIDENCY_TIME + + { // while loop + if (millis() > temp_ms + 1000UL) { //Print temp & remaining time every 1s while waiting + SERIAL_PROTOCOLPGM("T:"); + SERIAL_PROTOCOL_F(degHotend(target_extruder),1); + SERIAL_PROTOCOLPGM(" E:"); + SERIAL_PROTOCOL((int)target_extruder); + #ifdef TEMP_RESIDENCY_TIME + SERIAL_PROTOCOLPGM(" W:"); + if (residency_start_ms > -1) { + temp_ms = ((TEMP_RESIDENCY_TIME * 1000UL) - (millis() - residency_start_ms)) / 1000UL; + SERIAL_PROTOCOLLN(temp_ms); + } + else { + SERIAL_PROTOCOLLNPGM("?"); + } + #else + SERIAL_EOL; + #endif + temp_ms = millis(); + } + manage_heater(); + manage_inactivity(); + lcd_update(); + #ifdef TEMP_RESIDENCY_TIME + // start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time + // or when current temp falls outside the hysteresis after target temp was reached + if ((residency_start_ms == -1 && target_direction && (degHotend(target_extruder) >= (degTargetHotend(target_extruder)-TEMP_WINDOW))) || + (residency_start_ms == -1 && !target_direction && (degHotend(target_extruder) <= (degTargetHotend(target_extruder)+TEMP_WINDOW))) || + (residency_start_ms > -1 && labs(degHotend(target_extruder) - degTargetHotend(target_extruder)) > TEMP_HYSTERESIS) ) + { + residency_start_ms = millis(); + } + #endif //TEMP_RESIDENCY_TIME + } + + LCD_MESSAGEPGM(MSG_HEATING_COMPLETE); + refresh_cmd_timeout(); + starttime = previous_cmd_ms; +} + +#if HAS_TEMP_BED + + /** + * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating + * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling + */ + inline void gcode_M190() { + LCD_MESSAGEPGM(MSG_BED_HEATING); + CooldownNoWait = code_seen('S'); + if (CooldownNoWait || code_seen('R')) + setTargetBed(code_value()); + + millis_t temp_ms = millis(); + + cancel_heatup = false; + target_direction = isHeatingBed(); // true if heating, false if cooling + + while ( (target_direction)&&(!cancel_heatup) ? (isHeatingBed()) : (isCoolingBed()&&(CooldownNoWait==false)) ) { + millis_t ms = millis(); + if (ms > temp_ms + 1000UL) { //Print Temp Reading every 1 second while heating up. + temp_ms = ms; + float tt = degHotend(active_extruder); + SERIAL_PROTOCOLPGM("T:"); + SERIAL_PROTOCOL(tt); + SERIAL_PROTOCOLPGM(" E:"); + SERIAL_PROTOCOL((int)active_extruder); + SERIAL_PROTOCOLPGM(" B:"); + SERIAL_PROTOCOL_F(degBed(), 1); + SERIAL_EOL; + } + manage_heater(); + manage_inactivity(); + lcd_update(); + } + LCD_MESSAGEPGM(MSG_BED_DONE); + refresh_cmd_timeout(); + } + +#endif // HAS_TEMP_BED + +/** + * M112: Emergency Stop + */ +inline void gcode_M112() { + kill(); +} + +#ifdef BARICUDA + + #if HAS_HEATER_1 + /** + * M126: Heater 1 valve open + */ + inline void gcode_M126() { ValvePressure = code_seen('S') ? constrain(code_value(), 0, 255) : 255; } + /** + * M127: Heater 1 valve close + */ + inline void gcode_M127() { ValvePressure = 0; } + #endif + + #if HAS_HEATER_2 + /** + * M128: Heater 2 valve open + */ + inline void gcode_M128() { EtoPPressure = code_seen('S') ? constrain(code_value(), 0, 255) : 255; } + /** + * M129: Heater 2 valve close + */ + inline void gcode_M129() { EtoPPressure = 0; } + #endif + +#endif //BARICUDA + +/** + * M140: Set bed temperature + */ +inline void gcode_M140() { + if (code_seen('S')) setTargetBed(code_value()); +} + +#if HAS_POWER_SWITCH + + /** + * M80: Turn on Power Supply + */ + inline void gcode_M80() { + OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); //GND + + // If you have a switch on suicide pin, this is useful + // if you want to start another print with suicide feature after + // a print without suicide... + #if HAS_SUICIDE + OUT_WRITE(SUICIDE_PIN, HIGH); + #endif + + #ifdef ULTIPANEL + powersupply = true; + LCD_MESSAGEPGM(WELCOME_MSG); + lcd_update(); + #endif + } + +#endif // HAS_POWER_SWITCH + +/** + * M81: Turn off Power, including Power Supply, if there is one. + * + * This code should ALWAYS be available for EMERGENCY SHUTDOWN! + */ +inline void gcode_M81() { + disable_heater(); + st_synchronize(); + disable_e0(); + disable_e1(); + disable_e2(); + disable_e3(); + finishAndDisableSteppers(); + fanSpeed = 0; + delay(1000); // Wait 1 second before switching off + #if HAS_SUICIDE + st_synchronize(); + suicide(); + #elif HAS_POWER_SWITCH + OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP); + #endif + #ifdef ULTIPANEL + #if HAS_POWER_SWITCH + powersupply = false; + #endif + LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF "."); + lcd_update(); + #endif +} + + +/** + * M82: Set E codes absolute (default) + */ +inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; } + +/** + * M82: Set E codes relative while in Absolute Coordinates (G90) mode + */ +inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; } + +/** + * M18, M84: Disable all stepper motors + */ +inline void gcode_M18_M84() { + if (code_seen('S')) { + stepper_inactive_time = code_value() * 1000; + } + else { + bool all_axis = !((code_seen(axis_codes[X_AXIS])) || (code_seen(axis_codes[Y_AXIS])) || (code_seen(axis_codes[Z_AXIS]))|| (code_seen(axis_codes[E_AXIS]))); + if (all_axis) { + st_synchronize(); + disable_e0(); + disable_e1(); + disable_e2(); + disable_e3(); + finishAndDisableSteppers(); + } + else { + st_synchronize(); + if (code_seen('X')) disable_x(); + if (code_seen('Y')) disable_y(); + if (code_seen('Z')) disable_z(); + #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS + if (code_seen('E')) { + disable_e0(); + disable_e1(); + disable_e2(); + disable_e3(); + } + #endif + } + } +} + +/** + * M85: Set inactivity shutdown timer with parameter S. To disable set zero (default) + */ +inline void gcode_M85() { + if (code_seen('S')) max_inactive_time = code_value() * 1000; +} + +/** + * M92: Set inactivity shutdown timer with parameter S. To disable set zero (default) + */ +inline void gcode_M92() { + for(int8_t i=0; i < NUM_AXIS; i++) { + if (code_seen(axis_codes[i])) { + if (i == E_AXIS) { + float value = code_value(); + if (value < 20.0) { + float factor = axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab. + max_e_jerk *= factor; + max_feedrate[i] *= factor; + axis_steps_per_sqr_second[i] *= factor; + } + axis_steps_per_unit[i] = value; + } + else { + axis_steps_per_unit[i] = code_value(); + } + } + } +} + +/** + * M114: Output current position to serial port + */ +inline void gcode_M114() { + SERIAL_PROTOCOLPGM("X:"); + SERIAL_PROTOCOL(current_position[X_AXIS]); + SERIAL_PROTOCOLPGM(" Y:"); + SERIAL_PROTOCOL(current_position[Y_AXIS]); + SERIAL_PROTOCOLPGM(" Z:"); + SERIAL_PROTOCOL(current_position[Z_AXIS]); + SERIAL_PROTOCOLPGM(" E:"); + SERIAL_PROTOCOL(current_position[E_AXIS]); + + SERIAL_PROTOCOLPGM(MSG_COUNT_X); + SERIAL_PROTOCOL(float(st_get_position(X_AXIS))/axis_steps_per_unit[X_AXIS]); + SERIAL_PROTOCOLPGM(" Y:"); + SERIAL_PROTOCOL(float(st_get_position(Y_AXIS))/axis_steps_per_unit[Y_AXIS]); + SERIAL_PROTOCOLPGM(" Z:"); + SERIAL_PROTOCOL(float(st_get_position(Z_AXIS))/axis_steps_per_unit[Z_AXIS]); + + SERIAL_EOL; + + #ifdef SCARA + SERIAL_PROTOCOLPGM("SCARA Theta:"); + SERIAL_PROTOCOL(delta[X_AXIS]); + SERIAL_PROTOCOLPGM(" Psi+Theta:"); + SERIAL_PROTOCOL(delta[Y_AXIS]); + SERIAL_EOL; + + SERIAL_PROTOCOLPGM("SCARA Cal - Theta:"); + SERIAL_PROTOCOL(delta[X_AXIS]+home_offset[X_AXIS]); + SERIAL_PROTOCOLPGM(" Psi+Theta (90):"); + SERIAL_PROTOCOL(delta[Y_AXIS]-delta[X_AXIS]-90+home_offset[Y_AXIS]); + SERIAL_EOL; + + SERIAL_PROTOCOLPGM("SCARA step Cal - Theta:"); + SERIAL_PROTOCOL(delta[X_AXIS]/90*axis_steps_per_unit[X_AXIS]); + SERIAL_PROTOCOLPGM(" Psi+Theta:"); + SERIAL_PROTOCOL((delta[Y_AXIS]-delta[X_AXIS])/90*axis_steps_per_unit[Y_AXIS]); + SERIAL_EOL; SERIAL_EOL; + #endif +} + +/** + * M115: Capabilities string + */ +inline void gcode_M115() { + SERIAL_PROTOCOLPGM(MSG_M115_REPORT); +} + +/** + * M117: Set LCD Status Message + */ +inline void gcode_M117() { + char* codepos = strchr_pointer + 5; + char* starpos = strchr(codepos, '*'); + if (starpos) *starpos = '\0'; + lcd_setstatus(codepos); +} + +/** + * M119: Output endstop states to serial output + */ +inline void gcode_M119() { + SERIAL_PROTOCOLLN(MSG_M119_REPORT); + #if HAS_X_MIN + SERIAL_PROTOCOLPGM(MSG_X_MIN); + SERIAL_PROTOCOLLN(((READ(X_MIN_PIN)^X_MIN_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN)); + #endif + #if HAS_X_MAX + SERIAL_PROTOCOLPGM(MSG_X_MAX); + SERIAL_PROTOCOLLN(((READ(X_MAX_PIN)^X_MAX_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN)); + #endif + #if HAS_Y_MIN + SERIAL_PROTOCOLPGM(MSG_Y_MIN); + SERIAL_PROTOCOLLN(((READ(Y_MIN_PIN)^Y_MIN_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN)); + #endif + #if HAS_Y_MAX + SERIAL_PROTOCOLPGM(MSG_Y_MAX); + SERIAL_PROTOCOLLN(((READ(Y_MAX_PIN)^Y_MAX_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN)); + #endif + #if HAS_Z_MIN + SERIAL_PROTOCOLPGM(MSG_Z_MIN); + SERIAL_PROTOCOLLN(((READ(Z_MIN_PIN)^Z_MIN_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN)); + #endif + #if HAS_Z_MAX + SERIAL_PROTOCOLPGM(MSG_Z_MAX); + SERIAL_PROTOCOLLN(((READ(Z_MAX_PIN)^Z_MAX_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN)); + #endif + #if HAS_Z2_MAX + SERIAL_PROTOCOLPGM(MSG_Z2_MAX); + SERIAL_PROTOCOLLN(((READ(Z2_MAX_PIN)^Z2_MAX_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN)); + #endif + #if HAS_Z_PROBE + SERIAL_PROTOCOLPGM(MSG_Z_PROBE); + SERIAL_PROTOCOLLN(((READ(Z_PROBE_PIN)^Z_PROBE_ENDSTOP_INVERTING)?MSG_ENDSTOP_HIT:MSG_ENDSTOP_OPEN)); + #endif +} + +/** + * M120: Enable endstops + */ +inline void gcode_M120() { enable_endstops(false); } + +/** + * M121: Disable endstops + */ +inline void gcode_M121() { enable_endstops(true); } + +#ifdef BLINKM + + /** + * M150: Set Status LED Color - Use R-U-B for R-G-B + */ + inline void gcode_M150() { + SendColors( + code_seen('R') ? (byte)code_value_short() : 0, + code_seen('U') ? (byte)code_value_short() : 0, + code_seen('B') ? (byte)code_value_short() : 0 + ); + } + +#endif // BLINKM + +/** + * M200: Set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters). + * T + * D + */ +inline void gcode_M200() { + int tmp_extruder = active_extruder; + if (code_seen('T')) { + tmp_extruder = code_value_short(); + if (tmp_extruder >= EXTRUDERS) { + SERIAL_ECHO_START; + SERIAL_ECHO(MSG_M200_INVALID_EXTRUDER); + return; + } + } + + if (code_seen('D')) { + float diameter = code_value(); + // setting any extruder filament size disables volumetric on the assumption that + // slicers either generate in extruder values as cubic mm or as as filament feeds + // for all extruders + volumetric_enabled = (diameter != 0.0); + if (volumetric_enabled) { + filament_size[tmp_extruder] = diameter; + // make sure all extruders have some sane value for the filament size + for (int i=0; i 1 + + /** + * M218 - set hotend offset (in mm), T X Y + */ + inline void gcode_M218() { + if (setTargetedHotend(218)) return; + + if (code_seen('X')) extruder_offset[X_AXIS][target_extruder] = code_value(); + if (code_seen('Y')) extruder_offset[Y_AXIS][target_extruder] = code_value(); + + #ifdef DUAL_X_CARRIAGE + if (code_seen('Z')) extruder_offset[Z_AXIS][target_extruder] = code_value(); + #endif + + SERIAL_ECHO_START; + SERIAL_ECHOPGM(MSG_HOTEND_OFFSET); + for (int e = 0; e < EXTRUDERS; e++) { + SERIAL_CHAR(' '); + SERIAL_ECHO(extruder_offset[X_AXIS][e]); + SERIAL_CHAR(','); + SERIAL_ECHO(extruder_offset[Y_AXIS][e]); + #ifdef DUAL_X_CARRIAGE + SERIAL_CHAR(','); + SERIAL_ECHO(extruder_offset[Z_AXIS][e]); + #endif + } + SERIAL_EOL; + } + +#endif // EXTRUDERS > 1 + +/** + * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95) + */ +inline void gcode_M220() { + if (code_seen('S')) feedmultiply = code_value(); +} + +/** + * M221: Set extrusion percentage (M221 T0 S95) + */ +inline void gcode_M221() { + if (code_seen('S')) { + int sval = code_value(); + if (code_seen('T')) { + if (setTargetedHotend(221)) return; + extruder_multiply[target_extruder] = sval; + } + else { + extruder_multiply[active_extruder] = sval; + } + } +} + +/** + * M226: Wait until the specified pin reaches the state required (M226 P S) + */ +inline void gcode_M226() { + if (code_seen('P')) { + int pin_number = code_value(); + + int pin_state = code_seen('S') ? code_value() : -1; // required pin state - default is inverted + + if (pin_state >= -1 && pin_state <= 1) { + + for (int8_t i = 0; i < (int8_t)(sizeof(sensitive_pins)/sizeof(*sensitive_pins)); i++) { + if (sensitive_pins[i] == pin_number) { + pin_number = -1; + break; + } + } + + if (pin_number > -1) { + int target = LOW; + + st_synchronize(); + + pinMode(pin_number, INPUT); + + switch(pin_state){ + case 1: + target = HIGH; + break; + + case 0: + target = LOW; + break; + + case -1: + target = !digitalRead(pin_number); + break; + } + + while(digitalRead(pin_number) != target) { + manage_heater(); + manage_inactivity(); + lcd_update(); + } + + } // pin_number > -1 + } // pin_state -1 0 1 + } // code_seen('P') +} + +#if NUM_SERVOS > 0 + + /** + * M280: Set servo position absolute. P: servo index, S: angle or microseconds + */ + inline void gcode_M280() { + int servo_index = code_seen('P') ? code_value() : -1; + int servo_position = 0; + if (code_seen('S')) { + servo_position = code_value(); + if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) { + #if SERVO_LEVELING + servos[servo_index].attach(0); + #endif + servos[servo_index].write(servo_position); + #if SERVO_LEVELING + delay(PROBE_SERVO_DEACTIVATION_DELAY); + servos[servo_index].detach(); + #endif + } + else { + SERIAL_ECHO_START; + SERIAL_ECHO("Servo "); + SERIAL_ECHO(servo_index); + SERIAL_ECHOLN(" out of range"); + } + } + else if (servo_index >= 0) { + SERIAL_PROTOCOL(MSG_OK); + SERIAL_PROTOCOL(" Servo "); + SERIAL_PROTOCOL(servo_index); + SERIAL_PROTOCOL(": "); + SERIAL_PROTOCOL(servos[servo_index].read()); + SERIAL_EOL; + } + } + +#endif // NUM_SERVOS > 0 + +#if BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER) + + /** + * M300: Play beep sound S P + */ + inline void gcode_M300() { + uint16_t beepS = code_seen('S') ? code_value_short() : 110; + uint32_t beepP = code_seen('P') ? code_value_long() : 1000; + if (beepS > 0) { + #if BEEPER > 0 + tone(BEEPER, beepS); + delay(beepP); + noTone(BEEPER); + #elif defined(ULTRALCD) + lcd_buzz(beepS, beepP); + #elif defined(LCD_USE_I2C_BUZZER) + lcd_buzz(beepP, beepS); + #endif + } + else { + delay(beepP); + } + } + +#endif // BEEPER>0 || ULTRALCD || LCD_USE_I2C_BUZZER + +#ifdef PIDTEMP + + /** + * M301: Set PID parameters P I D (and optionally C) + */ + inline void gcode_M301() { + + // multi-extruder PID patch: M301 updates or prints a single extruder's PID values + // default behaviour (omitting E parameter) is to update for extruder 0 only + int e = code_seen('E') ? code_value() : 0; // extruder being updated + + if (e < EXTRUDERS) { // catch bad input value + if (code_seen('P')) PID_PARAM(Kp, e) = code_value(); + if (code_seen('I')) PID_PARAM(Ki, e) = scalePID_i(code_value()); + if (code_seen('D')) PID_PARAM(Kd, e) = scalePID_d(code_value()); + #ifdef PID_ADD_EXTRUSION_RATE + if (code_seen('C')) PID_PARAM(Kc, e) = code_value(); + #endif + + updatePID(); + SERIAL_PROTOCOL(MSG_OK); + #ifdef PID_PARAMS_PER_EXTRUDER + SERIAL_PROTOCOL(" e:"); // specify extruder in serial output + SERIAL_PROTOCOL(e); + #endif // PID_PARAMS_PER_EXTRUDER + SERIAL_PROTOCOL(" p:"); + SERIAL_PROTOCOL(PID_PARAM(Kp, e)); + SERIAL_PROTOCOL(" i:"); + SERIAL_PROTOCOL(unscalePID_i(PID_PARAM(Ki, e))); + SERIAL_PROTOCOL(" d:"); + SERIAL_PROTOCOL(unscalePID_d(PID_PARAM(Kd, e))); + #ifdef PID_ADD_EXTRUSION_RATE + SERIAL_PROTOCOL(" c:"); + //Kc does not have scaling applied above, or in resetting defaults + SERIAL_PROTOCOL(PID_PARAM(Kc, e)); + #endif + SERIAL_EOL; + } + else { + SERIAL_ECHO_START; + SERIAL_ECHOLN(MSG_INVALID_EXTRUDER); + } + } + +#endif // PIDTEMP + +#ifdef PIDTEMPBED + + inline void gcode_M304() { + if (code_seen('P')) bedKp = code_value(); + if (code_seen('I')) bedKi = scalePID_i(code_value()); + if (code_seen('D')) bedKd = scalePID_d(code_value()); + + updatePID(); + SERIAL_PROTOCOL(MSG_OK); + SERIAL_PROTOCOL(" p:"); + SERIAL_PROTOCOL(bedKp); + SERIAL_PROTOCOL(" i:"); + SERIAL_PROTOCOL(unscalePID_i(bedKi)); + SERIAL_PROTOCOL(" d:"); + SERIAL_PROTOCOL(unscalePID_d(bedKd)); + SERIAL_EOL; + } + +#endif // PIDTEMPBED + +#if defined(CHDK) || HAS_PHOTOGRAPH + + /** + * M240: Trigger a camera by emulating a Canon RC-1 + * See http://www.doc-diy.net/photo/rc-1_hacked/ + */ + inline void gcode_M240() { + #ifdef CHDK + + OUT_WRITE(CHDK, HIGH); + chdkHigh = millis(); + chdkActive = true; + + #elif HAS_PHOTOGRAPH + + const uint8_t NUM_PULSES = 16; + const float PULSE_LENGTH = 0.01524; + for (int i = 0; i < NUM_PULSES; i++) { + WRITE(PHOTOGRAPH_PIN, HIGH); + _delay_ms(PULSE_LENGTH); + WRITE(PHOTOGRAPH_PIN, LOW); + _delay_ms(PULSE_LENGTH); + } + delay(7.33); + for (int i = 0; i < NUM_PULSES; i++) { + WRITE(PHOTOGRAPH_PIN, HIGH); + _delay_ms(PULSE_LENGTH); + WRITE(PHOTOGRAPH_PIN, LOW); + _delay_ms(PULSE_LENGTH); + } + + #endif // !CHDK && HAS_PHOTOGRAPH + } + +#endif // CHDK || PHOTOGRAPH_PIN + +#ifdef HAS_LCD_CONTRAST + + /** + * M250: Read and optionally set the LCD contrast + */ + inline void gcode_M250() { + if (code_seen('C')) lcd_setcontrast(code_value_short() & 0x3F); + SERIAL_PROTOCOLPGM("lcd contrast value: "); + SERIAL_PROTOCOL(lcd_contrast); + SERIAL_EOL; + } + +#endif // HAS_LCD_CONTRAST + +#ifdef PREVENT_DANGEROUS_EXTRUDE + + void set_extrude_min_temp(float temp) { extrude_min_temp = temp; } + + /** + * M302: Allow cold extrudes, or set the minimum extrude S. + */ + inline void gcode_M302() { + set_extrude_min_temp(code_seen('S') ? code_value() : 0); + } + +#endif // PREVENT_DANGEROUS_EXTRUDE + +/** + * M303: PID relay autotune + * S sets the target temperature. (default target temperature = 150C) + * E (-1 for the bed) + * C + */ +inline void gcode_M303() { + int e = code_seen('E') ? code_value_short() : 0; + int c = code_seen('C') ? code_value_short() : 5; + float temp = code_seen('S') ? code_value() : (e < 0 ? 70.0 : 150.0); + PID_autotune(temp, e, c); +} + +#ifdef SCARA + bool SCARA_move_to_cal(uint8_t delta_x, uint8_t delta_y) { + //SoftEndsEnabled = false; // Ignore soft endstops during calibration + //SERIAL_ECHOLN(" Soft endstops disabled "); + if (IsRunning()) { + //get_coordinates(); // For X Y Z E F + delta[X_AXIS] = delta_x; + delta[Y_AXIS] = delta_y; + calculate_SCARA_forward_Transform(delta); + destination[X_AXIS] = delta[X_AXIS]/axis_scaling[X_AXIS]; + destination[Y_AXIS] = delta[Y_AXIS]/axis_scaling[Y_AXIS]; + prepare_move(); + //ClearToSend(); + return true; + } + return false; + } + + /** + * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration) + */ + inline bool gcode_M360() { + SERIAL_ECHOLN(" Cal: Theta 0 "); + return SCARA_move_to_cal(0, 120); + } + + /** + * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree) + */ + inline bool gcode_M361() { + SERIAL_ECHOLN(" Cal: Theta 90 "); + return SCARA_move_to_cal(90, 130); + } + + /** + * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration) + */ + inline bool gcode_M362() { + SERIAL_ECHOLN(" Cal: Psi 0 "); + return SCARA_move_to_cal(60, 180); + } + + /** + * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree) + */ + inline bool gcode_M363() { + SERIAL_ECHOLN(" Cal: Psi 90 "); + return SCARA_move_to_cal(50, 90); + } + + /** + * M364: SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position) + */ + inline bool gcode_M364() { + SERIAL_ECHOLN(" Cal: Theta-Psi 90 "); + return SCARA_move_to_cal(45, 135); + } + + /** + * M365: SCARA calibration: Scaling factor, X, Y, Z axis + */ + inline void gcode_M365() { + for (int8_t i = X_AXIS; i <= Z_AXIS; i++) { + if (code_seen(axis_codes[i])) { + axis_scaling[i] = code_value(); + } + } + } + +#endif // SCARA + +#ifdef EXT_SOLENOID + + void enable_solenoid(uint8_t num) { + switch(num) { + case 0: + OUT_WRITE(SOL0_PIN, HIGH); + break; + #if HAS_SOLENOID_1 + case 1: + OUT_WRITE(SOL1_PIN, HIGH); + break; + #endif + #if HAS_SOLENOID_2 + case 2: + OUT_WRITE(SOL2_PIN, HIGH); + break; + #endif + #if HAS_SOLENOID_3 + case 3: + OUT_WRITE(SOL3_PIN, HIGH); + break; + #endif + default: + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID); + break; + } + } + + void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); } + + void disable_all_solenoids() { + OUT_WRITE(SOL0_PIN, LOW); + OUT_WRITE(SOL1_PIN, LOW); + OUT_WRITE(SOL2_PIN, LOW); + OUT_WRITE(SOL3_PIN, LOW); + } + + /** + * M380: Enable solenoid on the active extruder + */ + inline void gcode_M380() { enable_solenoid_on_active_extruder(); } + + /** + * M381: Disable all solenoids + */ + inline void gcode_M381() { disable_all_solenoids(); } + +#endif // EXT_SOLENOID + +/** + * M400: Finish all moves + */ +inline void gcode_M400() { st_synchronize(); } + +#if defined(ENABLE_AUTO_BED_LEVELING) && (defined(SERVO_ENDSTOPS) || defined(Z_PROBE_ALLEN_KEY)) && not defined(Z_PROBE_SLED) + + /** + * M401: Engage Z Servo endstop if available + */ + inline void gcode_M401() { deploy_z_probe(); } + /** + * M402: Retract Z Servo endstop if enabled + */ + inline void gcode_M402() { stow_z_probe(); } + +#endif + +#ifdef FILAMENT_SENSOR + + /** + * M404: Display or set the nominal filament width (3mm, 1.75mm ) W<3.0> + */ + inline void gcode_M404() { + #if HAS_FILWIDTH + if (code_seen('W')) { + filament_width_nominal = code_value(); + } + else { + SERIAL_PROTOCOLPGM("Filament dia (nominal mm):"); + SERIAL_PROTOCOLLN(filament_width_nominal); + } + #endif + } + + /** + * M405: Turn on filament sensor for control + */ + inline void gcode_M405() { + if (code_seen('D')) meas_delay_cm = code_value(); + if (meas_delay_cm > MAX_MEASUREMENT_DELAY) meas_delay_cm = MAX_MEASUREMENT_DELAY; + + if (delay_index2 == -1) { //initialize the ring buffer if it has not been done since startup + int temp_ratio = widthFil_to_size_ratio(); + + for (delay_index1 = 0; delay_index1 < MAX_MEASUREMENT_DELAY + 1; ++delay_index1) + measurement_delay[delay_index1] = temp_ratio - 100; //subtract 100 to scale within a signed byte + + delay_index1 = delay_index2 = 0; + } + + filament_sensor = true; + + //SERIAL_PROTOCOLPGM("Filament dia (measured mm):"); + //SERIAL_PROTOCOL(filament_width_meas); + //SERIAL_PROTOCOLPGM("Extrusion ratio(%):"); + //SERIAL_PROTOCOL(extruder_multiply[active_extruder]); + } + + /** + * M406: Turn off filament sensor for control + */ + inline void gcode_M406() { filament_sensor = false; } + + /** + * M407: Get measured filament diameter on serial output + */ + inline void gcode_M407() { + SERIAL_PROTOCOLPGM("Filament dia (measured mm):"); + SERIAL_PROTOCOLLN(filament_width_meas); + } + +#endif // FILAMENT_SENSOR + +/** + * M500: Store settings in EEPROM + */ +inline void gcode_M500() { + Config_StoreSettings(); +} + +/** + * M501: Read settings from EEPROM + */ +inline void gcode_M501() { + Config_RetrieveSettings(); +} + +/** + * M502: Revert to default settings + */ +inline void gcode_M502() { + Config_ResetDefault(); +} + +/** + * M503: print settings currently in memory + */ +inline void gcode_M503() { + Config_PrintSettings(code_seen('S') && code_value() == 0); +} + +#ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED + + /** + * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>) + */ + inline void gcode_M540() { + if (code_seen('S')) abort_on_endstop_hit = (code_value() > 0); + } + +#endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED + +#ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET + + inline void gcode_SET_Z_PROBE_OFFSET() { + float value; + if (code_seen('Z')) { + value = code_value(); + if (Z_PROBE_OFFSET_RANGE_MIN <= value && value <= Z_PROBE_OFFSET_RANGE_MAX) { + zprobe_zoffset = -value; // compare w/ line 278 of ConfigurationStore.cpp + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM(MSG_ZPROBE_ZOFFSET " " MSG_OK); + SERIAL_EOL; + } + else { + SERIAL_ECHO_START; + SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET); + SERIAL_ECHOPGM(MSG_Z_MIN); + SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN); + SERIAL_ECHOPGM(MSG_Z_MAX); + SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX); + SERIAL_EOL; + } + } + else { + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM(MSG_ZPROBE_ZOFFSET " : "); + SERIAL_ECHO(-zprobe_zoffset); + SERIAL_EOL; + } + } + +#endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET + +#ifdef FILAMENTCHANGEENABLE + + /** + * M600: Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal] + */ + inline void gcode_M600() { + float target[NUM_AXIS], lastpos[NUM_AXIS], fr60 = feedrate / 60; + for (int i=0; i S) + */ + inline void gcode_M908() { + digitalPotWrite( + code_seen('P') ? code_value() : 0, + code_seen('S') ? code_value() : 0 + ); + } + +#endif // HAS_DIGIPOTSS + +#if HAS_MICROSTEPS + + // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers. + inline void gcode_M350() { + if(code_seen('S')) for(int i=0;i<=4;i++) microstep_mode(i,code_value()); + for(int i=0;i= EXTRUDERS) { + SERIAL_ECHO_START; + SERIAL_CHAR('T'); + SERIAL_ECHO(tmp_extruder); + SERIAL_ECHOLN(MSG_INVALID_EXTRUDER); + } + else { + target_extruder = tmp_extruder; + + #if EXTRUDERS > 1 + bool make_move = false; + #endif + + if (code_seen('F')) { + + #if EXTRUDERS > 1 + make_move = true; + #endif + + next_feedrate = code_value(); + if (next_feedrate > 0.0) feedrate = next_feedrate; + } + #if EXTRUDERS > 1 + if (tmp_extruder != active_extruder) { + // Save current position to return to after applying extruder offset + set_destination_to_current(); + #ifdef DUAL_X_CARRIAGE + if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE && IsRunning() && + (delayed_move_time != 0 || current_position[X_AXIS] != x_home_pos(active_extruder))) { + // Park old head: 1) raise 2) move to park position 3) lower + plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT, + current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder); + plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT, + current_position[E_AXIS], max_feedrate[X_AXIS], active_extruder); + plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS], + current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder); + st_synchronize(); + } + + // apply Y & Z extruder offset (x offset is already used in determining home pos) + current_position[Y_AXIS] = current_position[Y_AXIS] - + extruder_offset[Y_AXIS][active_extruder] + + extruder_offset[Y_AXIS][tmp_extruder]; + current_position[Z_AXIS] = current_position[Z_AXIS] - + extruder_offset[Z_AXIS][active_extruder] + + extruder_offset[Z_AXIS][tmp_extruder]; + + active_extruder = tmp_extruder; + + // This function resets the max/min values - the current position may be overwritten below. + axis_is_at_home(X_AXIS); + + if (dual_x_carriage_mode == DXC_FULL_CONTROL_MODE) { + current_position[X_AXIS] = inactive_extruder_x_pos; + inactive_extruder_x_pos = destination[X_AXIS]; + } + else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) { + active_extruder_parked = (active_extruder == 0); // this triggers the second extruder to move into the duplication position + if (active_extruder == 0 || active_extruder_parked) + current_position[X_AXIS] = inactive_extruder_x_pos; + else + current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset; + inactive_extruder_x_pos = destination[X_AXIS]; + extruder_duplication_enabled = false; + } + else { + // record raised toolhead position for use by unpark + memcpy(raised_parked_position, current_position, sizeof(raised_parked_position)); + raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT; + active_extruder_parked = true; + delayed_move_time = 0; + } + #else // !DUAL_X_CARRIAGE + // Offset extruder (only by XY) + for (int i=X_AXIS; i<=Y_AXIS; i++) + current_position[i] += extruder_offset[i][tmp_extruder] - extruder_offset[i][active_extruder]; + // Set the new active extruder and position + active_extruder = tmp_extruder; + #endif // !DUAL_X_CARRIAGE + #ifdef DELTA + sync_plan_position_delta(); + #else + sync_plan_position(); + #endif + // Move to the old position if 'F' was in the parameters + if (make_move && IsRunning()) prepare_move(); + } + + #ifdef EXT_SOLENOID + st_synchronize(); + disable_all_solenoids(); + enable_solenoid_on_active_extruder(); + #endif // EXT_SOLENOID + + #endif // EXTRUDERS > 1 + SERIAL_ECHO_START; + SERIAL_ECHO(MSG_ACTIVE_EXTRUDER); + SERIAL_PROTOCOLLN((int)active_extruder); + } +} + +/** + * Process Commands and dispatch them to handlers + * This is called from the main loop() + */ +void process_commands() { + if (code_seen('G')) { + + int gCode = code_value_short(); + + switch(gCode) { + + // G0, G1 + case 0: + case 1: + gcode_G0_G1(); + break; + + // G2, G3 + #ifndef SCARA + case 2: // G2 - CW ARC + case 3: // G3 - CCW ARC + gcode_G2_G3(gCode == 2); + break; + #endif + + // G4 Dwell + case 4: + gcode_G4(); + break; + + #ifdef FWRETRACT + + case 10: // G10: retract + case 11: // G11: retract_recover + gcode_G10_G11(gCode == 10); + break; + + #endif //FWRETRACT + + case 28: // G28: Home all axes, one at a time + gcode_G28(); + break; + + #if defined(ENABLE_AUTO_BED_LEVELING) || defined(MESH_BED_LEVELING) + case 29: // G29 Detailed Z-Probe, probes the bed at 3 or more points. + gcode_G29(); + break; + #endif + + #ifdef ENABLE_AUTO_BED_LEVELING + + #ifndef Z_PROBE_SLED + + case 30: // G30 Single Z Probe + gcode_G30(); + break; + + #else // Z_PROBE_SLED + + case 31: // G31: dock the sled + case 32: // G32: undock the sled + dock_sled(gCode == 31); + break; + + #endif // Z_PROBE_SLED + + #endif // ENABLE_AUTO_BED_LEVELING + + case 90: // G90 + relative_mode = false; + break; + case 91: // G91 + relative_mode = true; + break; + + case 92: // G92 + gcode_G92(); + break; + } + } + + else if (code_seen('M')) { + switch(code_value_short()) { + #ifdef ULTIPANEL + case 0: // M0 - Unconditional stop - Wait for user button press on LCD + case 1: // M1 - Conditional stop - Wait for user button press on LCD + gcode_M0_M1(); + break; + #endif // ULTIPANEL + + case 17: + gcode_M17(); + break; + + #ifdef SDSUPPORT + + case 20: // M20 - list SD card + gcode_M20(); break; + case 21: // M21 - init SD card + gcode_M21(); break; + case 22: //M22 - release SD card + gcode_M22(); break; + case 23: //M23 - Select file + gcode_M23(); break; + case 24: //M24 - Start SD print + gcode_M24(); break; + case 25: //M25 - Pause SD print + gcode_M25(); break; + case 26: //M26 - Set SD index + gcode_M26(); break; + case 27: //M27 - Get SD status + gcode_M27(); break; + case 28: //M28 - Start SD write + gcode_M28(); break; + case 29: //M29 - Stop SD write + gcode_M29(); break; + case 30: //M30 Delete File + gcode_M30(); break; + case 32: //M32 - Select file and start SD print + gcode_M32(); break; + case 928: //M928 - Start SD write + gcode_M928(); break; + + #endif //SDSUPPORT + + case 31: //M31 take time since the start of the SD print or an M109 command + gcode_M31(); + break; + + case 42: //M42 -Change pin status via gcode + gcode_M42(); + break; + + #if defined(ENABLE_AUTO_BED_LEVELING) && defined(Z_PROBE_REPEATABILITY_TEST) + case 48: // M48 Z-Probe repeatability + gcode_M48(); + break; + #endif // ENABLE_AUTO_BED_LEVELING && Z_PROBE_REPEATABILITY_TEST + + case 104: // M104 + gcode_M104(); + break; + + case 112: // M112 Emergency Stop + gcode_M112(); + break; + + case 140: // M140 Set bed temp + gcode_M140(); + break; + + case 105: // M105 Read current temperature + gcode_M105(); + return; + break; + + case 109: // M109 Wait for temperature + gcode_M109(); + break; + + #if HAS_TEMP_BED + case 190: // M190 - Wait for bed heater to reach target. + gcode_M190(); + break; + #endif // HAS_TEMP_BED + + #if HAS_FAN + case 106: //M106 Fan On + gcode_M106(); + break; + case 107: //M107 Fan Off + gcode_M107(); + break; + #endif // HAS_FAN + + #ifdef BARICUDA + // PWM for HEATER_1_PIN + #if HAS_HEATER_1 + case 126: // M126 valve open + gcode_M126(); + break; + case 127: // M127 valve closed + gcode_M127(); + break; + #endif // HAS_HEATER_1 + + // PWM for HEATER_2_PIN + #if HAS_HEATER_2 + case 128: // M128 valve open + gcode_M128(); + break; + case 129: // M129 valve closed + gcode_M129(); + break; + #endif // HAS_HEATER_2 + #endif // BARICUDA + + #if HAS_POWER_SWITCH + + case 80: // M80 - Turn on Power Supply + gcode_M80(); + break; + + #endif // HAS_POWER_SWITCH + + case 81: // M81 - Turn off Power, including Power Supply, if possible + gcode_M81(); + break; + + case 82: + gcode_M82(); + break; + case 83: + gcode_M83(); + break; + case 18: //compatibility + case 84: // M84 + gcode_M18_M84(); + break; + case 85: // M85 + gcode_M85(); + break; + case 92: // M92 + gcode_M92(); + break; + case 115: // M115 + gcode_M115(); + break; + case 117: // M117 display message + gcode_M117(); + break; + case 114: // M114 + gcode_M114(); + break; + case 120: // M120 + gcode_M120(); + break; + case 121: // M121 + gcode_M121(); + break; + case 119: // M119 + gcode_M119(); + break; + //TODO: update for all axis, use for loop + + #ifdef BLINKM + + case 150: // M150 + gcode_M150(); + break; + + #endif //BLINKM + + case 200: // M200 D set filament diameter and set E axis units to cubic millimeters (use S0 to set back to millimeters). + gcode_M200(); + break; + case 201: // M201 + gcode_M201(); + break; + #if 0 // Not used for Sprinter/grbl gen6 + case 202: // M202 + gcode_M202(); + break; + #endif + case 203: // M203 max feedrate mm/sec + gcode_M203(); + break; + case 204: // M204 acclereration S normal moves T filmanent only moves + gcode_M204(); + break; + case 205: //M205 advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk + gcode_M205(); + break; + case 206: // M206 additional homing offset + gcode_M206(); + break; + + #ifdef DELTA + case 665: // M665 set delta configurations L R S + gcode_M665(); + break; + #endif + + #if defined(DELTA) || defined(Z_DUAL_ENDSTOPS) + case 666: // M666 set delta / dual endstop adjustment + gcode_M666(); + break; + #endif + + #ifdef FWRETRACT + case 207: //M207 - set retract length S[positive mm] F[feedrate mm/min] Z[additional zlift/hop] + gcode_M207(); + break; + case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/min] + gcode_M208(); + break; + case 209: // M209 - S<1=true/0=false> enable automatic retract detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction. + gcode_M209(); + break; + #endif // FWRETRACT + + #if EXTRUDERS > 1 + case 218: // M218 - set hotend offset (in mm), T X Y + gcode_M218(); + break; + #endif + + case 220: // M220 S- set speed factor override percentage + gcode_M220(); + break; + + case 221: // M221 S- set extrude factor override percentage + gcode_M221(); + break; + + case 226: // M226 P S- Wait until the specified pin reaches the state required + gcode_M226(); + break; + + #if NUM_SERVOS > 0 + case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds + gcode_M280(); + break; + #endif // NUM_SERVOS > 0 + + #if BEEPER > 0 || defined(ULTRALCD) || defined(LCD_USE_I2C_BUZZER) + case 300: // M300 - Play beep tone + gcode_M300(); + break; + #endif // BEEPER > 0 || ULTRALCD || LCD_USE_I2C_BUZZER + + #ifdef PIDTEMP + case 301: // M301 + gcode_M301(); + break; + #endif // PIDTEMP + + #ifdef PIDTEMPBED + case 304: // M304 + gcode_M304(); + break; + #endif // PIDTEMPBED + + #if defined(CHDK) || HAS_PHOTOGRAPH + case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/ + gcode_M240(); + break; + #endif // CHDK || PHOTOGRAPH_PIN + + #ifdef HAS_LCD_CONTRAST + case 250: // M250 Set LCD contrast value: C (value 0..63) + gcode_M250(); + break; + #endif // HAS_LCD_CONTRAST + + #ifdef PREVENT_DANGEROUS_EXTRUDE + case 302: // allow cold extrudes, or set the minimum extrude temperature + gcode_M302(); + break; + #endif // PREVENT_DANGEROUS_EXTRUDE + + case 303: // M303 PID autotune + gcode_M303(); + break; + + #ifdef SCARA + case 360: // M360 SCARA Theta pos1 + if (gcode_M360()) return; + break; + case 361: // M361 SCARA Theta pos2 + if (gcode_M361()) return; + break; + case 362: // M362 SCARA Psi pos1 + if (gcode_M362()) return; + break; + case 363: // M363 SCARA Psi pos2 + if (gcode_M363()) return; + break; + case 364: // M364 SCARA Psi pos3 (90 deg to Theta) + if (gcode_M364()) return; + break; + case 365: // M365 Set SCARA scaling for X Y Z + gcode_M365(); + break; + #endif // SCARA + + case 400: // M400 finish all moves + gcode_M400(); + break; + + #if defined(ENABLE_AUTO_BED_LEVELING) && (defined(SERVO_ENDSTOPS) || defined(Z_PROBE_ALLEN_KEY)) && not defined(Z_PROBE_SLED) + case 401: + gcode_M401(); + break; + case 402: + gcode_M402(); + break; + #endif + + #ifdef FILAMENT_SENSOR + case 404: //M404 Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width + gcode_M404(); + break; + case 405: //M405 Turn on filament sensor for control + gcode_M405(); + break; + case 406: //M406 Turn off filament sensor for control + gcode_M406(); + break; + case 407: //M407 Display measured filament diameter + gcode_M407(); + break; + #endif // FILAMENT_SENSOR + + case 500: // M500 Store settings in EEPROM + gcode_M500(); + break; + case 501: // M501 Read settings from EEPROM + gcode_M501(); + break; + case 502: // M502 Revert to default settings + gcode_M502(); + break; + case 503: // M503 print settings currently in memory + gcode_M503(); + break; + + #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED + case 540: + gcode_M540(); + break; + #endif + + #ifdef CUSTOM_M_CODE_SET_Z_PROBE_OFFSET + case CUSTOM_M_CODE_SET_Z_PROBE_OFFSET: + gcode_SET_Z_PROBE_OFFSET(); + break; + #endif // CUSTOM_M_CODE_SET_Z_PROBE_OFFSET + + #ifdef FILAMENTCHANGEENABLE + case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal] + gcode_M600(); + break; + #endif // FILAMENTCHANGEENABLE + + #ifdef DUAL_X_CARRIAGE + case 605: + gcode_M605(); + break; + #endif // DUAL_X_CARRIAGE + + case 907: // M907 Set digital trimpot motor current using axis codes. + gcode_M907(); + break; + + #if HAS_DIGIPOTSS + case 908: // M908 Control digital trimpot directly. + gcode_M908(); + break; + #endif // HAS_DIGIPOTSS + + #if HAS_MICROSTEPS + + case 350: // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers. + gcode_M350(); + break; + + case 351: // M351 Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low. + gcode_M351(); + break; + + #endif // HAS_MICROSTEPS + + case 999: // M999: Restart after being Stopped + gcode_M999(); + break; + } + } + + else if (code_seen('T')) { + gcode_T(); + } + + else { + SERIAL_ECHO_START; + SERIAL_ECHOPGM(MSG_UNKNOWN_COMMAND); + SERIAL_ECHO(cmdbuffer[bufindr]); + SERIAL_ECHOLNPGM("\""); + } + + ClearToSend(); +} + +void FlushSerialRequestResend() { + //char cmdbuffer[bufindr][100]="Resend:"; + MYSERIAL.flush(); + SERIAL_PROTOCOLPGM(MSG_RESEND); + SERIAL_PROTOCOLLN(gcode_LastN + 1); + ClearToSend(); +} + +void ClearToSend() { + refresh_cmd_timeout(); + #ifdef SDSUPPORT + if (fromsd[bufindr]) return; + #endif + SERIAL_PROTOCOLLNPGM(MSG_OK); +} + +void get_coordinates() { + for (int i = 0; i < NUM_AXIS; i++) { + if (code_seen(axis_codes[i])) + destination[i] = code_value() + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0); + else + destination[i] = current_position[i]; + } + if (code_seen('F')) { + next_feedrate = code_value(); + if (next_feedrate > 0.0) feedrate = next_feedrate; + } +} + +void get_arc_coordinates() { + #ifdef SF_ARC_FIX + bool relative_mode_backup = relative_mode; + relative_mode = true; + #endif + get_coordinates(); + #ifdef SF_ARC_FIX + relative_mode = relative_mode_backup; + #endif + + offset[0] = code_seen('I') ? code_value() : 0; + offset[1] = code_seen('J') ? code_value() : 0; +} + +void clamp_to_software_endstops(float target[3]) { + if (min_software_endstops) { + NOLESS(target[X_AXIS], min_pos[X_AXIS]); + NOLESS(target[Y_AXIS], min_pos[Y_AXIS]); + + float negative_z_offset = 0; + #ifdef ENABLE_AUTO_BED_LEVELING + if (Z_PROBE_OFFSET_FROM_EXTRUDER < 0) negative_z_offset += Z_PROBE_OFFSET_FROM_EXTRUDER; + if (home_offset[Z_AXIS] < 0) negative_z_offset += home_offset[Z_AXIS]; + #endif + NOLESS(target[Z_AXIS], min_pos[Z_AXIS] + negative_z_offset); + } + + if (max_software_endstops) { + NOMORE(target[X_AXIS], max_pos[X_AXIS]); + NOMORE(target[Y_AXIS], max_pos[Y_AXIS]); + NOMORE(target[Z_AXIS], max_pos[Z_AXIS]); + } +} + +#ifdef DELTA + + void recalc_delta_settings(float radius, float diagonal_rod) { + delta_tower1_x = -SIN_60 * radius; // front left tower + delta_tower1_y = -COS_60 * radius; + delta_tower2_x = SIN_60 * radius; // front right tower + delta_tower2_y = -COS_60 * radius; + delta_tower3_x = 0.0; // back middle tower + delta_tower3_y = radius; + delta_diagonal_rod_2 = sq(diagonal_rod); + } + + void calculate_delta(float cartesian[3]) { + delta[X_AXIS] = sqrt(delta_diagonal_rod_2 + - sq(delta_tower1_x-cartesian[X_AXIS]) + - sq(delta_tower1_y-cartesian[Y_AXIS]) + ) + cartesian[Z_AXIS]; + delta[Y_AXIS] = sqrt(delta_diagonal_rod_2 + - sq(delta_tower2_x-cartesian[X_AXIS]) + - sq(delta_tower2_y-cartesian[Y_AXIS]) + ) + cartesian[Z_AXIS]; + delta[Z_AXIS] = sqrt(delta_diagonal_rod_2 + - sq(delta_tower3_x-cartesian[X_AXIS]) + - sq(delta_tower3_y-cartesian[Y_AXIS]) + ) + cartesian[Z_AXIS]; + /* + SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]); + SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]); + SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]); + + SERIAL_ECHOPGM("delta x="); SERIAL_ECHO(delta[X_AXIS]); + SERIAL_ECHOPGM(" y="); SERIAL_ECHO(delta[Y_AXIS]); + SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(delta[Z_AXIS]); + */ + } + + #ifdef ENABLE_AUTO_BED_LEVELING + + // Adjust print surface height by linear interpolation over the bed_level array. + void adjust_delta(float cartesian[3]) { + if (delta_grid_spacing[0] == 0 || delta_grid_spacing[1] == 0) return; // G29 not done! + + int half = (AUTO_BED_LEVELING_GRID_POINTS - 1) / 2; + float h1 = 0.001 - half, h2 = half - 0.001, + grid_x = max(h1, min(h2, cartesian[X_AXIS] / delta_grid_spacing[0])), + grid_y = max(h1, min(h2, cartesian[Y_AXIS] / delta_grid_spacing[1])); + int floor_x = floor(grid_x), floor_y = floor(grid_y); + float ratio_x = grid_x - floor_x, ratio_y = grid_y - floor_y, + z1 = bed_level[floor_x + half][floor_y + half], + z2 = bed_level[floor_x + half][floor_y + half + 1], + z3 = bed_level[floor_x + half + 1][floor_y + half], + z4 = bed_level[floor_x + half + 1][floor_y + half + 1], + left = (1 - ratio_y) * z1 + ratio_y * z2, + right = (1 - ratio_y) * z3 + ratio_y * z4, + offset = (1 - ratio_x) * left + ratio_x * right; + + delta[X_AXIS] += offset; + delta[Y_AXIS] += offset; + delta[Z_AXIS] += offset; + + /* + SERIAL_ECHOPGM("grid_x="); SERIAL_ECHO(grid_x); + SERIAL_ECHOPGM(" grid_y="); SERIAL_ECHO(grid_y); + SERIAL_ECHOPGM(" floor_x="); SERIAL_ECHO(floor_x); + SERIAL_ECHOPGM(" floor_y="); SERIAL_ECHO(floor_y); + SERIAL_ECHOPGM(" ratio_x="); SERIAL_ECHO(ratio_x); + SERIAL_ECHOPGM(" ratio_y="); SERIAL_ECHO(ratio_y); + SERIAL_ECHOPGM(" z1="); SERIAL_ECHO(z1); + SERIAL_ECHOPGM(" z2="); SERIAL_ECHO(z2); + SERIAL_ECHOPGM(" z3="); SERIAL_ECHO(z3); + SERIAL_ECHOPGM(" z4="); SERIAL_ECHO(z4); + SERIAL_ECHOPGM(" left="); SERIAL_ECHO(left); + SERIAL_ECHOPGM(" right="); SERIAL_ECHO(right); + SERIAL_ECHOPGM(" offset="); SERIAL_ECHOLN(offset); + */ + } + #endif // ENABLE_AUTO_BED_LEVELING + +#endif // DELTA + +#ifdef MESH_BED_LEVELING + + #if !defined(MIN) + #define MIN(_v1, _v2) (((_v1) < (_v2)) ? (_v1) : (_v2)) + #endif // ! MIN + +// This function is used to split lines on mesh borders so each segment is only part of one mesh area +void mesh_plan_buffer_line(float x, float y, float z, const float e, float feed_rate, const uint8_t &extruder, uint8_t x_splits=0xff, uint8_t y_splits=0xff) +{ + if (!mbl.active) { + plan_buffer_line(x, y, z, e, feed_rate, extruder); + set_current_to_destination(); + return; + } + int pix = mbl.select_x_index(current_position[X_AXIS]); + int piy = mbl.select_y_index(current_position[Y_AXIS]); + int ix = mbl.select_x_index(x); + int iy = mbl.select_y_index(y); + pix = MIN(pix, MESH_NUM_X_POINTS-2); + piy = MIN(piy, MESH_NUM_Y_POINTS-2); + ix = MIN(ix, MESH_NUM_X_POINTS-2); + iy = MIN(iy, MESH_NUM_Y_POINTS-2); + if (pix == ix && piy == iy) { + // Start and end on same mesh square + plan_buffer_line(x, y, z, e, feed_rate, extruder); + set_current_to_destination(); + return; + } + float nx, ny, ne, normalized_dist; + if (ix > pix && (x_splits) & BIT(ix)) { + nx = mbl.get_x(ix); + normalized_dist = (nx - current_position[X_AXIS])/(x - current_position[X_AXIS]); + ny = current_position[Y_AXIS] + (y - current_position[Y_AXIS]) * normalized_dist; + ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist; + x_splits ^= BIT(ix); + } else if (ix < pix && (x_splits) & BIT(pix)) { + nx = mbl.get_x(pix); + normalized_dist = (nx - current_position[X_AXIS])/(x - current_position[X_AXIS]); + ny = current_position[Y_AXIS] + (y - current_position[Y_AXIS]) * normalized_dist; + ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist; + x_splits ^= BIT(pix); + } else if (iy > piy && (y_splits) & BIT(iy)) { + ny = mbl.get_y(iy); + normalized_dist = (ny - current_position[Y_AXIS])/(y - current_position[Y_AXIS]); + nx = current_position[X_AXIS] + (x - current_position[X_AXIS]) * normalized_dist; + ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist; + y_splits ^= BIT(iy); + } else if (iy < piy && (y_splits) & BIT(piy)) { + ny = mbl.get_y(piy); + normalized_dist = (ny - current_position[Y_AXIS])/(y - current_position[Y_AXIS]); + nx = current_position[X_AXIS] + (x - current_position[X_AXIS]) * normalized_dist; + ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist; + y_splits ^= BIT(piy); + } else { + // Already split on a border + plan_buffer_line(x, y, z, e, feed_rate, extruder); + set_current_to_destination(); + return; + } + // Do the split and look for more borders + destination[X_AXIS] = nx; + destination[Y_AXIS] = ny; + destination[E_AXIS] = ne; + mesh_plan_buffer_line(nx, ny, z, ne, feed_rate, extruder, x_splits, y_splits); + destination[X_AXIS] = x; + destination[Y_AXIS] = y; + destination[E_AXIS] = e; + mesh_plan_buffer_line(x, y, z, e, feed_rate, extruder, x_splits, y_splits); +} +#endif // MESH_BED_LEVELING + +#ifdef PREVENT_DANGEROUS_EXTRUDE + + inline float prevent_dangerous_extrude(float &curr_e, float &dest_e) { + float de = dest_e - curr_e; + if (de) { + if (degHotend(active_extruder) < extrude_min_temp) { + curr_e = dest_e; // Behave as if the move really took place, but ignore E part + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP); + return 0; + } + #ifdef PREVENT_LENGTHY_EXTRUDE + if (labs(de) > EXTRUDE_MAXLENGTH) { + curr_e = dest_e; // Behave as if the move really took place, but ignore E part + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP); + return 0; + } + #endif + } + return de; + } + +#endif // PREVENT_DANGEROUS_EXTRUDE + +void prepare_move() { + clamp_to_software_endstops(destination); + refresh_cmd_timeout(); + + #ifdef PREVENT_DANGEROUS_EXTRUDE + (void)prevent_dangerous_extrude(current_position[E_AXIS], destination[E_AXIS]); + #endif + + #ifdef SCARA //for now same as delta-code + + float difference[NUM_AXIS]; + for (int8_t i = 0; i < NUM_AXIS; i++) difference[i] = destination[i] - current_position[i]; + + float cartesian_mm = sqrt(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS])); + if (cartesian_mm < 0.000001) { cartesian_mm = abs(difference[E_AXIS]); } + if (cartesian_mm < 0.000001) { return; } + float seconds = 6000 * cartesian_mm / feedrate / feedmultiply; + int steps = max(1, int(scara_segments_per_second * seconds)); + + //SERIAL_ECHOPGM("mm="); SERIAL_ECHO(cartesian_mm); + //SERIAL_ECHOPGM(" seconds="); SERIAL_ECHO(seconds); + //SERIAL_ECHOPGM(" steps="); SERIAL_ECHOLN(steps); + + for (int s = 1; s <= steps; s++) { + float fraction = float(s) / float(steps); + for (int8_t i = 0; i < NUM_AXIS; i++) destination[i] = current_position[i] + difference[i] * fraction; + + calculate_delta(destination); + //SERIAL_ECHOPGM("destination[X_AXIS]="); SERIAL_ECHOLN(destination[X_AXIS]); + //SERIAL_ECHOPGM("destination[Y_AXIS]="); SERIAL_ECHOLN(destination[Y_AXIS]); + //SERIAL_ECHOPGM("destination[Z_AXIS]="); SERIAL_ECHOLN(destination[Z_AXIS]); + //SERIAL_ECHOPGM("delta[X_AXIS]="); SERIAL_ECHOLN(delta[X_AXIS]); + //SERIAL_ECHOPGM("delta[Y_AXIS]="); SERIAL_ECHOLN(delta[Y_AXIS]); + //SERIAL_ECHOPGM("delta[Z_AXIS]="); SERIAL_ECHOLN(delta[Z_AXIS]); + + plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], feedrate/60*feedmultiply/100.0, active_extruder); + } + + #endif // SCARA + + #ifdef DELTA + + float difference[NUM_AXIS]; + for (int8_t i=0; i < NUM_AXIS; i++) difference[i] = destination[i] - current_position[i]; + + float cartesian_mm = sqrt(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS])); + if (cartesian_mm < 0.000001) cartesian_mm = abs(difference[E_AXIS]); + if (cartesian_mm < 0.000001) return; + float seconds = 6000 * cartesian_mm / feedrate / feedmultiply; + int steps = max(1, int(delta_segments_per_second * seconds)); + + // SERIAL_ECHOPGM("mm="); SERIAL_ECHO(cartesian_mm); + // SERIAL_ECHOPGM(" seconds="); SERIAL_ECHO(seconds); + // SERIAL_ECHOPGM(" steps="); SERIAL_ECHOLN(steps); + + for (int s = 1; s <= steps; s++) { + float fraction = float(s) / float(steps); + for (int8_t i = 0; i < NUM_AXIS; i++) destination[i] = current_position[i] + difference[i] * fraction; + calculate_delta(destination); + #ifdef ENABLE_AUTO_BED_LEVELING + adjust_delta(destination); + #endif + plan_buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], feedrate/60*feedmultiply/100.0, active_extruder); + } + + #endif // DELTA + + #ifdef DUAL_X_CARRIAGE + if (active_extruder_parked) { + if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0) { + // move duplicate extruder into correct duplication position. + plan_set_position(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); + plan_buffer_line(current_position[X_AXIS] + duplicate_extruder_x_offset, + current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[X_AXIS], 1); + sync_plan_position(); + st_synchronize(); + extruder_duplication_enabled = true; + active_extruder_parked = false; + } + else if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) { // handle unparking of head + if (current_position[E_AXIS] == destination[E_AXIS]) { + // 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) { + set_current_to_destination(); + NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]); + delayed_move_time = millis(); + return; + } + } + delayed_move_time = 0; + // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower + plan_buffer_line(raised_parked_position[X_AXIS], raised_parked_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder); + plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], min(max_feedrate[X_AXIS], max_feedrate[Y_AXIS]), active_extruder); + plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder); + active_extruder_parked = false; + } + } + #endif // DUAL_X_CARRIAGE + + #if !defined(DELTA) && !defined(SCARA) + // Do not use feedmultiply for E or Z only moves + if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS]) { + line_to_destination(); + } + else { + #ifdef MESH_BED_LEVELING + mesh_plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], (feedrate/60)*(feedmultiply/100.0), active_extruder); + return; + #else + line_to_destination(feedrate * feedmultiply / 100.0); + #endif // MESH_BED_LEVELING + } + #endif // !(DELTA || SCARA) + + set_current_to_destination(); +} + +void prepare_arc_move(char isclockwise) { + float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc + + // Trace the arc + mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate*feedmultiply/60/100.0, r, isclockwise, active_extruder); + + // As far as the parser is concerned, the position is now == target. In reality the + // motion control system might still be processing the action and the real tool position + // in any intermediate location. + set_current_to_destination(); + refresh_cmd_timeout(); +} + +#if HAS_CONTROLLERFAN + +millis_t lastMotor = 0; // Last time a motor was turned on +millis_t lastMotorCheck = 0; // Last time the state was checked + +void controllerFan() { + millis_t ms = millis(); + if (ms >= lastMotorCheck + 2500) { // Not a time critical function, so we only check every 2500ms + lastMotorCheck = ms; + if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON || soft_pwm_bed > 0 + || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled... + #if EXTRUDERS > 1 + || E1_ENABLE_READ == E_ENABLE_ON + #if HAS_X2_ENABLE + || X2_ENABLE_READ == X_ENABLE_ON + #endif + #if EXTRUDERS > 2 + || E2_ENABLE_READ == E_ENABLE_ON + #if EXTRUDERS > 3 + || E3_ENABLE_READ == E_ENABLE_ON + #endif + #endif + #endif + ) { + lastMotor = ms; //... set time to NOW so the fan will turn on + } + uint8_t speed = (lastMotor == 0 || ms >= lastMotor + (CONTROLLERFAN_SECS * 1000UL)) ? 0 : CONTROLLERFAN_SPEED; + // allows digital or PWM fan output to be used (see M42 handling) + digitalWrite(CONTROLLERFAN_PIN, speed); + analogWrite(CONTROLLERFAN_PIN, speed); + } +} +#endif + +#ifdef SCARA +void calculate_SCARA_forward_Transform(float f_scara[3]) +{ + // Perform forward kinematics, and place results in delta[3] + // The maths and first version has been done by QHARLEY . Integrated into masterbranch 06/2014 and slightly restructured by Joachim Cerny in June 2014 + + float x_sin, x_cos, y_sin, y_cos; + + //SERIAL_ECHOPGM("f_delta x="); SERIAL_ECHO(f_scara[X_AXIS]); + //SERIAL_ECHOPGM(" y="); SERIAL_ECHO(f_scara[Y_AXIS]); + + x_sin = sin(f_scara[X_AXIS]/SCARA_RAD2DEG) * Linkage_1; + x_cos = cos(f_scara[X_AXIS]/SCARA_RAD2DEG) * Linkage_1; + y_sin = sin(f_scara[Y_AXIS]/SCARA_RAD2DEG) * Linkage_2; + y_cos = cos(f_scara[Y_AXIS]/SCARA_RAD2DEG) * Linkage_2; + + // SERIAL_ECHOPGM(" x_sin="); SERIAL_ECHO(x_sin); + // SERIAL_ECHOPGM(" x_cos="); SERIAL_ECHO(x_cos); + // SERIAL_ECHOPGM(" y_sin="); SERIAL_ECHO(y_sin); + // SERIAL_ECHOPGM(" y_cos="); SERIAL_ECHOLN(y_cos); + + delta[X_AXIS] = x_cos + y_cos + SCARA_offset_x; //theta + delta[Y_AXIS] = x_sin + y_sin + SCARA_offset_y; //theta+phi + + //SERIAL_ECHOPGM(" delta[X_AXIS]="); SERIAL_ECHO(delta[X_AXIS]); + //SERIAL_ECHOPGM(" delta[Y_AXIS]="); SERIAL_ECHOLN(delta[Y_AXIS]); +} + +void calculate_delta(float cartesian[3]){ + //reverse kinematics. + // Perform reversed kinematics, and place results in delta[3] + // The maths and first version has been done by QHARLEY . Integrated into masterbranch 06/2014 and slightly restructured by Joachim Cerny in June 2014 + + float SCARA_pos[2]; + static float SCARA_C2, SCARA_S2, SCARA_K1, SCARA_K2, SCARA_theta, SCARA_psi; + + SCARA_pos[X_AXIS] = cartesian[X_AXIS] * axis_scaling[X_AXIS] - SCARA_offset_x; //Translate SCARA to standard X Y + SCARA_pos[Y_AXIS] = cartesian[Y_AXIS] * axis_scaling[Y_AXIS] - SCARA_offset_y; // With scaling factor. + + #if (Linkage_1 == Linkage_2) + SCARA_C2 = ( ( sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS]) ) / (2 * (float)L1_2) ) - 1; + #else + SCARA_C2 = ( sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS]) - (float)L1_2 - (float)L2_2 ) / 45000; + #endif + + SCARA_S2 = sqrt( 1 - sq(SCARA_C2) ); + + SCARA_K1 = Linkage_1 + Linkage_2 * SCARA_C2; + SCARA_K2 = Linkage_2 * SCARA_S2; + + SCARA_theta = ( atan2(SCARA_pos[X_AXIS],SCARA_pos[Y_AXIS])-atan2(SCARA_K1, SCARA_K2) ) * -1; + SCARA_psi = atan2(SCARA_S2,SCARA_C2); + + delta[X_AXIS] = SCARA_theta * SCARA_RAD2DEG; // Multiply by 180/Pi - theta is support arm angle + delta[Y_AXIS] = (SCARA_theta + SCARA_psi) * SCARA_RAD2DEG; // - equal to sub arm angle (inverted motor) + delta[Z_AXIS] = cartesian[Z_AXIS]; + + /* + SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]); + SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]); + SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]); + + SERIAL_ECHOPGM("scara x="); SERIAL_ECHO(SCARA_pos[X_AXIS]); + SERIAL_ECHOPGM(" y="); SERIAL_ECHOLN(SCARA_pos[Y_AXIS]); + + SERIAL_ECHOPGM("delta x="); SERIAL_ECHO(delta[X_AXIS]); + SERIAL_ECHOPGM(" y="); SERIAL_ECHO(delta[Y_AXIS]); + SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(delta[Z_AXIS]); + + SERIAL_ECHOPGM("C2="); SERIAL_ECHO(SCARA_C2); + SERIAL_ECHOPGM(" S2="); SERIAL_ECHO(SCARA_S2); + SERIAL_ECHOPGM(" Theta="); SERIAL_ECHO(SCARA_theta); + SERIAL_ECHOPGM(" Psi="); SERIAL_ECHOLN(SCARA_psi); + SERIAL_ECHOLN(" ");*/ +} + +#endif + +#ifdef TEMP_STAT_LEDS + + static bool red_led = false; + static millis_t next_status_led_update_ms = 0; + + void handle_status_leds(void) { + float max_temp = 0.0; + if (millis() > next_status_led_update_ms) { + next_status_led_update_ms += 500; // Update every 0.5s + for (int8_t cur_extruder = 0; cur_extruder < EXTRUDERS; ++cur_extruder) + max_temp = max(max(max_temp, degHotend(cur_extruder)), degTargetHotend(cur_extruder)); + #if HAS_TEMP_BED + max_temp = max(max(max_temp, degTargetBed()), degBed()); + #endif + bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led; + if (new_led != red_led) { + red_led = new_led; + digitalWrite(STAT_LED_RED, new_led ? HIGH : LOW); + digitalWrite(STAT_LED_BLUE, new_led ? LOW : HIGH); + } + } + } + +#endif + +void enable_all_steppers() { + enable_x(); + enable_y(); + enable_z(); + enable_e0(); + enable_e1(); + enable_e2(); + enable_e3(); +} + +void disable_all_steppers() { + disable_x(); + disable_y(); + disable_z(); + disable_e0(); + disable_e1(); + disable_e2(); + disable_e3(); +} + +/** + * Manage several activities: + * - Check for Filament Runout + * - Keep the command buffer full + * - Check for maximum inactive time between commands + * - Check for maximum inactive time between stepper commands + * - Check if pin CHDK needs to go LOW + * - Check for KILL button held down + * - Check for HOME button held down + * - Check if cooling fan needs to be switched on + * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT) + */ +void manage_inactivity(bool ignore_stepper_queue/*=false*/) { + + #if HAS_FILRUNOUT + if (card.sdprinting && !(READ(FILRUNOUT_PIN) ^ FIL_RUNOUT_INVERTING)) + filrunout(); + #endif + + if (buflen < BUFSIZE - 1) get_command(); + + millis_t ms = millis(); + + if (max_inactive_time && ms > previous_cmd_ms + max_inactive_time) kill(); + + if (stepper_inactive_time && ms > previous_cmd_ms + stepper_inactive_time + && !ignore_stepper_queue && !blocks_queued()) + disable_all_steppers(); + + #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH + if (chdkActive && ms > chdkHigh + CHDK_DELAY) { + chdkActive = false; + WRITE(CHDK, LOW); + } + #endif + + #if HAS_KILL + + // Check if the kill button was pressed and wait just in case it was an accidental + // key kill key press + // ------------------------------------------------------------------------------- + static int killCount = 0; // make the inactivity button a bit less responsive + const int KILL_DELAY = 750; + if (!READ(KILL_PIN)) + killCount++; + else if (killCount > 0) + killCount--; + + // Exceeded threshold and we can confirm that it was not accidental + // KILL the machine + // ---------------------------------------------------------------- + if (killCount >= KILL_DELAY) kill(); + #endif + + #if HAS_HOME + // Check to see if we have to home, use poor man's debouncer + // --------------------------------------------------------- + static int homeDebounceCount = 0; // poor man's debouncing count + const int HOME_DEBOUNCE_DELAY = 750; + if (!READ(HOME_PIN)) { + if (!homeDebounceCount) { + enqueuecommands_P(PSTR("G28")); + LCD_ALERTMESSAGEPGM(MSG_AUTO_HOME); + } + if (homeDebounceCount < HOME_DEBOUNCE_DELAY) + homeDebounceCount++; + else + homeDebounceCount = 0; + } + #endif + + #if HAS_CONTROLLERFAN + controllerFan(); // Check if fan should be turned on to cool stepper drivers down + #endif + + #ifdef EXTRUDER_RUNOUT_PREVENT + if (ms > previous_cmd_ms + EXTRUDER_RUNOUT_SECONDS * 1000) + if (degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) { + bool oldstatus; + switch(active_extruder) { + case 0: + oldstatus = E0_ENABLE_READ; + enable_e0(); + break; + #if EXTRUDERS > 1 + case 1: + oldstatus = E1_ENABLE_READ; + enable_e1(); + break; + #if EXTRUDERS > 2 + case 2: + oldstatus = E2_ENABLE_READ; + enable_e2(); + break; + #if EXTRUDERS > 3 + case 3: + oldstatus = E3_ENABLE_READ; + enable_e3(); + break; + #endif + #endif + #endif + } + float oldepos = current_position[E_AXIS], oldedes = destination[E_AXIS]; + plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], + destination[E_AXIS] + EXTRUDER_RUNOUT_EXTRUDE * EXTRUDER_RUNOUT_ESTEPS / axis_steps_per_unit[E_AXIS], + EXTRUDER_RUNOUT_SPEED / 60. * EXTRUDER_RUNOUT_ESTEPS / axis_steps_per_unit[E_AXIS], active_extruder); + current_position[E_AXIS] = oldepos; + destination[E_AXIS] = oldedes; + plan_set_e_position(oldepos); + previous_cmd_ms = ms; // refresh_cmd_timeout() + st_synchronize(); + switch(active_extruder) { + case 0: + E0_ENABLE_WRITE(oldstatus); + break; + #if EXTRUDERS > 1 + case 1: + E1_ENABLE_WRITE(oldstatus); + break; + #if EXTRUDERS > 2 + case 2: + E2_ENABLE_WRITE(oldstatus); + break; + #if EXTRUDERS > 3 + case 3: + E3_ENABLE_WRITE(oldstatus); + break; + #endif + #endif + #endif + } + } + #endif + + #ifdef DUAL_X_CARRIAGE + // handle delayed move timeout + if (delayed_move_time && ms > delayed_move_time + 1000 && IsRunning()) { + // travel moves have been received so enact them + delayed_move_time = 0xFFFFFFFFUL; // force moves to be done + set_destination_to_current(); + prepare_move(); + } + #endif + + #ifdef TEMP_STAT_LEDS + handle_status_leds(); + #endif + + check_axes_activity(); +} + +void kill() +{ + cli(); // Stop interrupts + disable_heater(); + + disable_all_steppers(); + + #if HAS_POWER_SWITCH + pinMode(PS_ON_PIN, INPUT); + #endif + + SERIAL_ERROR_START; + SERIAL_ERRORLNPGM(MSG_ERR_KILLED); + LCD_ALERTMESSAGEPGM(MSG_KILLED); + + // FMC small patch to update the LCD before ending + sei(); // enable interrupts + for (int i = 5; i--; lcd_update()) delay(200); // Wait a short time + cli(); // disable interrupts + suicide(); + while(1) { /* Intentionally left empty */ } // Wait for reset +} + +#ifdef FILAMENT_RUNOUT_SENSOR + void filrunout() + { + if filrunoutEnqued == false { + filrunoutEnqued = true; + enqueuecommand("M600"); + } + } +#endif + +void Stop() +{ + disable_heater(); + if (IsRunning()) { + Running = false; + Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart + SERIAL_ERROR_START; + SERIAL_ERRORLNPGM(MSG_ERR_STOPPED); + LCD_MESSAGEPGM(MSG_STOPPED); + } +} + +#ifdef FAST_PWM_FAN +void setPwmFrequency(uint8_t pin, int val) +{ + val &= 0x07; + switch(digitalPinToTimer(pin)) + { + + #if defined(TCCR0A) + case TIMER0A: + case TIMER0B: +// TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02)); +// TCCR0B |= val; + break; + #endif + + #if defined(TCCR1A) + case TIMER1A: + case TIMER1B: +// TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12)); +// TCCR1B |= val; + break; + #endif + + #if defined(TCCR2) + case TIMER2: + case TIMER2: + TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12)); + TCCR2 |= val; + break; + #endif + + #if defined(TCCR2A) + case TIMER2A: + case TIMER2B: + TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22)); + TCCR2B |= val; + break; + #endif + + #if defined(TCCR3A) + case TIMER3A: + case TIMER3B: + case TIMER3C: + TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32)); + TCCR3B |= val; + break; + #endif + + #if defined(TCCR4A) + case TIMER4A: + case TIMER4B: + case TIMER4C: + TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42)); + TCCR4B |= val; + break; + #endif + + #if defined(TCCR5A) + case TIMER5A: + case TIMER5B: + case TIMER5C: + TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52)); + TCCR5B |= val; + break; + #endif + + } +} +#endif //FAST_PWM_FAN + +bool setTargetedHotend(int code){ + target_extruder = active_extruder; + if (code_seen('T')) { + target_extruder = code_value_short(); + if (target_extruder >= EXTRUDERS) { + SERIAL_ECHO_START; + switch(code){ + case 104: + SERIAL_ECHO(MSG_M104_INVALID_EXTRUDER); + break; + case 105: + SERIAL_ECHO(MSG_M105_INVALID_EXTRUDER); + break; + case 109: + SERIAL_ECHO(MSG_M109_INVALID_EXTRUDER); + break; + case 218: + SERIAL_ECHO(MSG_M218_INVALID_EXTRUDER); + break; + case 221: + SERIAL_ECHO(MSG_M221_INVALID_EXTRUDER); + break; + } + SERIAL_ECHOLN(target_extruder); + return true; + } + } + return false; +} + +float calculate_volumetric_multiplier(float diameter) { + if (!volumetric_enabled || diameter == 0) return 1.0; + float d2 = diameter * 0.5; + return 1.0 / (M_PI * d2 * d2); +} + +void calculate_volumetric_multipliers() { + for (int i=0; i 1 + + #if EXTRUDERS > 4 + #error The maximum number of EXTRUDERS in Marlin is 4. + #endif + + #ifdef TEMP_SENSOR_1_AS_REDUNDANT + #error EXTRUDERS must be 1 with TEMP_SENSOR_1_AS_REDUNDANT. + #endif + + #ifdef HEATERS_PARALLEL + #error EXTRUDERS must be 1 with HEATERS_PARALLEL. + #endif + + #ifdef Y_DUAL_STEPPER_DRIVERS + #error EXTRUDERS must be 1 with Y_DUAL_STEPPER_DRIVERS. + #endif + + #ifdef Z_DUAL_STEPPER_DRIVERS + #error EXTRUDERS must be 1 with Z_DUAL_STEPPER_DRIVERS. + #endif + + #endif // EXTRUDERS > 1 + + /** + * Limited number of servos + */ + #if NUM_SERVOS > 4 + #error The maximum number of SERVOS in Marlin is 4. + #endif + + /** + * Required LCD language + */ + #if !defined(DOGLCD) && defined(ULTRA_LCD) && !defined(DISPLAY_CHARSET_HD44780_JAPAN) && !defined(DISPLAY_CHARSET_HD44780_WESTERN) + #error You must enable either DISPLAY_CHARSET_HD44780_JAPAN or DISPLAY_CHARSET_HD44780_WESTERN for your LCD controller. + #endif + + /** + * Mesh Bed Leveling + */ + #ifdef MESH_BED_LEVELING + #ifdef DELTA + #error MESH_BED_LEVELING does not yet support DELTA printers + #endif + #ifdef ENABLE_AUTO_BED_LEVELING + #error Select ENABLE_AUTO_BED_LEVELING or MESH_BED_LEVELING, not both + #endif + #if MESH_NUM_X_POINTS > 7 || MESH_NUM_Y_POINTS > 7 + #error MESH_NUM_X_POINTS and MESH_NUM_Y_POINTS need to be less than 8 + #endif + #endif + + /** + * Auto Bed Leveling + */ + #ifdef ENABLE_AUTO_BED_LEVELING + + /** + * Require a Z Min pin + */ + #if Z_MIN_PIN == -1 + #if Z_PROBE_PIN == -1 || (!defined(Z_PROBE_ENDSTOP) || defined(DISABLE_Z_PROBE_ENDSTOP)) // It's possible for someone to set a pin for the Z Probe, but not enable it. + #ifdef Z_PROBE_REPEATABILITY_TEST + #error You must have a Z_MIN or Z_PROBE endstop to enable Z_PROBE_REPEATABILITY_TEST. + #else + #error ENABLE_AUTO_BED_LEVELING requires a Z_MIN or Z_PROBE endstop. Z_MIN_PIN or Z_PROBE_PIN must point to a valid hardware pin. + #endif + #endif + #endif + + /** + * Require a Z Probe Pin if Z_PROBE_ENDSTOP is enabled. + */ + #if defined(Z_PROBE_ENDSTOP) + #ifndef Z_PROBE_PIN + #error You must have a Z_PROBE_PIN defined in your pins_XXXX.h file if you enable Z_PROBE_ENDSTOP + #endif + #if Z_PROBE_PIN == -1 + #error You must set Z_PROBE_PIN to a valid pin if you enable Z_PROBE_ENDSTOP + #endif +// Forcing Servo definitions can break some hall effect sensor setups. Leaving these here for further comment. +// #ifndef NUM_SERVOS +// #error You must have NUM_SERVOS defined and there must be at least 1 configured to use Z_PROBE_ENDSTOP +// #endif +// #if defined(NUM_SERVOS) && NUM_SERVOS < 1 +// #error You must have at least 1 servo defined for NUM_SERVOS to use Z_PROBE_ENDSTOP +// #endif +// #ifndef SERVO_ENDSTOPS +// #error You must have SERVO_ENDSTOPS defined and have the Z index set to at least 0 or above to use Z_PROBE_ENDSTOP +// #endif +// #ifndef SERVO_ENDSTOP_ANGLES +// #error You must have SERVO_ENDSTOP_ANGLES defined for Z Extend and Retract to use Z_PROBE_AND_ENSTOP +// #endif + #endif + /** + * Check if Probe_Offset * Grid Points is greater than Probing Range + */ + #ifdef AUTO_BED_LEVELING_GRID + + // Make sure probing points are reachable + #if LEFT_PROBE_BED_POSITION < MIN_PROBE_X + #error "The given LEFT_PROBE_BED_POSITION can't be reached by the probe." + #elif RIGHT_PROBE_BED_POSITION > MAX_PROBE_X + #error "The given RIGHT_PROBE_BED_POSITION can't be reached by the probe." + #elif FRONT_PROBE_BED_POSITION < MIN_PROBE_Y + #error "The given FRONT_PROBE_BED_POSITION can't be reached by the probe." + #elif BACK_PROBE_BED_POSITION > MAX_PROBE_Y + #error "The given BACK_PROBE_BED_POSITION can't be reached by the probe." + #endif + + #define PROBE_SIZE_X (X_PROBE_OFFSET_FROM_EXTRUDER * (AUTO_BED_LEVELING_GRID_POINTS-1)) + #define PROBE_SIZE_Y (Y_PROBE_OFFSET_FROM_EXTRUDER * (AUTO_BED_LEVELING_GRID_POINTS-1)) + #define PROBE_AREA_WIDTH (RIGHT_PROBE_BED_POSITION - LEFT_PROBE_BED_POSITION) + #define PROBE_AREA_DEPTH (BACK_PROBE_BED_POSITION - FRONT_PROBE_BED_POSITION) + #if X_PROBE_OFFSET_FROM_EXTRUDER < 0 + #if PROBE_SIZE_X <= -PROBE_AREA_WIDTH + #define X_PROBE_ERROR + #endif + #elif PROBE_SIZE_X >= PROBE_AREA_WIDTH + #define X_PROBE_ERROR + #endif + #ifdef X_PROBE_ERROR + #error The X axis probing range is too small to fit all the points defined in AUTO_BED_LEVELING_GRID_POINTS + #endif + #if Y_PROBE_OFFSET_FROM_EXTRUDER < 0 + #if PROBE_SIZE_Y <= -PROBE_AREA_DEPTH + #define Y_PROBE_ERROR + #endif + #elif PROBE_SIZE_Y >= PROBE_AREA_DEPTH + #define Y_PROBE_ERROR + #endif + #ifdef Y_PROBE_ERROR + #error The Y axis probing range is too small to fit all the points defined in AUTO_BED_LEVELING_GRID_POINTS + #endif + + #undef PROBE_SIZE_X + #undef PROBE_SIZE_Y + #undef PROBE_AREA_WIDTH + #undef PROBE_AREA_DEPTH + + #else // !AUTO_BED_LEVELING_GRID + + // Check the triangulation points + #if ABL_PROBE_PT_1_X < MIN_PROBE_X || ABL_PROBE_PT_1_X > MAX_PROBE_X + #error "The given ABL_PROBE_PT_1_X can't be reached by the probe." + #elif ABL_PROBE_PT_2_X < MIN_PROBE_X || ABL_PROBE_PT_2_X > MAX_PROBE_X + #error "The given ABL_PROBE_PT_2_X can't be reached by the probe." + #elif ABL_PROBE_PT_3_X < MIN_PROBE_X || ABL_PROBE_PT_3_X > MAX_PROBE_X + #error "The given ABL_PROBE_PT_3_X can't be reached by the probe." + #elif ABL_PROBE_PT_1_Y < MIN_PROBE_Y || ABL_PROBE_PT_1_Y > MAX_PROBE_Y + #error "The given ABL_PROBE_PT_1_Y can't be reached by the probe." + #elif ABL_PROBE_PT_2_Y < MIN_PROBE_Y || ABL_PROBE_PT_2_Y > MAX_PROBE_Y + #error "The given ABL_PROBE_PT_2_Y can't be reached by the probe." + #elif ABL_PROBE_PT_3_Y < MIN_PROBE_Y || ABL_PROBE_PT_3_Y > MAX_PROBE_Y + #error "The given ABL_PROBE_PT_3_Y can't be reached by the probe." + #endif + + #endif // !AUTO_BED_LEVELING_GRID + + #endif // ENABLE_AUTO_BED_LEVELING + + /** + * ULTIPANEL encoder + */ + #if defined(ULTIPANEL) && !defined(NEWPANEL) && !defined(SR_LCD_2W_NL) && !defined(SHIFT_CLK) + #error ULTIPANEL requires some kind of encoder. + #endif + + /** + * Delta has limited bed leveling options + */ + #ifdef DELTA + + #ifdef ENABLE_AUTO_BED_LEVELING + + #ifndef AUTO_BED_LEVELING_GRID + #error Only AUTO_BED_LEVELING_GRID is supported with DELTA. + #endif + + #ifdef Z_PROBE_SLED + #error You cannot use Z_PROBE_SLED with DELTA. + #endif + + #ifdef Z_PROBE_REPEATABILITY_TEST + #error Z_PROBE_REPEATABILITY_TEST is not supported with DELTA yet. + #endif + + #endif + + #endif + + /** + * Allen Key Z Probe requires Auto Bed Leveling grid and Delta + */ + #if defined(Z_PROBE_ALLEN_KEY) && !(defined(AUTO_BED_LEVELING_GRID) && defined(DELTA)) + #error Invalid use of Z_PROBE_ALLEN_KEY. + #endif + + /** + * Dual X Carriage requirements + */ + #ifdef DUAL_X_CARRIAGE + #if EXTRUDERS == 1 || defined(COREXY) \ + || !HAS_X2_ENABLE || !HAS_X2_STEP || !HAS_X2_DIR \ + || !defined(X2_HOME_POS) || !defined(X2_MIN_POS) || !defined(X2_MAX_POS) \ + || !HAS_X_MAX + #error Missing or invalid definitions for DUAL_X_CARRIAGE mode. + #endif + #if X_HOME_DIR != -1 || X2_HOME_DIR != 1 + #error Please use canonical x-carriage assignment. + #endif + #endif // DUAL_X_CARRIAGE + + /** + * Make sure auto fan pins don't conflict with the fan pin + */ + #if HAS_AUTO_FAN && HAS_FAN + #if EXTRUDER_0_AUTO_FAN_PIN == FAN_PIN + #error You cannot set EXTRUDER_0_AUTO_FAN_PIN equal to FAN_PIN + #elif EXTRUDER_1_AUTO_FAN_PIN == FAN_PIN + #error You cannot set EXTRUDER_1_AUTO_FAN_PIN equal to FAN_PIN + #elif EXTRUDER_2_AUTO_FAN_PIN == FAN_PIN + #error You cannot set EXTRUDER_2_AUTO_FAN_PIN equal to FAN_PIN + #elif EXTRUDER_3_AUTO_FAN_PIN == FAN_PIN + #error You cannot set EXTRUDER_3_AUTO_FAN_PIN equal to FAN_PIN + #endif + #endif + + #if HAS_FAN && CONTROLLERFAN_PIN == FAN_PIN + #error You cannot set CONTROLLERFAN_PIN equal to FAN_PIN + #endif + + /** + * Test required HEATER defines + */ + #if EXTRUDERS > 3 + #if !HAS_HEATER_3 + #error HEATER_3_PIN not defined for this board + #endif + #elif EXTRUDERS > 2 + #if !HAS_HEATER_2 + #error HEATER_2_PIN not defined for this board + #endif + #elif EXTRUDERS > 1 || defined(HEATERS_PARALLEL) + #if !HAS_HEATER_1 + #error HEATER_1_PIN not defined for this board + #endif + #endif + #if !HAS_HEATER_0 + #error HEATER_0_PIN not defined for this board + #endif + + /** + * Warnings for old configurations + */ + #ifdef X_HOME_RETRACT_MM + #error [XYZ]_HOME_RETRACT_MM settings have been renamed [XYZ]_HOME_BUMP_MM + #endif + +#endif //SANITYCHECK_H diff --git a/Marlin/Sd2Card.cpp b/Marlin/Sd2Card.cpp new file mode 100644 index 0000000..1182c99 --- /dev/null +++ b/Marlin/Sd2Card.cpp @@ -0,0 +1,723 @@ +/* Arduino Sd2Card Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino Sd2Card Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino Sd2Card Library. If not, see + * . + */ +#include "Marlin.h" + +#ifdef SDSUPPORT +#include "Sd2Card.h" +//------------------------------------------------------------------------------ +#ifndef SOFTWARE_SPI +// functions for hardware SPI +//------------------------------------------------------------------------------ +// make sure SPCR rate is in expected bits +#if (SPR0 != 0 || SPR1 != 1) +#error unexpected SPCR bits +#endif +/** + * Initialize hardware SPI + * Set SCK rate to F_CPU/pow(2, 1 + spiRate) for spiRate [0,6] + */ +static void spiInit(uint8_t spiRate) { + // See avr processor documentation + SPCR = BIT(SPE) | BIT(MSTR) | (spiRate >> 1); + SPSR = spiRate & 1 || spiRate == 6 ? 0 : BIT(SPI2X); +} +//------------------------------------------------------------------------------ +/** SPI receive a byte */ +static uint8_t spiRec() { + SPDR = 0XFF; + while (!TEST(SPSR, SPIF)) { /* Intentionally left empty */ } + return SPDR; +} +//------------------------------------------------------------------------------ +/** SPI read data - only one call so force inline */ +static inline __attribute__((always_inline)) +void spiRead(uint8_t* buf, uint16_t nbyte) { + if (nbyte-- == 0) return; + SPDR = 0XFF; + for (uint16_t i = 0; i < nbyte; i++) { + while (!TEST(SPSR, SPIF)) { /* Intentionally left empty */ } + buf[i] = SPDR; + SPDR = 0XFF; + } + while (!TEST(SPSR, SPIF)) { /* Intentionally left empty */ } + buf[nbyte] = SPDR; +} +//------------------------------------------------------------------------------ +/** SPI send a byte */ +static void spiSend(uint8_t b) { + SPDR = b; + while (!TEST(SPSR, SPIF)) { /* Intentionally left empty */ } +} +//------------------------------------------------------------------------------ +/** SPI send block - only one call so force inline */ +static inline __attribute__((always_inline)) + void spiSendBlock(uint8_t token, const uint8_t* buf) { + SPDR = token; + for (uint16_t i = 0; i < 512; i += 2) { + while (!TEST(SPSR, SPIF)) { /* Intentionally left empty */ } + SPDR = buf[i]; + while (!TEST(SPSR, SPIF)) { /* Intentionally left empty */ } + SPDR = buf[i + 1]; + } + while (!TEST(SPSR, SPIF)) { /* Intentionally left empty */ } +} +//------------------------------------------------------------------------------ +#else // SOFTWARE_SPI +//------------------------------------------------------------------------------ +/** nop to tune soft SPI timing */ +#define nop asm volatile ("nop\n\t") +//------------------------------------------------------------------------------ +/** Soft SPI receive byte */ +static uint8_t spiRec() { + uint8_t data = 0; + // no interrupts during byte receive - about 8 us + cli(); + // output pin high - like sending 0XFF + fastDigitalWrite(SPI_MOSI_PIN, HIGH); + + for (uint8_t i = 0; i < 8; i++) { + fastDigitalWrite(SPI_SCK_PIN, HIGH); + + // adjust so SCK is nice + nop; + nop; + + data <<= 1; + + if (fastDigitalRead(SPI_MISO_PIN)) data |= 1; + + fastDigitalWrite(SPI_SCK_PIN, LOW); + } + // enable interrupts + sei(); + return data; +} +//------------------------------------------------------------------------------ +/** Soft SPI read data */ +static void spiRead(uint8_t* buf, uint16_t nbyte) { + for (uint16_t i = 0; i < nbyte; i++) { + buf[i] = spiRec(); + } +} +//------------------------------------------------------------------------------ +/** Soft SPI send byte */ +static void spiSend(uint8_t data) { + // no interrupts during byte send - about 8 us + cli(); + for (uint8_t i = 0; i < 8; i++) { + fastDigitalWrite(SPI_SCK_PIN, LOW); + + fastDigitalWrite(SPI_MOSI_PIN, data & 0X80); + + data <<= 1; + + fastDigitalWrite(SPI_SCK_PIN, HIGH); + } + // hold SCK high for a few ns + nop; + nop; + nop; + nop; + + fastDigitalWrite(SPI_SCK_PIN, LOW); + // enable interrupts + sei(); +} +//------------------------------------------------------------------------------ +/** Soft SPI send block */ + void spiSendBlock(uint8_t token, const uint8_t* buf) { + spiSend(token); + for (uint16_t i = 0; i < 512; i++) { + spiSend(buf[i]); + } +} +#endif // SOFTWARE_SPI +//------------------------------------------------------------------------------ +// send command and return error code. Return zero for OK +uint8_t Sd2Card::cardCommand(uint8_t cmd, uint32_t arg) { + // select card + chipSelectLow(); + + // wait up to 300 ms if busy + waitNotBusy(300); + + // send command + spiSend(cmd | 0x40); + + // send argument + for (int8_t s = 24; s >= 0; s -= 8) spiSend(arg >> s); + + // send CRC + uint8_t crc = 0XFF; + if (cmd == CMD0) crc = 0X95; // correct crc for CMD0 with arg 0 + if (cmd == CMD8) crc = 0X87; // correct crc for CMD8 with arg 0X1AA + spiSend(crc); + + // skip stuff byte for stop read + if (cmd == CMD12) spiRec(); + + // wait for response + for (uint8_t i = 0; ((status_ = spiRec()) & 0X80) && i != 0XFF; i++) { /* Intentionally left empty */ } + return status_; +} +//------------------------------------------------------------------------------ +/** + * Determine the size of an SD flash memory card. + * + * \return The number of 512 byte data blocks in the card + * or zero if an error occurs. + */ +uint32_t Sd2Card::cardSize() { + csd_t csd; + if (!readCSD(&csd)) return 0; + if (csd.v1.csd_ver == 0) { + uint8_t read_bl_len = csd.v1.read_bl_len; + uint16_t c_size = (csd.v1.c_size_high << 10) + | (csd.v1.c_size_mid << 2) | csd.v1.c_size_low; + uint8_t c_size_mult = (csd.v1.c_size_mult_high << 1) + | csd.v1.c_size_mult_low; + return (uint32_t)(c_size + 1) << (c_size_mult + read_bl_len - 7); + } else if (csd.v2.csd_ver == 1) { + uint32_t c_size = ((uint32_t)csd.v2.c_size_high << 16) + | (csd.v2.c_size_mid << 8) | csd.v2.c_size_low; + return (c_size + 1) << 10; + } else { + error(SD_CARD_ERROR_BAD_CSD); + return 0; + } +} +//------------------------------------------------------------------------------ +void Sd2Card::chipSelectHigh() { + digitalWrite(chipSelectPin_, HIGH); +} +//------------------------------------------------------------------------------ +void Sd2Card::chipSelectLow() { +#ifndef SOFTWARE_SPI + spiInit(spiRate_); +#endif // SOFTWARE_SPI + digitalWrite(chipSelectPin_, LOW); +} +//------------------------------------------------------------------------------ +/** Erase a range of blocks. + * + * \param[in] firstBlock The address of the first block in the range. + * \param[in] lastBlock The address of the last block in the range. + * + * \note This function requests the SD card to do a flash erase for a + * range of blocks. The data on the card after an erase operation is + * either 0 or 1, depends on the card vendor. The card must support + * single block erase. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool Sd2Card::erase(uint32_t firstBlock, uint32_t lastBlock) { + csd_t csd; + if (!readCSD(&csd)) goto fail; + // check for single block erase + if (!csd.v1.erase_blk_en) { + // erase size mask + uint8_t m = (csd.v1.sector_size_high << 1) | csd.v1.sector_size_low; + if ((firstBlock & m) != 0 || ((lastBlock + 1) & m) != 0) { + // error card can't erase specified area + error(SD_CARD_ERROR_ERASE_SINGLE_BLOCK); + goto fail; + } + } + if (type_ != SD_CARD_TYPE_SDHC) { + firstBlock <<= 9; + lastBlock <<= 9; + } + if (cardCommand(CMD32, firstBlock) + || cardCommand(CMD33, lastBlock) + || cardCommand(CMD38, 0)) { + error(SD_CARD_ERROR_ERASE); + goto fail; + } + if (!waitNotBusy(SD_ERASE_TIMEOUT)) { + error(SD_CARD_ERROR_ERASE_TIMEOUT); + goto fail; + } + chipSelectHigh(); + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Determine if card supports single block erase. + * + * \return The value one, true, is returned if single block erase is supported. + * The value zero, false, is returned if single block erase is not supported. + */ +bool Sd2Card::eraseSingleBlockEnable() { + csd_t csd; + return readCSD(&csd) ? csd.v1.erase_blk_en : false; +} +//------------------------------------------------------------------------------ +/** + * Initialize an SD flash memory card. + * + * \param[in] sckRateID SPI clock rate selector. See setSckRate(). + * \param[in] chipSelectPin SD chip select pin number. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. The reason for failure + * can be determined by calling errorCode() and errorData(). + */ +bool Sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin) { + errorCode_ = type_ = 0; + chipSelectPin_ = chipSelectPin; + // 16-bit init start time allows over a minute + uint16_t t0 = (uint16_t)millis(); + uint32_t arg; + + // set pin modes + pinMode(chipSelectPin_, OUTPUT); + chipSelectHigh(); + pinMode(SPI_MISO_PIN, INPUT); + pinMode(SPI_MOSI_PIN, OUTPUT); + pinMode(SPI_SCK_PIN, OUTPUT); + +#ifndef SOFTWARE_SPI + // SS must be in output mode even it is not chip select + pinMode(SS_PIN, OUTPUT); + // set SS high - may be chip select for another SPI device +#if SET_SPI_SS_HIGH + digitalWrite(SS_PIN, HIGH); +#endif // SET_SPI_SS_HIGH + // set SCK rate for initialization commands + spiRate_ = SPI_SD_INIT_RATE; + spiInit(spiRate_); +#endif // SOFTWARE_SPI + + // must supply min of 74 clock cycles with CS high. + for (uint8_t i = 0; i < 10; i++) spiSend(0XFF); + + // command to go idle in SPI mode + while ((status_ = cardCommand(CMD0, 0)) != R1_IDLE_STATE) { + if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) { + error(SD_CARD_ERROR_CMD0); + goto fail; + } + } + // check SD version + if ((cardCommand(CMD8, 0x1AA) & R1_ILLEGAL_COMMAND)) { + type(SD_CARD_TYPE_SD1); + } else { + // only need last byte of r7 response + for (uint8_t i = 0; i < 4; i++) status_ = spiRec(); + if (status_ != 0XAA) { + error(SD_CARD_ERROR_CMD8); + goto fail; + } + type(SD_CARD_TYPE_SD2); + } + // initialize card and send host supports SDHC if SD2 + arg = type() == SD_CARD_TYPE_SD2 ? 0X40000000 : 0; + + while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) { + // check for timeout + if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) { + error(SD_CARD_ERROR_ACMD41); + goto fail; + } + } + // if SD2 read OCR register to check for SDHC card + if (type() == SD_CARD_TYPE_SD2) { + if (cardCommand(CMD58, 0)) { + error(SD_CARD_ERROR_CMD58); + goto fail; + } + if ((spiRec() & 0XC0) == 0XC0) type(SD_CARD_TYPE_SDHC); + // discard rest of ocr - contains allowed voltage range + for (uint8_t i = 0; i < 3; i++) spiRec(); + } + chipSelectHigh(); + +#ifndef SOFTWARE_SPI + return setSckRate(sckRateID); +#else // SOFTWARE_SPI + return true; +#endif // SOFTWARE_SPI + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + * Read a 512 byte block from an SD card. + * + * \param[in] blockNumber Logical block to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool Sd2Card::readBlock(uint32_t blockNumber, uint8_t* dst) { +#ifdef SD_CHECK_AND_RETRY + uint8_t retryCnt = 3; + // use address if not SDHC card + if (type()!= SD_CARD_TYPE_SDHC) blockNumber <<= 9; + retry2: + retryCnt --; + if (cardCommand(CMD17, blockNumber)) { + error(SD_CARD_ERROR_CMD17); + if (retryCnt > 0) goto retry; + goto fail; + } + if (!readData(dst, 512)) + { + if (retryCnt > 0) goto retry; + goto fail; + } + return true; + retry: + chipSelectHigh(); + cardCommand(CMD12, 0);//Try sending a stop command, but ignore the result. + errorCode_ = 0; + goto retry2; +#else + // use address if not SDHC card + if (type()!= SD_CARD_TYPE_SDHC) blockNumber <<= 9; + if (cardCommand(CMD17, blockNumber)) { + error(SD_CARD_ERROR_CMD17); + goto fail; + } + return readData(dst, 512); +#endif + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Read one data block in a multiple block read sequence + * + * \param[in] dst Pointer to the location for the data to be read. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool Sd2Card::readData(uint8_t *dst) { + chipSelectLow(); + return readData(dst, 512); +} + +#ifdef SD_CHECK_AND_RETRY +static const uint16_t crctab[] PROGMEM = { + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, + 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, + 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, + 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, + 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, + 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, + 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, + 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, + 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, + 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, + 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, + 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, + 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, + 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, + 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, + 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, + 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, + 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, + 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, + 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, + 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, + 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, + 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 +}; +static uint16_t CRC_CCITT(const uint8_t* data, size_t n) { + uint16_t crc = 0; + for (size_t i = 0; i < n; i++) { + crc = pgm_read_word(&crctab[(crc >> 8 ^ data[i]) & 0XFF]) ^ (crc << 8); + } + return crc; +} +#endif + +//------------------------------------------------------------------------------ +bool Sd2Card::readData(uint8_t* dst, uint16_t count) { + // wait for start block token + uint16_t t0 = millis(); + while ((status_ = spiRec()) == 0XFF) { + if (((uint16_t)millis() - t0) > SD_READ_TIMEOUT) { + error(SD_CARD_ERROR_READ_TIMEOUT); + goto fail; + } + } + if (status_ != DATA_START_BLOCK) { + error(SD_CARD_ERROR_READ); + goto fail; + } + // transfer data + spiRead(dst, count); + +#ifdef SD_CHECK_AND_RETRY + { + uint16_t calcCrc = CRC_CCITT(dst, count); + uint16_t recvCrc = spiRec() << 8; + recvCrc |= spiRec(); + if (calcCrc != recvCrc) + { + error(SD_CARD_ERROR_CRC); + goto fail; + } + } +#else + // discard CRC + spiRec(); + spiRec(); +#endif + chipSelectHigh(); + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** read CID or CSR register */ +bool Sd2Card::readRegister(uint8_t cmd, void* buf) { + uint8_t* dst = reinterpret_cast(buf); + if (cardCommand(cmd, 0)) { + error(SD_CARD_ERROR_READ_REG); + goto fail; + } + return readData(dst, 16); + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Start a read multiple blocks sequence. + * + * \param[in] blockNumber Address of first block in sequence. + * + * \note This function is used with readData() and readStop() for optimized + * multiple block reads. SPI chipSelect must be low for the entire sequence. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool Sd2Card::readStart(uint32_t blockNumber) { + if (type()!= SD_CARD_TYPE_SDHC) blockNumber <<= 9; + if (cardCommand(CMD18, blockNumber)) { + error(SD_CARD_ERROR_CMD18); + goto fail; + } + chipSelectHigh(); + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** End a read multiple blocks sequence. + * +* \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool Sd2Card::readStop() { + chipSelectLow(); + if (cardCommand(CMD12, 0)) { + error(SD_CARD_ERROR_CMD12); + goto fail; + } + chipSelectHigh(); + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** + * Set the SPI clock rate. + * + * \param[in] sckRateID A value in the range [0, 6]. + * + * The SPI clock will be set to F_CPU/pow(2, 1 + sckRateID). The maximum + * SPI rate is F_CPU/2 for \a sckRateID = 0 and the minimum rate is F_CPU/128 + * for \a scsRateID = 6. + * + * \return The value one, true, is returned for success and the value zero, + * false, is returned for an invalid value of \a sckRateID. + */ +bool Sd2Card::setSckRate(uint8_t sckRateID) { + if (sckRateID > 6) { + error(SD_CARD_ERROR_SCK_RATE); + return false; + } + spiRate_ = sckRateID; + return true; +} +//------------------------------------------------------------------------------ +// wait for card to go not busy +bool Sd2Card::waitNotBusy(uint16_t timeoutMillis) { + uint16_t t0 = millis(); + while (spiRec() != 0XFF) { + if (((uint16_t)millis() - t0) >= timeoutMillis) goto fail; + } + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** + * Writes a 512 byte block to an SD card. + * + * \param[in] blockNumber Logical block to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool Sd2Card::writeBlock(uint32_t blockNumber, const uint8_t* src) { + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9; + if (cardCommand(CMD24, blockNumber)) { + error(SD_CARD_ERROR_CMD24); + goto fail; + } + if (!writeData(DATA_START_BLOCK, src)) goto fail; + + // wait for flash programming to complete + if (!waitNotBusy(SD_WRITE_TIMEOUT)) { + error(SD_CARD_ERROR_WRITE_TIMEOUT); + goto fail; + } + // response is r2 so get and check two bytes for nonzero + if (cardCommand(CMD13, 0) || spiRec()) { + error(SD_CARD_ERROR_WRITE_PROGRAMMING); + goto fail; + } + chipSelectHigh(); + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Write one data block in a multiple block write sequence + * \param[in] src Pointer to the location of the data to be written. + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool Sd2Card::writeData(const uint8_t* src) { + chipSelectLow(); + // wait for previous write to finish + if (!waitNotBusy(SD_WRITE_TIMEOUT)) goto fail; + if (!writeData(WRITE_MULTIPLE_TOKEN, src)) goto fail; + chipSelectHigh(); + return true; + + fail: + error(SD_CARD_ERROR_WRITE_MULTIPLE); + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +// send one block of data for write block or write multiple blocks +bool Sd2Card::writeData(uint8_t token, const uint8_t* src) { + spiSendBlock(token, src); + + spiSend(0xff); // dummy crc + spiSend(0xff); // dummy crc + + status_ = spiRec(); + if ((status_ & DATA_RES_MASK) != DATA_RES_ACCEPTED) { + error(SD_CARD_ERROR_WRITE); + goto fail; + } + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** Start a write multiple blocks sequence. + * + * \param[in] blockNumber Address of first block in sequence. + * \param[in] eraseCount The number of blocks to be pre-erased. + * + * \note This function is used with writeData() and writeStop() + * for optimized multiple block writes. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool Sd2Card::writeStart(uint32_t blockNumber, uint32_t eraseCount) { + // send pre-erase count + if (cardAcmd(ACMD23, eraseCount)) { + error(SD_CARD_ERROR_ACMD23); + goto fail; + } + // use address if not SDHC card + if (type() != SD_CARD_TYPE_SDHC) blockNumber <<= 9; + if (cardCommand(CMD25, blockNumber)) { + error(SD_CARD_ERROR_CMD25); + goto fail; + } + chipSelectHigh(); + return true; + + fail: + chipSelectHigh(); + return false; +} +//------------------------------------------------------------------------------ +/** End a write multiple blocks sequence. + * +* \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool Sd2Card::writeStop() { + chipSelectLow(); + if (!waitNotBusy(SD_WRITE_TIMEOUT)) goto fail; + spiSend(STOP_TRAN_TOKEN); + if (!waitNotBusy(SD_WRITE_TIMEOUT)) goto fail; + chipSelectHigh(); + return true; + + fail: + error(SD_CARD_ERROR_STOP_TRAN); + chipSelectHigh(); + return false; +} + +#endif diff --git a/Marlin/Sd2Card.h b/Marlin/Sd2Card.h new file mode 100644 index 0000000..d6b302b --- /dev/null +++ b/Marlin/Sd2Card.h @@ -0,0 +1,243 @@ +/* Arduino Sd2Card Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino Sd2Card Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino Sd2Card Library. If not, see + * . + */ + +#include "Marlin.h" +#ifdef SDSUPPORT + +#ifndef Sd2Card_h +#define Sd2Card_h +/** + * \file + * \brief Sd2Card class for V2 SD/SDHC cards + */ +#include "SdFatConfig.h" +#include "Sd2PinMap.h" +#include "SdInfo.h" +//------------------------------------------------------------------------------ +// SPI speed is F_CPU/2^(1 + index), 0 <= index <= 6 +/** Set SCK to max rate of F_CPU/2. See Sd2Card::setSckRate(). */ +uint8_t const SPI_FULL_SPEED = 0; +/** Set SCK rate to F_CPU/4. See Sd2Card::setSckRate(). */ +uint8_t const SPI_HALF_SPEED = 1; +/** Set SCK rate to F_CPU/8. See Sd2Card::setSckRate(). */ +uint8_t const SPI_QUARTER_SPEED = 2; +/** Set SCK rate to F_CPU/16. See Sd2Card::setSckRate(). */ +uint8_t const SPI_EIGHTH_SPEED = 3; +/** Set SCK rate to F_CPU/32. See Sd2Card::setSckRate(). */ +uint8_t const SPI_SIXTEENTH_SPEED = 4; +//------------------------------------------------------------------------------ +/** init timeout ms */ +uint16_t const SD_INIT_TIMEOUT = 2000; +/** erase timeout ms */ +uint16_t const SD_ERASE_TIMEOUT = 10000; +/** read timeout ms */ +uint16_t const SD_READ_TIMEOUT = 300; +/** write time out ms */ +uint16_t const SD_WRITE_TIMEOUT = 600; +//------------------------------------------------------------------------------ +// SD card errors +/** timeout error for command CMD0 (initialize card in SPI mode) */ +uint8_t const SD_CARD_ERROR_CMD0 = 0X1; +/** CMD8 was not accepted - not a valid SD card*/ +uint8_t const SD_CARD_ERROR_CMD8 = 0X2; +/** card returned an error response for CMD12 (write stop) */ +uint8_t const SD_CARD_ERROR_CMD12 = 0X3; +/** card returned an error response for CMD17 (read block) */ +uint8_t const SD_CARD_ERROR_CMD17 = 0X4; +/** card returned an error response for CMD18 (read multiple block) */ +uint8_t const SD_CARD_ERROR_CMD18 = 0X5; +/** card returned an error response for CMD24 (write block) */ +uint8_t const SD_CARD_ERROR_CMD24 = 0X6; +/** WRITE_MULTIPLE_BLOCKS command failed */ +uint8_t const SD_CARD_ERROR_CMD25 = 0X7; +/** card returned an error response for CMD58 (read OCR) */ +uint8_t const SD_CARD_ERROR_CMD58 = 0X8; +/** SET_WR_BLK_ERASE_COUNT failed */ +uint8_t const SD_CARD_ERROR_ACMD23 = 0X9; +/** ACMD41 initialization process timeout */ +uint8_t const SD_CARD_ERROR_ACMD41 = 0XA; +/** card returned a bad CSR version field */ +uint8_t const SD_CARD_ERROR_BAD_CSD = 0XB; +/** erase block group command failed */ +uint8_t const SD_CARD_ERROR_ERASE = 0XC; +/** card not capable of single block erase */ +uint8_t const SD_CARD_ERROR_ERASE_SINGLE_BLOCK = 0XD; +/** Erase sequence timed out */ +uint8_t const SD_CARD_ERROR_ERASE_TIMEOUT = 0XE; +/** card returned an error token instead of read data */ +uint8_t const SD_CARD_ERROR_READ = 0XF; +/** read CID or CSD failed */ +uint8_t const SD_CARD_ERROR_READ_REG = 0X10; +/** timeout while waiting for start of read data */ +uint8_t const SD_CARD_ERROR_READ_TIMEOUT = 0X11; +/** card did not accept STOP_TRAN_TOKEN */ +uint8_t const SD_CARD_ERROR_STOP_TRAN = 0X12; +/** card returned an error token as a response to a write operation */ +uint8_t const SD_CARD_ERROR_WRITE = 0X13; +/** attempt to write protected block zero */ +uint8_t const SD_CARD_ERROR_WRITE_BLOCK_ZERO = 0X14; // REMOVE - not used +/** card did not go ready for a multiple block write */ +uint8_t const SD_CARD_ERROR_WRITE_MULTIPLE = 0X15; +/** card returned an error to a CMD13 status check after a write */ +uint8_t const SD_CARD_ERROR_WRITE_PROGRAMMING = 0X16; +/** timeout occurred during write programming */ +uint8_t const SD_CARD_ERROR_WRITE_TIMEOUT = 0X17; +/** incorrect rate selected */ +uint8_t const SD_CARD_ERROR_SCK_RATE = 0X18; +/** init() not called */ +uint8_t const SD_CARD_ERROR_INIT_NOT_CALLED = 0X19; +/** crc check error */ +uint8_t const SD_CARD_ERROR_CRC = 0X20; +//------------------------------------------------------------------------------ +// card types +/** Standard capacity V1 SD card */ +uint8_t const SD_CARD_TYPE_SD1 = 1; +/** Standard capacity V2 SD card */ +uint8_t const SD_CARD_TYPE_SD2 = 2; +/** High Capacity SD card */ +uint8_t const SD_CARD_TYPE_SDHC = 3; +/** + * define SOFTWARE_SPI to use bit-bang SPI + */ +//------------------------------------------------------------------------------ +#if MEGA_SOFT_SPI && (defined(__AVR_ATmega1280__)||defined(__AVR_ATmega2560__)) +#define SOFTWARE_SPI +#elif USE_SOFTWARE_SPI +#define SOFTWARE_SPI +#endif // MEGA_SOFT_SPI +//------------------------------------------------------------------------------ +// SPI pin definitions - do not edit here - change in SdFatConfig.h +// +#ifndef SOFTWARE_SPI +// hardware pin defs +/** The default chip select pin for the SD card is SS. */ +uint8_t const SD_CHIP_SELECT_PIN = SS_PIN; +// The following three pins must not be redefined for hardware SPI. +/** SPI Master Out Slave In pin */ +uint8_t const SPI_MOSI_PIN = MOSI_PIN; +/** SPI Master In Slave Out pin */ +uint8_t const SPI_MISO_PIN = MISO_PIN; +/** SPI Clock pin */ +uint8_t const SPI_SCK_PIN = SCK_PIN; + +#else // SOFTWARE_SPI + +/** SPI chip select pin */ +uint8_t const SD_CHIP_SELECT_PIN = SOFT_SPI_CS_PIN; +/** SPI Master Out Slave In pin */ +uint8_t const SPI_MOSI_PIN = SOFT_SPI_MOSI_PIN; +/** SPI Master In Slave Out pin */ +uint8_t const SPI_MISO_PIN = SOFT_SPI_MISO_PIN; +/** SPI Clock pin */ +uint8_t const SPI_SCK_PIN = SOFT_SPI_SCK_PIN; +#endif // SOFTWARE_SPI +//------------------------------------------------------------------------------ +/** + * \class Sd2Card + * \brief Raw access to SD and SDHC flash memory cards. + */ +class Sd2Card { + public: + /** Construct an instance of Sd2Card. */ + Sd2Card() : errorCode_(SD_CARD_ERROR_INIT_NOT_CALLED), type_(0) {} + uint32_t cardSize(); + bool erase(uint32_t firstBlock, uint32_t lastBlock); + bool eraseSingleBlockEnable(); + /** + * Set SD error code. + * \param[in] code value for error code. + */ + void error(uint8_t code) {errorCode_ = code;} + /** + * \return error code for last error. See Sd2Card.h for a list of error codes. + */ + int errorCode() const {return errorCode_;} + /** \return error data for last error. */ + int errorData() const {return status_;} + /** + * Initialize an SD flash memory card with default clock rate and chip + * select pin. See sd2Card::init(uint8_t sckRateID, uint8_t chipSelectPin). + * + * \return true for success or false for failure. + */ + bool init(uint8_t sckRateID = SPI_FULL_SPEED, + uint8_t chipSelectPin = SD_CHIP_SELECT_PIN); + bool readBlock(uint32_t block, uint8_t* dst); + /** + * Read a card's CID register. The CID contains card identification + * information such as Manufacturer ID, Product name, Product serial + * number and Manufacturing date. + * + * \param[out] cid pointer to area for returned data. + * + * \return true for success or false for failure. + */ + bool readCID(cid_t* cid) { + return readRegister(CMD10, cid); + } + /** + * Read a card's CSD register. The CSD contains Card-Specific Data that + * provides information regarding access to the card's contents. + * + * \param[out] csd pointer to area for returned data. + * + * \return true for success or false for failure. + */ + bool readCSD(csd_t* csd) { + return readRegister(CMD9, csd); + } + bool readData(uint8_t *dst); + bool readStart(uint32_t blockNumber); + bool readStop(); + bool setSckRate(uint8_t sckRateID); + /** Return the card type: SD V1, SD V2 or SDHC + * \return 0 - SD V1, 1 - SD V2, or 3 - SDHC. + */ + int type() const {return type_;} + bool writeBlock(uint32_t blockNumber, const uint8_t* src); + bool writeData(const uint8_t* src); + bool writeStart(uint32_t blockNumber, uint32_t eraseCount); + bool writeStop(); + private: + //---------------------------------------------------------------------------- + uint8_t chipSelectPin_; + uint8_t errorCode_; + uint8_t spiRate_; + uint8_t status_; + uint8_t type_; + // private functions + uint8_t cardAcmd(uint8_t cmd, uint32_t arg) { + cardCommand(CMD55, 0); + return cardCommand(cmd, arg); + } + uint8_t cardCommand(uint8_t cmd, uint32_t arg); + + bool readData(uint8_t* dst, uint16_t count); + bool readRegister(uint8_t cmd, void* buf); + void chipSelectHigh(); + void chipSelectLow(); + void type(uint8_t value) {type_ = value;} + bool waitNotBusy(uint16_t timeoutMillis); + bool writeData(uint8_t token, const uint8_t* src); +}; +#endif // Sd2Card_h + + +#endif \ No newline at end of file diff --git a/Marlin/Sd2PinMap.h b/Marlin/Sd2PinMap.h new file mode 100644 index 0000000..97fea8b --- /dev/null +++ b/Marlin/Sd2PinMap.h @@ -0,0 +1,436 @@ +/* Arduino SdFat Library + * Copyright (C) 2010 by William Greiman + * + * This file is part of the Arduino SdFat Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino SdFat Library. If not, see + * . + */ +// Warning this file was generated by a program. +#include "Marlin.h" +#ifdef SDSUPPORT + +#ifndef Sd2PinMap_h +#define Sd2PinMap_h +#include +//------------------------------------------------------------------------------ +/** struct for mapping digital pins */ +struct pin_map_t { + volatile uint8_t* ddr; + volatile uint8_t* pin; + volatile uint8_t* port; + uint8_t bit; +}; +//------------------------------------------------------------------------------ +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) // Mega + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 20; // D1 +uint8_t const SCL_PIN = 21; // D0 + +#undef MOSI_PIN +#undef MISO_PIN +#undef SCK_PIN +// SPI port +uint8_t const SS_PIN = 53; // B0 +uint8_t const MOSI_PIN = 51; // B2 +uint8_t const MISO_PIN = 50; // B3 +uint8_t const SCK_PIN = 52; // B1 + +static const pin_map_t digitalPinMap[] = { + {&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 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega644P__)\ +|| defined(__AVR_ATmega644__)\ +|| defined(__AVR_ATmega1284P__) +// Sanguino + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 17; // C1 +uint8_t const SCL_PIN = 18; // C2 + +// SPI port +uint8_t const SS_PIN = 4; // B4 +uint8_t const MOSI_PIN = 5; // B5 +uint8_t const MISO_PIN = 6; // B6 +uint8_t const SCK_PIN = 7; // B7 + +static const pin_map_t digitalPinMap[] = { + {&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 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega32U4__) +// Teensy 2.0 + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 6; // D1 +uint8_t const SCL_PIN = 5; // D0 + +// SPI port +uint8_t const SS_PIN = 0; // B0 +uint8_t const MOSI_PIN = 2; // B2 +uint8_t const MISO_PIN = 3; // B3 +uint8_t const SCK_PIN = 1; // B1 + +static const pin_map_t digitalPinMap[] = { + {&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 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_AT90USB646__)\ +|| defined(__AVR_AT90USB1286__) +// Teensy++ 1.0 & 2.0 + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 1; // D1 +uint8_t const SCL_PIN = 0; // D0 + +// SPI port +uint8_t const SS_PIN = 20; // B0 +uint8_t const MOSI_PIN = 22; // B2 +uint8_t const MISO_PIN = 23; // B3 +uint8_t const SCK_PIN = 21; // B1 + +static const pin_map_t digitalPinMap[] = { + {&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 +}; +//------------------------------------------------------------------------------ +#elif defined(__AVR_ATmega168__)\ +||defined(__AVR_ATmega168P__)\ +||defined(__AVR_ATmega328P__) +// 168 and 328 Arduinos + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 18; // C4 +uint8_t const SCL_PIN = 19; // C5 + +// SPI port +uint8_t const SS_PIN = 10; // B2 +uint8_t const MOSI_PIN = 11; // B3 +uint8_t const MISO_PIN = 12; // B4 +uint8_t const SCK_PIN = 13; // B5 + +static const pin_map_t digitalPinMap[] = { + {&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_ATmega1281__) +// Waspmote + +// Two Wire (aka I2C) ports +uint8_t const SDA_PIN = 41; +uint8_t const SCL_PIN = 40; + + +#undef MOSI_PIN +#undef MISO_PIN +// SPI port +uint8_t const SS_PIN = 16; // B0 +uint8_t const MOSI_PIN = 11; // B2 +uint8_t const MISO_PIN = 12; // B3 +uint8_t const SCK_PIN = 10; // B1 + +static const pin_map_t digitalPinMap[] = { + {&DDRE, &PINE, &PORTE, 0}, // E0 0 + {&DDRE, &PINE, &PORTE, 1}, // E1 1 + {&DDRE, &PINE, &PORTE, 3}, // E3 2 + {&DDRE, &PINE, &PORTE, 4}, // E4 3 + {&DDRC, &PINC, &PORTC, 4}, // C4 4 + {&DDRC, &PINC, &PORTC, 5}, // C5 5 + {&DDRC, &PINC, &PORTC, 6}, // C6 6 + {&DDRC, &PINC, &PORTC, 7}, // C7 7 + {&DDRA, &PINA, &PORTA, 2}, // A2 8 + {&DDRA, &PINA, &PORTA, 3}, // A3 9 + {&DDRA, &PINA, &PORTA, 4}, // A4 10 + {&DDRD, &PIND, &PORTD, 5}, // D5 11 + {&DDRD, &PIND, &PORTD, 6}, // D6 12 + {&DDRC, &PINC, &PORTC, 1}, // C1 13 + {&DDRF, &PINF, &PORTF, 1}, // F1 14 + {&DDRF, &PINF, &PORTF, 2}, // F2 15 + {&DDRF, &PINF, &PORTF, 3}, // F3 16 + {&DDRF, &PINF, &PORTF, 4}, // F4 17 + {&DDRF, &PINF, &PORTF, 5}, // F5 18 + {&DDRF, &PINF, &PORTF, 6}, // F6 19 + {&DDRF, &PINF, &PORTF, 7}, // F7 20 + {&DDRF, &PINF, &PORTF, 0}, // F0 21 + {&DDRA, &PINA, &PORTA, 1}, // A1 22 + {&DDRD, &PIND, &PORTD, 7}, // D7 23 + {&DDRE, &PINE, &PORTE, 5}, // E5 24 + {&DDRA, &PINA, &PORTA, 6}, // A6 25 + {&DDRE, &PINE, &PORTE, 2}, // E2 26 + {&DDRA, &PINA, &PORTA, 5}, // A5 27 + {&DDRC, &PINC, &PORTC, 0}, // C0 28 + {&DDRB, &PINB, &PORTB, 0}, // B0 29 + {&DDRB, &PINB, &PORTB, 1}, // B1 30 + {&DDRB, &PINB, &PORTB, 2}, // B2 31 + {&DDRB, &PINB, &PORTB, 3}, // B3 32 + {&DDRB, &PINB, &PORTB, 4}, // B4 33 + {&DDRB, &PINB, &PORTB, 5}, // B5 34 + {&DDRA, &PINA, &PORTA, 0}, // A0 35 + {&DDRB, &PINB, &PORTB, 6}, // B6 36 + {&DDRB, &PINB, &PORTB, 7}, // B7 37 + {&DDRE, &PINE, &PORTE, 6}, // E6 38 + {&DDRE, &PINE, &PORTE, 7}, // E7 39 + {&DDRD, &PIND, &PORTD, 0}, // D0 40 + {&DDRD, &PIND, &PORTD, 1}, // D1 41 + {&DDRC, &PINC, &PORTC, 3}, // C3 42 + {&DDRD, &PIND, &PORTD, 2}, // D2 43 + {&DDRD, &PIND, &PORTD, 3}, // D3 44 + {&DDRA, &PINA, &PORTA, 7}, // A7 45 + {&DDRC, &PINC, &PORTC, 2}, // C2 46 + {&DDRD, &PIND, &PORTD, 4}, // D4 47 + {&DDRG, &PING, &PORTG, 2}, // G2 48 + {&DDRG, &PING, &PORTG, 1}, // G1 49 + {&DDRG, &PING, &PORTG, 0}, // G0 50 +}; +#else // defined(__AVR_ATmega1280__) +#error unknown chip +#endif // defined(__AVR_ATmega1280__) +//------------------------------------------------------------------------------ +static const uint8_t digitalPinCount = sizeof(digitalPinMap)/sizeof(pin_map_t); + +uint8_t badPinNumber(void) + __attribute__((error("Pin number is too large or not a constant"))); + +static inline __attribute__((always_inline)) + bool getPinMode(uint8_t pin) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1; + } else { + return badPinNumber(); + } +} +static inline __attribute__((always_inline)) + void setPinMode(uint8_t pin, uint8_t mode) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + if (mode) { + *digitalPinMap[pin].ddr |= BIT(digitalPinMap[pin].bit); + } else { + *digitalPinMap[pin].ddr &= ~BIT(digitalPinMap[pin].bit); + } + } else { + badPinNumber(); + } +} +static inline __attribute__((always_inline)) + bool fastDigitalRead(uint8_t pin) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1; + } else { + return badPinNumber(); + } +} +static inline __attribute__((always_inline)) + void fastDigitalWrite(uint8_t pin, uint8_t value) { + if (__builtin_constant_p(pin) && pin < digitalPinCount) { + if (value) { + *digitalPinMap[pin].port |= BIT(digitalPinMap[pin].bit); + } else { + *digitalPinMap[pin].port &= ~BIT(digitalPinMap[pin].bit); + } + } else { + badPinNumber(); + } +} +#endif // Sd2PinMap_h + + +#endif diff --git a/Marlin/SdBaseFile.cpp b/Marlin/SdBaseFile.cpp new file mode 100644 index 0000000..c72eced --- /dev/null +++ b/Marlin/SdBaseFile.cpp @@ -0,0 +1,1825 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino SdFat Library. If not, see + * . + */ + +#include "Marlin.h" +#ifdef SDSUPPORT + +#include "SdBaseFile.h" +//------------------------------------------------------------------------------ +// pointer to cwd directory +SdBaseFile* SdBaseFile::cwd_ = 0; +// callback function for date/time +void (*SdBaseFile::dateTime_)(uint16_t* date, uint16_t* time) = 0; +//------------------------------------------------------------------------------ +// add a cluster to a file +bool SdBaseFile::addCluster() { + if (!vol_->allocContiguous(1, &curCluster_)) goto fail; + + // if first cluster of file link to directory entry + if (firstCluster_ == 0) { + firstCluster_ = curCluster_; + flags_ |= F_FILE_DIR_DIRTY; + } + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +// Add a cluster to a directory file and zero the cluster. +// return with first block of cluster in the cache +bool SdBaseFile::addDirCluster() { + uint32_t block; + // max folder size + if (fileSize_/sizeof(dir_t) >= 0XFFFF) goto fail; + + if (!addCluster()) goto fail; + if (!vol_->cacheFlush()) goto fail; + + block = vol_->clusterStartBlock(curCluster_); + + // set cache to first block of cluster + vol_->cacheSetBlockNumber(block, true); + + // zero first block of cluster + memset(vol_->cacheBuffer_.data, 0, 512); + + // zero rest of cluster + for (uint8_t i = 1; i < vol_->blocksPerCluster_; i++) { + if (!vol_->writeBlock(block + i, vol_->cacheBuffer_.data)) goto fail; + } + // Increase directory file size by cluster size + fileSize_ += 512UL << vol_->clusterSizeShift_; + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +// cache a file's directory entry +// return pointer to cached entry or null for failure +dir_t* SdBaseFile::cacheDirEntry(uint8_t action) { + if (!vol_->cacheRawBlock(dirBlock_, action)) goto fail; + return vol_->cache()->dir + dirIndex_; + + fail: + return 0; +} +//------------------------------------------------------------------------------ +/** Close a file and force cached data and directory information + * to be written to the storage device. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include no file is open or an I/O error. + */ +bool SdBaseFile::close() { + bool rtn = sync(); + type_ = FAT_FILE_TYPE_CLOSED; + return rtn; +} +//------------------------------------------------------------------------------ +/** Check for contiguous file and return its raw block range. + * + * \param[out] bgnBlock the first block address for the file. + * \param[out] endBlock the last block address for the file. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include file is not contiguous, file has zero length + * or an I/O error occurred. + */ +bool SdBaseFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) { + // error if no blocks + if (firstCluster_ == 0) goto fail; + + for (uint32_t c = firstCluster_; ; c++) { + uint32_t next; + if (!vol_->fatGet(c, &next)) goto fail; + + // check for contiguous + if (next != (c + 1)) { + // error if not end of chain + if (!vol_->isEOC(next)) goto fail; + *bgnBlock = vol_->clusterStartBlock(firstCluster_); + *endBlock = vol_->clusterStartBlock(c) + + vol_->blocksPerCluster_ - 1; + return true; + } + } + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Create and open a new contiguous file of a specified size. + * + * \note This function only supports short DOS 8.3 names. + * See open() for more information. + * + * \param[in] dirFile The directory where the file will be created. + * \param[in] path A path with a valid DOS 8.3 file name. + * \param[in] size The desired file size. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include \a path contains + * an invalid DOS 8.3 file name, the FAT volume has not been initialized, + * a file is already open, the file already exists, the root + * directory is full or an I/O error. + * + */ +bool SdBaseFile::createContiguous(SdBaseFile* dirFile, + const char* path, uint32_t size) { + uint32_t count; + // don't allow zero length file + if (size == 0) goto fail; + if (!open(dirFile, path, O_CREAT | O_EXCL | O_RDWR)) goto fail; + + // calculate number of clusters needed + count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1; + + // allocate clusters + if (!vol_->allocContiguous(count, &firstCluster_)) { + remove(); + goto fail; + } + fileSize_ = size; + + // insure sync() will update dir entry + flags_ |= F_FILE_DIR_DIRTY; + + return sync(); + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Return a file's directory entry. + * + * \param[out] dir Location for return of the file's directory entry. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool SdBaseFile::dirEntry(dir_t* dir) { + dir_t* p; + // make sure fields on SD are correct + if (!sync()) goto fail; + + // read entry + p = cacheDirEntry(SdVolume::CACHE_FOR_READ); + if (!p) goto fail; + + // copy to caller's struct + memcpy(dir, p, sizeof(dir_t)); + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Format the name field of \a dir into the 13 byte array + * \a name in standard 8.3 short name format. + * + * \param[in] dir The directory structure containing the name. + * \param[out] name A 13 byte char array for the formatted name. + */ +void SdBaseFile::dirName(const dir_t& dir, char* name) { + uint8_t j = 0; + for (uint8_t i = 0; i < 11; i++) { + if (dir.name[i] == ' ')continue; + if (i == 8) name[j++] = '.'; + name[j++] = dir.name[i]; + } + name[j] = 0; +} +//------------------------------------------------------------------------------ +/** Test for the existence of a file in a directory + * + * \param[in] name Name of the file to be tested for. + * + * The calling instance must be an open directory file. + * + * dirFile.exists("TOFIND.TXT") searches for "TOFIND.TXT" in the directory + * dirFile. + * + * \return true if the file exists else false. + */ +bool SdBaseFile::exists(const char* name) { + SdBaseFile file; + return file.open(this, name, O_READ); +} +//------------------------------------------------------------------------------ +/** + * Get a string from a file. + * + * fgets() reads bytes from a file into the array pointed to by \a str, until + * \a num - 1 bytes are read, or a delimiter is read and transferred to \a str, + * or end-of-file is encountered. The string is then terminated + * with a null byte. + * + * fgets() deletes CR, '\\r', from the string. This insures only a '\\n' + * terminates the string for Windows text files which use CRLF for newline. + * + * \param[out] str Pointer to the array where the string is stored. + * \param[in] num Maximum number of characters to be read + * (including the final null byte). Usually the length + * of the array \a str is used. + * \param[in] delim Optional set of delimiters. The default is "\n". + * + * \return For success fgets() returns the length of the string in \a str. + * If no data is read, fgets() returns zero for EOF or -1 if an error occurred. + **/ +int16_t SdBaseFile::fgets(char* str, int16_t num, char* delim) { + char ch; + int16_t n = 0; + int16_t r = -1; + while ((n + 1) < num && (r = read(&ch, 1)) == 1) { + // delete CR + if (ch == '\r') continue; + str[n++] = ch; + if (!delim) { + if (ch == '\n') break; + } else { + if (strchr(delim, ch)) break; + } + } + if (r < 0) { + // read error + return -1; + } + str[n] = '\0'; + return n; +} +//------------------------------------------------------------------------------ +/** Get a file's name + * + * \param[out] name An array of 13 characters for the file's name. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool SdBaseFile::getFilename(char* name) { + if (!isOpen()) return false; + + if (isRoot()) { + name[0] = '/'; + name[1] = '\0'; + return true; + } + // cache entry + dir_t* p = cacheDirEntry(SdVolume::CACHE_FOR_READ); + if (!p) return false; + + // format name + dirName(*p, name); + return true; +} +//------------------------------------------------------------------------------ +void SdBaseFile::getpos(fpos_t* pos) { + pos->position = curPosition_; + pos->cluster = curCluster_; +} + +//------------------------------------------------------------------------------ +/** List directory contents. + * + * \param[in] pr Print stream for list. + * + * \param[in] flags The inclusive OR of + * + * LS_DATE - %Print file modification date + * + * LS_SIZE - %Print file size. + * + * LS_R - Recursive list of subdirectories. + * + * \param[in] indent Amount of space before file name. Used for recursive + * list to indicate subdirectory level. + */ +void SdBaseFile::ls(uint8_t flags, uint8_t indent) { + rewind(); + int8_t status; + while ((status = lsPrintNext( flags, indent))) { + if (status > 1 && (flags & LS_R)) { + uint16_t index = curPosition()/32 - 1; + SdBaseFile s; + if (s.open(this, index, O_READ)) s.ls( flags, indent + 2); + seekSet(32 * (index + 1)); + } + } +} +//------------------------------------------------------------------------------ +// saves 32 bytes on stack for ls recursion +// return 0 - EOF, 1 - normal file, or 2 - directory +int8_t SdBaseFile::lsPrintNext( uint8_t flags, uint8_t indent) { + dir_t dir; + uint8_t w = 0; + + while (1) { + if (read(&dir, sizeof(dir)) != sizeof(dir)) return 0; + if (dir.name[0] == DIR_NAME_FREE) return 0; + + // skip deleted entry and entries for . and .. + if (dir.name[0] != DIR_NAME_DELETED && dir.name[0] != '.' + && DIR_IS_FILE_OR_SUBDIR(&dir)) break; + } + // indent for dir level + for (uint8_t i = 0; i < indent; i++) MYSERIAL.write(' '); + + // print name + for (uint8_t i = 0; i < 11; i++) { + if (dir.name[i] == ' ')continue; + if (i == 8) { + MYSERIAL.write('.'); + w++; + } + MYSERIAL.write(dir.name[i]); + w++; + } + if (DIR_IS_SUBDIR(&dir)) { + MYSERIAL.write('/'); + w++; + } + if (flags & (LS_DATE | LS_SIZE)) { + while (w++ < 14) MYSERIAL.write(' '); + } + // print modify date/time if requested + if (flags & LS_DATE) { + MYSERIAL.write(' '); + printFatDate( dir.lastWriteDate); + MYSERIAL.write(' '); + printFatTime( dir.lastWriteTime); + } + // print size if requested + if (!DIR_IS_SUBDIR(&dir) && (flags & LS_SIZE)) { + MYSERIAL.write(' '); + MYSERIAL.print(dir.fileSize); + } + MYSERIAL.println(); + return DIR_IS_FILE(&dir) ? 1 : 2; +} +//------------------------------------------------------------------------------ +// format directory name field from a 8.3 name string +bool SdBaseFile::make83Name(const char* str, uint8_t* name, const char** ptr) { + uint8_t c; + uint8_t n = 7; // max index for part before dot + uint8_t i = 0; + // blank fill name and extension + while (i < 11) name[i++] = ' '; + i = 0; + while (*str != '\0' && *str != '/') { + c = *str++; + if (c == '.') { + if (n == 10) goto fail; // only one dot allowed + n = 10; // max index for full 8.3 name + i = 8; // place for extension + } else { + // illegal FAT characters + PGM_P p = PSTR("|<>^+=?/[];,*\"\\"); + uint8_t b; + while ((b = pgm_read_byte(p++))) if (b == c) goto fail; + // check size and only allow ASCII printable characters + if (i > n || c < 0X21 || c > 0X7E)goto fail; + // only upper case allowed in 8.3 names - convert lower to upper + name[i++] = (c < 'a' || c > 'z') ? (c) : (c + ('A' - 'a')); + } + } + *ptr = str; + // must have a file name, extension is optional + return name[0] != ' '; + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Make a new directory. + * + * \param[in] parent An open SdFat instance for the directory that will contain + * the new directory. + * + * \param[in] path A path with a valid 8.3 DOS name for the new directory. + * + * \param[in] pFlag Create missing parent directories if true. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include this file is already open, \a parent is not a + * directory, \a path is invalid or already exists in \a parent. + */ +bool SdBaseFile::mkdir(SdBaseFile* parent, const char* path, bool pFlag) { + uint8_t dname[11]; + SdBaseFile dir1, dir2; + SdBaseFile* sub = &dir1; + SdBaseFile* start = parent; + + if (!parent || isOpen()) goto fail; + + if (*path == '/') { + while (*path == '/') path++; + if (!parent->isRoot()) { + if (!dir2.openRoot(parent->vol_)) goto fail; + parent = &dir2; + } + } + while (1) { + if (!make83Name(path, dname, &path)) goto fail; + while (*path == '/') path++; + if (!*path) break; + if (!sub->open(parent, dname, O_READ)) { + if (!pFlag || !sub->mkdir(parent, dname)) { + goto fail; + } + } + if (parent != start) parent->close(); + parent = sub; + sub = parent != &dir1 ? &dir1 : &dir2; + } + return mkdir(parent, dname); + + fail: + return false; +} +//------------------------------------------------------------------------------ +bool SdBaseFile::mkdir(SdBaseFile* parent, const uint8_t dname[11]) { + uint32_t block; + dir_t d; + dir_t* p; + + if (!parent->isDir()) goto fail; + + // create a normal file + if (!open(parent, dname, O_CREAT | O_EXCL | O_RDWR)) goto fail; + + // convert file to directory + flags_ = O_READ; + type_ = FAT_FILE_TYPE_SUBDIR; + + // allocate and zero first cluster + if (!addDirCluster())goto fail; + + // force entry to SD + if (!sync()) goto fail; + + // cache entry - should already be in cache due to sync() call + p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!p) goto fail; + + // change directory entry attribute + p->attributes = DIR_ATT_DIRECTORY; + + // make entry for '.' + memcpy(&d, p, sizeof(d)); + d.name[0] = '.'; + for (uint8_t i = 1; i < 11; i++) d.name[i] = ' '; + + // cache block for '.' and '..' + block = vol_->clusterStartBlock(firstCluster_); + if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) goto fail; + + // copy '.' to block + memcpy(&vol_->cache()->dir[0], &d, sizeof(d)); + + // make entry for '..' + d.name[1] = '.'; + if (parent->isRoot()) { + d.firstClusterLow = 0; + d.firstClusterHigh = 0; + } else { + d.firstClusterLow = parent->firstCluster_ & 0XFFFF; + d.firstClusterHigh = parent->firstCluster_ >> 16; + } + // copy '..' to block + memcpy(&vol_->cache()->dir[1], &d, sizeof(d)); + + // write first block + return vol_->cacheFlush(); + + fail: + return false; +} +//------------------------------------------------------------------------------ + /** Open a file in the current working directory. + * + * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. + * + * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t). + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ + bool SdBaseFile::open(const char* path, uint8_t oflag) { + return open(cwd_, path, oflag); + } +//------------------------------------------------------------------------------ +/** Open a file or directory by name. + * + * \param[in] dirFile An open SdFat instance for the directory containing the + * file to be opened. + * + * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. + * + * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + * OR of flags from the following list + * + * O_READ - Open for reading. + * + * O_RDONLY - Same as O_READ. + * + * O_WRITE - Open for writing. + * + * O_WRONLY - Same as O_WRITE. + * + * O_RDWR - Open for reading and writing. + * + * O_APPEND - If set, the file offset shall be set to the end of the + * file prior to each write. + * + * O_AT_END - Set the initial position at the end of the file. + * + * O_CREAT - If the file exists, this flag has no effect except as noted + * under O_EXCL below. Otherwise, the file shall be created + * + * O_EXCL - If O_CREAT and O_EXCL are set, open() shall fail if the file exists. + * + * O_SYNC - Call sync() after each write. This flag should not be used with + * write(uint8_t), write_P(PGM_P), writeln_P(PGM_P), or the Arduino Print class. + * These functions do character at a time writes so sync() will be called + * after each byte. + * + * O_TRUNC - If the file exists and is a regular file, and the file is + * successfully opened and is not read only, its length shall be truncated to 0. + * + * WARNING: A given file must not be opened by more than one SdBaseFile object + * of file corruption may occur. + * + * \note Directory files must be opened read only. Write and truncation is + * not allowed for directory files. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include this file is already open, \a dirFile is not + * a directory, \a path is invalid, the file does not exist + * or can't be opened in the access mode specified by oflag. + */ +bool SdBaseFile::open(SdBaseFile* dirFile, const char* path, uint8_t oflag) { + uint8_t dname[11]; + SdBaseFile dir1, dir2; + SdBaseFile *parent = dirFile; + SdBaseFile *sub = &dir1; + + if (!dirFile) goto fail; + + // error if already open + if (isOpen()) goto fail; + + if (*path == '/') { + while (*path == '/') path++; + if (!dirFile->isRoot()) { + if (!dir2.openRoot(dirFile->vol_)) goto fail; + parent = &dir2; + } + } + while (1) { + if (!make83Name(path, dname, &path)) goto fail; + while (*path == '/') path++; + if (!*path) break; + if (!sub->open(parent, dname, O_READ)) goto fail; + if (parent != dirFile) parent->close(); + parent = sub; + sub = parent != &dir1 ? &dir1 : &dir2; + } + return open(parent, dname, oflag); + + fail: + return false; +} +//------------------------------------------------------------------------------ +// open with filename in dname +bool SdBaseFile::open(SdBaseFile* dirFile, + const uint8_t dname[11], uint8_t oflag) { + bool emptyFound = false; + bool fileFound = false; + uint8_t index; + dir_t* p; + + vol_ = dirFile->vol_; + + dirFile->rewind(); + // search for file + + while (dirFile->curPosition_ < dirFile->fileSize_) { + index = 0XF & (dirFile->curPosition_ >> 5); + p = dirFile->readDirCache(); + if (!p) goto fail; + + if (p->name[0] == DIR_NAME_FREE || p->name[0] == DIR_NAME_DELETED) { + // remember first empty slot + if (!emptyFound) { + dirBlock_ = dirFile->vol_->cacheBlockNumber(); + dirIndex_ = index; + emptyFound = true; + } + // done if no entries follow + if (p->name[0] == DIR_NAME_FREE) break; + } else if (!memcmp(dname, p->name, 11)) { + fileFound = true; + break; + } + } + if (fileFound) { + // don't open existing file if O_EXCL + if (oflag & O_EXCL) goto fail; + } else { + // don't create unless O_CREAT and O_WRITE + if (!(oflag & O_CREAT) || !(oflag & O_WRITE)) goto fail; + if (emptyFound) { + index = dirIndex_; + p = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!p) goto fail; + } else { + if (dirFile->type_ == FAT_FILE_TYPE_ROOT_FIXED) goto fail; + + // add and zero cluster for dirFile - first cluster is in cache for write + if (!dirFile->addDirCluster()) goto fail; + + // use first entry in cluster + p = dirFile->vol_->cache()->dir; + index = 0; + } + // initialize as empty file + memset(p, 0, sizeof(dir_t)); + memcpy(p->name, dname, 11); + + // set timestamps + if (dateTime_) { + // call user date/time function + dateTime_(&p->creationDate, &p->creationTime); + } else { + // use default date/time + p->creationDate = FAT_DEFAULT_DATE; + p->creationTime = FAT_DEFAULT_TIME; + } + p->lastAccessDate = p->creationDate; + p->lastWriteDate = p->creationDate; + p->lastWriteTime = p->creationTime; + + // write entry to SD + if (!dirFile->vol_->cacheFlush()) goto fail; + } + // open entry in cache + return openCachedEntry(index, oflag); + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Open a file by index. + * + * \param[in] dirFile An open SdFat instance for the directory. + * + * \param[in] index The \a index of the directory entry for the file to be + * opened. The value for \a index is (directory file position)/32. + * + * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. + * + * See open() by path for definition of flags. + * \return true for success or false for failure. + */ +bool SdBaseFile::open(SdBaseFile* dirFile, uint16_t index, uint8_t oflag) { + dir_t* p; + + vol_ = dirFile->vol_; + + // error if already open + if (isOpen() || !dirFile) goto fail; + + // don't open existing file if O_EXCL - user call error + if (oflag & O_EXCL) goto fail; + + // seek to location of entry + if (!dirFile->seekSet(32 * index)) goto fail; + + // read entry into cache + p = dirFile->readDirCache(); + if (!p) goto fail; + + // error if empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_FREE || + p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { + goto fail; + } + // open cached entry + return openCachedEntry(index & 0XF, oflag); + + fail: + return false; +} +//------------------------------------------------------------------------------ +// open a cached directory entry. Assumes vol_ is initialized +bool SdBaseFile::openCachedEntry(uint8_t dirIndex, uint8_t oflag) { + // location of entry in cache + dir_t* p = &vol_->cache()->dir[dirIndex]; + + // write or truncate is an error for a directory or read-only file + if (p->attributes & (DIR_ATT_READ_ONLY | DIR_ATT_DIRECTORY)) { + if (oflag & (O_WRITE | O_TRUNC)) goto fail; + } + // remember location of directory entry on SD + dirBlock_ = vol_->cacheBlockNumber(); + dirIndex_ = dirIndex; + + // copy first cluster number for directory fields + firstCluster_ = (uint32_t)p->firstClusterHigh << 16; + firstCluster_ |= p->firstClusterLow; + + // make sure it is a normal file or subdirectory + if (DIR_IS_FILE(p)) { + fileSize_ = p->fileSize; + type_ = FAT_FILE_TYPE_NORMAL; + } else if (DIR_IS_SUBDIR(p)) { + if (!vol_->chainSize(firstCluster_, &fileSize_)) goto fail; + type_ = FAT_FILE_TYPE_SUBDIR; + } else { + goto fail; + } + // save open flags for read/write + flags_ = oflag & F_OFLAG; + + // set to start of file + curCluster_ = 0; + curPosition_ = 0; + if ((oflag & O_TRUNC) && !truncate(0)) return false; + return oflag & O_AT_END ? seekEnd(0) : true; + + fail: + type_ = FAT_FILE_TYPE_CLOSED; + return false; +} +//------------------------------------------------------------------------------ +/** Open the next file or subdirectory in a directory. + * + * \param[in] dirFile An open SdFat instance for the directory containing the + * file to be opened. + * + * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. + * + * See open() by path for definition of flags. + * \return true for success or false for failure. + */ +bool SdBaseFile::openNext(SdBaseFile* dirFile, uint8_t oflag) { + dir_t* p; + uint8_t index; + + if (!dirFile) goto fail; + + // error if already open + if (isOpen()) goto fail; + + vol_ = dirFile->vol_; + + while (1) { + index = 0XF & (dirFile->curPosition_ >> 5); + + // read entry into cache + p = dirFile->readDirCache(); + if (!p) goto fail; + + // done if last entry + if (p->name[0] == DIR_NAME_FREE) goto fail; + + // skip empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') { + continue; + } + // must be file or dir + if (DIR_IS_FILE_OR_SUBDIR(p)) { + return openCachedEntry(index, oflag); + } + } + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Open a directory's parent directory. + * + * \param[in] dir Parent of this directory will be opened. Must not be root. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool SdBaseFile::openParent(SdBaseFile* dir) { + dir_t entry; + dir_t* p; + SdBaseFile file; + uint32_t c; + uint32_t cluster; + uint32_t lbn; + // error if already open or dir is root or dir is not a directory + if (isOpen() || !dir || dir->isRoot() || !dir->isDir()) goto fail; + vol_ = dir->vol_; + // position to '..' + if (!dir->seekSet(32)) goto fail; + // read '..' entry + if (dir->read(&entry, sizeof(entry)) != 32) goto fail; + // verify it is '..' + if (entry.name[0] != '.' || entry.name[1] != '.') goto fail; + // start cluster for '..' + cluster = entry.firstClusterLow; + cluster |= (uint32_t)entry.firstClusterHigh << 16; + if (cluster == 0) return openRoot(vol_); + // start block for '..' + lbn = vol_->clusterStartBlock(cluster); + // first block of parent dir + if (!vol_->cacheRawBlock(lbn, SdVolume::CACHE_FOR_READ)) { + goto fail; + } + p = &vol_->cacheBuffer_.dir[1]; + // verify name for '../..' + if (p->name[0] != '.' || p->name[1] != '.') goto fail; + // '..' is pointer to first cluster of parent. open '../..' to find parent + if (p->firstClusterHigh == 0 && p->firstClusterLow == 0) { + if (!file.openRoot(dir->volume())) goto fail; + } else { + if (!file.openCachedEntry(1, O_READ)) goto fail; + } + // search for parent in '../..' + do { + if (file.readDir(&entry, NULL) != 32) goto fail; + c = entry.firstClusterLow; + c |= (uint32_t)entry.firstClusterHigh << 16; + } while (c != cluster); + // open parent + return open(&file, file.curPosition()/32 - 1, O_READ); + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Open a volume's root directory. + * + * \param[in] vol The FAT volume containing the root directory to be opened. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include the file is already open, the FAT volume has + * not been initialized or it a FAT12 volume. + */ +bool SdBaseFile::openRoot(SdVolume* vol) { + // error if file is already open + if (isOpen()) goto fail; + + if (vol->fatType() == 16 || (FAT12_SUPPORT && vol->fatType() == 12)) { + type_ = FAT_FILE_TYPE_ROOT_FIXED; + firstCluster_ = 0; + fileSize_ = 32 * vol->rootDirEntryCount(); + } else if (vol->fatType() == 32) { + type_ = FAT_FILE_TYPE_ROOT32; + firstCluster_ = vol->rootDirStart(); + if (!vol->chainSize(firstCluster_, &fileSize_)) goto fail; + } else { + // volume is not initialized, invalid, or FAT12 without support + return false; + } + vol_ = vol; + // read only + flags_ = O_READ; + + // set to start of file + curCluster_ = 0; + curPosition_ = 0; + + // root has no directory entry + dirBlock_ = 0; + dirIndex_ = 0; + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Return the next available byte without consuming it. + * + * \return The byte if no error and not at eof else -1; + */ +int SdBaseFile::peek() { + fpos_t pos; + getpos(&pos); + int c = read(); + if (c >= 0) setpos(&pos); + return c; +} + +//------------------------------------------------------------------------------ +/** %Print the name field of a directory entry in 8.3 format. + * \param[in] pr Print stream for output. + * \param[in] dir The directory structure containing the name. + * \param[in] width Blank fill name if length is less than \a width. + * \param[in] printSlash Print '/' after directory names if true. + */ +void SdBaseFile::printDirName(const dir_t& dir, + uint8_t width, bool printSlash) { + uint8_t w = 0; + for (uint8_t i = 0; i < 11; i++) { + if (dir.name[i] == ' ')continue; + if (i == 8) { + MYSERIAL.write('.'); + w++; + } + MYSERIAL.write(dir.name[i]); + w++; + } + if (DIR_IS_SUBDIR(&dir) && printSlash) { + MYSERIAL.write('/'); + w++; + } + while (w < width) { + MYSERIAL.write(' '); + w++; + } +} +//------------------------------------------------------------------------------ +// print uint8_t with width 2 +static void print2u( uint8_t v) { + if (v < 10) MYSERIAL.write('0'); + MYSERIAL.print(v, DEC); +} +//------------------------------------------------------------------------------ +/** %Print a directory date field to Serial. + * + * Format is yyyy-mm-dd. + * + * \param[in] fatDate The date field from a directory entry. + */ + +//------------------------------------------------------------------------------ +/** %Print a directory date field. + * + * Format is yyyy-mm-dd. + * + * \param[in] pr Print stream for output. + * \param[in] fatDate The date field from a directory entry. + */ +void SdBaseFile::printFatDate(uint16_t fatDate) { + MYSERIAL.print(FAT_YEAR(fatDate)); + MYSERIAL.write('-'); + print2u( FAT_MONTH(fatDate)); + MYSERIAL.write('-'); + print2u( FAT_DAY(fatDate)); +} + +//------------------------------------------------------------------------------ +/** %Print a directory time field. + * + * Format is hh:mm:ss. + * + * \param[in] pr Print stream for output. + * \param[in] fatTime The time field from a directory entry. + */ +void SdBaseFile::printFatTime( uint16_t fatTime) { + print2u( FAT_HOUR(fatTime)); + MYSERIAL.write(':'); + print2u( FAT_MINUTE(fatTime)); + MYSERIAL.write(':'); + print2u( FAT_SECOND(fatTime)); +} +//------------------------------------------------------------------------------ +/** Print a file's name to Serial + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool SdBaseFile::printName() { + char name[FILENAME_LENGTH]; + if (!getFilename(name)) return false; + MYSERIAL.print(name); + return true; +} +//------------------------------------------------------------------------------ +/** Read the next byte from a file. + * + * \return For success read returns the next byte in the file as an int. + * If an error occurs or end of file is reached -1 is returned. + */ +int16_t SdBaseFile::read() { + uint8_t b; + return read(&b, 1) == 1 ? b : -1; +} +//------------------------------------------------------------------------------ +/** Read data from a file starting at the current position. + * + * \param[out] buf Pointer to the location that will receive the data. + * + * \param[in] nbyte Maximum number of bytes to read. + * + * \return For success read() returns the number of bytes read. + * A value less than \a nbyte, including zero, will be returned + * if end of file is reached. + * If an error occurs, read() returns -1. Possible errors include + * read() called before a file has been opened, corrupt file system + * or an I/O error occurred. + */ +int16_t SdBaseFile::read(void* buf, uint16_t nbyte) { + uint8_t* dst = reinterpret_cast(buf); + uint16_t offset; + uint16_t toRead; + uint32_t block; // raw device block number + + // error if not open or write only + if (!isOpen() || !(flags_ & O_READ)) goto fail; + + // max bytes left in file + if (nbyte >= (fileSize_ - curPosition_)) { + nbyte = fileSize_ - curPosition_; + } + // amount left to read + toRead = nbyte; + while (toRead > 0) { + offset = curPosition_ & 0X1FF; // offset in block + if (type_ == FAT_FILE_TYPE_ROOT_FIXED) { + block = vol_->rootDirStart() + (curPosition_ >> 9); + } else { + uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); + if (offset == 0 && blockOfCluster == 0) { + // start of new cluster + if (curPosition_ == 0) { + // use first cluster in file + curCluster_ = firstCluster_; + } else { + // get next cluster from FAT + if (!vol_->fatGet(curCluster_, &curCluster_)) goto fail; + } + } + block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; + } + uint16_t n = toRead; + + // amount to be read from current block + if (n > (512 - offset)) n = 512 - offset; + + // no buffering needed if n == 512 + if (n == 512 && block != vol_->cacheBlockNumber()) { + if (!vol_->readBlock(block, dst)) goto fail; + } else { + // read block to cache and copy data to caller + if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) goto fail; + uint8_t* src = vol_->cache()->data + offset; + memcpy(dst, src, n); + } + dst += n; + curPosition_ += n; + toRead -= n; + } + return nbyte; + + fail: + return -1; +} +//------------------------------------------------------------------------------ +/** Read the next directory entry from a directory file. + * + * \param[out] dir The dir_t struct that will receive the data. + * + * \return For success readDir() returns the number of bytes read. + * A value of zero will be returned if end of file is reached. + * If an error occurs, readDir() returns -1. Possible errors include + * readDir() called before a directory has been opened, this is not + * a directory file or an I/O error occurred. + */ +int8_t SdBaseFile::readDir(dir_t* dir, char* longFilename) { + int16_t n; + // if not a directory file or miss-positioned return an error + if (!isDir() || (0X1F & curPosition_)) return -1; + + //If we have a longFilename buffer, mark it as invalid. If we find a long filename it will be filled automaticly. + if (longFilename != NULL) + { + longFilename[0] = '\0'; + } + + while (1) { + n = read(dir, sizeof(dir_t)); + if (n != sizeof(dir_t)) return n == 0 ? 0 : -1; + // last entry if DIR_NAME_FREE + if (dir->name[0] == DIR_NAME_FREE) return 0; + // skip empty entries and entry for . and .. + if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') continue; + //Fill the long filename if we have a long filename entry, + // long filename entries are stored before the actual filename. + if (DIR_IS_LONG_NAME(dir) && longFilename != NULL) + { + vfat_t *VFAT = (vfat_t*)dir; + //Sanity check the VFAT entry. The first cluster is always set to zero. And th esequence number should be higher then 0 + if (VFAT->firstClusterLow == 0 && (VFAT->sequenceNumber & 0x1F) > 0 && (VFAT->sequenceNumber & 0x1F) <= MAX_VFAT_ENTRIES) + { + //TODO: Store the filename checksum to verify if a none-long filename aware system modified the file table. + n = ((VFAT->sequenceNumber & 0x1F) - 1) * FILENAME_LENGTH; + longFilename[n+0] = VFAT->name1[0]; + longFilename[n+1] = VFAT->name1[1]; + longFilename[n+2] = VFAT->name1[2]; + longFilename[n+3] = VFAT->name1[3]; + longFilename[n+4] = VFAT->name1[4]; + longFilename[n+5] = VFAT->name2[0]; + longFilename[n+6] = VFAT->name2[1]; + longFilename[n+7] = VFAT->name2[2]; + longFilename[n+8] = VFAT->name2[3]; + longFilename[n+9] = VFAT->name2[4]; + longFilename[n+10] = VFAT->name2[5]; + longFilename[n+11] = VFAT->name3[0]; + longFilename[n+12] = VFAT->name3[1]; + //If this VFAT entry is the last one, add a NUL terminator at the end of the string + if (VFAT->sequenceNumber & 0x40) + longFilename[n+FILENAME_LENGTH] = '\0'; + } + } + // return if normal file or subdirectory + if (DIR_IS_FILE_OR_SUBDIR(dir)) return n; + } +} +//------------------------------------------------------------------------------ +// Read next directory entry into the cache +// Assumes file is correctly positioned +dir_t* SdBaseFile::readDirCache() { + uint8_t i; + // error if not directory + if (!isDir()) goto fail; + + // index of entry in cache + i = (curPosition_ >> 5) & 0XF; + + // use read to locate and cache block + if (read() < 0) goto fail; + + // advance to next entry + curPosition_ += 31; + + // return pointer to entry + return vol_->cache()->dir + i; + + fail: + return 0; +} +//------------------------------------------------------------------------------ +/** Remove a file. + * + * The directory entry and all data for the file are deleted. + * + * \note This function should not be used to delete the 8.3 version of a + * file that has a long name. For example if a file has the long name + * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include the file read-only, is a directory, + * or an I/O error occurred. + */ +bool SdBaseFile::remove() { + dir_t* d; + // free any clusters - will fail if read-only or directory + if (!truncate(0)) goto fail; + + // cache directory entry + d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) goto fail; + + // mark entry deleted + d->name[0] = DIR_NAME_DELETED; + + // set this file closed + type_ = FAT_FILE_TYPE_CLOSED; + + // write entry to SD + return vol_->cacheFlush(); + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Remove a file. + * + * The directory entry and all data for the file are deleted. + * + * \param[in] dirFile The directory that contains the file. + * \param[in] path Path for the file to be removed. + * + * \note This function should not be used to delete the 8.3 version of a + * file that has a long name. For example if a file has the long name + * "New Text Document.txt" you should not delete the 8.3 name "NEWTEX~1.TXT". + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include the file is a directory, is read only, + * \a dirFile is not a directory, \a path is not found + * or an I/O error occurred. + */ +bool SdBaseFile::remove(SdBaseFile* dirFile, const char* path) { + SdBaseFile file; + if (!file.open(dirFile, path, O_WRITE)) goto fail; + return file.remove(); + + fail: + // can't set iostate - static function + return false; +} +//------------------------------------------------------------------------------ +/** Rename a file or subdirectory. + * + * \param[in] dirFile Directory for the new path. + * \param[in] newPath New path name for the file/directory. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include \a dirFile is not open or is not a directory + * file, newPath is invalid or already exists, or an I/O error occurs. + */ +bool SdBaseFile::rename(SdBaseFile* dirFile, const char* newPath) { + dir_t entry; + uint32_t dirCluster = 0; + SdBaseFile file; + dir_t* d; + + // must be an open file or subdirectory + if (!(isFile() || isSubDir())) goto fail; + + // can't move file + if (vol_ != dirFile->vol_) goto fail; + + // sync() and cache directory entry + sync(); + d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) goto fail; + + // save directory entry + memcpy(&entry, d, sizeof(entry)); + + // mark entry deleted + d->name[0] = DIR_NAME_DELETED; + + // make directory entry for new path + if (isFile()) { + if (!file.open(dirFile, newPath, O_CREAT | O_EXCL | O_WRITE)) { + goto restore; + } + } else { + // don't create missing path prefix components + if (!file.mkdir(dirFile, newPath, false)) { + goto restore; + } + // save cluster containing new dot dot + dirCluster = file.firstCluster_; + } + // change to new directory entry + dirBlock_ = file.dirBlock_; + dirIndex_ = file.dirIndex_; + + // mark closed to avoid possible destructor close call + file.type_ = FAT_FILE_TYPE_CLOSED; + + // cache new directory entry + d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) goto fail; + + // copy all but name field to new directory entry + memcpy(&d->attributes, &entry.attributes, sizeof(entry) - sizeof(d->name)); + + // update dot dot if directory + if (dirCluster) { + // get new dot dot + uint32_t block = vol_->clusterStartBlock(dirCluster); + if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_READ)) goto fail; + memcpy(&entry, &vol_->cache()->dir[1], sizeof(entry)); + + // free unused cluster + if (!vol_->freeChain(dirCluster)) goto fail; + + // store new dot dot + block = vol_->clusterStartBlock(firstCluster_); + if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) goto fail; + memcpy(&vol_->cache()->dir[1], &entry, sizeof(entry)); + } + return vol_->cacheFlush(); + + restore: + d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) goto fail; + // restore entry + d->name[0] = entry.name[0]; + vol_->cacheFlush(); + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Remove a directory file. + * + * The directory file will be removed only if it is empty and is not the + * root directory. rmdir() follows DOS and Windows and ignores the + * read-only attribute for the directory. + * + * \note This function should not be used to delete the 8.3 version of a + * directory that has a long name. For example if a directory has the + * long name "New folder" you should not delete the 8.3 name "NEWFOL~1". + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include the file is not a directory, is the root + * directory, is not empty, or an I/O error occurred. + */ +bool SdBaseFile::rmdir() { + // must be open subdirectory + if (!isSubDir()) goto fail; + + rewind(); + + // make sure directory is empty + while (curPosition_ < fileSize_) { + dir_t* p = readDirCache(); + if (!p) goto fail; + // done if past last used entry + if (p->name[0] == DIR_NAME_FREE) break; + // skip empty slot, '.' or '..' + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; + // error not empty + if (DIR_IS_FILE_OR_SUBDIR(p)) goto fail; + } + // convert empty directory to normal file for remove + type_ = FAT_FILE_TYPE_NORMAL; + flags_ |= O_WRITE; + return remove(); + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Recursively delete a directory and all contained files. + * + * This is like the Unix/Linux 'rm -rf *' if called with the root directory + * hence the name. + * + * Warning - This will remove all contents of the directory including + * subdirectories. The directory will then be removed if it is not root. + * The read-only attribute for files will be ignored. + * + * \note This function should not be used to delete the 8.3 version of + * a directory that has a long name. See remove() and rmdir(). + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool SdBaseFile::rmRfStar() { + uint16_t index; + SdBaseFile f; + rewind(); + while (curPosition_ < fileSize_) { + // remember position + index = curPosition_/32; + + dir_t* p = readDirCache(); + if (!p) goto fail; + + // done if past last entry + if (p->name[0] == DIR_NAME_FREE) break; + + // skip empty slot or '.' or '..' + if (p->name[0] == DIR_NAME_DELETED || p->name[0] == '.') continue; + + // skip if part of long file name or volume label in root + if (!DIR_IS_FILE_OR_SUBDIR(p)) continue; + + if (!f.open(this, index, O_READ)) goto fail; + if (f.isSubDir()) { + // recursively delete + if (!f.rmRfStar()) goto fail; + } else { + // ignore read-only + f.flags_ |= O_WRITE; + if (!f.remove()) goto fail; + } + // position to next entry if required + if (curPosition_ != (32*(index + 1))) { + if (!seekSet(32*(index + 1))) goto fail; + } + } + // don't try to delete root + if (!isRoot()) { + if (!rmdir()) goto fail; + } + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Create a file object and open it in the current working directory. + * + * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. + * + * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t). + */ +SdBaseFile::SdBaseFile(const char* path, uint8_t oflag) { + type_ = FAT_FILE_TYPE_CLOSED; + writeError = false; + open(path, oflag); +} +//------------------------------------------------------------------------------ +/** Sets a file's position. + * + * \param[in] pos The new position in bytes from the beginning of the file. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool SdBaseFile::seekSet(uint32_t pos) { + uint32_t nCur; + uint32_t nNew; + // error if file not open or seek past end of file + if (!isOpen() || pos > fileSize_) goto fail; + + if (type_ == FAT_FILE_TYPE_ROOT_FIXED) { + curPosition_ = pos; + goto done; + } + if (pos == 0) { + // set position to start of file + curCluster_ = 0; + curPosition_ = 0; + goto done; + } + // calculate cluster index for cur and new position + nCur = (curPosition_ - 1) >> (vol_->clusterSizeShift_ + 9); + nNew = (pos - 1) >> (vol_->clusterSizeShift_ + 9); + + if (nNew < nCur || curPosition_ == 0) { + // must follow chain from first cluster + curCluster_ = firstCluster_; + } else { + // advance from curPosition + nNew -= nCur; + } + while (nNew--) { + if (!vol_->fatGet(curCluster_, &curCluster_)) goto fail; + } + curPosition_ = pos; + + done: + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +void SdBaseFile::setpos(fpos_t* pos) { + curPosition_ = pos->position; + curCluster_ = pos->cluster; +} +//------------------------------------------------------------------------------ +/** The sync() call causes all modified data and directory fields + * to be written to the storage device. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include a call to sync() before a file has been + * opened or an I/O error. + */ +bool SdBaseFile::sync() { + // only allow open files and directories + if (!isOpen()) goto fail; + + if (flags_ & F_FILE_DIR_DIRTY) { + dir_t* d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + // check for deleted by another open file object + if (!d || d->name[0] == DIR_NAME_DELETED) goto fail; + + // do not set filesize for dir files + if (!isDir()) d->fileSize = fileSize_; + + // update first cluster fields + d->firstClusterLow = firstCluster_ & 0XFFFF; + d->firstClusterHigh = firstCluster_ >> 16; + + // set modify time if user supplied a callback date/time function + if (dateTime_) { + dateTime_(&d->lastWriteDate, &d->lastWriteTime); + d->lastAccessDate = d->lastWriteDate; + } + // clear directory dirty + flags_ &= ~F_FILE_DIR_DIRTY; + } + return vol_->cacheFlush(); + + fail: + writeError = true; + return false; +} +//------------------------------------------------------------------------------ +/** Copy a file's timestamps + * + * \param[in] file File to copy timestamps from. + * + * \note + * Modify and access timestamps may be overwritten if a date time callback + * function has been set by dateTimeCallback(). + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool SdBaseFile::timestamp(SdBaseFile* file) { + dir_t* d; + dir_t dir; + + // get timestamps + if (!file->dirEntry(&dir)) goto fail; + + // update directory fields + if (!sync()) goto fail; + + d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) goto fail; + + // copy timestamps + d->lastAccessDate = dir.lastAccessDate; + d->creationDate = dir.creationDate; + d->creationTime = dir.creationTime; + d->creationTimeTenths = dir.creationTimeTenths; + d->lastWriteDate = dir.lastWriteDate; + d->lastWriteTime = dir.lastWriteTime; + + // write back entry + return vol_->cacheFlush(); + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Set a file's timestamps in its directory entry. + * + * \param[in] flags Values for \a flags are constructed by a bitwise-inclusive + * OR of flags from the following list + * + * T_ACCESS - Set the file's last access date. + * + * T_CREATE - Set the file's creation date and time. + * + * T_WRITE - Set the file's last write/modification date and time. + * + * \param[in] year Valid range 1980 - 2107 inclusive. + * + * \param[in] month Valid range 1 - 12 inclusive. + * + * \param[in] day Valid range 1 - 31 inclusive. + * + * \param[in] hour Valid range 0 - 23 inclusive. + * + * \param[in] minute Valid range 0 - 59 inclusive. + * + * \param[in] second Valid range 0 - 59 inclusive + * + * \note It is possible to set an invalid date since there is no check for + * the number of days in a month. + * + * \note + * Modify and access timestamps may be overwritten if a date time callback + * function has been set by dateTimeCallback(). + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + */ +bool SdBaseFile::timestamp(uint8_t flags, uint16_t year, uint8_t month, + uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) { + uint16_t dirDate; + uint16_t dirTime; + dir_t* d; + + if (!isOpen() + || year < 1980 + || year > 2107 + || month < 1 + || month > 12 + || day < 1 + || day > 31 + || hour > 23 + || minute > 59 + || second > 59) { + goto fail; + } + // update directory entry + if (!sync()) goto fail; + + d = cacheDirEntry(SdVolume::CACHE_FOR_WRITE); + if (!d) goto fail; + + dirDate = FAT_DATE(year, month, day); + dirTime = FAT_TIME(hour, minute, second); + if (flags & T_ACCESS) { + d->lastAccessDate = dirDate; + } + if (flags & T_CREATE) { + d->creationDate = dirDate; + d->creationTime = dirTime; + // seems to be units of 1/100 second not 1/10 as Microsoft states + d->creationTimeTenths = second & 1 ? 100 : 0; + } + if (flags & T_WRITE) { + d->lastWriteDate = dirDate; + d->lastWriteTime = dirTime; + } + return vol_->cacheFlush(); + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Truncate a file to a specified length. The current file position + * will be maintained if it is less than or equal to \a length otherwise + * it will be set to end of file. + * + * \param[in] length The desired length for the file. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. + * Reasons for failure include file is read only, file is a directory, + * \a length is greater than the current file size or an I/O error occurs. + */ +bool SdBaseFile::truncate(uint32_t length) { + uint32_t newPos; + // error if not a normal file or read-only + if (!isFile() || !(flags_ & O_WRITE)) goto fail; + + // error if length is greater than current size + if (length > fileSize_) goto fail; + + // fileSize and length are zero - nothing to do + if (fileSize_ == 0) return true; + + // remember position for seek after truncation + newPos = curPosition_ > length ? length : curPosition_; + + // position to last cluster in truncated file + if (!seekSet(length)) goto fail; + + if (length == 0) { + // free all clusters + if (!vol_->freeChain(firstCluster_)) goto fail; + firstCluster_ = 0; + } else { + uint32_t toFree; + if (!vol_->fatGet(curCluster_, &toFree)) goto fail; + + if (!vol_->isEOC(toFree)) { + // free extra clusters + if (!vol_->freeChain(toFree)) goto fail; + + // current cluster is end of chain + if (!vol_->fatPutEOC(curCluster_)) goto fail; + } + } + fileSize_ = length; + + // need to update directory entry + flags_ |= F_FILE_DIR_DIRTY; + + if (!sync()) goto fail; + + // set file to correct position + return seekSet(newPos); + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Write data to an open file. + * + * \note Data is moved to the cache but may not be written to the + * storage device until sync() is called. + * + * \param[in] buf Pointer to the location of the data to be written. + * + * \param[in] nbyte Number of bytes to write. + * + * \return For success write() returns the number of bytes written, always + * \a nbyte. If an error occurs, write() returns -1. Possible errors + * include write() is called before a file has been opened, write is called + * for a read-only file, device is full, a corrupt file system or an I/O error. + * + */ +int16_t SdBaseFile::write(const void* buf, uint16_t nbyte) { + // convert void* to uint8_t* - must be before goto statements + const uint8_t* src = reinterpret_cast(buf); + + // number of bytes left to write - must be before goto statements + uint16_t nToWrite = nbyte; + + // error if not a normal file or is read-only + if (!isFile() || !(flags_ & O_WRITE)) goto fail; + + // seek to end of file if append flag + if ((flags_ & O_APPEND) && curPosition_ != fileSize_) { + if (!seekEnd()) goto fail; + } + + while (nToWrite > 0) { + uint8_t blockOfCluster = vol_->blockOfCluster(curPosition_); + uint16_t blockOffset = curPosition_ & 0X1FF; + if (blockOfCluster == 0 && blockOffset == 0) { + // start of new cluster + if (curCluster_ == 0) { + if (firstCluster_ == 0) { + // allocate first cluster of file + if (!addCluster()) goto fail; + } else { + curCluster_ = firstCluster_; + } + } else { + uint32_t next; + if (!vol_->fatGet(curCluster_, &next)) goto fail; + if (vol_->isEOC(next)) { + // add cluster if at end of chain + if (!addCluster()) goto fail; + } else { + curCluster_ = next; + } + } + } + // max space in block + uint16_t n = 512 - blockOffset; + + // lesser of space and amount to write + if (n > nToWrite) n = nToWrite; + + // block for data write + uint32_t block = vol_->clusterStartBlock(curCluster_) + blockOfCluster; + if (n == 512) { + // full block - don't need to use cache + if (vol_->cacheBlockNumber() == block) { + // invalidate cache if block is in cache + vol_->cacheSetBlockNumber(0XFFFFFFFF, false); + } + if (!vol_->writeBlock(block, src)) goto fail; + } else { + if (blockOffset == 0 && curPosition_ >= fileSize_) { + // start of new block don't need to read into cache + if (!vol_->cacheFlush()) goto fail; + // set cache dirty and SD address of block + vol_->cacheSetBlockNumber(block, true); + } else { + // rewrite part of block + if (!vol_->cacheRawBlock(block, SdVolume::CACHE_FOR_WRITE)) goto fail; + } + uint8_t* dst = vol_->cache()->data + blockOffset; + memcpy(dst, src, n); + } + curPosition_ += n; + src += n; + nToWrite -= n; + } + if (curPosition_ > fileSize_) { + // update fileSize and insure sync will update dir entry + fileSize_ = curPosition_; + flags_ |= F_FILE_DIR_DIRTY; + } else if (dateTime_ && nbyte) { + // insure sync will update modified date and time + flags_ |= F_FILE_DIR_DIRTY; + } + + if (flags_ & O_SYNC) { + if (!sync()) goto fail; + } + return nbyte; + + fail: + // return for write error + writeError = true; + return -1; +} +//------------------------------------------------------------------------------ +// suppress cpplint warnings with NOLINT comment +#if ALLOW_DEPRECATED_FUNCTIONS && !defined(DOXYGEN) +void (*SdBaseFile::oldDateTime_)(uint16_t& date, uint16_t& time) = 0; // NOLINT +#endif // ALLOW_DEPRECATED_FUNCTIONS + + +#endif diff --git a/Marlin/SdBaseFile.h b/Marlin/SdBaseFile.h new file mode 100644 index 0000000..dea299a --- /dev/null +++ b/Marlin/SdBaseFile.h @@ -0,0 +1,483 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino SdFat Library. If not, see + * . + */ +#include "Marlin.h" +#ifdef SDSUPPORT + +#ifndef SdBaseFile_h +#define SdBaseFile_h +/** + * \file + * \brief SdBaseFile class + */ +#include "Marlin.h" +#include "SdFatConfig.h" +#include "SdVolume.h" +//------------------------------------------------------------------------------ +/** + * \struct fpos_t + * \brief internal type for istream + * do not use in user apps + */ +struct fpos_t { + /** stream position */ + uint32_t position; + /** cluster for position */ + uint32_t cluster; + fpos_t() : position(0), cluster(0) {} +}; + +// use the gnu style oflag in open() +/** open() oflag for reading */ +uint8_t const O_READ = 0X01; +/** open() oflag - same as O_IN */ +uint8_t const O_RDONLY = O_READ; +/** open() oflag for write */ +uint8_t const O_WRITE = 0X02; +/** open() oflag - same as O_WRITE */ +uint8_t const O_WRONLY = O_WRITE; +/** open() oflag for reading and writing */ +uint8_t const O_RDWR = (O_READ | O_WRITE); +/** open() oflag mask for access modes */ +uint8_t const O_ACCMODE = (O_READ | O_WRITE); +/** The file offset shall be set to the end of the file prior to each write. */ +uint8_t const O_APPEND = 0X04; +/** synchronous writes - call sync() after each write */ +uint8_t const O_SYNC = 0X08; +/** truncate the file to zero length */ +uint8_t const O_TRUNC = 0X10; +/** set the initial position at the end of the file */ +uint8_t const O_AT_END = 0X20; +/** create the file if nonexistent */ +uint8_t const O_CREAT = 0X40; +/** If O_CREAT and O_EXCL are set, open() shall fail if the file exists */ +uint8_t const O_EXCL = 0X80; + +// SdBaseFile class static and const definitions +// flags for ls() +/** ls() flag to print modify date */ +uint8_t const LS_DATE = 1; +/** ls() flag to print file size */ +uint8_t const LS_SIZE = 2; +/** ls() flag for recursive list of subdirectories */ +uint8_t const LS_R = 4; + + +// flags for timestamp +/** set the file's last access date */ +uint8_t const T_ACCESS = 1; +/** set the file's creation date and time */ +uint8_t const T_CREATE = 2; +/** Set the file's write date and time */ +uint8_t const T_WRITE = 4; +// values for type_ +/** This file has not been opened. */ +uint8_t const FAT_FILE_TYPE_CLOSED = 0; +/** A normal file */ +uint8_t const FAT_FILE_TYPE_NORMAL = 1; +/** A FAT12 or FAT16 root directory */ +uint8_t const FAT_FILE_TYPE_ROOT_FIXED = 2; +/** A FAT32 root directory */ +uint8_t const FAT_FILE_TYPE_ROOT32 = 3; +/** A subdirectory file*/ +uint8_t const FAT_FILE_TYPE_SUBDIR = 4; +/** Test value for directory type */ +uint8_t const FAT_FILE_TYPE_MIN_DIR = FAT_FILE_TYPE_ROOT_FIXED; + +/** date field for FAT directory entry + * \param[in] year [1980,2107] + * \param[in] month [1,12] + * \param[in] day [1,31] + * + * \return Packed date for dir_t entry. + */ +static inline uint16_t FAT_DATE(uint16_t year, uint8_t month, uint8_t day) { + return (year - 1980) << 9 | month << 5 | day; +} +/** year part of FAT directory date field + * \param[in] fatDate Date in packed dir format. + * + * \return Extracted year [1980,2107] + */ +static inline uint16_t FAT_YEAR(uint16_t fatDate) { + return 1980 + (fatDate >> 9); +} +/** month part of FAT directory date field + * \param[in] fatDate Date in packed dir format. + * + * \return Extracted month [1,12] + */ +static inline uint8_t FAT_MONTH(uint16_t fatDate) { + return (fatDate >> 5) & 0XF; +} +/** day part of FAT directory date field + * \param[in] fatDate Date in packed dir format. + * + * \return Extracted day [1,31] + */ +static inline uint8_t FAT_DAY(uint16_t fatDate) { + return fatDate & 0X1F; +} +/** time field for FAT directory entry + * \param[in] hour [0,23] + * \param[in] minute [0,59] + * \param[in] second [0,59] + * + * \return Packed time for dir_t entry. + */ +static inline uint16_t FAT_TIME(uint8_t hour, uint8_t minute, uint8_t second) { + return hour << 11 | minute << 5 | second >> 1; +} +/** hour part of FAT directory time field + * \param[in] fatTime Time in packed dir format. + * + * \return Extracted hour [0,23] + */ +static inline uint8_t FAT_HOUR(uint16_t fatTime) { + return fatTime >> 11; +} +/** minute part of FAT directory time field + * \param[in] fatTime Time in packed dir format. + * + * \return Extracted minute [0,59] + */ +static inline uint8_t FAT_MINUTE(uint16_t fatTime) { + return(fatTime >> 5) & 0X3F; +} +/** second part of FAT directory time field + * Note second/2 is stored in packed time. + * + * \param[in] fatTime Time in packed dir format. + * + * \return Extracted second [0,58] + */ +static inline uint8_t FAT_SECOND(uint16_t fatTime) { + return 2*(fatTime & 0X1F); +} +/** Default date for file timestamps is 1 Jan 2000 */ +uint16_t const FAT_DEFAULT_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1; +/** Default time for file timestamp is 1 am */ +uint16_t const FAT_DEFAULT_TIME = (1 << 11); +//------------------------------------------------------------------------------ +/** + * \class SdBaseFile + * \brief Base class for SdFile with Print and C++ streams. + */ +class SdBaseFile { + public: + /** Create an instance. */ + SdBaseFile() : writeError(false), type_(FAT_FILE_TYPE_CLOSED) {} + SdBaseFile(const char* path, uint8_t oflag); + ~SdBaseFile() {if(isOpen()) close();} + /** + * writeError is set to true if an error occurs during a write(). + * Set writeError to false before calling print() and/or write() and check + * for true after calls to print() and/or write(). + */ + bool writeError; + //---------------------------------------------------------------------------- + // helpers for stream classes + /** get position for streams + * \param[out] pos struct to receive position + */ + void getpos(fpos_t* pos); + /** set position for streams + * \param[out] pos struct with value for new position + */ + void setpos(fpos_t* pos); + //---------------------------------------------------------------------------- + bool close(); + bool contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); + bool createContiguous(SdBaseFile* dirFile, + const char* path, uint32_t size); + /** \return The current cluster number for a file or directory. */ + uint32_t curCluster() const {return curCluster_;} + /** \return The current position for a file or directory. */ + uint32_t curPosition() const {return curPosition_;} + /** \return Current working directory */ + static SdBaseFile* cwd() {return cwd_;} + /** Set the date/time callback function + * + * \param[in] dateTime The user's call back function. The callback + * function is of the form: + * + * \code + * void dateTime(uint16_t* date, uint16_t* time) { + * uint16_t year; + * uint8_t month, day, hour, minute, second; + * + * // User gets date and time from GPS or real-time clock here + * + * // return date using FAT_DATE macro to format fields + * *date = FAT_DATE(year, month, day); + * + * // return time using FAT_TIME macro to format fields + * *time = FAT_TIME(hour, minute, second); + * } + * \endcode + * + * Sets the function that is called when a file is created or when + * a file's directory entry is modified by sync(). All timestamps, + * access, creation, and modify, are set when a file is created. + * sync() maintains the last access date and last modify date/time. + * + * See the timestamp() function. + */ + static void dateTimeCallback( + void (*dateTime)(uint16_t* date, uint16_t* time)) { + dateTime_ = dateTime; + } + /** Cancel the date/time callback function. */ + static void dateTimeCallbackCancel() {dateTime_ = 0;} + bool dirEntry(dir_t* dir); + static void dirName(const dir_t& dir, char* name); + bool exists(const char* name); + int16_t fgets(char* str, int16_t num, char* delim = 0); + /** \return The total number of bytes in a file or directory. */ + uint32_t fileSize() const {return fileSize_;} + /** \return The first cluster number for a file or directory. */ + uint32_t firstCluster() const {return firstCluster_;} + bool getFilename(char* name); + /** \return True if this is a directory else false. */ + bool isDir() const {return type_ >= FAT_FILE_TYPE_MIN_DIR;} + /** \return True if this is a normal file else false. */ + bool isFile() const {return type_ == FAT_FILE_TYPE_NORMAL;} + /** \return True if this is an open file/directory else false. */ + bool isOpen() const {return type_ != FAT_FILE_TYPE_CLOSED;} + /** \return True if this is a subdirectory else false. */ + bool isSubDir() const {return type_ == FAT_FILE_TYPE_SUBDIR;} + /** \return True if this is the root directory. */ + bool isRoot() const { + return type_ == FAT_FILE_TYPE_ROOT_FIXED || type_ == FAT_FILE_TYPE_ROOT32; + } + void ls( uint8_t flags = 0, uint8_t indent = 0); + bool mkdir(SdBaseFile* dir, const char* path, bool pFlag = true); + // alias for backward compactability + bool makeDir(SdBaseFile* dir, const char* path) { + return mkdir(dir, path, false); + } + bool open(SdBaseFile* dirFile, uint16_t index, uint8_t oflag); + bool open(SdBaseFile* dirFile, const char* path, uint8_t oflag); + bool open(const char* path, uint8_t oflag = O_READ); + bool openNext(SdBaseFile* dirFile, uint8_t oflag); + bool openRoot(SdVolume* vol); + int peek(); + static void printFatDate(uint16_t fatDate); + static void printFatTime( uint16_t fatTime); + bool printName(); + int16_t read(); + int16_t read(void* buf, uint16_t nbyte); + int8_t readDir(dir_t* dir, char* longFilename); + static bool remove(SdBaseFile* dirFile, const char* path); + bool remove(); + /** Set the file's current position to zero. */ + void rewind() {seekSet(0);} + bool rename(SdBaseFile* dirFile, const char* newPath); + bool rmdir(); + // for backward compatibility + bool rmDir() {return rmdir();} + bool rmRfStar(); + /** Set the files position to current position + \a pos. See seekSet(). + * \param[in] offset The new position in bytes from the current position. + * \return true for success or false for failure. + */ + bool seekCur(int32_t offset) { + return seekSet(curPosition_ + offset); + } + /** Set the files position to end-of-file + \a offset. See seekSet(). + * \param[in] offset The new position in bytes from end-of-file. + * \return true for success or false for failure. + */ + bool seekEnd(int32_t offset = 0) {return seekSet(fileSize_ + offset);} + bool seekSet(uint32_t pos); + bool sync(); + bool timestamp(SdBaseFile* file); + bool timestamp(uint8_t flag, uint16_t year, uint8_t month, uint8_t day, + uint8_t hour, uint8_t minute, uint8_t second); + /** Type of file. You should use isFile() or isDir() instead of type() + * if possible. + * + * \return The file or directory type. + */ + uint8_t type() const {return type_;} + bool truncate(uint32_t size); + /** \return SdVolume that contains this file. */ + SdVolume* volume() const {return vol_;} + int16_t write(const void* buf, uint16_t nbyte); +//------------------------------------------------------------------------------ + private: + // allow SdFat to set cwd_ + friend class SdFat; + // global pointer to cwd dir + static SdBaseFile* cwd_; + // data time callback function + static void (*dateTime_)(uint16_t* date, uint16_t* time); + // bits defined in flags_ + // should be 0X0F + static uint8_t const F_OFLAG = (O_ACCMODE | O_APPEND | O_SYNC); + // sync of directory entry required + static uint8_t const F_FILE_DIR_DIRTY = 0X80; + + // private data + uint8_t flags_; // See above for definition of flags_ bits + uint8_t fstate_; // error and eof indicator + uint8_t type_; // type of file see above for values + uint32_t curCluster_; // cluster for current file position + uint32_t curPosition_; // current file position in bytes from beginning + uint32_t dirBlock_; // block for this files directory entry + uint8_t dirIndex_; // index of directory entry in dirBlock + uint32_t fileSize_; // file size in bytes + uint32_t firstCluster_; // first cluster of file + SdVolume* vol_; // volume where file is located + + /** experimental don't use */ + bool openParent(SdBaseFile* dir); + // private functions + bool addCluster(); + bool addDirCluster(); + dir_t* cacheDirEntry(uint8_t action); + int8_t lsPrintNext( uint8_t flags, uint8_t indent); + static bool make83Name(const char* str, uint8_t* name, const char** ptr); + bool mkdir(SdBaseFile* parent, const uint8_t dname[11]); + bool open(SdBaseFile* dirFile, const uint8_t dname[11], uint8_t oflag); + bool openCachedEntry(uint8_t cacheIndex, uint8_t oflags); + dir_t* readDirCache(); +//------------------------------------------------------------------------------ +// to be deleted + static void printDirName( const dir_t& dir, + uint8_t width, bool printSlash); +//------------------------------------------------------------------------------ +// Deprecated functions - suppress cpplint warnings with NOLINT comment +#if ALLOW_DEPRECATED_FUNCTIONS && !defined(DOXYGEN) + public: + /** \deprecated Use: + * bool contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock); + * \param[out] bgnBlock the first block address for the file. + * \param[out] endBlock the last block address for the file. + * \return true for success or false for failure. + */ + bool contiguousRange(uint32_t& bgnBlock, uint32_t& endBlock) { // NOLINT + return contiguousRange(&bgnBlock, &endBlock); + } + /** \deprecated Use: + * bool createContiguous(SdBaseFile* dirFile, + * const char* path, uint32_t size) + * \param[in] dirFile The directory where the file will be created. + * \param[in] path A path with a valid DOS 8.3 file name. + * \param[in] size The desired file size. + * \return true for success or false for failure. + */ + bool createContiguous(SdBaseFile& dirFile, // NOLINT + const char* path, uint32_t size) { + return createContiguous(&dirFile, path, size); + } + /** \deprecated Use: + * static void dateTimeCallback( + * void (*dateTime)(uint16_t* date, uint16_t* time)); + * \param[in] dateTime The user's call back function. + */ + static void dateTimeCallback( + void (*dateTime)(uint16_t& date, uint16_t& time)) { // NOLINT + oldDateTime_ = dateTime; + dateTime_ = dateTime ? oldToNew : 0; + } + /** \deprecated Use: bool dirEntry(dir_t* dir); + * \param[out] dir Location for return of the file's directory entry. + * \return true for success or false for failure. + */ + bool dirEntry(dir_t& dir) {return dirEntry(&dir);} // NOLINT + /** \deprecated Use: + * bool mkdir(SdBaseFile* dir, const char* path); + * \param[in] dir An open SdFat instance for the directory that will contain + * the new directory. + * \param[in] path A path with a valid 8.3 DOS name for the new directory. + * \return true for success or false for failure. + */ + bool mkdir(SdBaseFile& dir, const char* path) { // NOLINT + return mkdir(&dir, path); + } + /** \deprecated Use: + * bool open(SdBaseFile* dirFile, const char* path, uint8_t oflag); + * \param[in] dirFile An open SdFat instance for the directory containing the + * file to be opened. + * \param[in] path A path with a valid 8.3 DOS name for the file. + * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. + * \return true for success or false for failure. + */ + bool open(SdBaseFile& dirFile, // NOLINT + const char* path, uint8_t oflag) { + return open(&dirFile, path, oflag); + } + /** \deprecated Do not use in new apps + * \param[in] dirFile An open SdFat instance for the directory containing the + * file to be opened. + * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. + * \return true for success or false for failure. + */ + bool open(SdBaseFile& dirFile, const char* path) { // NOLINT + return open(dirFile, path, O_RDWR); + } + /** \deprecated Use: + * bool open(SdBaseFile* dirFile, uint16_t index, uint8_t oflag); + * \param[in] dirFile An open SdFat instance for the directory. + * \param[in] index The \a index of the directory entry for the file to be + * opened. The value for \a index is (directory file position)/32. + * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + * OR of flags O_READ, O_WRITE, O_TRUNC, and O_SYNC. + * \return true for success or false for failure. + */ + bool open(SdBaseFile& dirFile, uint16_t index, uint8_t oflag) { // NOLINT + return open(&dirFile, index, oflag); + } + /** \deprecated Use: bool openRoot(SdVolume* vol); + * \param[in] vol The FAT volume containing the root directory to be opened. + * \return true for success or false for failure. + */ + bool openRoot(SdVolume& vol) {return openRoot(&vol);} // NOLINT + /** \deprecated Use: int8_t readDir(dir_t* dir); + * \param[out] dir The dir_t struct that will receive the data. + * \return bytes read for success zero for eof or -1 for failure. + */ + int8_t readDir(dir_t& dir, char* longFilename) {return readDir(&dir, longFilename);} // NOLINT + /** \deprecated Use: + * static uint8_t remove(SdBaseFile* dirFile, const char* path); + * \param[in] dirFile The directory that contains the file. + * \param[in] path The name of the file to be removed. + * \return true for success or false for failure. + */ + static bool remove(SdBaseFile& dirFile, const char* path) { // NOLINT + return remove(&dirFile, path); + } +//------------------------------------------------------------------------------ +// rest are private + private: + static void (*oldDateTime_)(uint16_t& date, uint16_t& time); // NOLINT + static void oldToNew(uint16_t* date, uint16_t* time) { + uint16_t d; + uint16_t t; + oldDateTime_(d, t); + *date = d; + *time = t; + } +#endif // ALLOW_DEPRECATED_FUNCTIONS +}; + +#endif // SdBaseFile_h +#endif diff --git a/Marlin/SdFatConfig.h b/Marlin/SdFatConfig.h new file mode 100644 index 0000000..a549835 --- /dev/null +++ b/Marlin/SdFatConfig.h @@ -0,0 +1,125 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino SdFat Library. If not, see + * . + */ +/** + * \file + * \brief configuration definitions + */ +#include "Marlin.h" +#ifdef SDSUPPORT + +#ifndef SdFatConfig_h +#define SdFatConfig_h +#include +//------------------------------------------------------------------------------ +/** + * To use multiple SD cards set USE_MULTIPLE_CARDS nonzero. + * + * Using multiple cards costs 400 - 500 bytes of flash. + * + * Each card requires about 550 bytes of SRAM so use of a Mega is recommended. + */ +#define USE_MULTIPLE_CARDS 0 +//------------------------------------------------------------------------------ +/** + * Call flush for endl if ENDL_CALLS_FLUSH is nonzero + * + * The standard for iostreams is to call flush. This is very costly for + * SdFat. Each call to flush causes 2048 bytes of I/O to the SD. + * + * SdFat has a single 512 byte buffer for SD I/O so it must write the current + * data block to the SD, read the directory block from the SD, update the + * directory entry, write the directory block to the SD and read the data + * block back into the buffer. + * + * The SD flash memory controller is not designed for this many rewrites + * so performance may be reduced by more than a factor of 100. + * + * If ENDL_CALLS_FLUSH is zero, you must call flush and/or close to force + * all data to be written to the SD. + */ +#define ENDL_CALLS_FLUSH 0 +//------------------------------------------------------------------------------ +/** + * Allow use of deprecated functions if ALLOW_DEPRECATED_FUNCTIONS is nonzero + */ +#define ALLOW_DEPRECATED_FUNCTIONS 1 +//------------------------------------------------------------------------------ +/** + * Allow FAT12 volumes if FAT12_SUPPORT is nonzero. + * FAT12 has not been well tested. + */ +#define FAT12_SUPPORT 0 +//------------------------------------------------------------------------------ +/** + * SPI init rate for SD initialization commands. Must be 5 (F_CPU/64) + * or 6 (F_CPU/128). + */ +#define SPI_SD_INIT_RATE 5 +//------------------------------------------------------------------------------ +/** + * Set the SS pin high for hardware SPI. If SS is chip select for another SPI + * device this will disable that device during the SD init phase. + */ +#define SET_SPI_SS_HIGH 1 +//------------------------------------------------------------------------------ +/** + * Define MEGA_SOFT_SPI nonzero to use software SPI on Mega Arduinos. + * Pins used are SS 10, MOSI 11, MISO 12, and SCK 13. + * + * MEGA_SOFT_SPI allows an unmodified Adafruit GPS Shield to be used + * on Mega Arduinos. Software SPI works well with GPS Shield V1.1 + * but many SD cards will fail with GPS Shield V1.0. + */ +#define MEGA_SOFT_SPI 0 +//------------------------------------------------------------------------------ +/** + * Set USE_SOFTWARE_SPI nonzero to always use software SPI. + */ +#define USE_SOFTWARE_SPI 0 +// define software SPI pins so Mega can use unmodified 168/328 shields +/** Software SPI chip select pin for the SD */ +uint8_t const SOFT_SPI_CS_PIN = 10; +/** Software SPI Master Out Slave In pin */ +uint8_t const SOFT_SPI_MOSI_PIN = 11; +/** Software SPI Master In Slave Out pin */ +uint8_t const SOFT_SPI_MISO_PIN = 12; +/** Software SPI Clock pin */ +uint8_t const SOFT_SPI_SCK_PIN = 13; +//------------------------------------------------------------------------------ +/** + * The __cxa_pure_virtual function is an error handler that is invoked when + * a pure virtual function is called. + */ +#define USE_CXA_PURE_VIRTUAL 1 + +/** Number of UTF-16 characters per entry */ +#define FILENAME_LENGTH 13 + +/** + * Defines for long (vfat) filenames + */ +/** Number of VFAT entries used. Every entry has 13 UTF-16 characters */ +#define MAX_VFAT_ENTRIES (2) +/** Total size of the buffer used to store the long filenames */ +#define LONG_FILENAME_LENGTH (FILENAME_LENGTH*MAX_VFAT_ENTRIES+1) +#endif // SdFatConfig_h + + +#endif diff --git a/Marlin/SdFatStructs.h b/Marlin/SdFatStructs.h new file mode 100644 index 0000000..3867216 --- /dev/null +++ b/Marlin/SdFatStructs.h @@ -0,0 +1,646 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino SdFat Library. If not, see + * . + */ +#include "Marlin.h" +#ifdef SDSUPPORT + +#ifndef SdFatStructs_h +#define SdFatStructs_h + +#define PACKED __attribute__((__packed__)) +/** + * \file + * \brief FAT file structures + */ +/* + * mostly from Microsoft document fatgen103.doc + * http://www.microsoft.com/whdc/system/platform/firmware/fatgen.mspx + */ +//------------------------------------------------------------------------------ +/** Value for byte 510 of boot block or MBR */ +uint8_t const BOOTSIG0 = 0X55; +/** Value for byte 511 of boot block or MBR */ +uint8_t const BOOTSIG1 = 0XAA; +/** Value for bootSignature field int FAT/FAT32 boot sector */ +uint8_t const EXTENDED_BOOT_SIG = 0X29; +//------------------------------------------------------------------------------ +/** + * \struct partitionTable + * \brief MBR partition table entry + * + * A partition table entry for a MBR formatted storage device. + * The MBR partition table has four entries. + */ +struct partitionTable { + /** + * Boot Indicator . Indicates whether the volume is the active + * partition. Legal values include: 0X00. Do not use for booting. + * 0X80 Active partition. + */ + uint8_t boot; + /** + * Head part of Cylinder-head-sector address of the first block in + * the partition. Legal values are 0-255. Only used in old PC BIOS. + */ + uint8_t beginHead; + /** + * Sector part of Cylinder-head-sector address of the first block in + * the partition. Legal values are 1-63. Only used in old PC BIOS. + */ + unsigned beginSector : 6; + /** High bits cylinder for first block in partition. */ + unsigned beginCylinderHigh : 2; + /** + * Combine beginCylinderLow with beginCylinderHigh. Legal values + * are 0-1023. Only used in old PC BIOS. + */ + uint8_t beginCylinderLow; + /** + * Partition type. See defines that begin with PART_TYPE_ for + * some Microsoft partition types. + */ + uint8_t type; + /** + * head part of cylinder-head-sector address of the last sector in the + * partition. Legal values are 0-255. Only used in old PC BIOS. + */ + uint8_t endHead; + /** + * Sector part of cylinder-head-sector address of the last sector in + * the partition. Legal values are 1-63. Only used in old PC BIOS. + */ + unsigned endSector : 6; + /** High bits of end cylinder */ + unsigned endCylinderHigh : 2; + /** + * Combine endCylinderLow with endCylinderHigh. Legal values + * are 0-1023. Only used in old PC BIOS. + */ + uint8_t endCylinderLow; + /** Logical block address of the first block in the partition. */ + uint32_t firstSector; + /** Length of the partition, in blocks. */ + uint32_t totalSectors; +} PACKED; +/** Type name for partitionTable */ +typedef struct partitionTable part_t; +//------------------------------------------------------------------------------ +/** + * \struct masterBootRecord + * + * \brief Master Boot Record + * + * The first block of a storage device that is formatted with a MBR. + */ +struct masterBootRecord { + /** Code Area for master boot program. */ + uint8_t codeArea[440]; + /** Optional Windows NT disk signature. May contain boot code. */ + uint32_t diskSignature; + /** Usually zero but may be more boot code. */ + uint16_t usuallyZero; + /** Partition tables. */ + part_t part[4]; + /** First MBR signature byte. Must be 0X55 */ + uint8_t mbrSig0; + /** Second MBR signature byte. Must be 0XAA */ + uint8_t mbrSig1; +} PACKED; +/** Type name for masterBootRecord */ +typedef struct masterBootRecord mbr_t; +//------------------------------------------------------------------------------ +/** + * \struct fat_boot + * + * \brief Boot sector for a FAT12/FAT16 volume. + * + */ +struct fat_boot { + /** + * The first three bytes of the boot sector must be valid, + * executable x 86-based CPU instructions. This includes a + * jump instruction that skips the next nonexecutable bytes. + */ + uint8_t jump[3]; + /** + * This is typically a string of characters that identifies + * the operating system that formatted the volume. + */ + char oemId[8]; + /** + * The size of a hardware sector. Valid decimal values for this + * field are 512, 1024, 2048, and 4096. For most disks used in + * the United States, the value of this field is 512. + */ + uint16_t bytesPerSector; + /** + * Number of sectors per allocation unit. This value must be a + * power of 2 that is greater than 0. The legal values are + * 1, 2, 4, 8, 16, 32, 64, and 128. 128 should be avoided. + */ + uint8_t sectorsPerCluster; + /** + * The number of sectors preceding the start of the first FAT, + * including the boot sector. The value of this field is always 1. + */ + uint16_t reservedSectorCount; + /** + * The number of copies of the FAT on the volume. + * The value of this field is always 2. + */ + uint8_t fatCount; + /** + * For FAT12 and FAT16 volumes, this field contains the count of + * 32-byte directory entries in the root directory. For FAT32 volumes, + * this field must be set to 0. For FAT12 and FAT16 volumes, this + * value should always specify a count that when multiplied by 32 + * results in a multiple of bytesPerSector. FAT16 volumes should + * use the value 512. + */ + uint16_t rootDirEntryCount; + /** + * This field is the old 16-bit total count of sectors on the volume. + * This count includes the count of all sectors in all four regions + * of the volume. This field can be 0; if it is 0, then totalSectors32 + * must be nonzero. For FAT32 volumes, this field must be 0. For + * FAT12 and FAT16 volumes, this field contains the sector count, and + * totalSectors32 is 0 if the total sector count fits + * (is less than 0x10000). + */ + uint16_t totalSectors16; + /** + * This dates back to the old MS-DOS 1.x media determination and is + * no longer usually used for anything. 0xF8 is the standard value + * for fixed (nonremovable) media. For removable media, 0xF0 is + * frequently used. Legal values are 0xF0 or 0xF8-0xFF. + */ + uint8_t mediaType; + /** + * Count of sectors occupied by one FAT on FAT12/FAT16 volumes. + * On FAT32 volumes this field must be 0, and sectorsPerFat32 + * contains the FAT size count. + */ + uint16_t sectorsPerFat16; + /** Sectors per track for interrupt 0x13. Not used otherwise. */ + uint16_t sectorsPerTrack; + /** Number of heads for interrupt 0x13. Not used otherwise. */ + uint16_t headCount; + /** + * Count of hidden sectors preceding the partition that contains this + * FAT volume. This field is generally only relevant for media + * visible on interrupt 0x13. + */ + uint32_t hidddenSectors; + /** + * This field is the new 32-bit total count of sectors on the volume. + * This count includes the count of all sectors in all four regions + * of the volume. This field can be 0; if it is 0, then + * totalSectors16 must be nonzero. + */ + uint32_t totalSectors32; + /** + * Related to the BIOS physical drive number. Floppy drives are + * identified as 0x00 and physical hard disks are identified as + * 0x80, regardless of the number of physical disk drives. + * Typically, this value is set prior to issuing an INT 13h BIOS + * call to specify the device to access. The value is only + * relevant if the device is a boot device. + */ + uint8_t driveNumber; + /** used by Windows NT - should be zero for FAT */ + uint8_t reserved1; + /** 0X29 if next three fields are valid */ + uint8_t bootSignature; + /** + * A random serial number created when formatting a disk, + * which helps to distinguish between disks. + * Usually generated by combining date and time. + */ + uint32_t volumeSerialNumber; + /** + * A field once used to store the volume label. The volume label + * is now stored as a special file in the root directory. + */ + char volumeLabel[11]; + /** + * A field with a value of either FAT, FAT12 or FAT16, + * depending on the disk format. + */ + char fileSystemType[8]; + /** X86 boot code */ + uint8_t bootCode[448]; + /** must be 0X55 */ + uint8_t bootSectorSig0; + /** must be 0XAA */ + uint8_t bootSectorSig1; +} PACKED; +/** Type name for FAT Boot Sector */ +typedef struct fat_boot fat_boot_t; +//------------------------------------------------------------------------------ +/** + * \struct fat32_boot + * + * \brief Boot sector for a FAT32 volume. + * + */ +struct fat32_boot { + /** + * The first three bytes of the boot sector must be valid, + * executable x 86-based CPU instructions. This includes a + * jump instruction that skips the next nonexecutable bytes. + */ + uint8_t jump[3]; + /** + * This is typically a string of characters that identifies + * the operating system that formatted the volume. + */ + char oemId[8]; + /** + * The size of a hardware sector. Valid decimal values for this + * field are 512, 1024, 2048, and 4096. For most disks used in + * the United States, the value of this field is 512. + */ + uint16_t bytesPerSector; + /** + * Number of sectors per allocation unit. This value must be a + * power of 2 that is greater than 0. The legal values are + * 1, 2, 4, 8, 16, 32, 64, and 128. 128 should be avoided. + */ + uint8_t sectorsPerCluster; + /** + * The number of sectors preceding the start of the first FAT, + * including the boot sector. Must not be zero + */ + uint16_t reservedSectorCount; + /** + * The number of copies of the FAT on the volume. + * The value of this field is always 2. + */ + uint8_t fatCount; + /** + * FAT12/FAT16 only. For FAT32 volumes, this field must be set to 0. + */ + uint16_t rootDirEntryCount; + /** + * For FAT32 volumes, this field must be 0. + */ + uint16_t totalSectors16; + /** + * This dates back to the old MS-DOS 1.x media determination and is + * no longer usually used for anything. 0xF8 is the standard value + * for fixed (nonremovable) media. For removable media, 0xF0 is + * frequently used. Legal values are 0xF0 or 0xF8-0xFF. + */ + uint8_t mediaType; + /** + * On FAT32 volumes this field must be 0, and sectorsPerFat32 + * contains the FAT size count. + */ + uint16_t sectorsPerFat16; + /** Sectors per track for interrupt 0x13. Not used otherwise. */ + uint16_t sectorsPerTrack; + /** Number of heads for interrupt 0x13. Not used otherwise. */ + uint16_t headCount; + /** + * Count of hidden sectors preceding the partition that contains this + * FAT volume. This field is generally only relevant for media + * visible on interrupt 0x13. + */ + uint32_t hidddenSectors; + /** + * Contains the total number of sectors in the FAT32 volume. + */ + uint32_t totalSectors32; + /** + * Count of sectors occupied by one FAT on FAT32 volumes. + */ + uint32_t sectorsPerFat32; + /** + * This field is only defined for FAT32 media and does not exist on + * FAT12 and FAT16 media. + * Bits 0-3 -- Zero-based number of active FAT. + * Only valid if mirroring is disabled. + * Bits 4-6 -- Reserved. + * Bit 7 -- 0 means the FAT is mirrored at runtime into all FATs. + * -- 1 means only one FAT is active; it is the one referenced + * in bits 0-3. + * Bits 8-15 -- Reserved. + */ + uint16_t fat32Flags; + /** + * FAT32 version. High byte is major revision number. + * Low byte is minor revision number. Only 0.0 define. + */ + uint16_t fat32Version; + /** + * Cluster number of the first cluster of the root directory for FAT32. + * This usually 2 but not required to be 2. + */ + uint32_t fat32RootCluster; + /** + * Sector number of FSINFO structure in the reserved area of the + * FAT32 volume. Usually 1. + */ + uint16_t fat32FSInfo; + /** + * If nonzero, indicates the sector number in the reserved area + * of the volume of a copy of the boot record. Usually 6. + * No value other than 6 is recommended. + */ + uint16_t fat32BackBootBlock; + /** + * Reserved for future expansion. Code that formats FAT32 volumes + * should always set all of the bytes of this field to 0. + */ + uint8_t fat32Reserved[12]; + /** + * Related to the BIOS physical drive number. Floppy drives are + * identified as 0x00 and physical hard disks are identified as + * 0x80, regardless of the number of physical disk drives. + * Typically, this value is set prior to issuing an INT 13h BIOS + * call to specify the device to access. The value is only + * relevant if the device is a boot device. + */ + uint8_t driveNumber; + /** used by Windows NT - should be zero for FAT */ + uint8_t reserved1; + /** 0X29 if next three fields are valid */ + uint8_t bootSignature; + /** + * A random serial number created when formatting a disk, + * which helps to distinguish between disks. + * Usually generated by combining date and time. + */ + uint32_t volumeSerialNumber; + /** + * A field once used to store the volume label. The volume label + * is now stored as a special file in the root directory. + */ + char volumeLabel[11]; + /** + * A text field with a value of FAT32. + */ + char fileSystemType[8]; + /** X86 boot code */ + uint8_t bootCode[420]; + /** must be 0X55 */ + uint8_t bootSectorSig0; + /** must be 0XAA */ + uint8_t bootSectorSig1; +} PACKED; +/** Type name for FAT32 Boot Sector */ +typedef struct fat32_boot fat32_boot_t; +//------------------------------------------------------------------------------ +/** Lead signature for a FSINFO sector */ +uint32_t const FSINFO_LEAD_SIG = 0x41615252; +/** Struct signature for a FSINFO sector */ +uint32_t const FSINFO_STRUCT_SIG = 0x61417272; +/** + * \struct fat32_fsinfo + * + * \brief FSINFO sector for a FAT32 volume. + * + */ +struct fat32_fsinfo { + /** must be 0X52, 0X52, 0X61, 0X41 */ + uint32_t leadSignature; + /** must be zero */ + uint8_t reserved1[480]; + /** must be 0X72, 0X72, 0X41, 0X61 */ + uint32_t structSignature; + /** + * Contains the last known free cluster count on the volume. + * If the value is 0xFFFFFFFF, then the free count is unknown + * and must be computed. Any other value can be used, but is + * not necessarily correct. It should be range checked at least + * to make sure it is <= volume cluster count. + */ + uint32_t freeCount; + /** + * This is a hint for the FAT driver. It indicates the cluster + * number at which the driver should start looking for free clusters. + * If the value is 0xFFFFFFFF, then there is no hint and the driver + * should start looking at cluster 2. + */ + uint32_t nextFree; + /** must be zero */ + uint8_t reserved2[12]; + /** must be 0X00, 0X00, 0X55, 0XAA */ + uint8_t tailSignature[4]; +} PACKED; +/** Type name for FAT32 FSINFO Sector */ +typedef struct fat32_fsinfo fat32_fsinfo_t; +//------------------------------------------------------------------------------ +// End Of Chain values for FAT entries +/** FAT12 end of chain value used by Microsoft. */ +uint16_t const FAT12EOC = 0XFFF; +/** Minimum value for FAT12 EOC. Use to test for EOC. */ +uint16_t const FAT12EOC_MIN = 0XFF8; +/** FAT16 end of chain value used by Microsoft. */ +uint16_t const FAT16EOC = 0XFFFF; +/** Minimum value for FAT16 EOC. Use to test for EOC. */ +uint16_t const FAT16EOC_MIN = 0XFFF8; +/** FAT32 end of chain value used by Microsoft. */ +uint32_t const FAT32EOC = 0X0FFFFFFF; +/** Minimum value for FAT32 EOC. Use to test for EOC. */ +uint32_t const FAT32EOC_MIN = 0X0FFFFFF8; +/** Mask a for FAT32 entry. Entries are 28 bits. */ +uint32_t const FAT32MASK = 0X0FFFFFFF; +//------------------------------------------------------------------------------ +/** + * \struct directoryEntry + * \brief FAT short directory entry + * + * Short means short 8.3 name, not the entry size. + * + * Date Format. A FAT directory entry date stamp is a 16-bit field that is + * basically a date relative to the MS-DOS epoch of 01/01/1980. Here is the + * format (bit 0 is the LSB of the 16-bit word, bit 15 is the MSB of the + * 16-bit word): + * + * Bits 9-15: Count of years from 1980, valid value range 0-127 + * inclusive (1980-2107). + * + * Bits 5-8: Month of year, 1 = January, valid value range 1-12 inclusive. + * + * Bits 0-4: Day of month, valid value range 1-31 inclusive. + * + * Time Format. A FAT directory entry time stamp is a 16-bit field that has + * a granularity of 2 seconds. Here is the format (bit 0 is the LSB of the + * 16-bit word, bit 15 is the MSB of the 16-bit word). + * + * Bits 11-15: Hours, valid value range 0-23 inclusive. + * + * Bits 5-10: Minutes, valid value range 0-59 inclusive. + * + * Bits 0-4: 2-second count, valid value range 0-29 inclusive (0 - 58 seconds). + * + * The valid time range is from Midnight 00:00:00 to 23:59:58. + */ +struct directoryEntry { + /** Short 8.3 name. + * + * The first eight bytes contain the file name with blank fill. + * The last three bytes contain the file extension with blank fill. + */ + uint8_t name[11]; + /** Entry attributes. + * + * The upper two bits of the attribute byte are reserved and should + * always be set to 0 when a file is created and never modified or + * looked at after that. See defines that begin with DIR_ATT_. + */ + uint8_t attributes; + /** + * Reserved for use by Windows NT. Set value to 0 when a file is + * created and never modify or look at it after that. + */ + uint8_t reservedNT; + /** + * The granularity of the seconds part of creationTime is 2 seconds + * so this field is a count of tenths of a second and its valid + * value range is 0-199 inclusive. (WHG note - seems to be hundredths) + */ + uint8_t creationTimeTenths; + /** Time file was created. */ + uint16_t creationTime; + /** Date file was created. */ + uint16_t creationDate; + /** + * Last access date. Note that there is no last access time, only + * a date. This is the date of last read or write. In the case of + * a write, this should be set to the same date as lastWriteDate. + */ + uint16_t lastAccessDate; + /** + * High word of this entry's first cluster number (always 0 for a + * FAT12 or FAT16 volume). + */ + uint16_t firstClusterHigh; + /** Time of last write. File creation is considered a write. */ + uint16_t lastWriteTime; + /** Date of last write. File creation is considered a write. */ + uint16_t lastWriteDate; + /** Low word of this entry's first cluster number. */ + uint16_t firstClusterLow; + /** 32-bit unsigned holding this file's size in bytes. */ + uint32_t fileSize; +} PACKED; +/** + * \struct directoryVFATEntry + * \brief VFAT long filename directory entry + * + * directoryVFATEntries are found in the same list as normal directoryEntry. + * But have the attribute field set to DIR_ATT_LONG_NAME. + * + * Long filenames are saved in multiple directoryVFATEntries. + * Each entry containing 13 UTF-16 characters. + */ +struct directoryVFATEntry { + /** + * Sequence number. Consists of 2 parts: + * bit 6: indicates first long filename block for the next file + * bit 0-4: the position of this long filename block (first block is 1) + */ + uint8_t sequenceNumber; + /** First set of UTF-16 characters */ + uint16_t name1[5];//UTF-16 + /** attributes (at the same location as in directoryEntry), always 0x0F */ + uint8_t attributes; + /** Reserved for use by Windows NT. Always 0. */ + uint8_t reservedNT; + /** Checksum of the short 8.3 filename, can be used to checked if the file system as modified by a not-long-filename aware implementation. */ + uint8_t checksum; + /** Second set of UTF-16 characters */ + uint16_t name2[6];//UTF-16 + /** firstClusterLow is always zero for longFilenames */ + uint16_t firstClusterLow; + /** Third set of UTF-16 characters */ + uint16_t name3[2];//UTF-16 +} PACKED; +//------------------------------------------------------------------------------ +// Definitions for directory entries +// +/** Type name for directoryEntry */ +typedef struct directoryEntry dir_t; +/** Type name for directoryVFATEntry */ +typedef struct directoryVFATEntry vfat_t; +/** escape for name[0] = 0XE5 */ +uint8_t const DIR_NAME_0XE5 = 0X05; +/** name[0] value for entry that is free after being "deleted" */ +uint8_t const DIR_NAME_DELETED = 0XE5; +/** name[0] value for entry that is free and no allocated entries follow */ +uint8_t const DIR_NAME_FREE = 0X00; +/** file is read-only */ +uint8_t const DIR_ATT_READ_ONLY = 0X01; +/** File should hidden in directory listings */ +uint8_t const DIR_ATT_HIDDEN = 0X02; +/** Entry is for a system file */ +uint8_t const DIR_ATT_SYSTEM = 0X04; +/** Directory entry contains the volume label */ +uint8_t const DIR_ATT_VOLUME_ID = 0X08; +/** Entry is for a directory */ +uint8_t const DIR_ATT_DIRECTORY = 0X10; +/** Old DOS archive bit for backup support */ +uint8_t const DIR_ATT_ARCHIVE = 0X20; +/** Test value for long name entry. Test is + (d->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME. */ +uint8_t const DIR_ATT_LONG_NAME = 0X0F; +/** Test mask for long name entry */ +uint8_t const DIR_ATT_LONG_NAME_MASK = 0X3F; +/** defined attribute bits */ +uint8_t const DIR_ATT_DEFINED_BITS = 0X3F; +/** Directory entry is part of a long name + * \param[in] dir Pointer to a directory entry. + * + * \return true if the entry is for part of a long name else false. + */ +static inline uint8_t DIR_IS_LONG_NAME(const dir_t* dir) { + return (dir->attributes & DIR_ATT_LONG_NAME_MASK) == DIR_ATT_LONG_NAME; +} +/** Mask for file/subdirectory tests */ +uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY); +/** Directory entry is for a file + * \param[in] dir Pointer to a directory entry. + * + * \return true if the entry is for a normal file else false. + */ +static inline uint8_t DIR_IS_FILE(const dir_t* dir) { + return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == 0; +} +/** Directory entry is for a subdirectory + * \param[in] dir Pointer to a directory entry. + * + * \return true if the entry is for a subdirectory else false. + */ +static inline uint8_t DIR_IS_SUBDIR(const dir_t* dir) { + return (dir->attributes & DIR_ATT_FILE_TYPE_MASK) == DIR_ATT_DIRECTORY; +} +/** Directory entry is for a file or subdirectory + * \param[in] dir Pointer to a directory entry. + * + * \return true if the entry is for a normal file or subdirectory else false. + */ +static inline uint8_t DIR_IS_FILE_OR_SUBDIR(const dir_t* dir) { + return (dir->attributes & DIR_ATT_VOLUME_ID) == 0; +} +#endif // SdFatStructs_h + + +#endif diff --git a/Marlin/SdFatUtil.cpp b/Marlin/SdFatUtil.cpp new file mode 100644 index 0000000..32cd198 --- /dev/null +++ b/Marlin/SdFatUtil.cpp @@ -0,0 +1,82 @@ +/* Arduino SdFat Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino SdFat Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with the Arduino SdFat Library. If not, see + * . + */ +#include "Marlin.h" + +#ifdef SDSUPPORT +#include "SdFatUtil.h" + +//------------------------------------------------------------------------------ +/** Amount of free RAM + * \return The number of free bytes. + */ +#ifdef __arm__ +extern "C" char* sbrk(int incr); +int SdFatUtil::FreeRam() { + char top; + return &top - reinterpret_cast(sbrk(0)); +} +#else // __arm__ +extern char *__brkval; +extern char __bss_end; +/** Amount of free RAM + * \return The number of free bytes. + */ +int SdFatUtil::FreeRam() { + char top; + return __brkval ? &top - __brkval : &top - &__bss_end; +} +#endif // __arm + +//------------------------------------------------------------------------------ +/** %Print a string in flash memory. + * + * \param[in] pr Print object for output. + * \param[in] str Pointer to string stored in flash memory. + */ +void SdFatUtil::print_P( PGM_P str) { + for (uint8_t c; (c = pgm_read_byte(str)); str++) MYSERIAL.write(c); +} +//------------------------------------------------------------------------------ +/** %Print a string in flash memory followed by a CR/LF. + * + * \param[in] pr Print object for output. + * \param[in] str Pointer to string stored in flash memory. + */ +void SdFatUtil::println_P( PGM_P str) { + print_P( str); + MYSERIAL.println(); +} +//------------------------------------------------------------------------------ +/** %Print a string in flash memory to Serial. + * + * \param[in] str Pointer to string stored in flash memory. + */ +void SdFatUtil::SerialPrint_P(PGM_P str) { + print_P(str); +} +//------------------------------------------------------------------------------ +/** %Print a string in flash memory to Serial followed by a CR/LF. + * + * \param[in] str Pointer to string stored in flash memory. + */ +void SdFatUtil::SerialPrintln_P(PGM_P str) { + println_P( str); +} +#endif diff --git a/Marlin/SdFatUtil.h b/Marlin/SdFatUtil.h new file mode 100644 index 0000000..7f18094 --- /dev/null +++ b/Marlin/SdFatUtil.h @@ -0,0 +1,48 @@ +/* Arduino SdFat Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino SdFat Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with the Arduino SdFat Library. If not, see + * . + */ +#include "Marlin.h" +#ifdef SDSUPPORT + +#ifndef SdFatUtil_h +#define SdFatUtil_h +/** + * \file + * \brief Useful utility functions. + */ +#include "Marlin.h" +#include "MarlinSerial.h" +/** Store and print a string in flash memory.*/ +#define PgmPrint(x) SerialPrint_P(PSTR(x)) +/** Store and print a string in flash memory followed by a CR/LF.*/ +#define PgmPrintln(x) SerialPrintln_P(PSTR(x)) + +namespace SdFatUtil { + int FreeRam(); + void print_P( PGM_P str); + void println_P( PGM_P str); + void SerialPrint_P(PGM_P str); + void SerialPrintln_P(PGM_P str); +} + +using namespace SdFatUtil; // NOLINT +#endif // #define SdFatUtil_h + + +#endif \ No newline at end of file diff --git a/Marlin/SdFile.cpp b/Marlin/SdFile.cpp new file mode 100644 index 0000000..29f5efa --- /dev/null +++ b/Marlin/SdFile.cpp @@ -0,0 +1,95 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino SdFat Library. If not, see + * . + */ +#include "Marlin.h" + +#ifdef SDSUPPORT +#include "SdFile.h" +/** Create a file object and open it in the current working directory. + * + * \param[in] path A path with a valid 8.3 DOS name for a file to be opened. + * + * \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive + * OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t). + */ +SdFile::SdFile(const char* path, uint8_t oflag) : SdBaseFile(path, oflag) { +} +//------------------------------------------------------------------------------ +/** Write data to an open file. + * + * \note Data is moved to the cache but may not be written to the + * storage device until sync() is called. + * + * \param[in] buf Pointer to the location of the data to be written. + * + * \param[in] nbyte Number of bytes to write. + * + * \return For success write() returns the number of bytes written, always + * \a nbyte. If an error occurs, write() returns -1. Possible errors + * include write() is called before a file has been opened, write is called + * for a read-only file, device is full, a corrupt file system or an I/O error. + * + */ +int16_t SdFile::write(const void* buf, uint16_t nbyte) { + return SdBaseFile::write(buf, nbyte); +} +//------------------------------------------------------------------------------ +/** Write a byte to a file. Required by the Arduino Print class. + * \param[in] b the byte to be written. + * Use writeError to check for errors. + */ +#if ARDUINO >= 100 +size_t SdFile::write(uint8_t b) +{ + return SdBaseFile::write(&b, 1); +} +#else +void SdFile::write(uint8_t b) +{ + SdBaseFile::write(&b, 1); +} +#endif +//------------------------------------------------------------------------------ +/** Write a string to a file. Used by the Arduino Print class. + * \param[in] str Pointer to the string. + * Use writeError to check for errors. + */ +void SdFile::write(const char* str) { + SdBaseFile::write(str, strlen(str)); +} +//------------------------------------------------------------------------------ +/** Write a PROGMEM string to a file. + * \param[in] str Pointer to the PROGMEM string. + * Use writeError to check for errors. + */ +void SdFile::write_P(PGM_P str) { + for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c); +} +//------------------------------------------------------------------------------ +/** Write a PROGMEM string followed by CR/LF to a file. + * \param[in] str Pointer to the PROGMEM string. + * Use writeError to check for errors. + */ +void SdFile::writeln_P(PGM_P str) { + write_P(str); + write_P(PSTR("\r\n")); +} + + +#endif diff --git a/Marlin/SdFile.h b/Marlin/SdFile.h new file mode 100644 index 0000000..cbf1bbd --- /dev/null +++ b/Marlin/SdFile.h @@ -0,0 +1,54 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino SdFat Library. If not, see + * . + */ +/** + * \file + * \brief SdFile class + */ +#include "Marlin.h" + +#ifdef SDSUPPORT +#include "SdBaseFile.h" +#include +#ifndef SdFile_h +#define SdFile_h +//------------------------------------------------------------------------------ +/** + * \class SdFile + * \brief SdBaseFile with Print. + */ +class SdFile : public SdBaseFile, public Print { + public: + SdFile() {} + SdFile(const char* name, uint8_t oflag); + #if ARDUINO >= 100 + size_t write(uint8_t b); + #else + void write(uint8_t b); + #endif + + int16_t write(const void* buf, uint16_t nbyte); + void write(const char* str); + void write_P(PGM_P str); + void writeln_P(PGM_P str); +}; +#endif // SdFile_h + + +#endif \ No newline at end of file diff --git a/Marlin/SdInfo.h b/Marlin/SdInfo.h new file mode 100644 index 0000000..03ece10 --- /dev/null +++ b/Marlin/SdInfo.h @@ -0,0 +1,280 @@ +/* Arduino Sd2Card Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino Sd2Card Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino Sd2Card Library. If not, see + * . + */ +#include "Marlin.h" +#ifdef SDSUPPORT + +#ifndef SdInfo_h +#define SdInfo_h +#include +// Based on the document: +// +// SD Specifications +// Part 1 +// Physical Layer +// Simplified Specification +// Version 3.01 +// May 18, 2010 +// +// http://www.sdcard.org/developers/tech/sdcard/pls/simplified_specs +//------------------------------------------------------------------------------ +// SD card commands +/** GO_IDLE_STATE - init card in spi mode if CS low */ +uint8_t const CMD0 = 0X00; +/** SEND_IF_COND - verify SD Memory Card interface operating condition.*/ +uint8_t const CMD8 = 0X08; +/** SEND_CSD - read the Card Specific Data (CSD register) */ +uint8_t const CMD9 = 0X09; +/** SEND_CID - read the card identification information (CID register) */ +uint8_t const CMD10 = 0X0A; +/** STOP_TRANSMISSION - end multiple block read sequence */ +uint8_t const CMD12 = 0X0C; +/** SEND_STATUS - read the card status register */ +uint8_t const CMD13 = 0X0D; +/** READ_SINGLE_BLOCK - read a single data block from the card */ +uint8_t const CMD17 = 0X11; +/** READ_MULTIPLE_BLOCK - read a multiple data blocks from the card */ +uint8_t const CMD18 = 0X12; +/** WRITE_BLOCK - write a single data block to the card */ +uint8_t const CMD24 = 0X18; +/** WRITE_MULTIPLE_BLOCK - write blocks of data until a STOP_TRANSMISSION */ +uint8_t const CMD25 = 0X19; +/** ERASE_WR_BLK_START - sets the address of the first block to be erased */ +uint8_t const CMD32 = 0X20; +/** ERASE_WR_BLK_END - sets the address of the last block of the continuous + range to be erased*/ +uint8_t const CMD33 = 0X21; +/** ERASE - erase all previously selected blocks */ +uint8_t const CMD38 = 0X26; +/** APP_CMD - escape for application specific command */ +uint8_t const CMD55 = 0X37; +/** READ_OCR - read the OCR register of a card */ +uint8_t const CMD58 = 0X3A; +/** SET_WR_BLK_ERASE_COUNT - Set the number of write blocks to be + pre-erased before writing */ +uint8_t const ACMD23 = 0X17; +/** SD_SEND_OP_COMD - Sends host capacity support information and + activates the card's initialization process */ +uint8_t const ACMD41 = 0X29; +//------------------------------------------------------------------------------ +/** status for card in the ready state */ +uint8_t const R1_READY_STATE = 0X00; +/** status for card in the idle state */ +uint8_t const R1_IDLE_STATE = 0X01; +/** status bit for illegal command */ +uint8_t const R1_ILLEGAL_COMMAND = 0X04; +/** start data token for read or write single block*/ +uint8_t const DATA_START_BLOCK = 0XFE; +/** stop token for write multiple blocks*/ +uint8_t const STOP_TRAN_TOKEN = 0XFD; +/** start data token for write multiple blocks*/ +uint8_t const WRITE_MULTIPLE_TOKEN = 0XFC; +/** mask for data response tokens after a write block operation */ +uint8_t const DATA_RES_MASK = 0X1F; +/** write data accepted token */ +uint8_t const DATA_RES_ACCEPTED = 0X05; +//------------------------------------------------------------------------------ +/** Card IDentification (CID) register */ +typedef struct CID { + // byte 0 + /** Manufacturer ID */ + unsigned char mid; + // byte 1-2 + /** OEM/Application ID */ + char oid[2]; + // byte 3-7 + /** Product name */ + char pnm[5]; + // byte 8 + /** Product revision least significant digit */ + unsigned char prv_m : 4; + /** Product revision most significant digit */ + unsigned char prv_n : 4; + // byte 9-12 + /** Product serial number */ + uint32_t psn; + // byte 13 + /** Manufacturing date year low digit */ + unsigned char mdt_year_high : 4; + /** not used */ + unsigned char reserved : 4; + // byte 14 + /** Manufacturing date month */ + unsigned char mdt_month : 4; + /** Manufacturing date year low digit */ + unsigned char mdt_year_low :4; + // byte 15 + /** not used always 1 */ + unsigned char always1 : 1; + /** CRC7 checksum */ + unsigned char crc : 7; +}cid_t; +//------------------------------------------------------------------------------ +/** CSD for version 1.00 cards */ +typedef struct CSDV1 { + // byte 0 + unsigned char reserved1 : 6; + unsigned char csd_ver : 2; + // byte 1 + unsigned char taac; + // byte 2 + unsigned char nsac; + // byte 3 + unsigned char tran_speed; + // byte 4 + unsigned char ccc_high; + // byte 5 + unsigned char read_bl_len : 4; + unsigned char ccc_low : 4; + // byte 6 + unsigned char c_size_high : 2; + unsigned char reserved2 : 2; + unsigned char dsr_imp : 1; + unsigned char read_blk_misalign :1; + unsigned char write_blk_misalign : 1; + unsigned char read_bl_partial : 1; + // byte 7 + unsigned char c_size_mid; + // byte 8 + unsigned char vdd_r_curr_max : 3; + unsigned char vdd_r_curr_min : 3; + unsigned char c_size_low :2; + // byte 9 + unsigned char c_size_mult_high : 2; + unsigned char vdd_w_cur_max : 3; + unsigned char vdd_w_curr_min : 3; + // byte 10 + unsigned char sector_size_high : 6; + unsigned char erase_blk_en : 1; + unsigned char c_size_mult_low : 1; + // byte 11 + unsigned char wp_grp_size : 7; + unsigned char sector_size_low : 1; + // byte 12 + unsigned char write_bl_len_high : 2; + unsigned char r2w_factor : 3; + unsigned char reserved3 : 2; + unsigned char wp_grp_enable : 1; + // byte 13 + unsigned char reserved4 : 5; + unsigned char write_partial : 1; + unsigned char write_bl_len_low : 2; + // byte 14 + unsigned char reserved5: 2; + unsigned char file_format : 2; + unsigned char tmp_write_protect : 1; + unsigned char perm_write_protect : 1; + unsigned char copy : 1; + /** Indicates the file format on the card */ + unsigned char file_format_grp : 1; + // byte 15 + unsigned char always1 : 1; + unsigned char crc : 7; +}csd1_t; +//------------------------------------------------------------------------------ +/** CSD for version 2.00 cards */ +typedef struct CSDV2 { + // byte 0 + unsigned char reserved1 : 6; + unsigned char csd_ver : 2; + // byte 1 + /** fixed to 0X0E */ + unsigned char taac; + // byte 2 + /** fixed to 0 */ + unsigned char nsac; + // byte 3 + unsigned char tran_speed; + // byte 4 + unsigned char ccc_high; + // byte 5 + /** This field is fixed to 9h, which indicates READ_BL_LEN=512 Byte */ + unsigned char read_bl_len : 4; + unsigned char ccc_low : 4; + // byte 6 + /** not used */ + unsigned char reserved2 : 4; + unsigned char dsr_imp : 1; + /** fixed to 0 */ + unsigned char read_blk_misalign :1; + /** fixed to 0 */ + unsigned char write_blk_misalign : 1; + /** fixed to 0 - no partial read */ + unsigned char read_bl_partial : 1; + // byte 7 + /** not used */ + unsigned char reserved3 : 2; + /** high part of card size */ + unsigned char c_size_high : 6; + // byte 8 + /** middle part of card size */ + unsigned char c_size_mid; + // byte 9 + /** low part of card size */ + unsigned char c_size_low; + // byte 10 + /** sector size is fixed at 64 KB */ + unsigned char sector_size_high : 6; + /** fixed to 1 - erase single is supported */ + unsigned char erase_blk_en : 1; + /** not used */ + unsigned char reserved4 : 1; + // byte 11 + unsigned char wp_grp_size : 7; + /** sector size is fixed at 64 KB */ + unsigned char sector_size_low : 1; + // byte 12 + /** write_bl_len fixed for 512 byte blocks */ + unsigned char write_bl_len_high : 2; + /** fixed value of 2 */ + unsigned char r2w_factor : 3; + /** not used */ + unsigned char reserved5 : 2; + /** fixed value of 0 - no write protect groups */ + unsigned char wp_grp_enable : 1; + // byte 13 + unsigned char reserved6 : 5; + /** always zero - no partial block read*/ + unsigned char write_partial : 1; + /** write_bl_len fixed for 512 byte blocks */ + unsigned char write_bl_len_low : 2; + // byte 14 + unsigned char reserved7: 2; + /** Do not use always 0 */ + unsigned char file_format : 2; + unsigned char tmp_write_protect : 1; + unsigned char perm_write_protect : 1; + unsigned char copy : 1; + /** Do not use always 0 */ + unsigned char file_format_grp : 1; + // byte 15 + /** not used always 1 */ + unsigned char always1 : 1; + /** checksum */ + unsigned char crc : 7; +}csd2_t; +//------------------------------------------------------------------------------ +/** union of old and new style CSD register */ +union csd_t { + csd1_t v1; + csd2_t v2; +}; +#endif // SdInfo_h + +#endif \ No newline at end of file diff --git a/Marlin/SdVolume.cpp b/Marlin/SdVolume.cpp new file mode 100644 index 0000000..6297e2a --- /dev/null +++ b/Marlin/SdVolume.cpp @@ -0,0 +1,405 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino SdFat Library. If not, see + * . + */ +#include "Marlin.h" +#ifdef SDSUPPORT + +#include "SdVolume.h" +//------------------------------------------------------------------------------ +#if !USE_MULTIPLE_CARDS +// raw block cache +uint32_t SdVolume::cacheBlockNumber_; // current block number +cache_t SdVolume::cacheBuffer_; // 512 byte cache for Sd2Card +Sd2Card* SdVolume::sdCard_; // pointer to SD card object +bool SdVolume::cacheDirty_; // cacheFlush() will write block if true +uint32_t SdVolume::cacheMirrorBlock_; // mirror block for second FAT +#endif // USE_MULTIPLE_CARDS +//------------------------------------------------------------------------------ +// find a contiguous group of clusters +bool SdVolume::allocContiguous(uint32_t count, uint32_t* curCluster) { + // start of group + uint32_t bgnCluster; + // end of group + uint32_t endCluster; + // last cluster of FAT + uint32_t fatEnd = clusterCount_ + 1; + + // flag to save place to start next search + bool setStart; + + // set search start cluster + if (*curCluster) { + // try to make file contiguous + bgnCluster = *curCluster + 1; + + // don't save new start location + setStart = false; + } else { + // start at likely place for free cluster + bgnCluster = allocSearchStart_; + + // save next search start if one cluster + setStart = count == 1; + } + // end of group + endCluster = bgnCluster; + + // search the FAT for free clusters + for (uint32_t n = 0;; n++, endCluster++) { + // can't find space checked all clusters + if (n >= clusterCount_) goto fail; + + // past end - start from beginning of FAT + if (endCluster > fatEnd) { + bgnCluster = endCluster = 2; + } + uint32_t f; + if (!fatGet(endCluster, &f)) goto fail; + + if (f != 0) { + // cluster in use try next cluster as bgnCluster + bgnCluster = endCluster + 1; + } else if ((endCluster - bgnCluster + 1) == count) { + // done - found space + break; + } + } + // mark end of chain + if (!fatPutEOC(endCluster)) goto fail; + + // link clusters + while (endCluster > bgnCluster) { + if (!fatPut(endCluster - 1, endCluster)) goto fail; + endCluster--; + } + if (*curCluster != 0) { + // connect chains + if (!fatPut(*curCluster, bgnCluster)) goto fail; + } + // return first cluster number to caller + *curCluster = bgnCluster; + + // remember possible next free cluster + if (setStart) allocSearchStart_ = bgnCluster + 1; + + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +bool SdVolume::cacheFlush() { + if (cacheDirty_) { + if (!sdCard_->writeBlock(cacheBlockNumber_, cacheBuffer_.data)) { + goto fail; + } + // mirror FAT tables + if (cacheMirrorBlock_) { + if (!sdCard_->writeBlock(cacheMirrorBlock_, cacheBuffer_.data)) { + goto fail; + } + cacheMirrorBlock_ = 0; + } + cacheDirty_ = 0; + } + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +bool SdVolume::cacheRawBlock(uint32_t blockNumber, bool dirty) { + if (cacheBlockNumber_ != blockNumber) { + if (!cacheFlush()) goto fail; + if (!sdCard_->readBlock(blockNumber, cacheBuffer_.data)) goto fail; + cacheBlockNumber_ = blockNumber; + } + if (dirty) cacheDirty_ = true; + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +// return the size in bytes of a cluster chain +bool SdVolume::chainSize(uint32_t cluster, uint32_t* size) { + uint32_t s = 0; + do { + if (!fatGet(cluster, &cluster)) goto fail; + s += 512UL << clusterSizeShift_; + } while (!isEOC(cluster)); + *size = s; + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +// Fetch a FAT entry +bool SdVolume::fatGet(uint32_t cluster, uint32_t* value) { + uint32_t lba; + if (cluster > (clusterCount_ + 1)) goto fail; + if (FAT12_SUPPORT && fatType_ == 12) { + uint16_t index = cluster; + index += index >> 1; + lba = fatStartBlock_ + (index >> 9); + if (!cacheRawBlock(lba, CACHE_FOR_READ)) goto fail; + index &= 0X1FF; + uint16_t tmp = cacheBuffer_.data[index]; + index++; + if (index == 512) { + if (!cacheRawBlock(lba + 1, CACHE_FOR_READ)) goto fail; + index = 0; + } + tmp |= cacheBuffer_.data[index] << 8; + *value = cluster & 1 ? tmp >> 4 : tmp & 0XFFF; + return true; + } + if (fatType_ == 16) { + lba = fatStartBlock_ + (cluster >> 8); + } else if (fatType_ == 32) { + lba = fatStartBlock_ + (cluster >> 7); + } else { + goto fail; + } + if (lba != cacheBlockNumber_) { + if (!cacheRawBlock(lba, CACHE_FOR_READ)) goto fail; + } + if (fatType_ == 16) { + *value = cacheBuffer_.fat16[cluster & 0XFF]; + } else { + *value = cacheBuffer_.fat32[cluster & 0X7F] & FAT32MASK; + } + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +// Store a FAT entry +bool SdVolume::fatPut(uint32_t cluster, uint32_t value) { + uint32_t lba; + // error if reserved cluster + if (cluster < 2) goto fail; + + // error if not in FAT + if (cluster > (clusterCount_ + 1)) goto fail; + + if (FAT12_SUPPORT && fatType_ == 12) { + uint16_t index = cluster; + index += index >> 1; + lba = fatStartBlock_ + (index >> 9); + if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) goto fail; + // mirror second FAT + if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; + index &= 0X1FF; + uint8_t tmp = value; + if (cluster & 1) { + tmp = (cacheBuffer_.data[index] & 0XF) | tmp << 4; + } + cacheBuffer_.data[index] = tmp; + index++; + if (index == 512) { + lba++; + index = 0; + if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) goto fail; + // mirror second FAT + if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; + } + tmp = value >> 4; + if (!(cluster & 1)) { + tmp = ((cacheBuffer_.data[index] & 0XF0)) | tmp >> 4; + } + cacheBuffer_.data[index] = tmp; + return true; + } + if (fatType_ == 16) { + lba = fatStartBlock_ + (cluster >> 8); + } else if (fatType_ == 32) { + lba = fatStartBlock_ + (cluster >> 7); + } else { + goto fail; + } + if (!cacheRawBlock(lba, CACHE_FOR_WRITE)) goto fail; + // store entry + if (fatType_ == 16) { + cacheBuffer_.fat16[cluster & 0XFF] = value; + } else { + cacheBuffer_.fat32[cluster & 0X7F] = value; + } + // mirror second FAT + if (fatCount_ > 1) cacheMirrorBlock_ = lba + blocksPerFat_; + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +// free a cluster chain +bool SdVolume::freeChain(uint32_t cluster) { + uint32_t next; + + // clear free cluster location + allocSearchStart_ = 2; + + do { + if (!fatGet(cluster, &next)) goto fail; + + // free cluster + if (!fatPut(cluster, 0)) goto fail; + + cluster = next; + } while (!isEOC(cluster)); + + return true; + + fail: + return false; +} +//------------------------------------------------------------------------------ +/** Volume free space in clusters. + * + * \return Count of free clusters for success or -1 if an error occurs. + */ +int32_t SdVolume::freeClusterCount() { + uint32_t free = 0; + uint16_t n; + uint32_t todo = clusterCount_ + 2; + + if (fatType_ == 16) { + n = 256; + } else if (fatType_ == 32) { + n = 128; + } else { + // put FAT12 here + return -1; + } + + for (uint32_t lba = fatStartBlock_; todo; todo -= n, lba++) { + if (!cacheRawBlock(lba, CACHE_FOR_READ)) return -1; + if (todo < n) n = todo; + if (fatType_ == 16) { + for (uint16_t i = 0; i < n; i++) { + if (cacheBuffer_.fat16[i] == 0) free++; + } + } else { + for (uint16_t i = 0; i < n; i++) { + if (cacheBuffer_.fat32[i] == 0) free++; + } + } + } + return free; +} +//------------------------------------------------------------------------------ +/** Initialize a FAT volume. + * + * \param[in] dev The SD card where the volume is located. + * + * \param[in] part The partition to be used. Legal values for \a part are + * 1-4 to use the corresponding partition on a device formatted with + * a MBR, Master Boot Record, or zero if the device is formatted as + * a super floppy with the FAT boot sector in block zero. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. Reasons for + * failure include not finding a valid partition, not finding a valid + * FAT file system in the specified partition or an I/O error. + */ +bool SdVolume::init(Sd2Card* dev, uint8_t part) { + uint32_t totalBlocks; + uint32_t volumeStartBlock = 0; + fat32_boot_t* fbs; + + sdCard_ = dev; + fatType_ = 0; + allocSearchStart_ = 2; + cacheDirty_ = 0; // cacheFlush() will write block if true + cacheMirrorBlock_ = 0; + cacheBlockNumber_ = 0XFFFFFFFF; + + // if part == 0 assume super floppy with FAT boot sector in block zero + // if part > 0 assume mbr volume with partition table + if (part) { + if (part > 4)goto fail; + if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) goto fail; + part_t* p = &cacheBuffer_.mbr.part[part-1]; + if ((p->boot & 0X7F) !=0 || + p->totalSectors < 100 || + p->firstSector == 0) { + // not a valid partition + goto fail; + } + volumeStartBlock = p->firstSector; + } + if (!cacheRawBlock(volumeStartBlock, CACHE_FOR_READ)) goto fail; + fbs = &cacheBuffer_.fbs32; + if (fbs->bytesPerSector != 512 || + fbs->fatCount == 0 || + fbs->reservedSectorCount == 0 || + fbs->sectorsPerCluster == 0) { + // not valid FAT volume + goto fail; + } + fatCount_ = fbs->fatCount; + blocksPerCluster_ = fbs->sectorsPerCluster; + // determine shift that is same as multiply by blocksPerCluster_ + clusterSizeShift_ = 0; + while (blocksPerCluster_ != BIT(clusterSizeShift_)) { + // error if not power of 2 + if (clusterSizeShift_++ > 7) goto fail; + } + blocksPerFat_ = fbs->sectorsPerFat16 ? + fbs->sectorsPerFat16 : fbs->sectorsPerFat32; + + fatStartBlock_ = volumeStartBlock + fbs->reservedSectorCount; + + // count for FAT16 zero for FAT32 + rootDirEntryCount_ = fbs->rootDirEntryCount; + + // directory start for FAT16 dataStart for FAT32 + rootDirStart_ = fatStartBlock_ + fbs->fatCount * blocksPerFat_; + + // data start for FAT16 and FAT32 + dataStartBlock_ = rootDirStart_ + ((32 * fbs->rootDirEntryCount + 511)/512); + + // total blocks for FAT16 or FAT32 + totalBlocks = fbs->totalSectors16 ? + fbs->totalSectors16 : fbs->totalSectors32; + // total data blocks + clusterCount_ = totalBlocks - (dataStartBlock_ - volumeStartBlock); + + // divide by cluster size to get cluster count + clusterCount_ >>= clusterSizeShift_; + + // FAT type is determined by cluster count + if (clusterCount_ < 4085) { + fatType_ = 12; + if (!FAT12_SUPPORT) goto fail; + } else if (clusterCount_ < 65525) { + fatType_ = 16; + } else { + rootDirStart_ = fbs->fat32RootCluster; + fatType_ = 32; + } + return true; + + fail: + return false; +} +#endif \ No newline at end of file diff --git a/Marlin/SdVolume.h b/Marlin/SdVolume.h new file mode 100644 index 0000000..2ff2b6e --- /dev/null +++ b/Marlin/SdVolume.h @@ -0,0 +1,214 @@ +/* Arduino SdFat Library + * Copyright (C) 2009 by William Greiman + * + * This file is part of the Arduino SdFat Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 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 General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Arduino SdFat Library. If not, see + * . + */ +#include "Marlin.h" +#ifdef SDSUPPORT +#ifndef SdVolume_h +#define SdVolume_h +/** + * \file + * \brief SdVolume class + */ +#include "SdFatConfig.h" +#include "Sd2Card.h" +#include "SdFatStructs.h" + +//============================================================================== +// SdVolume class +/** + * \brief Cache for an SD data block + */ +union cache_t { + /** Used to access cached file data blocks. */ + uint8_t data[512]; + /** Used to access cached FAT16 entries. */ + uint16_t fat16[256]; + /** Used to access cached FAT32 entries. */ + uint32_t fat32[128]; + /** Used to access cached directory entries. */ + dir_t dir[16]; + /** Used to access a cached Master Boot Record. */ + mbr_t mbr; + /** Used to access to a cached FAT boot sector. */ + fat_boot_t fbs; + /** Used to access to a cached FAT32 boot sector. */ + fat32_boot_t fbs32; + /** Used to access to a cached FAT32 FSINFO sector. */ + fat32_fsinfo_t fsinfo; +}; +//------------------------------------------------------------------------------ +/** + * \class SdVolume + * \brief Access FAT16 and FAT32 volumes on SD and SDHC cards. + */ +class SdVolume { + public: + /** Create an instance of SdVolume */ + SdVolume() : fatType_(0) {} + /** Clear the cache and returns a pointer to the cache. Used by the WaveRP + * recorder to do raw write to the SD card. Not for normal apps. + * \return A pointer to the cache buffer or zero if an error occurs. + */ + cache_t* cacheClear() { + if (!cacheFlush()) return 0; + cacheBlockNumber_ = 0XFFFFFFFF; + return &cacheBuffer_; + } + /** Initialize a FAT volume. Try partition one first then try super + * floppy format. + * + * \param[in] dev The Sd2Card where the volume is located. + * + * \return The value one, true, is returned for success and + * the value zero, false, is returned for failure. Reasons for + * failure include not finding a valid partition, not finding a valid + * FAT file system or an I/O error. + */ + bool init(Sd2Card* dev) { return init(dev, 1) ? true : init(dev, 0);} + bool init(Sd2Card* dev, uint8_t part); + + // inline functions that return volume info + /** \return The volume's cluster size in blocks. */ + uint8_t blocksPerCluster() const {return blocksPerCluster_;} + /** \return The number of blocks in one FAT. */ + uint32_t blocksPerFat() const {return blocksPerFat_;} + /** \return The total number of clusters in the volume. */ + uint32_t clusterCount() const {return clusterCount_;} + /** \return The shift count required to multiply by blocksPerCluster. */ + uint8_t clusterSizeShift() const {return clusterSizeShift_;} + /** \return The logical block number for the start of file data. */ + uint32_t dataStartBlock() const {return dataStartBlock_;} + /** \return The number of FAT structures on the volume. */ + uint8_t fatCount() const {return fatCount_;} + /** \return The logical block number for the start of the first FAT. */ + uint32_t fatStartBlock() const {return fatStartBlock_;} + /** \return The FAT type of the volume. Values are 12, 16 or 32. */ + uint8_t fatType() const {return fatType_;} + int32_t freeClusterCount(); + /** \return The number of entries in the root directory for FAT16 volumes. */ + uint32_t rootDirEntryCount() const {return rootDirEntryCount_;} + /** \return The logical block number for the start of the root directory + on FAT16 volumes or the first cluster number on FAT32 volumes. */ + uint32_t rootDirStart() const {return rootDirStart_;} + /** Sd2Card object for this volume + * \return pointer to Sd2Card object. + */ + Sd2Card* sdCard() {return sdCard_;} + /** Debug access to FAT table + * + * \param[in] n cluster number. + * \param[out] v value of entry + * \return true for success or false for failure + */ + bool dbgFat(uint32_t n, uint32_t* v) {return fatGet(n, v);} +//------------------------------------------------------------------------------ + private: + // Allow SdBaseFile access to SdVolume private data. + friend class SdBaseFile; + + // value for dirty argument in cacheRawBlock to indicate read from cache + static bool const CACHE_FOR_READ = false; + // value for dirty argument in cacheRawBlock to indicate write to cache + static bool const CACHE_FOR_WRITE = true; + +#if USE_MULTIPLE_CARDS + cache_t cacheBuffer_; // 512 byte cache for device blocks + uint32_t cacheBlockNumber_; // Logical number of block in the cache + Sd2Card* sdCard_; // Sd2Card object for cache + bool cacheDirty_; // cacheFlush() will write block if true + uint32_t cacheMirrorBlock_; // block number for mirror FAT +#else // USE_MULTIPLE_CARDS + static cache_t cacheBuffer_; // 512 byte cache for device blocks + static uint32_t cacheBlockNumber_; // Logical number of block in the cache + static Sd2Card* sdCard_; // Sd2Card object for cache + static bool cacheDirty_; // cacheFlush() will write block if true + static uint32_t cacheMirrorBlock_; // block number for mirror FAT +#endif // USE_MULTIPLE_CARDS + uint32_t allocSearchStart_; // start cluster for alloc search + uint8_t blocksPerCluster_; // cluster size in blocks + uint32_t blocksPerFat_; // FAT size in blocks + uint32_t clusterCount_; // clusters in one FAT + uint8_t clusterSizeShift_; // shift to convert cluster count to block count + uint32_t dataStartBlock_; // first data block number + uint8_t fatCount_; // number of FATs on volume + uint32_t fatStartBlock_; // start block for first FAT + uint8_t fatType_; // volume type (12, 16, OR 32) + uint16_t rootDirEntryCount_; // number of entries in FAT16 root dir + uint32_t rootDirStart_; // root start block for FAT16, cluster for FAT32 + //---------------------------------------------------------------------------- + bool allocContiguous(uint32_t count, uint32_t* curCluster); + uint8_t blockOfCluster(uint32_t position) const { + return (position >> 9) & (blocksPerCluster_ - 1);} + uint32_t clusterStartBlock(uint32_t cluster) const { + return dataStartBlock_ + ((cluster - 2) << clusterSizeShift_);} + uint32_t blockNumber(uint32_t cluster, uint32_t position) const { + return clusterStartBlock(cluster) + blockOfCluster(position);} + cache_t *cache() {return &cacheBuffer_;} + uint32_t cacheBlockNumber() {return cacheBlockNumber_;} +#if USE_MULTIPLE_CARDS + bool cacheFlush(); + bool cacheRawBlock(uint32_t blockNumber, bool dirty); +#else // USE_MULTIPLE_CARDS + static bool cacheFlush(); + static bool cacheRawBlock(uint32_t blockNumber, bool dirty); +#endif // USE_MULTIPLE_CARDS + // used by SdBaseFile write to assign cache to SD location + void cacheSetBlockNumber(uint32_t blockNumber, bool dirty) { + cacheDirty_ = dirty; + cacheBlockNumber_ = blockNumber; + } + void cacheSetDirty() {cacheDirty_ |= CACHE_FOR_WRITE;} + bool chainSize(uint32_t beginCluster, uint32_t* size); + bool fatGet(uint32_t cluster, uint32_t* value); + bool fatPut(uint32_t cluster, uint32_t value); + bool fatPutEOC(uint32_t cluster) { + return fatPut(cluster, 0x0FFFFFFF); + } + bool freeChain(uint32_t cluster); + bool isEOC(uint32_t cluster) const { + if (FAT12_SUPPORT && fatType_ == 12) return cluster >= FAT12EOC_MIN; + if (fatType_ == 16) return cluster >= FAT16EOC_MIN; + return cluster >= FAT32EOC_MIN; + } + bool readBlock(uint32_t block, uint8_t* dst) { + return sdCard_->readBlock(block, dst);} + bool writeBlock(uint32_t block, const uint8_t* dst) { + return sdCard_->writeBlock(block, dst); + } +//------------------------------------------------------------------------------ + // Deprecated functions - suppress cpplint warnings with NOLINT comment +#if ALLOW_DEPRECATED_FUNCTIONS && !defined(DOXYGEN) + public: + /** \deprecated Use: bool SdVolume::init(Sd2Card* dev); + * \param[in] dev The SD card where the volume is located. + * \return true for success or false for failure. + */ + bool init(Sd2Card& dev) {return init(&dev);} // NOLINT + /** \deprecated Use: bool SdVolume::init(Sd2Card* dev, uint8_t vol); + * \param[in] dev The SD card where the volume is located. + * \param[in] part The partition to be used. + * \return true for success or false for failure. + */ + bool init(Sd2Card& dev, uint8_t part) { // NOLINT + return init(&dev, part); + } +#endif // ALLOW_DEPRECATED_FUNCTIONS +}; +#endif // SdVolume +#endif \ No newline at end of file diff --git a/Marlin/Servo.cpp b/Marlin/Servo.cpp new file mode 100644 index 0000000..27a7d3c --- /dev/null +++ b/Marlin/Servo.cpp @@ -0,0 +1,304 @@ +/* + Servo.cpp - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2 + Copyright (c) 2009 Michael Margolis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + + A servo is activated by creating an instance of the Servo class passing the desired pin to the attach() method. + The servos are pulsed in the background using the value most recently written using the write() method + + Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached. + Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four. + + The methods are: + + Servo - Class for manipulating servo motors connected to Arduino pins. + + attach(pin ) - Attaches a servo motor to an i/o pin. + attach(pin, min, max ) - Attaches to a pin setting min and max values in microseconds + default min is 544, max is 2400 + + write() - Sets the servo angle in degrees. (invalid angle that is valid as pulse in microseconds is treated as microseconds) + writeMicroseconds() - Sets the servo pulse width in microseconds + read() - Gets the last written servo pulse width as an angle between 0 and 180. + readMicroseconds() - Gets the last written servo pulse width in microseconds. (was read_us() in first release) + attached() - Returns true if there is a servo attached. + detach() - Stops an attached servos from pulsing its i/o pin. + +*/ +#include "Configuration.h" + +#ifdef NUM_SERVOS + +#include +#include + +#include "Servo.h" + +#define usToTicks(_us) (( clockCyclesPerMicrosecond()* _us) / 8) // converts microseconds to tick (assumes prescale of 8) // 12 Aug 2009 +#define ticksToUs(_ticks) (( (unsigned)_ticks * 8)/ clockCyclesPerMicrosecond() ) // converts from ticks back to microseconds + +#define TRIM_DURATION 2 // compensation ticks to trim adjust for digitalWrite delays // 12 August 2009 + +//#define NBR_TIMERS (MAX_SERVOS / SERVOS_PER_TIMER) + +static servo_t servos[MAX_SERVOS]; // static array of servo structures +static volatile int8_t Channel[_Nbr_16timers ]; // counter for the servo being pulsed for each timer (or -1 if refresh interval) + +uint8_t ServoCount = 0; // the total number of attached servos + + +// convenience macros +#define SERVO_INDEX_TO_TIMER(_servo_nbr) ((timer16_Sequence_t)(_servo_nbr / SERVOS_PER_TIMER)) // returns the timer controlling this servo +#define SERVO_INDEX_TO_CHANNEL(_servo_nbr) (_servo_nbr % SERVOS_PER_TIMER) // returns the index of the servo on this timer +#define SERVO_INDEX(_timer,_channel) ((_timer*SERVOS_PER_TIMER) + _channel) // macro to access servo index by timer and channel +#define SERVO(_timer,_channel) (servos[SERVO_INDEX(_timer,_channel)]) // macro to access servo class by timer and channel + +#define SERVO_MIN() (MIN_PULSE_WIDTH - this->min * 4) // minimum value in uS for this servo +#define SERVO_MAX() (MAX_PULSE_WIDTH - this->max * 4) // maximum value in uS for this servo + +/************ static functions common to all instances ***********************/ + +static inline void handle_interrupts(timer16_Sequence_t timer, volatile uint16_t *TCNTn, volatile uint16_t* OCRnA) { + if (Channel[timer] < 0) + *TCNTn = 0; // channel set to -1 indicated that refresh interval completed so reset the timer + else { + if (SERVO_INDEX(timer,Channel[timer]) < ServoCount && SERVO(timer,Channel[timer]).Pin.isActive) + digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,LOW); // pulse this channel low if activated + } + + Channel[timer]++; // increment to the next channel + if (SERVO_INDEX(timer,Channel[timer]) < ServoCount && Channel[timer] < SERVOS_PER_TIMER) { + *OCRnA = *TCNTn + SERVO(timer,Channel[timer]).ticks; + if (SERVO(timer,Channel[timer]).Pin.isActive) // check if activated + digitalWrite( SERVO(timer,Channel[timer]).Pin.nbr,HIGH); // its an active channel so pulse it high + } + else { + // finished all channels so wait for the refresh period to expire before starting over + if ( ((unsigned)*TCNTn) + 4 < usToTicks(REFRESH_INTERVAL) ) // allow a few ticks to ensure the next OCR1A not missed + *OCRnA = (unsigned int)usToTicks(REFRESH_INTERVAL); + else + *OCRnA = *TCNTn + 4; // at least REFRESH_INTERVAL has elapsed + Channel[timer] = -1; // this will get incremented at the end of the refresh period to start again at the first channel + } +} + +#ifndef WIRING // Wiring pre-defines signal handlers so don't define any if compiling for the Wiring platform + + // Interrupt handlers for Arduino + #if defined(_useTimer1) + SIGNAL (TIMER1_COMPA_vect) { handle_interrupts(_timer1, &TCNT1, &OCR1A); } + #endif + + #if defined(_useTimer3) + SIGNAL (TIMER3_COMPA_vect) { handle_interrupts(_timer3, &TCNT3, &OCR3A); } + #endif + + #if defined(_useTimer4) + SIGNAL (TIMER4_COMPA_vect) { handle_interrupts(_timer4, &TCNT4, &OCR4A); } + #endif + + #if defined(_useTimer5) + SIGNAL (TIMER5_COMPA_vect) { handle_interrupts(_timer5, &TCNT5, &OCR5A); } + #endif + +#else //!WIRING + + // Interrupt handlers for Wiring + #if defined(_useTimer1) + void Timer1Service() { handle_interrupts(_timer1, &TCNT1, &OCR1A); } + #endif + #if defined(_useTimer3) + void Timer3Service() { handle_interrupts(_timer3, &TCNT3, &OCR3A); } + #endif + +#endif //!WIRING + + +static void initISR(timer16_Sequence_t timer) { + #if defined(_useTimer1) + if (timer == _timer1) { + TCCR1A = 0; // normal counting mode + TCCR1B = _BV(CS11); // set prescaler of 8 + TCNT1 = 0; // clear the timer count + #if defined(__AVR_ATmega8__)|| defined(__AVR_ATmega128__) + TIFR |= _BV(OCF1A); // clear any pending interrupts; + TIMSK |= _BV(OCIE1A); // enable the output compare interrupt + #else + // here if not ATmega8 or ATmega128 + TIFR1 |= _BV(OCF1A); // clear any pending interrupts; + TIMSK1 |= _BV(OCIE1A); // enable the output compare interrupt + #endif + #if defined(WIRING) + timerAttach(TIMER1OUTCOMPAREA_INT, Timer1Service); + #endif + } + #endif + + #if defined(_useTimer3) + if (timer == _timer3) { + TCCR3A = 0; // normal counting mode + TCCR3B = _BV(CS31); // set prescaler of 8 + TCNT3 = 0; // clear the timer count + #if defined(__AVR_ATmega128__) + TIFR |= _BV(OCF3A); // clear any pending interrupts; + ETIMSK |= _BV(OCIE3A); // enable the output compare interrupt + #else + TIFR3 = _BV(OCF3A); // clear any pending interrupts; + TIMSK3 = _BV(OCIE3A) ; // enable the output compare interrupt + #endif + #if defined(WIRING) + timerAttach(TIMER3OUTCOMPAREA_INT, Timer3Service); // for Wiring platform only + #endif + } + #endif + + #if defined(_useTimer4) + if (timer == _timer4) { + TCCR4A = 0; // normal counting mode + TCCR4B = _BV(CS41); // set prescaler of 8 + TCNT4 = 0; // clear the timer count + TIFR4 = _BV(OCF4A); // clear any pending interrupts; + TIMSK4 = _BV(OCIE4A) ; // enable the output compare interrupt + } + #endif + + #if defined(_useTimer5) + if (timer == _timer5) { + TCCR5A = 0; // normal counting mode + TCCR5B = _BV(CS51); // set prescaler of 8 + TCNT5 = 0; // clear the timer count + TIFR5 = _BV(OCF5A); // clear any pending interrupts; + TIMSK5 = _BV(OCIE5A) ; // enable the output compare interrupt + } + #endif +} + +static void finISR(timer16_Sequence_t timer) { + // Disable use of the given timer + #if defined(WIRING) + if (timer == _timer1) { + #if defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__) + TIMSK1 + #else + TIMSK + #endif + &= ~_BV(OCIE1A); // disable timer 1 output compare interrupt + timerDetach(TIMER1OUTCOMPAREA_INT); + } + else if (timer == _timer3) { + #if defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__) + TIMSK3 + #else + ETIMSK + #endif + &= ~_BV(OCIE3A); // disable the timer3 output compare A interrupt + timerDetach(TIMER3OUTCOMPAREA_INT); + } + #else //!WIRING + // For arduino - in future: call here to a currently undefined function to reset the timer + #endif +} + +static boolean isTimerActive(timer16_Sequence_t timer) { + // returns true if any servo is active on this timer + for(uint8_t channel=0; channel < SERVOS_PER_TIMER; channel++) { + if (SERVO(timer,channel).Pin.isActive) + return true; + } + return false; +} + + +/****************** end of static functions ******************************/ + +Servo::Servo() { + if ( ServoCount < MAX_SERVOS) { + this->servoIndex = ServoCount++; // assign a servo index to this instance + servos[this->servoIndex].ticks = usToTicks(DEFAULT_PULSE_WIDTH); // store default values - 12 Aug 2009 + } + else + this->servoIndex = INVALID_SERVO; // too many servos +} + +uint8_t Servo::attach(int pin) { + return this->attach(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH); +} + +uint8_t Servo::attach(int pin, int min, int max) { + if (this->servoIndex < MAX_SERVOS ) { + #if defined(ENABLE_AUTO_BED_LEVELING) && (PROBE_SERVO_DEACTIVATION_DELAY > 0) + if (pin > 0) this->pin = pin; else pin = this->pin; + #endif + pinMode(pin, OUTPUT); // set servo pin to output + servos[this->servoIndex].Pin.nbr = pin; + // todo min/max check: abs(min - MIN_PULSE_WIDTH) /4 < 128 + this->min = (MIN_PULSE_WIDTH - min) / 4; //resolution of min/max is 4 uS + this->max = (MAX_PULSE_WIDTH - max) / 4; + // initialize the timer if it has not already been initialized + timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex); + if (!isTimerActive(timer)) initISR(timer); + servos[this->servoIndex].Pin.isActive = true; // this must be set after the check for isTimerActive + } + return this->servoIndex; +} + +void Servo::detach() { + servos[this->servoIndex].Pin.isActive = false; + timer16_Sequence_t timer = SERVO_INDEX_TO_TIMER(servoIndex); + if (!isTimerActive(timer)) finISR(timer); +} + +void Servo::write(int value) { + if (value < MIN_PULSE_WIDTH) { // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds) + if (value < 0) value = 0; + if (value > 180) value = 180; + value = map(value, 0, 180, SERVO_MIN(), SERVO_MAX()); + } + this->writeMicroseconds(value); +} + +void Servo::writeMicroseconds(int value) { + // calculate and store the values for the given channel + byte channel = this->servoIndex; + if (channel < MAX_SERVOS) { // ensure channel is valid + if (value < SERVO_MIN()) // ensure pulse width is valid + value = SERVO_MIN(); + else if (value > SERVO_MAX()) + value = SERVO_MAX(); + + value = value - TRIM_DURATION; + value = usToTicks(value); // convert to ticks after compensating for interrupt overhead - 12 Aug 2009 + + uint8_t oldSREG = SREG; + cli(); + servos[channel].ticks = value; + SREG = oldSREG; + } +} + +// return the value as degrees +int Servo::read() { return map( this->readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180); } + +int Servo::readMicroseconds() { + return (this->servoIndex == INVALID_SERVO) ? 0 : ticksToUs(servos[this->servoIndex].ticks) + TRIM_DURATION; +} + +bool Servo::attached() { return servos[this->servoIndex].Pin.isActive; } + +#endif diff --git a/Marlin/Servo.h b/Marlin/Servo.h new file mode 100644 index 0000000..682a3b3 --- /dev/null +++ b/Marlin/Servo.h @@ -0,0 +1,135 @@ +/* + Servo.h - Interrupt driven Servo library for Arduino using 16 bit timers- Version 2 + Copyright (c) 2009 Michael Margolis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +/* + + A servo is activated by creating an instance of the Servo class passing the desired pin to the attach() method. + The servos are pulsed in the background using the value most recently written using the write() method + + Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached. + Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four. + The sequence used to seize timers is defined in timers.h + + The methods are: + + Servo - Class for manipulating servo motors connected to Arduino pins. + + attach(pin ) - Attaches a servo motor to an i/o pin. + attach(pin, min, max ) - Attaches to a pin setting min and max values in microseconds + default min is 544, max is 2400 + + write() - Sets the servo angle in degrees. (invalid angle that is valid as pulse in microseconds is treated as microseconds) + writeMicroseconds() - Sets the servo pulse width in microseconds + read() - Gets the last written servo pulse width as an angle between 0 and 180. + readMicroseconds() - Gets the last written servo pulse width in microseconds. (was read_us() in first release) + attached() - Returns true if there is a servo attached. + detach() - Stops an attached servos from pulsing its i/o pin. + */ + +#ifndef Servo_h +#define Servo_h + +#include + +/* + * Defines for 16 bit timers used with Servo library + * + * If _useTimerX is defined then TimerX is a 16 bit timer on the current board + * timer16_Sequence_t enumerates the sequence that the timers should be allocated + * _Nbr_16timers indicates how many 16 bit timers are available. + * + */ + +// Say which 16 bit timers can be used and in what order +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + #define _useTimer5 + //#define _useTimer1 + #define _useTimer3 + #define _useTimer4 + //typedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers } timer16_Sequence_t ; + typedef enum { _timer5, _timer3, _timer4, _Nbr_16timers } timer16_Sequence_t ; + +#elif defined(__AVR_ATmega32U4__) + //#define _useTimer1 + #define _useTimer3 + //typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t ; + typedef enum { _timer3, _Nbr_16timers } timer16_Sequence_t ; + +#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) + #define _useTimer3 + //#define _useTimer1 + //typedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t ; + typedef enum { _timer3, _Nbr_16timers } timer16_Sequence_t ; + +#elif defined(__AVR_ATmega128__) ||defined(__AVR_ATmega1281__) || defined(__AVR_ATmega1284P__) ||defined(__AVR_ATmega2561__) + #define _useTimer3 + //#define _useTimer1 + //typedef enum { _timer3, _timer1, _Nbr_16timers } timer16_Sequence_t ; + typedef enum { _timer3, _Nbr_16timers } timer16_Sequence_t ; + +#else // everything else + //#define _useTimer1 + //typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t ; + typedef enum { _Nbr_16timers } timer16_Sequence_t ; + +#endif + +#define Servo_VERSION 2 // software version of this library + +#define MIN_PULSE_WIDTH 544 // the shortest pulse sent to a servo +#define MAX_PULSE_WIDTH 2400 // the longest pulse sent to a servo +#define DEFAULT_PULSE_WIDTH 1500 // default pulse width when servo is attached +#define REFRESH_INTERVAL 20000 // minimum time to refresh servos in microseconds + +#define SERVOS_PER_TIMER 12 // the maximum number of servos controlled by one timer +#define MAX_SERVOS (_Nbr_16timers * SERVOS_PER_TIMER) + +#define INVALID_SERVO 255 // flag indicating an invalid servo index + +typedef struct { + uint8_t nbr :6 ; // a pin number from 0 to 63 + uint8_t isActive :1 ; // true if this channel is enabled, pin not pulsed if false +} ServoPin_t; + +typedef struct { + ServoPin_t Pin; + unsigned int ticks; +} servo_t; + +class Servo { + public: + Servo(); + uint8_t attach(int pin); // attach the given pin to the next free channel, sets pinMode, returns channel number or 0 if failure + uint8_t attach(int pin, int min, int max); // as above but also sets min and max values for writes. + void detach(); + void write(int value); // if value is < 200 it is treated as an angle, otherwise as pulse width in microseconds + void writeMicroseconds(int value); // Write pulse width in microseconds + int read(); // returns current pulse width as an angle between 0 and 180 degrees + int readMicroseconds(); // returns current pulse width in microseconds for this servo (was read_us() in first release) + bool attached(); // return true if this servo is attached, otherwise false + #if defined(ENABLE_AUTO_BED_LEVELING) && PROBE_SERVO_DEACTIVATION_DELAY > 0 + int pin; // store the hardware pin of the servo + #endif + private: + uint8_t servoIndex; // index into the channel data for this servo + int8_t min; // minimum is this value times 4 added to MIN_PULSE_WIDTH + int8_t max; // maximum is this value times 4 added to MAX_PULSE_WIDTH +}; + +#endif diff --git a/Marlin/boards.h b/Marlin/boards.h new file mode 100644 index 0000000..8a60f01 --- /dev/null +++ b/Marlin/boards.h @@ -0,0 +1,62 @@ +#ifndef BOARDS_H +#define BOARDS_H + +#define BOARD_UNKNOWN -1 + +#define BOARD_GEN7_CUSTOM 10 // Gen7 custom (Alfons3 Version) "https://github.com/Alfons3/Generation_7_Electronics" +#define BOARD_GEN7_12 11 // Gen7 v1.1, v1.2 +#define BOARD_GEN7_13 12 // Gen7 v1.3 +#define BOARD_GEN7_14 13 // Gen7 v1.4 +#define BOARD_CHEAPTRONIC 2 // Cheaptronic v1.0 +#define BOARD_SETHI 20 // Sethi 3D_1 +#define BOARD_RAMPS_OLD 3 // MEGA/RAMPS up to 1.2 +#define BOARD_RAMPS_13_EFB 33 // RAMPS 1.3 / 1.4 (Power outputs: Extruder, Fan, Bed) +#define BOARD_RAMPS_13_EEB 34 // RAMPS 1.3 / 1.4 (Power outputs: Extruder0, Extruder1, Bed) +#define BOARD_RAMPS_13_EFF 35 // RAMPS 1.3 / 1.4 (Power outputs: Extruder, Fan, Fan) +#define BOARD_RAMPS_13_EEF 36 // RAMPS 1.3 / 1.4 (Power outputs: Extruder0, Extruder1, Fan) +#define BOARD_FELIX2 37 // Felix 2.0+ Electronics Board (RAMPS like) +#define BOARD_DUEMILANOVE_328P 4 // Duemilanove w/ ATMega328P pin assignments +#define BOARD_GEN6 5 // Gen6 +#define BOARD_GEN6_DELUXE 51 // Gen6 deluxe +#define BOARD_SANGUINOLOLU_11 6 // Sanguinololu < 1.2 +#define BOARD_SANGUINOLOLU_12 62 // Sanguinololu 1.2 and above +#define BOARD_MELZI 63 // Melzi +#define BOARD_STB_11 64 // STB V1.1 +#define BOARD_AZTEEG_X1 65 // Azteeg X1 +#define BOARD_MELZI_1284 66 // Melzi with ATmega1284 (MaKr3d version) +#define BOARD_AZTEEG_X3 67 // Azteeg X3 +#define BOARD_AZTEEG_X3_PRO 68 // Azteeg X3 Pro +#define BOARD_ULTIMAKER 7 // Ultimaker +#define BOARD_ULTIMAKER_OLD 71 // Ultimaker (Older electronics. Pre 1.5.4. This is rare) +#define BOARD_ULTIMAIN_2 72 // Ultimainboard 2.x (Uses TEMP_SENSOR 20) +#define BOARD_3DRAG 77 // 3Drag Controller +#define BOARD_K8200 78 // Vellemann K8200 Controller (derived from 3Drag Controller) +#define BOARD_TEENSYLU 8 // Teensylu +#define BOARD_RUMBA 80 // Rumba +#define BOARD_PRINTRBOARD 81 // Printrboard (AT90USB1286) +#define BOARD_BRAINWAVE 82 // Brainwave (AT90USB646) +#define BOARD_SAV_MKI 83 // SAV Mk-I (AT90USB1286) +#define BOARD_TEENSY2 84 // Teensy++2.0 (AT90USB1286) - CLI compile: DEFINES=AT90USBxx_TEENSYPP_ASSIGNMENTS HARDWARE_MOTHERBOARD=84 make +#define BOARD_BRAINWAVE_PRO 85 // Brainwave Pro (AT90USB1286) +#define BOARD_GEN3_PLUS 9 // Gen3+ +#define BOARD_GEN3_MONOLITHIC 22 // Gen3 Monolithic Electronics +#define BOARD_MEGATRONICS 70 // Megatronics +#define BOARD_MEGATRONICS_2 701 // Megatronics v2.0 +#define BOARD_MEGATRONICS_1 702 // Minitronics v1.0 +#define BOARD_MEGATRONICS_3 703 // Megatronics v3.0 +#define BOARD_OMCA_A 90 // Alpha OMCA board +#define BOARD_OMCA 91 // Final OMCA board +#define BOARD_RAMBO 301 // Rambo +#define BOARD_ELEFU_3 21 // Elefu Ra Board (v3) +#define BOARD_5DPRINT 88 // 5DPrint D8 Driver Board +#define BOARD_LEAPFROG 999 // Leapfrog +#define BOARD_WITBOX 41 // bq WITBOX +#define BOARD_HEPHESTOS 42 // bq Prusa i3 Hephestos +#define BOARD_BAM_DICE 401 // 2PrintBeta BAM&DICE with STK drivers +#define BOARD_BAM_DICE_DUE 402 // 2PrintBeta BAM&DICE Due with STK drivers + +#define BOARD_99 99 // This is in pins.h but...? + +#define MB(board) (MOTHERBOARD==BOARD_##board) + +#endif //__BOARDS_H diff --git a/Marlin/cardreader.cpp b/Marlin/cardreader.cpp new file mode 100644 index 0000000..639b4f2 --- /dev/null +++ b/Marlin/cardreader.cpp @@ -0,0 +1,517 @@ +#include "Marlin.h" +#include "cardreader.h" +#include "ultralcd.h" +#include "stepper.h" +#include "temperature.h" +#include "language.h" + +#ifdef SDSUPPORT + +CardReader::CardReader() { + filesize = 0; + sdpos = 0; + sdprinting = false; + cardOK = false; + saving = false; + logging = false; + workDirDepth = 0; + file_subcall_ctr = 0; + memset(workDirParents, 0, sizeof(workDirParents)); + + autostart_stilltocheck = true; //the SD start is delayed, because otherwise the serial cannot answer fast enough to make contact with the host software. + autostart_index = 0; + //power to SD reader + #if SDPOWER > -1 + OUT_WRITE(SDPOWER, HIGH); + #endif //SDPOWER + + next_autostart_ms = millis() + 5000; +} + +char *createFilename(char *buffer, const dir_t &p) { //buffer > 12characters + char *pos = buffer; + for (uint8_t i = 0; i < 11; i++) { + if (p.name[i] == ' ') continue; + if (i == 8) *pos++ = '.'; + *pos++ = p.name[i]; + } + *pos++ = 0; + return buffer; +} + +void CardReader::lsDive(const char *prepend, SdFile parent, const char * const match/*=NULL*/) { + dir_t p; + uint8_t cnt = 0; + + while (parent.readDir(p, longFilename) > 0) { + if (DIR_IS_SUBDIR(&p) && lsAction != LS_Count && lsAction != LS_GetFilename) { // hence LS_SerialPrint + char path[FILENAME_LENGTH*2]; + char lfilename[FILENAME_LENGTH]; + createFilename(lfilename, p); + + path[0] = 0; + if (prepend[0] == 0) strcat(path, "/"); //avoid leading / if already in prepend + strcat(path, prepend); + strcat(path, lfilename); + strcat(path, "/"); + + //Serial.print(path); + + SdFile dir; + if (!dir.open(parent, lfilename, O_READ)) { + if (lsAction == LS_SerialPrint) { + SERIAL_ECHO_START; + SERIAL_ECHOLN(MSG_SD_CANT_OPEN_SUBDIR); + SERIAL_ECHOLN(lfilename); + } + } + lsDive(path, dir); + //close done automatically by destructor of SdFile + } + else { + char pn0 = p.name[0]; + if (pn0 == DIR_NAME_FREE) break; + if (pn0 == DIR_NAME_DELETED || pn0 == '.') continue; + char lf0 = longFilename[0]; + if (lf0 == '.') continue; + + if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue; + + filenameIsDir = DIR_IS_SUBDIR(&p); + + if (!filenameIsDir && (p.name[8] != 'G' || p.name[9] == '~')) continue; + + //if (cnt++ != nr) continue; + createFilename(filename, p); + if (lsAction == LS_SerialPrint) { + SERIAL_PROTOCOL(prepend); + SERIAL_PROTOCOLLN(filename); + } + else if (lsAction == LS_Count) { + nrFiles++; + } + else if (lsAction == LS_GetFilename) { + if (match != NULL) { + if (strcasecmp(match, filename) == 0) return; + } + else if (cnt == nrFiles) return; + cnt++; + } + } + } +} + +void CardReader::ls() { + lsAction = LS_SerialPrint; + root.rewind(); + lsDive("", root); +} + +void CardReader::initsd() { + cardOK = false; + if (root.isOpen()) root.close(); + + #ifdef SDSLOW + #define SPI_SPEED SPI_HALF_SPEED + #else + #define SPI_SPEED SPI_FULL_SPEED + #endif + + if (!card.init(SPI_SPEED,SDSS) + #if defined(LCD_SDSS) && (LCD_SDSS != SDSS) + && !card.init(SPI_SPEED, LCD_SDSS) + #endif + ) { + //if (!card.init(SPI_HALF_SPEED,SDSS)) + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM(MSG_SD_INIT_FAIL); + } + else if (!volume.init(&card)) { + SERIAL_ERROR_START; + SERIAL_ERRORLNPGM(MSG_SD_VOL_INIT_FAIL); + } + else if (!root.openRoot(&volume)) { + SERIAL_ERROR_START; + SERIAL_ERRORLNPGM(MSG_SD_OPENROOT_FAIL); + } + else { + cardOK = true; + SERIAL_ECHO_START; + SERIAL_ECHOLNPGM(MSG_SD_CARD_OK); + } + workDir = root; + curDir = &root; + /* + if (!workDir.openRoot(&volume)) { + SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL); + } + */ +} + +void CardReader::setroot() { + /*if (!workDir.openRoot(&volume)) { + SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL); + }*/ + workDir = root; + curDir = &workDir; +} + +void CardReader::release() { + sdprinting = false; + cardOK = false; +} + +void CardReader::startFileprint() { + if (cardOK) { + sdprinting = true; + } +} + +void CardReader::pauseSDPrint() { + if (sdprinting) sdprinting = false; +} + +void CardReader::openLogFile(char* name) { + logging = true; + openFile(name, false); +} + +void CardReader::getAbsFilename(char *t) { + uint8_t cnt = 0; + *t = '/'; t++; cnt++; + for (uint8_t i = 0; i < workDirDepth; i++) { + workDirParents[i].getFilename(t); //SDBaseFile.getfilename! + while(*t && cnt < MAXPATHNAMELENGTH) { t++; cnt++; } //crawl counter forward. + } + if (cnt < MAXPATHNAMELENGTH - FILENAME_LENGTH) + file.getFilename(t); + else + t[0] = 0; +} + +void CardReader::openFile(char* name, bool read, bool replace_current/*=true*/) { + if (!cardOK) return; + if (file.isOpen()) { //replacing current file by new file, or subfile call + if (!replace_current) { + if (file_subcall_ctr > SD_PROCEDURE_DEPTH - 1) { + SERIAL_ERROR_START; + SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:"); + SERIAL_ERRORLN(SD_PROCEDURE_DEPTH); + kill(); + return; + } + + SERIAL_ECHO_START; + SERIAL_ECHOPGM("SUBROUTINE CALL target:\""); + SERIAL_ECHO(name); + SERIAL_ECHOPGM("\" parent:\""); + + //store current filename and position + getAbsFilename(filenames[file_subcall_ctr]); + + SERIAL_ECHO(filenames[file_subcall_ctr]); + SERIAL_ECHOPGM("\" pos"); + SERIAL_ECHOLN(sdpos); + filespos[file_subcall_ctr] = sdpos; + file_subcall_ctr++; + } + else { + SERIAL_ECHO_START; + SERIAL_ECHOPGM("Now doing file: "); + SERIAL_ECHOLN(name); + } + file.close(); + } + else { //opening fresh file + file_subcall_ctr = 0; //resetting procedure depth in case user cancels print while in procedure + SERIAL_ECHO_START; + SERIAL_ECHOPGM("Now fresh file: "); + SERIAL_ECHOLN(name); + } + sdprinting = false; + + SdFile myDir; + curDir = &root; + char *fname = name; + + char *dirname_start, *dirname_end; + if (name[0] == '/') { + dirname_start = &name[1]; + while(dirname_start > 0) { + dirname_end = strchr(dirname_start, '/'); + //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start - name)); + //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end - name)); + if (dirname_end > 0 && dirname_end > dirname_start) { + char subdirname[FILENAME_LENGTH]; + strncpy(subdirname, dirname_start, dirname_end - dirname_start); + subdirname[dirname_end - dirname_start] = 0; + SERIAL_ECHOLN(subdirname); + if (!myDir.open(curDir, subdirname, O_READ)) { + SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); + SERIAL_PROTOCOL(subdirname); + SERIAL_PROTOCOLCHAR('.'); + return; + } + else { + //SERIAL_ECHOLN("dive ok"); + } + + curDir = &myDir; + dirname_start = dirname_end + 1; + } + else { // the remainder after all /fsa/fdsa/ is the filename + fname = dirname_start; + //SERIAL_ECHOLN("remainder"); + //SERIAL_ECHOLN(fname); + break; + } + } + } + else { //relative path + curDir = &workDir; + } + + if (read) { + if (file.open(curDir, fname, O_READ)) { + filesize = file.fileSize(); + SERIAL_PROTOCOLPGM(MSG_SD_FILE_OPENED); + SERIAL_PROTOCOL(fname); + SERIAL_PROTOCOLPGM(MSG_SD_SIZE); + SERIAL_PROTOCOLLN(filesize); + sdpos = 0; + + SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED); + getfilename(0, fname); + lcd_setstatus(longFilename[0] ? longFilename : fname); + } + else { + SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); + SERIAL_PROTOCOL(fname); + SERIAL_PROTOCOLCHAR('.'); + } + } + else { //write + if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) { + SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); + SERIAL_PROTOCOL(fname); + SERIAL_PROTOCOLCHAR('.'); + } + else { + saving = true; + SERIAL_PROTOCOLPGM(MSG_SD_WRITE_TO_FILE); + SERIAL_PROTOCOLLN(name); + lcd_setstatus(fname); + } + } +} + +void CardReader::removeFile(char* name) { + if (!cardOK) return; + + file.close(); + sdprinting = false; + + SdFile myDir; + curDir = &root; + char *fname = name; + + char *dirname_start, *dirname_end; + if (name[0] == '/') { + dirname_start = strchr(name, '/') + 1; + while (dirname_start > 0) { + dirname_end = strchr(dirname_start, '/'); + //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start - name)); + //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end - name)); + if (dirname_end > 0 && dirname_end > dirname_start) { + char subdirname[FILENAME_LENGTH]; + strncpy(subdirname, dirname_start, dirname_end - dirname_start); + subdirname[dirname_end - dirname_start] = 0; + SERIAL_ECHOLN(subdirname); + if (!myDir.open(curDir, subdirname, O_READ)) { + SERIAL_PROTOCOLPGM("open failed, File: "); + SERIAL_PROTOCOL(subdirname); + SERIAL_PROTOCOLCHAR('.'); + return; + } + else { + //SERIAL_ECHOLN("dive ok"); + } + + curDir = &myDir; + dirname_start = dirname_end + 1; + } + else { // the remainder after all /fsa/fdsa/ is the filename + fname = dirname_start; + //SERIAL_ECHOLN("remainder"); + //SERIAL_ECHOLN(fname); + break; + } + } + } + else { // relative path + curDir = &workDir; + } + + if (file.remove(curDir, fname)) { + SERIAL_PROTOCOLPGM("File deleted:"); + SERIAL_PROTOCOLLN(fname); + sdpos = 0; + } + else { + SERIAL_PROTOCOLPGM("Deletion failed, File: "); + SERIAL_PROTOCOL(fname); + SERIAL_PROTOCOLCHAR('.'); + } +} + +void CardReader::getStatus() { + if (cardOK) { + SERIAL_PROTOCOLPGM(MSG_SD_PRINTING_BYTE); + SERIAL_PROTOCOL(sdpos); + SERIAL_PROTOCOLCHAR('/'); + SERIAL_PROTOCOLLN(filesize); + } + else { + SERIAL_PROTOCOLLNPGM(MSG_SD_NOT_PRINTING); + } +} + +void CardReader::write_command(char *buf) { + char* begin = buf; + char* npos = 0; + char* end = buf + strlen(buf) - 1; + + file.writeError = false; + if ((npos = strchr(buf, 'N')) != NULL) { + begin = strchr(npos, ' ') + 1; + end = strchr(npos, '*') - 1; + } + end[1] = '\r'; + end[2] = '\n'; + end[3] = '\0'; + file.write(begin); + if (file.writeError) { + SERIAL_ERROR_START; + SERIAL_ERRORLNPGM(MSG_SD_ERR_WRITE_TO_FILE); + } +} + +void CardReader::checkautostart(bool force) { + if (!force && (!autostart_stilltocheck || next_autostart_ms < millis())) + return; + + autostart_stilltocheck = false; + + if (!cardOK) { + initsd(); + if (!cardOK) return; // fail + } + + char autoname[30]; + sprintf_P(autoname, PSTR("auto%i.g"), autostart_index); + for (int8_t i = 0; i < (int8_t)strlen(autoname); i++) autoname[i] = tolower(autoname[i]); + + dir_t p; + + root.rewind(); + + bool found = false; + while (root.readDir(p, NULL) > 0) { + for (int8_t i = 0; i < (int8_t)strlen((char*)p.name); i++) p.name[i] = tolower(p.name[i]); + if (p.name[9] != '~' && strncmp((char*)p.name, autoname, 5) == 0) { + char cmd[30]; + sprintf_P(cmd, PSTR("M23 %s"), autoname); + enqueuecommand(cmd); + enqueuecommands_P(PSTR("M24")); + found = true; + } + } + if (!found) + autostart_index = -1; + else + autostart_index++; +} + +void CardReader::closefile(bool store_location) { + file.sync(); + file.close(); + saving = logging = false; + + if (store_location) { + //future: store printer state, filename and position for continuing a stopped print + // so one can unplug the printer and continue printing the next day. + } +} + +/** + * Get the name of a file in the current directory by index + */ +void CardReader::getfilename(uint16_t nr, const char * const match/*=NULL*/) { + curDir = &workDir; + lsAction = LS_GetFilename; + nrFiles = nr; + curDir->rewind(); + lsDive("", *curDir, match); +} + +uint16_t CardReader::getnrfilenames() { + curDir = &workDir; + lsAction = LS_Count; + nrFiles = 0; + curDir->rewind(); + lsDive("", *curDir); + //SERIAL_ECHOLN(nrFiles); + return nrFiles; +} + +void CardReader::chdir(const char * relpath) { + SdFile newfile; + SdFile *parent = &root; + + if (workDir.isOpen()) parent = &workDir; + + if (!newfile.open(*parent, relpath, O_READ)) { + SERIAL_ECHO_START; + SERIAL_ECHOPGM(MSG_SD_CANT_ENTER_SUBDIR); + SERIAL_ECHOLN(relpath); + } + else { + if (workDirDepth < MAX_DIR_DEPTH) { + ++workDirDepth; + for (int d = workDirDepth; d--;) workDirParents[d + 1] = workDirParents[d]; + workDirParents[0] = *parent; + } + workDir = newfile; + } +} + +void CardReader::updir() { + if (workDirDepth > 0) { + --workDirDepth; + workDir = workDirParents[0]; + for (uint16_t d = 0; d < workDirDepth; d++) + workDirParents[d] = workDirParents[d+1]; + } +} + +void CardReader::printingHasFinished() { + st_synchronize(); + if (file_subcall_ctr > 0) { // Heading up to a parent file that called current as a procedure. + file.close(); + file_subcall_ctr--; + openFile(filenames[file_subcall_ctr], true, true); + setIndex(filespos[file_subcall_ctr]); + startFileprint(); + } + else { + file.close(); + sdprinting = false; + if (SD_FINISHED_STEPPERRELEASE) { + //finishAndDisableSteppers(); + enqueuecommands_P(PSTR(SD_FINISHED_RELEASECOMMAND)); + } + autotempShutdown(); + } +} + +#endif //SDSUPPORT diff --git a/Marlin/cardreader.h b/Marlin/cardreader.h new file mode 100644 index 0000000..03d4303 --- /dev/null +++ b/Marlin/cardreader.h @@ -0,0 +1,97 @@ +#ifndef CARDREADER_H +#define CARDREADER_H + +#ifdef SDSUPPORT + +#define MAX_DIR_DEPTH 10 // Maximum folder depth + +#include "SdFile.h" +enum LsAction { LS_SerialPrint, LS_Count, LS_GetFilename }; + +class CardReader { +public: + CardReader(); + + void initsd(); + void write_command(char *buf); + //files auto[0-9].g on the sd card are performed in a row + //this is to delay autostart and hence the initialisaiton of the sd card to some seconds after the normal init, so the device is available quick after a reset + + void checkautostart(bool x); + void openFile(char* name,bool read,bool replace_current=true); + void openLogFile(char* name); + void removeFile(char* name); + void closefile(bool store_location=false); + void release(); + void startFileprint(); + void pauseSDPrint(); + void getStatus(); + void printingHasFinished(); + + void getfilename(uint16_t nr, const char* const match=NULL); + uint16_t getnrfilenames(); + + void getAbsFilename(char *t); + + void ls(); + void chdir(const char * relpath); + void updir(); + void setroot(); + + + FORCE_INLINE bool isFileOpen() { return file.isOpen(); } + FORCE_INLINE bool eof() { return sdpos >= filesize; } + FORCE_INLINE int16_t get() { sdpos = file.curPosition(); return (int16_t)file.read(); } + FORCE_INLINE void setIndex(long index) { sdpos = index; file.seekSet(index); } + FORCE_INLINE uint8_t percentDone() { return (isFileOpen() && filesize) ? sdpos / ((filesize + 99) / 100) : 0; } + FORCE_INLINE char* getWorkDirName() { workDir.getFilename(filename); return filename; } + +public: + bool saving, logging, sdprinting, cardOK, filenameIsDir; + char filename[FILENAME_LENGTH], longFilename[LONG_FILENAME_LENGTH]; + int autostart_index; +private: + SdFile root, *curDir, workDir, workDirParents[MAX_DIR_DEPTH]; + uint16_t workDirDepth; + Sd2Card card; + SdVolume volume; + SdFile file; + #define SD_PROCEDURE_DEPTH 1 + #define MAXPATHNAMELENGTH (FILENAME_LENGTH*MAX_DIR_DEPTH + MAX_DIR_DEPTH + 1) + uint8_t file_subcall_ctr; + uint32_t filespos[SD_PROCEDURE_DEPTH]; + char filenames[SD_PROCEDURE_DEPTH][MAXPATHNAMELENGTH]; + uint32_t filesize; + millis_t next_autostart_ms; + uint32_t sdpos; + + bool autostart_stilltocheck; //the sd start is delayed, because otherwise the serial cannot answer fast enought to make contact with the hostsoftware. + + LsAction lsAction; //stored for recursion. + uint16_t nrFiles; //counter for the files in the current directory and recycled as position counter for getting the nrFiles'th name in the directory. + char* diveDirName; + void lsDive(const char *prepend, SdFile parent, const char * const match=NULL); +}; + +extern CardReader card; + +#define IS_SD_PRINTING (card.sdprinting) + +#if (SDCARDDETECT > -1) + #ifdef SDCARDDETECTINVERTED + #define IS_SD_INSERTED (READ(SDCARDDETECT) != 0) + #else + #define IS_SD_INSERTED (READ(SDCARDDETECT) == 0) + #endif +#else + //No card detect line? Assume the card is inserted. + #define IS_SD_INSERTED true +#endif + +#else + +#define IS_SD_PRINTING (false) + +#endif //SDSUPPORT + +#endif //__CARDREADER_H diff --git a/Marlin/configurator/config/Configuration.h b/Marlin/configurator/config/Configuration.h new file mode 100644 index 0000000..2b2175c --- /dev/null +++ b/Marlin/configurator/config/Configuration.h @@ -0,0 +1,816 @@ +#ifndef CONFIGURATION_H +#define CONFIGURATION_H + +#include "boards.h" + +//=========================================================================== +//============================= Getting Started ============================= +//=========================================================================== +/* +Here are some standard links for getting your machine calibrated: + * http://reprap.org/wiki/Calibration + * http://youtu.be/wAL9d7FgInk + * http://calculator.josefprusa.cz + * http://reprap.org/wiki/Triffid_Hunter%27s_Calibration_Guide + * http://www.thingiverse.com/thing:5573 + * https://sites.google.com/site/repraplogphase/calibration-of-your-reprap + * http://www.thingiverse.com/thing:298812 +*/ + +// This configuration file contains the basic settings. +// Advanced settings can be found in Configuration_adv.h +// BASIC SETTINGS: select your board type, temperature sensor type, axis scaling, and endstop configuration + +//=========================================================================== +//============================= DELTA Printer =============================== +//=========================================================================== +// For a Delta printer replace the configuration files with the files in the +// example_configurations/delta directory. +// + +//=========================================================================== +//============================= SCARA Printer =============================== +//=========================================================================== +// For a Scara printer replace the configuration files with the files in the +// example_configurations/SCARA directory. +// + +// @section info + +// User-specified version info of this build to display in [Pronterface, etc] terminal window during +// startup. Implementation of an idea by Prof Braino to inform user that any changes made to this +// build by the user have been successfully uploaded into firmware. +#define STRING_VERSION "1.0.3 dev" +#define STRING_URL "reprap.org" +#define STRING_VERSION_CONFIG_H __DATE__ " " __TIME__ // build date and time +#define STRING_CONFIG_H_AUTHOR "(none, default config)" // Who made the changes. +#define STRING_SPLASH_LINE1 "v" STRING_VERSION // will be shown during bootup in line 1 +//#define STRING_SPLASH_LINE2 STRING_VERSION_CONFIG_H // will be shown during bootup in line2 + +// @section machine + +// SERIAL_PORT selects which serial port should be used for communication with the host. +// This allows the connection of wireless adapters (for instance) to non-default port pins. +// Serial port 0 is still used by the Arduino bootloader regardless of this setting. +// :[0,1,2,3,4,5,6,7] +#define SERIAL_PORT 0 + +// This determines the communication speed of the printer +// :[2400,9600,19200,38400,57600,115200,250000] +#define BAUDRATE 250000 + +// This enables the serial port associated to the Bluetooth interface +//#define BTENABLED // Enable BT interface on AT90USB devices + +// The following define selects which electronics board you have. +// Please choose the name from boards.h that matches your setup +#ifndef MOTHERBOARD + #define MOTHERBOARD BOARD_RAMPS_13_EFB +#endif + +// Optional custom name for your RepStrap or other custom machine +// Displayed in the LCD "Ready" message +// #define CUSTOM_MACHINE_NAME "3D Printer" + +// Define this to set a unique identifier for this printer, (Used by some programs to differentiate between machines) +// You can use an online service to generate a random UUID. (eg http://www.uuidgenerator.net/version4) +// #define MACHINE_UUID "00000000-0000-0000-0000-000000000000" + +// This defines the number of extruders +// :[1,2,3,4] +#define EXTRUDERS 1 + +// Offset of the extruders (uncomment if using more than one and relying on firmware to position when changing). +// The offset has to be X=0, Y=0 for the extruder 0 hotend (default extruder). +// For the other hotends it is their distance from the extruder 0 hotend. +//#define EXTRUDER_OFFSET_X {0.0, 20.00} // (in mm) for each extruder, offset of the hotend on the X axis +//#define EXTRUDER_OFFSET_Y {0.0, 5.00} // (in mm) for each extruder, offset of the hotend on the Y axis + +//// The following define selects which power supply you have. Please choose the one that matches your setup +// 1 = ATX +// 2 = X-Box 360 203Watts (the blue wire connected to PS_ON and the red wire to VCC) +// :{1:'ATX',2:'X-Box 360'} + +#define POWER_SUPPLY 1 + +// Define this to have the electronics keep the power supply off on startup. If you don't know what this is leave it. +// #define PS_DEFAULT_OFF + +// @section temperature + +//=========================================================================== +//============================= Thermal Settings ============================ +//=========================================================================== +// +//--NORMAL IS 4.7kohm PULLUP!-- 1kohm pullup can be used on hotend sensor, using correct resistor and table +// +//// Temperature sensor settings: +// -2 is thermocouple with MAX6675 (only for sensor 0) +// -1 is thermocouple with AD595 +// 0 is not used +// 1 is 100k thermistor - best choice for EPCOS 100k (4.7k pullup) +// 2 is 200k thermistor - ATC Semitec 204GT-2 (4.7k pullup) +// 3 is Mendel-parts thermistor (4.7k pullup) +// 4 is 10k thermistor !! do not use it for a hotend. It gives bad resolution at high temp. !! +// 5 is 100K thermistor - ATC Semitec 104GT-2 (Used in ParCan & J-Head) (4.7k pullup) +// 6 is 100k EPCOS - Not as accurate as table 1 (created using a fluke thermocouple) (4.7k pullup) +// 7 is 100k Honeywell thermistor 135-104LAG-J01 (4.7k pullup) +// 71 is 100k Honeywell thermistor 135-104LAF-J01 (4.7k pullup) +// 8 is 100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) +// 9 is 100k GE Sensing AL03006-58.2K-97-G1 (4.7k pullup) +// 10 is 100k RS thermistor 198-961 (4.7k pullup) +// 11 is 100k beta 3950 1% thermistor (4.7k pullup) +// 12 is 100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) (calibrated for Makibox hot bed) +// 13 is 100k Hisens 3950 1% up to 300°C for hotend "Simple ONE " & "Hotend "All In ONE" +// 20 is the PT100 circuit found in the Ultimainboard V2.x +// 60 is 100k Maker's Tool Works Kapton Bed Thermistor beta=3950 +// +// 1k ohm pullup tables - This is not normal, you would have to have changed out your 4.7k for 1k +// (but gives greater accuracy and more stable PID) +// 51 is 100k thermistor - EPCOS (1k pullup) +// 52 is 200k thermistor - ATC Semitec 204GT-2 (1k pullup) +// 55 is 100k thermistor - ATC Semitec 104GT-2 (Used in ParCan & J-Head) (1k pullup) +// +// 1047 is Pt1000 with 4k7 pullup +// 1010 is Pt1000 with 1k pullup (non standard) +// 147 is Pt100 with 4k7 pullup +// 110 is Pt100 with 1k pullup (non standard) +// 998 and 999 are Dummy Tables. They will ALWAYS read 25°C or the temperature defined below. +// Use it for Testing or Development purposes. NEVER for production machine. +// #define DUMMY_THERMISTOR_998_VALUE 25 +// #define DUMMY_THERMISTOR_999_VALUE 100 +// :{ '0': "Not used", '4': "10k !! do not use for a hotend. Bad resolution at high temp. !!", '1': "100k / 4.7k - EPCOS", '51': "100k / 1k - EPCOS", '6': "100k / 4.7k EPCOS - Not as accurate as Table 1", '5': "100K / 4.7k - ATC Semitec 104GT-2 (Used in ParCan & J-Head)", '7': "100k / 4.7k Honeywell 135-104LAG-J01", '71': "100k / 4.7k Honeywell 135-104LAF-J01", '8': "100k / 4.7k 0603 SMD Vishay NTCS0603E3104FXT", '9': "100k / 4.7k GE Sensing AL03006-58.2K-97-G1", '10': "100k / 4.7k RS 198-961", '11': "100k / 4.7k beta 3950 1%", '12': "100k / 4.7k 0603 SMD Vishay NTCS0603E3104FXT (calibrated for Makibox hot bed)", '13': "100k Hisens 3950 1% up to 300°C for hotend 'Simple ONE ' & hotend 'All In ONE'", '60': "100k Maker's Tool Works Kapton Bed Thermistor beta=3950", '55': "100k / 1k - ATC Semitec 104GT-2 (Used in ParCan & J-Head)", '2': "200k / 4.7k - ATC Semitec 204GT-2", '52': "200k / 1k - ATC Semitec 204GT-2", '-2': "Thermocouple + MAX6675 (only for sensor 0)", '-1': "Thermocouple + AD595", '3': "Mendel-parts / 4.7k", '1047': "Pt1000 / 4.7k", '1010': "Pt1000 / 1k (non standard)", '20': "PT100 (Ultimainboard V2.x)", '147': "Pt100 / 4.7k", '110': "Pt100 / 1k (non-standard)", '998': "Dummy 1", '999': "Dummy 2" } +#define TEMP_SENSOR_0 1 +#define TEMP_SENSOR_1 0 +#define TEMP_SENSOR_2 0 +#define TEMP_SENSOR_3 0 +#define TEMP_SENSOR_BED 0 + +// This makes temp sensor 1 a redundant sensor for sensor 0. If the temperatures difference between these sensors is to high the print will be aborted. +//#define TEMP_SENSOR_1_AS_REDUNDANT +#define MAX_REDUNDANT_TEMP_SENSOR_DIFF 10 + +// Actual temperature must be close to target for this long before M109 returns success +#define TEMP_RESIDENCY_TIME 10 // (seconds) +#define TEMP_HYSTERESIS 3 // (degC) range of +/- temperatures considered "close" to the target one +#define TEMP_WINDOW 1 // (degC) Window around target to start the residency timer x degC early. + +// The minimal temperature defines the temperature below which the heater will not be enabled It is used +// to check that the wiring to the thermistor is not broken. +// Otherwise this would lead to the heater being powered on all the time. +#define HEATER_0_MINTEMP 5 +#define HEATER_1_MINTEMP 5 +#define HEATER_2_MINTEMP 5 +#define HEATER_3_MINTEMP 5 +#define BED_MINTEMP 5 + +// When temperature exceeds max temp, your heater will be switched off. +// This feature exists to protect your hotend from overheating accidentally, but *NOT* from thermistor short/failure! +// You should use MINTEMP for thermistor short/failure protection. +#define HEATER_0_MAXTEMP 275 +#define HEATER_1_MAXTEMP 275 +#define HEATER_2_MAXTEMP 275 +#define HEATER_3_MAXTEMP 275 +#define BED_MAXTEMP 150 + +// If your bed has low resistance e.g. .6 ohm and throws the fuse you can duty cycle it to reduce the +// average current. The value should be an integer and the heat bed will be turned on for 1 interval of +// HEATER_BED_DUTY_CYCLE_DIVIDER intervals. +//#define HEATER_BED_DUTY_CYCLE_DIVIDER 4 + +// If you want the M105 heater power reported in watts, define the BED_WATTS, and (shared for all extruders) EXTRUDER_WATTS +//#define EXTRUDER_WATTS (12.0*12.0/6.7) // P=I^2/R +//#define BED_WATTS (12.0*12.0/1.1) // P=I^2/R + +//=========================================================================== +//============================= PID Settings ================================ +//=========================================================================== +// PID Tuning Guide here: http://reprap.org/wiki/PID_Tuning + +// Comment the following line to disable PID and enable bang-bang. +#define PIDTEMP +#define BANG_MAX 255 // limits current to nozzle while in bang-bang mode; 255=full current +#define PID_MAX BANG_MAX // limits current to nozzle while PID is active (see PID_FUNCTIONAL_RANGE below); 255=full current +#ifdef PIDTEMP + //#define PID_DEBUG // Sends debug data to the serial port. + //#define PID_OPENLOOP 1 // Puts PID in open loop. M104/M140 sets the output power from 0 to PID_MAX + //#define SLOW_PWM_HEATERS // PWM with very low frequency (roughly 0.125Hz=8s) and minimum state time of approximately 1s useful for heaters driven by a relay + //#define PID_PARAMS_PER_EXTRUDER // Uses separate PID parameters for each extruder (useful for mismatched extruders) + // Set/get with gcode: M301 E[extruder number, 0-2] + #define PID_FUNCTIONAL_RANGE 10 // If the temperature difference between the target temperature and the actual temperature + // is more then PID_FUNCTIONAL_RANGE then the PID will be shut off and the heater will be set to min/max. + #define PID_INTEGRAL_DRIVE_MAX PID_MAX //limit for the integral term + #define K1 0.95 //smoothing factor within the PID + +// If you are using a pre-configured hotend then you can use one of the value sets by uncommenting it +// Ultimaker + #define DEFAULT_Kp 22.2 + #define DEFAULT_Ki 1.08 + #define DEFAULT_Kd 114 + +// MakerGear +// #define DEFAULT_Kp 7.0 +// #define DEFAULT_Ki 0.1 +// #define DEFAULT_Kd 12 + +// Mendel Parts V9 on 12V +// #define DEFAULT_Kp 63.0 +// #define DEFAULT_Ki 2.25 +// #define DEFAULT_Kd 440 +#endif // PIDTEMP + +//=========================================================================== +//============================= PID > Bed Temperature Control =============== +//=========================================================================== +// Select PID or bang-bang with PIDTEMPBED. If bang-bang, BED_LIMIT_SWITCHING will enable hysteresis +// +// Uncomment this to enable PID on the bed. It uses the same frequency PWM as the extruder. +// If your PID_dT is the default, and correct for your hardware/configuration, that means 7.689Hz, +// which is fine for driving a square wave into a resistive load and does not significantly impact you FET heating. +// This also works fine on a Fotek SSR-10DA Solid State Relay into a 250W heater. +// If your configuration is significantly different than this and you don't understand the issues involved, you probably +// shouldn't use bed PID until someone else verifies your hardware works. +// If this is enabled, find your own PID constants below. +//#define PIDTEMPBED +// +//#define BED_LIMIT_SWITCHING + +// This sets the max power delivered to the bed, and replaces the HEATER_BED_DUTY_CYCLE_DIVIDER option. +// all forms of bed control obey this (PID, bang-bang, bang-bang with hysteresis) +// setting this to anything other than 255 enables a form of PWM to the bed just like HEATER_BED_DUTY_CYCLE_DIVIDER did, +// so you shouldn't use it unless you are OK with PWM on your bed. (see the comment on enabling PIDTEMPBED) +#define MAX_BED_POWER 255 // limits duty cycle to bed; 255=full current + +//#define PID_BED_DEBUG // Sends debug data to the serial port. + +#ifdef PIDTEMPBED +//120v 250W silicone heater into 4mm borosilicate (MendelMax 1.5+) +//from FOPDT model - kp=.39 Tp=405 Tdead=66, Tc set to 79.2, aggressive factor of .15 (vs .1, 1, 10) + #define DEFAULT_bedKp 10.00 + #define DEFAULT_bedKi .023 + #define DEFAULT_bedKd 305.4 + +//120v 250W silicone heater into 4mm borosilicate (MendelMax 1.5+) +//from pidautotune +// #define DEFAULT_bedKp 97.1 +// #define DEFAULT_bedKi 1.41 +// #define DEFAULT_bedKd 1675.16 + +// FIND YOUR OWN: "M303 E-1 C8 S90" to run autotune on the bed at 90 degreesC for 8 cycles. +#endif // PIDTEMPBED + +// @section extruder + +//this prevents dangerous Extruder moves, i.e. if the temperature is under the limit +//can be software-disabled for whatever purposes by +#define PREVENT_DANGEROUS_EXTRUDE +//if PREVENT_DANGEROUS_EXTRUDE is on, you can still disable (uncomment) very long bits of extrusion separately. +#define PREVENT_LENGTHY_EXTRUDE + +#define EXTRUDE_MINTEMP 170 +#define EXTRUDE_MAXLENGTH (X_MAX_LENGTH+Y_MAX_LENGTH) //prevent extrusion of very large distances. + +//=========================================================================== +//============================= Thermal Runaway Protection ================== +//=========================================================================== +/* +This is a feature to protect your printer from burn up in flames if it has +a thermistor coming off place (this happened to a friend of mine recently and +motivated me writing this feature). + +The issue: If a thermistor come off, it will read a lower temperature than actual. +The system will turn the heater on forever, burning up the filament and anything +else around. + +After the temperature reaches the target for the first time, this feature will +start measuring for how long the current temperature stays below the target +minus _HYSTERESIS (set_temperature - THERMAL_RUNAWAY_PROTECTION_HYSTERESIS). + +If it stays longer than _PERIOD, it means the thermistor temperature +cannot catch up with the target, so something *may be* wrong. Then, to be on the +safe side, the system will he halt. + +Bear in mind the count down will just start AFTER the first time the +thermistor temperature is over the target, so you will have no problem if +your extruder heater takes 2 minutes to hit the target on heating. + +*/ +// If you want to enable this feature for all your extruder heaters, +// uncomment the 2 defines below: + +// Parameters for all extruder heaters +//#define THERMAL_RUNAWAY_PROTECTION_PERIOD 40 //in seconds +//#define THERMAL_RUNAWAY_PROTECTION_HYSTERESIS 4 // in degree Celsius + +// If you want to enable this feature for your bed heater, +// uncomment the 2 defines below: + +// Parameters for the bed heater +//#define THERMAL_RUNAWAY_PROTECTION_BED_PERIOD 20 //in seconds +//#define THERMAL_RUNAWAY_PROTECTION_BED_HYSTERESIS 2 // in degree Celsius + + +//=========================================================================== +//============================= Mechanical Settings ========================= +//=========================================================================== + +// @section machine + +// Uncomment this option to enable CoreXY kinematics +// #define COREXY + +// Enable this option for Toshiba steppers +// #define CONFIG_STEPPERS_TOSHIBA + +// @section homing + +// coarse Endstop Settings +#define ENDSTOPPULLUPS // Comment this out (using // at the start of the line) to disable the endstop pullup resistors + +#ifndef ENDSTOPPULLUPS + // fine endstop settings: Individual pullups. will be ignored if ENDSTOPPULLUPS is defined + // #define ENDSTOPPULLUP_XMAX + // #define ENDSTOPPULLUP_YMAX + // #define ENDSTOPPULLUP_ZMAX + // #define ENDSTOPPULLUP_XMIN + // #define ENDSTOPPULLUP_YMIN + // #define ENDSTOPPULLUP_ZMIN + // #define ENDSTOPPULLUP_ZPROBE +#endif + +// Mechanical endstop with COM to ground and NC to Signal uses "false" here (most common setup). +const bool X_MIN_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Y_MIN_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Z_MIN_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool X_MAX_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Y_MAX_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Z_MAX_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +const bool Z_PROBE_ENDSTOP_INVERTING = false; // set to true to invert the logic of the endstop. +//#define DISABLE_MAX_ENDSTOPS +//#define DISABLE_MIN_ENDSTOPS + +// @section machine +// If you want to enable the Z Probe pin, but disable its use, uncomment the line below. +// This only affects a Z Probe Endstop if you have separate Z min endstop as well and have +// activated Z_PROBE_ENDSTOP below. If you are using the Z Min endstop on your Z Probe, +// this has no effect. +//#define DISABLE_Z_PROBE_ENDSTOP + +// For Inverting Stepper Enable Pins (Active Low) use 0, Non Inverting (Active High) use 1 +// :{0:'Low',1:'High'} +#define X_ENABLE_ON 0 +#define Y_ENABLE_ON 0 +#define Z_ENABLE_ON 0 +#define E_ENABLE_ON 0 // For all extruders + +// Disables axis when it's not being used. +#define DISABLE_X false +#define DISABLE_Y false +#define DISABLE_Z false + +// @section extruder + +#define DISABLE_E false // For all extruders +#define DISABLE_INACTIVE_EXTRUDER true //disable only inactive extruders and keep active extruder enabled + +// @section machine + +// Invert the stepper direction. Change (or reverse the motor connector) if an axis goes the wrong way. +#define INVERT_X_DIR false +#define INVERT_Y_DIR false +#define INVERT_Z_DIR false + +// @section extruder + +// For direct drive extruder v9 set to true, for geared extruder set to false. +#define INVERT_E0_DIR false +#define INVERT_E1_DIR false +#define INVERT_E2_DIR false +#define INVERT_E3_DIR false + +// @section homing + +// ENDSTOP SETTINGS: +// Sets direction of endstops when homing; 1=MAX, -1=MIN +// :[-1,1] +#define X_HOME_DIR -1 +#define Y_HOME_DIR -1 +#define Z_HOME_DIR -1 + +#define min_software_endstops true // If true, axis won't move to coordinates less than HOME_POS. +#define max_software_endstops true // If true, axis won't move to coordinates greater than the defined lengths below. + +// @section machine + +// Travel limits after homing (units are in mm) +#define X_MIN_POS 0 +#define Y_MIN_POS 0 +#define Z_MIN_POS 0 +#define X_MAX_POS 200 +#define Y_MAX_POS 200 +#define Z_MAX_POS 200 + +//=========================================================================== +//============================= Filament Runout Sensor ====================== +//=========================================================================== +//#define FILAMENT_RUNOUT_SENSOR // Uncomment for defining a filament runout sensor such as a mechanical or opto endstop to check the existence of filament + // In RAMPS uses servo pin 2. Can be changed in pins file. For other boards pin definition should be made. + // It is assumed that when logic high = filament available + // when logic low = filament ran out +//const bool FIL_RUNOUT_INVERTING = true; // Should be uncommented and true or false should assigned +//#define ENDSTOPPULLUP_FIL_RUNOUT // Uncomment to use internal pullup for filament runout pins if the sensor is defined. + +//=========================================================================== +//============================ Manual Bed Leveling ========================== +//=========================================================================== + +// #define MANUAL_BED_LEVELING // Add display menu option for bed leveling +// #define MESH_BED_LEVELING // Enable mesh bed leveling + +#ifdef MANUAL_BED_LEVELING + #define MBL_Z_STEP 0.025 +#endif // MANUAL_BED_LEVELING + +#ifdef MESH_BED_LEVELING + #define MESH_MIN_X 10 + #define MESH_MAX_X (X_MAX_POS - MESH_MIN_X) + #define MESH_MIN_Y 10 + #define MESH_MAX_Y (Y_MAX_POS - MESH_MIN_Y) + #define MESH_NUM_X_POINTS 3 // Don't use more than 7 points per axis, implementation limited + #define MESH_NUM_Y_POINTS 3 + #define MESH_HOME_SEARCH_Z 4 // Z after Home, bed somewhere below but above 0.0 +#endif // MESH_BED_LEVELING + +//=========================================================================== +//============================= Bed Auto Leveling =========================== +//=========================================================================== + +// @section bedlevel + +//#define ENABLE_AUTO_BED_LEVELING // Delete the comment to enable (remove // at the start of the line) +#define Z_PROBE_REPEATABILITY_TEST // If not commented out, Z-Probe Repeatability test will be included if Auto Bed Leveling is Enabled. + +#ifdef ENABLE_AUTO_BED_LEVELING + + // There are 2 different ways to specify probing locations + // + // - "grid" mode + // Probe several points in a rectangular grid. + // You specify the rectangle and the density of sample points. + // This mode is preferred because there are more measurements. + // + // - "3-point" mode + // Probe 3 arbitrary points on the bed (that aren't colinear) + // You specify the XY coordinates of all 3 points. + + // Enable this to sample the bed in a grid (least squares solution) + // Note: this feature generates 10KB extra code size + #define AUTO_BED_LEVELING_GRID + + #ifdef AUTO_BED_LEVELING_GRID + + #define LEFT_PROBE_BED_POSITION 15 + #define RIGHT_PROBE_BED_POSITION 170 + #define FRONT_PROBE_BED_POSITION 20 + #define BACK_PROBE_BED_POSITION 170 + + #define MIN_PROBE_EDGE 10 // The probe square sides can be no smaller than this + + // Set the number of grid points per dimension + // You probably don't need more than 3 (squared=9) + #define AUTO_BED_LEVELING_GRID_POINTS 2 + + #else // !AUTO_BED_LEVELING_GRID + + // Arbitrary points to probe. A simple cross-product + // is used to estimate the plane of the bed. + #define ABL_PROBE_PT_1_X 15 + #define ABL_PROBE_PT_1_Y 180 + #define ABL_PROBE_PT_2_X 15 + #define ABL_PROBE_PT_2_Y 20 + #define ABL_PROBE_PT_3_X 170 + #define ABL_PROBE_PT_3_Y 20 + + #endif // AUTO_BED_LEVELING_GRID + + // Offsets to the probe relative to the extruder tip (Hotend - Probe) + // X and Y offsets must be integers + #define X_PROBE_OFFSET_FROM_EXTRUDER -25 // Probe on: -left +right + #define Y_PROBE_OFFSET_FROM_EXTRUDER -29 // Probe on: -front +behind + #define Z_PROBE_OFFSET_FROM_EXTRUDER -12.35 // -below (always!) + + #define Z_RAISE_BEFORE_HOMING 4 // (in mm) Raise Z before homing (G28) for Probe Clearance. + // Be sure you have this distance over your Z_MAX_POS in case + + #define XY_TRAVEL_SPEED 8000 // X and Y axis travel speed between probes, in mm/min + + #define Z_RAISE_BEFORE_PROBING 15 //How much the extruder will be raised before traveling to the first probing point. + #define Z_RAISE_BETWEEN_PROBINGS 5 //How much the extruder will be raised when traveling from between next probing points + #define Z_RAISE_AFTER_PROBING 15 //How much the extruder will be raised after the last probing point. + +// #define Z_PROBE_END_SCRIPT "G1 Z10 F12000\nG1 X15 Y330\nG1 Z0.5\nG1 Z10" //These commands will be executed in the end of G29 routine. + //Useful to retract a deployable probe. + + //#define Z_PROBE_SLED // turn on if you have a z-probe mounted on a sled like those designed by Charles Bell + //#define SLED_DOCKING_OFFSET 5 // the extra distance the X axis must travel to pickup the sled. 0 should be fine but you can push it further if you'd like. + + //If defined, the Probe servo will be turned on only during movement and then turned off to avoid jerk + //The value is the delay to turn the servo off after powered on - depends on the servo speed; 300ms is good value, but you can try lower it. + // You MUST HAVE the SERVO_ENDSTOPS defined to use here a value higher than zero otherwise your code will not compile. + +// #define PROBE_SERVO_DEACTIVATION_DELAY 300 + + +//If you have enabled the Bed Auto Leveling and are using the same Z Probe for Z Homing, +//it is highly recommended you let this Z_SAFE_HOMING enabled!!! + + #define Z_SAFE_HOMING // This feature is meant to avoid Z homing with probe outside the bed area. + // When defined, it will: + // - Allow Z homing only after X and Y homing AND stepper drivers still enabled + // - If stepper drivers timeout, it will need X and Y homing again before Z homing + // - Position the probe in a defined XY point before Z Homing when homing all axis (G28) + // - Block Z homing only when the probe is outside bed area. + + #ifdef Z_SAFE_HOMING + + #define Z_SAFE_HOMING_X_POINT (X_MAX_LENGTH/2) // X point for Z homing when homing all axis (G28) + #define Z_SAFE_HOMING_Y_POINT (Y_MAX_LENGTH/2) // Y point for Z homing when homing all axis (G28) + + #endif + + // Support for a dedicated Z PROBE endstop separate from the Z MIN endstop. + // If you would like to use both a Z PROBE and a Z MIN endstop together or just a Z PROBE with a custom pin, uncomment #define Z_PROBE_ENDSTOP and read the instructions below. + // If you want to still use the Z min endstop for homing, disable Z_SAFE_HOMING above. Eg; to park the head outside the bed area when homing with G28. + // WARNING: The Z MIN endstop will need to set properly as it would without a Z PROBE to prevent head crashes and premature stopping during a print. + // To use a separate Z PROBE endstop, you must have a Z_PROBE_PIN defined in the pins.h file for your control board. + // If you are using a servo based Z PROBE, you will need to enable NUM_SERVOS, SERVO_ENDSTOPS and SERVO_ENDSTOPS_ANGLES in the R/C Servo below. + // RAMPS 1.3/1.4 boards may be able to use the 5V, Ground and the D32 pin in the Aux 4 section of the RAMPS board. Use 5V for powered sensors, otherwise connect to ground and D32 + // for normally closed configuration and 5V and D32 for normally open configurations. Normally closed configuration is advised and assumed. + // The D32 pin in Aux 4 on RAMPS maps to the Arduino D32 pin. Z_PROBE_PIN is setting the pin to use on the Arduino. Since the D32 pin on the RAMPS maps to D32 on Arduino, this works. + // D32 is currently selected in the RAMPS 1.3/1.4 pin file. All other boards will need changes to the respective pins_XXXXX.h file. + // WARNING: Setting the wrong pin may have unexpected and potentially disastrous outcomes. Use with caution and do your homework. + + //#define Z_PROBE_ENDSTOP + +#endif // ENABLE_AUTO_BED_LEVELING + + +// @section homing + +// The position of the homing switches +//#define MANUAL_HOME_POSITIONS // If defined, MANUAL_*_HOME_POS below will be used +//#define BED_CENTER_AT_0_0 // If defined, the center of the bed is at (X=0, Y=0) + +// Manual homing switch locations: +// For deltabots this means top and center of the Cartesian print volume. +#ifdef MANUAL_HOME_POSITIONS + #define MANUAL_X_HOME_POS 0 + #define MANUAL_Y_HOME_POS 0 + #define MANUAL_Z_HOME_POS 0 + //#define MANUAL_Z_HOME_POS 402 // For delta: Distance between nozzle and print surface after homing. +#endif + +// @section movement + +/** + * MOVEMENT SETTINGS + */ + +#define HOMING_FEEDRATE {50*60, 50*60, 4*60, 0} // set the homing speeds (mm/min) + +// default settings + +#define DEFAULT_AXIS_STEPS_PER_UNIT {80,80,4000,500} // default steps per unit for Ultimaker +#define DEFAULT_MAX_FEEDRATE {300, 300, 5, 25} // (mm/sec) +#define DEFAULT_MAX_ACCELERATION {3000,3000,100,10000} // X, Y, Z, E maximum start speed for accelerated moves. E default values are good for Skeinforge 40+, for older versions raise them a lot. + +#define DEFAULT_ACCELERATION 3000 // X, Y, Z and E acceleration in mm/s^2 for printing moves +#define DEFAULT_RETRACT_ACCELERATION 3000 // E acceleration in mm/s^2 for retracts +#define DEFAULT_TRAVEL_ACCELERATION 3000 // X, Y, Z acceleration in mm/s^2 for travel (non printing) moves + +// The speed change that does not require acceleration (i.e. the software might assume it can be done instantaneously) +#define DEFAULT_XYJERK 20.0 // (mm/sec) +#define DEFAULT_ZJERK 0.4 // (mm/sec) +#define DEFAULT_EJERK 5.0 // (mm/sec) + + +//============================================================================= +//============================= Additional Features =========================== +//============================================================================= + +// @section more + +// Custom M code points +#define CUSTOM_M_CODES +#ifdef CUSTOM_M_CODES + #ifdef ENABLE_AUTO_BED_LEVELING + #define CUSTOM_M_CODE_SET_Z_PROBE_OFFSET 851 + #define Z_PROBE_OFFSET_RANGE_MIN -20 + #define Z_PROBE_OFFSET_RANGE_MAX 20 + #endif +#endif + +// @section extras + +// EEPROM +// The microcontroller can store settings in the EEPROM, e.g. max velocity... +// M500 - stores parameters in EEPROM +// M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily). +// M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to. +//define this to enable EEPROM support +//#define EEPROM_SETTINGS + +#ifdef EEPROM_SETTINGS + // To disable EEPROM Serial responses and decrease program space by ~1700 byte: comment this out: + #define EEPROM_CHITCHAT // please keep turned on if you can. +#endif + +// @section temperature + +// Preheat Constants +#define PLA_PREHEAT_HOTEND_TEMP 180 +#define PLA_PREHEAT_HPB_TEMP 70 +#define PLA_PREHEAT_FAN_SPEED 0 // Insert Value between 0 and 255 + +#define ABS_PREHEAT_HOTEND_TEMP 240 +#define ABS_PREHEAT_HPB_TEMP 110 +#define ABS_PREHEAT_FAN_SPEED 0 // Insert Value between 0 and 255 + +//==============================LCD and SD support============================= +// @section lcd + +// Define your display language below. Replace (en) with your language code and uncomment. +// en, pl, fr, de, es, ru, it, pt, pt-br, fi, an, nl, ca, eu, kana, kana_utf8, test +// See also language.h +#define LANGUAGE_INCLUDE GENERATE_LANGUAGE_INCLUDE(en) + +// Choose ONE of these 3 charsets. This has to match your hardware. Ignored for full graphic display. +// To find out what type you have - compile with (test) - upload - click to get the menu. You'll see two typical lines from the upper half of the charset. +// See also documentation/LCDLanguageFont.md + #define DISPLAY_CHARSET_HD44780_JAPAN // this is the most common hardware + //#define DISPLAY_CHARSET_HD44780_WESTERN + //#define DISPLAY_CHARSET_HD44780_CYRILLIC + +//#define ULTRA_LCD //general LCD support, also 16x2 +//#define DOGLCD // Support for SPI LCD 128x64 (Controller ST7565R graphic Display Family) +//#define SDSUPPORT // Enable SD Card Support in Hardware Console +//#define SDSLOW // Use slower SD transfer mode (not normally needed - uncomment if you're getting volume init error) +//#define SD_CHECK_AND_RETRY // Use CRC checks and retries on the SD communication +//#define ENCODER_PULSES_PER_STEP 1 // Increase if you have a high resolution encoder +//#define ENCODER_STEPS_PER_MENU_ITEM 5 // Set according to ENCODER_PULSES_PER_STEP or your liking +//#define ULTIMAKERCONTROLLER //as available from the Ultimaker online store. +//#define ULTIPANEL //the UltiPanel as on Thingiverse +//#define LCD_FEEDBACK_FREQUENCY_HZ 1000 // this is the tone frequency the buzzer plays when on UI feedback. ie Screen Click +//#define LCD_FEEDBACK_FREQUENCY_DURATION_MS 100 // the duration the buzzer plays the UI feedback sound. ie Screen Click + // 0 to disable buzzer feedback + +// PanelOne from T3P3 (via RAMPS 1.4 AUX2/AUX3) +// http://reprap.org/wiki/PanelOne +//#define PANEL_ONE + +// The MaKr3d Makr-Panel with graphic controller and SD support +// http://reprap.org/wiki/MaKr3d_MaKrPanel +//#define MAKRPANEL + +// The Panucatt Devices Viki 2.0 and mini Viki with Graphic LCD +// http://panucatt.com +// ==> REMEMBER TO INSTALL U8glib to your ARDUINO library folder: http://code.google.com/p/u8glib/wiki/u8glib +//#define VIKI2 +//#define miniVIKI + +// The RepRapDiscount Smart Controller (white PCB) +// http://reprap.org/wiki/RepRapDiscount_Smart_Controller +//#define REPRAP_DISCOUNT_SMART_CONTROLLER + +// The GADGETS3D G3D LCD/SD Controller (blue PCB) +// http://reprap.org/wiki/RAMPS_1.3/1.4_GADGETS3D_Shield_with_Panel +//#define G3D_PANEL + +// The RepRapDiscount FULL GRAPHIC Smart Controller (quadratic white PCB) +// http://reprap.org/wiki/RepRapDiscount_Full_Graphic_Smart_Controller +// +// ==> REMEMBER TO INSTALL U8glib to your ARDUINO library folder: http://code.google.com/p/u8glib/wiki/u8glib +//#define REPRAP_DISCOUNT_FULL_GRAPHIC_SMART_CONTROLLER + +// The RepRapWorld REPRAPWORLD_KEYPAD v1.1 +// http://reprapworld.com/?products_details&products_id=202&cPath=1591_1626 +//#define REPRAPWORLD_KEYPAD +//#define REPRAPWORLD_KEYPAD_MOVE_STEP 10.0 // how much should be moved when a key is pressed, eg 10.0 means 10mm per click + +// The Elefu RA Board Control Panel +// http://www.elefu.com/index.php?route=product/product&product_id=53 +// REMEMBER TO INSTALL LiquidCrystal_I2C.h in your ARDUINO library folder: https://github.com/kiyoshigawa/LiquidCrystal_I2C +//#define RA_CONTROL_PANEL + +/** + * I2C Panels + */ + +//#define LCD_I2C_SAINSMART_YWROBOT + +// PANELOLU2 LCD with status LEDs, separate encoder and click inputs +//#define LCD_I2C_PANELOLU2 + +// Panucatt VIKI LCD with status LEDs, integrated click & L/R/U/P buttons, separate encoder inputs +//#define LCD_I2C_VIKI + +// Shift register panels +// --------------------- +// 2 wire Non-latching LCD SR from: +// https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/schematics#!shiftregister-connection + +//#define SAV_3DLCD + +// @section extras + +// Increase the FAN pwm frequency. Removes the PWM noise but increases heating in the FET/Arduino +//#define FAST_PWM_FAN + +// Use software PWM to drive the fan, as for the heaters. This uses a very low frequency +// which is not as annoying as with the hardware PWM. On the other hand, if this frequency +// is too low, you should also increment SOFT_PWM_SCALE. +//#define FAN_SOFT_PWM + +// Incrementing this by 1 will double the software PWM frequency, +// affecting heaters, and the fan if FAN_SOFT_PWM is enabled. +// However, control resolution will be halved for each increment; +// at zero value, there are 128 effective control positions. +#define SOFT_PWM_SCALE 0 + +// Temperature status LEDs that display the hotend and bet temperature. +// If all hotends and bed temperature and temperature setpoint are < 54C then the BLUE led is on. +// Otherwise the RED led is on. There is 1C hysteresis. +//#define TEMP_STAT_LEDS + +// M240 Triggers a camera by emulating a Canon RC-1 Remote +// Data from: http://www.doc-diy.net/photo/rc-1_hacked/ +// #define PHOTOGRAPH_PIN 23 + +// SkeinForge sends the wrong arc g-codes when using Arc Point as fillet procedure +//#define SF_ARC_FIX + +// Support for the BariCUDA Paste Extruder. +//#define BARICUDA + +//define BlinkM/CyzRgb Support +//#define BLINKM + +/*********************************************************************\ +* R/C SERVO support +* Sponsored by TrinityLabs, Reworked by codexmas +**********************************************************************/ + +// Number of servos +// +// If you select a configuration below, this will receive a default value and does not need to be set manually +// set it manually if you have more servos than extruders and wish to manually control some +// leaving it undefined or defining as 0 will disable the servo subsystem +// If unsure, leave commented / disabled +// +//#define NUM_SERVOS 3 // Servo index starts with 0 for M280 command + +// Servo Endstops +// +// This allows for servo actuated endstops, primary usage is for the Z Axis to eliminate calibration or bed height changes. +// Use M851 to set the z-probe vertical offset from the nozzle. Store that setting with M500. +// +//#define SERVO_ENDSTOPS {-1, -1, 0} // Servo index for X, Y, Z. Disable with -1 +//#define SERVO_ENDSTOP_ANGLES {0,0, 0,0, 70,0} // X,Y,Z Axis Extend and Retract angles + +/**********************************************************************\ + * Support for a filament diameter sensor + * Also allows adjustment of diameter at print time (vs at slicing) + * Single extruder only at this point (extruder 0) + * + * Motherboards + * 34 - RAMPS1.4 - uses Analog input 5 on the AUX2 connector + * 81 - Printrboard - Uses Analog input 2 on the Exp1 connector (version B,C,D,E) + * 301 - Rambo - uses Analog input 3 + * Note may require analog pins to be defined for different motherboards + **********************************************************************/ +// Uncomment below to enable +//#define FILAMENT_SENSOR + +#define FILAMENT_SENSOR_EXTRUDER_NUM 0 //The number of the extruder that has the filament sensor (0,1,2) +#define MEASUREMENT_DELAY_CM 14 //measurement delay in cm. This is the distance from filament sensor to middle of barrel + +#define DEFAULT_NOMINAL_FILAMENT_DIA 3.0 //Enter the diameter (in mm) of the filament generally used (3.0 mm or 1.75 mm) - this is then used in the slicer software. Used for sensor reading validation +#define MEASURED_UPPER_LIMIT 3.30 //upper limit factor used for sensor reading validation in mm +#define MEASURED_LOWER_LIMIT 1.90 //lower limit factor for sensor reading validation in mm +#define MAX_MEASUREMENT_DELAY 20 //delay buffer size in bytes (1 byte = 1cm)- limits maximum measurement delay allowable (must be larger than MEASUREMENT_DELAY_CM and lower number saves RAM) + +//defines used in the code +#define DEFAULT_MEASURED_FILAMENT_DIA DEFAULT_NOMINAL_FILAMENT_DIA //set measured to nominal initially + +//When using an LCD, uncomment the line below to display the Filament sensor data on the last line instead of status. Status will appear for 5 sec. +//#define FILAMENT_LCD_DISPLAY + + + + + + +#include "Configuration_adv.h" +#include "thermistortables.h" + +#endif //CONFIGURATION_H diff --git a/Marlin/configurator/config/Configuration_adv.h b/Marlin/configurator/config/Configuration_adv.h new file mode 100644 index 0000000..6478eb9 --- /dev/null +++ b/Marlin/configurator/config/Configuration_adv.h @@ -0,0 +1,549 @@ +#ifndef CONFIGURATION_ADV_H +#define CONFIGURATION_ADV_H + +#include "Conditionals.h" + +// @section temperature + +//=========================================================================== +//=============================Thermal Settings ============================ +//=========================================================================== + +#ifdef BED_LIMIT_SWITCHING + #define BED_HYSTERESIS 2 //only disable heating if T>target+BED_HYSTERESIS and enable heating if T>target-BED_HYSTERESIS +#endif +#define BED_CHECK_INTERVAL 5000 //ms between checks in bang-bang control + +//// Heating sanity check: +// This waits for the watch period in milliseconds whenever an M104 or M109 increases the target temperature +// If the temperature has not increased at the end of that period, the target temperature is set to zero. +// It can be reset with another M104/M109. This check is also only triggered if the target temperature and the current temperature +// differ by at least 2x WATCH_TEMP_INCREASE +//#define WATCH_TEMP_PERIOD 40000 //40 seconds +//#define WATCH_TEMP_INCREASE 10 //Heat up at least 10 degree in 20 seconds + +#ifdef PIDTEMP + // this adds an experimental additional term to the heating power, proportional to the extrusion speed. + // if Kc is chosen well, the additional required power due to increased melting should be compensated. + #define PID_ADD_EXTRUSION_RATE + #ifdef PID_ADD_EXTRUSION_RATE + #define DEFAULT_Kc (1) //heating power=Kc*(e_speed) + #endif +#endif + + +//automatic temperature: The hot end target temperature is calculated by all the buffered lines of gcode. +//The maximum buffered steps/sec of the extruder motor are called "se". +//You enter the autotemp mode by a M109 S B F +// the target temperature is set to mintemp+factor*se[steps/sec] and limited by mintemp and maxtemp +// you exit the value by any M109 without F* +// Also, if the temperature is set to a value Z2 (yes, it is.. think about it) and the Z adjust would be positive. + // Play a little bit with small adjustments (0.5mm) and check the behaviour. + // The M119 (endstops report) will start reporting the Z2 Endstop as well. + + #define Z_DUAL_ENDSTOPS + + #ifdef Z_DUAL_ENDSTOPS + #define Z2_STEP_PIN E2_STEP_PIN // Stepper to be used to Z2 axis. + #define Z2_DIR_PIN E2_DIR_PIN + #define Z2_ENABLE_PIN E2_ENABLE_PIN + #define Z2_MAX_PIN 36 //Endstop used for Z2 axis. In this case I'm using XMAX in a Rumba Board (pin 36) + const bool Z2_MAX_ENDSTOP_INVERTING = false; + #define DISABLE_XMAX_ENDSTOP //Better to disable the XMAX to avoid conflict. Just rename "XMAX_ENDSTOP" by the endstop you are using for Z2 axis. + #endif + +#endif // Z_DUAL_STEPPER_DRIVERS + +// Same again but for Y Axis. +//#define Y_DUAL_STEPPER_DRIVERS + +// Define if the two Y drives need to rotate in opposite directions +#define INVERT_Y2_VS_Y_DIR true + +// Enable this for dual x-carriage printers. +// A dual x-carriage design has the advantage that the inactive extruder can be parked which +// prevents hot-end ooze contaminating the print. It also reduces the weight of each x-carriage +// allowing faster printing speeds. +//#define DUAL_X_CARRIAGE +#ifdef DUAL_X_CARRIAGE + // Configuration for second X-carriage + // Note: the first x-carriage is defined as the x-carriage which homes to the minimum endstop; + // the second x-carriage always homes to the maximum endstop. + #define X2_MIN_POS 80 // set minimum to ensure second x-carriage doesn't hit the parked first X-carriage + #define X2_MAX_POS 353 // set maximum to the distance between toolheads when both heads are homed + #define X2_HOME_DIR 1 // the second X-carriage always homes to the maximum endstop position + #define X2_HOME_POS X2_MAX_POS // default home position is the maximum carriage position + // However: In this mode the EXTRUDER_OFFSET_X value for the second extruder provides a software + // override for X2_HOME_POS. This also allow recalibration of the distance between the two endstops + // without modifying the firmware (through the "M218 T1 X???" command). + // Remember: you should set the second extruder x-offset to 0 in your slicer. + + // Pins for second x-carriage stepper driver (defined here to avoid further complicating pins.h) + #define X2_ENABLE_PIN 29 + #define X2_STEP_PIN 25 + #define X2_DIR_PIN 23 + + // There are a few selectable movement modes for dual x-carriages using M605 S + // Mode 0: Full control. The slicer has full control over both x-carriages and can achieve optimal travel results + // as long as it supports dual x-carriages. (M605 S0) + // Mode 1: Auto-park mode. The firmware will automatically park and unpark the x-carriages on tool changes so + // that additional slicer support is not required. (M605 S1) + // Mode 2: Duplication mode. The firmware will transparently make the second x-carriage and extruder copy all + // actions of the first x-carriage. This allows the printer to print 2 arbitrary items at + // once. (2nd extruder x offset and temp offset are set using: M605 S2 [Xnnn] [Rmmm]) + + // This is the default power-up mode which can be later using M605. + #define DEFAULT_DUAL_X_CARRIAGE_MODE 0 + + // Default settings in "Auto-park Mode" + #define TOOLCHANGE_PARK_ZLIFT 0.2 // the distance to raise Z axis when parking an extruder + #define TOOLCHANGE_UNPARK_ZLIFT 1 // the distance to raise Z axis when unparking an extruder + + // Default x offset in duplication mode (typically set to half print bed width) + #define DEFAULT_DUPLICATION_X_OFFSET 100 + +#endif //DUAL_X_CARRIAGE + +// @section homing + +//homing hits the endstop, then retracts by this distance, before it tries to slowly bump again: +#define X_HOME_BUMP_MM 5 +#define Y_HOME_BUMP_MM 5 +#define Z_HOME_BUMP_MM 2 +#define HOMING_BUMP_DIVISOR {2, 2, 4} // Re-Bump Speed Divisor (Divides the Homing Feedrate) +//#define QUICK_HOME //if this is defined, if both x and y are to be homed, a diagonal move will be performed initially. + +// @section machine + +#define AXIS_RELATIVE_MODES {false, false, false, false} + +// @section machine + +//By default pololu step drivers require an active high signal. However, some high power drivers require an active low signal as step. +#define INVERT_X_STEP_PIN false +#define INVERT_Y_STEP_PIN false +#define INVERT_Z_STEP_PIN false +#define INVERT_E_STEP_PIN false + +// Default stepper release if idle. Set to 0 to deactivate. +#define DEFAULT_STEPPER_DEACTIVE_TIME 60 + +#define DEFAULT_MINIMUMFEEDRATE 0.0 // minimum feedrate +#define DEFAULT_MINTRAVELFEEDRATE 0.0 + +// @section lcd + +#ifdef ULTIPANEL + #define MANUAL_FEEDRATE {50*60, 50*60, 4*60, 60} // Feedrates for manual moves along X, Y, Z, E from panel + #define ULTIPANEL_FEEDMULTIPLY // Comment to disable setting feedrate multiplier via encoder +#endif + +// @section extras + +// minimum time in microseconds that a movement needs to take if the buffer is emptied. +#define DEFAULT_MINSEGMENTTIME 20000 + +// If defined the movements slow down when the look ahead buffer is only half full +#define SLOWDOWN + +// Frequency limit +// See nophead's blog for more info +// Not working O +//#define XY_FREQUENCY_LIMIT 15 + +// Minimum planner junction speed. Sets the default minimum speed the planner plans for at the end +// of the buffer and all stops. This should not be much greater than zero and should only be changed +// if unwanted behavior is observed on a user's machine when running at very slow speeds. +#define MINIMUM_PLANNER_SPEED 0.05// (mm/sec) + +// Microstep setting (Only functional when stepper driver microstep pins are connected to MCU. +#define MICROSTEP_MODES {16,16,16,16,16} // [1,2,4,8,16] + +// Motor Current setting (Only functional when motor driver current ref pins are connected to a digital trimpot on supported boards) +#define DIGIPOT_MOTOR_CURRENT {135,135,135,135,135} // Values 0-255 (RAMBO 135 = ~0.75A, 185 = ~1A) + +// uncomment to enable an I2C based DIGIPOT like on the Azteeg X3 Pro +//#define DIGIPOT_I2C +// Number of channels available for I2C digipot, For Azteeg X3 Pro we have 8 +#define DIGIPOT_I2C_NUM_CHANNELS 8 +// actual motor currents in Amps, need as many here as DIGIPOT_I2C_NUM_CHANNELS +#define DIGIPOT_I2C_MOTOR_CURRENTS {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0} + +//=========================================================================== +//=============================Additional Features=========================== +//=========================================================================== + +#define ENCODER_RATE_MULTIPLIER // If defined, certain menu edit operations automatically multiply the steps when the encoder is moved quickly +#define ENCODER_10X_STEPS_PER_SEC 75 // If the encoder steps per sec exceeds this value, multiply steps moved x10 to quickly advance the value +#define ENCODER_100X_STEPS_PER_SEC 160 // If the encoder steps per sec exceeds this value, multiply steps moved x100 to really quickly advance the value +//#define ENCODER_RATE_MULTIPLIER_DEBUG // If defined, output the encoder steps per second value + +//#define CHDK 4 //Pin for triggering CHDK to take a picture see how to use it here http://captain-slow.dk/2014/03/09/3d-printing-timelapses/ +#define CHDK_DELAY 50 //How long in ms the pin should stay HIGH before going LOW again + +// @section lcd + +#ifdef SDSUPPORT + + // If you are using a RAMPS board or cheap E-bay purchased boards that do not detect when an SD card is inserted + // You can get round this by connecting a push button or single throw switch to the pin defined as SDCARDCARDDETECT + // in the pins.h file. When using a push button pulling the pin to ground this will need inverted. This setting should + // be commented out otherwise + #define SDCARDDETECTINVERTED + + #define SD_FINISHED_STEPPERRELEASE true //if sd support and the file is finished: disable steppers? + #define SD_FINISHED_RELEASECOMMAND "M84 X Y Z E" // You might want to keep the z enabled so your bed stays in place. + + #define SDCARD_RATHERRECENTFIRST //reverse file order of sd card menu display. Its sorted practically after the file system block order. + // if a file is deleted, it frees a block. hence, the order is not purely chronological. To still have auto0.g accessible, there is again the option to do that. + // using: + //#define MENU_ADDAUTOSTART + + // Show a progress bar on HD44780 LCDs for SD printing + //#define LCD_PROGRESS_BAR + + #ifdef LCD_PROGRESS_BAR + // Amount of time (ms) to show the bar + #define PROGRESS_BAR_BAR_TIME 2000 + // Amount of time (ms) to show the status message + #define PROGRESS_BAR_MSG_TIME 3000 + // Amount of time (ms) to retain the status message (0=forever) + #define PROGRESS_MSG_EXPIRE 0 + // Enable this to show messages for MSG_TIME then hide them + //#define PROGRESS_MSG_ONCE + #endif + +#endif // SDSUPPORT + +// @section more + +// The hardware watchdog should reset the microcontroller disabling all outputs, in case the firmware gets stuck and doesn't do temperature regulation. +//#define USE_WATCHDOG + +#ifdef USE_WATCHDOG +// If you have a watchdog reboot in an ArduinoMega2560 then the device will hang forever, as a watchdog reset will leave the watchdog on. +// The "WATCHDOG_RESET_MANUAL" goes around this by not using the hardware reset. +// However, THIS FEATURE IS UNSAFE!, as it will only work if interrupts are disabled. And the code could hang in an interrupt routine with interrupts disabled. +//#define WATCHDOG_RESET_MANUAL +#endif + +// Enable the option to stop SD printing when hitting and endstops, needs to be enabled from the LCD menu when this option is enabled. +//#define ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED + +// @section lcd + +// Babystepping enables the user to control the axis in tiny amounts, independently from the normal printing process +// it can e.g. be used to change z-positions in the print startup phase in real-time +// does not respect endstops! +//#define BABYSTEPPING +#ifdef BABYSTEPPING + #define BABYSTEP_XY //not only z, but also XY in the menu. more clutter, more functions + #define BABYSTEP_INVERT_Z false //true for inverse movements in Z + #define BABYSTEP_Z_MULTIPLICATOR 2 //faster z movements +#endif + +// @section extruder + +// extruder advance constant (s2/mm3) +// +// advance (steps) = STEPS_PER_CUBIC_MM_E * EXTRUDER_ADVANCE_K * cubic mm per second ^ 2 +// +// Hooke's law says: force = k * distance +// Bernoulli's principle says: v ^ 2 / 2 + g . h + pressure / density = constant +// so: v ^ 2 is proportional to number of steps we advance the extruder +//#define ADVANCE + +#ifdef ADVANCE + #define EXTRUDER_ADVANCE_K .0 + #define D_FILAMENT 2.85 + #define STEPS_MM_E 836 +#endif + +// @section extras + +// Arc interpretation settings: +#define MM_PER_ARC_SEGMENT 1 +#define N_ARC_CORRECTION 25 + +const unsigned int dropsegments=5; //everything with less than this number of steps will be ignored as move and joined with the next movement + +// @section temperature + +// Control heater 0 and heater 1 in parallel. +//#define HEATERS_PARALLEL + +//=========================================================================== +//=============================Buffers ============================ +//=========================================================================== + +// @section hidden + +// The number of linear motions that can be in the plan at any give time. +// THE BLOCK_BUFFER_SIZE NEEDS TO BE A POWER OF 2, i.g. 8,16,32 because shifts and ors are used to do the ring-buffering. +#ifdef SDSUPPORT + #define BLOCK_BUFFER_SIZE 16 // SD,LCD,Buttons take more memory, block buffer needs to be smaller +#else + #define BLOCK_BUFFER_SIZE 16 // maximize block buffer +#endif + +// @section more + +//The ASCII buffer for receiving from the serial: +#define MAX_CMD_SIZE 96 +#define BUFSIZE 4 + +// @section fwretract + +// Firmware based and LCD controlled retract +// M207 and M208 can be used to define parameters for the retraction. +// The retraction can be called by the slicer using G10 and G11 +// until then, intended retractions can be detected by moves that only extrude and the direction. +// the moves are than replaced by the firmware controlled ones. + +// #define FWRETRACT //ONLY PARTIALLY TESTED +#ifdef FWRETRACT + #define MIN_RETRACT 0.1 //minimum extruded mm to accept a automatic gcode retraction attempt + #define RETRACT_LENGTH 3 //default retract length (positive mm) + #define RETRACT_LENGTH_SWAP 13 //default swap retract length (positive mm), for extruder change + #define RETRACT_FEEDRATE 45 //default feedrate for retracting (mm/s) + #define RETRACT_ZLIFT 0 //default retract Z-lift + #define RETRACT_RECOVER_LENGTH 0 //default additional recover length (mm, added to retract length when recovering) + #define RETRACT_RECOVER_LENGTH_SWAP 0 //default additional swap recover length (mm, added to retract length when recovering from extruder change) + #define RETRACT_RECOVER_FEEDRATE 8 //default feedrate for recovering from retraction (mm/s) +#endif + +// Add support for experimental filament exchange support M600; requires display +#ifdef ULTIPANEL + //#define FILAMENTCHANGEENABLE + #ifdef FILAMENTCHANGEENABLE + #define FILAMENTCHANGE_XPOS 3 + #define FILAMENTCHANGE_YPOS 3 + #define FILAMENTCHANGE_ZADD 10 + #define FILAMENTCHANGE_FIRSTRETRACT -2 + #define FILAMENTCHANGE_FINALRETRACT -100 + #endif +#endif + +/******************************************************************************\ + * enable this section if you have TMC26X motor drivers. + * you need to import the TMC26XStepper library into the arduino IDE for this + ******************************************************************************/ + +// @section tmc + +//#define HAVE_TMCDRIVER +#ifdef HAVE_TMCDRIVER + +// #define X_IS_TMC + #define X_MAX_CURRENT 1000 //in mA + #define X_SENSE_RESISTOR 91 //in mOhms + #define X_MICROSTEPS 16 //number of microsteps + +// #define X2_IS_TMC + #define X2_MAX_CURRENT 1000 //in mA + #define X2_SENSE_RESISTOR 91 //in mOhms + #define X2_MICROSTEPS 16 //number of microsteps + +// #define Y_IS_TMC + #define Y_MAX_CURRENT 1000 //in mA + #define Y_SENSE_RESISTOR 91 //in mOhms + #define Y_MICROSTEPS 16 //number of microsteps + +// #define Y2_IS_TMC + #define Y2_MAX_CURRENT 1000 //in mA + #define Y2_SENSE_RESISTOR 91 //in mOhms + #define Y2_MICROSTEPS 16 //number of microsteps + +// #define Z_IS_TMC + #define Z_MAX_CURRENT 1000 //in mA + #define Z_SENSE_RESISTOR 91 //in mOhms + #define Z_MICROSTEPS 16 //number of microsteps + +// #define Z2_IS_TMC + #define Z2_MAX_CURRENT 1000 //in mA + #define Z2_SENSE_RESISTOR 91 //in mOhms + #define Z2_MICROSTEPS 16 //number of microsteps + +// #define E0_IS_TMC + #define E0_MAX_CURRENT 1000 //in mA + #define E0_SENSE_RESISTOR 91 //in mOhms + #define E0_MICROSTEPS 16 //number of microsteps + +// #define E1_IS_TMC + #define E1_MAX_CURRENT 1000 //in mA + #define E1_SENSE_RESISTOR 91 //in mOhms + #define E1_MICROSTEPS 16 //number of microsteps + +// #define E2_IS_TMC + #define E2_MAX_CURRENT 1000 //in mA + #define E2_SENSE_RESISTOR 91 //in mOhms + #define E2_MICROSTEPS 16 //number of microsteps + +// #define E3_IS_TMC + #define E3_MAX_CURRENT 1000 //in mA + #define E3_SENSE_RESISTOR 91 //in mOhms + #define E3_MICROSTEPS 16 //number of microsteps + +#endif + +/******************************************************************************\ + * enable this section if you have L6470 motor drivers. + * you need to import the L6470 library into the arduino IDE for this + ******************************************************************************/ + +// @section l6470 + +//#define HAVE_L6470DRIVER +#ifdef HAVE_L6470DRIVER + +// #define X_IS_L6470 + #define X_MICROSTEPS 16 //number of microsteps + #define X_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define X_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define X_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define X2_IS_L6470 + #define X2_MICROSTEPS 16 //number of microsteps + #define X2_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define X2_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define X2_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define Y_IS_L6470 + #define Y_MICROSTEPS 16 //number of microsteps + #define Y_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define Y_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define Y_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define Y2_IS_L6470 + #define Y2_MICROSTEPS 16 //number of microsteps + #define Y2_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define Y2_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define Y2_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define Z_IS_L6470 + #define Z_MICROSTEPS 16 //number of microsteps + #define Z_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define Z_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define Z_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define Z2_IS_L6470 + #define Z2_MICROSTEPS 16 //number of microsteps + #define Z2_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define Z2_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define Z2_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define E0_IS_L6470 + #define E0_MICROSTEPS 16 //number of microsteps + #define E0_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define E0_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define E0_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define E1_IS_L6470 + #define E1_MICROSTEPS 16 //number of microsteps + #define E1_MICROSTEPS 16 //number of microsteps + #define E1_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define E1_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define E1_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define E2_IS_L6470 + #define E2_MICROSTEPS 16 //number of microsteps + #define E2_MICROSTEPS 16 //number of microsteps + #define E2_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define E2_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define E2_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +// #define E3_IS_L6470 + #define E3_MICROSTEPS 16 //number of microsteps + #define E3_MICROSTEPS 16 //number of microsteps + #define E3_K_VAL 50 // 0 - 255, Higher values, are higher power. Be carefull not to go too high + #define E3_OVERCURRENT 2000 //maxc current in mA. If the current goes over this value, the driver will switch off + #define E3_STALLCURRENT 1500 //current in mA where the driver will detect a stall + +#endif + +#include "Conditionals.h" +#include "SanityCheck.h" + +#endif //CONFIGURATION_ADV_H diff --git a/Marlin/configurator/config/_htaccess b/Marlin/configurator/config/_htaccess new file mode 100644 index 0000000..f289550 --- /dev/null +++ b/Marlin/configurator/config/_htaccess @@ -0,0 +1 @@ +Header set Access-Control-Allow-Origin "*" diff --git a/Marlin/configurator/config/boards.h b/Marlin/configurator/config/boards.h new file mode 100644 index 0000000..8a60f01 --- /dev/null +++ b/Marlin/configurator/config/boards.h @@ -0,0 +1,62 @@ +#ifndef BOARDS_H +#define BOARDS_H + +#define BOARD_UNKNOWN -1 + +#define BOARD_GEN7_CUSTOM 10 // Gen7 custom (Alfons3 Version) "https://github.com/Alfons3/Generation_7_Electronics" +#define BOARD_GEN7_12 11 // Gen7 v1.1, v1.2 +#define BOARD_GEN7_13 12 // Gen7 v1.3 +#define BOARD_GEN7_14 13 // Gen7 v1.4 +#define BOARD_CHEAPTRONIC 2 // Cheaptronic v1.0 +#define BOARD_SETHI 20 // Sethi 3D_1 +#define BOARD_RAMPS_OLD 3 // MEGA/RAMPS up to 1.2 +#define BOARD_RAMPS_13_EFB 33 // RAMPS 1.3 / 1.4 (Power outputs: Extruder, Fan, Bed) +#define BOARD_RAMPS_13_EEB 34 // RAMPS 1.3 / 1.4 (Power outputs: Extruder0, Extruder1, Bed) +#define BOARD_RAMPS_13_EFF 35 // RAMPS 1.3 / 1.4 (Power outputs: Extruder, Fan, Fan) +#define BOARD_RAMPS_13_EEF 36 // RAMPS 1.3 / 1.4 (Power outputs: Extruder0, Extruder1, Fan) +#define BOARD_FELIX2 37 // Felix 2.0+ Electronics Board (RAMPS like) +#define BOARD_DUEMILANOVE_328P 4 // Duemilanove w/ ATMega328P pin assignments +#define BOARD_GEN6 5 // Gen6 +#define BOARD_GEN6_DELUXE 51 // Gen6 deluxe +#define BOARD_SANGUINOLOLU_11 6 // Sanguinololu < 1.2 +#define BOARD_SANGUINOLOLU_12 62 // Sanguinololu 1.2 and above +#define BOARD_MELZI 63 // Melzi +#define BOARD_STB_11 64 // STB V1.1 +#define BOARD_AZTEEG_X1 65 // Azteeg X1 +#define BOARD_MELZI_1284 66 // Melzi with ATmega1284 (MaKr3d version) +#define BOARD_AZTEEG_X3 67 // Azteeg X3 +#define BOARD_AZTEEG_X3_PRO 68 // Azteeg X3 Pro +#define BOARD_ULTIMAKER 7 // Ultimaker +#define BOARD_ULTIMAKER_OLD 71 // Ultimaker (Older electronics. Pre 1.5.4. This is rare) +#define BOARD_ULTIMAIN_2 72 // Ultimainboard 2.x (Uses TEMP_SENSOR 20) +#define BOARD_3DRAG 77 // 3Drag Controller +#define BOARD_K8200 78 // Vellemann K8200 Controller (derived from 3Drag Controller) +#define BOARD_TEENSYLU 8 // Teensylu +#define BOARD_RUMBA 80 // Rumba +#define BOARD_PRINTRBOARD 81 // Printrboard (AT90USB1286) +#define BOARD_BRAINWAVE 82 // Brainwave (AT90USB646) +#define BOARD_SAV_MKI 83 // SAV Mk-I (AT90USB1286) +#define BOARD_TEENSY2 84 // Teensy++2.0 (AT90USB1286) - CLI compile: DEFINES=AT90USBxx_TEENSYPP_ASSIGNMENTS HARDWARE_MOTHERBOARD=84 make +#define BOARD_BRAINWAVE_PRO 85 // Brainwave Pro (AT90USB1286) +#define BOARD_GEN3_PLUS 9 // Gen3+ +#define BOARD_GEN3_MONOLITHIC 22 // Gen3 Monolithic Electronics +#define BOARD_MEGATRONICS 70 // Megatronics +#define BOARD_MEGATRONICS_2 701 // Megatronics v2.0 +#define BOARD_MEGATRONICS_1 702 // Minitronics v1.0 +#define BOARD_MEGATRONICS_3 703 // Megatronics v3.0 +#define BOARD_OMCA_A 90 // Alpha OMCA board +#define BOARD_OMCA 91 // Final OMCA board +#define BOARD_RAMBO 301 // Rambo +#define BOARD_ELEFU_3 21 // Elefu Ra Board (v3) +#define BOARD_5DPRINT 88 // 5DPrint D8 Driver Board +#define BOARD_LEAPFROG 999 // Leapfrog +#define BOARD_WITBOX 41 // bq WITBOX +#define BOARD_HEPHESTOS 42 // bq Prusa i3 Hephestos +#define BOARD_BAM_DICE 401 // 2PrintBeta BAM&DICE with STK drivers +#define BOARD_BAM_DICE_DUE 402 // 2PrintBeta BAM&DICE Due with STK drivers + +#define BOARD_99 99 // This is in pins.h but...? + +#define MB(board) (MOTHERBOARD==BOARD_##board) + +#endif //__BOARDS_H diff --git a/Marlin/configurator/config/language.h b/Marlin/configurator/config/language.h new file mode 100644 index 0000000..5d1fd6c --- /dev/null +++ b/Marlin/configurator/config/language.h @@ -0,0 +1,238 @@ +#ifndef LANGUAGE_H +#define LANGUAGE_H + +#include "Configuration.h" + +#define LANGUAGE_CONCAT(M) #M +#define GENERATE_LANGUAGE_INCLUDE(M) LANGUAGE_CONCAT(language_##M.h) + + +// NOTE: IF YOU CHANGE LANGUAGE FILES OR MERGE A FILE WITH CHANGES +// +// ==> ALWAYS TRY TO COMPILE MARLIN WITH/WITHOUT "ULTIPANEL" / "ULTRALCD" / "SDSUPPORT" #define IN "Configuration.h" +// ==> ALSO TRY ALL AVAILABLE LANGUAGE OPTIONS +// See also documentation/LCDLanguageFont.md + +// Languages +// en English +// pl Polish +// fr French +// de German +// es Spanish +// ru Russian +// it Italian +// pt Portuguese +// pt-br Portuguese (Brazil) +// fi Finnish +// an Aragonese +// nl Dutch +// ca Catalan +// eu Basque-Euskera +// kana Japanese +// kana_utf Japanese + +#ifndef LANGUAGE_INCLUDE + // pick your language from the list above + #define LANGUAGE_INCLUDE GENERATE_LANGUAGE_INCLUDE(en) +#endif + +#ifdef HAS_AUTOMATIC_VERSIONING + #include "_Version.h" +#endif + +#define PROTOCOL_VERSION "1.0" + +#if MB(ULTIMAKER)|| MB(ULTIMAKER_OLD)|| MB(ULTIMAIN_2) + #define MACHINE_NAME "Ultimaker" + #define FIRMWARE_URL "http://firmware.ultimaker.com" +#elif MB(RUMBA) + #define MACHINE_NAME "Rumba" +#elif MB(3DRAG) + #define MACHINE_NAME "3Drag" + #define FIRMWARE_URL "http://3dprint.elettronicain.it/" +#elif MB(K8200) + #define MACHINE_NAME "K8200" +#elif MB(5DPRINT) + #define MACHINE_NAME "Makibox" +#elif MB(SAV_MKI) + #define MACHINE_NAME "SAV MkI" + #define FIRMWARE_URL "https://github.com/fmalpartida/Marlin/tree/SAV-MkI-config" +#elif MB(WITBOX) + #define MACHINE_NAME "WITBOX" + #define FIRMWARE_URL "http://www.bq.com/gb/downloads-witbox.html" +#elif MB(HEPHESTOS) + #define MACHINE_NAME "HEPHESTOS" + #define FIRMWARE_URL "http://www.bq.com/gb/downloads-prusa-i3-hephestos.html" +#elif MB(BRAINWAVE_PRO) + #define MACHINE_NAME "Kossel Pro" + #ifndef FIRMWARE_URL + #define FIRMWARE_URL "https://github.com/OpenBeamUSA/Marlin/" + #endif +#else + #ifndef MACHINE_NAME + #define MACHINE_NAME "Mendel" + #endif +#endif + +#ifdef CUSTOM_MENDEL_NAME + #error CUSTOM_MENDEL_NAME deprecated - use CUSTOM_MACHINE_NAME + #define CUSTOM_MACHINE_NAME CUSTOM_MENDEL_NAME +#endif + +#ifdef CUSTOM_MACHINE_NAME + #undef MACHINE_NAME + #define MACHINE_NAME CUSTOM_MACHINE_NAME +#endif + +#ifndef FIRMWARE_URL + #define FIRMWARE_URL "https://github.com/MarlinFirmware/Marlin" +#endif + +#ifndef BUILD_VERSION + #define BUILD_VERSION "V1; Sprinter/grbl mashup for gen6" +#endif + +#ifndef MACHINE_UUID + #define MACHINE_UUID "00000000-0000-0000-0000-000000000000" +#endif + + +#define STRINGIFY_(n) #n +#define STRINGIFY(n) STRINGIFY_(n) + + +// Common LCD messages + + /* nothing here yet */ + +// Common serial messages +#define MSG_MARLIN "Marlin" + +// Serial Console Messages (do not translate those!) + +#define MSG_Enqueing "enqueing \"" +#define MSG_POWERUP "PowerUp" +#define MSG_EXTERNAL_RESET " External Reset" +#define MSG_BROWNOUT_RESET " Brown out Reset" +#define MSG_WATCHDOG_RESET " Watchdog Reset" +#define MSG_SOFTWARE_RESET " Software Reset" +#define MSG_AUTHOR " | Author: " +#define MSG_CONFIGURATION_VER " Last Updated: " +#define MSG_FREE_MEMORY " Free Memory: " +#define MSG_PLANNER_BUFFER_BYTES " PlannerBufferBytes: " +#define MSG_OK "ok" +#define MSG_FILE_SAVED "Done saving file." +#define MSG_ERR_LINE_NO "Line Number is not Last Line Number+1, Last Line: " +#define MSG_ERR_CHECKSUM_MISMATCH "checksum mismatch, Last Line: " +#define MSG_ERR_NO_CHECKSUM "No Checksum with line number, Last Line: " +#define MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM "No Line Number with checksum, Last Line: " +#define MSG_FILE_PRINTED "Done printing file" +#define MSG_BEGIN_FILE_LIST "Begin file list" +#define MSG_END_FILE_LIST "End file list" +#define MSG_M104_INVALID_EXTRUDER "M104 Invalid extruder " +#define MSG_M105_INVALID_EXTRUDER "M105 Invalid extruder " +#define MSG_M200_INVALID_EXTRUDER "M200 Invalid extruder " +#define MSG_M218_INVALID_EXTRUDER "M218 Invalid extruder " +#define MSG_M221_INVALID_EXTRUDER "M221 Invalid extruder " +#define MSG_ERR_NO_THERMISTORS "No thermistors - no temperature" +#define MSG_M109_INVALID_EXTRUDER "M109 Invalid extruder " +#define MSG_HEATING "Heating..." +#define MSG_HEATING_COMPLETE "Heating done." +#define MSG_BED_HEATING "Bed Heating." +#define MSG_BED_DONE "Bed done." +#define MSG_M115_REPORT "FIRMWARE_NAME:Marlin " BUILD_VERSION " FIRMWARE_URL:" FIRMWARE_URL " PROTOCOL_VERSION:" PROTOCOL_VERSION " MACHINE_TYPE:" MACHINE_NAME " EXTRUDER_COUNT:" STRINGIFY(EXTRUDERS) " UUID:" MACHINE_UUID "\n" +#define MSG_COUNT_X " Count X: " +#define MSG_ERR_KILLED "Printer halted. kill() called!" +#define MSG_ERR_STOPPED "Printer stopped due to errors. Fix the error and use M999 to restart. (Temperature is reset. Set it after restarting)" +#define MSG_RESEND "Resend: " +#define MSG_UNKNOWN_COMMAND "Unknown command: \"" +#define MSG_ACTIVE_EXTRUDER "Active Extruder: " +#define MSG_INVALID_EXTRUDER "Invalid extruder" +#define MSG_INVALID_SOLENOID "Invalid solenoid" +#define MSG_X_MIN "x_min: " +#define MSG_X_MAX "x_max: " +#define MSG_Y_MIN "y_min: " +#define MSG_Y_MAX "y_max: " +#define MSG_Z_MIN "z_min: " +#define MSG_Z_MAX "z_max: " +#define MSG_Z2_MAX "z2_max: " +#define MSG_Z_PROBE "z_probe: " +#define MSG_M119_REPORT "Reporting endstop status" +#define MSG_ENDSTOP_HIT "TRIGGERED" +#define MSG_ENDSTOP_OPEN "open" +#define MSG_HOTEND_OFFSET "Hotend offsets:" + +#define MSG_SD_CANT_OPEN_SUBDIR "Cannot open subdir" +#define MSG_SD_INIT_FAIL "SD init fail" +#define MSG_SD_VOL_INIT_FAIL "volume.init failed" +#define MSG_SD_OPENROOT_FAIL "openRoot failed" +#define MSG_SD_CARD_OK "SD card ok" +#define MSG_SD_WORKDIR_FAIL "workDir open failed" +#define MSG_SD_OPEN_FILE_FAIL "open failed, File: " +#define MSG_SD_FILE_OPENED "File opened: " +#define MSG_SD_SIZE " Size: " +#define MSG_SD_FILE_SELECTED "File selected" +#define MSG_SD_WRITE_TO_FILE "Writing to file: " +#define MSG_SD_PRINTING_BYTE "SD printing byte " +#define MSG_SD_NOT_PRINTING "Not SD printing" +#define MSG_SD_ERR_WRITE_TO_FILE "error writing to file" +#define MSG_SD_CANT_ENTER_SUBDIR "Cannot enter subdir: " + +#define MSG_STEPPER_TOO_HIGH "Steprate too high: " +#define MSG_ENDSTOPS_HIT "endstops hit: " +#define MSG_ERR_COLD_EXTRUDE_STOP " cold extrusion prevented" +#define MSG_ERR_LONG_EXTRUDE_STOP " too long extrusion prevented" +#define MSG_BABYSTEPPING_X "Babystepping X" +#define MSG_BABYSTEPPING_Y "Babystepping Y" +#define MSG_BABYSTEPPING_Z "Babystepping Z" +#define MSG_SERIAL_ERROR_MENU_STRUCTURE "Error in menu structure" + +#define MSG_ERR_EEPROM_WRITE "Error writing to EEPROM!" + +// temperature.cpp strings +#define MSG_PID_AUTOTUNE "PID Autotune" +#define MSG_PID_AUTOTUNE_START MSG_PID_AUTOTUNE " start" +#define MSG_PID_AUTOTUNE_FAILED MSG_PID_AUTOTUNE " failed!" +#define MSG_PID_BAD_EXTRUDER_NUM MSG_PID_AUTOTUNE_FAILED " Bad extruder number" +#define MSG_PID_TEMP_TOO_HIGH MSG_PID_AUTOTUNE_FAILED " Temperature too high" +#define MSG_PID_TIMEOUT MSG_PID_AUTOTUNE_FAILED " timeout" +#define MSG_BIAS " bias: " +#define MSG_D " d: " +#define MSG_T_MIN " min: " +#define MSG_T_MAX " max: " +#define MSG_KU " Ku: " +#define MSG_TU " Tu: " +#define MSG_CLASSIC_PID " Classic PID " +#define MSG_KP " Kp: " +#define MSG_KI " Ki: " +#define MSG_KD " Kd: " +#define MSG_OK_B "ok B:" +#define MSG_OK_T "ok T:" +#define MSG_AT " @:" +#define MSG_PID_AUTOTUNE_FINISHED MSG_PID_AUTOTUNE " finished! Put the last Kp, Ki and Kd constants from above into Configuration.h" +#define MSG_PID_DEBUG " PID_DEBUG " +#define MSG_PID_DEBUG_INPUT ": Input " +#define MSG_PID_DEBUG_OUTPUT " Output " +#define MSG_PID_DEBUG_PTERM " pTerm " +#define MSG_PID_DEBUG_ITERM " iTerm " +#define MSG_PID_DEBUG_DTERM " dTerm " +#define MSG_HEATING_FAILED "Heating failed" +#define MSG_EXTRUDER_SWITCHED_OFF "Extruder switched off. Temperature difference between temp sensors is too high !" + +#define MSG_INVALID_EXTRUDER_NUM " - Invalid extruder number !" +#define MSG_THERMAL_RUNAWAY_STOP "Thermal Runaway, system stopped! Heater_ID: " +#define MSG_SWITCHED_OFF_MAX " switched off. MAXTEMP triggered !!" +#define MSG_MINTEMP_EXTRUDER_OFF ": Extruder switched off. MINTEMP triggered !" +#define MSG_MAXTEMP_EXTRUDER_OFF ": Extruder" MSG_SWITCHED_OFF_MAX +#define MSG_MAXTEMP_BED_OFF "Heated bed" MSG_SWITCHED_OFF_MAX + +// LCD Menu Messages + +#if !(defined( DISPLAY_CHARSET_HD44780_JAPAN ) || defined( DISPLAY_CHARSET_HD44780_WESTERN ) || defined( DISPLAY_CHARSET_HD44780_CYRILLIC )) + #define DISPLAY_CHARSET_HD44780_JAPAN +#endif + +#include LANGUAGE_INCLUDE +#include "language_en.h" + +#endif //__LANGUAGE_H diff --git a/Marlin/configurator/css/configurator.css b/Marlin/configurator/css/configurator.css new file mode 100644 index 0000000..8833207 --- /dev/null +++ b/Marlin/configurator/css/configurator.css @@ -0,0 +1,344 @@ +/* configurator.css */ +/* Styles for Marlin Configurator */ + +.clear { clear: both; } + +/* Prevent selection except PRE tags */ +* { + -webkit-touch-callout: none; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + } +pre { + -webkit-touch-callout: text; + -webkit-user-select: text; + -khtml-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + } + +body { margin: 0; padding: 0; background: #56A; color: #000; font-family: monospace; } +#main { + max-width: 1100px; + margin: 0 auto 10px; + padding: 0 2%; width: 96%; + } + +h1, h2, h3, h4, h5, h6 { clear: both; } + +h1, p.info { font-family: sans-serif; } +h1 { + height: 38px; + margin-bottom: -30px; + color: #FFF; + background: transparent url(logo.png) right top no-repeat; + } +p.info { padding: 0; color: #000; } +p.info span { color: #800; } + +#message { text-align: center; } +#message { width: 80%; margin: 0 auto 0.25em; color: #FF0; } +#message p { padding: 2px 0; font-weight: bold; border-radius: 0.8em; } +#message p.message { color: #080; background: #CFC; } +#message p.error { color: #F00; background: #FF4; } +#message p.warning { color: #FF0; background: #BA4; } +#message p.message span, +#message p.error span, +#message p.warning span { + color: #A00; + background: rgba(255, 255, 255, 1); + border: 1px solid rgba(0,0,0,0.5); + border-radius: 1em; + float: right; + margin-right: 0.5em; + padding: 0 3px; + font-family: sans-serif; + font-size: small; + position: relative; + top: -1px; + } + +#help strong { color: #0DD; } +img { display: none; } + +/* Forms */ + +#config_form { + display: block; + background: #EEE; + padding: 6px 20px 20px; + color: #000; + position: relative; + border-radius: 1.5em; + border-top-left-radius: 0; + } +fieldset { + height: 16.1em; + overflow-y: scroll; + overflow-x: hidden; + margin-top: 10px; + } +label, input, select, textarea { display: block; float: left; margin: 1px 0; } +label.newline, textarea, fieldset { clear: both; } +label { + width: 120px; /* label area */ + height: 1em; + padding: 10px 460px 10px 1em; + margin-right: -450px; + text-align: right; + } +label.blocked, label.added.blocked, label.added.blocked.sublabel { color: #AAA; } + +label.added.sublabel { + width: auto; + margin: 11px -2.5em 0 1em; + padding: 0 3em 0 0; + font-style: italic; + color: #444; + } +label+label.added.sublabel { + margin-left: 0; + } + +input[type="text"], select { margin: 0.75em 0 0; } +input[type="checkbox"], input[type="radio"], input[type="file"] { margin: 1em 0 0; } +input[type="checkbox"].enabler, input[type="radio"].enabler { margin-left: 1em; } + +input:disabled { color: #BBB; } + +#config_form input[type="text"].subitem { width: 4em; } +#config_form input[type="text"].subitem+.subitem { margin-left: 4px; } + +input[type="text"].added { width: 20em; } +label.added { + width: 265px; /* label area */ + height: 1em; + padding: 10px 370px 10px 1em; + margin-right: -360px; + text-align: right; + } + +ul.tabs { padding: 0; list-style: none; } +ul.tabs li { display: inline; } +ul.tabs li a, +ul.tabs li a.active:hover, +ul.tabs li a.active:active { + display: block; + float: left; + background: #1E4059; + color: #CCC; + font-size: 110%; + border-radius: 0.25em 0.25em 0 0; + margin: 0 4px 0 0; + padding: 2px 8px; + text-decoration: none; + font-family: georgia,"times new roman",times; + } +ul.tabs li a.active:link, +ul.tabs li a.active:visited { + background: #DDD; + color: #06F; + cursor: default; + margin-top: -4px; + padding-bottom: 4px; + padding-top: 4px; + } +ul.tabs li a:hover, +ul.tabs li a:active { + background: #000; + color: #FFF; + } + +fieldset { display: none; border: 1px solid #AAA; border-radius: 1em; } +fieldset legend { display: none; } + +.hilightable span { + display: block; + float: left; + width: 100%; + height: 1.3em; + background: rgba(225,255,0,1); + margin: 0 -100% -1em 0; + } + +#serial_stepper { padding-top: 0.75em; display: block; float: left; } +/*#SERIAL_PORT { display: none; }*/ + +/* Tooltips */ + +#tooltip { + display: none; + max-width: 30em; + padding: 8px; + border: 2px solid #73d699; + border-radius: 1em; + position: absolute; + z-index: 999; + font-family: sans-serif; + font-size: 85%; + color: #000; + line-height: 1.1; + background: #e2ff99; /* Old browsers */ + background: -moz-linear-gradient(top, #e2ff99 0%, #73d699 100%); /* FF3.6+ */ + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#e2ff99), color-stop(100%,#73d699)); /* Chrome,Safari4+ */ + background: -webkit-linear-gradient(top, #e2ff99 0%,#73d699 100%); /* Chrome10+,Safari5.1+ */ + background: -o-linear-gradient(top, #e2ff99 0%,#73d699 100%); /* Opera 11.10+ */ + background: -ms-linear-gradient(top, #e2ff99 0%,#73d699 100%); /* IE10+ */ + background: linear-gradient(to bottom, #e2ff99 0%,#73d699 100%); /* W3C */ + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e2ff99', endColorstr='#73d699',GradientType=0 ); /* IE6-9 */ + -webkit-box-shadow: 0px 6px 25px -4px rgba(0,0,0,0.75); + -moz-box-shadow: 0px 6px 25px -4px rgba(0,0,0,0.75); + box-shadow: 0px 6px 25px -4px rgba(0,0,0,0.75); + } +#tooltip>span { + position: absolute; + content: ""; + width: 0; + height: 0; + border-left: 8px solid transparent; + border-right: 8px solid transparent; + border-top: 8px solid #73d699; + z-index: 999; + bottom: -10px; + left: 20px; + } +#tooltip>strong { color: #00B; } + +/* Tooltips Checkbox */ + +#tipson { + width: auto; + height: auto; + padding: 0; + margin-right: 0; + float: right; + font-weight: bold; + font-size: 100%; + font-family: helvetica; + text-align: left; + cursor: pointer; + } +#tipson input { float: none; display: inline; cursor: pointer; } + +/* Config Text */ + +pre.config { + height: 25em; + padding: 10px; + border: 2px solid #888; + border-radius: 5px; + overflow: auto; + clear: both; + background-color: #FFF; + color: #000; + font-family: "Fira Mono", monospace; + font-size: small; + } + +/* Pre Headers */ + +h2 { + width: 100%; + margin: 12px -300px 4px 0; + padding: 0; + float: left; + } + +/* Disclosure Widget */ + +span.disclose, a.download, a.download-all {︎ + display: block; + float: right; + margin-top: 12px; + } + +span.disclose { + margin-right: -10px; /* total width */ + margin-left: 14px; + width: 0; + height: 0; + position: relative; + left: 3px; + top: 3px; + cursor: pointer; + border-left: 8px solid transparent; + border-right: 8px solid transparent; + border-top: 10px solid #000; + } +span.disclose.closed { + margin-right: -8px; /* total width */ + margin-left: 10px; + left: 0; + top: 0; + border-top: 8px solid transparent; + border-bottom: 8px solid transparent; + border-right: 10px solid #000; + } +span.disclose.almost { + -ms-transform: rotate(45deg); /* IE 9 */ + -webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */ + transform: rotate(45deg); + } +span.disclose.closed.almost { + left: 1px; + top: 3px; + -ms-transform: rotate(315deg); /* IE 9 */ + -webkit-transform: rotate(315deg); /* Chrome, Safari, Opera */ + transform: rotate(315deg); + } + +/* Download Button */ + +a.download, a.download-all { + visibility: hidden; + padding: 2px; + border: 1px solid #494; + border-radius: 4px; + margin: 12px 0 0; + background: #FFF; + color: #494; + font-family: sans-serif; + font-size: small; + font-weight: bold; + text-decoration: none; + } +a.download-all { margin: 9px 2em 0; color: #449; border-color: #449; } + +input[type="text"].one_of_2 { max-width: 15%; } +input[type="text"].one_of_3 { max-width: 10%; } +input[type="text"].one_of_4 { max-width: 7%; } + +select.one_of_2 { max-width: 15%; } +select.one_of_3 { max-width: 10%; } +select.one_of_4 { max-width: 14%; } +select.one_of_4+span.label+select.one_of_4+span.label { clear: both; margin-left: 265px; padding-left: 1.75em; } +select.one_of_4+span.label+select.one_of_4+span.label+select.one_of_4+span.label { clear: none; margin-left: 1em; padding-left: 0; } + +@media all and (min-width: 1140px) { + + #main { max-width: 10000px; } + + fieldset { float: left; width: 50%; height: auto; } + + #config_text, #config_adv_text { float: right; clear: right; width: 45%; } + + pre.config { height: 20em; } + + .disclose { display: none; } + + input[type="text"].one_of_2 { max-width: 15%; } + input[type="text"].one_of_3 { max-width: 9%; } + input[type="text"].one_of_4 { max-width: 8%; } + + select.one_of_2 { max-width: 15%; } + select.one_of_3 { max-width: 10%; } + select.one_of_4 { max-width: 16%; } + +} + +/*label.blocked, .blocked { display: none; }*/ + diff --git a/Marlin/configurator/css/logo.png b/Marlin/configurator/css/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..0618dc17ae4ab7842475d493592e8184fd9a77e9 GIT binary patch literal 1266 zcmVU8P*7-ZbZ>KLZ*U+lnSp_Ufq@}0xwybFAi#%#fq@|}KQEO56)-X|e7nZL z$iTqBa9P*U#mSX{G{Bl%P*lRez;J+pfx##xwK$o9f#C}S14DXwNkIt%17i#W1A|CX zc0maP17iUL1A|C*NRTrF17iyV0~1e4YDEbH0|SF|enDkXW_m`6f}y3QrGjHhep0GJ zaAk2xYHqQDXI^rCQ9*uDVo7QW0|Nup4h9AW240u^5(W3f%sd4n162kpgNVo|1qcff zJ_s=cNG>fZg9jx8g8+j9g8_pBLjXe}Lp{R+hNBE`7{wV~7)u#fFy3PlV+vxLz;uCG zm^qSpA@ds+OO_6nTdaDlt*rOhEZL^9ePa)2-_4=K(Z%tFGm-NGmm}8}ZcXk5JW@PU zd4+f<@d@)yL(o<5icqT158+-B6_LH7;i6x}CW#w~Uy-Pgl#@Irl`kzV zeL|*8R$ca%T%Wv){2zs_iiJvgN^h0dsuZZ2sQy$tsNSU!s;Q*;LF<6_B%M@UD?LHI zSNcZ`78uqV#TeU~$eS{ozBIdFzSClfs*^S+dw;4dus<{M;#|MXC)T}S9v!D zcV!QCPhBq)ZyO(X-(bH4|NMaZz==UigLj2o41F2S6d@OB6%`R(5i>J(Puzn9wnW{e zu;hl6HK{k#IWjCVGqdJqU(99Cv(K+6*i`tgSi2;vbXD1#3jNBGs$DgVwO(~o>mN4i zHPtkqZIx>)Y(Ls5-Br|mx>vQYvH$Kwn@O`L|D75??eGkZnfg$5<;Xeg_o%+-I&+-3%01W^SH2RkDT>t<8AY({UO#lFTB>(_`g8%^e z{{R4h=>PzAFaQARU;qF*m;eA5Z<1fdMgRZ-R7pfZRCwC#nZXi+APhv=jQ{`3+e>SU zEwExT0#k1aB9BcrieUOYke@DaZ0n+BfG@n6D53S@jyIo#3Zl)6r_I^s3(a$gHoJ+i z8O9t-4w!>lD)I5aQuq5`YrT4&lOvip zoaVIG{TQOs7N=c(wXgXxo5iy4C)Wy? c%(Cq<0NcG|Qs2|@asU7T07*qoM6N<$f&+;(;s5{u literal 0 HcmV?d00001 diff --git a/Marlin/configurator/index.html b/Marlin/configurator/index.html new file mode 100644 index 0000000..5435391 --- /dev/null +++ b/Marlin/configurator/index.html @@ -0,0 +1,129 @@ + + + + + Marlin Firmware Configurator + + + + + + + + + + + + +
+

Marlin Configurator

+

Select presets (coming soon), modify, and download.

+ +
+
+ +
+ +
+ + + + Download Zip + +
+ Info +
+ +
+ Machine + +
+ + + + + + + + + + + + + + + + + + +
+ +
+ Homing +
+ +
+ Temperature + + + + + + + + + + +
+ +
+ Extruder +
+ +
+ LCD / SD +
+ +
+ Bed Leveling +
+ +
+ FW Retract +
+ +
+ TMC +
+ +
+ L6470 +
+ +
+ Extras +
+ +
+ More… +
+ +
+

Configuration.h

+ + Download +

+        
+ +
+

Configuration_adv.h

+ + Download +

+        
+ +
+
+
+ + diff --git a/Marlin/configurator/js/FileSaver.min.js b/Marlin/configurator/js/FileSaver.min.js new file mode 100644 index 0000000..f731960 --- /dev/null +++ b/Marlin/configurator/js/FileSaver.min.js @@ -0,0 +1,2 @@ +/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ +var saveAs=saveAs||typeof navigator!=="undefined"&&navigator.msSaveOrOpenBlob&&navigator.msSaveOrOpenBlob.bind(navigator)||function(view){"use strict";if(typeof navigator!=="undefined"&&/MSIE [1-9]\./.test(navigator.userAgent)){return}var doc=view.document,get_URL=function(){return view.URL||view.webkitURL||view},save_link=doc.createElementNS("http://www.w3.org/1999/xhtml","a"),can_use_save_link="download"in save_link,click=function(node){var event=doc.createEvent("MouseEvents");event.initMouseEvent("click",true,false,view,0,0,0,0,0,false,false,false,false,0,null);node.dispatchEvent(event)},webkit_req_fs=view.webkitRequestFileSystem,req_fs=view.requestFileSystem||webkit_req_fs||view.mozRequestFileSystem,throw_outside=function(ex){(view.setImmediate||view.setTimeout)(function(){throw ex},0)},force_saveable_type="application/octet-stream",fs_min_size=0,arbitrary_revoke_timeout=500,revoke=function(file){var revoker=function(){if(typeof file==="string"){get_URL().revokeObjectURL(file)}else{file.remove()}};if(view.chrome){revoker()}else{setTimeout(revoker,arbitrary_revoke_timeout)}},dispatch=function(filesaver,event_types,event){event_types=[].concat(event_types);var i=event_types.length;while(i--){var listener=filesaver["on"+event_types[i]];if(typeof listener==="function"){try{listener.call(filesaver,event||filesaver)}catch(ex){throw_outside(ex)}}}},FileSaver=function(blob,name){var filesaver=this,type=blob.type,blob_changed=false,object_url,target_view,dispatch_all=function(){dispatch(filesaver,"writestart progress write writeend".split(" "))},fs_error=function(){if(blob_changed||!object_url){object_url=get_URL().createObjectURL(blob)}if(target_view){target_view.location.href=object_url}else{var new_tab=view.open(object_url,"_blank");if(new_tab==undefined&&typeof safari!=="undefined"){view.location.href=object_url}}filesaver.readyState=filesaver.DONE;dispatch_all();revoke(object_url)},abortable=function(func){return function(){if(filesaver.readyState!==filesaver.DONE){return func.apply(this,arguments)}}},create_if_not_found={create:true,exclusive:false},slice;filesaver.readyState=filesaver.INIT;if(!name){name="download"}if(can_use_save_link){object_url=get_URL().createObjectURL(blob);save_link.href=object_url;save_link.download=name;click(save_link);filesaver.readyState=filesaver.DONE;dispatch_all();revoke(object_url);return}if(view.chrome&&type&&type!==force_saveable_type){slice=blob.slice||blob.webkitSlice;blob=slice.call(blob,0,blob.size,force_saveable_type);blob_changed=true}if(webkit_req_fs&&name!=="download"){name+=".download"}if(type===force_saveable_type||webkit_req_fs){target_view=view}if(!req_fs){fs_error();return}fs_min_size+=blob.size;req_fs(view.TEMPORARY,fs_min_size,abortable(function(fs){fs.root.getDirectory("saved",create_if_not_found,abortable(function(dir){var save=function(){dir.getFile(name,create_if_not_found,abortable(function(file){file.createWriter(abortable(function(writer){writer.onwriteend=function(event){target_view.location.href=file.toURL();filesaver.readyState=filesaver.DONE;dispatch(filesaver,"writeend",event);revoke(file)};writer.onerror=function(){var error=writer.error;if(error.code!==error.ABORT_ERR){fs_error()}};"writestart progress write abort".split(" ").forEach(function(event){writer["on"+event]=filesaver["on"+event]});writer.write(blob);filesaver.abort=function(){writer.abort();filesaver.readyState=filesaver.DONE};filesaver.readyState=filesaver.WRITING}),fs_error)}),fs_error)};dir.getFile(name,{create:false},abortable(function(file){file.remove();save()}),abortable(function(ex){if(ex.code===ex.NOT_FOUND_ERR){save()}else{fs_error()}}))}),fs_error)}),fs_error)},FS_proto=FileSaver.prototype,saveAs=function(blob,name){return new FileSaver(blob,name)};FS_proto.abort=function(){var filesaver=this;filesaver.readyState=filesaver.DONE;dispatch(filesaver,"abort")};FS_proto.readyState=FS_proto.INIT=0;FS_proto.WRITING=1;FS_proto.DONE=2;FS_proto.error=FS_proto.onwritestart=FS_proto.onprogress=FS_proto.onwrite=FS_proto.onabort=FS_proto.onerror=FS_proto.onwriteend=null;return saveAs}(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||this.content);if(typeof module!=="undefined"&&module.exports){module.exports.saveAs=saveAs}else if(typeof define!=="undefined"&&define!==null&&define.amd!=null){define([],function(){return saveAs})} diff --git a/Marlin/configurator/js/binaryfileuploader.js b/Marlin/configurator/js/binaryfileuploader.js new file mode 100644 index 0000000..0a1f38f --- /dev/null +++ b/Marlin/configurator/js/binaryfileuploader.js @@ -0,0 +1,79 @@ +function BinaryFileUploader(o) { + this.options = null; + + + this._defaultOptions = { + element: null, // HTML file element + onFileLoad: function(file) { + console.log(file.toString()); + } + }; + + + this._init = function(o) { + if (!this.hasFileUploaderSupport()) return; + + this._verifyDependencies(); + + this.options = this._mergeObjects(this._defaultOptions, o); + this._verifyOptions(); + + this.addFileChangeListener(); + } + + + this.hasFileUploaderSupport = function() { + return !!(window.File && window.FileReader && window.FileList && window.Blob); + } + + this.addFileChangeListener = function() { + this.options.element.addEventListener( + 'change', + this._bind(this, this.onFileChange) + ); + } + + this.onFileChange = function(e) { + // TODO accept multiple files + var file = e.target.files[0], + reader = new FileReader(); + + reader.onload = this._bind(this, this.onFileLoad); + reader.readAsBinaryString(file); + } + + this.onFileLoad = function(e) { + var content = e.target.result, + string = new BinaryString(content); + this.options.onFileLoad(string); + } + + + this._mergeObjects = function(starting, override) { + var merged = starting; + for (key in override) merged[key] = override[key]; + + return merged; + } + + this._verifyOptions = function() { + if (!(this.options.element && this.options.element.type && this.options.element.type === 'file')) { + throw 'Invalid element param in options. Must be a file upload DOM element'; + } + + if (typeof this.options.onFileLoad !== 'function') { + throw 'Invalid onFileLoad param in options. Must be a function'; + } + } + + this._verifyDependencies = function() { + if (!window.BinaryString) throw 'BinaryString is missing. Check that you\'ve correctly included it'; + } + + // helper function for binding methods to objects + this._bind = function(object, method) { + return function() {return method.apply(object, arguments);}; + } + + this._init(o); +} diff --git a/Marlin/configurator/js/binarystring.js b/Marlin/configurator/js/binarystring.js new file mode 100644 index 0000000..06af64f --- /dev/null +++ b/Marlin/configurator/js/binarystring.js @@ -0,0 +1,168 @@ +function BinaryString(source) { + this._source = null; + this._bytes = []; + this._pos = 0; + this._length = 0; + + this._init = function(source) { + this._source = source; + this._bytes = this._stringToBytes(this._source); + this._length = this._bytes.length; + } + + this.current = function() {return this._pos;} + + this.rewind = function() {return this.jump(0);} + this.end = function() {return this.jump(this.length() - 1);} + this.next = function() {return this.jump(this.current() + 1);} + this.prev = function() {return this.jump(this.current() - 1);} + + this.jump = function(pos) { + if (pos < 0 || pos >= this.length()) return false; + + this._pos = pos; + return true; + } + + this.readByte = function(pos) { + pos = (typeof pos == 'number') ? pos : this.current(); + return this.readBytes(1, pos)[0]; + } + + this.readBytes = function(length, pos) { + length = length || 1; + pos = (typeof pos == 'number') ? pos : this.current(); + + if (pos > this.length() || + pos < 0 || + length <= 0 || + pos + length > this.length() || + pos + length < 0 + ) { + return false; + } + + var bytes = []; + + for (var i = pos; i < pos + length; i++) { + bytes.push(this._bytes[i]); + } + + return bytes; + } + + this.length = function() {return this._length;} + + this.toString = function() { + var string = '', + length = this.length(); + + for (var i = 0; i < length; i++) { + string += String.fromCharCode(this.readByte(i)); + } + + return string; + } + + this.toUtf8 = function() { + var inc = 0, + string = '', + length = this.length(); + + // determine if first 3 characters are the BOM + // then skip them in output if so + if (length >= 3 && + this.readByte(0) === 0xEF && + this.readByte(1) === 0xBB && + this.readByte(2) === 0xBF + ) { + inc = 3; + } + + for (; inc < length; inc++) { + var byte1 = this.readByte(inc), + byte2 = 0, + byte3 = 0, + byte4 = 0, + code1 = 0, + code2 = 0, + point = 0; + + switch (true) { + // single byte character; same as ascii + case (byte1 < 0x80): + code1 = byte1; + break; + + // 2 byte character + case (byte1 >= 0xC2 && byte1 < 0xE0): + byte2 = this.readByte(++inc); + + code1 = ((byte1 & 0x1F) << 6) + + (byte2 & 0x3F); + break; + + // 3 byte character + case (byte1 >= 0xE0 && byte1 < 0xF0): + byte2 = this.readByte(++inc); + byte3 = this.readByte(++inc); + + code1 = ((byte1 & 0xFF) << 12) + + ((byte2 & 0x3F) << 6) + + (byte3 & 0x3F); + break; + + // 4 byte character + case (byte1 >= 0xF0 && byte1 < 0xF5): + byte2 = this.readByte(++inc); + byte3 = this.readByte(++inc); + byte4 = this.readByte(++inc); + + point = ((byte1 & 0x07) << 18) + + ((byte2 & 0x3F) << 12) + + ((byte3 & 0x3F) << 6) + + (byte4 & 0x3F) + point -= 0x10000; + + code1 = (point >> 10) + 0xD800; + code2 = (point & 0x3FF) + 0xDC00; + break; + + default: + throw 'Invalid byte ' + this._byteToString(byte1) + ' whilst converting to UTF-8'; + break; + } + + string += (code2) ? String.fromCharCode(code1, code2) + : String.fromCharCode(code1); + } + + return string; + } + + this.toArray = function() {return this.readBytes(this.length() - 1, 0);} + + + this._stringToBytes = function(str) { + var bytes = [], + chr = 0; + + for (var i = 0; i < str.length; i++) { + chr = str.charCodeAt(i); + bytes.push(chr & 0xFF); + } + + return bytes; + } + + this._byteToString = function(byte) { + var asString = byte.toString(16).toUpperCase(); + while (asString.length < 2) { + asString = '0' + asString; + } + + return '0x' + asString; + } + + this._init(source); +} diff --git a/Marlin/configurator/js/configurator.js b/Marlin/configurator/js/configurator.js new file mode 100644 index 0000000..1a0da92 --- /dev/null +++ b/Marlin/configurator/js/configurator.js @@ -0,0 +1,1432 @@ +/** + * configurator.js + * + * Marlin Configuration Utility + * - Web form for entering configuration options + * - A reprap calculator to calculate movement values + * - Uses HTML5 to generate downloadables in Javascript + * - Reads and parses standard configuration files from local folders + * + * Supporting functions + * - Parser to read Marlin Configuration.h and Configuration_adv.h files + * - Utilities to replace values in configuration files + */ + +"use strict"; + +$(function(){ + +/** + * Github API useful GET paths. (Start with "https://api.github.com/repos/:owner/:repo/") + * + * contributors Get a list of contributors + * tags Get a list of tags + * contents/[path]?ref=branch/tag/commit Get the contents of a file + */ + + // GitHub + // Warning! Limited to 60 requests per hour! +var config = { + type: 'github', + host: 'https://api.github.com', + owner: 'MarlinFirmware', + repo: 'Marlin', + ref: 'Development', + path: 'Marlin/configurator/config' +}; +/**/ + +/* // Remote +var config = { + type: 'remote', + host: 'http://www.thinkyhead.com', + path: '_marlin/config' +}; +/**/ + +/* // Local +var config = { + type: 'local', + path: 'config' +}; +/**/ + +function github_command(conf, command, path) { + var req = conf.host+'/repos/'+conf.owner+'/'+conf.repo+'/'+command; + if (path) req += '/' + path; + return req; +} +function config_path(item) { + var path = '', ref = ''; + switch(config.type) { + case 'github': + path = github_command(config, 'contents', config.path); + if (config.ref !== undefined) ref = '?ref=' + config.ref; + break; + case 'remote': + path = config.host + '/' + config.path + '/'; + break; + case 'local': + path = config.path + '/'; + break; + } + return path + '/' + item + ref; +} + +// Extend builtins +String.prototype.lpad = function(len, chr) { + if (chr === undefined) { chr = ' '; } + var s = this+'', need = len - s.length; + if (need > 0) { s = new Array(need+1).join(chr) + s; } + return s; +}; + +String.prototype.prePad = function(len, chr) { return len ? this.lpad(len, chr) : this; }; +String.prototype.zeroPad = function(len) { return this.prePad(len, '0'); }; +String.prototype.toHTML = function() { return jQuery('
').text(this).html(); }; +String.prototype.regEsc = function() { return this.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&"); } +String.prototype.lineCount = function(ind) { var len = (ind === undefined ? this : this.substr(0,ind*1)).split(/\r?\n|\r/).length; return len > 0 ? len - 1 : 0; }; +String.prototype.line = function(num) { var arr = this.split(/\r?\n|\r/); return num < arr.length ? arr[1*num] : ''; }; +String.prototype.replaceLine = function(num,txt) { var arr = this.split(/\r?\n|\r/); if (num < arr.length) { arr[num] = txt; return arr.join('\n'); } else return this; } +String.prototype.toLabel = function() { return this.replace(/[\[\]]/g, '').replace(/_/g, ' ').toTitleCase(); } +String.prototype.toTitleCase = function() { return this.replace(/([A-Z])(\w+)/gi, function(m,p1,p2) { return p1.toUpperCase() + p2.toLowerCase(); }); } +Number.prototype.limit = function(m1, m2) { + if (m2 == null) return this > m1 ? m1 : this; + return this < m1 ? m1 : this > m2 ? m2 : this; +}; +Date.prototype.fileStamp = function(filename) { + var fs = this.getFullYear() + + ((this.getMonth()+1)+'').zeroPad(2) + + (this.getDate()+'').zeroPad(2) + + (this.getHours()+'').zeroPad(2) + + (this.getMinutes()+'').zeroPad(2) + + (this.getSeconds()+'').zeroPad(2); + + if (filename !== undefined) + return filename.replace(/^(.+)(\.\w+)$/g, '$1-['+fs+']$2'); + + return fs; +} + +/** + * selectField.addOptions takes an array or keyed object + */ +$.fn.extend({ + addOptions: function(arrObj) { + return this.each(function() { + var sel = $(this); + var isArr = Object.prototype.toString.call(arrObj) == "[object Array]"; + $.each(arrObj, function(k, v) { + sel.append( $('