├── .gitignore ├── .vscode ├── c_cpp_properties.json ├── extensions.json └── launch.json ├── COPYING ├── Makefile ├── README.md ├── build └── .gitignore ├── doc ├── csv │ ├── alarm_codes_en_US.csv │ ├── build_option_codes_en_US.csv │ ├── error_codes_en_US.csv │ └── setting_codes_en_US.csv ├── images │ ├── Mega-5X-logo.svg │ ├── arduino-mega-pinout-detail.png │ ├── arduino-mega-pinout-diagram.png │ └── grbl-Mega-5X_Wiring.svg ├── log │ ├── commit_log_v0.7.txt │ ├── commit_log_v0.8c.txt │ ├── commit_log_v0.9g.txt │ ├── commit_log_v0.9i.txt │ ├── commit_log_v0.9j.txt │ ├── commit_log_v1.0b.txt │ ├── commit_log_v1.0c.txt │ ├── commit_log_v1.0d.txt │ └── commit_log_v1.1.txt ├── markdown │ ├── change_summary.md │ ├── commands.md │ ├── interface.md │ ├── jogging.md │ ├── laser_mode.md │ └── settings.md └── script │ ├── fit_nonlinear_spindle.py │ ├── simple_stream.py │ └── stream.py ├── grbl ├── config.h ├── coolant_control.c ├── coolant_control.h ├── cpu_map.h ├── defaults.h ├── eeprom.c ├── eeprom.h ├── examples │ └── grblUpload │ │ ├── grblUpload.ino │ │ └── license.txt ├── gcode.c ├── gcode.h ├── grbl.h ├── jog.c ├── jog.h ├── limits.c ├── limits.h ├── main.c ├── motion_control.c ├── motion_control.h ├── nuts_bolts.c ├── nuts_bolts.h ├── planner.c ├── planner.h ├── print.c ├── print.h ├── probe.c ├── probe.h ├── protocol.c ├── protocol.h ├── report.c ├── report.h ├── serial.c ├── serial.h ├── settings.c ├── settings.h ├── sleep.c ├── sleep.h ├── spindle_control.c ├── spindle_control.h ├── stepper.c ├── stepper.h ├── system.c └── system.h └── platformio.ini /.gitignore: -------------------------------------------------------------------------------- 1 | *.hex 2 | *.zip 3 | *.o 4 | *.elf 5 | *.DS_Store 6 | *.d 7 | .grbl* 8 | 9 | README.md 10 | -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "!!! WARNING !!! AUTO-GENERATED FILE, PLEASE DO NOT MODIFY IT AND USE https://docs.platformio.org/page/projectconf/section_env_build.html#build-flags" 5 | }, 6 | { 7 | "name": "Win32", 8 | "includePath": [ 9 | "c:/Users/perner/My Projects/grbl-Mega-5X/grbl", 10 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/cores/arduino", 11 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/variants/mega", 12 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/libraries/EEPROM/src", 13 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/libraries/HID/src", 14 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/libraries/SPI/src", 15 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/libraries/SoftwareSerial/src", 16 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/libraries/Wire/src", 17 | "C:/Users/perner/.platformio/packages/tool-unity", 18 | "" 19 | ], 20 | "browse": { 21 | "limitSymbolsToIncludedHeaders": true, 22 | "path": [ 23 | "c:/Users/perner/My Projects/grbl-Mega-5X/grbl", 24 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/cores/arduino", 25 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/variants/mega", 26 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/libraries/EEPROM/src", 27 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/libraries/HID/src", 28 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/libraries/SPI/src", 29 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/libraries/SoftwareSerial/src", 30 | "C:/Users/perner/.platformio/packages/framework-arduino-avr/libraries/Wire/src", 31 | "C:/Users/perner/.platformio/packages/tool-unity", 32 | "" 33 | ] 34 | }, 35 | "defines": [ 36 | "PLATFORMIO=40304", 37 | "ARDUINO_AVR_MEGA2560", 38 | "F_CPU=16000000L", 39 | "ARDUINO_ARCH_AVR", 40 | "ARDUINO=10808", 41 | "__AVR_ATmega2560__", 42 | "" 43 | ], 44 | "intelliSenseMode": "clang-x64", 45 | "cStandard": "c11", 46 | "cppStandard": "c++11", 47 | "compilerPath": "C:/Users/perner/.platformio/packages/toolchain-atmelavr/bin/avr-gcc.exe", 48 | "compilerArgs": [ 49 | "-mmcu=atmega2560", 50 | "" 51 | ] 52 | } 53 | ], 54 | "version": 4 55 | } 56 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "platformio.platformio-ide" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | // AUTOMATICALLY GENERATED FILE. PLEASE DO NOT MODIFY IT MANUALLY 2 | 3 | // PIO Unified Debugger 4 | // 5 | // Documentation: https://docs.platformio.org/page/plus/debugging.html 6 | // Configuration: https://docs.platformio.org/page/projectconf/section_env_debug.html 7 | 8 | { 9 | "version": "0.2.0", 10 | "configurations": [ 11 | { 12 | "type": "platformio-debug", 13 | "request": "launch", 14 | "name": "PIO Debug", 15 | "executable": "c:/Users/perner/My Projects/grbl-Mega-5X/build/build/megaatmega2560/firmware.elf", 16 | "toolchainBinDir": "C:/Users/perner/.platformio/packages/toolchain-atmelavr/bin", 17 | "preLaunchTask": { 18 | "type": "PlatformIO", 19 | "task": "Pre-Debug" 20 | }, 21 | "internalConsoleOptions": "openOnSessionStart" 22 | }, 23 | { 24 | "type": "platformio-debug", 25 | "request": "launch", 26 | "name": "PIO Debug (skip Pre-Debug)", 27 | "executable": "c:/Users/perner/My Projects/grbl-Mega-5X/build/build/megaatmega2560/firmware.elf", 28 | "toolchainBinDir": "C:/Users/perner/.platformio/packages/toolchain-atmelavr/bin", 29 | "internalConsoleOptions": "openOnSessionStart" 30 | } 31 | ] 32 | } -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Part of Grbl 2 | # 3 | # Copyright (c) 2009-2011 Simen Svale Skogsrud 4 | # Copyright (c) 2012-2015 Sungeun K. Jeon 5 | # 6 | # Grbl is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Grbl is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with Grbl. If not, see . 18 | 19 | 20 | # This is a prototype Makefile. Modify it according to your needs. 21 | # You should at least check the settings for 22 | # DEVICE ....... The AVR device you compile for 23 | # CLOCK ........ Target AVR clock rate in Hertz 24 | # OBJECTS ...... The object files created from your source files. This list is 25 | # usually the same as the list of source files with suffix ".o". 26 | # PROGRAMMER ... Options to avrdude which define the hardware you use for 27 | # uploading to the AVR and the interface where this hardware 28 | # is connected. 29 | # FUSES ........ Parameters for avrdude to flash the fuses appropriately. 30 | 31 | DEVICE ?= atmega2560 32 | CLOCK = 16000000L 33 | ###PROGRAMMER ?= -c avrisp2 -P usb 34 | PROGRAMMER ?= -D -v -c avrisp2 -P /dev/ttyUSB0 35 | SOURCE = main.c motion_control.c gcode.c spindle_control.c coolant_control.c serial.c \ 36 | protocol.c stepper.c eeprom.c settings.c planner.c nuts_bolts.c limits.c \ 37 | print.c probe.c report.c system.c sleep.c jog.c 38 | BUILDDIR = build 39 | SOURCEDIR = grbl 40 | # FUSES = -U hfuse:w:0xd9:m -U lfuse:w:0x24:m 41 | FUSES = -U hfuse:w:0xd2:m -U lfuse:w:0xff:m 42 | 43 | # Tune the lines below only if you know what you are doing: 44 | 45 | AVRDUDE = avrdude $(PROGRAMMER) -p $(DEVICE) -B 10 -F 46 | 47 | # Compile flags for avr-gcc v4.8.1. Does not produce -flto warnings. 48 | # COMPILE = avr-gcc -Wall -Os -DF_CPU=$(CLOCK) -mmcu=$(DEVICE) -I. -ffunction-sections 49 | 50 | # Compile flags for avr-gcc v4.9.2 compatible with the IDE. Or if you don't care about the warnings. 51 | COMPILE = avr-gcc -Wall -Os -DF_CPU=$(CLOCK) -mmcu=$(DEVICE) -I. -ffunction-sections -flto 52 | 53 | 54 | OBJECTS = $(addprefix $(BUILDDIR)/,$(notdir $(SOURCE:.c=.o))) 55 | 56 | # symbolic targets: 57 | all: grbl.hex 58 | 59 | $(BUILDDIR)/%.o: $(SOURCEDIR)/%.c 60 | $(COMPILE) -MMD -MP -c $< -o $@ 61 | 62 | .S.o: 63 | $(COMPILE) -x assembler-with-cpp -c $< -o $(BUILDDIR)/$@ 64 | # "-x assembler-with-cpp" should not be necessary since this is the default 65 | # file type for the .S (with capital S) extension. However, upper case 66 | # characters are not always preserved on Windows. To ensure WinAVR 67 | # compatibility define the file type manually. 68 | 69 | #.c.s: 70 | $(COMPILE) -S $< -o $(BUILDDIR)/$@ 71 | 72 | flash: all 73 | $(AVRDUDE) -U flash:w:grbl.hex:i 74 | 75 | fuse: 76 | $(AVRDUDE) $(FUSES) 77 | 78 | # Xcode uses the Makefile targets "", "clean" and "install" 79 | install: flash fuse 80 | 81 | # if you use a bootloader, change the command below appropriately: 82 | load: all 83 | bootloadHID grbl.hex 84 | 85 | clean: 86 | rm -f grbl.hex $(BUILDDIR)/*.o $(BUILDDIR)/*.d $(BUILDDIR)/*.elf 87 | 88 | # file targets: 89 | $(BUILDDIR)/main.elf: $(OBJECTS) 90 | $(COMPILE) -o $(BUILDDIR)/main.elf $(OBJECTS) -lm -Wl,--gc-sections 91 | 92 | grbl.hex: $(BUILDDIR)/main.elf 93 | rm -f grbl.hex 94 | avr-objcopy -j .text -j .data -O ihex $(BUILDDIR)/main.elf grbl.hex 95 | avr-size --format=berkeley $(BUILDDIR)/main.elf 96 | # If you have an EEPROM section, you must also create a hex file for the 97 | # EEPROM and add it to the "flash" target. 98 | 99 | # Targets for code debugging and analysis: 100 | disasm: main.elf 101 | avr-objdump -d $(BUILDDIR)/main.elf 102 | 103 | cpp: 104 | $(COMPILE) -E $(SOURCEDIR)/main.c 105 | 106 | # include generated header dependencies 107 | -include $(BUILDDIR)/$(OBJECTS:.o=.d) 108 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![GitHub Logo](https://github.com/fra589/grbl-Mega-5X/blob/edge/doc/images/Mega-5X-logo.svg) 2 | 3 | *** 4 | 5 | Grbl is a no-compromise, high performance, low cost alternative to parallel-port-based motion control for CNC milling. This version of Grbl runs on an Arduino Mega2560 only. 6 | 7 | The controller is written in highly optimized C utilizing every clever feature of the AVR-chips to achieve precise timing and asynchronous operation. It is able to maintain up to 30kHz of stable, jitter free control pulses. 8 | 9 | It accepts standards-compliant g-code and has been tested with the output of several CAM tools with no problems. Arcs, circles and helical motion are fully supported, as well as, all other primary g-code commands. Macro functions, variables, and most canned cycles are not supported, but we think GUIs can do a much better job at translating them into straight g-code anyhow. 10 | 11 | Grbl includes full acceleration management with look ahead. That means the controller will look up to 24 motions into the future and plan its velocities ahead to deliver smooth acceleration and jerk-free cornering. 12 | 13 | * [Licensing](https://github.com/fra589/grbl-Mega-5X/blob/edge/COPYING): Grbl is free software, released under the GPLv3 license. 14 | 15 | * For more information and help, check out our **[Wiki pages!](https://github.com/gnea/grbl/wiki)** If you find that the information is out-dated, please to help us keep it updated by editing it or notifying our community! Thanks! 16 | 17 | * Lead Developer: Gauthier Brière (France) aka @fra589 18 | 19 | * Built on the wonderful Grbl v1.1f (2017) firmware originally written by Simen Svale Skogsrud (Norway) and maintained by Sungeun "Sonny" Jeon, Ph.D. (USA) aka @chamnit 20 | 21 | *** 22 | 23 | ##Update Summary for v1.1 24 | - **IMPORTANT:** Your EEPROM will be wiped and restored with new settings. This is due to the addition of two new spindle speed '$' settings. 25 | 26 | - **Real-time Overrides** : Alters the machine running state immediately with feed, rapid, spindle speed, spindle stop, and coolant toggle controls. This awesome new feature is common only on industrial machines, often used to optimize speeds and feeds while a job is running. Most hobby CNC's try to mimic this behavior, but usually have large amounts of lag. Grbl executes overrides in realtime and within tens of milliseconds. 27 | 28 | - **Jogging Mode** : The new jogging commands are independent of the g-code parser, so that the parser state doesn't get altered and cause a potential crash if not restored properly. Documentation is included on how this works and how it can be used to control your machine via a joystick or rotary dial with a low-latency, satisfying response. 29 | 30 | - **Laser Mode** : The new "laser" mode will cause Grbl to move continuously through consecutive G1, G2, and G3 commands with spindle speed changes. When "laser" mode is disabled, Grbl will instead come to a stop to ensure a spindle comes up to speed properly. Spindle speed overrides also work with laser mode so you can tweak the laser power, if you need to during the job. Switch between "laser" mode and "normal" mode via a `$` setting. 31 | 32 | - **Dynamic Laser Power Scaling with Speed** : If your machine has low accelerations, Grbl will automagically scale the laser power based on how fast Grbl is traveling, so you won't have burnt corners when your CNC has to make a turn! Enabled by the `M4` spindle CCW command when laser mode is enabled! 33 | 34 | - **Sleep Mode** : Grbl may now be put to "sleep" via a `$SLP` command. This will disable everything, including the stepper drivers. Nice to have when you are leaving your machine unattended and want to power down everything automatically. Only a reset exits the sleep state. 35 | 36 | - **Significant Interface Improvements**: Tweaked to increase overall performance, include lots more real-time data, and to simplify maintaining and writing GUIs. Based on direct feedback from multiple GUI developers and bench performance testing. _NOTE: GUIs need to specifically update their code to be compatible with v1.1 and later._ 37 | 38 | - **New Status Reports**: To account for the additional override data, status reports have been tweaked to cram more data into it, while still being smaller than before. Documentation is included, outlining how it has been changed. 39 | - **Improved Error/Alarm Feedback** : All Grbl error and alarm messages have been changed to providing a code. Each code is associated with a specific problem, so users will know exactly what is wrong without having to guess. Documentation and an easy to parse CSV is included in the repo. 40 | - **Extended-ASCII realtime commands** : All overrides and future real-time commands are defined in the extended-ASCII character space. Unfortunately not easily type-able on a keyboard, but helps prevent accidental commands from a g-code file having these characters and gives lots of space for future expansion. 41 | - **Message Prefixes** : Every message type from Grbl has a unique prefix to help GUIs immediately determine what the message is and parse it accordingly without having to know context. The prior interface had several instances of GUIs having to figure out the meaning of a message, which made everything more complicated than it needed to be. 42 | 43 | - New OEM specific features, such as safety door parking, single configuration file build option, EEPROM restrictions and restoring controls, and storing product data information. 44 | 45 | - New safety door parking motion as a compile-option. Grbl will retract, disable the spindle/coolant, and park near Z max. When resumed, it will perform these task in reverse order and continue the program. Highly configurable, even to add more than one parking motion. See config.h for details. 46 | 47 | - New '$' Grbl settings for max and min spindle rpm. Allows for tweaking the PWM output to more closely match true spindle rpm. When max rpm is set to zero or less than min rpm, the PWM pin D11 will act like a simple enable on/off output. 48 | 49 | - Updated G28 and G30 behavior from NIST to LinuxCNC g-code description. In short, if a intermediate motion is specified, only the axes specified will move to the stored coordinates, not all axes as before. 50 | 51 | - Lots of minor bug fixes and refactoring to make the code more efficient and flexible. 52 | 53 | 54 | ``` 55 | List of Supported G-Codes in Grbl v1.1: 56 | - Non-Modal Commands: G4, G10L2, G10L20, G28, G30, G28.1, G30.1, G53, G92, G92.1 57 | - Motion Modes: G0, G1, G2, G3, G38.2, G38.3, G38.4, G38.5, G80 58 | - Feed Rate Modes: G93, G94 59 | - Unit Modes: G20, G21 60 | - Distance Modes: G90, G91 61 | - Arc IJK Distance Modes: G91.1 62 | - Plane Select Modes: G17, G18, G19 63 | - Tool Length Offset Modes: G43.1, G49 64 | - Cutter Compensation Modes: G40 65 | - Coordinate System Modes: G54, G55, G56, G57, G58, G59 66 | - Control Modes: G61 67 | - Program Flow: M0, M1, M2, M30* 68 | - Coolant Control: M7*, M8, M9 69 | - Spindle Control: M3, M4, M5 70 | - Valid Non-Command Words: F, I, J, K, L, N, P, R, S, T, X, Y, Z, A, B, C 71 | ``` 72 | 73 | ------------- 74 | Grbl-Mega-5X is an open-source project and fueled by the free-time of our intrepid administrators and altruistic users. If you'd like to donate, all proceeds will be used to help fund supporting hardware and testing equipment. Thank you! 75 | 76 | [![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://paypal.me/pools/c/842hNSm2It) 77 | 78 | ## Updated to use platformio 79 | 80 | build using the following commands 81 | 82 | ``` 83 | $pio run 84 | ``` 85 | Upload to your board using 86 | 87 | ``` 88 | $pio run --target upload 89 | ``` 90 | -------------------------------------------------------------------------------- /build/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | * 3 | # Except this file 4 | !.gitignore -------------------------------------------------------------------------------- /doc/csv/alarm_codes_en_US.csv: -------------------------------------------------------------------------------- 1 | "Alarm Code in v1.1+"," Alarm Message in v1.0-"," Alarm Description" 2 | "1","Hard limit","Hard limit has been triggered. Machine position is likely lost due to sudden halt. Re-homing is highly recommended." 3 | "2","Soft limit","Soft limit alarm. G-code motion target exceeds machine travel. Machine position retained. Alarm may be safely unlocked." 4 | "3","Abort during cycle","Reset while in motion. Machine position is likely lost due to sudden halt. Re-homing is highly recommended." 5 | "4","Probe fail","Probe fail. Probe is not in the expected initial state before starting probe cycle when G38.2 and G38.3 is not triggered and G38.4 and G38.5 is triggered." 6 | "5","Probe fail","Probe fail. Probe did not contact the workpiece within the programmed travel for G38.2 and G38.4." 7 | "6","Homing fail","Homing fail. The active homing cycle was reset." 8 | "7","Homing fail","Homing fail. Safety door was opened during homing cycle." 9 | "8","Homing fail","Homing fail. Pull off travel failed to clear limit switch. Try increasing pull-off setting or check wiring." 10 | "9","Homing fail","Homing fail. Could not find limit switch within search distances. Try increasing max travel, decreasing pull-off distance, or check wiring." 11 | -------------------------------------------------------------------------------- /doc/csv/build_option_codes_en_US.csv: -------------------------------------------------------------------------------- 1 | "OPT: Code"," Build-Option Description","State" 2 | "V","Variable spindle","Enabled" 3 | "N","Line numbers","Enabled" 4 | "M","Mist coolant M7","Enabled" 5 | "C","CoreXY","Enabled" 6 | "P","Parking motion","Enabled" 7 | "Z","Homing force origin","Enabled" 8 | "H","Homing single axis commands","Enabled" 9 | "T","Two limit switches on axis","Enabled" 10 | "A","Allow feed rate overrides in probe cycles","Enabled" 11 | "D","Use spindle direction as enable pin","Enabled" 12 | "0","Spindle enable off when speed is zero","Enabled" 13 | "S","Software limit pin debouncing","Enabled" 14 | "R","Parking override control","Enabled" 15 | "*","Restore all EEPROM command","Disabled" 16 | "$","Restore EEPROM `$` settings command","Disabled" 17 | "#","Restore EEPROM parameter data command","Disabled" 18 | "I","Build info write user string command","Disabled" 19 | "E","Force sync upon EEPROM write","Disabled" 20 | "W","Force sync upon work coordinate offset change","Disabled" 21 | "L","Homing initialization auto-lock","Disabled" -------------------------------------------------------------------------------- /doc/csv/error_codes_en_US.csv: -------------------------------------------------------------------------------- 1 | "Error Code in v1.1+","Error Message in v1.0-","Error Description" 2 | "1","Expected command letter","G-code words consist of a letter and a value. Letter was not found." 3 | "2","Bad number format","Missing the expected G-code word value or numeric value format is not valid." 4 | "3","Invalid statement","Grbl '$' system command was not recognized or supported." 5 | "4","Value < 0","Negative value received for an expected positive value." 6 | "5","Setting disabled","Homing cycle failure. Homing is not enabled via settings." 7 | "6","Value < 3 usec","Minimum step pulse time must be greater than 3usec." 8 | "7","EEPROM read fail. Using defaults","An EEPROM read failed. Auto-restoring affected EEPROM to default values." 9 | "8","Not idle","Grbl '$' command cannot be used unless Grbl is IDLE. Ensures smooth operation during a job." 10 | "9","G-code lock","G-code commands are locked out during alarm or jog state." 11 | "10","Homing not enabled","Soft limits cannot be enabled without homing also enabled." 12 | "11","Line overflow","Max characters per line exceeded. Received command line was not executed." 13 | "12","Step rate > 30kHz","Grbl '$' setting value cause the step rate to exceed the maximum supported." 14 | "13","Check Door","Safety door detected as opened and door state initiated." 15 | "14","Line length exceeded","Build info or startup line exceeded EEPROM line length limit. Line not stored." 16 | "15","Travel exceeded","Jog target exceeds machine travel. Jog command has been ignored." 17 | "16","Invalid jog command","Jog command has no '=' or contains prohibited g-code." 18 | "17","Setting disabled","Laser mode requires PWM output." 19 | "20","Unsupported command","Unsupported or invalid g-code command found in block." 20 | "21","Modal group violation","More than one g-code command from same modal group found in block." 21 | "22","Undefined feed rate","Feed rate has not yet been set or is undefined." 22 | "23","Invalid gcode ID:23","G-code command in block requires an integer value." 23 | "24","Invalid gcode ID:24","More than one g-code command that requires axis words found in block." 24 | "25","Invalid gcode ID:25","Repeated g-code word found in block." 25 | "26","Invalid gcode ID:26","No axis words found in block for g-code command or current modal state which requires them." 26 | "27","Invalid gcode ID:27","Line number value is invalid." 27 | "28","Invalid gcode ID:28","G-code command is missing a required value word." 28 | "29","Invalid gcode ID:29","G59.x work coordinate systems are not supported." 29 | "30","Invalid gcode ID:30","G53 only allowed with G0 and G1 motion modes." 30 | "31","Invalid gcode ID:31","Axis words found in block when no command or current modal state uses them." 31 | "32","Invalid gcode ID:32","G2 and G3 arcs require at least one in-plane axis word." 32 | "33","Invalid gcode ID:33","Motion command target is invalid." 33 | "34","Invalid gcode ID:34","Arc radius value is invalid." 34 | "35","Invalid gcode ID:35","G2 and G3 arcs require at least one in-plane offset word." 35 | "36","Invalid gcode ID:36","Unused value words found in block." 36 | "37","Invalid gcode ID:37","G43.1 dynamic tool length offset is not assigned to configured tool length axis." 37 | "38","Invalid gcode ID:38","Tool number greater than max supported value." -------------------------------------------------------------------------------- /doc/csv/setting_codes_en_US.csv: -------------------------------------------------------------------------------- 1 | "$-Code"," Setting"," Units"," Setting Description" 2 | "0","Step pulse time","microseconds","Sets time length per step. Minimum 3usec." 3 | "1","Step idle delay","milliseconds","Sets a short hold delay when stopping to let dynamics settle before disabling steppers. Value 255 keeps motors enabled with no delay." 4 | "2","Step pulse invert","mask","Inverts the step signal. Set axis bit to invert (00000ZYX)." 5 | "3","Step direction invert","mask","Inverts the direction signal. Set axis bit to invert (00000ZYX)." 6 | "4","Invert step enable pin","boolean","Inverts the stepper driver enable pin signal." 7 | "5","Invert limit pins","boolean","Inverts the all of the limit input pins." 8 | "6","Invert probe pin","boolean","Inverts the probe input pin signal." 9 | "10","Status report options","mask","Alters data included in status reports." 10 | "11","Junction deviation","millimeters","Sets how fast Grbl travels through consecutive motions. Lower value slows it down." 11 | "12","Arc tolerance","millimeters","Sets the G2 and G3 arc tracing accuracy based on radial error. Beware: A very small value may effect performance." 12 | "13","Report in inches","boolean","Enables inch units when returning any position and rate value that is not a settings value." 13 | "20","Soft limits enable","boolean","Enables soft limits checks within machine travel and sets alarm when exceeded. Requires homing." 14 | "21","Hard limits enable","boolean","Enables hard limits. Immediately halts motion and throws an alarm when switch is triggered." 15 | "22","Homing cycle enable","boolean","Enables homing cycle. Requires limit switches on all axes." 16 | "23","Homing direction invert","mask","Homing searches for a switch in the positive direction. Set axis bit (00000ZYX) to search in negative direction." 17 | "24","Homing locate feed rate","mm/min","Feed rate to slowly engage limit switch to determine its location accurately." 18 | "25","Homing search seek rate","mm/min","Seek rate to quickly find the limit switch before the slower locating phase." 19 | "26","Homing switch debounce delay","milliseconds","Sets a short delay between phases of homing cycle to let a switch debounce." 20 | "27","Homing switch pull-off distance","millimeters","Retract distance after triggering switch to disengage it. Homing will fail if switch isn't cleared." 21 | "30","Maximum spindle speed","RPM","Maximum spindle speed. Sets PWM to 100% duty cycle." 22 | "31","Minimum spindle speed","RPM","Minimum spindle speed. Sets PWM to 0.4% or lowest duty cycle." 23 | "32","Laser-mode enable","boolean","Enables laser mode. Consecutive G1/2/3 commands will not halt when spindle speed is changed." 24 | "100","X-axis travel resolution","step/mm","X-axis travel resolution in steps per millimeter." 25 | "101","Y-axis travel resolution","step/mm","Y-axis travel resolution in steps per millimeter." 26 | "102","Z-axis travel resolution","step/mm","Z-axis travel resolution in steps per millimeter." 27 | "103","A-axis travel resolution","step/degre","A-Axis travel resolution in steps per degre" 28 | "104","B-axis travel resolution","step/degre","B-Axis travel resolution in steps per degre" 29 | "110","X-axis maximum rate","mm/min","X-axis maximum rate. Used as G0 rapid rate." 30 | "111","Y-axis maximum rate","mm/min","Y-axis maximum rate. Used as G0 rapid rate." 31 | "112","Z-axis maximum rate","mm/min","Z-axis maximum rate. Used as G0 rapid rate." 32 | "113","A-axis maximum rate","degre/min","A-axis maximum rate. Used as G0 rapid rate" 33 | "114","B-axis maximum rate","degre/min","B-axis maximum rate. Used as G0 rapid rate" 34 | "120","X-axis acceleration","mm/sec^2","X-axis acceleration. Used for motion planning to not exceed motor torque and lose steps." 35 | "121","Y-axis acceleration","mm/sec^2","Y-axis acceleration. Used for motion planning to not exceed motor torque and lose steps." 36 | "122","Z-axis acceleration","mm/sec^2","Z-axis acceleration. Used for motion planning to not exceed motor torque and lose steps." 37 | "123","A-Axis acceleration","degre/sec^2","A-axis acceleration. Used for motion planning to not exceed motor torque and lose steps." 38 | "124","B-Axis acceleration","degre/sec^2","B-axis acceleration. Used for motion planning to not exceed motor torque and lose steps." 39 | "130","X-axis maximum travel","millimeters","Maximum X-axis travel distance from homing switch. Determines valid machine space for soft-limits and homing search distances." 40 | "131","Y-axis maximum travel","millimeters","Maximum Y-axis travel distance from homing switch. Determines valid machine space for soft-limits and homing search distances." 41 | "132","Z-axis maximum travel","millimeters","Maximum Z-axis travel distance from homing switch. Determines valid machine space for soft-limits and homing search distances." 42 | "133","A-axis maximum travel","degres","Maximum A-axis travel distance from homing switch. Determines valid machine space for soft-limits and homing search distances." 43 | "134","B-axis maximum travel","degres","Maximum B-axis travel distance from homing switch. Determines valid machine space for soft-limits and homing search distances." 44 | -------------------------------------------------------------------------------- /doc/images/arduino-mega-pinout-detail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/perivar/grbl-Mega-5X/9d65cf514c3407b163b9ba0b69ba4520d0a5360d/doc/images/arduino-mega-pinout-detail.png -------------------------------------------------------------------------------- /doc/images/arduino-mega-pinout-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/perivar/grbl-Mega-5X/9d65cf514c3407b163b9ba0b69ba4520d0a5360d/doc/images/arduino-mega-pinout-diagram.png -------------------------------------------------------------------------------- /doc/log/commit_log_v0.9j.txt: -------------------------------------------------------------------------------- 1 | ---------------- 2 | Date: 2015-08-14 3 | Author: Sonny Jeon 4 | Subject: Individual control pin invert compile-option. 5 | 6 | - Control pins may be individually inverted through a 7 | CONTROL_INVERT_MASK macro. This mask is define in the cpu_map.h file. 8 | 9 | 10 | ---------------- 11 | Date: 2015-07-17 12 | Author: Sonny Jeon 13 | Subject: Version bump to v0.9j 14 | 15 | - Version bump requested by OEMs to easily determine whether the 16 | firmware supports the new EEPROM reset feature. Other than that, no 17 | significant changes. 18 | -------------------------------------------------------------------------------- /doc/log/commit_log_v1.0b.txt: -------------------------------------------------------------------------------- 1 | ---------------- 2 | Date: 2015-09-30 3 | Author: Sonny Jeon 4 | Subject: Bug fixes. 5 | 6 | - G38.x was not printing correctly in the $G g-code state reports. Now 7 | fixed. 8 | 9 | - When investigating the above issue, it was noticed that G38.x 10 | wouldn’t show at all, but instead a G0 would be printed. This was 11 | unlike the v0.9j master build. It turned out volatile variables do not 12 | like to be defined inside a C struct. These are undefined on how to be 13 | handled. Once pulled out, all weird issues went away. 14 | 15 | - Also changed two ‘sizeof()’ statements in the mc_probe() and 16 | probe_state_monitor() functions to be more robust later on. 17 | 18 | - Updated the commit logs to individual files for each minor release. 19 | Forgot to update the generating script to account for this. 20 | 21 | 22 | ---------------- 23 | Date: 2015-09-30 24 | Author: Sonny Jeon 25 | Subject: Minor bug fixes. 26 | 27 | - G38.x was not printing correctly in the $G g-code state reports. Now 28 | fixed. 29 | 30 | - Potential bug regarding volatile variables inside a struct. It has 31 | never been a problem in v0.9, but ran into this during v1.0 32 | development. Just to be safe, the fixes are applied here. 33 | 34 | - Updated pre-built firmwares with these two bug fixes. 35 | 36 | 37 | ---------------- 38 | Date: 2015-09-24 39 | Author: Sonny Jeon 40 | Subject: Updated G28/G30 intermediate motion behavior. 41 | 42 | - G28 and G30’s behavior has been updated from the old NIST g-code 43 | standard to LinuxCNC’s. Previously when an intermediate motion was 44 | programmed, the NIST standard would move all axes to the final G28/30 45 | stored coordinates. LinuxCNC states it only moves the axes specified in 46 | the command. 47 | 48 | For example, suppose G28’s stored position is (x,y,z) = (1,2,3) for 49 | simplicity, and we want to do an automated z-axis tool retraction and 50 | then park at the x,y location. `G28 G91 Z5` will first move the Z axis 51 | 5mm(or inches) up, then move Z to position 3 in machine coordinates. 52 | Next, the command `G28 G91 X0 Y0` would skip the intermediate move 53 | since distance is zero, but then move only the x and y axes to machine 54 | coordinates 1 and 2, respectively. The z-axis wouldn’t move in this 55 | case, since it wasn’t specified. 56 | 57 | This change is intended to make Grbl more LinuxCNC compatible while 58 | making commands, like the shown tool retraction, much easier to 59 | implement. 60 | 61 | 62 | ---------------- 63 | Date: 2015-09-05 64 | Author: Sonny Jeon 65 | Subject: Parking motion bug fix. 66 | 67 | - Parking motion would intermittently complete the queued tool path 68 | upon resuming in certain scenarios. Now fixed. 69 | 70 | 71 | ---------------- 72 | Date: 2015-08-29 73 | Author: Sonny Jeon 74 | Subject: Optional line number reporting bug fix. 75 | 76 | - Fixed a bug where it would not compile when USE_LINE_NUMBERS was 77 | enabled. 78 | 79 | 80 | ---------------- 81 | Date: 2015-08-27 82 | Author: Sonny Jeon 83 | Subject: Update README 84 | 85 | 86 | ---------------- 87 | Date: 2015-08-27 88 | Author: Sonny Jeon 89 | Subject: v1.0 Beta Release. 90 | 91 | - Tons of new stuff in this release, which is fairly stable and well 92 | tested. However, much more is coming soon! 93 | 94 | - Real-time parking motion with safety door. When this compile option 95 | is enabled, an opened safety door will cause Grbl to automatically feed 96 | hold, retract, de-energize the spindle/coolant, and parks near Z max. 97 | After the door is closed and resume is commanded, this reverses and the 98 | program continues as if nothing happened. This is also highly 99 | configurable. See config.h for details. 100 | 101 | - New spindle max and min rpm ‘$’ settings! This has been requested 102 | often. Grbl will output 5V when commanded to turn on the spindle at its 103 | max rpm, and 0.02V with min rpm. The voltage and the rpm range are 104 | linear to each other. This should help users tweak their settings to 105 | get close to true rpm’s. 106 | 107 | - If the new max rpm ‘$’ setting is set = 0 or less than min rpm, the 108 | spindle speed PWM pin will act like a regular on/off spindle enable 109 | pin. On pin D11. 110 | 111 | - BEWARE: Your old EEPROM settings will be wiped! The new spindle rpm 112 | settings require a new settings version, so Grbl will automatically 113 | wipe and restore the EEPROM with the new defaults. 114 | 115 | - Control pin can now be inverted individually with a 116 | CONTROL_INVERT_MASK in the cpu_map header file. Not typical for users 117 | to need this, but handy to have. 118 | 119 | - Fixed bug when Grbl receive too many characters in a line and 120 | overflows. Previously it would respond with an error per overflow 121 | character and another acknowledge upon an EOL character. This broke the 122 | streaming protocol. Now fixed to only respond with an error after an 123 | EOL character. 124 | 125 | - Fixed a bug with the safety door during an ALARM mode. You now can’t 126 | home or unlock the axes until the safety door has been closed. This is 127 | for safety reasons (obviously.) 128 | 129 | - Tweaked some the Mega2560 cpu_map settings . Increased segment buffer 130 | size and fixed the spindle PWM settings to output at a higher PWM 131 | frequency. 132 | 133 | - Generalized the delay function used by G4 delay for use by parking 134 | motion. Allows non-blocking status reports and real-time control during 135 | re-energizing of the spindle and coolant. 136 | 137 | - Added spindle rpm max and min defaults to default.h files. 138 | 139 | - Added a new print float for rpm values. 140 | 141 | -------------------------------------------------------------------------------- /doc/log/commit_log_v1.0c.txt: -------------------------------------------------------------------------------- 1 | ---------------- 2 | Date: 2016-03-11 3 | Author: Sonny Jeon 4 | Subject: Soft limit error bug fix. 5 | 6 | - Soft limit errors were stuck in a feed hold without notifying the 7 | user why it was in a hold. When resumed, the soft limit error would 8 | kick in. Issue should be fixed to behave as intended. To automatically 9 | hold and issue a soft limit alarm once the machine has come to a stop. 10 | 11 | 12 | ---------------- 13 | Date: 2016-03-04 14 | Author: Sonny Jeon 15 | Subject: Applied master branch bug fixes. 16 | 17 | - Planner was under-estimating maximum speeds through straight 18 | junctions in certain cases. The calculations have been updated to be 19 | more accurate. 20 | 21 | - Strange sizeof() bug in the most recent releases. Manifested as an 22 | alarm upon a power up even when homing was disabled. Fixed by declaring 23 | sizeof() with struct types, rather than variable names, even though 24 | they were validated to give the same value. 25 | 26 | - Spindle speed zero should disable the spindle. Now fixed. 27 | 28 | - New configuration option for inverting certain limit pins. Handy for 29 | mixed NO and NC switch machines. See config.h for details. 30 | 31 | 32 | ---------------- 33 | Date: 2015-11-09 34 | Author: Sonny Jeon 35 | Subject: Pin state reporting of all pins. Flash optimization. 36 | 37 | - New pin state realtime reporting feature. Instead of `Lim:000` for 38 | limit state reports, the new feature shows `Pin:000|0|0000`, or 39 | something similar. The `|` delimited fields indicate xyz limits, probe, 40 | and control pin states, where 0 is always not triggered, and 1 is 41 | triggered. Invert masks ARE accounted for. 42 | Each field may be enabled or disabled via the `$10` status report 43 | setting. The probe and control pin flags are bits 5 and 6, respectively. 44 | 45 | - Remove the now deprecated `REPORT_CONTROL_PIN_STATE` option in 46 | config.h 47 | 48 | - The old limit pin reports `Lim:000` may be re-enabled by commenting 49 | out `REPORT_ALL_PIN_STATES` in config.h. 50 | 51 | - Incremented the version letter (v1.0c) to indicate the change in 52 | reporting style. 53 | 54 | - Replaced all bit_true_atomic and bit_false_atomic macros with 55 | function calls. This saved a couple hundred bytes of flash. 56 | 57 | -------------------------------------------------------------------------------- /doc/log/commit_log_v1.0d.txt: -------------------------------------------------------------------------------- 1 | ---------------- 2 | Date: 2017-08-01 3 | Author: Sonny Jeon 4 | Subject: Fixed RAMPS control pin conflict 5 | 6 | [fix] RAMPS soft-reset control pin interfered with Z-enable. Shifted 7 | all control pins by plus one on the analog pins. RAMPS defines these 8 | pins as belonging to the AUX 2 port, which is assumed to be unused. 9 | 10 | 11 | ---------------- 12 | Date: 2017-07-17 13 | Author: Sonny Jeon 14 | Subject: Merge pull request #28 from docwelch/Ramps-1.4 15 | 16 | Add Ramps 1.4 Board Support. Note: This is highly experimental and your mileage may vary. This will be polished soon. 17 | 18 | ---------------- 19 | Date: 2017-07-17 20 | Author: Sonny Jeon 21 | Subject: Merge branch 'edge' into Ramps-1.4 22 | 23 | ---------------- 24 | Date: 2017-07-17 25 | Author: Sonny Jeon 26 | Subject: Syncing mainstream v1.1f 27 | 28 | - See details in mainstream commits from 1/14/17 to 7/17/17. 29 | 30 | 31 | ---------------- 32 | Date: 2017-06-26 33 | Author: docwelch 34 | Subject: Add Ramps 1.4 Board Support 35 | 36 | Changes based on @jekhor’s work 37 | Uses D8 as the spindle pin 38 | 39 | 40 | ---------------- 41 | Date: 2017-03-19 42 | Author: Sonny Jeon 43 | Subject: Moved Grbl logo files to separate repo. 44 | 45 | 46 | ---------------- 47 | Date: 2017-03-19 48 | Author: Sonny Jeon 49 | Subject: Update README.md 50 | 51 | ---------------- 52 | Date: 2017-03-19 53 | Author: Sonny Jeon 54 | Subject: Update README.md 55 | 56 | ---------------- 57 | Date: 2017-01-14 58 | Author: Sonny Jeon 59 | Subject: Pulled in Grbl-328p changes. 60 | 61 | - [fix] Spindle enable pin behavior corrected to be independent of the 62 | PWM output. There was some crossover behavior. 63 | 64 | - [fix] Tool numbers are now tracking and reporting correctly. 65 | 66 | - [fix] G-code parser error when G0 is commanded without a feed rate 67 | word while in inverse time mode. 68 | 69 | - [fix] Config file was missing an option for probing behavior. 70 | 71 | - [doc] Updated documentation. 72 | 73 | 74 | ---------------- 75 | Date: 2016-12-19 76 | Author: Sonny Jeon 77 | Subject: Alarm handling bug fix. 78 | 79 | - Applied an alarm handling bug fix that would not show the correct 80 | alarm code, nor clear the alarm. It would occasionally go into an 81 | infinite loop and would usually happen during a homing cycle fail. 82 | 83 | 84 | ---------------- 85 | Date: 2016-12-19 86 | Author: Sonny Jeon 87 | Subject: Spindle PWM update for Mega2560 88 | 89 | - Spindle PWM is set with a 16-bit value, rather than 8-bit on a 328p. 90 | Updated stepper.c to reflect this change. 91 | 92 | 93 | ---------------- 94 | Date: 2016-12-19 95 | Author: Sonny Jeon 96 | Subject: Grbl v1.1e port to Mega2560 branch 97 | 98 | - v1.1e 99 | 100 | - Ported all current changes from the main Grbl 328p repo to the 101 | Mega2560 branch. Main differences are increased planner, RX, TX, and 102 | line buffers. And an optional sleep timeout feature. 103 | 104 | - WARNING: Code compiles, but has not been tested. 105 | 106 | 107 | ---------------- 108 | Date: 2016-08-31 109 | Author: chamnit 110 | Subject: Minor bug fix to certain safety conditions. 111 | 112 | - Grbl would become unresponsive, if a safety door is reset when active 113 | and then homed immediately after. A system variable was not properly 114 | restored. Now fixed. 115 | 116 | 117 | ---------------- 118 | Date: 2016-05-10 119 | Author: chamnit 120 | Subject: Planner and printFloat update. 121 | 122 | - Planner model update. Improves performance for machines with 123 | different accelerations on each axes. Particularly for 3D carving. 124 | 125 | - Print float update to print 13 (from 10) characters. Help reduce 126 | print errors for unusually long floating point values. 127 | 128 | 129 | ---------------- 130 | Date: 2016-04-10 131 | Author: chamnit 132 | Subject: Alarm and safety door bug fix. 133 | 134 | - Typo in protocol.c caused a safety door to lock out the system during 135 | an alarm. The correct character should keep that from happening and 136 | bring back the original door/alarm behavior. 137 | 138 | 139 | ---------------- 140 | Date: 2016-04-04 141 | Author: Sonny Jeon 142 | Subject: Update readme and sleep documentation. 143 | 144 | 145 | ---------------- 146 | Date: 2016-04-03 147 | Author: chamnit 148 | Subject: Sleep feature. General re-org and bug fixes. 149 | 150 | - New sleep safety feature. If powered components (spindle/coolant) are 151 | enabled and if there is no motion, incoming data, or commands, Grbl 152 | will start a short sleep countdown. Upon elapse, Grbl will depower and 153 | enter a sleep state. If parking is enabled, sleep will also park the 154 | machine. Only a reset will exit sleep and the job will be 155 | unrecoverable. This is purely a safety feature to address serial 156 | disconnection problems. 157 | 158 | - Re-organized the cpu-map and default files and put them back into 159 | single files. Makes it easier for OEMs to just drop in their 160 | configuration files for a custom build. 161 | 162 | - Introduced a single-file configuration method for OEMs. See config.h 163 | for details. Basically just add the cpu_map and default files to the 164 | bottom of config.h. 165 | 166 | - Moved the control pin invert mask to config.h 167 | 168 | - Refactored some cpu_map defines to be more descriptive of what they 169 | belong to. 170 | 171 | - Added invert coolant pins options to config.h 172 | 173 | - Added a new realtime status report. Only a proposal at this time, and 174 | the old classic report is enabled by default. Comment out the 175 | USE_CLASSIC_REALTIME_REPORT define in config.h to use the new report. 176 | Please note that the new report is not finalized and is subject to 177 | change. 178 | 179 | 180 | ---------------- 181 | Date: 2016-03-20 182 | Author: chamnit 183 | Subject: EEPROM string checks and re-added some compile options. 184 | 185 | - Incremented version to v1.0d, but more changes to come before release. 186 | 187 | - EEPROM strings were linked to the LINE_BUFFER_SIZE, which were 188 | increased from 80 to 256. This caused a problem with EEPROM storage and 189 | would corrupt any existing data there. Now fixed to preserve the data 190 | there by limiting the size read or written to EEPROM to 80 characters. 191 | 192 | - When EEPROM string length is exceeded, Grbl will respond with a “Line 193 | length exceeded” error. 194 | 195 | - Re-added a couple of compile-time options: realtime line numbers and 196 | rate reporting. This is to ensure backward support for GUIs for the 197 | time being. These removal options will go away eventually before they 198 | become hard-coded in. (They will be toggle-able with the status report 199 | mask in settings though.) 200 | 201 | 202 | ---------------- 203 | Date: 2016-03-19 204 | Author: Sonny Jeon 205 | Subject: Removed 328p-related code. Enabled options by default. 206 | 207 | - Removed all of the 328p-related code, which seemed to clean up things 208 | quite a bit without all those ifdefs everywhere. 209 | 210 | - Since the 328p was very memory and flash limited, lots of 211 | compile-time options were disabled by default. These have been now been 212 | enabled by default. As they are considered generally helpful and does 213 | not significantly impact how Grbl runs. 214 | 215 | - For example, status reports can now report back real time feed rate 216 | and line number being executed. Variable spindle is standard with a 217 | separate spindle enable pin. Grbl will now check if a user setting has 218 | exceeded the maximum step frequency and report an error, if so. And 219 | finally, M7 flood coolant is enabled. 220 | 221 | - In addition, all buffers have been significantly increased to take 222 | advantage of the additional memory available. The planner buffer can 223 | plan up to 36 motions. The serial buffers have been doubled in size 224 | (256/128 bytes RX/TX). And the longest line Grbl can accept is 256 225 | bytes, per the g-code standard (Grbl 328p is limited to 80). 226 | 227 | - Removed the cpu_map folder, since this version is strictly Mega2560. 228 | 229 | 230 | ---------------- 231 | Date: 2016-03-19 232 | Author: chamnit 233 | Subject: Update README 234 | 235 | 236 | ---------------- 237 | Date: 2016-03-19 238 | Author: Sonny Jeon 239 | Subject: No variable spindle and spindle speed fix. 240 | 241 | - Soft limit errors were stuck in a feed hold without notifying the 242 | user why it was in a hold. When resumed, the soft limit error would 243 | kick in. Issue should be fixed to behave as intended to automatically 244 | hold and issue a soft limit alarm once the machine has come to a stop. 245 | 246 | -------------------------------------------------------------------------------- /doc/log/commit_log_v1.1.txt: -------------------------------------------------------------------------------- 1 | ---------------- 2 | Date: 2016-12-19 3 | Author: Sonny Jeon 4 | Subject: Alarm handling bug fix. 5 | 6 | - Applied an alarm handling bug fix that would not show the correct 7 | alarm code, nor clear the alarm. It would occasionally go into an 8 | infinite loop and would usually happen during a homing cycle fail. 9 | 10 | 11 | ---------------- 12 | Date: 2016-12-19 13 | Author: Sonny Jeon 14 | Subject: Spindle PWM update for Mega2560 15 | 16 | - Spindle PWM is set with a 16-bit value, rather than 8-bit on a 328p. 17 | Updated stepper.c to reflect this change. 18 | 19 | 20 | ---------------- 21 | Date: 2016-12-19 22 | Author: Sonny Jeon 23 | Subject: Grbl v1.1e port to Mega2560 branch 24 | 25 | - v1.1e 26 | 27 | - Ported all current changes from the main Grbl 328p repo to the 28 | Mega2560 branch. Main differences are increased planner, RX, TX, and 29 | line buffers. And an optional sleep timeout feature. 30 | 31 | - WARNING: Code compiles, but has not been tested. 32 | 33 | -------------------------------------------------------------------------------- /doc/markdown/change_summary.md: -------------------------------------------------------------------------------- 1 | ### _Grbl v1.1 - Change Summary_ 2 | 3 | -------- 4 | 5 | ### _Specific details are available in the other markdown documents._ 6 | -------- 7 | 8 | #### GUI Interface Tweaks from Grbl v0.9 9 | 10 | Grbl v1.1's interface protocol has been tweaked in the attempt to make GUI development cleaner, clearer, and hopefully easier. All messages are designed to be deterministic without needing to know the context of the message. Each can be inferred to a much greater degree than before just by the message type, which are all listed below. 11 | 12 | - `ok` / `error:x` : Normal send command and execution response acknowledgement. Used for streaming. 13 | 14 | - `< >` : Enclosed chevrons contains status report data. 15 | 16 | - `Grbl X.Xx ['$' for help]` : Welcome message indicates initialization. 17 | 18 | - `ALARM:x` : Indicates an alarm has been thrown. Grbl is now in an alarm state. 19 | 20 | - `$x=val` and `$Nx=line` indicate a settings printout from a `$` and `$N` user query, respectively. 21 | 22 | - `[MSG:]` : Indicates a non-queried feedback message. 23 | 24 | - `[GC:]` : Indicates a queried `$G` g-code state message. 25 | 26 | - `[HLP:]` : Indicates the help message. 27 | 28 | - `[G54:]`, `[G55:]`, `[G56:]`, `[G57:]`, `[G58:]`, `[G59:]`, `[G28:]`, `[G30:]`, `[G92:]`, `[TLO:]`, and `[PRB:]` messages indicate the parameter data printout from a `$#` user query. 29 | 30 | - `[VER:]` : Indicates build info and string from a `$I` user query. 31 | 32 | - `[OPT:]` : Indicates compile-time option info from a `$I` user query. 33 | 34 | - `[echo:]` : Indicates an automated line echo from a pre-parsed string prior to g-code parsing. Enabled by config.h option. 35 | 36 | - `>G54G20:ok` : The open chevron indicates startup line execution. The `:ok` suffix shows it executed correctly without adding an unmatched `ok` response on a new line. 37 | 38 | In addition, all `$x=val` settings, `error:`, and `ALARM:` messages no longer contain human-readable strings, but rather codes that are defined in other documents. The `$` help message is also reduced to just showing the available commands. Doing this saves incredible amounts of flash space. Otherwise, the new overrides features would not have fit. 39 | 40 | Other minor changes and bug fixes that may effect GUI parsing include: 41 | 42 | - Floating point values printed with zero precision do not show a decimal, or look like an integer. This includes spindle speed RPM and feed rate in mm mode. 43 | - `$G` reports fixed a long time bug with program modal state. It always showed `M0` program pause when running. Now during a normal program run, no program modal state is given until an `M0`, `M2`, or `M30` is active and then the appropriate state will be shown. 44 | 45 | On a final note, these interface tweaks came about out of necessity, because more data is being sent back from Grbl, it is capable of doing many more things, and flash space is at a premium. It's not intended to be altered again in the near future, if at all. This is likely the only and last major change to this. If you have any comments or suggestions before Grbl v1.1 goes to master, please do immediately so we can all vet the new alteration before its installed. 46 | 47 | ---- 48 | 49 | #### Realtime Status Reports Changes from Grbl v0.9 50 | 51 | - Intent of changes is to make parsing cleaner, reduce transmitting overhead without effecting overall Grbl performance, and add more feedback data, which includes three new override values and real-time velocity. 52 | 53 | - Data fields are separated by `|` pipe delimiters, rather than `,` commas that were used to separate data values. This should help with parsing. 54 | 55 | - The ability to mask and add/remove data fields from status reports via the `$10` status report mask setting has been disabled. Only selecting `MPos:` or `WPos:` coordinates is allowed. 56 | - All available data is always sent to standardize the reports across all GUIs. 57 | - For unique situations, data fields can be removed by config.h macros, but it is highly recommended to not alter these. 58 | 59 | 60 | - `MPos:` OR `WPos:` are always included in a report, but not BOTH at the same time. 61 | 62 | - This reduces transmit overhead tremendously by removing upwards to 40 characters. 63 | - `WCO:0.000,10.000,2.500` A current work coordinate offset is now sent to easily convert between position vectors, where `WPos = MPos - WCO` for each axis. 64 | - `WCO:` is included immediately whenever a `WCO:` value changes or intermittently after every **X** status reports as a refresh. Refresh rates can dynamically vary from 10 to 30 (configurable) reports depending on what Grbl is doing. 65 | - `WCO:` is simply the sum of the work coordinate system, G92, and G43.1 tool length offsets. 66 | - Basically, a GUI just needs to retain the last `WCO:` and apply the equation to get the other position vector. 67 | - `WCO:` messages may only be disabled via a config.h compile-option, if a GUI wants to handle the work position calculations on its own to free up more transmit bandwidth. 68 | - Be aware of the following issue regarding `WPos:`. 69 | - In Grbl v0.9 and prior, there is an old outstanding bug where the `WPos:` work position reported may not correlate to what is executing, because `WPos:` is based on the g-code parser state, which can be several motions behind. Grbl v1.1 now forces the planner buffer to empty, sync, and stops motion whenever there is a command that alters the work coordinate offsets `G10,G43.1,G92,G54-59`. This is the simplest way to ensure `WPos:` is always correct. Fortunately, it's exceedingly rare that any of these commands are used need continuous motions through them. 70 | - A compile-time option is available to disable the planner sync and forced stop, but, if used, it's up to the GUI to handle this position correlation issue. 71 | 72 | 73 | - The `Hold` and `Door` states includes useful sub-state info via a `:` colon delimiter and an integer value. See descriptions for details. 74 | 75 | - Limit and other input pin reports have significantly changed to reduce transmit overhead. 76 | - The data type description is now just `Pn:`, rather than `Lim:000` or `Pin:000|0|0000` 77 | - It does not appear if no inputs are detected as triggered. 78 | - If an input is triggered, ```Pn:``` will be followed by a letter or set of letters of every triggered input pin. `XYZPDHRS` for the XYZ-axes limits, Probe, Door, Hold, soft-Reset, cycle Start pins, respectively. 79 | - For example, a triggered Z-limit and probe pin would report `Pn:ZP`. 80 | 81 | 82 | - Buffer data (planner and serial RX) reports have been tweaked and combined. 83 | 84 | - `Bf:15,128`. The first value is the available blocks in the planner buffer and the second is available bytes in the serial RX buffer. 85 | - Note that this is different than before, where it reported blocks/bytes "in-use", rather than "available". This change does not require a GUI to know how many blocks/bytes Grbl has been compiled with, which can be substantially different on a Grbl-Mega build. 86 | 87 | 88 | - Override reports are intermittent since they don't change often once set. 89 | 90 | - Overrides are included in every 10 or 20 status reports (configurable) depending on what Grbl is doing or, if an override value or toggle state changes, automatically in the next report. 91 | - There are two override fields: 92 | - `Ov:100,100,100` Organized as feed, rapid, and spindle speed overrides in percent. 93 | 94 | - Accessory states are shown alongside override reports when they are active. Like pin states, an accessory state report `A:SFM` contains a letter indicating an active accessory. Letters `S`, `C`, `F`, and `M` are defined as spindle CW, spindle CCW, flood coolant, and mist coolant, respectively. The pins are directly polled and shown here. 95 | 96 | - Line numbers, when enabled in config.h, are omitted when: 97 | 98 | - No line number is passed to Grbl in a block. 99 | - Grbl is performing a system motion like homing, jogging, or parking. 100 | - Grbl is executing g-code block that does not contain a motion, like `G20G54` or `G4P1` dwell. (NOTE: Looking to fixing this later.) 101 | 102 | ------- 103 | 104 | #### New Commands 105 | 106 | - `$SLP` - Grbl v1.1 now has a sleep mode that can be invoked by this command. It requires Grbl to be in either an IDLE or ALARM state. Once invoked, Grbl will de-energize all connected systems, including the spindle, coolant, and stepper drivers. It'll enter a suspend state that can only be exited by a reset. When reset, Grbl will re-initiatize in an ALARM state because the steppers were disabled and position can not be guaranteed. 107 | - NOTE: Grbl-Mega can invoke the sleep mode at any time, when the sleep timeout feature is enabled in config.h. It does so when Grbl has not received any external input after a timeout period. 108 | 109 | - `$J=line` New jogging commands. This command behaves much like a normal G1 command, but there are some key differences. Jog commands don't alter the g-code parser state, meaning a GUI doesn't have to manage it anymore. Jog commands may be queued and cancelled at any time, where they are automatically flushed from the planner buffer without requiring a reset. See the jogging documentation on how they work and how they may be used to implement a low-latency joystick or rotary dial. 110 | 111 | - Laser mode `$` setting - When enabled, laser mode will move through consecutive G1, G2, and G3 motion commands that have different spindle speed values without stopping. A spindle speed of zero will disable the laser without stopping as well. However, when spindle states change, like M3 or M5, stops are still enforced. 112 | - NOTE: Parking motions are automatically disabled when laser mode is enabled to prevent burning. 113 | 114 | - `G56 P1` and `G56 P0` - When enabled in config.h with Grbl's parking motion, these commands enable and disable, respectively, the parking motion. Like all override control commands, these commands are modal and are part of the g-code stream. -------------------------------------------------------------------------------- /doc/markdown/jogging.md: -------------------------------------------------------------------------------- 1 | # Grbl v1.1 Jogging 2 | 3 | This document outlines how to use Grbl v1.1's new jogging commands. These command differ because they can be cancelled and all queued motions are automatically purged with a simple jog-cancel or feed hold real-time command. Jogging command do not alter the g-code parser state in any way, so you no longer have to worry if you remembered to set the distance mode back to `G90` prior to starting a job. Also, jogging works well with an analog joysticks and rotary dials! See the implementation notes below. 4 | 5 | ## How to Use 6 | Executing a jog requires a specific command structure, as described below: 7 | 8 | - The first three characters must be '$J=' to indicate the jog. 9 | - The jog command follows immediate after the '=' and works like a normal G1 command. 10 | - Feed rate is only interpreted in G94 units per minute. A prior G93 state is ignored during jog. 11 | - Required words: 12 | - XYZ: One or more axis words with target value. 13 | - F - Feed rate value. NOTE: Each jog requires this value and is not treated as modal. 14 | - Optional words: Jog executes based on current G20/G21 and G90/G91 g-code parser state. If one of the following optional words is passed, that state is overridden for one command only. 15 | - G20 or G21 - Inch and millimeter mode 16 | - G90 or G91 - Absolute and incremental distances 17 | - G53 - Move in machine coordinates 18 | - N line numbers are valid. Will show in reports, if enabled, but is otherwise ignored. 19 | - All other g-codes, m-codes, and value words (including S and T) are not accepted in the jog command. 20 | - Spaces and comments are allowed in the command. These are removed by the pre-parser. 21 | 22 | - Example: G21 and G90 are active modal states prior to jogging. These are sequential commands. 23 | - `$J=X10.0 Y-1.5` will move to X=10.0mm and Y=-1.5mm in work coordinate frame (WPos). 24 | - `$J=G91 G20 X0.5` will move +0.5 inches (12.7mm) to X=22.7mm (WPos). Note that G91 and G20 are only applied to this jog command. 25 | - `$J=G53 Y5.0` will move the machine to Y=5.0mm in the machine coordinate frame (MPos). If the work coordinate offset for the y-axis is 2.0mm, then Y is 3.0mm in (WPos). 26 | 27 | Jog commands behave almost identically to normal g-code streaming. Every jog command will 28 | return an 'ok' when the jogging motion has been parsed and is setup for execution. If a 29 | command is not valid, Grbl will return an 'error:'. Multiple jogging commands may be 30 | queued in sequence. 31 | 32 | The main differences are: 33 | 34 | - During a jog, Grbl will report a 'Jog' state while executing the jog. 35 | - A jog command will only be accepted when Grbl is in either the 'Idle' or 'Jog' states. 36 | - Jogging motions may not be mixed with g-code commands while executing, which will return a lockout error, if attempted. 37 | - All jogging motion(s) may be cancelled at anytime with a simple jog cancel realtime command or a feed hold or safety door event. Grbl will automatically flush Grbl's internal buffers of any queued jogging motions and return to the 'Idle' state. No soft-reset required. 38 | - If soft-limits are enabled, jog commands that exceed the machine travel simply does not execute the command and return an error, rather than throwing an alarm in normal operation. 39 | - IMPORTANT: Jogging does not alter the g-code parser state. Hence, no g-code modes need to be explicitly managed, unlike previous ways of implementing jogs with commands like 'G91G1X1F100'. Since G91, G1, and F feed rates are modal and if they are not changed back prior to resuming/starting a job, a job may not run how its was intended and result in a crash. 40 | 41 | ------ 42 | 43 | ## Joystick Implementation 44 | 45 | Jogging in Grbl v1.1 is generally intended to address some prior issues with old bootstrapped jogging methods. Unfortunately, the new Grbl jogging is not a complete solution. Flash and memory restrictions prevent the original envisioned implementation, but most of these can be mimicked by the following suggested methodology. 46 | 47 | With a combination of the new jog cancel and moving in `G91` incremental mode, the following implementation can create low latency feel for an analog joystick or similar control device. 48 | 49 | - Basic Implementation Overview: 50 | - Create a loop to read the joystick signal and translate it to a desired jog motion vector. 51 | - Send Grbl a very short `G91` incremental distance jog command with a feed rate based on the joystick throw. 52 | - Wait for an 'ok' acknowledgement before restarting the loop. 53 | - Continually read the joystick input and send Grbl short jog motions to keep Grbl's planner buffer full. 54 | - If the joystick is returned to its neutral position, stop the jog loop and simply send Grbl a jog cancel real-time command. This will stop motion immediately somewhere along the programmed jog path with virtually zero-latency and automatically flush Grbl's planner queue. It's not advised to use a feed hold to cancel a jog, as it can lead to inadvertently suspending Grbl if its sent after returning to the IDLE state. 55 | 56 | 57 | The overall idea is to minimize the total distance in the planner queue to provide a low-latency feel to joystick control. The main trick is ensuring there is just enough distance in the planner queue, such that the programmed feed rate is always met. How to compute this will be explain later. In practice, most machines will have a 0.5-1.0 second latency. When combined with the immediate jog cancel command, joystick interaction can be quite enjoyable and satisfying. 58 | 59 | However, please note, if a machine has a low acceleration and is being asked to move at a high programmed feed rate, joystick latency can get up to a handful of seconds. It may sound bad, but this is how long it'll take for a low acceleration machine, traveling at a high feed rate, to slow down to a stop. The argument can be made for a low acceleration machine that you really shouldn't be jogging at a high feed rate. It is difficult for a user to gauge where the machine will come to a stop. You risk overshooting your target destination, which can result in an expensive or dangerous crash. 60 | 61 | One of the advantages of this approach is that a GUI can deterministically track where Grbl will go by the jog commands it has already sent to Grbl. As long as a jog isn't cancelled, every jog command is guaranteed to execute. In the event a jog cancel is invoked, the GUI would just need to refresh their internal position from a status report after Grbl has cleared planner buffer and returned to the IDLE (or DOOR, if ajar) state from the JOG state. This stopped position will always be somewhere along the programmed jog path. If desired, jogging can then be quickly and easily restarted with a new tracked path. 62 | 63 | In combination with `G53` move in machine coordinates, a GUI can restrict jogging from moving into "keep-out" zones inside the machine space. This can be very useful for avoiding crashing into delicate probing hardware, workholding mechanisms, or other fixed features inside machine space that you want to avoid. 64 | 65 | #### How to compute incremental distances 66 | 67 | The quickest and easiest way to determine what the length of a jog motion needs to be to minimize latency are defined by the following equations. 68 | 69 | `s = v * dt` - Computes distance traveled for next jog command. 70 | 71 | where: 72 | 73 | - `s` - Incremental distance of jog command. 74 | - `dt` - Estimated execution time of a single jog command in seconds. 75 | - `v` - Current jog feed rate in **mm/sec**, not mm/min. Less than or equal to max jog rate. 76 | - `N` - Number of Grbl planner blocks (`N=15`) 77 | - `T = dt * N` - Computes total estimated latency in seconds. 78 | 79 | The time increment `dt` may be defined to whatever value you need. Obviously, you'd like the lowest value, since that translates to lower overall latency `T`. However, it is constrained by two factors. 80 | 81 | - `dt > 10ms` - The time it takes Grbl to parse and plan one jog command and receive the next one. Depending on a lot of factors, this can be around 1 to 5 ms. To be conservative, `10ms` is used. Keep in mind that on some systems, this value may still be greater than `10ms` due to round-trip communication latency. 82 | 83 | - `dt > v^2 / (2 * a * (N-1))` - The time increment needs to be large enough to ensure the jog feed rate will be acheived. Grbl always plans to a stop over the total distance queued in the planner buffer. This is primarily to ensure the machine will safely stop if a disconnection occurs. This equation simply ensures that `dt` is big enough to satisfy this constraint. 84 | 85 | - For simplicity, use the max jog feed rate for `v` in mm/sec and the smallest acceleration setting between the jog axes being moved in mm/sec^2. 86 | 87 | - For a lower latency, `dt` can be computed for each jog motion, where `v` is the current rate and `a` is the max acceleration along the jog vector. This is very useful if traveling a very slow speeds to locate a part zero. The `v` rate would be much lower in this scenario and the total latency would decrease quadratically. 88 | 89 | In practice, most CNC machines will operate with a jogging time increment of `0.025 sec` < `dt` < `0.06 sec`, which translates to about a `0.4` to `0.9` second total latency when traveling at the max jog rate. Good enough for most people. 90 | 91 | However, if jogging at a slower speed and a GUI adjusts the `dt` with it, you can get very close to the 0.1 second response time by human-interface guidelines for "feeling instantaneous". Not too shabby! 92 | 93 | With some ingenuity, this jogging methodology may be applied to different devices such as a rotary dial or touchscreen. An "inertial-feel", like swipe-scrolling on a smartphone or tablet, can be simulated by managing the jog rate decay and sending Grbl the associated jog commands. While this jogging implementation requires more initial work by a GUI, it is also inherently more flexible because you have complete deterministic control of how jogging behaves. -------------------------------------------------------------------------------- /doc/markdown/laser_mode.md: -------------------------------------------------------------------------------- 1 | ## Grbl v1.1 Laser Mode 2 | 3 | **_DISCLAIMER: Lasers are extremely dangerous devices. They can instantly cause fires and permanently damage your vision. Please read and understand all related documentation for your laser prior to using it. The Grbl project is not resposible for any damage or issues the firmware may cause, as defined by its GPL license._** 4 | 5 | ---- 6 | 7 | Outlined in this document is how Grbl alters its running conditions for the new laser mode to provide both improved performance and attempting to enforce some basic user safety precautions. 8 | 9 | ## Laser Mode Overview 10 | 11 | The main difference between default Grbl operation and the laser mode is how the spindle/laser output is controlled with motions involved. Every time a spindle state `M3 M4 M5` or spindle speed `Sxxx` is altered, Grbl would come to a stop, allow the spindle to change, and then continue. This is the normal operating procedure for a milling machine spindle. It needs time to change speeds. 12 | 13 | However, if a laser starts and stops like this for every spindle change, this leads to scorching and uneven cutting/engraving! Grbl's new laser mode prevents unnecessary stops whenever possible and adds a new dynamic laser power mode that automagically scales power based on current speed related to programmed rate. So, you can get super clean and crisp results, even on a low-acceleration machine! 14 | 15 | Enabling or disabling Grbl's laser mode is easy. Just alter the **$32** Grbl setting. 16 | - **To Enable**: Send Grbl a `$32=1` command. 17 | - **To Disable:** Send Grbl a `$32=0` command. 18 | 19 | **WARNING:** If you switch back from laser mode to a spindle for milling, you **MUST** disable laser mode by sending Grbl a `$32=0` command. Milling operations require the spindle to get up to the right rpm to cut correctly and to be **safe**, helping to prevent a tool from breaking and flinging metal shards everywhere. With laser mode disabled, Grbl will briefly pause upon any spindle speed or state change to give the spindle a chance to get up to speed before continuing. 20 | 21 | 22 | ## Laser Mode Operation 23 | 24 | When laser mode is enabled, Grbl controls laser power by varying the **0-5V** voltage from the spindle PWM D11 pin. **0V** should be treated as disabled, while **5V** is full power. Intermediate output voltages are also assumed to be linear with laser power, such that **2.5V** is approximate 50% laser power. (A compile time option exists to shift this linear model to start at a non-zero voltage.) 25 | 26 | By default, the spindle PWM frequency is **1kHz**, which is the recommended PWM frequency for most current Grbl-compatible lasers system. If a different frequency is required, this may be altered by editing the `cpu_map.h` file. 27 | 28 | The laser is enabled with the `M3` spindle CW and `M4` spindle CCW commands. These enable two different laser modes that are advantageous for different reasons each. 29 | 30 | - **`M3` Constant Laser Power Mode:** 31 | 32 | - Constant laser power mode simply keeps the laser power as programmed, regardless if the machine is moving, accelerating, or stopped. This provides better control of the laser state. With a good G-code program, this can lead to more consistent cuts in more difficult materials. 33 | 34 | - For a clean cut and prevent scorching with `M3` constant power mode, it's a good idea to add lead-in and lead-out motions around the line you want to cut to give some space for the machine to accelerate and decelerate. 35 | 36 | - NOTE: `M3` can be used to keep the laser on for focusing. 37 | 38 | - **`M4` Dynamic Laser Power Mode:** 39 | - Dynamic laser power mode will automatically adjust laser power based on the current speed relative to the programmed rate. It essentially ensures the amount of laser energy along a cut is consistent even though the machine may be stopped or actively accelerating. This is very useful for clean, precise engraving and cutting on simple materials across a large range of G-code generation methods by CAM programs. It will generally run faster and may be all you need to use. 40 | 41 | - Grbl calculates laser power based on the assumption that laser power is linear with speed and the material. Often, this is not the case. Lasers can cut differently at varying power levels and some materials may not cut well at a particular speed and/power. In short, this means that dynamic power mode may not work for all situations. Always do a test piece prior to using this with a new material or machine. 42 | 43 | - When not in motion, `M4` dynamic mode turns off the laser. It only turns on when the machine moves. This generally makes the laser safer to operate, because, unlike `M3`, it will never burn a hole through your table, if you stop and forget to turn `M3` off in time. 44 | 45 | Describe below are the operational changes to Grbl when laser mode is enabled. Please read these carefully and understand them fully, because nothing is worse than a garage _**fire**_. 46 | 47 | - Grbl will move continuously through **consecutive** motion commands when programmed with a new `S` spindle speed (laser power). The spindle PWM pin will be updated instantaneously through each motion without stopping. 48 | - Example: The following set of g-code commands will not pause between each of them when laser mode is enabled, but will pause when disabled. 49 | 50 | ``` 51 | G1 X10 S100 F50 52 | G1 X0 S90 53 | G2 X0 I5 S80 54 | ``` 55 | - Grbl will enforce a laser mode motion stop in a few circumstances. Primarily to ensure alterations stay in sync with the g-code program. 56 | 57 | - Any `M3`, `M4`, `M5` spindle state _change_. 58 | - `M3` only and no motion programmed: A `S` spindle speed _change_. 59 | - `M3` only and no motion programmed: A `G1 G2 G3` laser powered state _change_ to `G0 G80` laser disabled state. 60 | - NOTE: `M4` does not stop for anything but a spindle state _change_. 61 | 62 | - The laser will only turn on when Grbl is in a `G1`, `G2`, or `G3` motion mode. 63 | 64 | - In other words, a `G0` rapid motion mode or `G38.x` probe cycle will never turn on and always disable the laser, but will still update the running modal state. When changed to a `G1 G2 G3` modal state, Grbl will immediately enable the laser based on the current running state. 65 | 66 | - Please remember that `G0` is the default motion mode upon power up and reset. You will need to alter it to `G1`, `G2`, or `G3` if you want to manually turn on your laser. This is strictly a safety measure. 67 | 68 | - Example: `G0 M3 S1000` will not turn on the laser, but will set the laser modal state to `M3` enabled and power of `S1000`. A following `G1` command will then immediately be set to `M3` and `S1000`. 69 | 70 | - To have the laser powered during a jog motion, first enable a valid motion mode and spindle state. The following jog motions will inherit and maintain the previous laser state. Please use with caution though. This ability is primarily to allow turning on the laser on a _very low_ power to use the laser dot to jog and visibly locate the start position of a job. 71 | 72 | 73 | - An `S0` spindle speed of zero will turn off the laser. When programmed with a valid laser motion, Grbl will disable the laser instantaneously without stopping for the duration of that motion and future motions until set greater than zero.. 74 | 75 | - `M3` constant laser mode, this is a great way to turn off the laser power while continuously moving between a `G1` laser motion and a `G0` rapid motion without having to stop. Program a short `G1 S0` motion right before the `G0` motion and a `G1 Sxxx` motion is commanded right after to go back to cutting. 76 | 77 | 78 | ----- 79 | ###CAM Developer Implementation Notes 80 | 81 | TODO: Add some suggestions on how to write laser G-code for Grbl. 82 | 83 | - When using `M3` constant laser power mode, try to avoid force-sync conditions during a job whenever possible. Basically every spindle speed change must be accompanied by a valid motion. Any motion is fine, since Grbl will automatically enable and disable the laser based on the modal state. Avoid a `G0` and `G1` command with no axis words in this mode and in the middle of a job. 84 | 85 | - Ensure smooth motions throughout by turning the laser on and off without an `M3 M4 M5` spindle state command. There are two ways to do this: 86 | 87 | - _Program a zero spindle speed `S0`_: `S0` is valid G-code and turns off the spindle/laser without changing the spindle state. In laser mode, Grbl will smoothly move through consecutive motions and turn off the spindle. Conversely, you can turn on the laser with a spindle speed `S` greater than zero. Remember that `M3` constant power mode requires any spindle speed `S` change to be programmed with a motion to allow continuous motion, while `M4` dynamic power mode does not. 88 | 89 | - _Program an unpowered motion between powered motions_: If you are traversing between parts of a raster job that don't need to have the laser powered, program a `G0` rapid between them. `G0` enforces the laser to be disabled automatically. The last spindle speed programmed doesn't change, so if a valid powered motion, like a `G1` is executed after, it'll immediately re-power the laser with the last programmed spindle speed when executing that motion. 90 | -------------------------------------------------------------------------------- /doc/script/simple_stream.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """\ 3 | Simple g-code streaming script for grbl 4 | 5 | Provided as an illustration of the basic communication interface 6 | for grbl. When grbl has finished parsing the g-code block, it will 7 | return an 'ok' or 'error' response. When the planner buffer is full, 8 | grbl will not send a response until the planner buffer clears space. 9 | 10 | G02/03 arcs are special exceptions, where they inject short line 11 | segments directly into the planner. So there may not be a response 12 | from grbl for the duration of the arc. 13 | 14 | --------------------- 15 | The MIT License (MIT) 16 | 17 | Copyright (c) 2012 Sungeun K. Jeon 18 | 19 | Permission is hereby granted, free of charge, to any person obtaining a copy 20 | of this software and associated documentation files (the "Software"), to deal 21 | in the Software without restriction, including without limitation the rights 22 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 23 | copies of the Software, and to permit persons to whom the Software is 24 | furnished to do so, subject to the following conditions: 25 | 26 | The above copyright notice and this permission notice shall be included in 27 | all copies or substantial portions of the Software. 28 | 29 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 30 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 31 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 32 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 33 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 34 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 35 | THE SOFTWARE. 36 | --------------------- 37 | """ 38 | 39 | import serial 40 | import time 41 | 42 | # Open grbl serial port 43 | s = serial.Serial('/dev/tty.usbmodem1811',115200) 44 | 45 | # Open g-code file 46 | f = open('grbl.gcode','r'); 47 | 48 | # Wake up grbl 49 | s.write("\r\n\r\n") 50 | time.sleep(2) # Wait for grbl to initialize 51 | s.flushInput() # Flush startup text in serial input 52 | 53 | # Stream g-code to grbl 54 | for line in f: 55 | l = line.strip() # Strip all EOL characters for consistency 56 | print 'Sending: ' + l, 57 | s.write(l + '\n') # Send g-code block to grbl 58 | grbl_out = s.readline() # Wait for grbl response with carriage return 59 | print ' : ' + grbl_out.strip() 60 | 61 | # Wait here until grbl is finished to close serial port and file. 62 | raw_input(" Press to exit and disable grbl.") 63 | 64 | # Close file and serial port 65 | f.close() 66 | s.close() -------------------------------------------------------------------------------- /doc/script/stream.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """\ 3 | 4 | Stream g-code to grbl controller 5 | 6 | This script differs from the simple_stream.py script by 7 | tracking the number of characters in grbl's serial read 8 | buffer. This allows grbl to fetch the next line directly 9 | from the serial buffer and does not have to wait for a 10 | response from the computer. This effectively adds another 11 | buffer layer to prevent buffer starvation. 12 | 13 | CHANGELOG: 14 | - 20170531: Status report feedback at 1.0 second intervals. 15 | Configurable baudrate and report intervals. Bug fixes. 16 | - 20161212: Added push message feedback for simple streaming 17 | - 20140714: Updated baud rate to 115200. Added a settings 18 | write mode via simple streaming method. MIT-licensed. 19 | 20 | TODO: 21 | - Add realtime control commands during streaming. 22 | 23 | --------------------- 24 | The MIT License (MIT) 25 | 26 | Copyright (c) 2012-2017 Sungeun K. Jeon 27 | 28 | Permission is hereby granted, free of charge, to any person obtaining a copy 29 | of this software and associated documentation files (the "Software"), to deal 30 | in the Software without restriction, including without limitation the rights 31 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 32 | copies of the Software, and to permit persons to whom the Software is 33 | furnished to do so, subject to the following conditions: 34 | 35 | The above copyright notice and this permission notice shall be included in 36 | all copies or substantial portions of the Software. 37 | 38 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 39 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 40 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 41 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 42 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 43 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 44 | THE SOFTWARE. 45 | --------------------- 46 | """ 47 | 48 | import serial 49 | import re 50 | import time 51 | import sys 52 | import argparse 53 | import threading 54 | 55 | RX_BUFFER_SIZE = 128 56 | BAUD_RATE = 115200 57 | ENABLE_STATUS_REPORTS = True 58 | REPORT_INTERVAL = 1.0 # seconds 59 | 60 | is_run = True # Controls query timer 61 | 62 | # Define command line argument interface 63 | parser = argparse.ArgumentParser(description='Stream g-code file to grbl. (pySerial and argparse libraries required)') 64 | parser.add_argument('gcode_file', type=argparse.FileType('r'), 65 | help='g-code filename to be streamed') 66 | parser.add_argument('device_file', 67 | help='serial device path') 68 | parser.add_argument('-q','--quiet',action='store_true', default=False, 69 | help='suppress output text') 70 | parser.add_argument('-s','--settings',action='store_true', default=False, 71 | help='settings write mode') 72 | parser.add_argument('-c','--check',action='store_true', default=False, 73 | help='stream in check mode') 74 | args = parser.parse_args() 75 | 76 | # Periodic timer to query for status reports 77 | # TODO: Need to track down why this doesn't restart consistently before a release. 78 | def send_status_query(): 79 | s.write('?') 80 | 81 | def periodic_timer() : 82 | while is_run: 83 | send_status_query() 84 | time.sleep(REPORT_INTERVAL) 85 | 86 | 87 | # Initialize 88 | s = serial.Serial(args.device_file,BAUD_RATE) 89 | f = args.gcode_file 90 | verbose = True 91 | if args.quiet : verbose = False 92 | settings_mode = False 93 | if args.settings : settings_mode = True 94 | check_mode = False 95 | if args.check : check_mode = True 96 | 97 | # Wake up grbl 98 | print "Initializing Grbl..." 99 | s.write("\r\n\r\n") 100 | 101 | # Wait for grbl to initialize and flush startup text in serial input 102 | time.sleep(2) 103 | s.flushInput() 104 | 105 | if check_mode : 106 | print "Enabling Grbl Check-Mode: SND: [$C]", 107 | s.write("$C\n") 108 | while 1: 109 | grbl_out = s.readline().strip() # Wait for grbl response with carriage return 110 | if grbl_out.find('error') >= 0 : 111 | print "REC:",grbl_out 112 | print " Failed to set Grbl check-mode. Aborting..." 113 | quit() 114 | elif grbl_out.find('ok') >= 0 : 115 | if verbose: print 'REC:',grbl_out 116 | break 117 | 118 | start_time = time.time(); 119 | 120 | # Start status report periodic timer 121 | if ENABLE_STATUS_REPORTS : 122 | timerThread = threading.Thread(target=periodic_timer) 123 | timerThread.daemon = True 124 | timerThread.start() 125 | 126 | # Stream g-code to grbl 127 | l_count = 0 128 | error_count = 0 129 | if settings_mode: 130 | # Send settings file via simple call-response streaming method. Settings must be streamed 131 | # in this manner since the EEPROM accessing cycles shut-off the serial interrupt. 132 | print "SETTINGS MODE: Streaming", args.gcode_file.name, " to ", args.device_file 133 | for line in f: 134 | l_count += 1 # Iterate line counter 135 | # l_block = re.sub('\s|\(.*?\)','',line).upper() # Strip comments/spaces/new line and capitalize 136 | l_block = line.strip() # Strip all EOL characters for consistency 137 | if verbose: print "SND>"+str(l_count)+": \"" + l_block + "\"" 138 | s.write(l_block + '\n') # Send g-code block to grbl 139 | while 1: 140 | grbl_out = s.readline().strip() # Wait for grbl response with carriage return 141 | if grbl_out.find('ok') >= 0 : 142 | if verbose: print " REC<"+str(l_count)+": \""+grbl_out+"\"" 143 | break 144 | elif grbl_out.find('error') >= 0 : 145 | if verbose: print " REC<"+str(l_count)+": \""+grbl_out+"\"" 146 | error_count += 1 147 | break 148 | else: 149 | print " MSG: \""+grbl_out+"\"" 150 | else: 151 | # Send g-code program via a more agressive streaming protocol that forces characters into 152 | # Grbl's serial read buffer to ensure Grbl has immediate access to the next g-code command 153 | # rather than wait for the call-response serial protocol to finish. This is done by careful 154 | # counting of the number of characters sent by the streamer to Grbl and tracking Grbl's 155 | # responses, such that we never overflow Grbl's serial read buffer. 156 | g_count = 0 157 | c_line = [] 158 | for line in f: 159 | l_count += 1 # Iterate line counter 160 | l_block = re.sub('\s|\(.*?\)','',line).upper() # Strip comments/spaces/new line and capitalize 161 | # l_block = line.strip() 162 | c_line.append(len(l_block)+1) # Track number of characters in grbl serial read buffer 163 | grbl_out = '' 164 | while sum(c_line) >= RX_BUFFER_SIZE-1 | s.inWaiting() : 165 | out_temp = s.readline().strip() # Wait for grbl response 166 | if out_temp.find('ok') < 0 and out_temp.find('error') < 0 : 167 | print " MSG: \""+out_temp+"\"" # Debug response 168 | else : 169 | if out_temp.find('error') >= 0 : error_count += 1 170 | g_count += 1 # Iterate g-code counter 171 | if verbose: print " REC<"+str(g_count)+": \""+out_temp+"\"" 172 | del c_line[0] # Delete the block character count corresponding to the last 'ok' 173 | s.write(l_block + '\n') # Send g-code block to grbl 174 | if verbose: print "SND>"+str(l_count)+": \"" + l_block + "\"" 175 | # Wait until all responses have been received. 176 | while l_count > g_count : 177 | out_temp = s.readline().strip() # Wait for grbl response 178 | if out_temp.find('ok') < 0 and out_temp.find('error') < 0 : 179 | print " MSG: \""+out_temp+"\"" # Debug response 180 | else : 181 | if out_temp.find('error') >= 0 : error_count += 1 182 | g_count += 1 # Iterate g-code counter 183 | del c_line[0] # Delete the block character count corresponding to the last 'ok' 184 | if verbose: print " REC<"+str(g_count)+": \""+out_temp + "\"" 185 | 186 | # Wait for user input after streaming is completed 187 | print "\nG-code streaming finished!" 188 | end_time = time.time(); 189 | is_run = False; 190 | print " Time elapsed: ",end_time-start_time,"\n" 191 | if check_mode : 192 | if error_count > 0 : 193 | print "CHECK FAILED:",error_count,"errors found! See output for details.\n" 194 | else : 195 | print "CHECK PASSED: No errors found in g-code program.\n" 196 | else : 197 | print "WARNING: Wait until Grbl completes buffered g-code blocks before exiting." 198 | raw_input(" Press to exit and disable Grbl.") 199 | 200 | # Close file and serial port 201 | f.close() 202 | s.close() 203 | -------------------------------------------------------------------------------- /grbl/coolant_control.c: -------------------------------------------------------------------------------- 1 | /* 2 | coolant_control.c - coolant control methods 3 | Part of Grbl 4 | 5 | Copyright (c) 2012-2016 Sungeun K. Jeon for Gnea Research LLC 6 | 7 | Grbl is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | Grbl is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with Grbl. If not, see . 19 | */ 20 | 21 | #include "grbl.h" 22 | 23 | 24 | void coolant_init() 25 | { 26 | COOLANT_FLOOD_DDR |= (1 << COOLANT_FLOOD_BIT); // Configure as output pin. 27 | COOLANT_MIST_DDR |= (1 << COOLANT_MIST_BIT); // Configure as output pin. 28 | coolant_stop(); 29 | } 30 | 31 | 32 | // Returns current coolant output state. Overrides may alter it from programmed state. 33 | uint8_t coolant_get_state() 34 | { 35 | uint8_t cl_state = COOLANT_STATE_DISABLE; 36 | #ifdef INVERT_COOLANT_FLOOD_PIN 37 | if (bit_isfalse(COOLANT_FLOOD_PORT,(1 << COOLANT_FLOOD_BIT))) { 38 | #else 39 | if (bit_istrue(COOLANT_FLOOD_PORT,(1 << COOLANT_FLOOD_BIT))) { 40 | #endif 41 | cl_state |= COOLANT_STATE_FLOOD; 42 | } 43 | #ifdef INVERT_COOLANT_MIST_PIN 44 | if (bit_isfalse(COOLANT_MIST_PORT,(1 << COOLANT_MIST_BIT))) { 45 | #else 46 | if (bit_istrue(COOLANT_MIST_PORT,(1 << COOLANT_MIST_BIT))) { 47 | #endif 48 | cl_state |= COOLANT_STATE_MIST; 49 | } 50 | return(cl_state); 51 | } 52 | 53 | 54 | // Directly called by coolant_init(), coolant_set_state(), and mc_reset(), which can be at 55 | // an interrupt-level. No report flag set, but only called by routines that don't need it. 56 | void coolant_stop() 57 | { 58 | #ifdef INVERT_COOLANT_FLOOD_PIN 59 | COOLANT_FLOOD_PORT |= (1 << COOLANT_FLOOD_BIT); 60 | #else 61 | COOLANT_FLOOD_PORT &= ~(1 << COOLANT_FLOOD_BIT); 62 | #endif 63 | #ifdef INVERT_COOLANT_MIST_PIN 64 | COOLANT_MIST_PORT |= (1 << COOLANT_MIST_BIT); 65 | #else 66 | COOLANT_MIST_PORT &= ~(1 << COOLANT_MIST_BIT); 67 | #endif 68 | } 69 | 70 | 71 | // Main program only. Immediately sets flood coolant running state and also mist coolant, 72 | // if enabled. Also sets a flag to report an update to a coolant state. 73 | // Called by coolant toggle override, parking restore, parking retract, sleep mode, g-code 74 | // parser program end, and g-code parser coolant_sync(). 75 | void coolant_set_state(uint8_t mode) 76 | { 77 | if (sys.abort) { return; } // Block during abort. 78 | 79 | if (mode == COOLANT_DISABLE) { 80 | 81 | coolant_stop(); 82 | 83 | } else { 84 | 85 | if (mode & COOLANT_FLOOD_ENABLE) { 86 | #ifdef INVERT_COOLANT_FLOOD_PIN 87 | COOLANT_FLOOD_PORT &= ~(1 << COOLANT_FLOOD_BIT); 88 | #else 89 | COOLANT_FLOOD_PORT |= (1 << COOLANT_FLOOD_BIT); 90 | #endif 91 | } 92 | 93 | if (mode & COOLANT_MIST_ENABLE) { 94 | #ifdef INVERT_COOLANT_MIST_PIN 95 | COOLANT_MIST_PORT &= ~(1 << COOLANT_MIST_BIT); 96 | #else 97 | COOLANT_MIST_PORT |= (1 << COOLANT_MIST_BIT); 98 | #endif 99 | } 100 | 101 | } 102 | sys.report_ovr_counter = 0; // Set to report change immediately 103 | } 104 | 105 | 106 | // G-code parser entry-point for setting coolant state. Forces a planner buffer sync and bails 107 | // if an abort or check-mode is active. 108 | void coolant_sync(uint8_t mode) 109 | { 110 | if (sys.state == STATE_CHECK_MODE) { return; } 111 | protocol_buffer_synchronize(); // Ensure coolant turns on when specified in program. 112 | coolant_set_state(mode); 113 | } 114 | -------------------------------------------------------------------------------- /grbl/coolant_control.h: -------------------------------------------------------------------------------- 1 | /* 2 | coolant_control.h - spindle control methods 3 | Part of Grbl 4 | 5 | Copyright (c) 2012-2016 Sungeun K. Jeon for Gnea Research LLC 6 | 7 | Grbl is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | Grbl is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with Grbl. If not, see . 19 | */ 20 | 21 | #ifndef coolant_control_h 22 | #define coolant_control_h 23 | 24 | #define COOLANT_NO_SYNC false 25 | #define COOLANT_FORCE_SYNC true 26 | 27 | #define COOLANT_STATE_DISABLE 0 // Must be zero 28 | #define COOLANT_STATE_FLOOD bit(0) 29 | #define COOLANT_STATE_MIST bit(1) 30 | 31 | 32 | // Initializes coolant control pins. 33 | void coolant_init(); 34 | 35 | // Returns current coolant output state. Overrides may alter it from programmed state. 36 | uint8_t coolant_get_state(); 37 | 38 | // Immediately disables coolant pins. 39 | void coolant_stop(); 40 | 41 | // Sets the coolant pins according to state specified. 42 | void coolant_set_state(uint8_t mode); 43 | 44 | // G-code parser entry-point for setting coolant states. Checks for and executes additional conditions. 45 | void coolant_sync(uint8_t mode); 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /grbl/eeprom.c: -------------------------------------------------------------------------------- 1 | // This file has been prepared for Doxygen automatic documentation generation. 2 | /*! \file ******************************************************************** 3 | * 4 | * Atmel Corporation 5 | * 6 | * \li File: eeprom.c 7 | * \li Compiler: IAR EWAAVR 3.10c 8 | * \li Support mail: avr@atmel.com 9 | * 10 | * \li Supported devices: All devices with split EEPROM erase/write 11 | * capabilities can be used. 12 | * The example is written for ATmega48. 13 | * 14 | * \li AppNote: AVR103 - Using the EEPROM Programming Modes. 15 | * 16 | * \li Description: Example on how to use the split EEPROM erase/write 17 | * capabilities in e.g. ATmega48. All EEPROM 18 | * programming modes are tested, i.e. Erase+Write, 19 | * Erase-only and Write-only. 20 | * 21 | * $Revision: 1.6 $ 22 | * $Date: Friday, February 11, 2005 07:16:44 UTC $ 23 | ****************************************************************************/ 24 | #include 25 | #include 26 | 27 | /* These EEPROM bits have different names on different devices. */ 28 | #ifndef EEPE 29 | #define EEPE EEWE //!< EEPROM program/write enable. 30 | #define EEMPE EEMWE //!< EEPROM master program/write enable. 31 | #endif 32 | 33 | /* These two are unfortunately not defined in the device include files. */ 34 | #define EEPM1 5 //!< EEPROM Programming Mode Bit 1. 35 | #define EEPM0 4 //!< EEPROM Programming Mode Bit 0. 36 | 37 | /* Define to reduce code size. */ 38 | #define EEPROM_IGNORE_SELFPROG //!< Remove SPM flag polling. 39 | 40 | /*! \brief Read byte from EEPROM. 41 | * 42 | * This function reads one byte from a given EEPROM address. 43 | * 44 | * \note The CPU is halted for 4 clock cycles during EEPROM read. 45 | * 46 | * \param addr EEPROM address to read from. 47 | * \return The byte read from the EEPROM address. 48 | */ 49 | unsigned char eeprom_get_char( unsigned int addr ) 50 | { 51 | do {} while( EECR & (1< 0; size--) { 133 | checksum = (checksum << 1) || (checksum >> 7); 134 | checksum += *source; 135 | eeprom_put_char(destination++, *(source++)); 136 | } 137 | eeprom_put_char(destination, checksum); 138 | } 139 | 140 | int memcpy_from_eeprom_with_checksum(char *destination, unsigned int source, unsigned int size) { 141 | unsigned char data, checksum = 0; 142 | for(; size > 0; size--) { 143 | data = eeprom_get_char(source++); 144 | checksum = (checksum << 1) || (checksum >> 7); 145 | checksum += data; 146 | *(destination++) = data; 147 | } 148 | return(checksum == eeprom_get_char(source)); 149 | } 150 | 151 | // end of file 152 | -------------------------------------------------------------------------------- /grbl/eeprom.h: -------------------------------------------------------------------------------- 1 | /* 2 | eeprom.h - EEPROM methods 3 | Part of Grbl 4 | 5 | Copyright (c) 2009-2011 Simen Svale Skogsrud 6 | 7 | Grbl is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | Grbl is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with Grbl. If not, see . 19 | */ 20 | 21 | #ifndef eeprom_h 22 | #define eeprom_h 23 | 24 | unsigned char eeprom_get_char(unsigned int addr); 25 | void eeprom_put_char(unsigned int addr, unsigned char new_value); 26 | void memcpy_to_eeprom_with_checksum(unsigned int destination, char *source, unsigned int size); 27 | int memcpy_from_eeprom_with_checksum(char *destination, unsigned int source, unsigned int size); 28 | 29 | #endif 30 | -------------------------------------------------------------------------------- /grbl/examples/grblUpload/grblUpload.ino: -------------------------------------------------------------------------------- 1 | /*********************************************************************** 2 | This sketch compiles and uploads Grbl to your 328p-based Arduino! 3 | 4 | To use: 5 | - First make sure you have imported Grbl source code into your Arduino 6 | IDE. There are details on our Github website on how to do this. 7 | 8 | - Select your Arduino Board and Serial Port in the Tools drop-down menu. 9 | NOTE: Grbl only officially supports 328p-based Arduinos, like the Uno. 10 | Using other boards will likely not work! 11 | 12 | - Then just click 'Upload'. That's it! 13 | 14 | For advanced users: 15 | If you'd like to see what else Grbl can do, there are some additional 16 | options for customization and features you can enable or disable. 17 | Navigate your file system to where the Arduino IDE has stored the Grbl 18 | source code files, open the 'config.h' file in your favorite text 19 | editor. Inside are dozens of feature descriptions and #defines. Simply 20 | comment or uncomment the #defines or alter their assigned values, save 21 | your changes, and then click 'Upload' here. 22 | 23 | Copyright (c) 2015 Sungeun K. Jeon 24 | Released under the MIT-license. See license.txt for details. 25 | ***********************************************************************/ 26 | 27 | #include 28 | 29 | // Do not alter this file! 30 | -------------------------------------------------------------------------------- /grbl/examples/grblUpload/license.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Sungeun K. Jeon 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /grbl/gcode.h: -------------------------------------------------------------------------------- 1 | /* 2 | gcode.h - rs274/ngc parser. 3 | Part of Grbl 4 | 5 | Copyright (c) 2017-2018 Gauthier Briere 6 | Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC 7 | Copyright (c) 2009-2011 Simen Svale Skogsrud 8 | 9 | Grbl is free software: you can redistribute it and/or modify 10 | it under the terms of the GNU General Public License as published by 11 | the Free Software Foundation, either version 3 of the License, or 12 | (at your option) any later version. 13 | 14 | Grbl is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | GNU General Public License for more details. 18 | 19 | You should have received a copy of the GNU General Public License 20 | along with Grbl. If not, see . 21 | */ 22 | 23 | #ifndef gcode_h 24 | #define gcode_h 25 | 26 | 27 | // Define modal group internal numbers for checking multiple command violations and tracking the 28 | // type of command that is called in the block. A modal group is a group of g-code commands that are 29 | // mutually exclusive, or cannot exist on the same line, because they each toggle a state or execute 30 | // a unique motion. These are defined in the NIST RS274-NGC v3 g-code standard, available online, 31 | // and are similar/identical to other g-code interpreters by manufacturers (Haas,Fanuc,Mazak,etc). 32 | // NOTE: Modal group define values must be sequential and starting from zero. 33 | #define MODAL_GROUP_G0 0 // [G4,G10,G28,G28.1,G30,G30.1,G53,G92,G92.1] Non-modal 34 | #define MODAL_GROUP_G1 1 // [G0,G1,G2,G3,G38.2,G38.3,G38.4,G38.5,G80] Motion 35 | #define MODAL_GROUP_G2 2 // [G17,G18,G19] Plane selection 36 | #define MODAL_GROUP_G3 3 // [G90,G91] Distance mode 37 | #define MODAL_GROUP_G4 4 // [G91.1] Arc IJK distance mode 38 | #define MODAL_GROUP_G5 5 // [G93,G94] Feed rate mode 39 | #define MODAL_GROUP_G6 6 // [G20,G21] Units 40 | #define MODAL_GROUP_G7 7 // [G40] Cutter radius compensation mode. G41/42 NOT SUPPORTED. 41 | #define MODAL_GROUP_G8 8 // [G43.1,G49] Tool length offset 42 | #define MODAL_GROUP_G12 9 // [G54,G55,G56,G57,G58,G59] Coordinate system selection 43 | #define MODAL_GROUP_G13 10 // [G61] Control mode 44 | 45 | #define MODAL_GROUP_M4 11 // [M0,M1,M2,M30] Stopping 46 | #define MODAL_GROUP_M7 12 // [M3,M4,M5] Spindle turning 47 | #define MODAL_GROUP_M8 13 // [M7,M8,M9] Coolant control 48 | #define MODAL_GROUP_M9 14 // [M56] Override control 49 | 50 | // Define command actions for within execution-type modal groups (motion, stopping, non-modal). Used 51 | // internally by the parser to know which command to execute. 52 | // NOTE: Some macro values are assigned specific values to make g-code state reporting and parsing 53 | // compile a litte smaller. Necessary due to being completely out of flash on the 328p. Although not 54 | // ideal, just be careful with values that state 'do not alter' and check both report.c and gcode.c 55 | // to see how they are used, if you need to alter them. 56 | 57 | // Modal Group G0: Non-modal actions 58 | #define NON_MODAL_NO_ACTION 0 // (Default: Must be zero) 59 | #define NON_MODAL_DWELL 4 // G4 (Do not alter value) 60 | #define NON_MODAL_SET_COORDINATE_DATA 10 // G10 (Do not alter value) 61 | #define NON_MODAL_GO_HOME_0 28 // G28 (Do not alter value) 62 | #define NON_MODAL_SET_HOME_0 38 // G28.1 (Do not alter value) 63 | #define NON_MODAL_GO_HOME_1 30 // G30 (Do not alter value) 64 | #define NON_MODAL_SET_HOME_1 40 // G30.1 (Do not alter value) 65 | #define NON_MODAL_ABSOLUTE_OVERRIDE 53 // G53 (Do not alter value) 66 | #define NON_MODAL_SET_COORDINATE_OFFSET 92 // G92 (Do not alter value) 67 | #define NON_MODAL_RESET_COORDINATE_OFFSET 102 //G92.1 (Do not alter value) 68 | 69 | // Modal Group G1: Motion modes 70 | #define MOTION_MODE_SEEK 0 // G0 (Default: Must be zero) 71 | #define MOTION_MODE_LINEAR 1 // G1 (Do not alter value) 72 | #define MOTION_MODE_CW_ARC 2 // G2 (Do not alter value) 73 | #define MOTION_MODE_CCW_ARC 3 // G3 (Do not alter value) 74 | #define MOTION_MODE_PROBE_TOWARD 140 // G38.2 (Do not alter value) 75 | #define MOTION_MODE_PROBE_TOWARD_NO_ERROR 141 // G38.3 (Do not alter value) 76 | #define MOTION_MODE_PROBE_AWAY 142 // G38.4 (Do not alter value) 77 | #define MOTION_MODE_PROBE_AWAY_NO_ERROR 143 // G38.5 (Do not alter value) 78 | #define MOTION_MODE_NONE 80 // G80 (Do not alter value) 79 | 80 | // Modal Group G2: Plane select 81 | #define PLANE_SELECT_XY 0 // G17 (Default: Must be zero) 82 | #define PLANE_SELECT_ZX 1 // G18 (Do not alter value) 83 | #define PLANE_SELECT_YZ 2 // G19 (Do not alter value) 84 | 85 | // Modal Group G3: Distance mode 86 | #define DISTANCE_MODE_ABSOLUTE 0 // G90 (Default: Must be zero) 87 | #define DISTANCE_MODE_INCREMENTAL 1 // G91 (Do not alter value) 88 | 89 | // Modal Group G4: Arc IJK distance mode 90 | #define DISTANCE_ARC_MODE_INCREMENTAL 0 // G91.1 (Default: Must be zero) 91 | 92 | // Modal Group M4: Program flow 93 | #define PROGRAM_FLOW_RUNNING 0 // (Default: Must be zero) 94 | #define PROGRAM_FLOW_PAUSED 3 // M0 95 | #define PROGRAM_FLOW_OPTIONAL_STOP 1 // M1 NOTE: Not supported, but valid and ignored. 96 | #define PROGRAM_FLOW_COMPLETED_M2 2 // M2 (Do not alter value) 97 | #define PROGRAM_FLOW_COMPLETED_M30 30 // M30 (Do not alter value) 98 | 99 | // Modal Group G5: Feed rate mode 100 | #define FEED_RATE_MODE_UNITS_PER_MIN 0 // G94 (Default: Must be zero) 101 | #define FEED_RATE_MODE_INVERSE_TIME 1 // G93 (Do not alter value) 102 | 103 | // Modal Group G6: Units mode 104 | #define UNITS_MODE_MM 0 // G21 (Default: Must be zero) 105 | #define UNITS_MODE_INCHES 1 // G20 (Do not alter value) 106 | 107 | // Modal Group G7: Cutter radius compensation mode 108 | #define CUTTER_COMP_DISABLE 0 // G40 (Default: Must be zero) 109 | 110 | // Modal Group G13: Control mode 111 | #define CONTROL_MODE_EXACT_PATH 0 // G61 (Default: Must be zero) 112 | 113 | // Modal Group M7: Spindle control 114 | #define SPINDLE_DISABLE 0 // M5 (Default: Must be zero) 115 | #define SPINDLE_ENABLE_CW PL_COND_FLAG_SPINDLE_CW // M3 (NOTE: Uses planner condition bit flag) 116 | #define SPINDLE_ENABLE_CCW PL_COND_FLAG_SPINDLE_CCW // M4 (NOTE: Uses planner condition bit flag) 117 | 118 | // Modal Group M8: Coolant control 119 | #define COOLANT_DISABLE 0 // M9 (Default: Must be zero) 120 | #define COOLANT_FLOOD_ENABLE PL_COND_FLAG_COOLANT_FLOOD // M8 (NOTE: Uses planner condition bit flag) 121 | #define COOLANT_MIST_ENABLE PL_COND_FLAG_COOLANT_MIST // M7 (NOTE: Uses planner condition bit flag) 122 | 123 | // Modal Group G8: Tool length offset 124 | #define TOOL_LENGTH_OFFSET_CANCEL 0 // G49 (Default: Must be zero) 125 | #define TOOL_LENGTH_OFFSET_ENABLE_DYNAMIC 1 // G43.1 126 | 127 | // Modal Group M9: Override control 128 | #ifdef DEACTIVATE_PARKING_UPON_INIT 129 | #define OVERRIDE_DISABLED 0 // (Default: Must be zero) 130 | #define OVERRIDE_PARKING_MOTION 1 // M56 131 | #else 132 | #define OVERRIDE_PARKING_MOTION 0 // M56 (Default: Must be zero) 133 | #define OVERRIDE_DISABLED 1 // Parking disabled. 134 | #endif 135 | 136 | // Modal Group G12: Active work coordinate system 137 | // N/A: Stores coordinate system value (54-59) to change to. 138 | 139 | // Define parameter word mapping. 140 | // Updated to 32 bits tou support more than 16 values... Needed for new axis U, V & W 141 | #define DWORD_F 0 142 | #define DWORD_I 1 143 | #define DWORD_J 2 144 | #define DWORD_K 3 145 | #define DWORD_L 4 146 | #define DWORD_N 5 147 | #define DWORD_P 6 148 | #define DWORD_R 7 149 | #define DWORD_S 8 150 | #define DWORD_T 9 151 | #define DWORD_X 10 152 | #define DWORD_Y 11 153 | #define DWORD_Z 12 154 | #define DWORD_A 13 155 | #define DWORD_B 14 156 | #define DWORD_C 15 157 | #define DWORD_U 16 158 | #define DWORD_V 17 159 | #define DWORD_W 18 160 | 161 | // Define g-code parser position updating flags 162 | #define GC_UPDATE_POS_TARGET 0 // Must be zero 163 | #define GC_UPDATE_POS_SYSTEM 1 164 | #define GC_UPDATE_POS_NONE 2 165 | 166 | // Define probe cycle exit states and assign proper position updating. 167 | #define GC_PROBE_FOUND GC_UPDATE_POS_SYSTEM 168 | #define GC_PROBE_ABORT GC_UPDATE_POS_NONE 169 | #define GC_PROBE_FAIL_INIT GC_UPDATE_POS_NONE 170 | #define GC_PROBE_FAIL_END GC_UPDATE_POS_TARGET 171 | #ifdef SET_CHECK_MODE_PROBE_TO_START 172 | #define GC_PROBE_CHECK_MODE GC_UPDATE_POS_NONE 173 | #else 174 | #define GC_PROBE_CHECK_MODE GC_UPDATE_POS_TARGET 175 | #endif 176 | 177 | // Define gcode parser flags for handling special cases. 178 | #define GC_PARSER_NONE 0 // Must be zero. 179 | #define GC_PARSER_JOG_MOTION bit(0) 180 | #define GC_PARSER_CHECK_MANTISSA bit(1) 181 | #define GC_PARSER_ARC_IS_CLOCKWISE bit(2) 182 | #define GC_PARSER_PROBE_IS_AWAY bit(3) 183 | #define GC_PARSER_PROBE_IS_NO_ERROR bit(4) 184 | #define GC_PARSER_LASER_FORCE_SYNC bit(5) 185 | #define GC_PARSER_LASER_DISABLE bit(6) 186 | #define GC_PARSER_LASER_ISMOTION bit(7) 187 | 188 | 189 | // NOTE: When this struct is zeroed, the above defines set the defaults for the system. 190 | typedef struct { 191 | uint8_t motion; // {G0,G1,G2,G3,G38.2,G80} 192 | uint8_t feed_rate; // {G93,G94} 193 | uint8_t units; // {G20,G21} 194 | uint8_t distance; // {G90,G91} 195 | // uint8_t distance_arc; // {G91.1} NOTE: Don't track. Only default supported. 196 | uint8_t plane_select; // {G17,G18,G19} 197 | // uint8_t cutter_comp; // {G40} NOTE: Don't track. Only default supported. 198 | uint8_t tool_length; // {G43.1,G49} 199 | uint8_t coord_select; // {G54,G55,G56,G57,G58,G59} 200 | // uint8_t control; // {G61} NOTE: Don't track. Only default supported. 201 | uint8_t program_flow; // {M0,M1,M2,M30} 202 | uint8_t coolant; // {M7,M8,M9} 203 | uint8_t spindle; // {M3,M4,M5} 204 | uint8_t override; // {M56} 205 | } gc_modal_t; 206 | 207 | typedef struct { 208 | float f; // Feed 209 | #if N_AXIS > 3 210 | float ijk[N_AXIS]; // axes offsets for XYZ & AB(C) 211 | #else 212 | float ijk[3]; // I,J,K Axis arc offsets 213 | #endif 214 | uint8_t l; // G10 or canned cycles parameters 215 | int32_t n; // Line number 216 | float p; // G10 or dwell parameters 217 | // float q; // G82 peck drilling 218 | float r; // Arc radius 219 | float s; // Spindle speed 220 | uint8_t t; // Tool selection 221 | #if N_AXIS > 3 222 | float xyz[N_AXIS]; // X,Y,Z Translational axes & A,B,(C) 223 | #else 224 | float xyz[3]; // X,Y,Z Translational axes 225 | #endif 226 | } gc_values_t; 227 | 228 | 229 | typedef struct { 230 | gc_modal_t modal; 231 | 232 | float spindle_speed; // RPM 233 | float feed_rate; // Millimeters/min 234 | uint8_t tool; // Tracks tool number. NOT USED. 235 | int32_t line_number; // Last line number sent 236 | 237 | float position[N_AXIS]; // Where the interpreter considers the tool to be at this point in the code 238 | 239 | float coord_system[N_AXIS]; // Current work coordinate system (G54+). Stores offset from absolute machine 240 | // position in mm. Loaded from EEPROM when called. 241 | float coord_offset[N_AXIS]; // Retains the G92 coordinate offset (work coordinates) relative to 242 | // machine zero in mm. Non-persistent. Cleared upon reset and boot. 243 | float tool_length_offset; // Tracks tool length offset value when enabled. 244 | } parser_state_t; 245 | extern parser_state_t gc_state; 246 | 247 | 248 | typedef struct { 249 | uint8_t non_modal_command; 250 | gc_modal_t modal; 251 | gc_values_t values; 252 | } parser_block_t; 253 | 254 | 255 | // Initialize the parser 256 | void gc_init(); 257 | 258 | // Execute one block of rs275/ngc/g-code 259 | uint8_t gc_execute_line(char *line); 260 | 261 | // Set g-code parser position. Input in steps. 262 | void gc_sync_position(); 263 | 264 | #endif 265 | -------------------------------------------------------------------------------- /grbl/grbl.h: -------------------------------------------------------------------------------- 1 | /* 2 | grbl.h - main Grbl include file 3 | Part of Grbl 4 | 5 | Copyright (c) 2017-2018 Gauthier Briere 6 | Copyright (c) 2015-2016 Sungeun K. Jeon for Gnea Research LLC 7 | 8 | Grbl is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | Grbl is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with Grbl. If not, see . 20 | */ 21 | 22 | #ifndef grbl_h 23 | #define grbl_h 24 | 25 | // Grbl versioning system 26 | #define GRBL_VERSION "1.1n" 27 | #define GRBL_VERSION_BUILD "20200424" 28 | 29 | // Define standard libraries used by Grbl. 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | 42 | // Define the Grbl system include files. NOTE: Do not alter organization. 43 | #include "config.h" 44 | #include "nuts_bolts.h" 45 | #include "settings.h" 46 | #include "system.h" 47 | #include "defaults.h" 48 | #include "cpu_map.h" 49 | #include "planner.h" 50 | #include "coolant_control.h" 51 | #include "eeprom.h" 52 | #include "gcode.h" 53 | #include "limits.h" 54 | #include "motion_control.h" 55 | #include "planner.h" 56 | #include "print.h" 57 | #include "probe.h" 58 | #include "protocol.h" 59 | #include "report.h" 60 | #include "serial.h" 61 | #include "spindle_control.h" 62 | #include "stepper.h" 63 | #include "jog.h" 64 | #include "sleep.h" 65 | 66 | // --------------------------------------------------------------------------------------- 67 | // COMPILE-TIME ERROR CHECKING OF DEFINE VALUES: 68 | 69 | #ifndef HOMING_CYCLE_0 70 | #error "Required HOMING_CYCLE_0 not defined." 71 | #endif 72 | 73 | #if defined(PARKING_ENABLE) 74 | #if defined(HOMING_FORCE_SET_ORIGIN) 75 | #error "HOMING_FORCE_SET_ORIGIN is not supported with PARKING_ENABLE at this time." 76 | #endif 77 | #endif 78 | 79 | #if defined(ENABLE_PARKING_OVERRIDE_CONTROL) 80 | #if !defined(PARKING_ENABLE) 81 | #error "ENABLE_PARKING_OVERRIDE_CONTROL must be enabled with PARKING_ENABLE." 82 | #endif 83 | #endif 84 | 85 | #if defined(SPINDLE_PWM_MIN_VALUE) 86 | #if !(SPINDLE_PWM_MIN_VALUE > 0) 87 | #error "SPINDLE_PWM_MIN_VALUE must be greater than zero." 88 | #endif 89 | #endif 90 | 91 | #if (REPORT_WCO_REFRESH_BUSY_COUNT < REPORT_WCO_REFRESH_IDLE_COUNT) 92 | #error "WCO busy refresh is less than idle refresh." 93 | #endif 94 | #if (REPORT_OVR_REFRESH_BUSY_COUNT < REPORT_OVR_REFRESH_IDLE_COUNT) 95 | #error "Override busy refresh is less than idle refresh." 96 | #endif 97 | #if (REPORT_WCO_REFRESH_IDLE_COUNT < 2) 98 | #error "WCO refresh must be greater than one." 99 | #endif 100 | #if (REPORT_OVR_REFRESH_IDLE_COUNT < 1) 101 | #error "Override refresh must be greater than zero." 102 | #endif 103 | 104 | // --------------------------------------------------------------------------------------- 105 | 106 | #endif 107 | -------------------------------------------------------------------------------- /grbl/jog.c: -------------------------------------------------------------------------------- 1 | /* 2 | jog.h - Jogging methods 3 | Part of Grbl 4 | 5 | Copyright (c) 2016 Sungeun K. Jeon for Gnea Research LLC 6 | 7 | Grbl is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | Grbl is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with Grbl. If not, see . 19 | */ 20 | 21 | #include "grbl.h" 22 | 23 | 24 | // Sets up valid jog motion received from g-code parser, checks for soft-limits, and executes the jog. 25 | uint8_t jog_execute(plan_line_data_t *pl_data, parser_block_t *gc_block) 26 | { 27 | // Initialize planner data struct for jogging motions. 28 | // NOTE: Spindle and coolant are allowed to fully function with overrides during a jog. 29 | pl_data->feed_rate = gc_block->values.f; 30 | pl_data->condition |= PL_COND_FLAG_NO_FEED_OVERRIDE; 31 | pl_data->line_number = gc_block->values.n; 32 | 33 | if (bit_istrue(settings.flags,BITFLAG_SOFT_LIMIT_ENABLE)) { 34 | if (system_check_travel_limits(gc_block->values.xyz)) { return(STATUS_TRAVEL_EXCEEDED); } 35 | } 36 | 37 | // Valid jog command. Plan, set state, and execute. 38 | mc_line(gc_block->values.xyz,pl_data); 39 | if (sys.state == STATE_IDLE) { 40 | if (plan_get_current_block() != NULL) { // Check if there is a block to execute. 41 | sys.state = STATE_JOG; 42 | st_prep_buffer(); 43 | st_wake_up(); // NOTE: Manual start. No state machine required. 44 | } 45 | } 46 | 47 | return(STATUS_OK); 48 | } 49 | -------------------------------------------------------------------------------- /grbl/jog.h: -------------------------------------------------------------------------------- 1 | /* 2 | jog.h - Jogging methods 3 | Part of Grbl 4 | 5 | Copyright (c) 2016 Sungeun K. Jeon for Gnea Research LLC 6 | 7 | Grbl is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | Grbl is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with Grbl. If not, see . 19 | */ 20 | 21 | #ifndef jog_h 22 | #define jog_h 23 | 24 | #include "gcode.h" 25 | 26 | // System motion line numbers must be zero. 27 | #define JOG_LINE_NUMBER 0 28 | 29 | // Sets up valid jog motion received from g-code parser, checks for soft-limits, and executes the jog. 30 | uint8_t jog_execute(plan_line_data_t *pl_data, parser_block_t *gc_block); 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /grbl/limits.h: -------------------------------------------------------------------------------- 1 | /* 2 | limits.h - code pertaining to limit-switches and performing the homing cycle 3 | Part of Grbl 4 | 5 | Copyright (c) 2012-2016 Sungeun K. Jeon for Gnea Research LLC 6 | Copyright (c) 2009-2011 Simen Svale Skogsrud 7 | 8 | Grbl is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | Grbl is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with Grbl. If not, see . 20 | */ 21 | 22 | #ifndef limits_h 23 | #define limits_h 24 | 25 | 26 | // Initialize the limits module 27 | void limits_init(); 28 | 29 | // Disables hard limits. 30 | void limits_disable(); 31 | 32 | // Returns limit state as a bit-wise uint8 variable. 33 | uint8_t limits_get_state(); 34 | 35 | // Perform one portion of the homing cycle based on the input settings. 36 | void limits_go_home(uint8_t cycle_mask); 37 | 38 | // Check for soft limit violations 39 | void limits_soft_check(float *target); 40 | 41 | // Hard limit error for RAMPS non interrupt hardware limits 42 | #ifdef ENABLE_RAMPS_HW_LIMITS 43 | void ramps_hard_limit(); 44 | #endif 45 | #endif 46 | -------------------------------------------------------------------------------- /grbl/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | main.c - An embedded CNC Controller with rs274/ngc (g-code) support 3 | Part of Grbl 4 | 5 | Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC 6 | Copyright (c) 2009-2011 Simen Svale Skogsrud 7 | 8 | Grbl is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | Grbl is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with Grbl. If not, see . 20 | */ 21 | 22 | #include "grbl.h" 23 | 24 | 25 | // Declare system global variable structure 26 | system_t sys; 27 | int32_t sys_position[N_AXIS]; // Real-time machine (aka home) position vector in steps. 28 | int32_t sys_probe_position[N_AXIS]; // Last probe position in machine coordinates and steps. 29 | volatile uint8_t sys_probe_state; // Probing state value. Used to coordinate the probing cycle with stepper ISR. 30 | volatile uint8_t sys_rt_exec_state; // Global realtime executor bitflag variable for state management. See EXEC bitmasks. 31 | volatile uint8_t sys_rt_exec_alarm; // Global realtime executor bitflag variable for setting various alarms. 32 | volatile uint8_t sys_rt_exec_motion_override; // Global realtime executor bitflag variable for motion-based overrides. 33 | volatile uint8_t sys_rt_exec_accessory_override; // Global realtime executor bitflag variable for spindle/coolant overrides. 34 | uint8_t axis_X_mask = 0; // Global mask for axis X bits 35 | uint8_t axis_Y_mask = 0; // Global mask for axis Y bits 36 | uint8_t axis_Z_mask = 0; // Global mask for axis Z bits 37 | uint8_t axis_A_mask = 0; // Global mask for axis A bits 38 | uint8_t axis_B_mask = 0; // Global mask for axis B bits 39 | uint8_t axis_C_mask = 0; // Global mask for axis C bits 40 | uint8_t axis_U_mask = 0; // Global mask for axis C bits 41 | uint8_t axis_V_mask = 0; // Global mask for axis C bits 42 | uint8_t axis_W_mask = 0; // Global mask for axis C bits 43 | unsigned char axis_name[N_AXIS]; // Global table of axis names 44 | #ifdef DEBUG 45 | volatile uint8_t sys_rt_exec_debug; 46 | #endif 47 | #ifdef SORT_REPORT_BY_AXIS_NAME 48 | uint8_t n_axis_report; 49 | #endif 50 | 51 | int main(void) 52 | { 53 | // Initialize system upon power-up. 54 | serial_init(); // Setup serial baud rate and interrupts 55 | settings_init(); // Load Grbl settings from EEPROM 56 | stepper_init(); // Configure stepper pins and interrupt timers 57 | system_init(); // Configure pinout pins and pin-change interrupt 58 | 59 | // Initialize axis mask bits (ability to axis renaming and cloning) 60 | // and global table of axis names. 61 | if (AXIS_1_NAME == 'X') { 62 | axis_X_mask |= (1< 3 351 | if ((AXIS_4_NAME != AXIS_3_NAME) && (AXIS_4_NAME != AXIS_2_NAME) && (AXIS_4_NAME != AXIS_1_NAME)) { 352 | n_axis_report++; 353 | } 354 | #endif 355 | #if N_AXIS > 4 356 | if ((AXIS_5_NAME != AXIS_4_NAME) && (AXIS_5_NAME != AXIS_3_NAME) && (AXIS_5_NAME != AXIS_2_NAME) && (AXIS_5_NAME != AXIS_1_NAME)) { 357 | n_axis_report++; 358 | } 359 | #endif 360 | #if N_AXIS > 5 361 | if ((AXIS_6_NAME != AXIS_5_NAME) && (AXIS_6_NAME != AXIS_4_NAME) && (AXIS_6_NAME != AXIS_3_NAME) && (AXIS_6_NAME != AXIS_2_NAME) && (AXIS_6_NAME != AXIS_1_NAME)) { 362 | n_axis_report++; 363 | } 364 | #endif 365 | #else 366 | n_axis_report = N_AXIS; 367 | #endif 368 | #endif 369 | 370 | memset(sys_position,0,sizeof(sys_position)); // Clear machine position. 371 | sei(); // Enable interrupts 372 | 373 | // Initialize system state. 374 | #ifdef FORCE_INITIALIZATION_ALARM 375 | // Force Grbl into an ALARM state upon a power-cycle or hard reset. 376 | sys.state = STATE_ALARM; 377 | #else 378 | sys.state = STATE_IDLE; 379 | #endif 380 | 381 | // Check for power-up and set system alarm if homing is enabled to force homing cycle 382 | // by setting Grbl's alarm state. Alarm locks out all g-code commands, including the 383 | // startup scripts, but allows access to settings and internal commands. Only a homing 384 | // cycle '$H' or kill alarm locks '$X' will disable the alarm. 385 | // NOTE: The startup script will run after successful completion of the homing cycle, but 386 | // not after disabling the alarm locks. Prevents motion startup blocks from crashing into 387 | // things uncontrollably. Very bad. 388 | #ifdef HOMING_INIT_LOCK 389 | if (bit_istrue(settings.flags,BITFLAG_HOMING_ENABLE)) { sys.state = STATE_ALARM; } 390 | #endif 391 | 392 | // Grbl initialization loop upon power-up or a system abort. For the latter, all processes 393 | // will return to this loop to be cleanly re-initialized. 394 | for(;;) { 395 | 396 | // Reset system variables. 397 | uint8_t prior_state = sys.state; 398 | memset(&sys, 0, sizeof(system_t)); // Clear system struct variable. 399 | sys.state = prior_state; 400 | sys.f_override = DEFAULT_FEED_OVERRIDE; // Set to 100% 401 | sys.r_override = DEFAULT_RAPID_OVERRIDE; // Set to 100% 402 | sys.spindle_speed_ovr = DEFAULT_SPINDLE_SPEED_OVERRIDE; // Set to 100% 403 | memset(sys_probe_position,0,sizeof(sys_probe_position)); // Clear probe position. 404 | sys_probe_state = 0; 405 | sys_rt_exec_state = 0; 406 | sys_rt_exec_alarm = 0; 407 | sys_rt_exec_motion_override = 0; 408 | sys_rt_exec_accessory_override = 0; 409 | 410 | // Reset Grbl primary systems. 411 | serial_reset_read_buffer(); // Clear serial read buffer 412 | gc_init(); // Set g-code parser to default state 413 | spindle_init(); 414 | coolant_init(); 415 | limits_init(); 416 | probe_init(); 417 | sleep_init(); 418 | plan_reset(); // Clear block buffer and planner variables 419 | st_reset(); // Clear stepper subsystem variables. 420 | 421 | // Sync cleared gcode and planner positions to current system position. 422 | plan_sync_position(); 423 | gc_sync_position(); 424 | 425 | // Print welcome message. Indicates an initialization has occured at power-up or with a reset. 426 | report_init_message(); 427 | 428 | // Start Grbl main loop. Processes program inputs and executes them. 429 | protocol_main_loop(); 430 | 431 | } 432 | return 0; /* Never reached */ 433 | } 434 | -------------------------------------------------------------------------------- /grbl/motion_control.h: -------------------------------------------------------------------------------- 1 | /* 2 | motion_control.h - high level interface for issuing motion commands 3 | Part of Grbl 4 | 5 | Copyright (c) 2017-2018 Gauthier Briere 6 | Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC 7 | Copyright (c) 2009-2011 Simen Svale Skogsrud 8 | 9 | Grbl is free software: you can redistribute it and/or modify 10 | it under the terms of the GNU General Public License as published by 11 | the Free Software Foundation, either version 3 of the License, or 12 | (at your option) any later version. 13 | 14 | Grbl is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | GNU General Public License for more details. 18 | 19 | You should have received a copy of the GNU General Public License 20 | along with Grbl. If not, see . 21 | */ 22 | 23 | #ifndef motion_control_h 24 | #define motion_control_h 25 | 26 | 27 | // System motion commands must have a line number of zero. 28 | #define HOMING_CYCLE_LINE_NUMBER 0 29 | #define PARKING_MOTION_LINE_NUMBER 0 30 | 31 | #define HOMING_CYCLE_ALL 0 // Must be zero. 32 | 33 | // Execute linear motion in absolute millimeter coordinates. Feed rate given in millimeters/second 34 | // unless invert_feed_rate is true. Then the feed_rate means that the motion should be completed in 35 | // (1 minute)/feed_rate time. 36 | void mc_line(float *target, plan_line_data_t *pl_data); 37 | 38 | // Execute an arc in offset mode format. position == current xyz, target == target xyz, 39 | // offset == offset from current xyz, axis_XXX defines circle plane in tool space, axis_linear is 40 | // the direction of helical travel, radius == circle radius, is_clockwise_arc boolean. Used 41 | // for vector transformation direction. 42 | void mc_arc(float *target, plan_line_data_t *pl_data, float *position, float *offset, float radius, 43 | uint8_t axis_0, uint8_t axis_1, uint8_t axis_linear, uint8_t axis_0_mask, uint8_t axis_1_mask, uint8_t axis_linear_mask, 44 | uint8_t axis_a, uint8_t axis_b, uint8_t axis_c, uint8_t axis_a_mask, uint8_t axis_b_mask, uint8_t axis_c_mask, 45 | uint8_t axis_u, uint8_t axis_v, uint8_t axis_w, uint8_t axis_u_mask, uint8_t axis_v_mask, uint8_t axis_w_mask, 46 | uint8_t is_clockwise_arc); 47 | 48 | // Dwell for a specific number of seconds 49 | void mc_dwell(float seconds); 50 | 51 | // Perform homing cycle to locate machine zero. Requires limit switches. 52 | void mc_homing_cycle(uint8_t cycle_mask); 53 | 54 | // Perform tool length probe cycle. Requires probe switch. 55 | uint8_t mc_probe_cycle(float *target, plan_line_data_t *pl_data, uint8_t parser_flags); 56 | 57 | // Handles updating the override control state. 58 | void mc_override_ctrl_update(uint8_t override_state); 59 | 60 | // Plans and executes the single special motion case for parking. Independent of main planner buffer. 61 | void mc_parking_motion(float *parking_target, plan_line_data_t *pl_data); 62 | 63 | // Performs system reset. If in motion state, kills all motion and sets system alarm. 64 | void mc_reset(); 65 | 66 | #endif 67 | -------------------------------------------------------------------------------- /grbl/nuts_bolts.c: -------------------------------------------------------------------------------- 1 | /* 2 | nuts_bolts.c - Shared functions 3 | Part of Grbl 4 | 5 | Copyright (c) 2017-2018 Gauthier Briere 6 | Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC 7 | Copyright (c) 2009-2011 Simen Svale Skogsrud 8 | 9 | Grbl is free software: you can redistribute it and/or modify 10 | it under the terms of the GNU General Public License as published by 11 | the Free Software Foundation, either version 3 of the License, or 12 | (at your option) any later version. 13 | 14 | Grbl is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | GNU General Public License for more details. 18 | 19 | You should have received a copy of the GNU General Public License 20 | along with Grbl. If not, see . 21 | */ 22 | 23 | #include "grbl.h" 24 | 25 | 26 | #define MAX_INT_DIGITS 8 // Maximum number of digits in int32 (and float) 27 | 28 | 29 | // Extracts a floating point value from a string. The following code is based loosely on 30 | // the avr-libc strtod() function by Michael Stumpf and Dmitry Xmelkov and many freely 31 | // available conversion method examples, but has been highly optimized for Grbl. For known 32 | // CNC applications, the typical decimal value is expected to be in the range of E0 to E-4. 33 | // Scientific notation is officially not supported by g-code, and the 'E' character may 34 | // be a g-code word on some CNC systems. So, 'E' notation will not be recognized. 35 | // NOTE: Thanks to Radu-Eosif Mihailescu for identifying the issues with using strtod(). 36 | uint8_t read_float(char *line, uint8_t *char_counter, float *float_ptr) 37 | { 38 | char *ptr = line + *char_counter; 39 | unsigned char c; 40 | 41 | // Grab first character and increment pointer. No spaces assumed in line. 42 | c = *ptr++; 43 | 44 | // Capture initial positive/minus character 45 | bool isnegative = false; 46 | if (c == '-') { 47 | isnegative = true; 48 | c = *ptr++; 49 | } else if (c == '+') { 50 | c = *ptr++; 51 | } 52 | 53 | // Extract number into fast integer. Track decimal in terms of exponent value. 54 | uint32_t intval = 0; 55 | int8_t exp = 0; 56 | uint8_t ndigit = 0; 57 | bool isdecimal = false; 58 | while(1) { 59 | c -= '0'; 60 | if (c <= 9) { 61 | ndigit++; 62 | if (ndigit <= MAX_INT_DIGITS) { 63 | if (isdecimal) { exp--; } 64 | intval = (((intval << 2) + intval) << 1) + c; // intval*10 + c 65 | } else { 66 | if (!(isdecimal)) { exp++; } // Drop overflow digits 67 | } 68 | } else if (c == (('.'-'0') & 0xff) && !(isdecimal)) { 69 | isdecimal = true; 70 | } else { 71 | break; 72 | } 73 | c = *ptr++; 74 | } 75 | 76 | // Return if no digits have been read. 77 | if (!ndigit) { return(false); }; 78 | 79 | // Convert integer into floating point. 80 | float fval; 81 | fval = (float)intval; 82 | 83 | // Apply decimal. Should perform no more than two floating point multiplications for the 84 | // expected range of E0 to E-4. 85 | if (fval != 0) { 86 | while (exp <= -2) { 87 | fval *= 0.01; 88 | exp += 2; 89 | } 90 | if (exp < 0) { 91 | fval *= 0.1; 92 | } else if (exp > 0) { 93 | do { 94 | fval *= 10.0; 95 | } while (--exp > 0); 96 | } 97 | } 98 | 99 | // Assign floating point value with correct sign. 100 | if (isnegative) { 101 | *float_ptr = -fval; 102 | } else { 103 | *float_ptr = fval; 104 | } 105 | 106 | *char_counter = ptr - line - 1; // Set char_counter to next statement 107 | 108 | return(true); 109 | } 110 | 111 | 112 | // Non-blocking delay function used for general operation and suspend features. 113 | void delay_sec(float seconds, uint8_t mode) 114 | { 115 | uint16_t i = ceil(1000/DWELL_TIME_STEP*seconds); 116 | while (i-- > 0) { 117 | if (sys.abort) { return; } 118 | if (mode == DELAY_MODE_DWELL) { 119 | protocol_execute_realtime(); 120 | } else { // DELAY_MODE_SYS_SUSPEND 121 | // Execute rt_system() only to avoid nesting suspend loops. 122 | protocol_exec_rt_system(); 123 | if (sys.suspend & SUSPEND_RESTART_RETRACT) { return; } // Bail, if safety door reopens. 124 | } 125 | _delay_ms(DWELL_TIME_STEP); // Delay DWELL_TIME_STEP increment 126 | } 127 | } 128 | 129 | 130 | // Delays variable defined milliseconds. Compiler compatibility fix for _delay_ms(), 131 | // which only accepts constants in future compiler releases. 132 | void delay_ms(uint16_t ms) 133 | { 134 | while ( ms-- ) { _delay_ms(1); } 135 | } 136 | 137 | 138 | // Delays variable defined microseconds. Compiler compatibility fix for _delay_us(), 139 | // which only accepts constants in future compiler releases. Written to perform more 140 | // efficiently with larger delays, as the counter adds parasitic time in each iteration. 141 | void delay_us(uint32_t us) 142 | { 143 | while (us) { 144 | if (us < 10) { 145 | _delay_us(1); 146 | us--; 147 | } else if (us < 100) { 148 | _delay_us(10); 149 | us -= 10; 150 | } else if (us < 1000) { 151 | _delay_us(100); 152 | us -= 100; 153 | } else { 154 | _delay_ms(1); 155 | us -= 1000; 156 | } 157 | } 158 | } 159 | 160 | 161 | // Simple hypotenuse computation function. 162 | float hypot_f(float x, float y) { return(sqrt(x*x + y*y)); } 163 | 164 | 165 | float convert_delta_vector_to_unit_vector(float *vector) 166 | { 167 | uint8_t idx, j; 168 | bool isclone; 169 | float magnitude = 0.0; 170 | for (idx=0; idx. 21 | */ 22 | 23 | #ifndef nuts_bolts_h 24 | #define nuts_bolts_h 25 | 26 | #define false 0 27 | #define true 1 28 | 29 | #define SOME_LARGE_VALUE 1.0E+38 30 | 31 | // CoreXY motor assignments. DO NOT ALTER. 32 | // NOTE: If the A and B motor axis bindings are changed, this effects the CoreXY equations. 33 | #ifdef COREXY 34 | #define A_MOTOR AXIS_1 // Must be AXIS_1 (X) 35 | #define B_MOTOR AXIS_2 // Must be AXIS_2 (Y) 36 | #endif 37 | 38 | // Conversions 39 | #define MM_PER_INCH (25.40) 40 | #define INCH_PER_MM (0.0393701) 41 | #define TICKS_PER_MICROSECOND (F_CPU/1000000) 42 | 43 | #define DELAY_MODE_DWELL 0 44 | #define DELAY_MODE_SYS_SUSPEND 1 45 | 46 | // Useful macros 47 | #define clear_vector(a) memset(a, 0, sizeof(a)) 48 | #define clear_vector_float(a) memset(a, 0.0, sizeof(float)*N_AXIS) 49 | // #define clear_vector_long(a) memset(a, 0.0, sizeof(long)*N_AXIS) 50 | #define max(a,b) (((a) > (b)) ? (a) : (b)) 51 | #define min(a,b) (((a) < (b)) ? (a) : (b)) 52 | #define isequal_position_vector(a,b) !(memcmp(a, b, sizeof(float)*N_AXIS)) 53 | 54 | // Bit field and masking macros 55 | #define bit(n) (1 << n) 56 | #define dwbit(n) ((uint32_t)1 << n) 57 | #define bit_true(x,mask) (x) |= (mask) 58 | #define bit_false(x,mask) (x) &= ~(mask) 59 | #define bit_istrue(x,mask) ((x & mask) != 0) 60 | #define bit_isfalse(x,mask) ((x & mask) == 0) 61 | 62 | // Read a floating point value from a string. Line points to the input buffer, char_counter 63 | // is the indexer pointing to the current character of the line, while float_ptr is 64 | // a pointer to the result variable. Returns true when it succeeds 65 | uint8_t read_float(char *line, uint8_t *char_counter, float *float_ptr); 66 | 67 | // Non-blocking delay function used for general operation and suspend features. 68 | void delay_sec(float seconds, uint8_t mode); 69 | 70 | // Delays variable-defined milliseconds. Compiler compatibility fix for _delay_ms(). 71 | void delay_ms(uint16_t ms); 72 | 73 | // Delays variable-defined microseconds. Compiler compatibility fix for _delay_us(). 74 | void delay_us(uint32_t us); 75 | 76 | // Computes hypotenuse, avoiding avr-gcc's bloated version and the extra error checking. 77 | float hypot_f(float x, float y); 78 | 79 | float convert_delta_vector_to_unit_vector(float *vector); 80 | float limit_value_by_axis_maximum(float *max_value, float *unit_vec); 81 | 82 | #endif 83 | -------------------------------------------------------------------------------- /grbl/planner.h: -------------------------------------------------------------------------------- 1 | /* 2 | planner.h - buffers movement commands and manages the acceleration profile plan 3 | Part of Grbl 4 | 5 | Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC 6 | Copyright (c) 2009-2011 Simen Svale Skogsrud 7 | 8 | Grbl is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | Grbl is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with Grbl. If not, see . 20 | */ 21 | 22 | #ifndef planner_h 23 | #define planner_h 24 | 25 | 26 | // The number of linear motions that can be in the plan at any give time 27 | #ifndef BLOCK_BUFFER_SIZE 28 | #define BLOCK_BUFFER_SIZE 36 29 | #endif 30 | 31 | // Returned status message from planner. 32 | #define PLAN_OK true 33 | #define PLAN_EMPTY_BLOCK false 34 | 35 | // Define planner data condition flags. Used to denote running conditions of a block. 36 | #define PL_COND_FLAG_RAPID_MOTION bit(0) 37 | #define PL_COND_FLAG_SYSTEM_MOTION bit(1) // Single motion. Circumvents planner state. Used by home/park. 38 | #define PL_COND_FLAG_NO_FEED_OVERRIDE bit(2) // Motion does not honor feed override. 39 | #define PL_COND_FLAG_INVERSE_TIME bit(3) // Interprets feed rate value as inverse time when set. 40 | #define PL_COND_FLAG_SPINDLE_CW bit(4) 41 | #define PL_COND_FLAG_SPINDLE_CCW bit(5) 42 | #define PL_COND_FLAG_COOLANT_FLOOD bit(6) 43 | #define PL_COND_FLAG_COOLANT_MIST bit(7) 44 | #define PL_COND_MOTION_MASK (PL_COND_FLAG_RAPID_MOTION|PL_COND_FLAG_SYSTEM_MOTION|PL_COND_FLAG_NO_FEED_OVERRIDE) 45 | #define PL_COND_ACCESSORY_MASK (PL_COND_FLAG_SPINDLE_CW|PL_COND_FLAG_SPINDLE_CCW|PL_COND_FLAG_COOLANT_FLOOD|PL_COND_FLAG_COOLANT_MIST) 46 | 47 | 48 | // This struct stores a linear movement of a g-code block motion with its critical "nominal" values 49 | // are as specified in the source g-code. 50 | typedef struct { 51 | // Fields used by the bresenham algorithm for tracing the line 52 | // NOTE: Used by stepper algorithm to execute the block correctly. Do not alter these values. 53 | uint32_t steps[N_AXIS]; // Step count along each axis 54 | uint32_t step_event_count; // The maximum step axis count and number of steps required to complete this block. 55 | #ifdef DEFAULTS_RAMPS_BOARD 56 | uint8_t direction_bits[N_AXIS]; // The direction bit set for this block (refers to *_DIRECTION_BIT in config.h) 57 | #else 58 | uint8_t direction_bits; // The direction bit set for this block (refers to *_DIRECTION_BIT in config.h) 59 | #endif // DEFAULTS_RAMPS_BOARD 60 | // Block condition data to ensure correct execution depending on states and overrides. 61 | uint8_t condition; // Block bitflag variable defining block run conditions. Copied from pl_line_data. 62 | int32_t line_number; // Block line number for real-time reporting. Copied from pl_line_data. 63 | 64 | // Fields used by the motion planner to manage acceleration. Some of these values may be updated 65 | // by the stepper module during execution of special motion cases for replanning purposes. 66 | float entry_speed_sqr; // The current planned entry speed at block junction in (mm/min)^2 67 | float max_entry_speed_sqr; // Maximum allowable entry speed based on the minimum of junction limit and 68 | // neighboring nominal speeds with overrides in (mm/min)^2 69 | float acceleration; // Axis-limit adjusted line acceleration in (mm/min^2). Does not change. 70 | float millimeters; // The remaining distance for this block to be executed in (mm). 71 | // NOTE: This value may be altered by stepper algorithm during execution. 72 | 73 | // Stored rate limiting data used by planner when changes occur. 74 | float max_junction_speed_sqr; // Junction entry speed limit based on direction vectors in (mm/min)^2 75 | float rapid_rate; // Axis-limit adjusted maximum rate for this block direction in (mm/min) 76 | float programmed_rate; // Programmed rate of this block (mm/min). 77 | 78 | // Stored spindle speed data used by spindle overrides and resuming methods. 79 | float spindle_speed; // Block spindle speed. Copied from pl_line_data. 80 | } plan_block_t; 81 | 82 | 83 | // Planner data prototype. Must be used when passing new motions to the planner. 84 | typedef struct { 85 | float feed_rate; // Desired feed rate for line motion. Value is ignored, if rapid motion. 86 | float spindle_speed; // Desired spindle speed through line motion. 87 | int32_t line_number; // Desired line number to report when executing. 88 | uint8_t condition; // Bitflag variable to indicate planner conditions. See defines above. 89 | } plan_line_data_t; 90 | 91 | 92 | // Initialize and reset the motion plan subsystem 93 | void plan_reset(); // Reset all 94 | void plan_reset_buffer(); // Reset buffer only. 95 | 96 | // Add a new linear movement to the buffer. target[N_AXIS] is the signed, absolute target position 97 | // in millimeters. Feed rate specifies the speed of the motion. If feed rate is inverted, the feed 98 | // rate is taken to mean "frequency" and would complete the operation in 1/feed_rate minutes. 99 | uint8_t plan_buffer_line(float *target, plan_line_data_t *pl_data); 100 | 101 | // Called when the current block is no longer needed. Discards the block and makes the memory 102 | // availible for new blocks. 103 | void plan_discard_current_block(); 104 | 105 | // Gets the planner block for the special system motion cases. (Parking/Homing) 106 | plan_block_t *plan_get_system_motion_block(); 107 | 108 | // Gets the current block. Returns NULL if buffer empty 109 | plan_block_t *plan_get_current_block(); 110 | 111 | // Called periodically by step segment buffer. Mostly used internally by planner. 112 | uint8_t plan_next_block_index(uint8_t block_index); 113 | 114 | // Called by step segment buffer when computing executing block velocity profile. 115 | float plan_get_exec_block_exit_speed_sqr(); 116 | 117 | // Called by main program during planner calculations and step segment buffer during initialization. 118 | float plan_compute_profile_nominal_speed(plan_block_t *block); 119 | 120 | // Re-calculates buffered motions profile parameters upon a motion-based override change. 121 | void plan_update_velocity_profile_parameters(); 122 | 123 | // Reset the planner position vector (in steps) 124 | void plan_sync_position(); 125 | 126 | // Reinitialize plan with a partially completed block 127 | void plan_cycle_reinitialize(); 128 | 129 | // Returns the number of available blocks are in the planner buffer. 130 | uint8_t plan_get_block_buffer_available(); 131 | 132 | // Returns the number of active blocks are in the planner buffer. 133 | // NOTE: Deprecated. Not used unless classic status reports are enabled in config.h 134 | uint8_t plan_get_block_buffer_count(); 135 | 136 | // Returns the status of the block ring buffer. True, if buffer is full. 137 | uint8_t plan_check_full_buffer(); 138 | 139 | void plan_get_planner_mpos(float *target); 140 | 141 | 142 | #endif 143 | -------------------------------------------------------------------------------- /grbl/print.c: -------------------------------------------------------------------------------- 1 | /* 2 | print.c - Functions for formatting output strings 3 | Part of Grbl 4 | 5 | Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC 6 | Copyright (c) 2009-2011 Simen Svale Skogsrud 7 | 8 | Grbl is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | Grbl is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with Grbl. If not, see . 20 | */ 21 | 22 | #include "grbl.h" 23 | 24 | 25 | void printString(const char *s) 26 | { 27 | while (*s) 28 | serial_write(*s++); 29 | } 30 | 31 | 32 | // Print a string stored in PGM-memory 33 | void printPgmString(const char *s) 34 | { 35 | char c; 36 | while ((c = pgm_read_byte_near(s++))) 37 | serial_write(c); 38 | } 39 | 40 | 41 | // void printIntegerInBase(unsigned long n, unsigned long base) 42 | // { 43 | // unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars. 44 | // unsigned long i = 0; 45 | // 46 | // if (n == 0) { 47 | // serial_write('0'); 48 | // return; 49 | // } 50 | // 51 | // while (n > 0) { 52 | // buf[i++] = n % base; 53 | // n /= base; 54 | // } 55 | // 56 | // for (; i > 0; i--) 57 | // serial_write(buf[i - 1] < 10 ? 58 | // '0' + buf[i - 1] : 59 | // 'A' + buf[i - 1] - 10); 60 | // } 61 | 62 | 63 | // Prints an uint8 variable in base 10. 64 | void print_uint8_base10(uint8_t n) 65 | { 66 | uint8_t digit_a = 0; 67 | uint8_t digit_b = 0; 68 | if (n >= 100) { // 100-255 69 | digit_a = '0' + n % 10; 70 | n /= 10; 71 | } 72 | if (n >= 10) { // 10-99 73 | digit_b = '0' + n % 10; 74 | n /= 10; 75 | } 76 | serial_write('0' + n); 77 | if (digit_b) { serial_write(digit_b); } 78 | if (digit_a) { serial_write(digit_a); } 79 | } 80 | 81 | 82 | // Prints an uint8 variable in base 2 with desired number of desired digits. 83 | void print_uint8_base2_ndigit(uint8_t n, uint8_t digits) { 84 | unsigned char buf[digits]; 85 | uint8_t i = 0; 86 | 87 | for (; i < digits; i++) { 88 | buf[i] = n % 2 ; 89 | n /= 2; 90 | } 91 | 92 | for (; i > 0; i--) 93 | serial_write('0' + buf[i - 1]); 94 | } 95 | 96 | 97 | void print_uint32_base10(uint32_t n) 98 | { 99 | if (n == 0) { 100 | serial_write('0'); 101 | return; 102 | } 103 | 104 | unsigned char buf[10]; 105 | uint8_t i = 0; 106 | 107 | while (n > 0) { 108 | buf[i++] = n % 10; 109 | n /= 10; 110 | } 111 | 112 | for (; i > 0; i--) 113 | serial_write('0' + buf[i-1]); 114 | } 115 | 116 | 117 | void printInteger(long n) 118 | { 119 | if (n < 0) { 120 | serial_write('-'); 121 | print_uint32_base10(-n); 122 | } else { 123 | print_uint32_base10(n); 124 | } 125 | } 126 | 127 | 128 | // Convert float to string by immediately converting to a long integer, which contains 129 | // more digits than a float. Number of decimal places, which are tracked by a counter, 130 | // may be set by the user. The integer is then efficiently converted to a string. 131 | // NOTE: AVR '%' and '/' integer operations are very efficient. Bitshifting speed-up 132 | // techniques are actually just slightly slower. Found this out the hard way. 133 | void printFloat(float n, uint8_t decimal_places) 134 | { 135 | if (n < 0) { 136 | serial_write('-'); 137 | n = -n; 138 | } 139 | 140 | uint8_t decimals = decimal_places; 141 | while (decimals >= 2) { // Quickly convert values expected to be E0 to E-4. 142 | n *= 100; 143 | decimals -= 2; 144 | } 145 | if (decimals) { n *= 10; } 146 | n += 0.5; // Add rounding factor. Ensures carryover through entire value. 147 | 148 | // Generate digits backwards and store in string. 149 | unsigned char buf[13]; 150 | uint8_t i = 0; 151 | uint32_t a = (long)n; 152 | while(a > 0) { 153 | buf[i++] = (a % 10) + '0'; // Get digit 154 | a /= 10; 155 | } 156 | while (i < decimal_places) { 157 | buf[i++] = '0'; // Fill in zeros to decimal point for (n < 1) 158 | } 159 | if (i == decimal_places) { // Fill in leading zero, if needed. 160 | buf[i++] = '0'; 161 | } 162 | 163 | // Print the generated string. 164 | for (; i > 0; i--) { 165 | if (i == decimal_places) { serial_write('.'); } // Insert decimal point in right place. 166 | serial_write(buf[i-1]); 167 | } 168 | } 169 | 170 | 171 | // Floating value printing handlers for special variables types used in Grbl and are defined 172 | // in the config.h. 173 | // - CoordValue: Handles all position or coordinate values in inches or mm reporting. 174 | // - RateValue: Handles feed rate and current velocity in inches or mm reporting. 175 | void printFloat_CoordValue(float n) { 176 | if (bit_istrue(settings.flags,BITFLAG_REPORT_INCHES)) { 177 | printFloat(n*INCH_PER_MM,N_DECIMAL_COORDVALUE_INCH); 178 | } else { 179 | printFloat(n,N_DECIMAL_COORDVALUE_MM); 180 | } 181 | } 182 | 183 | void printFloat_RateValue(float n) { 184 | if (bit_istrue(settings.flags,BITFLAG_REPORT_INCHES)) { 185 | printFloat(n*INCH_PER_MM,N_DECIMAL_RATEVALUE_INCH); 186 | } else { 187 | printFloat(n,N_DECIMAL_RATEVALUE_MM); 188 | } 189 | } 190 | 191 | // Debug tool to print free memory in bytes at the called point. 192 | // NOTE: Keep commented unless using. Part of this function always gets compiled in. 193 | // void printFreeMemory() 194 | // { 195 | // extern int __heap_start, *__brkval; 196 | // uint16_t free; // Up to 64k values. 197 | // free = (int) &free - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); 198 | // printInteger((int32_t)free); 199 | // printString(" "); 200 | // } 201 | -------------------------------------------------------------------------------- /grbl/print.h: -------------------------------------------------------------------------------- 1 | /* 2 | print.h - Functions for formatting output strings 3 | Part of Grbl 4 | 5 | Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC 6 | Copyright (c) 2009-2011 Simen Svale Skogsrud 7 | 8 | Grbl is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | Grbl is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with Grbl. If not, see . 20 | */ 21 | 22 | #ifndef print_h 23 | #define print_h 24 | 25 | 26 | void printString(const char *s); 27 | 28 | void printPgmString(const char *s); 29 | 30 | void printInteger(long n); 31 | 32 | void print_uint32_base10(uint32_t n); 33 | 34 | // Prints an uint8 variable in base 10. 35 | void print_uint8_base10(uint8_t n); 36 | 37 | // Prints an uint8 variable in base 2 with desired number of desired digits. 38 | void print_uint8_base2_ndigit(uint8_t n, uint8_t digits); 39 | 40 | void printFloat(float n, uint8_t decimal_places); 41 | 42 | // Floating value printing handlers for special variables types used in Grbl. 43 | // - CoordValue: Handles all position or coordinate values in inches or mm reporting. 44 | // - RateValue: Handles feed rate and current velocity in inches or mm reporting. 45 | void printFloat_CoordValue(float n); 46 | void printFloat_RateValue(float n); 47 | 48 | // Debug tool to print free memory in bytes at the called point. Not used otherwise. 49 | void printFreeMemory(); 50 | 51 | #endif 52 | -------------------------------------------------------------------------------- /grbl/probe.c: -------------------------------------------------------------------------------- 1 | /* 2 | probe.c - code pertaining to probing methods 3 | Part of Grbl 4 | 5 | Copyright (c) 2014-2016 Sungeun K. Jeon for Gnea Research LLC 6 | 7 | Grbl is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | Grbl is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with Grbl. If not, see . 19 | */ 20 | 21 | #include "grbl.h" 22 | 23 | 24 | // Inverts the probe pin state depending on user settings and probing cycle mode. 25 | uint8_t probe_invert_mask; 26 | 27 | 28 | // Probe pin initialization routine. 29 | void probe_init() 30 | { 31 | PROBE_DDR &= ~(PROBE_MASK); // Configure as input pins 32 | #ifdef DISABLE_PROBE_PIN_PULL_UP 33 | PROBE_PORT &= ~(PROBE_MASK); // Normal low operation. Requires external pull-down. 34 | #else 35 | PROBE_PORT |= PROBE_MASK; // Enable internal pull-up resistors. Normal high operation. 36 | #endif 37 | probe_configure_invert_mask(false); // Initialize invert mask. 38 | } 39 | 40 | 41 | // Called by probe_init() and the mc_probe() routines. Sets up the probe pin invert mask to 42 | // appropriately set the pin logic according to setting for normal-high/normal-low operation 43 | // and the probing cycle modes for toward-workpiece/away-from-workpiece. 44 | void probe_configure_invert_mask(uint8_t is_probe_away) 45 | { 46 | probe_invert_mask = 0; // Initialize as zero. 47 | if (bit_isfalse(settings.flags,BITFLAG_INVERT_PROBE_PIN)) { probe_invert_mask ^= PROBE_MASK; } 48 | if (is_probe_away) { probe_invert_mask ^= PROBE_MASK; } 49 | } 50 | 51 | 52 | // Returns the probe pin state. Triggered = true. Called by gcode parser and probe state monitor. 53 | uint8_t probe_get_state() { return((PROBE_PIN & PROBE_MASK) ^ probe_invert_mask); } 54 | 55 | 56 | // Monitors probe pin state and records the system position when detected. Called by the 57 | // stepper ISR per ISR tick. 58 | // NOTE: This function must be extremely efficient as to not bog down the stepper ISR. 59 | void probe_state_monitor() 60 | { 61 | if (probe_get_state()) { 62 | sys_probe_state = PROBE_OFF; 63 | memcpy(sys_probe_position, sys_position, sizeof(sys_position)); 64 | bit_true(sys_rt_exec_state, EXEC_MOTION_CANCEL); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /grbl/probe.h: -------------------------------------------------------------------------------- 1 | /* 2 | probe.h - code pertaining to probing methods 3 | Part of Grbl 4 | 5 | Copyright (c) 2014-2016 Sungeun K. Jeon for Gnea Research LLC 6 | 7 | Grbl is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | Grbl is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with Grbl. If not, see . 19 | */ 20 | 21 | #ifndef probe_h 22 | #define probe_h 23 | 24 | // Values that define the probing state machine. 25 | #define PROBE_OFF 0 // Probing disabled or not in use. (Must be zero.) 26 | #define PROBE_ACTIVE 1 // Actively watching the input pin. 27 | 28 | // Probe pin initialization routine. 29 | void probe_init(); 30 | 31 | // Called by probe_init() and the mc_probe() routines. Sets up the probe pin invert mask to 32 | // appropriately set the pin logic according to setting for normal-high/normal-low operation 33 | // and the probing cycle modes for toward-workpiece/away-from-workpiece. 34 | void probe_configure_invert_mask(uint8_t is_probe_away); 35 | 36 | // Returns probe pin state. Triggered = true. Called by gcode parser and probe state monitor. 37 | uint8_t probe_get_state(); 38 | 39 | // Monitors probe pin state and records the system position when detected. Called by the 40 | // stepper ISR per ISR tick. 41 | void probe_state_monitor(); 42 | 43 | #endif 44 | -------------------------------------------------------------------------------- /grbl/protocol.h: -------------------------------------------------------------------------------- 1 | /* 2 | protocol.h - controls Grbl execution protocol and procedures 3 | Part of Grbl 4 | 5 | Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC 6 | Copyright (c) 2009-2011 Simen Svale Skogsrud 7 | 8 | Grbl is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | Grbl is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with Grbl. If not, see . 20 | */ 21 | 22 | #ifndef protocol_h 23 | #define protocol_h 24 | 25 | // Line buffer size from the serial input stream to be executed. 26 | #ifndef LINE_BUFFER_SIZE 27 | #define LINE_BUFFER_SIZE 256 28 | #endif 29 | 30 | // Starts Grbl main loop. It handles all incoming characters from the serial port and executes 31 | // them as they complete. It is also responsible for finishing the initialization procedures. 32 | void protocol_main_loop(); 33 | 34 | // Checks and executes a realtime command at various stop points in main program 35 | void protocol_execute_realtime(); 36 | void protocol_exec_rt_system(); 37 | 38 | // Executes the auto cycle feature, if enabled. 39 | void protocol_auto_cycle_start(); 40 | 41 | // Block until all buffered steps are executed 42 | void protocol_buffer_synchronize(); 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /grbl/report.h: -------------------------------------------------------------------------------- 1 | /* 2 | report.h - reporting and messaging methods 3 | Part of Grbl 4 | 5 | Copyright (c) 2012-2016 Sungeun K. Jeon for Gnea Research LLC 6 | 7 | Grbl is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | Grbl is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with Grbl. If not, see . 19 | */ 20 | #ifndef report_h 21 | #define report_h 22 | 23 | // Define Grbl status codes. Valid values (0-255) 24 | #define STATUS_OK 0 25 | #define STATUS_EXPECTED_COMMAND_LETTER 1 26 | #define STATUS_BAD_NUMBER_FORMAT 2 27 | #define STATUS_INVALID_STATEMENT 3 28 | #define STATUS_NEGATIVE_VALUE 4 29 | #define STATUS_SETTING_DISABLED 5 30 | #define STATUS_SETTING_STEP_PULSE_MIN 6 31 | #define STATUS_SETTING_READ_FAIL 7 32 | #define STATUS_IDLE_ERROR 8 33 | #define STATUS_SYSTEM_GC_LOCK 9 34 | #define STATUS_SOFT_LIMIT_ERROR 10 35 | #define STATUS_OVERFLOW 11 36 | #define STATUS_MAX_STEP_RATE_EXCEEDED 12 37 | #define STATUS_CHECK_DOOR 13 38 | #define STATUS_LINE_LENGTH_EXCEEDED 14 39 | #define STATUS_TRAVEL_EXCEEDED 15 40 | #define STATUS_INVALID_JOG_COMMAND 16 41 | #define STATUS_SETTING_DISABLED_LASER 17 42 | 43 | #define STATUS_GCODE_UNSUPPORTED_COMMAND 20 44 | #define STATUS_GCODE_MODAL_GROUP_VIOLATION 21 45 | #define STATUS_GCODE_UNDEFINED_FEED_RATE 22 46 | #define STATUS_GCODE_COMMAND_VALUE_NOT_INTEGER 23 47 | #define STATUS_GCODE_AXIS_COMMAND_CONFLICT 24 48 | #define STATUS_GCODE_WORD_REPEATED 25 49 | #define STATUS_GCODE_NO_AXIS_WORDS 26 50 | #define STATUS_GCODE_INVALID_LINE_NUMBER 27 51 | #define STATUS_GCODE_VALUE_WORD_MISSING 28 52 | #define STATUS_GCODE_UNSUPPORTED_COORD_SYS 29 53 | #define STATUS_GCODE_G53_INVALID_MOTION_MODE 30 54 | #define STATUS_GCODE_AXIS_WORDS_EXIST 31 55 | #define STATUS_GCODE_NO_AXIS_WORDS_IN_PLANE 32 56 | #define STATUS_GCODE_INVALID_TARGET 33 57 | #define STATUS_GCODE_ARC_RADIUS_ERROR 34 58 | #define STATUS_GCODE_NO_OFFSETS_IN_PLANE 35 59 | #define STATUS_GCODE_UNUSED_WORDS 36 60 | #define STATUS_GCODE_G43_DYNAMIC_AXIS_ERROR 37 61 | #define STATUS_GCODE_MAX_VALUE_EXCEEDED 38 62 | 63 | // Define Grbl alarm codes. Valid values (1-255). 0 is reserved. 64 | #define ALARM_HARD_LIMIT_ERROR EXEC_ALARM_HARD_LIMIT 65 | #define ALARM_SOFT_LIMIT_ERROR EXEC_ALARM_SOFT_LIMIT 66 | #define ALARM_ABORT_CYCLE EXEC_ALARM_ABORT_CYCLE 67 | #define ALARM_PROBE_FAIL_INITIAL EXEC_ALARM_PROBE_FAIL_INITIAL 68 | #define ALARM_PROBE_FAIL_CONTACT EXEC_ALARM_PROBE_FAIL_CONTACT 69 | #define ALARM_HOMING_FAIL_RESET EXEC_ALARM_HOMING_FAIL_RESET 70 | #define ALARM_HOMING_FAIL_DOOR EXEC_ALARM_HOMING_FAIL_DOOR 71 | #define ALARM_HOMING_FAIL_PULLOFF EXEC_ALARM_HOMING_FAIL_PULLOFF 72 | #define ALARM_HOMING_FAIL_APPROACH EXEC_ALARM_HOMING_FAIL_APPROACH 73 | 74 | // Define Grbl feedback message codes. Valid values (0-255). 75 | #define MESSAGE_CRITICAL_EVENT 1 76 | #define MESSAGE_ALARM_LOCK 2 77 | #define MESSAGE_ALARM_UNLOCK 3 78 | #define MESSAGE_ENABLED 4 79 | #define MESSAGE_DISABLED 5 80 | #define MESSAGE_SAFETY_DOOR_AJAR 6 81 | #define MESSAGE_CHECK_LIMITS 7 82 | #define MESSAGE_PROGRAM_END 8 83 | #define MESSAGE_RESTORE_DEFAULTS 9 84 | #define MESSAGE_SPINDLE_RESTORE 10 85 | #define MESSAGE_SLEEP_MODE 11 86 | 87 | // Prints system status messages. 88 | void report_status_message(uint8_t status_code); 89 | 90 | // Prints system alarm messages. 91 | void report_alarm_message(uint8_t alarm_code); 92 | 93 | // Prints miscellaneous feedback messages. 94 | void report_feedback_message(uint8_t message_code); 95 | 96 | // Prints welcome message 97 | void report_init_message(); 98 | 99 | // Prints Grbl help and current global settings 100 | void report_grbl_help(); 101 | 102 | // Prints Grbl global settings 103 | void report_grbl_settings(); 104 | 105 | // Prints an echo of the pre-parsed line received right before execution. 106 | void report_echo_line_received(char *line); 107 | 108 | // Prints realtime status report 109 | void report_realtime_status(); 110 | 111 | // Prints recorded probe position 112 | void report_probe_parameters(); 113 | 114 | // Prints Grbl NGC parameters (coordinate offsets, probe) 115 | void report_ngc_parameters(); 116 | 117 | // Prints current g-code parser mode state 118 | void report_gcode_modes(); 119 | 120 | // Prints startup line when requested and executed. 121 | void report_startup_line(uint8_t n, char *line); 122 | void report_execute_startup_message(char *line, uint8_t status_code); 123 | 124 | // Prints build info and user info 125 | void report_build_info(char *line); 126 | 127 | #ifdef DEBUG 128 | void report_realtime_debug(); 129 | #endif 130 | 131 | #endif 132 | -------------------------------------------------------------------------------- /grbl/serial.c: -------------------------------------------------------------------------------- 1 | /* 2 | serial.c - Low level functions for sending and recieving bytes via the serial port 3 | Part of Grbl 4 | 5 | Copyright (c) 2017-2018 Gauthier Briere 6 | Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC 7 | Copyright (c) 2009-2011 Simen Svale Skogsrud 8 | 9 | Grbl is free software: you can redistribute it and/or modify 10 | it under the terms of the GNU General Public License as published by 11 | the Free Software Foundation, either version 3 of the License, or 12 | (at your option) any later version. 13 | 14 | Grbl is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | GNU General Public License for more details. 18 | 19 | You should have received a copy of the GNU General Public License 20 | along with Grbl. If not, see . 21 | */ 22 | 23 | #include "grbl.h" 24 | 25 | #define RX_RING_BUFFER (RX_BUFFER_SIZE+1) 26 | #define TX_RING_BUFFER (TX_BUFFER_SIZE+1) 27 | 28 | uint8_t serial_rx_buffer[RX_RING_BUFFER]; 29 | uint8_t serial_rx_buffer_head = 0; 30 | volatile uint8_t serial_rx_buffer_tail = 0; 31 | 32 | uint8_t serial_tx_buffer[TX_RING_BUFFER]; 33 | uint8_t serial_tx_buffer_head = 0; 34 | volatile uint8_t serial_tx_buffer_tail = 0; 35 | 36 | 37 | // Returns the number of bytes available in the RX serial buffer. 38 | uint8_t serial_get_rx_buffer_available() 39 | { 40 | uint8_t rtail = serial_rx_buffer_tail; // Copy to limit multiple calls to volatile 41 | if (serial_rx_buffer_head >= rtail) { return(RX_BUFFER_SIZE - (serial_rx_buffer_head-rtail)); } 42 | return((rtail-serial_rx_buffer_head-1)); 43 | } 44 | 45 | 46 | // Returns the number of bytes used in the RX serial buffer. 47 | // NOTE: Deprecated. Not used unless classic status reports are enabled in config.h. 48 | uint8_t serial_get_rx_buffer_count() 49 | { 50 | uint8_t rtail = serial_rx_buffer_tail; // Copy to limit multiple calls to volatile 51 | if (serial_rx_buffer_head >= rtail) { return(serial_rx_buffer_head-rtail); } 52 | return (RX_BUFFER_SIZE - (rtail-serial_rx_buffer_head)); 53 | } 54 | 55 | 56 | // Returns the number of bytes used in the TX serial buffer. 57 | // NOTE: Not used except for debugging and ensuring no TX bottlenecks. 58 | uint8_t serial_get_tx_buffer_count() 59 | { 60 | uint8_t ttail = serial_tx_buffer_tail; // Copy to limit multiple calls to volatile 61 | if (serial_tx_buffer_head >= ttail) { return(serial_tx_buffer_head-ttail); } 62 | return (TX_RING_BUFFER - (ttail-serial_tx_buffer_head)); 63 | } 64 | 65 | 66 | void serial_init() 67 | { 68 | // Set baud rate 69 | #if BAUD_RATE < 57600 70 | uint16_t UBRR0_value = ((F_CPU / (8L * BAUD_RATE)) - 1)/2 ; 71 | UCSR0A &= ~(1 << U2X0); // baud doubler off - Only needed on Uno XXX 72 | #else 73 | uint16_t UBRR0_value = ((F_CPU / (4L * BAUD_RATE)) - 1)/2; 74 | UCSR0A |= (1 << U2X0); // baud doubler on for high baud rates, i.e. 115200 75 | #endif 76 | UBRR0H = UBRR0_value >> 8; 77 | UBRR0L = UBRR0_value; 78 | 79 | // enable rx, tx, and interrupt on complete reception of a byte 80 | UCSR0B |= (1< 0x7F) { // Real-time control characters are extended ACSII only. 158 | switch(data) { 159 | case CMD_SAFETY_DOOR: system_set_exec_state_flag(EXEC_SAFETY_DOOR); break; // Set as true 160 | case CMD_JOG_CANCEL: 161 | if (sys.state & STATE_JOG) { // Block all other states from invoking motion cancel. 162 | system_set_exec_state_flag(EXEC_MOTION_CANCEL); 163 | serial_reset_read_buffer(); // Vide un reste éventuel de données dans le buffer 164 | } 165 | break; 166 | #ifdef DEBUG 167 | case CMD_DEBUG_REPORT: {uint8_t sreg = SREG; cli(); bit_true(sys_rt_exec_debug,EXEC_DEBUG_REPORT); SREG = sreg;} break; 168 | #endif 169 | case CMD_FEED_OVR_RESET: system_set_exec_motion_override_flag(EXEC_FEED_OVR_RESET); break; 170 | case CMD_FEED_OVR_COARSE_PLUS: system_set_exec_motion_override_flag(EXEC_FEED_OVR_COARSE_PLUS); break; 171 | case CMD_FEED_OVR_COARSE_MINUS: system_set_exec_motion_override_flag(EXEC_FEED_OVR_COARSE_MINUS); break; 172 | case CMD_FEED_OVR_FINE_PLUS: system_set_exec_motion_override_flag(EXEC_FEED_OVR_FINE_PLUS); break; 173 | case CMD_FEED_OVR_FINE_MINUS: system_set_exec_motion_override_flag(EXEC_FEED_OVR_FINE_MINUS); break; 174 | case CMD_RAPID_OVR_RESET: system_set_exec_motion_override_flag(EXEC_RAPID_OVR_RESET); break; 175 | case CMD_RAPID_OVR_MEDIUM: system_set_exec_motion_override_flag(EXEC_RAPID_OVR_MEDIUM); break; 176 | case CMD_RAPID_OVR_LOW: system_set_exec_motion_override_flag(EXEC_RAPID_OVR_LOW); break; 177 | case CMD_SPINDLE_OVR_RESET: system_set_exec_accessory_override_flag(EXEC_SPINDLE_OVR_RESET); break; 178 | case CMD_SPINDLE_OVR_COARSE_PLUS: system_set_exec_accessory_override_flag(EXEC_SPINDLE_OVR_COARSE_PLUS); break; 179 | case CMD_SPINDLE_OVR_COARSE_MINUS: system_set_exec_accessory_override_flag(EXEC_SPINDLE_OVR_COARSE_MINUS); break; 180 | case CMD_SPINDLE_OVR_FINE_PLUS: system_set_exec_accessory_override_flag(EXEC_SPINDLE_OVR_FINE_PLUS); break; 181 | case CMD_SPINDLE_OVR_FINE_MINUS: system_set_exec_accessory_override_flag(EXEC_SPINDLE_OVR_FINE_MINUS); break; 182 | case CMD_SPINDLE_OVR_STOP: system_set_exec_accessory_override_flag(EXEC_SPINDLE_OVR_STOP); break; 183 | case CMD_COOLANT_FLOOD_OVR_TOGGLE: system_set_exec_accessory_override_flag(EXEC_COOLANT_FLOOD_OVR_TOGGLE); break; 184 | case CMD_COOLANT_MIST_OVR_TOGGLE: system_set_exec_accessory_override_flag(EXEC_COOLANT_MIST_OVR_TOGGLE); break; 185 | } 186 | // Throw away any unfound extended-ASCII character by not passing it to the serial buffer. 187 | } else { // Write character to buffer 188 | next_head = serial_rx_buffer_head + 1; 189 | if (next_head == RX_RING_BUFFER) { next_head = 0; } 190 | 191 | // Write data to buffer unless it is full. 192 | if (next_head != serial_rx_buffer_tail) { 193 | serial_rx_buffer[serial_rx_buffer_head] = data; 194 | serial_rx_buffer_head = next_head; 195 | } 196 | } 197 | } 198 | } 199 | 200 | 201 | void serial_reset_read_buffer() 202 | { 203 | serial_rx_buffer_tail = serial_rx_buffer_head; 204 | } 205 | 206 | 207 | void serial_putstring(char* StringPtr) 208 | { 209 | int i; 210 | int len = strlen(StringPtr); 211 | for(i=0; i. 20 | */ 21 | 22 | #ifndef serial_h 23 | #define serial_h 24 | 25 | 26 | #ifndef RX_BUFFER_SIZE 27 | #define RX_BUFFER_SIZE 255 28 | #endif 29 | #ifndef TX_BUFFER_SIZE 30 | #define TX_BUFFER_SIZE 255 31 | #endif 32 | 33 | #define SERIAL_NO_DATA 0xff 34 | 35 | 36 | void serial_init(); 37 | 38 | // Writes one byte to the TX serial buffer. Called by main program. 39 | void serial_write(uint8_t data); 40 | 41 | // Write à string to the TX serial buffer. (for debugging) 42 | void serial_putstring(char* StringPtr); 43 | 44 | // Fetches the first byte in the serial read buffer. Called by main program. 45 | uint8_t serial_read(); 46 | 47 | // Reset and empty data in read buffer. Used by e-stop and reset. 48 | void serial_reset_read_buffer(); 49 | 50 | // Returns the number of bytes available in the RX serial buffer. 51 | uint8_t serial_get_rx_buffer_available(); 52 | 53 | // Returns the number of bytes used in the RX serial buffer. 54 | // NOTE: Deprecated. Not used unless classic status reports are enabled in config.h. 55 | uint8_t serial_get_rx_buffer_count(); 56 | 57 | // Returns the number of bytes used in the TX serial buffer. 58 | // NOTE: Not used except for debugging and ensuring no TX bottlenecks. 59 | uint8_t serial_get_tx_buffer_count(); 60 | 61 | #endif 62 | -------------------------------------------------------------------------------- /grbl/settings.h: -------------------------------------------------------------------------------- 1 | /* 2 | settings.h - eeprom configuration handling 3 | Part of Grbl 4 | 5 | Copyright (c) 2017-2018 Gauthier Briere 6 | Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC 7 | Copyright (c) 2009-2011 Simen Svale Skogsrud 8 | 9 | Grbl is free software: you can redistribute it and/or modify 10 | it under the terms of the GNU General Public License as published by 11 | the Free Software Foundation, either version 3 of the License, or 12 | (at your option) any later version. 13 | 14 | Grbl is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | GNU General Public License for more details. 18 | 19 | You should have received a copy of the GNU General Public License 20 | along with Grbl. If not, see . 21 | */ 22 | 23 | #ifndef settings_h 24 | #define settings_h 25 | 26 | #include "grbl.h" 27 | 28 | #ifndef EEPROM_LINE_SIZE 29 | #define EEPROM_LINE_SIZE 80 30 | #endif 31 | 32 | // Version of the EEPROM data. Will be used to migrate existing data from older versions of Grbl 33 | // when firmware is upgraded. Always stored in byte 0 of eeprom 34 | #define SETTINGS_VERSION 10 // NOTE: Check settings_reset() when moving to next version. 35 | 36 | // Define bit flag masks for the boolean settings in settings.flag. 37 | #define BITFLAG_REPORT_INCHES bit(0) 38 | #define BITFLAG_LASER_MODE bit(1) 39 | #define BITFLAG_INVERT_ST_ENABLE bit(2) 40 | #define BITFLAG_HARD_LIMIT_ENABLE bit(3) 41 | #define BITFLAG_HOMING_ENABLE bit(4) 42 | #define BITFLAG_SOFT_LIMIT_ENABLE bit(5) 43 | #define BITFLAG_INVERT_LIMIT_PINS bit(6) 44 | #define BITFLAG_INVERT_PROBE_PIN bit(7) 45 | 46 | // Define status reporting boolean enable bit flags in settings.status_report_mask 47 | #define BITFLAG_RT_STATUS_POSITION_TYPE bit(0) 48 | #define BITFLAG_RT_STATUS_BUFFER_STATE bit(1) 49 | 50 | // Define settings restore bitflags. 51 | #define SETTINGS_RESTORE_DEFAULTS bit(0) 52 | #define SETTINGS_RESTORE_PARAMETERS bit(1) 53 | #define SETTINGS_RESTORE_STARTUP_LINES bit(2) 54 | #define SETTINGS_RESTORE_BUILD_INFO bit(3) 55 | #ifndef SETTINGS_RESTORE_ALL 56 | #define SETTINGS_RESTORE_ALL 0xFF // All bitflags 57 | #endif 58 | 59 | // Define EEPROM memory address location values for Grbl settings and parameters 60 | #define EEPROM_ADDR_GLOBAL 1U 61 | #define EEPROM_ADDR_PARAMETERS 512U 62 | #define EEPROM_ADDR_STARTUP_BLOCK 768U 63 | #define EEPROM_ADDR_BUILD_INFO 942U 64 | 65 | // Define EEPROM address indexing for coordinate parameters 66 | #define N_COORDINATE_SYSTEM 6 // Number of supported work coordinate systems (from index 1) 67 | #define SETTING_INDEX_NCOORD N_COORDINATE_SYSTEM+1 // Total number of system stored (from index 0) 68 | // NOTE: Work coordinate indices are (0=G54, 1=G55, ... , 6=G59) 69 | #define SETTING_INDEX_G28 N_COORDINATE_SYSTEM // Home position 1 70 | #define SETTING_INDEX_G30 N_COORDINATE_SYSTEM+1 // Home position 2 71 | // #define SETTING_INDEX_G92 N_COORDINATE_SYSTEM+2 // Coordinate offset (G92.2,G92.3 not supported) 72 | 73 | // Define Grbl axis settings numbering scheme. Starts at START_VAL, every INCREMENT, over N_SETTINGS. 74 | #define AXIS_N_SETTINGS 4 75 | #define AXIS_SETTINGS_START_VAL 100 // NOTE: Reserving settings values >= 100 for axis settings. Up to 255. 76 | #define AXIS_SETTINGS_INCREMENT 10 // Must be greater than the number of axis settings 77 | 78 | // Global persistent settings (Stored from byte EEPROM_ADDR_GLOBAL onwards) 79 | typedef struct { 80 | // Axis settings 81 | float steps_per_mm[N_AXIS]; // Steps per units => steps_per_degre for rotationals axis (AXIS_4 and AXIS_5) 82 | float max_rate[N_AXIS]; 83 | float acceleration[N_AXIS]; 84 | float max_travel[N_AXIS]; 85 | 86 | // Remaining Grbl settings 87 | uint8_t pulse_microseconds; 88 | uint8_t step_invert_mask; 89 | uint8_t dir_invert_mask; 90 | uint8_t stepper_idle_lock_time; // If max value 255, steppers do not disable. 91 | uint8_t status_report_mask; // Mask to indicate desired report data. 92 | float junction_deviation; 93 | float arc_tolerance; 94 | 95 | float rpm_max; 96 | float rpm_min; 97 | 98 | uint8_t flags; // Contains default boolean settings 99 | 100 | uint8_t homing_dir_mask; 101 | float homing_feed_rate; 102 | float homing_seek_rate; 103 | uint16_t homing_debounce_delay; 104 | float homing_pulloff; 105 | } settings_t; 106 | extern settings_t settings; 107 | 108 | // Initialize the configuration subsystem (load settings from EEPROM) 109 | void settings_init(); 110 | 111 | // Helper function to clear and restore EEPROM defaults 112 | void settings_restore(uint8_t restore_flag); 113 | 114 | // A helper method to set new settings from command line 115 | uint8_t settings_store_global_setting(uint8_t parameter, float value); 116 | 117 | // Stores the protocol line variable as a startup line in EEPROM 118 | void settings_store_startup_line(uint8_t n, char *line); 119 | 120 | // Reads an EEPROM startup line to the protocol line variable 121 | uint8_t settings_read_startup_line(uint8_t n, char *line); 122 | 123 | // Stores build info user-defined string 124 | void settings_store_build_info(char *line); 125 | 126 | // Reads build info user-defined string 127 | uint8_t settings_read_build_info(char *line); 128 | 129 | // Writes selected coordinate data to EEPROM 130 | void settings_write_coord_data(uint8_t coord_select, float *coord_data); 131 | 132 | // Reads selected coordinate data from EEPROM 133 | uint8_t settings_read_coord_data(uint8_t coord_select, float *coord_data); 134 | 135 | // Returns the step pin mask according to Grbl's internal axis numbering 136 | uint8_t get_step_pin_mask(uint8_t i); 137 | 138 | // Returns the direction pin mask according to Grbl's internal axis numbering 139 | uint8_t get_direction_pin_mask(uint8_t i); 140 | 141 | // Returns the limit pin mask according to Grbl's internal axis numbering 142 | uint8_t get_limit_pin_mask(uint8_t i); 143 | 144 | 145 | #endif 146 | -------------------------------------------------------------------------------- /grbl/sleep.c: -------------------------------------------------------------------------------- 1 | /* 2 | sleep.c - determines and executes sleep procedures 3 | Part of Grbl 4 | 5 | Copyright (c) 2016 Sungeun K. Jeon 6 | 7 | Grbl is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | Grbl is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with Grbl. If not, see . 19 | */ 20 | 21 | #include "grbl.h" 22 | 23 | 24 | #define SLEEP_SEC_PER_OVERFLOW (65535.0*64.0/F_CPU) // With 16-bit timer size and prescaler 25 | #define SLEEP_COUNT_MAX (SLEEP_DURATION/SLEEP_SEC_PER_OVERFLOW) 26 | 27 | volatile uint8_t sleep_counter; 28 | 29 | 30 | // Initialize sleep counters and enable timer. 31 | static void sleep_enable() { 32 | sleep_counter = 0; // Reset sleep counter 33 | TCNT3 = 0; // Reset timer3 counter register 34 | TIMSK3 |= (1< rx_initial) || sys_rt_exec_state || sys_rt_exec_alarm ) { 74 | // Disable sleep timer and return to normal operation. 75 | sleep_disable(); 76 | return; 77 | } 78 | } while(sleep_counter <= SLEEP_COUNT_MAX); 79 | 80 | // If reached, sleep counter has expired. Execute sleep procedures. 81 | // Notify user that Grbl has timed out and will be parking. 82 | // To exit sleep, resume or reset. Either way, the job will not be recoverable. 83 | report_feedback_message(MESSAGE_SLEEP_MODE); 84 | system_set_exec_state_flag(EXEC_SLEEP); 85 | } 86 | 87 | 88 | // Checks running conditions for sleep. If satisfied, enables sleep countdown and executes 89 | // sleep mode upon elapse. 90 | // NOTE: Sleep procedures can be blocking, since Grbl isn't receiving any commands, nor moving. 91 | // Hence, make sure any valid running state that executes the sleep timer is not one that is moving. 92 | void sleep_check() 93 | { 94 | // The sleep execution feature will continue only if the machine is in an IDLE or HOLD state and 95 | // has any powered components enabled. 96 | // NOTE: With overrides or in laser mode, modal spindle and coolant state are not guaranteed. Need 97 | // to directly monitor and record running state during parking to ensure proper function. 98 | if (gc_state.modal.spindle || gc_state.modal.coolant) { 99 | if (sys.state == STATE_IDLE) { 100 | sleep_execute(); 101 | } else if ((sys.state & STATE_HOLD) && (sys.suspend & SUSPEND_HOLD_COMPLETE)) { 102 | sleep_execute(); 103 | } else if (sys.state == STATE_SAFETY_DOOR && (sys.suspend & SUSPEND_RETRACT_COMPLETE)) { 104 | sleep_execute(); 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /grbl/sleep.h: -------------------------------------------------------------------------------- 1 | /* 2 | sleep.h - Sleep methods header file 3 | Part of Grbl 4 | 5 | Copyright (c) 2016 Sungeun K. Jeon 6 | 7 | Grbl is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | Grbl is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with Grbl. If not, see . 19 | */ 20 | 21 | #ifndef sleep_h 22 | #define sleep_h 23 | 24 | #include "grbl.h" 25 | 26 | 27 | // Initialize sleep timer 28 | void sleep_init(); 29 | 30 | // Checks running conditions for sleep. If satisfied, enables sleep countdown and executes 31 | // sleep mode upon elapse. 32 | void sleep_check(); 33 | 34 | #endif 35 | -------------------------------------------------------------------------------- /grbl/spindle_control.c: -------------------------------------------------------------------------------- 1 | /* 2 | spindle_control.c - spindle control methods 3 | Part of Grbl 4 | 5 | Copyright (c) 2012-2017 Sungeun K. Jeon for Gnea Research LLC 6 | Copyright (c) 2009-2011 Simen Svale Skogsrud 7 | 8 | Grbl is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | Grbl is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with Grbl. If not, see . 20 | */ 21 | 22 | #include "grbl.h" 23 | 24 | 25 | static float pwm_gradient; // Precalulated value to speed up rpm to PWM conversions. 26 | 27 | 28 | void spindle_init() 29 | { 30 | // Configure variable spindle PWM and enable pin, if required. 31 | SPINDLE_PWM_DDR |= (1<= settings.rpm_max) || (rpm >= RPM_MAX)) { 106 | rpm = RPM_MAX; 107 | pwm_value = SPINDLE_PWM_MAX_VALUE; 108 | } else if (rpm <= RPM_MIN) { 109 | if (rpm == 0.0) { // S0 disables spindle 110 | pwm_value = SPINDLE_PWM_OFF_VALUE; 111 | } else { 112 | rpm = RPM_MIN; 113 | pwm_value = SPINDLE_PWM_MIN_VALUE; 114 | } 115 | } else { 116 | // Compute intermediate PWM value with linear spindle speed model via piecewise linear fit model. 117 | #if (N_PIECES > 3) 118 | if (rpm > RPM_POINT34) { 119 | pwm_value = floor(RPM_LINE_A4*rpm - RPM_LINE_B4); 120 | } else 121 | #endif 122 | #if (N_PIECES > 2) 123 | if (rpm > RPM_POINT23) { 124 | pwm_value = floor(RPM_LINE_A3*rpm - RPM_LINE_B3); 125 | } else 126 | #endif 127 | #if (N_PIECES > 1) 128 | if (rpm > RPM_POINT12) { 129 | pwm_value = floor(RPM_LINE_A2*rpm - RPM_LINE_B2); 130 | } else 131 | #endif 132 | { 133 | pwm_value = floor(RPM_LINE_A1*rpm - RPM_LINE_B1); 134 | } 135 | } 136 | sys.spindle_speed = rpm; 137 | return(pwm_value); 138 | } 139 | 140 | #else 141 | 142 | // Called by spindle_set_state() and step segment generator. Keep routine small and efficient. 143 | uint16_t spindle_compute_pwm_value(float rpm) // Mega2560 PWM register is 16-bit. 144 | { 145 | uint16_t pwm_value; 146 | rpm *= (0.010*sys.spindle_speed_ovr); // Scale by spindle speed override value. 147 | // Calculate PWM register value based on rpm max/min settings and programmed rpm. 148 | if ((settings.rpm_min >= settings.rpm_max) || (rpm >= settings.rpm_max)) { 149 | // No PWM range possible. Set simple on/off spindle control pin state. 150 | sys.spindle_speed = settings.rpm_max; 151 | pwm_value = SPINDLE_PWM_MAX_VALUE; 152 | } else if (rpm <= settings.rpm_min) { 153 | if (rpm == 0.0) { // S0 disables spindle 154 | sys.spindle_speed = 0.0; 155 | pwm_value = SPINDLE_PWM_OFF_VALUE; 156 | } else { // Set minimum PWM output 157 | sys.spindle_speed = settings.rpm_min; 158 | pwm_value = SPINDLE_PWM_MIN_VALUE; 159 | } 160 | } else { 161 | // Compute intermediate PWM value with linear spindle speed model. 162 | // NOTE: A nonlinear model could be installed here, if required, but keep it VERY light-weight. 163 | sys.spindle_speed = rpm; 164 | pwm_value = floor((rpm-settings.rpm_min)*pwm_gradient) + SPINDLE_PWM_MIN_VALUE; 165 | } 166 | return(pwm_value); 167 | } 168 | 169 | #endif 170 | 171 | // Immediately sets spindle running state with direction and spindle rpm via PWM, if enabled. 172 | // Called by g-code parser spindle_sync(), parking retract and restore, g-code program end, 173 | // sleep, and spindle stop override. 174 | void spindle_set_state(uint8_t state, float rpm) 175 | { 176 | if (sys.abort) { return; } // Block during abort. 177 | if (state == SPINDLE_DISABLE) { // Halt or set spindle direction and rpm. 178 | 179 | sys.spindle_speed = 0.0; 180 | spindle_stop(); 181 | 182 | } else { 183 | 184 | if (state == SPINDLE_ENABLE_CW) { 185 | SPINDLE_DIRECTION_PORT &= ~(1<. 20 | */ 21 | 22 | #ifndef spindle_control_h 23 | #define spindle_control_h 24 | 25 | #define SPINDLE_NO_SYNC false 26 | #define SPINDLE_FORCE_SYNC true 27 | 28 | #define SPINDLE_STATE_DISABLE 0 // Must be zero. 29 | #define SPINDLE_STATE_CW bit(0) 30 | #define SPINDLE_STATE_CCW bit(1) 31 | 32 | 33 | // Initializes spindle pins and hardware PWM, if enabled. 34 | void spindle_init(); 35 | 36 | // Returns current spindle output state. Overrides may alter it from programmed states. 37 | uint8_t spindle_get_state(); 38 | 39 | // Called by g-code parser when setting spindle state and requires a buffer sync. 40 | // Immediately sets spindle running state with direction and spindle rpm via PWM, if enabled. 41 | // Called by spindle_sync() after sync and parking motion/spindle stop override during restore. 42 | 43 | // Called by g-code parser when setting spindle state and requires a buffer sync. 44 | void spindle_sync(uint8_t state, float rpm); 45 | 46 | // Sets spindle running state with direction, enable, and spindle PWM. 47 | void spindle_set_state(uint8_t state, float rpm); 48 | 49 | // Sets spindle PWM quickly for stepper ISR. Also called by spindle_set_state(). 50 | // NOTE: Mega2560 PWM register is 16-bit. 51 | void spindle_set_speed(uint16_t pwm_value); 52 | 53 | // Computes Mega2560-specific PWM register value for the given RPM for quick updating. 54 | uint16_t spindle_compute_pwm_value(float rpm); 55 | 56 | // Stop and start spindle routines. Called by all spindle routines and stepper ISR. 57 | void spindle_stop(); 58 | 59 | 60 | #endif 61 | -------------------------------------------------------------------------------- /grbl/stepper.h: -------------------------------------------------------------------------------- 1 | /* 2 | stepper.h - stepper motor driver: executes motion plans of planner.c using the stepper motors 3 | Part of Grbl 4 | 5 | Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC 6 | Copyright (c) 2009-2011 Simen Svale Skogsrud 7 | 8 | Grbl is free software: you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation, either version 3 of the License, or 11 | (at your option) any later version. 12 | 13 | Grbl is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with Grbl. If not, see . 20 | */ 21 | 22 | #ifndef stepper_h 23 | #define stepper_h 24 | 25 | #ifndef SEGMENT_BUFFER_SIZE 26 | #define SEGMENT_BUFFER_SIZE 10 27 | #endif 28 | 29 | // Initialize and setup the stepper motor subsystem 30 | void stepper_init(); 31 | 32 | // Enable steppers, but cycle does not start unless called by motion control or realtime command. 33 | void st_wake_up(); 34 | 35 | // Immediately disables steppers 36 | void st_go_idle(); 37 | 38 | // Generate the step and direction port invert masks. 39 | void st_generate_step_dir_invert_masks(); 40 | 41 | // Reset the stepper subsystem variables 42 | void st_reset(); 43 | 44 | // Changes the run state of the step segment buffer to execute the special parking motion. 45 | void st_parking_setup_buffer(); 46 | 47 | // Restores the step segment buffer to the normal run state after a parking motion. 48 | void st_parking_restore_buffer(); 49 | 50 | // Reloads step segment buffer. Called continuously by realtime execution system. 51 | void st_prep_buffer(); 52 | 53 | // Called by planner_recalculate() when the executing block is updated by the new plan. 54 | void st_update_plan_block_parameters(); 55 | 56 | // Called by realtime status reporting if realtime rate reporting is enabled in config.h. 57 | float st_get_realtime_rate(); 58 | 59 | #endif 60 | -------------------------------------------------------------------------------- /grbl/system.h: -------------------------------------------------------------------------------- 1 | /* 2 | system.h - Header for system level commands and real-time processes 3 | Part of Grbl 4 | 5 | Copyright (c) 2014-2016 Sungeun K. Jeon for Gnea Research LLC 6 | 7 | Grbl is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | Grbl is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with Grbl. If not, see . 19 | */ 20 | 21 | #ifndef system_h 22 | #define system_h 23 | 24 | #include "grbl.h" 25 | 26 | // Define system executor bit map. Used internally by realtime protocol as realtime command flags, 27 | // which notifies the main program to execute the specified realtime command asynchronously. 28 | // NOTE: The system executor uses an unsigned 8-bit volatile variable (8 flag limit.) The default 29 | // flags are always false, so the realtime protocol only needs to check for a non-zero value to 30 | // know when there is a realtime command to execute. 31 | #define EXEC_STATUS_REPORT bit(0) // bitmask 00000001 32 | #define EXEC_CYCLE_START bit(1) // bitmask 00000010 33 | #define EXEC_CYCLE_STOP bit(2) // bitmask 00000100 34 | #define EXEC_FEED_HOLD bit(3) // bitmask 00001000 35 | #define EXEC_RESET bit(4) // bitmask 00010000 36 | #define EXEC_SAFETY_DOOR bit(5) // bitmask 00100000 37 | #define EXEC_MOTION_CANCEL bit(6) // bitmask 01000000 38 | #define EXEC_SLEEP bit(7) // bitmask 10000000 39 | 40 | // Alarm executor codes. Valid values (1-255). Zero is reserved. 41 | #define EXEC_ALARM_HARD_LIMIT 1 42 | #define EXEC_ALARM_SOFT_LIMIT 2 43 | #define EXEC_ALARM_ABORT_CYCLE 3 44 | #define EXEC_ALARM_PROBE_FAIL_INITIAL 4 45 | #define EXEC_ALARM_PROBE_FAIL_CONTACT 5 46 | #define EXEC_ALARM_HOMING_FAIL_RESET 6 47 | #define EXEC_ALARM_HOMING_FAIL_DOOR 7 48 | #define EXEC_ALARM_HOMING_FAIL_PULLOFF 8 49 | #define EXEC_ALARM_HOMING_FAIL_APPROACH 9 50 | 51 | // Override bit maps. Realtime bitflags to control feed, rapid, spindle, and coolant overrides. 52 | // Spindle/coolant and feed/rapids are separated into two controlling flag variables. 53 | #define EXEC_FEED_OVR_RESET bit(0) 54 | #define EXEC_FEED_OVR_COARSE_PLUS bit(1) 55 | #define EXEC_FEED_OVR_COARSE_MINUS bit(2) 56 | #define EXEC_FEED_OVR_FINE_PLUS bit(3) 57 | #define EXEC_FEED_OVR_FINE_MINUS bit(4) 58 | #define EXEC_RAPID_OVR_RESET bit(5) 59 | #define EXEC_RAPID_OVR_MEDIUM bit(6) 60 | #define EXEC_RAPID_OVR_LOW bit(7) 61 | // #define EXEC_RAPID_OVR_EXTRA_LOW bit(*) // *NOT SUPPORTED* 62 | 63 | #define EXEC_SPINDLE_OVR_RESET bit(0) 64 | #define EXEC_SPINDLE_OVR_COARSE_PLUS bit(1) 65 | #define EXEC_SPINDLE_OVR_COARSE_MINUS bit(2) 66 | #define EXEC_SPINDLE_OVR_FINE_PLUS bit(3) 67 | #define EXEC_SPINDLE_OVR_FINE_MINUS bit(4) 68 | #define EXEC_SPINDLE_OVR_STOP bit(5) 69 | #define EXEC_COOLANT_FLOOD_OVR_TOGGLE bit(6) 70 | #define EXEC_COOLANT_MIST_OVR_TOGGLE bit(7) 71 | 72 | // Define system state bit map. The state variable primarily tracks the individual functions 73 | // of Grbl to manage each without overlapping. It is also used as a messaging flag for 74 | // critical events. 75 | #define STATE_IDLE 0 // Must be zero. No flags. 76 | #define STATE_ALARM bit(0) // In alarm state. Locks out all g-code processes. Allows settings access. 77 | #define STATE_CHECK_MODE bit(1) // G-code check mode. Locks out planner and motion only. 78 | #define STATE_HOMING bit(2) // Performing homing cycle 79 | #define STATE_CYCLE bit(3) // Cycle is running or motions are being executed. 80 | #define STATE_HOLD bit(4) // Active feed hold 81 | #define STATE_JOG bit(5) // Jogging mode. 82 | #define STATE_SAFETY_DOOR bit(6) // Safety door is ajar. Feed holds and de-energizes system. 83 | #define STATE_SLEEP bit(7) // Sleep state. 84 | 85 | // Define system suspend flags. Used in various ways to manage suspend states and procedures. 86 | #define SUSPEND_DISABLE 0 // Must be zero. 87 | #define SUSPEND_HOLD_COMPLETE bit(0) // Indicates initial feed hold is complete. 88 | #define SUSPEND_RESTART_RETRACT bit(1) // Flag to indicate a retract from a restore parking motion. 89 | #define SUSPEND_RETRACT_COMPLETE bit(2) // (Safety door only) Indicates retraction and de-energizing is complete. 90 | #define SUSPEND_INITIATE_RESTORE bit(3) // (Safety door only) Flag to initiate resume procedures from a cycle start. 91 | #define SUSPEND_RESTORE_COMPLETE bit(4) // (Safety door only) Indicates ready to resume normal operation. 92 | #define SUSPEND_SAFETY_DOOR_AJAR bit(5) // Tracks safety door state for resuming. 93 | #define SUSPEND_MOTION_CANCEL bit(6) // Indicates a canceled resume motion. Currently used by probing routine. 94 | #define SUSPEND_JOG_CANCEL bit(7) // Indicates a jog cancel in process and to reset buffers when complete. 95 | 96 | // Define step segment generator state flags. 97 | #define STEP_CONTROL_NORMAL_OP 0 // Must be zero. 98 | #define STEP_CONTROL_END_MOTION bit(0) 99 | #define STEP_CONTROL_EXECUTE_HOLD bit(1) 100 | #define STEP_CONTROL_EXECUTE_SYS_MOTION bit(2) 101 | #define STEP_CONTROL_UPDATE_SPINDLE_PWM bit(3) 102 | 103 | // Define control pin index for Grbl internal use. Pin maps may change, but these values don't. 104 | #define N_CONTROL_PIN 4 105 | #define CONTROL_PIN_INDEX_SAFETY_DOOR bit(0) 106 | #define CONTROL_PIN_INDEX_RESET bit(1) 107 | #define CONTROL_PIN_INDEX_FEED_HOLD bit(2) 108 | #define CONTROL_PIN_INDEX_CYCLE_START bit(3) 109 | 110 | // Define spindle stop override control states. 111 | #define SPINDLE_STOP_OVR_DISABLED 0 // Must be zero. 112 | #define SPINDLE_STOP_OVR_ENABLED bit(0) 113 | #define SPINDLE_STOP_OVR_INITIATE bit(1) 114 | #define SPINDLE_STOP_OVR_RESTORE bit(2) 115 | #define SPINDLE_STOP_OVR_RESTORE_CYCLE bit(3) 116 | 117 | 118 | // Define global system variables 119 | typedef struct { 120 | uint8_t state; // Tracks the current system state of Grbl. 121 | uint8_t abort; // System abort flag. Forces exit back to main loop for reset. 122 | uint8_t suspend; // System suspend bitflag variable that manages holds, cancels, and safety door. 123 | uint8_t soft_limit; // Tracks soft limit errors for the state machine. (boolean) 124 | uint8_t step_control; // Governs the step segment generator depending on system state. 125 | uint8_t probe_succeeded; // Tracks if last probing cycle was successful. 126 | #ifdef DEFAULTS_RAMPS_BOARD 127 | uint8_t homing_axis_lock[N_AXIS]; // Locks axes when limits engage. Used as an axis motion mask in the stepper ISR. 128 | #else 129 | uint8_t homing_axis_lock; // Locks axes when limits engage. Used as an axis motion mask in the stepper ISR. 130 | #endif 131 | uint8_t f_override; // Feed rate override value in percent 132 | uint8_t r_override; // Rapids override value in percent 133 | uint8_t spindle_speed_ovr; // Spindle speed value in percent 134 | uint8_t spindle_stop_ovr; // Tracks spindle stop override states 135 | uint8_t report_ovr_counter; // Tracks when to add override data to status reports. 136 | uint8_t report_wco_counter; // Tracks when to add work coordinate offset data to status reports. 137 | #ifdef ENABLE_PARKING_OVERRIDE_CONTROL 138 | uint8_t override_ctrl; // Tracks override control states. 139 | #endif 140 | float spindle_speed; 141 | } system_t; 142 | extern system_t sys; 143 | 144 | // NOTE: These position variables may need to be declared as volatiles, if problems arise. 145 | extern int32_t sys_position[N_AXIS]; // Real-time machine (aka home) position vector in steps. 146 | extern int32_t sys_probe_position[N_AXIS]; // Last probe position in machine coordinates and steps. 147 | 148 | extern volatile uint8_t sys_probe_state; // Probing state value. Used to coordinate the probing cycle with stepper ISR. 149 | extern volatile uint8_t sys_rt_exec_state; // Global realtime executor bitflag variable for state management. See EXEC bitmasks. 150 | extern volatile uint8_t sys_rt_exec_alarm; // Global realtime executor bitflag variable for setting various alarms. 151 | extern volatile uint8_t sys_rt_exec_motion_override; // Global realtime executor bitflag variable for motion-based overrides. 152 | extern volatile uint8_t sys_rt_exec_accessory_override; // Global realtime executor bitflag variable for spindle/coolant overrides. 153 | extern uint8_t axis_X_mask; // Global mask for axis X bits 154 | extern uint8_t axis_Y_mask; // Global mask for axis Y bits 155 | extern uint8_t axis_Z_mask; // Global mask for axis Z bits 156 | extern uint8_t axis_A_mask; // Global mask for axis A bits 157 | extern uint8_t axis_B_mask; // Global mask for axis B bits 158 | extern uint8_t axis_C_mask; // Global mask for axis C bits 159 | extern uint8_t axis_U_mask; // Global mask for axis A bits 160 | extern uint8_t axis_V_mask; // Global mask for axis B bits 161 | extern uint8_t axis_W_mask; // Global mask for axis C bits 162 | extern unsigned char axis_name[N_AXIS]; // Global table of axis names 163 | #ifdef DEBUG 164 | #define EXEC_DEBUG_REPORT bit(0) 165 | extern volatile uint8_t sys_rt_exec_debug; 166 | #endif 167 | 168 | // Initialize the serial protocol 169 | void system_init(); 170 | 171 | // Returns bitfield of control pin states, organized by CONTROL_PIN_INDEX. (1=triggered, 0=not triggered). 172 | uint8_t system_control_get_state(); 173 | 174 | // Returns if safety door is open or closed, based on pin state. 175 | uint8_t system_check_safety_door_ajar(); 176 | 177 | // Executes an internal system command, defined as a string starting with a '$' 178 | uint8_t system_execute_line(char *line); 179 | 180 | // Execute the startup script lines stored in EEPROM upon initialization 181 | void system_execute_startup(char *line); 182 | 183 | 184 | void system_flag_wco_change(); 185 | 186 | // Returns machine position of axis 'idx'. Must be sent a 'step' array. 187 | float system_convert_axis_steps_to_mpos(int32_t *steps, uint8_t idx); 188 | 189 | // Updates a machine 'position' array based on the 'step' array sent. 190 | void system_convert_array_steps_to_mpos(float *position, int32_t *steps); 191 | 192 | // CoreXY calculation only. Returns x or y-axis "steps" based on CoreXY motor steps. 193 | #ifdef COREXY 194 | int32_t system_convert_corexy_to_x_axis_steps(int32_t *steps); 195 | int32_t system_convert_corexy_to_y_axis_steps(int32_t *steps); 196 | #endif 197 | 198 | // Checks and reports if target array exceeds machine travel limits. 199 | uint8_t system_check_travel_limits(float *target); 200 | 201 | // Special handlers for setting and clearing Grbl's real-time execution flags. 202 | void system_set_exec_state_flag(uint8_t mask); 203 | void system_clear_exec_state_flag(uint8_t mask); 204 | void system_set_exec_alarm(uint8_t code); 205 | void system_clear_exec_alarm(); 206 | void system_set_exec_motion_override_flag(uint8_t mask); 207 | void system_set_exec_accessory_override_flag(uint8_t mask); 208 | void system_clear_exec_motion_overrides(); 209 | void system_clear_exec_accessory_overrides(); 210 | 211 | 212 | #endif 213 | -------------------------------------------------------------------------------- /platformio.ini: -------------------------------------------------------------------------------- 1 | ;PlatformIO Project Configuration File 2 | ; 3 | ; Build options: build flags, source filter 4 | ; Upload options: custom upload port, speed and extra flags 5 | ; Library options: dependencies, extra library storages 6 | ; Advanced options: extra scripting 7 | ; 8 | ; Please visit documentation for the other options and examples 9 | ; https://docs.platformio.org/page/projectconf.html 10 | 11 | [platformio] 12 | workspace_dir=build 13 | src_dir=grbl 14 | include_dir=grbl 15 | 16 | [env:megaatmega2560] 17 | platform = atmelavr 18 | board = megaatmega2560 19 | framework = arduino 20 | monitor_speed = 115200 --------------------------------------------------------------------------------