diff --git a/grbl/config.h b/grbl/config.h
index dcad5b40d..93233d072 100644
--- a/grbl/config.h
+++ b/grbl/config.h
@@ -34,12 +34,22 @@
// NOTE: OEMs can avoid the need to maintain/update the defaults.h and cpu_map.h files and use only
// one configuration file by placing their specific defaults and pin map at the bottom of this file.
// If doing so, simply comment out these two defines and see instructions below.
-#define DEFAULTS_GENERIC
-#define CPU_MAP_2560_INITIAL
+//#define DEFAULTS_GENERIC
+//#define CPU_MAP_2560_INITIAL
+
+#define DEFAULT_CNC3020
// Serial baud rate
#define BAUD_RATE 115200
+#ifdef WIN32
+#define CPU_MAP_WIN32
+#endif
+
+#ifdef STM32F103C8
+#define CPU_MAP_STM32F103
+#endif
+
// Define realtime command special characters. These characters are 'picked-off' directly from the
// serial read data stream and are not passed to the grbl line execution parser. Select characters
// that do not and must not exist in the streamed g-code program. ASCII control characters may be
@@ -122,9 +132,10 @@
// through an automatically generated message. If disabled, users can still access the last probe
// coordinates through Grbl '$#' print parameters.
#define MESSAGE_PROBE_COORDINATES // Enabled by default. Comment to disable.
-
+
// After the safety door switch has been toggled and restored, this setting sets the power-up delay
// between restoring the spindle and coolant and resuming the cycle.
+
#define SAFETY_DOOR_SPINDLE_DELAY 4.0 // Float (seconds)
#define SAFETY_DOOR_COOLANT_DELAY 1.0 // Float (seconds)
@@ -137,6 +148,7 @@
// have the same steps per mm internally.
// #define COREXY // Default disabled. Uncomment to enable.
+
// Inverts pin logic of the control command pins based on a mask. This essentially means you can use
// normally-closed switches on the specified pins, rather than the default normally-open switches.
// NOTE: The top option will mask and invert all control pins. The bottom option is an example of
@@ -212,7 +224,7 @@
// check in the settings module to prevent settings values that will exceed this limitation. The maximum
// step rate is strictly limited by the CPU speed and will change if something other than an AVR running
// at 16MHz is used.
-#define MAX_STEP_RATE_HZ 30000 // Hz
+//#define MAX_STEP_RATE_HZ 30000 // Hz
// By default, Grbl sets all input pins to normal-high operation with their internal pull-up resistors
// enabled. This simplifies the wiring for users by requiring only a switch connected to ground,
@@ -341,7 +353,7 @@
// NOTE: Be very careful when changing this value. Check EEPROM address locations to make sure
// these string storage locations won't corrupt one another.
// #define EEPROM_LINE_SIZE 80 // Uncomment to override defaults in settings.h
-
+
// Toggles XON/XOFF software flow control for serial communications. Not officially supported
// due to problems involving the Atmega8U2 USB-to-serial chips on current Arduinos. The firmware
// on these chips do not support XON/XOFF flow control characters and the intermediate buffer
@@ -415,7 +427,6 @@
// #define SLEEP_ENABLE // Default disabled. Uncomment to enable.
#define SLEEP_DURATION 5.0 // Float (0.25 - 61.0) seconds before sleep mode is executed.
-
// ---------------------------------------------------------------------------------------
// COMPILE-TIME ERROR CHECKING OF DEFINE VALUES:
@@ -441,5 +452,4 @@
// Paste CPU_MAP definitions here.
// Paste default settings definitions here.
-
#endif
diff --git a/grbl/coolant_control.c b/grbl/coolant_control.c
index 8467118e1..0ecd68a3a 100644
--- a/grbl/coolant_control.c
+++ b/grbl/coolant_control.c
@@ -1,36 +1,53 @@
-/*
- coolant_control.c - coolant control methods
- Part of Grbl
-
- Copyright (c) 2012-2016 Sungeun K. Jeon
-
- Grbl is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Grbl is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with Grbl. If not, see .
-*/
-
-#include "grbl.h"
-
-
-void coolant_init()
-{
- COOLANT_FLOOD_DDR |= (1 << COOLANT_FLOOD_BIT); // Configure as output pin.
- COOLANT_MIST_DDR |= (1 << COOLANT_MIST_BIT); // Configure as output pin.
- coolant_stop();
-}
-
+/*
+ coolant_control.c - coolant control methods
+ Part of Grbl
+
+ Copyright (c) 2012-2015 Sungeun K. Jeon
+
+ Grbl is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Grbl is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with Grbl. If not, see .
+*/
+
+#include "grbl.h"
+
+
+void coolant_init()
+{
+#ifdef AVRTARGET
+ COOLANT_FLOOD_DDR |= (1 << COOLANT_FLOOD_BIT);
+ COOLANT_MIST_DDR |= (1 << COOLANT_MIST_BIT);
+#endif
+#ifdef STM32F103C8
+ GPIO_InitTypeDef GPIO_InitStructure;
+ RCC_APB2PeriphClockCmd(RCC_COOLANT_FLOOD_PORT, ENABLE);
+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
+ GPIO_InitStructure.GPIO_Pin = 1 << COOLANT_FLOOD_BIT;
+ GPIO_Init(COOLANT_FLOOD_PORT, &GPIO_InitStructure);
+
+ RCC_APB2PeriphClockCmd(RCC_COOLANT_MIST_PORT, ENABLE);
+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
+ GPIO_InitStructure.GPIO_Pin = 1 << COOLANT_MIST_BIT;
+ GPIO_Init(COOLANT_FLOOD_PORT, &GPIO_InitStructure);
+#endif
+ coolant_stop();
+}
+
uint8_t coolant_is_enabled()
{
+#ifdef AVRTARGET
#ifdef INVERT_COOLANT_FLOOD_PIN
if (!(COOLANT_FLOOD_PORT & (1<
#include
-
+#endif
+#ifdef WIN32
+#include
+#include
+#endif
+#ifdef STM32F103C8
+#include
+#include "stm32eeprom.h"
+#include "settings.h"
+#endif
+#if defined(WIN32) || defined (STM32F103C8)
+unsigned char EE_Buffer[0x400];
+#endif
/* These EEPROM bits have different names on different devices. */
+#ifdef AVRTARGET
#ifndef EEPE
#define EEPE EEWE //!< EEPROM program/write enable.
#define EEMPE EEMWE //!< EEPROM master program/write enable.
@@ -46,12 +60,104 @@
* \param addr EEPROM address to read from.
* \return The byte read from the EEPROM address.
*/
+#endif
+
+#if defined(WIN32)
+void eeprom_flush()
+{
+ FILE *out = fopen("eeprom.bin","wb");
+ fwrite(EE_Buffer,1,0x400,out);
+ fclose(out);
+}
+void eeprom_init()
+{
+ FILE *in = fopen("eeprom.bin","rb");
+ if (in != NULL)
+ {
+ fread(EE_Buffer,1,0x400,in);
+ fclose(in);
+ }
+ else
+ {
+ memset(EE_Buffer,0xff,0x400);
+ }
+}
+#endif
+
+#ifdef STM32F103C8
+#ifndef NOEEPROMSUPPORT
+void eeprom_flush()
+{
+ uint32_t nAddress = EEPROM_START_ADDRESS;
+ uint16_t *pBuffer = (uint16_t *)EE_Buffer;
+ uint16_t nSize = PAGE_SIZE;
+
+ FLASH_Status FlashStatus = FLASH_COMPLETE;
+
+ /* Erase Page0 */
+ FlashStatus = FLASH_ErasePage(EEPROM_START_ADDRESS);
+
+ /* If erase operation was failed, a Flash error code is returned */
+ if (FlashStatus != FLASH_COMPLETE)
+ {
+ return;
+ }
+
+ while (nSize > 0)
+ {
+ if (*pBuffer != 0xffff)
+ {
+ FLASH_ProgramHalfWord(nAddress,*pBuffer ++);
+ }
+ else
+ {
+ pBuffer ++;
+ }
+ if (*pBuffer != 0xffff)
+ {
+ FLASH_ProgramHalfWord(nAddress + 2,*pBuffer ++);
+ }
+ else
+ {
+ pBuffer ++;
+ }
+ nSize -= 4;
+ nAddress += 4;
+ }
+}
+void eeprom_init()
+{
+ uint16_t VarIdx = 0;
+ uint8_t *pTmp = EE_Buffer;
+
+ for (VarIdx = 0; VarIdx < PAGE_SIZE; VarIdx ++)
+ {
+ *pTmp ++ = (*(__IO uint8_t*)(EEPROM_START_ADDRESS +VarIdx));
+ }
+
+ if (EE_Buffer[0] != SETTINGS_VERSION)
+ {
+ pTmp = EE_Buffer;
+
+ for (VarIdx = 0; VarIdx < PAGE_SIZE; VarIdx ++)
+ {
+ *pTmp ++ = 0xFF;
+ }
+ }
+}
+#endif
+#endif
unsigned char eeprom_get_char( unsigned int addr )
{
+#ifdef AVRTARGET
do {} while( EECR & (1< 0.005) {
if (delta_r > 0.5) { FAIL(STATUS_GCODE_INVALID_TARGET); } // [Arc definition error] > 0.5mm
if (delta_r > (0.001*gc_block.values.r)) { FAIL(STATUS_GCODE_INVALID_TARGET); } // [Arc definition error] > 0.005mm AND 0.1% radius
@@ -956,11 +961,11 @@ uint8_t gc_execute_line(char *line)
break;
case MOTION_MODE_CW_ARC:
mc_arc(gc_state.position, gc_block.values.xyz, gc_block.values.ijk, gc_block.values.r,
- gc_state.feed_rate, gc_state.modal.feed_rate, axis_0, axis_1, axis_linear, true, gc_state.line_number);
+ gc_state.feed_rate, gc_state.modal.feed_rate, axis_0, axis_1, axis_linear, true, gc_state.line_number);
break;
case MOTION_MODE_CCW_ARC:
mc_arc(gc_state.position, gc_block.values.xyz, gc_block.values.ijk, gc_block.values.r,
- gc_state.feed_rate, gc_state.modal.feed_rate, axis_0, axis_1, axis_linear, false, gc_state.line_number);
+ gc_state.feed_rate, gc_state.modal.feed_rate, axis_0, axis_1, axis_linear, false, gc_state.line_number);
break;
case MOTION_MODE_PROBE_TOWARD:
// NOTE: gc_block.values.xyz is returned from mc_probe_cycle with the updated position value. So
@@ -989,6 +994,7 @@ uint8_t gc_execute_line(char *line)
// refill and can only be resumed by the cycle start run-time command.
gc_state.modal.program_flow = gc_block.modal.program_flow;
if (gc_state.modal.program_flow) {
+ protocol_buffer_synchronize(); // Sync and finish all remaining buffered motions before moving on.
protocol_buffer_synchronize(); // Sync and finish all remaining buffered motions before moving on.
if (gc_state.modal.program_flow == PROGRAM_FLOW_PAUSED) {
if (sys.state != STATE_CHECK_MODE) {
diff --git a/grbl/grbl.h b/grbl/grbl.h
index a5baa0080..333c5b371 100644
--- a/grbl/grbl.h
+++ b/grbl/grbl.h
@@ -1,63 +1,103 @@
-/*
- grbl.h - main Grbl include file
- Part of Grbl
-
- Copyright (c) 2015 Sungeun K. Jeon
-
- Grbl is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Grbl is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with Grbl. If not, see .
-*/
-
-#ifndef grbl_h
-#define grbl_h
-
-// Grbl versioning system
+/*
+ grbl.h - main Grbl include file
+ Part of Grbl
+
+ Copyright (c) 2015 Sungeun K. Jeon
+
+ Grbl is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Grbl is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with Grbl. If not, see .
+*/
+
+#ifndef grbl_h
+#define grbl_h
+
+// Grbl versioning system
#define GRBL_VERSION "1.0d"
-#define GRBL_VERSION_BUILD "20160510"
-
-// Define standard libraries used by Grbl.
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-// Define the Grbl system include files. NOTE: Do not alter organization.
-#include "config.h"
-#include "nuts_bolts.h"
-#include "settings.h"
-#include "system.h"
-#include "defaults.h"
-#include "cpu_map.h"
-#include "coolant_control.h"
-#include "eeprom.h"
-#include "gcode.h"
-#include "limits.h"
-#include "motion_control.h"
-#include "planner.h"
-#include "print.h"
-#include "probe.h"
-#include "protocol.h"
-#include "report.h"
-#include "serial.h"
-#include "spindle_control.h"
-#include "stepper.h"
-#include "sleep.h"
-
-#endif
+#define GRBL_VERSION_BUILD "20160510"
+
+// Define standard libraries used by Grbl.
+#ifdef AVRTARGET
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#define PORTPINDEF uint8_t
+#endif
+#include
+#ifdef WIN32
+#include
+typedef signed char int8_t;
+typedef signed short int16_t;
+typedef signed int int32_t;
+typedef unsigned char uint8_t;
+typedef unsigned short uint16_t;
+typedef unsigned int uint32_t;
+typedef signed long long int64_t;
+typedef unsigned long long uint64_t;
+typedef int bool;
+#define false 0
+#define true 1
+#define trunc(x) (int32_t)x
+#define lround(x) (int32_t) (x + 0.5)
+#define round(x) (int32_t) (x + 0.5)
+#define PSTR(x) x
+#define pgm_read_byte_near(x) *(x)
+#define _delay_ms(x) Sleep(x)
+#define M_PI (float)3.1415926
+#define LOG(x,y)
+#define PORTPINDEF uint8_t
+#endif
+#ifdef STM32F103C8
+#include "stm32f10x.h"
+#include "stm32f10x_gpio.h"
+#include "stm32f10x_exti.h"
+#include "misc.h"
+#define PSTR(x) x
+#define pgm_read_byte_near(x) *(x)
+void _delay_ms(uint32_t x);
+void _delay_us(uint32_t x);
+#define false 0
+#define true 1
+#define PORTPINDEF uint16_t
+typedef int bool;
+#define NOEEPROMSUPPORT
+#endif
+#include
+#include
+#include
+
+// Define the Grbl system include files. NOTE: Do not alter organization.
+#include "config.h"
+#include "nuts_bolts.h"
+#include "settings.h"
+#include "system.h"
+#include "defaults.h"
+#include "cpu_map.h"
+#include "coolant_control.h"
+#include "eeprom.h"
+#include "gcode.h"
+#include "limits.h"
+#include "motion_control.h"
+#include "planner.h"
+#include "print.h"
+#include "probe.h"
+#include "protocol.h"
+#include "report.h"
+#include "serial.h"
+#include "spindle_control.h"
+#include "stepper.h"
+#include "sleep.h"
+#endif
diff --git a/grbl/grblwin/ReadMe.txt b/grbl/grblwin/ReadMe.txt
new file mode 100755
index 000000000..ae094d974
--- /dev/null
+++ b/grbl/grblwin/ReadMe.txt
@@ -0,0 +1,40 @@
+========================================================================
+ CONSOLE APPLICATION : grbl Project Overview
+========================================================================
+
+AppWizard has created this grbl application for you.
+
+This file contains a summary of what you will find in each of the files that
+make up your grbl application.
+
+
+grbl.vcxproj
+ This is the main project file for VC++ projects generated using an Application Wizard.
+ It contains information about the version of Visual C++ that generated the file, and
+ information about the platforms, configurations, and project features selected with the
+ Application Wizard.
+
+grbl.vcxproj.filters
+ This is the filters file for VC++ projects generated using an Application Wizard.
+ It contains information about the association between the files in your project
+ and the filters. This association is used in the IDE to show grouping of files with
+ similar extensions under a specific node (for e.g. ".cpp" files are associated with the
+ "Source Files" filter).
+
+grbl.cpp
+ This is the main application source file.
+
+/////////////////////////////////////////////////////////////////////////////
+Other standard files:
+
+StdAfx.h, StdAfx.cpp
+ These files are used to build a precompiled header (PCH) file
+ named grbl.pch and a precompiled types file named StdAfx.obj.
+
+/////////////////////////////////////////////////////////////////////////////
+Other notes:
+
+AppWizard uses "TODO:" comments to indicate parts of the source code you
+should add to or customize.
+
+/////////////////////////////////////////////////////////////////////////////
diff --git a/grbl/grblwin/eeprom.bin b/grbl/grblwin/eeprom.bin
new file mode 100755
index 000000000..db3507188
Binary files /dev/null and b/grbl/grblwin/eeprom.bin differ
diff --git a/grbl/grblwin/grblmegawin.sdf b/grbl/grblwin/grblmegawin.sdf
new file mode 100755
index 000000000..d497e1ef3
Binary files /dev/null and b/grbl/grblwin/grblmegawin.sdf differ
diff --git a/grbl/grblwin/grblmegawin.sln b/grbl/grblwin/grblmegawin.sln
new file mode 100755
index 000000000..e866d2e75
--- /dev/null
+++ b/grbl/grblwin/grblmegawin.sln
@@ -0,0 +1,20 @@
+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "grblmegawin", "grblmegawin.vcxproj", "{8AA96864-9EFE-4D5C-BE3C-15B61047A8D9}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Win32 = Debug|Win32
+ Release|Win32 = Release|Win32
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {8AA96864-9EFE-4D5C-BE3C-15B61047A8D9}.Debug|Win32.ActiveCfg = Debug|Win32
+ {8AA96864-9EFE-4D5C-BE3C-15B61047A8D9}.Debug|Win32.Build.0 = Debug|Win32
+ {8AA96864-9EFE-4D5C-BE3C-15B61047A8D9}.Release|Win32.ActiveCfg = Release|Win32
+ {8AA96864-9EFE-4D5C-BE3C-15B61047A8D9}.Release|Win32.Build.0 = Release|Win32
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/grbl/grblwin/grblmegawin.suo b/grbl/grblwin/grblmegawin.suo
new file mode 100755
index 000000000..4dad98694
Binary files /dev/null and b/grbl/grblwin/grblmegawin.suo differ
diff --git a/grbl/grblwin/grblmegawin.vcxproj b/grbl/grblwin/grblmegawin.vcxproj
new file mode 100755
index 000000000..5353fea74
--- /dev/null
+++ b/grbl/grblwin/grblmegawin.vcxproj
@@ -0,0 +1,124 @@
+
+
+
+
+ Debug
+ Win32
+
+
+ Release
+ Win32
+
+
+
+ {8AA96864-9EFE-4D5C-BE3C-15B61047A8D9}
+ Win32Proj
+ grbl
+
+
+
+ Application
+ true
+ Unicode
+
+
+ Application
+ false
+ true
+ Unicode
+
+
+
+
+
+
+
+
+
+
+
+
+ true
+ j:\buildoutput\grblmega\Debug\
+ $(OutDir)\
+
+
+ false
+ j:\buildoutput\grblmegawin\Release\
+ $(OutDir)\
+
+
+
+ NotUsing
+ Level3
+ Disabled
+ WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
+
+
+ Console
+ true
+
+
+
+
+ Level3
+ NotUsing
+ MaxSpeed
+ true
+ true
+ WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
+
+
+ Console
+ true
+ true
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/grbl/grblwin/grblmegawin.vcxproj.user b/grbl/grblwin/grblmegawin.vcxproj.user
new file mode 100755
index 000000000..ea95f2784
--- /dev/null
+++ b/grbl/grblwin/grblmegawin.vcxproj.user
@@ -0,0 +1,7 @@
+
+
+
+ COM4
+ WindowsLocalDebugger
+
+
\ No newline at end of file
diff --git a/grbl/grblwin/ipch/grblmegawin-33d77f06/grblmegawin-4038fdb1.ipch b/grbl/grblwin/ipch/grblmegawin-33d77f06/grblmegawin-4038fdb1.ipch
new file mode 100755
index 000000000..7c1ec9524
Binary files /dev/null and b/grbl/grblwin/ipch/grblmegawin-33d77f06/grblmegawin-4038fdb1.ipch differ
diff --git a/grbl/limits.c b/grbl/limits.c
index 9a8e1d96a..fde07caab 100644
--- a/grbl/limits.c
+++ b/grbl/limits.c
@@ -1,214 +1,290 @@
-/*
- limits.c - code pertaining to limit-switches and performing the homing cycle
- Part of Grbl
-
- Copyright (c) 2012-2015 Sungeun K. Jeon
- Copyright (c) 2009-2011 Simen Svale Skogsrud
-
- Grbl is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Grbl is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with Grbl. If not, see .
-*/
-
-#include "grbl.h"
-
-
-// Homing axis search distance multiplier. Computed by this value times the cycle travel.
-#ifndef HOMING_AXIS_SEARCH_SCALAR
- #define HOMING_AXIS_SEARCH_SCALAR 1.5 // Must be > 1 to ensure limit switch will be engaged.
-#endif
-#ifndef HOMING_AXIS_LOCATE_SCALAR
- #define HOMING_AXIS_LOCATE_SCALAR 5.0 // Must be > 1 to ensure limit switch is cleared.
-#endif
-
-void limits_init()
-{
- LIMIT_DDR &= ~(LIMIT_MASK); // Set as input pins
-
- #ifdef DISABLE_LIMIT_PIN_PULL_UP
- LIMIT_PORT &= ~(LIMIT_MASK); // Normal low operation. Requires external pull-down.
- #else
- LIMIT_PORT |= (LIMIT_MASK); // Enable internal pull-up resistors. Normal high operation.
- #endif
-
- if (bit_istrue(settings.flags,BITFLAG_HARD_LIMIT_ENABLE)) {
- LIMIT_PCMSK |= LIMIT_MASK; // Enable specific pins of the Pin Change Interrupt
- PCICR |= (1 << LIMIT_INT); // Enable Pin Change Interrupt
- } else {
- limits_disable();
- }
-
- #ifdef ENABLE_SOFTWARE_DEBOUNCE
- MCUSR &= ~(1<.
+*/
+
+#include "grbl.h"
+
+// Homing axis search distance multiplier. Computed by this value times the cycle travel.
+#ifndef HOMING_AXIS_SEARCH_SCALAR
+ #define HOMING_AXIS_SEARCH_SCALAR 1.5 // Must be > 1 to ensure limit switch will be engaged.
+#endif
+#ifndef HOMING_AXIS_LOCATE_SCALAR
+ #define HOMING_AXIS_LOCATE_SCALAR 5.0 // Must be > 1 to ensure limit switch is cleared.
+#endif
+
+void limits_init()
+{
+#ifdef AVRTARGET
+ LIMIT_DDR &= ~(LIMIT_MASK); // Set as input pins
+
+ #ifdef DISABLE_LIMIT_PIN_PULL_UP
+ LIMIT_PORT &= ~(LIMIT_MASK); // Normal low operation. Requires external pull-down.
+ #else
+ LIMIT_PORT |= (LIMIT_MASK); // Enable internal pull-up resistors. Normal high operation.
+ #endif
+
+ if (bit_istrue(settings.flags,BITFLAG_HARD_LIMIT_ENABLE)) {
+ LIMIT_PCMSK |= LIMIT_MASK; // Enable specific pins of the Pin Change Interrupt
+ PCICR |= (1 << LIMIT_INT); // Enable Pin Change Interrupt
+ } else {
+ limits_disable();
+ }
+
+ #ifdef ENABLE_SOFTWARE_DEBOUNCE
+ MCUSR &= ~(1< 0);
-
- // The active cycle axes should now be homed and machine limits have been located. By
- // default, Grbl defines machine space as all negative, as do most CNCs. Since limit switches
- // can be on either side of an axes, check and set axes machine zero appropriately. Also,
- // set up pull-off maneuver from axes limit switches that have been homed. This provides
- // some initial clearance off the switches and should also help prevent them from falsely
- // triggering when hard limits are enabled or when more than one axes shares a limit pin.
- #ifdef COREXY
- int32_t off_axis_position = 0;
- #endif
- int32_t set_axis_position;
- // Set machine positions for homed limit switches. Don't update non-homed axes.
- for (idx=0; idx 0);
+
+ // The active cycle axes should now be homed and machine limits have been located. By
+ // default, Grbl defines machine space as all negative, as do most CNCs. Since limit switches
+ // can be on either side of an axes, check and set axes machine zero appropriately. Also,
+ // set up pull-off maneuver from axes limit switches that have been homed. This provides
+ // some initial clearance off the switches and should also help prevent them from falsely
+ // triggering when hard limits are enabled or when more than one axes shares a limit pin.
+ #ifdef COREXY
+ int32_t off_axis_position = 0;
+ #endif
+ // Set machine positions for homed limit switches. Don't update non-homed axes.
+ for (idx=0; idx -settings.max_travel[idx]) { sys.soft_limit = true; }
} else {
if (target[idx] > 0 || target[idx] < settings.max_travel[idx]) { sys.soft_limit = true; }
- }
- #else
- // NOTE: max_travel is stored as negative
+ }
+ #else
+ // NOTE: max_travel is stored as negative
if (target[idx] > 0 || target[idx] < settings.max_travel[idx]) { sys.soft_limit = true; }
- #endif
-
+ #endif
+
if (sys.soft_limit) {
- // Force feed hold if cycle is active. All buffered blocks are guaranteed to be within
- // workspace volume so just come to a controlled stop so position is not lost. When complete
- // enter alarm mode.
- if (sys.state == STATE_CYCLE) {
- system_set_exec_state_flag(EXEC_FEED_HOLD);
- do {
- protocol_execute_realtime();
- if (sys.abort) { return; }
- } while ( sys.state != STATE_IDLE );
- }
-
- mc_reset(); // Issue system reset and ensure spindle and coolant are shutdown.
+ // Force feed hold if cycle is active. All buffered blocks are guaranteed to be within
+ // workspace volume so just come to a controlled stop so position is not lost. When complete
+ // enter alarm mode.
+ if (sys.state == STATE_CYCLE) {
+ system_set_exec_state_flag(EXEC_FEED_HOLD);
+ do {
+ protocol_execute_realtime();
+ if (sys.abort) { return; }
+ } while ( sys.state != STATE_IDLE );
+ }
+
+ mc_reset(); // Issue system reset and ensure spindle and coolant are shutdown.
system_set_exec_alarm_flag((EXEC_ALARM_SOFT_LIMIT|EXEC_CRITICAL_EVENT)); // Indicate soft limit critical event
- protocol_execute_realtime(); // Execute to enter critical event loop and system abort
- return;
- }
- }
-}
+ protocol_execute_realtime(); // Execute to enter critical event loop and system abort
+ return;
+ }
+ }
+}
diff --git a/grbl/main.c b/grbl/main.c
index add314946..1aae868c1 100644
--- a/grbl/main.c
+++ b/grbl/main.c
@@ -1,91 +1,102 @@
-/*
- main.c - An embedded CNC Controller with rs274/ngc (g-code) support
- Part of Grbl
-
- Copyright (c) 2011-2015 Sungeun K. Jeon
- Copyright (c) 2009-2011 Simen Svale Skogsrud
-
- Grbl is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Grbl is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with Grbl. If not, see .
-*/
-
-#include "grbl.h"
-
-
-// Declare system global variable structure
-system_t sys;
-
-
-int main(void)
-{
- // Initialize system upon power-up.
- serial_init(); // Setup serial baud rate and interrupts
- settings_init(); // Load Grbl settings from EEPROM
- stepper_init(); // Configure stepper pins and interrupt timers
- system_init(); // Configure pinout pins and pin-change interrupt
-
- memset(&sys, 0, sizeof(system_t)); // Clear all system variables
- sys.abort = true; // Set abort to complete initialization
- sei(); // Enable interrupts
-
- // Check for power-up and set system alarm if homing is enabled to force homing cycle
- // by setting Grbl's alarm state. Alarm locks out all g-code commands, including the
- // startup scripts, but allows access to settings and internal commands. Only a homing
- // cycle '$H' or kill alarm locks '$X' will disable the alarm.
- // NOTE: The startup script will run after successful completion of the homing cycle, but
- // not after disabling the alarm locks. Prevents motion startup blocks from crashing into
- // things uncontrollably. Very bad.
- #ifdef HOMING_INIT_LOCK
- if (bit_istrue(settings.flags,BITFLAG_HOMING_ENABLE)) { sys.state = STATE_ALARM; }
- #endif
-
- // Force Grbl into an ALARM state upon a power-cycle or hard reset.
- #ifdef FORCE_INITIALIZATION_ALARM
- sys.state = STATE_ALARM;
- #endif
-
- // Grbl initialization loop upon power-up or a system abort. For the latter, all processes
- // will return to this loop to be cleanly re-initialized.
- for(;;) {
-
- // TODO: Separate configure task that require interrupts to be disabled, especially upon
- // a system abort and ensuring any active interrupts are cleanly reset.
-
- // Reset Grbl primary systems.
- serial_reset_read_buffer(); // Clear serial read buffer
- gc_init(); // Set g-code parser to default state
- spindle_init();
- coolant_init();
- limits_init();
- probe_init();
- sleep_init();
- plan_reset(); // Clear block buffer and planner variables
- st_reset(); // Clear stepper subsystem variables.
-
- // Sync cleared gcode and planner positions to current system position.
- plan_sync_position();
- gc_sync_position();
-
- // Reset system variables.
- sys.abort = false;
- sys_rt_exec_state = 0;
- sys_rt_exec_alarm = 0;
- sys.suspend = false;
- sys.soft_limit = false;
-
- // Start Grbl main loop. Processes program inputs and executes them.
- protocol_main_loop();
-
- }
- return 0; /* Never reached */
-}
+/*
+ main.c - An embedded CNC Controller with rs274/ngc (g-code) support
+ Part of Grbl
+
+ Copyright (c) 2011-2015 Sungeun K. Jeon
+ Copyright (c) 2009-2011 Simen Svale Skogsrud
+
+ Grbl is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Grbl is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with Grbl. If not, see .
+*/
+
+#include "grbl.h"
+
+
+// Declare system global variable structure
+system_t sys;
+
+#ifdef WIN32
+int main(int argc, char *argv[])
+#else
+int main(void)
+#endif
+{
+ // Initialize system upon power-up.
+#ifdef WIN32
+ winserial_init(argv[1]);
+#ifndef NOEEPROMSUPPORT
+ eeprom_init();
+#endif
+#endif
+ serial_init(); // Setup serial baud rate and interrupts
+ settings_init(); // Load Grbl settings from EEPROM
+ stepper_init(); // Configure stepper pins and interrupt timers
+ system_init(); // Configure pinout pins and pin-change interrupt
+
+ memset(&sys, 0, sizeof(system_t)); // Clear all system variables
+ sys.abort = true; // Set abort to complete initialization
+#ifdef AVRTARGET
+ sei(); // Enable interrupts
+#endif
+
+ // Check for power-up and set system alarm if homing is enabled to force homing cycle
+ // by setting Grbl's alarm state. Alarm locks out all g-code commands, including the
+ // startup scripts, but allows access to settings and internal commands. Only a homing
+ // cycle '$H' or kill alarm locks '$X' will disable the alarm.
+ // NOTE: The startup script will run after successful completion of the homing cycle, but
+ // not after disabling the alarm locks. Prevents motion startup blocks from crashing into
+ // things uncontrollably. Very bad.
+ #ifdef HOMING_INIT_LOCK
+ if (bit_istrue(settings.flags,BITFLAG_HOMING_ENABLE)) { sys.state = STATE_ALARM; }
+ #endif
+
+ // Force Grbl into an ALARM state upon a power-cycle or hard reset.
+ #ifdef FORCE_INITIALIZATION_ALARM
+ sys.state = STATE_ALARM;
+ #endif
+
+ // Grbl initialization loop upon power-up or a system abort. For the latter, all processes
+ // will return to this loop to be cleanly re-initialized.
+ for(;;) {
+
+ // TODO: Separate configure task that require interrupts to be disabled, especially upon
+ // a system abort and ensuring any active interrupts are cleanly reset.
+
+ // Reset Grbl primary systems.
+ serial_reset_read_buffer(); // Clear serial read buffer
+ gc_init(); // Set g-code parser to default state
+ spindle_init();
+ coolant_init();
+ limits_init();
+ probe_init();
+ sleep_init();
+ plan_reset(); // Clear block buffer and planner variables
+ st_reset(); // Clear stepper subsystem variables.
+
+ // Sync cleared gcode and planner positions to current system position.
+ plan_sync_position();
+ gc_sync_position();
+
+ // Reset system variables.
+ sys.abort = false;
+ sys_rt_exec_state = 0;
+ sys_rt_exec_alarm = 0;
+ sys.suspend = false;
+ sys.soft_limit = false;
+
+ // Start Grbl main loop. Processes program inputs and executes them.
+ protocol_main_loop();
+
+ }
+ return 0; /* Never reached */
+}
diff --git a/grbl/motion_control.c b/grbl/motion_control.c
index 1cf22f5a8..bb6fadea5 100644
--- a/grbl/motion_control.c
+++ b/grbl/motion_control.c
@@ -86,7 +86,18 @@ void mc_arc(float *position, float *target, float *offset, float radius, float f
float rt_axis1 = target[axis_1] - center_axis1;
// CCW angle between position and target from circle center. Only one atan2() trig computation required.
- float angular_travel = atan2(r_axis0*rt_axis1-r_axis1*rt_axis0, r_axis0*rt_axis0+r_axis1*rt_axis1);
+ float angular_travel = (float)atan2(r_axis0*rt_axis1-r_axis1*rt_axis0, r_axis0*rt_axis0+r_axis1*rt_axis1);
+ uint16_t segments;
+ float theta_per_segment;
+ float linear_per_segment;
+ float cos_T;
+ float sin_T;
+ float sin_Ti;
+ float cos_Ti;
+ float r_axisi;
+ uint16_t i;
+ uint8_t count = 0;
+
if (is_clockwise_arc) { // Correct atan2 output per direction
if (angular_travel >= -ARC_ANGULAR_TRAVEL_EPSILON) { angular_travel -= 2*M_PI; }
} else {
@@ -97,7 +108,7 @@ void mc_arc(float *position, float *target, float *offset, float radius, float f
// (2x) settings.arc_tolerance. For 99% of users, this is just fine. If a different arc segment fit
// is desired, i.e. least-squares, midpoint on arc, just change the mm_per_arc_segment calculation.
// For the intended uses of Grbl, this value shouldn't exceed 2000 for the strictest of cases.
- uint16_t segments = floor(fabs(0.5*angular_travel*radius)/
+ segments = (uint16_t)floor(fabs(0.5*angular_travel*radius)/
sqrt(settings.arc_tolerance*(2*radius - settings.arc_tolerance)) );
if (segments) {
@@ -106,8 +117,8 @@ void mc_arc(float *position, float *target, float *offset, float radius, float f
// all segments.
if (invert_feed_rate) { feed_rate *= segments; }
- float theta_per_segment = angular_travel/segments;
- float linear_per_segment = (target[axis_linear] - position[axis_linear])/segments;
+ theta_per_segment = angular_travel/segments;
+ linear_per_segment = (target[axis_linear] - position[axis_linear])/segments;
/* Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
and phi is the angle of rotation. Solution approach by Jens Geisler.
@@ -135,15 +146,11 @@ void mc_arc(float *position, float *target, float *offset, float radius, float f
This is important when there are successive arc motions.
*/
// Computes: cos_T = 1 - theta_per_segment^2/2, sin_T = theta_per_segment - theta_per_segment^3/6) in ~52usec
- float cos_T = 2.0 - theta_per_segment*theta_per_segment;
- float sin_T = theta_per_segment*0.16666667*(cos_T + 4.0);
- cos_T *= 0.5;
+ cos_T = (float)(2.0 - theta_per_segment*theta_per_segment);
+ sin_T = (float)(theta_per_segment*0.16666667*(cos_T + 4.0));
+ cos_T *= (float)0.5;
- float sin_Ti;
- float cos_Ti;
- float r_axisi;
- uint16_t i;
- uint8_t count = 0;
+ count = 0;
for (i = 1; i 0) {
do {
fval *= 10.0;
@@ -125,7 +124,6 @@ void delay_sec(float seconds, uint8_t mode)
}
}
-
// Delays variable defined milliseconds. Compiler compatibility fix for _delay_ms(),
// which only accepts constants in future compiler releases.
void delay_ms(uint16_t ms)
@@ -134,28 +132,6 @@ void delay_ms(uint16_t ms)
}
-// Delays variable defined microseconds. Compiler compatibility fix for _delay_us(),
-// which only accepts constants in future compiler releases. Written to perform more
-// efficiently with larger delays, as the counter adds parasitic time in each iteration.
-void delay_us(uint32_t us)
-{
- while (us) {
- if (us < 10) {
- _delay_us(1);
- us--;
- } else if (us < 100) {
- _delay_us(10);
- us -= 10;
- } else if (us < 1000) {
- _delay_us(100);
- us -= 100;
- } else {
- _delay_ms(1);
- us -= 1000;
- }
- }
-}
-
// Simple hypotenuse computation function.
-float hypot_f(float x, float y) { return(sqrt(x*x + y*y)); }
+float hypot_f(float x, float y) { return((float)sqrt(x*x + y*y)); }
diff --git a/grbl/nuts_bolts.h b/grbl/nuts_bolts.h
index 7611aac3a..6fe0c0b0b 100644
--- a/grbl/nuts_bolts.h
+++ b/grbl/nuts_bolts.h
@@ -21,7 +21,9 @@
#ifndef nuts_bolts_h
#define nuts_bolts_h
-
+#ifdef STM32F103C8
+#include "stm32f10x_rcc.h"
+#endif
#define false 0
#define true 1
@@ -43,19 +45,26 @@
#define MM_PER_INCH (25.40)
#define INCH_PER_MM (0.0393701)
#define TICKS_PER_MICROSECOND (F_CPU/1000000)
+#ifdef WIN32
+#define F_CPU Win32Frequency.QuadPart
+#endif
+
+#ifdef STM32F103C8
+#define F_CPU SystemCoreClock
+#endif
#define DELAY_MODE_DWELL 0
#define DELAY_MODE_SAFETY_DOOR 1
// Useful macros
#define clear_vector(a) memset(a, 0, sizeof(a))
-#define clear_vector_float(a) memset(a, 0.0, sizeof(float)*N_AXIS)
// #define clear_vector_long(a) memset(a, 0.0, sizeof(long)*N_AXIS)
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))
// Bit field and masking macros
#define bit(n) (1 << n)
+
#define bit_true(x,mask) (x) |= (mask)
#define bit_false(x,mask) (x) &= ~(mask)
#define bit_istrue(x,mask) ((x & mask) != 0)
diff --git a/grbl/planner.c b/grbl/planner.c
index 0bafd95e2..109426914 100644
--- a/grbl/planner.c
+++ b/grbl/planner.c
@@ -121,13 +121,15 @@ static uint8_t plan_prev_block_index(uint8_t block_index)
motion(s) distance per block to a desired tolerance. The more combined distance the planner has to use,
the faster it can go. (3) Maximize the planner buffer size. This also will increase the combined distance
for the planner to compute over. It also increases the number of computations the planner has to perform
- to compute an optimal plan, so select carefully.
-
+ to compute an optimal plan, so select carefully.
*/
static void planner_recalculate()
{
// Initialize block index to the last block in the planner buffer.
uint8_t block_index = plan_prev_block_index(block_buffer_head);
+ float entry_speed_sqr;
+ plan_block_t *next;
+ plan_block_t *current = &block_buffer[block_index];
// Bail. Can't do anything with one only one plan-able block.
if (block_index == block_buffer_planned) { return; }
@@ -135,9 +137,6 @@ static void planner_recalculate()
// Reverse Pass: Coarsely maximize all possible deceleration curves back-planning from the last
// block in buffer. Cease planning when the last optimal planned or tail pointer is reached.
// NOTE: Forward pass will later refine and correct the reverse pass to create an optimal plan.
- float entry_speed_sqr;
- plan_block_t *next;
- plan_block_t *current = &block_buffer[block_index];
// Calculate maximum entry speed for last block in buffer, where the exit speed is always zero.
current->entry_speed_sqr = min( current->max_entry_speed_sqr, 2*current->acceleration*current->millimeters);
@@ -217,13 +216,11 @@ void plan_discard_current_block()
}
}
-
plan_block_t *plan_get_parking_block()
{
return(&block_buffer[block_buffer_head]);
}
-
plan_block_t *plan_get_current_block()
{
if (block_buffer_head == block_buffer_tail) { return(NULL); } // Buffer empty
@@ -235,7 +232,7 @@ float plan_get_exec_block_exit_speed()
{
uint8_t block_index = plan_next_block_index(block_buffer_tail);
if (block_index == block_buffer_head) { return( 0.0 ); }
- return( sqrt( block_buffer[block_index].entry_speed_sqr ) );
+ return( (float)sqrt( block_buffer[block_index].entry_speed_sqr ) );
}
@@ -263,23 +260,28 @@ uint8_t plan_check_full_buffer()
to execute the parking motion. */
uint8_t plan_buffer_line(float *target, float feed_rate, uint8_t invert_feed_rate, uint8_t is_parking_motion, int32_t line_number)
{
+ int32_t target_steps[N_AXIS], position_steps[N_AXIS];
+ float unit_vec[N_AXIS], delta_mm;
+ uint8_t idx;
+
// Prepare and initialize new block
plan_block_t *block = &block_buffer[block_buffer_head];
+ float inverse_millimeters;
+ float junction_vec[N_AXIS];
+ float junction_cos_theta = 0.0;
+ float magnitude_junction_vec = 0.0;
+
block->step_event_count = 0;
block->millimeters = 0;
block->direction_bits = 0;
- block->acceleration = SOME_LARGE_VALUE; // Scaled down to maximum acceleration later
+ block->acceleration = (float)SOME_LARGE_VALUE; // Scaled down to maximum acceleration later
block->line_number = line_number;
- // Compute and store initial move distance data.
- int32_t target_steps[N_AXIS], position_steps[N_AXIS];
- float unit_vec[N_AXIS], delta_mm;
- uint8_t idx;
// Copy position data based on type of motion being planned.
if (is_parking_motion) { memcpy(position_steps, sys.position, sizeof(sys.position)); }
else { memcpy(position_steps, pl.position, sizeof(pl.position)); }
-
+
#ifdef COREXY
target_steps[A_MOTOR] = lround(target[A_MOTOR]*settings.steps_per_mm[A_MOTOR]);
target_steps[B_MOTOR] = lround(target[B_MOTOR]*settings.steps_per_mm[B_MOTOR]);
@@ -309,7 +311,7 @@ uint8_t plan_buffer_line(float *target, float feed_rate, uint8_t invert_feed_rat
block->steps[idx] = labs(target_steps[idx]-position_steps[idx]);
block->step_event_count = max(block->step_event_count, block->steps[idx]);
delta_mm = (target_steps[idx] - position_steps[idx])/settings.steps_per_mm[idx];
- #endif
+ #endif
unit_vec[idx] = delta_mm; // Store unit vector numerator. Denominator computed later.
// Set direction bits. Bit enabled always means direction is negative.
@@ -318,24 +320,21 @@ uint8_t plan_buffer_line(float *target, float feed_rate, uint8_t invert_feed_rat
// Incrementally compute total move distance by Euclidean norm. First add square of each term.
block->millimeters += delta_mm*delta_mm;
}
- block->millimeters = sqrt(block->millimeters); // Complete millimeters calculation with sqrt()
+ block->millimeters = (float)sqrt(block->millimeters); // Complete millimeters calculation with sqrt()
// Bail if this is a zero-length block. Highly unlikely to occur.
if (block->step_event_count == 0) { return(PLAN_EMPTY_BLOCK); }
// Adjust feed_rate value to mm/min depending on type of rate input (normal, inverse time, or rapids)
- if (feed_rate < 0) { feed_rate = SOME_LARGE_VALUE; } // Scaled down to absolute max/rapids rate later
+ if (feed_rate < 0) { feed_rate = (float)SOME_LARGE_VALUE; } // Scaled down to absolute max/rapids rate later
else if (invert_feed_rate) { feed_rate *= block->millimeters; }
if (feed_rate < MINIMUM_FEED_RATE) { feed_rate = MINIMUM_FEED_RATE; } // Prevents step generation round-off condition.
+ inverse_millimeters = (float)(1.0/block->millimeters); // Inverse millimeters to remove multiple float divides
// Calculate the unit vector of the line move and the block maximum feed rate and acceleration scaled
// down such that no individual axes maximum values are exceeded with respect to the line direction.
// NOTE: This calculation assumes all axes are orthogonal (Cartesian) and works with ABC-axes,
// if they are also orthogonal/independent. Operates on the absolute value of the unit vector.
- float junction_vec[N_AXIS];
- float inverse_millimeters = 1.0/block->millimeters; // Inverse millimeters to remove multiple float divides
- float junction_cos_theta = 0.0;
- float magnitude_junction_vec = 0.0;
for (idx=0; idxacceleration = min(block->acceleration,fabs(settings.acceleration[idx]/unit_vec[idx]));
feed_rate = min(feed_rate,fabs(settings.max_rate[idx]/unit_vec[idx]));
-
// Incrementally compute cosine of angle between previous and current path. Cos(theta) of the junction
// between the current move and the previous move is simply the dot product of the two unit vectors,
// where prev_unit_vec is negative. Used later to compute maximum junction speed.
@@ -353,15 +351,12 @@ uint8_t plan_buffer_line(float *target, float feed_rate, uint8_t invert_feed_rat
junction_vec[idx] = unit_vec[idx]-pl.previous_unit_vec[idx];
magnitude_junction_vec += junction_vec[idx]*junction_vec[idx];
}
-
// TODO: Need to check this method handling zero junction speeds when starting from rest.
if ((block_buffer_head == block_buffer_tail) || is_parking_motion) {
-
// Initialize block entry speed as zero. Assume it will be starting from rest. Planner will correct this later.
// If parking motion, the parking block always is assumed to start from rest and end at a complete stop.
block->entry_speed_sqr = 0.0;
block->max_junction_speed_sqr = 0.0; // Starting from rest. Enforce start from zero velocity.
-
} else {
/*
Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
@@ -380,13 +375,11 @@ uint8_t plan_buffer_line(float *target, float feed_rate, uint8_t invert_feed_rat
is exactly the same. Instead of motioning all the way to junction point, the machine will
just follow the arc circle defined here. The Arduino doesn't have the CPU cycles to perform
a continuous mode path, but ARM-based microcontrollers most certainly do.
-
NOTE: The max junction speed is a fixed value, since machine acceleration limits cannot be
changed dynamically during operation nor can the line move geometry. This must be kept in
memory in the event of a feedrate override changing the nominal speeds of blocks, which can
change the overall maximum entry speed conditions of all blocks.
*/
-
// NOTE: Computed without any expensive trig, sin() or acos(), by trig half angle identity of cos(theta).
if (junction_cos_theta > 0.999999) {
// For a 0 degree acute junction, just set minimum junction speed.
@@ -397,6 +390,7 @@ uint8_t plan_buffer_line(float *target, float feed_rate, uint8_t invert_feed_rat
block->max_junction_speed_sqr = SOME_LARGE_VALUE;
} else {
float junction_acceleration = SOME_LARGE_VALUE;
+ float sin_theta_d2;
magnitude_junction_vec = sqrt(magnitude_junction_vec); // Complete magnitude calculation.
for (idx=0; idxmax_junction_speed_sqr = max( MINIMUM_JUNCTION_SPEED*MINIMUM_JUNCTION_SPEED,
(junction_acceleration * settings.junction_deviation * sin_theta_d2)/(1.0-sin_theta_d2) );
}
}
}
-
// Store block nominal speed
block->nominal_speed_sqr = feed_rate*feed_rate; // (mm/min). Always > 0
diff --git a/grbl/planner.h b/grbl/planner.h
index 39806a3b3..2c040c60c 100644
--- a/grbl/planner.h
+++ b/grbl/planner.h
@@ -25,7 +25,7 @@
// The number of linear motions that can be in the plan at any give time
#ifndef BLOCK_BUFFER_SIZE
- #define BLOCK_BUFFER_SIZE 36
+ #define BLOCK_BUFFER_SIZE 36
#endif
#define PLAN_OK true
diff --git a/grbl/print.c b/grbl/print.c
index 86c82460f..1b35ff687 100644
--- a/grbl/print.c
+++ b/grbl/print.c
@@ -1,205 +1,215 @@
-/*
- print.c - Functions for formatting output strings
- Part of Grbl
-
- Copyright (c) 2011-2015 Sungeun K. Jeon
- Copyright (c) 2009-2011 Simen Svale Skogsrud
-
- Grbl is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Grbl is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with Grbl. If not, see .
-*/
-
-#include "grbl.h"
-
-
-void printString(const char *s)
-{
- while (*s)
- serial_write(*s++);
-}
-
-
-// Print a string stored in PGM-memory
-void printPgmString(const char *s)
-{
- char c;
- while ((c = pgm_read_byte_near(s++)))
- serial_write(c);
-}
-
-
-// void printIntegerInBase(unsigned long n, unsigned long base)
-// {
-// unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars.
-// unsigned long i = 0;
-//
-// if (n == 0) {
-// serial_write('0');
-// return;
-// }
-//
-// while (n > 0) {
-// buf[i++] = n % base;
-// n /= base;
-// }
-//
-// for (; i > 0; i--)
-// serial_write(buf[i - 1] < 10 ?
-// '0' + buf[i - 1] :
-// 'A' + buf[i - 1] - 10);
-// }
-
-
-// Prints an uint8 variable with base and number of desired digits.
-void print_unsigned_int8(uint8_t n, uint8_t base, uint8_t digits)
-{
- unsigned char buf[digits];
- uint8_t i = 0;
-
- for (; i < digits; i++) {
- buf[i] = n % base ;
- n /= base;
- }
-
- for (; i > 0; i--)
- serial_write('0' + buf[i - 1]);
-}
-
-
-// Prints an uint8 variable in base 2.
-void print_uint8_base2(uint8_t n) {
- print_unsigned_int8(n,2,8);
-}
-
-
-// Prints an uint8 variable in base 10.
-void print_uint8_base10(uint8_t n)
-{
- uint8_t digits;
- if (n < 10) { digits = 1; }
- else if (n < 100) { digits = 2; }
- else { digits = 3; }
- print_unsigned_int8(n,10,digits);
-}
-
-
-void print_uint32_base10(uint32_t n)
-{
- if (n == 0) {
- serial_write('0');
- return;
- }
-
- unsigned char buf[10];
- uint8_t i = 0;
-
- while (n > 0) {
- buf[i++] = n % 10;
- n /= 10;
- }
-
- for (; i > 0; i--)
- serial_write('0' + buf[i-1]);
-}
-
-
-void printInteger(long n)
-{
- if (n < 0) {
- serial_write('-');
- print_uint32_base10(-n);
- } else {
- print_uint32_base10(n);
- }
-}
-
-
-// Convert float to string by immediately converting to a long integer, which contains
-// more digits than a float. Number of decimal places, which are tracked by a counter,
-// may be set by the user. The integer is then efficiently converted to a string.
-// NOTE: AVR '%' and '/' integer operations are very efficient. Bitshifting speed-up
-// techniques are actually just slightly slower. Found this out the hard way.
-void printFloat(float n, uint8_t decimal_places)
-{
- if (n < 0) {
- serial_write('-');
- n = -n;
- }
-
- uint8_t decimals = decimal_places;
- while (decimals >= 2) { // Quickly convert values expected to be E0 to E-4.
- n *= 100;
- decimals -= 2;
- }
- if (decimals) { n *= 10; }
- n += 0.5; // Add rounding factor. Ensures carryover through entire value.
-
- // Generate digits backwards and store in string.
- unsigned char buf[13];
- uint8_t i = 0;
- uint32_t a = (long)n;
- buf[decimal_places] = '.'; // Place decimal point, even if decimal places are zero.
- while(a > 0) {
- if (i == decimal_places) { i++; } // Skip decimal point location
- buf[i++] = (a % 10) + '0'; // Get digit
- a /= 10;
- }
- while (i < decimal_places) {
- buf[i++] = '0'; // Fill in zeros to decimal point for (n < 1)
- }
- if (i == decimal_places) { // Fill in leading zero, if needed.
- i++;
- buf[i++] = '0';
- }
-
- // Print the generated string.
- for (; i > 0; i--)
- serial_write(buf[i-1]);
-}
-
-
-// Floating value printing handlers for special variables types used in Grbl and are defined
-// in the config.h.
-// - CoordValue: Handles all position or coordinate values in inches or mm reporting.
-// - RateValue: Handles feed rate and current velocity in inches or mm reporting.
-// - SettingValue: Handles all floating point settings values (always in mm.)
-void printFloat_CoordValue(float n) {
- if (bit_istrue(settings.flags,BITFLAG_REPORT_INCHES)) {
- printFloat(n*INCH_PER_MM,N_DECIMAL_COORDVALUE_INCH);
- } else {
- printFloat(n,N_DECIMAL_COORDVALUE_MM);
- }
-}
-
-void printFloat_RateValue(float n) {
- if (bit_istrue(settings.flags,BITFLAG_REPORT_INCHES)) {
- printFloat(n*INCH_PER_MM,N_DECIMAL_RATEVALUE_INCH);
- } else {
- printFloat(n,N_DECIMAL_RATEVALUE_MM);
- }
-}
-
-void printFloat_SettingValue(float n) { printFloat(n,N_DECIMAL_SETTINGVALUE); }
-
+/*
+ print.c - Functions for formatting output strings
+ Part of Grbl
+
+ Copyright (c) 2011-2015 Sungeun K. Jeon
+ Copyright (c) 2009-2011 Simen Svale Skogsrud
+
+ Grbl is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Grbl is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with Grbl. If not, see .
+*/
+
+#include "grbl.h"
+
+
+void printString(const char *s)
+{
+ while (*s)
+ serial_write(*s++);
+}
+
+
+// Print a string stored in PGM-memory
+void printPgmString(const char *s)
+{
+ char c;
+ while ((c = pgm_read_byte_near(s++)))
+ serial_write(c);
+}
+
+
+// void printIntegerInBase(unsigned long n, unsigned long base)
+// {
+// unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars.
+// unsigned long i = 0;
+//
+// if (n == 0) {
+// serial_write('0');
+// return;
+// }
+//
+// while (n > 0) {
+// buf[i++] = n % base;
+// n /= base;
+// }
+//
+// for (; i > 0; i--)
+// serial_write(buf[i - 1] < 10 ?
+// '0' + buf[i - 1] :
+// 'A' + buf[i - 1] - 10);
+// }
+
+
+// Prints an uint8 variable with base and number of desired digits.
+void print_unsigned_int8(uint8_t n, uint8_t base, uint8_t digits)
+{
+#if defined(AVRTARGET) || defined(STM32F103C8)
+ unsigned char buf[digits];
+#endif
+#ifdef WIN32
+ unsigned char *buf = malloc(digits * sizeof(unsigned char));
+#endif
+
+ uint8_t i = 0;
+
+ for (; i < digits; i++) {
+ buf[i] = n % base ;
+ n /= base;
+ }
+
+ for (; i > 0; i--)
+ serial_write('0' + buf[i - 1]);
+#ifdef WIN32
+ free(buf);
+#endif
+}
+
+
+// Prints an uint8 variable in base 2.
+void print_uint8_base2(uint8_t n) {
+ print_unsigned_int8(n,2,8);
+}
+
+
+// Prints an uint8 variable in base 10.
+void print_uint8_base10(uint8_t n)
+{
+ uint8_t digits;
+ if (n < 10) { digits = 1; }
+ else if (n < 100) { digits = 2; }
+ else { digits = 3; }
+ print_unsigned_int8(n,10,digits);
+}
+
+
+void print_uint32_base10(uint32_t n)
+{
+ unsigned char buf[10];
+ uint8_t i = 0;
+ if (n == 0) {
+ serial_write('0');
+ return;
+ }
+
+
+ while (n > 0) {
+ buf[i++] = n % 10;
+ n /= 10;
+ }
+
+ for (; i > 0; i--)
+ serial_write('0' + buf[i-1]);
+}
+
+
+void printInteger(long n)
+{
+ if (n < 0) {
+ serial_write('-');
+ print_uint32_base10(-n);
+ } else {
+ print_uint32_base10(n);
+ }
+}
+
+
+// Convert float to string by immediately converting to a long integer, which contains
+// more digits than a float. Number of decimal places, which are tracked by a counter,
+// may be set by the user. The integer is then efficiently converted to a string.
+// NOTE: AVR '%' and '/' integer operations are very efficient. Bitshifting speed-up
+// techniques are actually just slightly slower. Found this out the hard way.
+void printFloat(float n, uint8_t decimal_places)
+{
+ uint8_t decimals = decimal_places;
+ unsigned char buf[13];
+ uint8_t i = 0;
+ uint32_t a;
+ if (n < 0) {
+ serial_write('-');
+ n = -n;
+ }
+
+ while (decimals >= 2) { // Quickly convert values expected to be E0 to E-4.
+ n *= 100;
+ decimals -= 2;
+ }
+ if (decimals) { n *= 10; }
+ n += 0.5; // Add rounding factor. Ensures carryover through entire value.
+
+ a = (long)n;
+ // Generate digits backwards and store in string.
+ buf[decimal_places] = '.'; // Place decimal point, even if decimal places are zero.
+ while(a > 0) {
+ if (i == decimal_places) { i++; } // Skip decimal point location
+ buf[i++] = (a % 10) + '0'; // Get digit
+ a /= 10;
+ }
+ while (i < decimal_places) {
+ buf[i++] = '0'; // Fill in zeros to decimal point for (n < 1)
+ }
+ if (i == decimal_places) { // Fill in leading zero, if needed.
+ i++;
+ buf[i++] = '0';
+ }
+
+ // Print the generated string.
+ for (; i > 0; i--)
+ serial_write(buf[i-1]);
+}
+
+
+// Floating value printing handlers for special variables types used in Grbl and are defined
+// in the config.h.
+// - CoordValue: Handles all position or coordinate values in inches or mm reporting.
+// - RateValue: Handles feed rate and current velocity in inches or mm reporting.
+// - SettingValue: Handles all floating point settings values (always in mm.)
+void printFloat_CoordValue(float n) {
+ if (bit_istrue(settings.flags,BITFLAG_REPORT_INCHES)) {
+ printFloat(n*(float)INCH_PER_MM,N_DECIMAL_COORDVALUE_INCH);
+ } else {
+ printFloat(n,N_DECIMAL_COORDVALUE_MM);
+ }
+}
+
+void printFloat_RateValue(float n) {
+ if (bit_istrue(settings.flags,BITFLAG_REPORT_INCHES)) {
+ printFloat(n*(float)INCH_PER_MM,N_DECIMAL_RATEVALUE_INCH);
+ } else {
+ printFloat(n,N_DECIMAL_RATEVALUE_MM);
+ }
+}
+
+void printFloat_SettingValue(float n) { printFloat(n,N_DECIMAL_SETTINGVALUE); }
+
void printFloat_RPMValue(float n) { printFloat(n,N_DECIMAL_RPMVALUE); }
-
-// Debug tool to print free memory in bytes at the called point.
-// NOTE: Keep commented unless using. Part of this function always gets compiled in.
-// void printFreeMemory()
-// {
-// extern int __heap_start, *__brkval;
-// uint16_t free; // Up to 64k values.
-// free = (int) &free - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
-// printInteger((int32_t)free);
-// printString(" ");
-// }
+
+// Debug tool to print free memory in bytes at the called point.
+// NOTE: Keep commented unless using. Part of this function always gets compiled in.
+// void printFreeMemory()
+// {
+// extern int __heap_start, *__brkval;
+// uint16_t free; // Up to 64k values.
+// free = (int) &free - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
+// printInteger((int32_t)free);
+// printString(" ");
+// }
diff --git a/grbl/print.h b/grbl/print.h
index b8cabde75..8453ae124 100644
--- a/grbl/print.h
+++ b/grbl/print.h
@@ -48,7 +48,9 @@ void printFloat(float n, uint8_t decimal_places);
// - SettingValue: Handles all floating point settings values (always in mm.)
// - RPMValue: Handles spindle RPM values in settings and reports.
void printFloat_CoordValue(float n);
+
void printFloat_RateValue(float n);
+
void printFloat_SettingValue(float n);
void printFloat_RPMValue(float n);
diff --git a/grbl/probe.c b/grbl/probe.c
index 5a3377742..1462ee5fb 100644
--- a/grbl/probe.c
+++ b/grbl/probe.c
@@ -1,68 +1,93 @@
-/*
- probe.c - code pertaining to probing methods
- Part of Grbl
-
- Copyright (c) 2014-2015 Sungeun K. Jeon
-
- Grbl is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Grbl is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with Grbl. If not, see .
-*/
-
-#include "grbl.h"
-
-
-// Inverts the probe pin state depending on user settings and probing cycle mode.
-uint8_t probe_invert_mask;
-
-
-// Probe pin initialization routine.
-void probe_init()
-{
- PROBE_DDR &= ~(PROBE_MASK); // Configure as input pins
- #ifdef DISABLE_PROBE_PIN_PULL_UP
- PROBE_PORT &= ~(PROBE_MASK); // Normal low operation. Requires external pull-down.
- #else
- PROBE_PORT |= PROBE_MASK; // Enable internal pull-up resistors. Normal high operation.
- #endif
- probe_configure_invert_mask(false); // Initialize invert mask. Re-updated during use.
-}
-
-
-// Called by probe_init() and the mc_probe() routines. Sets up the probe pin invert mask to
-// appropriately set the pin logic according to setting for normal-high/normal-low operation
-// and the probing cycle modes for toward-workpiece/away-from-workpiece.
-void probe_configure_invert_mask(uint8_t is_probe_away)
-{
- probe_invert_mask = 0; // Initialize as zero.
- if (bit_isfalse(settings.flags,BITFLAG_INVERT_PROBE_PIN)) { probe_invert_mask ^= PROBE_MASK; }
- if (is_probe_away) { probe_invert_mask ^= PROBE_MASK; }
-}
-
-
-// Returns the probe pin state. Triggered = true. Called by gcode parser and probe state monitor.
-uint8_t probe_get_state() { return((PROBE_PIN & PROBE_MASK) ^ probe_invert_mask); }
-
-
-// Monitors probe pin state and records the system position when detected. Called by the
-// stepper ISR per ISR tick.
-// NOTE: This function must be extremely efficient as to not bog down the stepper ISR.
-void probe_state_monitor()
-{
- if (sys_probe_state == PROBE_ACTIVE) {
- if (probe_get_state()) {
- sys_probe_state = PROBE_OFF;
- memcpy(sys.probe_position, sys.position, sizeof(sys.position));
- bit_true(sys_rt_exec_state, EXEC_MOTION_CANCEL);
- }
- }
-}
+/*
+ probe.c - code pertaining to probing methods
+ Part of Grbl
+
+ Copyright (c) 2014-2015 Sungeun K. Jeon
+
+ Grbl is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Grbl is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with Grbl. If not, see .
+*/
+
+#include "grbl.h"
+
+
+// Inverts the probe pin state depending on user settings and probing cycle mode.
+uint8_t probe_invert_mask;
+
+
+// Probe pin initialization routine.
+void probe_init()
+{
+#ifdef AVRTARGET
+ PROBE_DDR &= ~(PROBE_MASK); // Configure as input pins
+ #ifdef DISABLE_PROBE_PIN_PULL_UP
+ PROBE_PORT &= ~(PROBE_MASK); // Normal low operation. Requires external pull-down.
+ #else
+ PROBE_PORT |= PROBE_MASK; // Enable internal pull-up resistors. Normal high operation.
+ #endif
+#endif
+#ifdef STM32F103C8
+ GPIO_InitTypeDef GPIO_InitStructure;
+ RCC_APB2PeriphClockCmd(RCC_PROBE_PORT, ENABLE);
+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
+#ifdef DISABLE_PROBE_PIN_PULL_UP
+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
+#else
+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
+#endif
+ GPIO_InitStructure.GPIO_Pin = PROBE_MASK;
+ GPIO_Init(PROBE_PORT, &GPIO_InitStructure);
+#endif
+ probe_configure_invert_mask(false); // Initialize invert mask. Not required. Updated when in-use.
+}
+
+
+// Called by probe_init() and the mc_probe() routines. Sets up the probe pin invert mask to
+// appropriately set the pin logic according to setting for normal-high/normal-low operation
+// and the probing cycle modes for toward-workpiece/away-from-workpiece.
+void probe_configure_invert_mask(uint8_t is_probe_away)
+{
+ probe_invert_mask = 0; // Initialize as zero.
+ if (bit_isfalse(settings.flags,BITFLAG_INVERT_PROBE_PIN)) { probe_invert_mask ^= PROBE_MASK; }
+ if (is_probe_away) { probe_invert_mask ^= PROBE_MASK; }
+}
+
+
+// Returns the probe pin state. Triggered = true. Called by gcode parser and probe state monitor.
+uint8_t probe_get_state()
+{
+#ifdef AVRTARGET
+ return((PROBE_PIN & PROBE_MASK) ^ probe_invert_mask);
+#endif
+#ifdef WIN32
+ return 0;
+#endif
+#ifdef STM32F103C8
+ return ((GPIO_ReadInputData(PROBE_PORT) & PROBE_MASK) ^ probe_invert_mask) != 0;
+#endif
+}
+
+
+// Monitors probe pin state and records the system position when detected. Called by the
+// stepper ISR per ISR tick.
+// NOTE: This function must be extremely efficient as to not bog down the stepper ISR.
+void probe_state_monitor()
+{
+ if (sys_probe_state == PROBE_ACTIVE) {
+ if (probe_get_state()) {
+ sys_probe_state = PROBE_OFF;
+ memcpy(sys.probe_position, sys.position, sizeof(sys.position));
+ bit_true(sys_rt_exec_state, EXEC_MOTION_CANCEL);
+ }
+ }
+}
diff --git a/grbl/protocol.c b/grbl/protocol.c
index a72983874..17f979a45 100644
--- a/grbl/protocol.c
+++ b/grbl/protocol.c
@@ -1,85 +1,92 @@
-/*
- protocol.c - controls Grbl execution protocol and procedures
- Part of Grbl
-
- Copyright (c) 2011-2015 Sungeun K. Jeon
- Copyright (c) 2009-2011 Simen Svale Skogsrud
-
- Grbl is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Grbl is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with Grbl. If not, see .
-*/
-
-#include "grbl.h"
-
+/*
+ protocol.c - controls Grbl execution protocol and procedures
+ Part of Grbl
+
+ Copyright (c) 2011-2015 Sungeun K. Jeon
+ Copyright (c) 2009-2011 Simen Svale Skogsrud
+
+ Grbl is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Grbl is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with Grbl. If not, see .
+*/
+
+#include "grbl.h"
+#ifdef WIN32
+#define WINLOG
+#include
+#endif
// Define line flags. Includes comment type tracking and line overflow detection.
#define LINE_FLAG_OVERFLOW bit(0)
#define LINE_FLAG_COMMENT_PARENTHESES bit(1)
#define LINE_FLAG_COMMENT_SEMICOLON bit(2)
-
-
-static char line[LINE_BUFFER_SIZE]; // Line to be executed. Zero-terminated.
-
-static void protocol_exec_rt_suspend();
-
-
-/*
- GRBL PRIMARY LOOP:
-*/
-void protocol_main_loop()
-{
- // ------------------------------------------------------------
- // Complete initialization procedures upon a power-up or reset.
- // ------------------------------------------------------------
-
- // Print welcome message
- report_init_message();
-
- // Check for and report alarm state after a reset, error, or an initial power up.
- if (sys.state == STATE_ALARM) {
- report_feedback_message(MESSAGE_ALARM_LOCK);
- } else {
- // All systems go! But first check for safety door.
- sys.state = STATE_IDLE;
- if (system_check_safety_door_ajar()) {
- bit_true(sys_rt_exec_state, EXEC_SAFETY_DOOR);
- protocol_execute_realtime(); // Enter safety door mode. Should return as IDLE state.
- }
- system_execute_startup(line); // Execute startup script.
- }
-
- // ---------------------------------------------------------------------------------
- // Primary loop! Upon a system abort, this exits back to main() to reset the system.
- // This is also where Grbl idles while waiting for something to do.
- // ---------------------------------------------------------------------------------
-
+
+
+char line[LINE_BUFFER_SIZE]; // Line to be executed. Zero-terminated.
+#ifdef LEDBLINK
+void LedBlink(void);
+#endif
+
+static void protocol_exec_rt_suspend();
+
+/*
+ GRBL PRIMARY LOOP:
+*/
+void protocol_main_loop()
+{
uint8_t line_flags = 0;
- uint8_t char_counter = 0;
- uint8_t c;
- for (;;) {
-
- // Process one line of incoming serial data, as the data becomes available. Performs an
+ uint8_t char_counter = 0;
+ uint8_t c;
+ // ------------------------------------------------------------
+ // Complete initialization procedures upon a power-up or reset.
+ // ------------------------------------------------------------
+
+ // Print welcome message
+ report_init_message();
+
+ // Check for and report alarm state after a reset, error, or an initial power up.
+ if (sys.state == STATE_ALARM) {
+ report_feedback_message(MESSAGE_ALARM_LOCK);
+ } else {
+ sys.state = STATE_IDLE;
+ // All systems go! But first check for safety door.
+ if (system_check_safety_door_ajar()) {
+ bit_true(sys_rt_exec_state, EXEC_SAFETY_DOOR);
+ protocol_execute_realtime(); // Enter safety door mode. Should return as IDLE state.
+ }
+ system_execute_startup(line); // Execute startup script.
+ }
+
+ // ---------------------------------------------------------------------------------
+ // Primary loop! Upon a system abort, this exits back to main() to reset the system.
+ // This is also where Grbl idles while waiting for something to do.
+ // ---------------------------------------------------------------------------------
+
+ for (;;) {
+
+ // Process one line of incoming serial data, as the data becomes available. Performs an
// initial filtering by removing spaces and comments and capitalizing all letters.
- while((c = serial_read()) != SERIAL_NO_DATA) {
- if ((c == '\n') || (c == '\r')) { // End of line reached
-
+
+ while((c = serial_read()) != SERIAL_NO_DATA) {
+ if ((c == '\n') || (c == '\r')) { // End of line reached
protocol_execute_realtime(); // Runtime command check point.
- if (sys.abort) { return; } // Bail to calling function upon system abort
-
- line[char_counter] = 0; // Set string termination character.
+ if (sys.abort) { return; } // Bail to calling function upon system abort
+ line[char_counter] = 0; // Set string termination character.
+#ifdef LEDBLINK
+ LedBlink();
+#endif
#ifdef REPORT_ECHO_LINE_RECEIVED
report_echo_line_received(line);
#endif
-
+
// Direct and execute one line of formatted input, and report status of execution.
if (line_flags & LINE_FLAG_OVERFLOW) {
// Report line overflow error.
@@ -100,69 +107,65 @@ void protocol_main_loop()
// Reset tracking data for next line.
line_flags = 0;
- char_counter = 0;
-
- } else {
-
+ char_counter = 0;
+ } else {
if (line_flags) {
// Throw away all (except EOL) comment characters and overflow characters.
if (c == ')') {
// End of '()' comment. Resume line allowed.
if (line_flags & LINE_FLAG_COMMENT_PARENTHESES) { line_flags &= ~(LINE_FLAG_COMMENT_PARENTHESES); }
- }
- } else {
- if (c <= ' ') {
- // Throw away whitepace and control characters
- } else if (c == '/') {
- // Block delete NOT SUPPORTED. Ignore character.
- // NOTE: If supported, would simply need to check the system if block delete is enabled.
- } else if (c == '(') {
- // Enable comments flag and ignore all characters until ')' or EOL.
- // NOTE: This doesn't follow the NIST definition exactly, but is good enough for now.
- // In the future, we could simply remove the items within the comments, but retain the
- // comment control characters, so that the g-code parser can error-check it.
+ }
+ } else {
+ if (c <= ' ') {
+ // Throw away whitepace and control characters
+ } else if (c == '/') {
+ // Block delete NOT SUPPORTED. Ignore character.
+ // NOTE: If supported, would simply need to check the system if block delete is enabled.
+ } else if (c == '(') {
+ // Enable comments flag and ignore all characters until ')' or EOL.
+ // NOTE: This doesn't follow the NIST definition exactly, but is good enough for now.
+ // In the future, we could simply remove the items within the comments, but retain the
+ // comment control characters, so that the g-code parser can error-check it.
line_flags |= LINE_FLAG_COMMENT_PARENTHESES;
- } else if (c == ';') {
- // NOTE: ';' comment to EOL is a LinuxCNC definition. Not NIST.
+ } else if (c == ';') {
+ // NOTE: ';' comment to EOL is a LinuxCNC definition. Not NIST.
line_flags |= LINE_FLAG_COMMENT_SEMICOLON;
- // TODO: Install '%' feature
- // } else if (c == '%') {
- // Program start-end percent sign NOT SUPPORTED.
- // NOTE: This maybe installed to tell Grbl when a program is running vs manual input,
- // where, during a program, the system auto-cycle start will continue to execute
- // everything until the next '%' sign. This will help fix resuming issues with certain
- // functions that empty the planner buffer to execute its task on-time.
+
+ // TODO: Install '%' feature
+ // } else if (c == '%') {
+ // Program start-end percent sign NOT SUPPORTED.
+ // NOTE: This maybe installed to tell Grbl when a program is running vs manual input,
+ // where, during a program, the system auto-cycle start will continue to execute
+ // everything until the next '%' sign. This will help fix resuming issues with certain
+ // functions that empty the planner buffer to execute its task on-time.
} else if (char_counter >= (LINE_BUFFER_SIZE-1)) {
// Detect line buffer overflow and set flag.
line_flags |= LINE_FLAG_OVERFLOW;
- } else if (c >= 'a' && c <= 'z') { // Upcase lowercase
- line[char_counter++] = c-'a'+'A';
- } else {
- line[char_counter++] = c;
- }
- }
-
- }
- }
-
- // If there are no more characters in the serial read buffer to be processed and executed,
- // this indicates that g-code streaming has either filled the planner buffer or has
- // completed. In either case, auto-cycle start, if enabled, any queued moves.
- protocol_auto_cycle_start();
-
- protocol_execute_realtime(); // Runtime command check point.
- if (sys.abort) { return; } // Bail to main() program loop to reset system.
-
+ } else if (c >= 'a' && c <= 'z') { // Upcase lowercase
+ line[char_counter++] = c-'a'+'A';
+ } else {
+ line[char_counter++] = c;
+ }
+ }
+ }
+ }
+
+ // If there are no more characters in the serial read buffer to be processed and executed,
+ // this indicates that g-code streaming has either filled the planner buffer or has
+ // completed. In either case, auto-cycle start, if enabled, any queued moves.
+ protocol_auto_cycle_start();
+
+ protocol_execute_realtime(); // Runtime command check point.
+ if (sys.abort) { return; } // Bail to main() program loop to reset system.
#ifdef SLEEP_ENABLE
// Check for sleep conditions and execute auto-park, if timeout duration elapses.
sleep_check();
#endif
- }
-
- return; /* Never reached */
-}
-
-
+ }
+
+ return; /* Never reached */
+}
+
// Block until all buffered steps are executed or in a cycle state. Works with feed hold
// during a synchronize call, if it should happen. Also, waits for clean cycle end.
void protocol_buffer_synchronize()
@@ -204,10 +207,10 @@ void protocol_auto_cycle_start()
// handles them, removing the need to define more computationally-expensive volatile variables. This
// also provides a controlled way to execute certain tasks without having two or more instances of
// the same task, such as the planner recalculating the buffer upon a feedhold or overrides.
-// NOTE: The sys_rt_exec_state variable flags are set by any process, step or serial interrupts, pinouts,
-// limit switches, or the main program.
-void protocol_execute_realtime()
-{
+// NOTE: The sys_rt_exec_state variable flags are set by any process, step or serial interrupts, pinouts,
+// limit switches, or the main program.
+void protocol_execute_realtime()
+{
protocol_exec_rt_system();
if (sys.suspend) { protocol_exec_rt_suspend(); }
}
@@ -219,27 +222,28 @@ void protocol_execute_realtime()
void protocol_exec_rt_system()
{
uint8_t rt_exec; // Temp variable to avoid calling volatile multiple times.
- rt_exec = sys_rt_exec_alarm; // Copy volatile sys_rt_exec_alarm.
- if (rt_exec) { // Enter only if any bit flag is true
- // System alarm. Everything has shutdown by something that has gone severely wrong. Report
- // the source of the error to the user. If critical, Grbl disables by entering an infinite
- // loop until system reset/abort.
- sys.state = STATE_ALARM; // Set system alarm state
- if (rt_exec & EXEC_ALARM_HARD_LIMIT) {
- report_alarm_message(ALARM_HARD_LIMIT_ERROR);
- } else if (rt_exec & EXEC_ALARM_SOFT_LIMIT) {
- report_alarm_message(ALARM_SOFT_LIMIT_ERROR);
- } else if (rt_exec & EXEC_ALARM_ABORT_CYCLE) {
- report_alarm_message(ALARM_ABORT_CYCLE);
- } else if (rt_exec & EXEC_ALARM_PROBE_FAIL) {
- report_alarm_message(ALARM_PROBE_FAIL);
- } else if (rt_exec & EXEC_ALARM_HOMING_FAIL) {
- report_alarm_message(ALARM_HOMING_FAIL);
- }
- // Halt everything upon a critical event flag. Currently hard and soft limits flag this.
- if (rt_exec & EXEC_CRITICAL_EVENT) {
- report_feedback_message(MESSAGE_CRITICAL_EVENT);
- system_clear_exec_state_flag(EXEC_RESET); // Disable any existing reset
+ // Check and execute alarms.
+ rt_exec = sys_rt_exec_alarm; // Copy volatile sys_rt_exec_alarm.
+ if (rt_exec) { // Enter only if any bit flag is true
+ // System alarm. Everything has shutdown by something that has gone severely wrong. Report
+ // the source of the error to the user. If critical, Grbl disables by entering an infinite
+ // loop until system reset/abort.
+ sys.state = STATE_ALARM; // Set system alarm state
+ if (rt_exec & EXEC_ALARM_HARD_LIMIT) {
+ report_alarm_message(ALARM_HARD_LIMIT_ERROR);
+ } else if (rt_exec & EXEC_ALARM_SOFT_LIMIT) {
+ report_alarm_message(ALARM_SOFT_LIMIT_ERROR);
+ } else if (rt_exec & EXEC_ALARM_ABORT_CYCLE) {
+ report_alarm_message(ALARM_ABORT_CYCLE);
+ } else if (rt_exec & EXEC_ALARM_PROBE_FAIL) {
+ report_alarm_message(ALARM_PROBE_FAIL);
+ } else if (rt_exec & EXEC_ALARM_HOMING_FAIL) {
+ report_alarm_message(ALARM_HOMING_FAIL);
+ }
+ // Halt everything upon a critical event flag. Currently hard and soft limits flag this.
+ if (rt_exec & EXEC_CRITICAL_EVENT) {
+ report_feedback_message(MESSAGE_CRITICAL_EVENT);
+ system_clear_exec_state_flag(EXEC_RESET); // Disable any existing reset
do {
// Block everything, except reset and status reports, until user issues reset or power
// cycles. Hard limits typically occur while unattended or not paying attention. Gives
@@ -256,65 +260,66 @@ void protocol_exec_rt_system()
} while (bit_isfalse(sys_rt_exec_state,EXEC_RESET));
}
system_clear_exec_alarm_flag(0xFF); // Clear all alarm flags
- }
-
- rt_exec = sys_rt_exec_state; // Copy volatile sys_rt_exec_state.
- if (rt_exec) {
-
- // Execute system abort.
- if (rt_exec & EXEC_RESET) {
- sys.abort = true; // Only place this is set true.
- return; // Nothing else to do but exit.
- }
-
- // Execute and serial print status
- if (rt_exec & EXEC_STATUS_REPORT) {
- report_realtime_status();
- system_clear_exec_state_flag(EXEC_STATUS_REPORT);
- }
-
- // NOTE: The math involved to calculate the hold should be low enough for most, if not all,
- // operational scenarios. Once hold is initiated, the system enters a suspend state to block
- // all main program processes until either reset or resumed.
+ }
+
+ rt_exec = sys_rt_exec_state; // Copy volatile sys_rt_exec_state.
+ if (rt_exec) {
+
+ // Execute system abort.
+ if (rt_exec & EXEC_RESET) {
+ sys.abort = true; // Only place this is set true.
+ return; // Nothing else to do but exit.
+ }
+
+ // Execute and serial print status
+ if (rt_exec & EXEC_STATUS_REPORT) {
+ report_realtime_status();
+ system_clear_exec_state_flag(EXEC_STATUS_REPORT);
+ }
+
+ // Execute hold states.
+ // NOTE: The math involved to calculate the hold should be low enough for most, if not all,
+ // operational scenarios. Once hold is initiated, the system enters a suspend state to block
+ // all main program processes until either reset or resumed.
if (rt_exec & (EXEC_MOTION_CANCEL | EXEC_FEED_HOLD | EXEC_SAFETY_DOOR | EXEC_SLEEP)) {
-
- // TODO: CHECK MODE? How to handle this? Likely nothing, since it only works when IDLE and then resets Grbl.
-
- // State check for allowable states for hold methods.
- if (!(sys.state & (STATE_ALARM | STATE_CHECK_MODE))) {
-
- // If in CYCLE state, all hold states immediately initiate a motion HOLD.
- if (sys.state == STATE_CYCLE) {
- st_update_plan_block_parameters(); // Notify stepper module to recompute for hold deceleration.
- sys.step_control = STEP_CONTROL_EXECUTE_HOLD; // Initiate suspend state with active flag.
- }
+
+ // TODO: CHECK MODE? How to handle this? Likely nothing, since it only works when IDLE and then resets Grbl.
+
+ // State check for allowable states for hold methods.
+ if (!(sys.state & (STATE_ALARM | STATE_CHECK_MODE))) {
+
+ // If in CYCLE state, all hold states immediately initiate a motion HOLD.
+ if (sys.state == STATE_CYCLE) {
+ st_update_plan_block_parameters(); // Notify stepper module to recompute for hold deceleration.
+ sys.step_control = STEP_CONTROL_EXECUTE_HOLD; // Initiate suspend state with active flag.
+ }
// If IDLE, Grbl is not in motion. Simply indicate suspend state and hold is complete.
if (sys.state == STATE_IDLE) {
sys.suspend = SUSPEND_HOLD_COMPLETE;
sys.step_control = STEP_CONTROL_END_MOTION;
}
-
- // Execute and flag a motion cancel with deceleration and return to idle. Used primarily by probing cycle
- // to halt and cancel the remainder of the motion.
- if (rt_exec & EXEC_MOTION_CANCEL) {
- // MOTION_CANCEL only occurs during a CYCLE, but a HOLD and SAFETY_DOOR may been initiated beforehand
- // to hold the CYCLE. If so, only flag that motion cancel is complete.
- if (sys.state == STATE_CYCLE) { sys.state = STATE_MOTION_CANCEL; }
+
+ // Execute and flag a motion cancel with deceleration and return to idle. Used primarily by probing cycle
+ // to halt and cancel the remainder of the motion.
+ if (rt_exec & EXEC_MOTION_CANCEL) {
+ // MOTION_CANCEL only occurs during a CYCLE, but a HOLD and SAFETY_DOOR may been initiated beforehand
+ // to hold the CYCLE. If so, only flag that motion cancel is complete.
+ if (sys.state == STATE_CYCLE) { sys.state = STATE_MOTION_CANCEL; }
// NOTE: Ensures the motion cancel is handled correctly if it is active during a HOLD or DOOR state.
sys.suspend |= SUSPEND_MOTION_CANCEL; // Indicate motion cancel when resuming.
- }
-
+ }
+
// Execute a feed hold with deceleration, if required. Then, suspend system.
- if (rt_exec & EXEC_FEED_HOLD) {
+ if (rt_exec & EXEC_FEED_HOLD) {
// Block SAFETY_DOOR and SLEEP states from changing to HOLD state.
if (!(sys.state & (STATE_SAFETY_DOOR|STATE_SLEEP))) { sys.state = STATE_HOLD; }
- }
-
+ }
+
// Execute a safety door stop with a feed hold and disable spindle/coolant.
- // NOTE: Safety door differs from feed holds by stopping everything no matter state, disables powered
+ // NOTE: Safety door differs from feed holds by stopping everything no matter state, disables powered
// devices (spindle/coolant), and blocks resuming until switch is re-engaged.
- if (rt_exec & EXEC_SAFETY_DOOR) {
- report_feedback_message(MESSAGE_SAFETY_DOOR_AJAR);
+ if (rt_exec & EXEC_SAFETY_DOOR) {
+ report_feedback_message(MESSAGE_SAFETY_DOOR_AJAR);
// Check if the safety re-opened during a restore parking motion only. Ignore if
// already retracting, parked or in sleep state.
@@ -337,22 +342,19 @@ void protocol_exec_rt_system()
// are executed if the door switch closes and the state returns to HOLD.
sys.suspend |= SUSPEND_SAFETY_DOOR_AJAR;
if (sys.state != STATE_SLEEP) { sys.state = STATE_SAFETY_DOOR; }
- }
-
+ }
if (rt_exec & EXEC_SLEEP) {
sys.state = STATE_SLEEP;
}
-
- }
-
+ }
system_clear_exec_state_flag((EXEC_MOTION_CANCEL | EXEC_FEED_HOLD | EXEC_SAFETY_DOOR | EXEC_SLEEP));
- }
-
- // Execute a cycle start by starting the stepper interrupt to begin executing the blocks in queue.
- if (rt_exec & EXEC_CYCLE_START) {
- // Block if called at same time as the hold commands: feed hold, motion cancel, and safety door.
- // Ensures auto-cycle-start doesn't resume a hold without an explicit user-input.
- if (!(rt_exec & (EXEC_FEED_HOLD | EXEC_MOTION_CANCEL | EXEC_SAFETY_DOOR))) {
+ }
+
+ // Execute a cycle start by starting the stepper interrupt to begin executing the blocks in queue.
+ if (rt_exec & EXEC_CYCLE_START) {
+ // Block if called at same time as the hold commands: feed hold, motion cancel, and safety door.
+ // Ensures auto-cycle-start doesn't resume a hold without an explicit user-input.
+ if (!(rt_exec & (EXEC_FEED_HOLD | EXEC_MOTION_CANCEL | EXEC_SAFETY_DOOR))) {
// Resume door state when parking motion has retracted and door has been closed.
if ((sys.state == STATE_SAFETY_DOOR) && !(sys.suspend & SUSPEND_SAFETY_DOOR_AJAR)) {
if (sys.suspend & SUSPEND_RESTORE_COMPLETE) {
@@ -415,8 +417,7 @@ void protocol_exec_rt_system()
}
}
-
-
+
// Handles Grbl system suspend procedures, such as feed hold, safety door, and parking motion.
// The system will enter this loop, create local variables for suspend tasks, and return to
// whatever function that invoked the suspend, such that Grbl resumes normal operation.
diff --git a/grbl/protocol.h b/grbl/protocol.h
index e8f51d985..45ad69a11 100644
--- a/grbl/protocol.h
+++ b/grbl/protocol.h
@@ -23,6 +23,11 @@
#define protocol_h
// Line buffer size from the serial input stream to be executed.
+// NOTE: Not a problem except for extreme cases, but the line buffer size can be too small
+// and g-code blocks can get truncated. Officially, the g-code standards support up to 256
+// characters. In future versions, this will be increased, when we know how much extra
+// memory space we can invest into here or we re-write the g-code parser not to have this
+// buffer.
#ifndef LINE_BUFFER_SIZE
#define LINE_BUFFER_SIZE 256
#endif
diff --git a/grbl/report.c b/grbl/report.c
index 7d7b80b66..ee8f2640e 100644
--- a/grbl/report.c
+++ b/grbl/report.c
@@ -69,13 +69,15 @@ void report_status_message(uint8_t status_code)
printPgmString(PSTR("Homing not enabled")); break;
case STATUS_OVERFLOW:
printPgmString(PSTR("Line overflow")); break;
- case STATUS_MAX_STEP_RATE_EXCEEDED:
- printPgmString(PSTR("Step rate > 30kHz")); break;
+ #ifdef MAX_STEP_RATE_HZ
+ case STATUS_MAX_STEP_RATE_EXCEEDED:
+ printPgmString(PSTR("Step rate > 30kHz")); break;
+ #endif
case STATUS_CHECK_DOOR:
printPgmString(PSTR("Check Door")); break;
case STATUS_LINE_LENGTH_EXCEEDED:
printPgmString(PSTR("Line length exceeded")); break;
- // Common g-code parser errors.
+ // Common g-code parser errors. // Common g-code parser errors.
case STATUS_GCODE_MODAL_GROUP_VIOLATION:
printPgmString(PSTR("Modal group violation")); break;
case STATUS_GCODE_UNSUPPORTED_COMMAND:
@@ -225,7 +227,7 @@ void report_grbl_settings() {
printPgmString(PSTR(" (homing dir invert mask:")); print_uint8_base2(settings.homing_dir_mask);
printPgmString(PSTR(")\r\n$24=")); printFloat_SettingValue(settings.homing_feed_rate);
printPgmString(PSTR(" (homing feed, mm/min)\r\n$25=")); printFloat_SettingValue(settings.homing_seek_rate);
- printPgmString(PSTR(" (homing seek, mm/min)\r\n$26=")); print_uint8_base10(settings.homing_debounce_delay);
+ printPgmString(PSTR(" (homing seek, mm/min)\r\n$26=")); print_uint32_base10(settings.homing_debounce_delay);
printPgmString(PSTR(" (homing debounce, msec)\r\n$27=")); printFloat_SettingValue(settings.homing_pulloff);
printPgmString(PSTR(" (homing pull-off, mm)\r\n$30=")); printFloat_RPMValue(settings.rpm_max);
printPgmString(PSTR(" (rpm max)\r\n$31=")); printFloat_RPMValue(settings.rpm_min);
@@ -233,6 +235,7 @@ void report_grbl_settings() {
#endif
// Print axis settings
+ {
uint8_t idx, set_idx;
uint8_t val = AXIS_SETTINGS_START_VAL;
for (set_idx=0; set_idxline_number;
}
@@ -655,8 +663,3 @@ void report_realtime_status()
printPgmString(PSTR(">\r\n"));
}
-
-
-
-
-
diff --git a/grbl/serial.c b/grbl/serial.c
index d7d54ddb4..3b561c18c 100644
--- a/grbl/serial.c
+++ b/grbl/serial.c
@@ -1,201 +1,520 @@
-/*
- serial.c - Low level functions for sending and recieving bytes via the serial port
- Part of Grbl
-
- Copyright (c) 2011-2015 Sungeun K. Jeon
- Copyright (c) 2009-2011 Simen Svale Skogsrud
-
- Grbl is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Grbl is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with Grbl. If not, see .
-*/
-
-#include "grbl.h"
-
-
-uint8_t serial_rx_buffer[RX_BUFFER_SIZE];
-uint8_t serial_rx_buffer_head = 0;
-volatile uint8_t serial_rx_buffer_tail = 0;
-
-uint8_t serial_tx_buffer[TX_BUFFER_SIZE];
-uint8_t serial_tx_buffer_head = 0;
-volatile uint8_t serial_tx_buffer_tail = 0;
-
-
-#ifdef ENABLE_XONXOFF
- volatile uint8_t flow_ctrl = XON_SENT; // Flow control state variable
-#endif
-
-
-// Returns the number of bytes used in the RX serial buffer.
-uint8_t serial_get_rx_buffer_count()
-{
- uint8_t rtail = serial_rx_buffer_tail; // Copy to limit multiple calls to volatile
- if (serial_rx_buffer_head >= rtail) { return(serial_rx_buffer_head-rtail); }
- return (RX_BUFFER_SIZE - (rtail-serial_rx_buffer_head));
-}
-
-
-// Returns the number of bytes used in the TX serial buffer.
-// NOTE: Not used except for debugging and ensuring no TX bottlenecks.
-uint8_t serial_get_tx_buffer_count()
-{
- uint8_t ttail = serial_tx_buffer_tail; // Copy to limit multiple calls to volatile
- if (serial_tx_buffer_head >= ttail) { return(serial_tx_buffer_head-ttail); }
- return (TX_BUFFER_SIZE - (ttail-serial_tx_buffer_head));
-}
-
-
-void serial_init()
-{
- // Set baud rate
- #if BAUD_RATE < 57600
- uint16_t UBRR0_value = ((F_CPU / (8L * BAUD_RATE)) - 1)/2 ;
- UCSR0A &= ~(1 << U2X0); // baud doubler off - Only needed on Uno XXX
- #else
- uint16_t UBRR0_value = ((F_CPU / (4L * BAUD_RATE)) - 1)/2;
- UCSR0A |= (1 << U2X0); // baud doubler on for high baud rates, i.e. 115200
- #endif
- UBRR0H = UBRR0_value >> 8;
- UBRR0L = UBRR0_value;
-
- // enable rx and tx
- UCSR0B |= 1<= RX_BUFFER_FULL) && flow_ctrl == XON_SENT) {
- flow_ctrl = SEND_XOFF;
- UCSR0B |= (1 << UDRIE0); // Force TX
- }
- #endif
-
- }
- //TODO: else alarm on overflow?
- }
-}
-
-
-void serial_reset_read_buffer()
-{
- serial_rx_buffer_tail = serial_rx_buffer_head;
-
- #ifdef ENABLE_XONXOFF
- flow_ctrl = XON_SENT;
- #endif
-}
+/*
+ serial.c - Low level functions for sending and recieving bytes via the serial port
+ Part of Grbl
+
+ Copyright (c) 2011-2015 Sungeun K. Jeon
+ Copyright (c) 2009-2011 Simen Svale Skogsrud
+
+ Grbl is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Grbl is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with Grbl. If not, see .
+*/
+
+#include "grbl.h"
+#ifdef WIN32
+#include
+#include
+#include
+CRITICAL_SECTION CriticalSection;
+
+HANDLE hSerial = INVALID_HANDLE_VALUE;
+void RecvthreadFunction( void *);
+void SendthreadFunction( void *);
+HANDLE g_hRecv;
+HANDLE g_hSend;
+HANDLE g_hSendEvent;
+
+#endif
+#ifdef STM32F103C8
+#include "stm32f10x.h"
+#include "core_cm3.h"
+#endif
+
+uint8_t serial_rx_buffer[RX_BUFFER_SIZE];
+uint8_t serial_rx_buffer_head = 0;
+volatile uint8_t serial_rx_buffer_tail = 0;
+
+uint8_t serial_tx_buffer[TX_BUFFER_SIZE];
+uint8_t serial_tx_buffer_head = 0;
+volatile uint8_t serial_tx_buffer_tail = 0;
+
+
+#ifdef ENABLE_XONXOFF
+ volatile uint8_t flow_ctrl = XON_SENT; // Flow control state variable
+#endif
+
+
+// Returns the number of bytes used in the RX serial buffer.
+uint8_t serial_get_rx_buffer_count()
+{
+ uint8_t rtail = serial_rx_buffer_tail; // Copy to limit multiple calls to volatile
+ if (serial_rx_buffer_head >= rtail) { return(serial_rx_buffer_head-rtail); }
+ return (RX_BUFFER_SIZE - (rtail-serial_rx_buffer_head));
+}
+
+
+// Returns the number of bytes used in the TX serial buffer.
+// NOTE: Not used except for debugging and ensuring no TX bottlenecks.
+uint8_t serial_get_tx_buffer_count()
+{
+ uint8_t ttail = serial_tx_buffer_tail; // Copy to limit multiple calls to volatile
+ if (serial_tx_buffer_head >= ttail) { return(serial_tx_buffer_head-ttail); }
+ return (TX_BUFFER_SIZE - (ttail-serial_tx_buffer_head));
+}
+
+
+void serial_init()
+{
+#ifdef AVRTARGET
+ // Set baud rate
+ #if BAUD_RATE < 57600
+ uint16_t UBRR0_value = ((F_CPU / (8L * BAUD_RATE)) - 1)/2 ;
+ UCSR0A &= ~(1 << U2X0); // baud doubler off - Only needed on Uno XXX
+ #else
+ uint16_t UBRR0_value = ((F_CPU / (4L * BAUD_RATE)) - 1)/2;
+ UCSR0A |= (1 << U2X0); // baud doubler on for high baud rates, i.e. 115200
+ #endif
+ UBRR0H = UBRR0_value >> 8;
+ UBRR0L = UBRR0_value;
+
+ // enable rx and tx
+ UCSR0B |= 1< serial_tx_buffer_tail)
+ USB_Tx_length = serial_tx_buffer_head - serial_tx_buffer_tail;
+ else
+ {
+ USB_Tx_length = TX_BUFFER_SIZE - serial_tx_buffer_tail;
+ if (USB_Tx_length == 0)
+ {
+ USB_Tx_length = serial_tx_buffer_head;
+ serial_tx_buffer_tail = 0;
+ }
+ }
+ if (USB_Tx_length > 16)
+ USB_Tx_length = 16;
+
+ memcpy(szBuf,&serial_tx_buffer[serial_tx_buffer_tail],USB_Tx_length);
+ serial_tx_buffer_tail += USB_Tx_length;
+ if (serial_tx_buffer_tail == TX_BUFFER_SIZE)
+ serial_tx_buffer_tail = 0;
+
+ // copy data
+ ReleaseMutex(g_hSend);
+ if (serial_tx_buffer_head == serial_tx_buffer_tail)
+ ResetEvent(g_hSendEvent);
+ else
+ SetEvent(g_hSendEvent);
+
+ if (USB_Tx_length != 0)
+ {
+ if (hSerial != INVALID_HANDLE_VALUE)
+ WriteFile(hSerial, szBuf,USB_Tx_length, &dwBytesWritten, NULL);
+ else
+ fwrite(szBuf,1,USB_Tx_length,stdout);
+ }
+ }
+
+#else
+ DWORD nTotalByte;
+ DWORD dwBytesWritten;
+ for (;;)
+ {
+ WaitForSingleObject(g_hSendEvent,INFINITE);
+ WaitForSingleObject(g_hSend,INFINITE);
+ nTotalByte = 0;
+ while (serial_tx_buffer_tail != serial_tx_buffer_head)
+ {
+ szBuf[nTotalByte ++] = serial_tx_buffer[serial_tx_buffer_tail ++];
+ if (serial_tx_buffer_tail == TX_BUFFER_SIZE)
+ serial_tx_buffer_tail = 0;
+ }
+ // copy data
+ ReleaseMutex(g_hSend);
+ if (nTotalByte != 0)
+ {
+ if (hSerial != INVALID_HANDLE_VALUE)
+ WriteFile(hSerial, szBuf,nTotalByte, &dwBytesWritten, NULL);
+ else
+ fwrite(szBuf,1,nTotalByte,stdout);
+ }
+ }
+#endif
+}
+#endif
+// Fetches the first byte in the serial read buffer. Called by main program.
+uint8_t serial_read()
+{
+#ifdef WIN32
+ uint8_t tail = serial_rx_buffer_tail; // Temporary serial_rx_buffer_tail (to optimize for volatile)
+ if (serial_rx_buffer_head == tail)
+ {
+ return SERIAL_NO_DATA;
+ }
+ else
+ {
+ uint8_t data;
+ WaitForSingleObject(g_hRecv,INFINITE);
+ data = serial_rx_buffer[tail];
+ tail++;
+ if (tail == RX_BUFFER_SIZE)
+ {
+ tail = 0;
+ }
+ serial_rx_buffer_tail = tail;
+ ReleaseMutex(g_hRecv);
+ return data;
+ }
+#endif
+#if defined(AVRTARGET) || defined (STM32F103C8)
+ uint8_t tail = serial_rx_buffer_tail; // Temporary serial_rx_buffer_tail (to optimize for volatile)
+ if (serial_rx_buffer_head == tail) {
+ return SERIAL_NO_DATA;
+ } else {
+#if defined (STM32F103C8)
+ NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn);
+#endif
+ uint8_t data = serial_rx_buffer[tail];
+
+ tail++;
+ if (tail == RX_BUFFER_SIZE) { tail = 0; }
+ serial_rx_buffer_tail = tail;
+
+ #ifdef ENABLE_XONXOFF
+ if ((serial_get_rx_buffer_count() < RX_BUFFER_LOW) && flow_ctrl == XOFF_SENT) {
+ flow_ctrl = SEND_XON;
+ UCSR0B |= (1 << UDRIE0); // Force TX
+ }
+ #endif
+#if defined (STM32F103C8)
+ NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
+#endif
+
+ return data;
+ }
+#endif
+}
+
+#ifdef AVRTARGET
+ISR(SERIAL_RX)
+{
+ uint8_t data = UDR0;
+ uint8_t next_head;
+
+ // Pick off realtime command characters directly from the serial stream. These characters are
+ // not passed into the buffer, but these set system state flag bits for realtime execution.
+ switch (data) {
+ case CMD_STATUS_REPORT: system_set_exec_state_flag(EXEC_STATUS_REPORT); break; // Set as true
+ case CMD_CYCLE_START: system_set_exec_state_flag(EXEC_CYCLE_START); break; // Set as true
+ case CMD_FEED_HOLD: system_set_exec_state_flag(EXEC_FEED_HOLD); break; // Set as true
+ case CMD_SAFETY_DOOR: system_set_exec_state_flag(EXEC_SAFETY_DOOR); break; // Set as true
+ case CMD_RESET: mc_reset(); break; // Call motion control reset routine.
+ default: // Write character to buffer
+ next_head = serial_rx_buffer_head + 1;
+ if (next_head == RX_BUFFER_SIZE) { next_head = 0; }
+
+ // Write data to buffer unless it is full.
+ if (next_head != serial_rx_buffer_tail) {
+ serial_rx_buffer[serial_rx_buffer_head] = data;
+ serial_rx_buffer_head = next_head;
+
+ #ifdef ENABLE_XONXOFF
+ if ((serial_get_rx_buffer_count() >= RX_BUFFER_FULL) && flow_ctrl == XON_SENT) {
+ flow_ctrl = SEND_XOFF;
+ UCSR0B |= (1 << UDRIE0); // Force TX
+ }
+ #endif
+
+ }
+ //TODO: else alarm on overflow?
+ }
+}
+#endif
+
+void serial_reset_read_buffer()
+{
+ serial_rx_buffer_tail = serial_rx_buffer_head;
+
+ #ifdef ENABLE_XONXOFF
+ flow_ctrl = XON_SENT;
+ #endif
+}
diff --git a/grbl/serial.h b/grbl/serial.h
index fab5dd5c1..a3f1e49c6 100644
--- a/grbl/serial.h
+++ b/grbl/serial.h
@@ -1,64 +1,70 @@
-/*
- serial.c - Low level functions for sending and recieving bytes via the serial port
- Part of Grbl
-
- Copyright (c) 2011-2015 Sungeun K. Jeon
- Copyright (c) 2009-2011 Simen Svale Skogsrud
-
- Grbl is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Grbl is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with Grbl. If not, see .
-*/
-
-#ifndef serial_h
-#define serial_h
-
-
-#ifndef RX_BUFFER_SIZE
- #define RX_BUFFER_SIZE 256
-#endif
-#ifndef TX_BUFFER_SIZE
- #define TX_BUFFER_SIZE 128
-#endif
-
-#define SERIAL_NO_DATA 0xff
-
-#ifdef ENABLE_XONXOFF
- #define RX_BUFFER_FULL 96 // XOFF high watermark
- #define RX_BUFFER_LOW 64 // XON low watermark
- #define SEND_XOFF 1
- #define SEND_XON 2
- #define XOFF_SENT 3
- #define XON_SENT 4
- #define XOFF_CHAR 0x13
- #define XON_CHAR 0x11
-#endif
-
-void serial_init();
-
-// Writes one byte to the TX serial buffer. Called by main program.
-void serial_write(uint8_t data);
-
-// Fetches the first byte in the serial read buffer. Called by main program.
-uint8_t serial_read();
-
-// Reset and empty data in read buffer. Used by e-stop and reset.
-void serial_reset_read_buffer();
-
-// Returns the number of bytes used in the RX serial buffer.
-uint8_t serial_get_rx_buffer_count();
-
-// Returns the number of bytes used in the TX serial buffer.
-// NOTE: Not used except for debugging and ensuring no TX bottlenecks.
-uint8_t serial_get_tx_buffer_count();
-
-#endif
+/*
+ serial.c - Low level functions for sending and recieving bytes via the serial port
+ Part of Grbl
+
+ Copyright (c) 2011-2015 Sungeun K. Jeon
+ Copyright (c) 2009-2011 Simen Svale Skogsrud
+
+ Grbl is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Grbl is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with Grbl. If not, see .
+*/
+
+#ifndef serial_h
+#define serial_h
+
+
+#ifndef RX_BUFFER_SIZE
+ #define RX_BUFFER_SIZE 128
+#endif
+#ifndef TX_BUFFER_SIZE
+#if defined (STM32F103C8)
+ #define TX_BUFFER_SIZE 256
+#else
+ #define TX_BUFFER_SIZE 64
+#endif
+#endif
+
+#define SERIAL_NO_DATA 0xff
+
+#ifdef ENABLE_XONXOFF
+ #define RX_BUFFER_FULL 96 // XOFF high watermark
+ #define RX_BUFFER_LOW 64 // XON low watermark
+ #define SEND_XOFF 1
+ #define SEND_XON 2
+ #define XOFF_SENT 3
+ #define XON_SENT 4
+ #define XOFF_CHAR 0x13
+ #define XON_CHAR 0x11
+#endif
+
+#ifdef WIN32
+void winserial_init(char *pPort);
+#endif
+void serial_init();
+
+// Writes one byte to the TX serial buffer. Called by main program.
+void serial_write(uint8_t data);
+// Fetches the first byte in the serial read buffer. Called by main program.
+uint8_t serial_read();
+
+// Reset and empty data in read buffer. Used by e-stop and reset.
+void serial_reset_read_buffer();
+
+// Returns the number of bytes used in the RX serial buffer.
+uint8_t serial_get_rx_buffer_count();
+
+// Returns the number of bytes used in the TX serial buffer.
+// NOTE: Not used except for debugging and ensuring no TX bottlenecks.
+uint8_t serial_get_tx_buffer_count();
+
+#endif
diff --git a/grbl/settings.c b/grbl/settings.c
index 50a2d28fa..6ad064c8e 100644
--- a/grbl/settings.c
+++ b/grbl/settings.c
@@ -54,6 +54,7 @@ void write_global_settings()
memcpy_to_eeprom_with_checksum(EEPROM_ADDR_GLOBAL, (char*)&settings, sizeof(settings_t));
}
+extern char line[];
// Method to restore EEPROM-saved Grbl global settings back to defaults.
void settings_restore(uint8_t restore_flag) {
@@ -100,22 +101,23 @@ void settings_restore(uint8_t restore_flag) {
}
if (restore_flag & SETTINGS_RESTORE_PARAMETERS) {
- uint8_t idx;
- float coord_data[N_AXIS];
- memset(&coord_data, 0, sizeof(coord_data));
- for (idx=0; idx <= SETTING_INDEX_NCOORD; idx++) { settings_write_coord_data(idx, coord_data); }
+ uint8_t idx;
+ float coord_data[N_AXIS];
+ memset(&coord_data, 0, sizeof(coord_data));
+ for (idx=0; idx <= SETTING_INDEX_NCOORD; idx++) { settings_write_coord_data(idx, coord_data); }
}
if (restore_flag & SETTINGS_RESTORE_STARTUP_LINES) {
- #if N_STARTUP_LINE > 0
- eeprom_put_char(EEPROM_ADDR_STARTUP_BLOCK, 0);
- #endif
- #if N_STARTUP_LINE > 1
- eeprom_put_char(EEPROM_ADDR_STARTUP_BLOCK+(EEPROM_LINE_SIZE+1), 0);
- #endif
+ line[0] = 0;
+ #if N_STARTUP_LINE > 0
+ settings_store_startup_line(0,line);
+ #endif
+ #if N_STARTUP_LINE > 1
+ settings_store_startup_line(1,line);
+ #endif
}
- if (restore_flag & SETTINGS_RESTORE_BUILD_INFO) { eeprom_put_char(EEPROM_ADDR_BUILD_INFO , 0); }
+ if (restore_flag & SETTINGS_RESTORE_BUILD_INFO) { settings_store_build_info(line); }
}
@@ -149,10 +151,14 @@ uint8_t settings_read_build_info(char *line)
// Read selected coordinate data from EEPROM. Updates pointed coord_data value.
uint8_t settings_read_coord_data(uint8_t coord_select, float *coord_data)
{
+ int i;
uint32_t addr = coord_select*(sizeof(float)*N_AXIS+1) + EEPROM_ADDR_PARAMETERS;
if (!(memcpy_from_eeprom_with_checksum((char*)coord_data, addr, sizeof(float)*N_AXIS))) {
// Reset with default zero vector
- clear_vector_float(coord_data);
+ for (i = 0; i < N_AXIS; i ++)
+ {
+ coord_data[i] = 0.0;
+ }
settings_write_coord_data(coord_select,coord_data);
return(false);
}
@@ -178,22 +184,26 @@ uint8_t read_global_settings() {
// A helper method to set settings from command line
uint8_t settings_store_global_setting(uint8_t parameter, float value) {
+ uint8_t set_idx = 0;
if (value < 0.0) { return(STATUS_NEGATIVE_VALUE); }
if (parameter >= AXIS_SETTINGS_START_VAL) {
// Store axis configuration. Axis numbering sequence set by AXIS_SETTING defines.
// NOTE: Ensure the setting index corresponds to the report.c settings printout.
parameter -= AXIS_SETTINGS_START_VAL;
- uint8_t set_idx = 0;
while (set_idx < AXIS_N_SETTINGS) {
if (parameter < N_AXIS) {
// Valid axis setting found.
switch (set_idx) {
case 0:
- if (value*settings.max_rate[parameter] > (MAX_STEP_RATE_HZ*60.0)) { return(STATUS_MAX_STEP_RATE_EXCEEDED); }
+ #ifdef MAX_STEP_RATE_HZ
+ if (value*settings.max_rate[parameter] > (MAX_STEP_RATE_HZ*60.0)) { return(STATUS_MAX_STEP_RATE_EXCEEDED); }
+ #endif
settings.steps_per_mm[parameter] = value;
break;
case 1:
- if (value*settings.steps_per_mm[parameter] > (MAX_STEP_RATE_HZ*60.0)) { return(STATUS_MAX_STEP_RATE_EXCEEDED); }
+ #ifdef MAX_STEP_RATE_HZ
+ if (value*settings.steps_per_mm[parameter] > (MAX_STEP_RATE_HZ*60.0)) { return(STATUS_MAX_STEP_RATE_EXCEEDED); }
+ #endif
settings.max_rate[parameter] = value;
break;
case 2: settings.acceleration[parameter] = value*60*60; break; // Convert to mm/min^2 for grbl internal use.
@@ -279,9 +289,14 @@ uint8_t settings_store_global_setting(uint8_t parameter, float value) {
// Initialize the config subsystem
void settings_init() {
if(!read_global_settings()) {
+#ifndef STM32F103C8
+ // STM32F103C8 is not ready when doing this. So print out display is not needed in here.
report_status_message(STATUS_SETTING_READ_FAIL);
+#endif
settings_restore(SETTINGS_RESTORE_ALL); // Force restore all EEPROM data.
+#ifndef STM32F103C8
report_grbl_settings();
+#endif
}
// NOTE: Checking paramater data, startup lines, and build info string should be done here,
@@ -299,7 +314,7 @@ void settings_init() {
// Returns step pin mask according to Grbl internal axis indexing.
-uint8_t get_step_pin_mask(uint8_t axis_idx)
+PORTPINDEF get_step_pin_mask(uint8_t axis_idx)
{
if ( axis_idx == X_AXIS ) { return((1<.
-*/
-
-#include "grbl.h"
-
-
-void spindle_init()
-{
+/*
+ spindle_control.c - spindle control methods
+ Part of Grbl
+
+ Copyright (c) 2012-2015 Sungeun K. Jeon
+ Copyright (c) 2009-2011 Simen Svale Skogsrud
+
+ Grbl is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Grbl is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with Grbl. If not, see .
+*/
+
+#include "grbl.h"
+
+
+void spindle_init()
+{
+#ifdef AVRTARGET
// Configure variable spindle PWM and enable pin, if required.
SPINDLE_PWM_DDR |= (1< settings.rpm_max) { rpm = settings.rpm_max; }
- if (rpm < settings.rpm_min) { rpm = settings.rpm_min; }
- #ifdef SPINDLE_MINIMUM_PWM
- float pwm_gradient = (SPINDLE_PWM_MAX_VALUE-SPINDLE_MINIMUM_PWM)/(settings.rpm_max-settings.rpm_min);
- current_pwm = floor( (rpm-settings.rpm_min)*pwm_gradient + (SPINDLE_MINIMUM_PWM+0.5));
- #else
- float pwm_gradient = (SPINDLE_PWM_MAX_VALUE)/(settings.rpm_max-settings.rpm_min);
- current_pwm = floor( (rpm-settings.rpm_min)*pwm_gradient + 0.5);
- #endif
- }
-
- SPINDLE_OCR_REGISTER = current_pwm; // Set PWM output level.
- SPINDLE_TCCRA_REGISTER |= (1< SPINDLE_RPM_RANGE ) { rpm = SPINDLE_RPM_RANGE; } // Prevent integer overflow
+ }
+ current_pwm = floor( rpm*(PWM_MAX_VALUE/SPINDLE_RPM_RANGE) + 0.5);
+ #ifdef MINIMUM_SPINDLE_PWM
+ if (current_pwm < MINIMUM_SPINDLE_PWM) { current_pwm = MINIMUM_SPINDLE_PWM; }
+ #endif
+ OCR_REGISTER = current_pwm; // Set PWM pin output
+
+ // On the Uno, spindle enable and PWM are shared, unless otherwise specified.
+ #if defined(CPU_MAP_ATMEGA2560) || defined(USE_SPINDLE_DIR_AS_ENABLE_PIN)
+ #ifdef INVERT_SPINDLE_ENABLE_PIN
+#if defined(AVRTARGET)
+ SPINDLE_ENABLE_PORT &= ~(1<.
-*/
-
-#include "grbl.h"
-
-
-// Some useful constants.
-#define DT_SEGMENT (1.0/(ACCELERATION_TICKS_PER_SECOND*60.0)) // min/segment
-#define REQ_MM_INCREMENT_SCALAR 1.25
-#define RAMP_ACCEL 0
-#define RAMP_CRUISE 1
-#define RAMP_DECEL 2
-
+/*
+ stepper.c - stepper motor driver: executes motion plans using stepper motors
+ Part of Grbl
+
+ Copyright (c) 2011-2015 Sungeun K. Jeon
+ Copyright (c) 2009-2011 Simen Svale Skogsrud
+
+ Grbl is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Grbl is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with Grbl. If not, see .
+*/
+
+#include "grbl.h"
+#ifdef STM32F103C8
+typedef int bool;
+#include "stm32f10x_rcc.h"
+#include "stm32f10x_tim.h"
+#include "misc.h"
+void TIM_Configuration(TIM_TypeDef* TIMER,u16 Period,u16 Prescaler,u8 PP);
+#endif
+
+// Some useful constants.
+#define DT_SEGMENT (1.0/(ACCELERATION_TICKS_PER_SECOND*60.0)) // min/segment
+#define REQ_MM_INCREMENT_SCALAR 1.25
+#define RAMP_ACCEL 0
+#define RAMP_CRUISE 1
+#define RAMP_DECEL 2
+
#define PREP_FLAG_RECALCULATE bit(0)
#define PREP_FLAG_HOLD_PARTIAL_BLOCK bit(1)
#define PREP_FLAG_PARKING bit(2)
-
-// Define Adaptive Multi-Axis Step-Smoothing(AMASS) levels and cutoff frequencies. The highest level
-// frequency bin starts at 0Hz and ends at its cutoff frequency. The next lower level frequency bin
-// starts at the next higher cutoff frequency, and so on. The cutoff frequencies for each level must
-// be considered carefully against how much it over-drives the stepper ISR, the accuracy of the 16-bit
-// timer, and the CPU overhead. Level 0 (no AMASS, normal operation) frequency bin starts at the
-// Level 1 cutoff frequency and up to as fast as the CPU allows (over 30kHz in limited testing).
-// NOTE: AMASS cutoff frequency multiplied by ISR overdrive factor must not exceed maximum step frequency.
-// NOTE: Current settings are set to overdrive the ISR to no more than 16kHz, balancing CPU overhead
-// and timer accuracy. Do not alter these settings unless you know what you are doing.
-#define MAX_AMASS_LEVEL 3
-// AMASS_LEVEL0: Normal operation. No AMASS. No upper cutoff frequency. Starts at LEVEL1 cutoff frequency.
-#define AMASS_LEVEL1 (F_CPU/8000) // Over-drives ISR (x2). Defined as F_CPU/(Cutoff frequency in Hz)
-#define AMASS_LEVEL2 (F_CPU/4000) // Over-drives ISR (x4)
-#define AMASS_LEVEL3 (F_CPU/2000) // Over-drives ISR (x8)
-
-
-// Stores the planner block Bresenham algorithm execution data for the segments in the segment
-// buffer. Normally, this buffer is partially in-use, but, for the worst case scenario, it will
-// never exceed the number of accessible stepper buffer segments (SEGMENT_BUFFER_SIZE-1).
-// NOTE: This data is copied from the prepped planner blocks so that the planner blocks may be
-// discarded when entirely consumed and completed by the segment buffer. Also, AMASS alters this
-// data for its own use.
-typedef struct {
- uint8_t direction_bits;
- uint32_t steps[N_AXIS];
- uint32_t step_event_count;
-} st_block_t;
-static st_block_t st_block_buffer[SEGMENT_BUFFER_SIZE-1];
-
-// Primary stepper segment ring buffer. Contains small, short line segments for the stepper
-// algorithm to execute, which are "checked-out" incrementally from the first block in the
-// planner buffer. Once "checked-out", the steps in the segments buffer cannot be modified by
-// the planner, where the remaining planner block steps still can.
-typedef struct {
- uint16_t n_step; // Number of step events to be executed for this segment
- uint8_t st_block_index; // Stepper block data index. Uses this information to execute this segment.
- uint16_t cycles_per_tick; // Step distance traveled per ISR tick, aka step rate.
- #ifdef ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING
- uint8_t amass_level; // Indicates AMASS level for the ISR to execute this segment
- #else
- uint8_t prescaler; // Without AMASS, a prescaler is required to adjust for slow timing.
- #endif
-} segment_t;
-static segment_t segment_buffer[SEGMENT_BUFFER_SIZE];
-
-// Stepper ISR data struct. Contains the running data for the main stepper ISR.
-typedef struct {
- // Used by the bresenham line algorithm
- uint32_t counter_x, // Counter variables for the bresenham line tracer
- counter_y,
- counter_z;
- #ifdef STEP_PULSE_DELAY
- uint8_t step_bits; // Stores out_bits output to complete the step pulse delay
- #endif
-
- uint8_t execute_step; // Flags step execution for each interrupt.
- uint8_t step_pulse_time; // Step pulse reset time after step rise
- uint8_t step_outbits; // The next stepping-bits to be output
- uint8_t dir_outbits;
- #ifdef ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING
- uint32_t steps[N_AXIS];
- #endif
-
- uint16_t step_count; // Steps remaining in line segment motion
- uint8_t exec_block_index; // Tracks the current st_block index. Change indicates new block.
- st_block_t *exec_block; // Pointer to the block data for the segment being executed
- segment_t *exec_segment; // Pointer to the segment being executed
-} stepper_t;
-static stepper_t st;
-
-// Step segment ring buffer indices
-static volatile uint8_t segment_buffer_tail;
-static uint8_t segment_buffer_head;
-static uint8_t segment_next_head;
-
-// Step and direction port invert masks.
-static uint8_t step_port_invert_mask;
-static uint8_t dir_port_invert_mask;
-
-// Used to avoid ISR nesting of the "Stepper Driver Interrupt". Should never occur though.
-static volatile uint8_t busy;
-
-// Pointers for the step segment being prepped from the planner buffer. Accessed only by the
-// main program. Pointers may be planning segments or planner blocks ahead of what being executed.
-static plan_block_t *pl_block; // Pointer to the planner block being prepped
-static st_block_t *st_prep_block; // Pointer to the stepper block data being prepped
-
-// Segment preparation data struct. Contains all the necessary information to compute new segments
-// based on the current executing planner block.
-typedef struct {
- uint8_t st_block_index; // Index of stepper common data block being prepped
+
+// Define Adaptive Multi-Axis Step-Smoothing(AMASS) levels and cutoff frequencies. The highest level
+// frequency bin starts at 0Hz and ends at its cutoff frequency. The next lower level frequency bin
+// starts at the next higher cutoff frequency, and so on. The cutoff frequencies for each level must
+// be considered carefully against how much it over-drives the stepper ISR, the accuracy of the 16-bit
+// timer, and the CPU overhead. Level 0 (no AMASS, normal operation) frequency bin starts at the
+// Level 1 cutoff frequency and up to as fast as the CPU allows (over 30kHz in limited testing).
+// NOTE: AMASS cutoff frequency multiplied by ISR overdrive factor must not exceed maximum step frequency.
+// NOTE: Current settings are set to overdrive the ISR to no more than 16kHz, balancing CPU overhead
+// and timer accuracy. Do not alter these settings unless you know what you are doing.
+#define MAX_AMASS_LEVEL 3
+// AMASS_LEVEL0: Normal operation. No AMASS. No upper cutoff frequency. Starts at LEVEL1 cutoff frequency.
+#define AMASS_LEVEL1 (F_CPU/8000) // Over-drives ISR (x2). Defined as F_CPU/(Cutoff frequency in Hz)
+#define AMASS_LEVEL2 (F_CPU/4000) // Over-drives ISR (x4)
+#define AMASS_LEVEL3 (F_CPU/2000) // Over-drives ISR (x8)
+#ifdef WIN32
+#include "windows.h"
+#include "Winbase.h"
+unsigned char PORTB = 0;
+unsigned char DDRD = 0;
+unsigned char DDRB = 0;
+unsigned char PORTD = 0;
+LARGE_INTEGER Win32Frequency;
+LONGLONG nTimer1Out = 0;
+LONGLONG nTimer0Out = 0;
+#endif
+
+
+// Stores the planner block Bresenham algorithm execution data for the segments in the segment
+// buffer. Normally, this buffer is partially in-use, but, for the worst case scenario, it will
+// never exceed the number of accessible stepper buffer segments (SEGMENT_BUFFER_SIZE-1).
+// NOTE: This data is copied from the prepped planner blocks so that the planner blocks may be
+// discarded when entirely consumed and completed by the segment buffer. Also, AMASS alters this
+// data for its own use.
+typedef struct {
+ PORTPINDEF direction_bits;
+ uint32_t steps[N_AXIS];
+ uint32_t step_event_count;
+} st_block_t;
+static st_block_t st_block_buffer[SEGMENT_BUFFER_SIZE-1];
+
+// Primary stepper segment ring buffer. Contains small, short line segments for the stepper
+// algorithm to execute, which are "checked-out" incrementally from the first block in the
+// planner buffer. Once "checked-out", the steps in the segments buffer cannot be modified by
+// the planner, where the remaining planner block steps still can.
+typedef struct {
+ uint16_t n_step; // Number of step events to be executed for this segment
+ uint8_t st_block_index; // Stepper block data index. Uses this information to execute this segment.
+ uint16_t cycles_per_tick; // Step distance traveled per ISR tick, aka step rate.
+ #ifdef ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING
+ uint8_t amass_level; // Indicates AMASS level for the ISR to execute this segment
+ #else
+ uint8_t prescaler; // Without AMASS, a prescaler is required to adjust for slow timing.
+ #endif
+} segment_t;
+static segment_t segment_buffer[SEGMENT_BUFFER_SIZE];
+
+// Stepper ISR data struct. Contains the running data for the main stepper ISR.
+typedef struct {
+ // Used by the bresenham line algorithm
+ uint32_t counter_x, // Counter variables for the bresenham line tracer
+ counter_y,
+ counter_z;
+ #ifdef STEP_PULSE_DELAY
+ uint8_t step_bits; // Stores out_bits output to complete the step pulse delay
+ #endif
+
+ uint8_t execute_step; // Flags step execution for each interrupt.
+#ifndef WIN32
+ uint8_t step_pulse_time; // Step pulse reset time after step rise
+#else
+ LONGLONG step_pulse_time;
+#endif
+ PORTPINDEF step_outbits; // The next stepping-bits to be output
+ PORTPINDEF dir_outbits;
+ #ifdef ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING
+ uint32_t steps[N_AXIS];
+ #endif
+
+ uint16_t step_count; // Steps remaining in line segment motion
+ uint8_t exec_block_index; // Tracks the current st_block index. Change indicates new block.
+ st_block_t *exec_block; // Pointer to the block data for the segment being executed
+ segment_t *exec_segment; // Pointer to the segment being executed
+} stepper_t;
+static stepper_t st;
+
+// Step segment ring buffer indices
+static volatile uint8_t segment_buffer_tail;
+static uint8_t segment_buffer_head;
+static uint8_t segment_next_head;
+
+// Step and direction port invert masks.
+static PORTPINDEF step_port_invert_mask;
+static PORTPINDEF dir_port_invert_mask;
+
+// Used to avoid ISR nesting of the "Stepper Driver Interrupt". Should never occur though.
+static volatile uint8_t busy;
+
+// Pointers for the step segment being prepped from the planner buffer. Accessed only by the
+// main program. Pointers may be planning segments or planner blocks ahead of what being executed.
+static plan_block_t *pl_block; // Pointer to the planner block being prepped
+static st_block_t *st_prep_block; // Pointer to the stepper block data being prepped
+
+// Segment preparation data struct. Contains all the necessary information to compute new segments
+// based on the current executing planner block.
+typedef struct {
+ uint8_t st_block_index; // Index of stepper common data block being prepped
uint8_t recalculate_flag;
-
+
float dt_remainder;
- float steps_remaining;
- float step_per_mm;
- float req_mm_increment;
+ float steps_remaining;
+ float step_per_mm;
+ float req_mm_increment;
#ifdef PARKING_ENABLE
uint8_t last_st_block_index;
@@ -137,384 +158,581 @@ typedef struct {
float last_step_per_mm;
float last_dt_remainder;
#endif
-
- uint8_t ramp_type; // Current segment ramp state
- float mm_complete; // End of velocity profile from end of current planner block in (mm).
- // NOTE: This value must coincide with a step(no mantissa) when converted.
- float current_speed; // Current speed at the end of the segment buffer (mm/min)
- float maximum_speed; // Maximum speed of executing block. Not always nominal speed. (mm/min)
- float exit_speed; // Exit speed of executing block (mm/min)
- float accelerate_until; // Acceleration ramp end measured from end of block (mm)
- float decelerate_after; // Deceleration ramp start measured from end of block (mm)
-} st_prep_t;
-static st_prep_t prep;
-
-
-/* BLOCK VELOCITY PROFILE DEFINITION
- __________________________
- /| |\ _________________ ^
- / | | \ /| |\ |
- / | | \ / | | \ s
- / | | | | | \ p
- / | | | | | \ e
- +-----+------------------------+---+--+---------------+----+ e
- | BLOCK 1 ^ BLOCK 2 | d
- |
- time -----> EXAMPLE: Block 2 entry speed is at max junction velocity
-
- The planner block buffer is planned assuming constant acceleration velocity profiles and are
- continuously joined at block junctions as shown above. However, the planner only actively computes
- the block entry speeds for an optimal velocity plan, but does not compute the block internal
- velocity profiles. These velocity profiles are computed ad-hoc as they are executed by the
- stepper algorithm and consists of only 7 possible types of profiles: cruise-only, cruise-
- deceleration, acceleration-cruise, acceleration-only, deceleration-only, full-trapezoid, and
- triangle(no cruise).
-
- maximum_speed (< nominal_speed) -> +
- +--------+ <- maximum_speed (= nominal_speed) /|\
- / \ / | \
- current_speed -> + \ / | + <- exit_speed
- | + <- exit_speed / | |
- +-------------+ current_speed -> +----+--+
- time --> ^ ^ ^ ^
- | | | |
- decelerate_after(in mm) decelerate_after(in mm)
- ^ ^ ^ ^
- | | | |
- accelerate_until(in mm) accelerate_until(in mm)
-
- The step segment buffer computes the executing block velocity profile and tracks the critical
- parameters for the stepper algorithm to accurately trace the profile. These critical parameters
- are shown and defined in the above illustration.
-*/
-
-
-// Stepper state initialization. Cycle should only start if the st.cycle_start flag is
-// enabled. Startup init and limits call this function but shouldn't start the cycle.
-void st_wake_up()
-{
- // Enable stepper drivers.
- if (bit_istrue(settings.flags,BITFLAG_INVERT_ST_ENABLE)) { STEPPERS_DISABLE_PORT |= (1<> 3);
- // Set delay between direction pin write and step command.
- OCR0A = -(((settings.pulse_microseconds)*TICKS_PER_MICROSECOND) >> 3);
- #else // Normal operation
- // Set step pulse time. Ad hoc computation from oscilloscope. Uses two's complement.
- st.step_pulse_time = -(((settings.pulse_microseconds-2)*TICKS_PER_MICROSECOND) >> 3);
- #endif
-
- // Enable Stepper Driver Interrupt
- TIMSK1 |= (1<prescaler<cycles_per_tick;
- st.step_count = st.exec_segment->n_step; // NOTE: Can sometimes be zero when moving slow.
- // If the new segment starts a new planner block, initialize stepper variables and counters.
- // NOTE: When the segment data index changes, this indicates a new planner block.
- if ( st.exec_block_index != st.exec_segment->st_block_index ) {
- st.exec_block_index = st.exec_segment->st_block_index;
- st.exec_block = &st_block_buffer[st.exec_block_index];
-
- // Initialize Bresenham line and distance counters
- st.counter_x = st.counter_y = st.counter_z = (st.exec_block->step_event_count >> 1);
- }
- st.dir_outbits = st.exec_block->direction_bits ^ dir_port_invert_mask;
-
- #ifdef ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING
- // With AMASS enabled, adjust Bresenham axis increment counters according to AMASS level.
- st.steps[X_AXIS] = st.exec_block->steps[X_AXIS] >> st.exec_segment->amass_level;
- st.steps[Y_AXIS] = st.exec_block->steps[Y_AXIS] >> st.exec_segment->amass_level;
- st.steps[Z_AXIS] = st.exec_block->steps[Z_AXIS] >> st.exec_segment->amass_level;
- #endif
-
- } else {
- // Segment buffer empty. Shutdown.
- st_go_idle();
- system_set_exec_state_flag(EXEC_CYCLE_STOP); // Flag main program for cycle end
- return; // Nothing to do but exit.
- }
- }
-
-
- // Check probing state.
- probe_state_monitor();
-
- // Reset step out bits.
- st.step_outbits = 0;
-
- // Execute step displacement profile by Bresenham line algorithm
- #ifdef ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING
- st.counter_x += st.steps[X_AXIS];
- #else
- st.counter_x += st.exec_block->steps[X_AXIS];
- #endif
- if (st.counter_x > st.exec_block->step_event_count) {
- st.step_outbits |= (1<step_event_count;
- if (st.exec_block->direction_bits & (1<steps[Y_AXIS];
- #endif
- if (st.counter_y > st.exec_block->step_event_count) {
- st.step_outbits |= (1<step_event_count;
- if (st.exec_block->direction_bits & (1<steps[Z_AXIS];
- #endif
- if (st.counter_z > st.exec_block->step_event_count) {
- st.step_outbits |= (1<step_event_count;
- if (st.exec_block->direction_bits & (1< EXAMPLE: Block 2 entry speed is at max junction velocity
+
+ The planner block buffer is planned assuming constant acceleration velocity profiles and are
+ continuously joined at block junctions as shown above. However, the planner only actively computes
+ the block entry speeds for an optimal velocity plan, but does not compute the block internal
+ velocity profiles. These velocity profiles are computed ad-hoc as they are executed by the
+ stepper algorithm and consists of only 7 possible types of profiles: cruise-only, cruise-
+ deceleration, acceleration-cruise, acceleration-only, deceleration-only, full-trapezoid, and
+ triangle(no cruise).
+
+ maximum_speed (< nominal_speed) -> +
+ +--------+ <- maximum_speed (= nominal_speed) /|\
+ / \ / | \
+ current_speed -> + \ / | + <- exit_speed
+ | + <- exit_speed / | |
+ +-------------+ current_speed -> +----+--+
+ time --> ^ ^ ^ ^
+ | | | |
+ decelerate_after(in mm) decelerate_after(in mm)
+ ^ ^ ^ ^
+ | | | |
+ accelerate_until(in mm) accelerate_until(in mm)
+
+ The step segment buffer computes the executing block velocity profile and tracks the critical
+ parameters for the stepper algorithm to accurately trace the profile. These critical parameters
+ are shown and defined in the above illustration.
+*/
+// Stepper state initialization. Cycle should only start if the st.cycle_start flag is
+// enabled. Startup init and limits call this function but shouldn't start the cycle.
+void st_wake_up()
+{
+ // Enable stepper drivers.
+ if (bit_istrue(settings.flags,BITFLAG_INVERT_ST_ENABLE))
+ {
+ SetStepperDisableBit();
+ }
+ else
+ {
+ ResetStepperDisableBit();
+ }
+
+ // Initialize stepper output bits
+ st.dir_outbits = dir_port_invert_mask;
+ st.step_outbits = step_port_invert_mask;
+
+ // Initialize step pulse timing from settings. Here to ensure updating after re-writing.
+ #ifdef STEP_PULSE_DELAY
+ // Set total step pulse time after direction pin set. Ad hoc computation from oscilloscope.
+ st.step_pulse_time = -(((settings.pulse_microseconds+STEP_PULSE_DELAY-2)*TICKS_PER_MICROSECOND) >> 3);
+ // Set delay between direction pin write and step command.
+ OCR0A = -(((settings.pulse_microseconds)*TICKS_PER_MICROSECOND) >> 3);
+ #else // Normal operation
+ // Set step pulse time. Ad hoc computation from oscilloscope. Uses two's complement.
+#ifdef AVRTARGET
+ st.step_pulse_time = -(((settings.pulse_microseconds-2)*TICKS_PER_MICROSECOND) >> 3);
+#elif defined (WIN32)
+ st.step_pulse_time = (settings.pulse_microseconds)*TICKS_PER_MICROSECOND;
+#elif defined (STM32F103C8)
+ st.step_pulse_time = (settings.pulse_microseconds)*TICKS_PER_MICROSECOND;
+#else
+#error not defined
+#endif
+ #endif
+
+#ifdef AVRTARGET
+ // Enable Stepper Driver Interrupt
+ TIMSK1 |= (1<SR & 0x0001) != 0) // check interrupt source
+ {
+ TIM2->SR &= ~(1<<0); // clear UIF flag
+ TIM2->CNT = 0;
+ }
+ else
+ {
+ return;
+ }
+#endif
+// SPINDLE_ENABLE_PORT ^= 1<SR = (uint16_t)~TIM_IT_Update;
+#endif
+ NVIC_EnableIRQ(TIM3_IRQn);
+#endif
+ busy = true;
+#ifdef AVRTARGET
+ sei(); // Re-enable interrupts to allow Stepper Port Reset Interrupt to fire on-time.
+ // NOTE: The remaining code in this ISR will finish before returning to main program.
+#endif
+ // If there is no step segment, attempt to pop one from the stepper buffer
+ if (st.exec_segment == NULL) {
+ // Anything in the buffer? If so, load and initialize next step segment.
+ if (segment_buffer_head != segment_buffer_tail) {
+ // Initialize new step segment and load number of steps to execute
+ st.exec_segment = &segment_buffer[segment_buffer_tail];
+
+ #ifndef ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING
+ // With AMASS is disabled, set timer prescaler for segments with slow step frequencies (< 250Hz).
+ TCCR1B = (TCCR1B & ~(0x07<prescaler<cycles_per_tick;
+#endif
+#ifdef WIN32
+ nTimer1Out = st.exec_segment->cycles_per_tick;
+#endif
+#ifdef STM32F103C8
+ TIM2->ARR = st.exec_segment->cycles_per_tick - 1;
+#endif
+ st.step_count = st.exec_segment->n_step; // NOTE: Can sometimes be zero when moving slow.
+ // If the new segment starts a new planner block, initialize stepper variables and counters.
+ // NOTE: When the segment data index changes, this indicates a new planner block.
+ if ( st.exec_block_index != st.exec_segment->st_block_index ) {
+ st.exec_block_index = st.exec_segment->st_block_index;
+ st.exec_block = &st_block_buffer[st.exec_block_index];
+
+ // Initialize Bresenham line and distance counters
+ st.counter_x = st.counter_y = st.counter_z = (st.exec_block->step_event_count >> 1);
+ }
+ st.dir_outbits = st.exec_block->direction_bits ^ dir_port_invert_mask;
+
+ #ifdef ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING
+ // With AMASS enabled, adjust Bresenham axis increment counters according to AMASS level.
+ st.steps[X_AXIS] = st.exec_block->steps[X_AXIS] >> st.exec_segment->amass_level;
+ st.steps[Y_AXIS] = st.exec_block->steps[Y_AXIS] >> st.exec_segment->amass_level;
+ st.steps[Z_AXIS] = st.exec_block->steps[Z_AXIS] >> st.exec_segment->amass_level;
+ #endif
+
+ } else {
+ // Segment buffer empty. Shutdown.
+ st_go_idle();
+ system_set_exec_state_flag(EXEC_CYCLE_STOP); // Flag main program for cycle end
+ return; // Nothing to do but exit.
+ }
+ }
+
+
+ // Check probing state.
+ probe_state_monitor();
+
+ // Reset step out bits.
+ st.step_outbits = 0;
+
+ // Execute step displacement profile by Bresenham line algorithm
+ #ifdef ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING
+ st.counter_x += st.steps[X_AXIS];
+ #else
+ st.counter_x += st.exec_block->steps[X_AXIS];
+ #endif
+ if (st.counter_x > st.exec_block->step_event_count) {
+ st.step_outbits |= (1<step_event_count;
+ if (st.exec_block->direction_bits & (1<steps[Y_AXIS];
+ #endif
+ if (st.counter_y > st.exec_block->step_event_count) {
+ st.step_outbits |= (1<step_event_count;
+ if (st.exec_block->direction_bits & (1<steps[Z_AXIS];
+ #endif
+ if (st.counter_z > st.exec_block->step_event_count) {
+ st.step_outbits |= (1<step_event_count;
+ if (st.exec_block->direction_bits & (1<SR & 0x0001) != 0) // check interrupt source
+ {
+ TIM3->SR &= ~(1<<0); // clear UIF flag
+ TIM3->CNT = 0;
+ NVIC_DisableIRQ(TIM3_IRQn);
+ GPIO_Write(STEP_PORT,(GPIO_ReadOutputData(STEP_PORT) & ~STEP_MASK) | (step_port_invert_mask & STEP_MASK));
+ }
+#endif
+#ifdef AVRTARGET
+ // Reset stepping pins (leave the direction pins)
+ STEP_PORT = (STEP_PORT & ~STEP_MASK) | (step_port_invert_mask & STEP_MASK);
+ TCCR0B = 0; // Disable Timer0 to prevent re-entering this interrupt when it's not needed.
+#endif
+#ifdef WIN32
+ nTimer0Out = 0;
+#endif
+}
+#ifdef STEP_PULSE_DELAY
+ // This interrupt is used only when STEP_PULSE_DELAY is enabled. Here, the step pulse is
+ // initiated after the STEP_PULSE_DELAY time period has elapsed. The ISR TIMER2_OVF interrupt
+ // will then trigger after the appropriate settings.pulse_microseconds, as in normal operation.
+ // The new timing between direction, step pulse, and step complete events are setup in the
+ // st_wake_up() routine.
+ ISR(TIMER0_COMPA_vect)
+ {
+ STEP_PORT = st.step_bits; // Begin step pulse.
+ }
+#endif
+#ifdef WIN32
+DWORD WINAPI Timer1Thread(LPVOID lpParameter)
+{
+ LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;
+
+ for (;;)
+ {
+ while (nTimer1Out == 0)
+ Sleep(0);
+ QueryPerformanceCounter(&StartingTime);
+ do
+ {
+ QueryPerformanceCounter(&EndingTime);
+ ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;
+ } while (ElapsedMicroseconds.QuadPart < nTimer1Out);
+ Timer1Proc();
+ }
+ return 0;
+}
+
+DWORD WINAPI Timer0Thread(LPVOID lpParameter)
+{
+ LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;
+
+ for (;;)
+ {
+ while (nTimer0Out == 0)
+ Sleep(0);
+ QueryPerformanceCounter(&StartingTime);
+ do
+ {
+ QueryPerformanceCounter(&EndingTime);
+ ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;
+ } while (ElapsedMicroseconds.QuadPart < nTimer0Out);
+ Timer0Proc();
+ }
+ return 0;
+}
+
+#endif
+
+// Generates the step and direction port invert masks used in the Stepper Interrupt Driver.
+void st_generate_step_dir_invert_masks()
+{
+ uint8_t idx;
+ step_port_invert_mask = 0;
+ dir_port_invert_mask = 0;
+ for (idx=0; idxAPB1ENR |= RCC_APB1Periph_TIM2;
+ TIM_Configuration(TIM2,1,1,1);
+ RCC->APB1ENR |= RCC_APB1Periph_TIM3;
+ TIM_Configuration(TIM3,st.step_pulse_time,1,0); // just initialize it
+ NVIC_DisableIRQ(TIM3_IRQn);
+ NVIC_DisableIRQ(TIM2_IRQn);
+#endif
+#ifdef AVRTARGET
+ STEP_DDR |= STEP_MASK;
+ DIRECTION_DDR |= DIRECTION_MASK;
+
+ // Configure Timer 1: Stepper Driver Interrupt
+ TCCR1B &= ~(1<entry_speed_sqr = prep.current_speed*prep.current_speed; // Update entry speed.
+ pl_block->entry_speed_sqr = prep.current_speed*prep.current_speed; // Update entry speed.
pl_block = NULL; // Flag st_prep_segment() to load and check active velocity profile.
- }
-}
-
-
+ }
+}
+
// Increments the step segment buffer block data ring buffer.
static uint8_t st_next_block_index(uint8_t block_index)
{
@@ -523,7 +741,6 @@ static uint8_t st_next_block_index(uint8_t block_index)
return(block_index);
}
-
#ifdef PARKING_ENABLE
// Changes the run state of the step segment buffer to execute the special parking motion.
void st_parking_setup_buffer()
@@ -562,29 +779,47 @@ static uint8_t st_next_block_index(uint8_t block_index)
}
#endif
-
-/* Prepares step segment buffer. Continuously called from main program.
-
- The segment buffer is an intermediary buffer interface between the execution of steps
- by the stepper algorithm and the velocity profiles generated by the planner. The stepper
- algorithm only executes steps within the segment buffer and is filled by the main program
- when steps are "checked-out" from the first block in the planner buffer. This keeps the
- step execution and planning optimization processes atomic and protected from each other.
- The number of steps "checked-out" from the planner buffer and the number of segments in
- the segment buffer is sized and computed such that no operation in the main program takes
- longer than the time it takes the stepper algorithm to empty it before refilling it.
- Currently, the segment buffer conservatively holds roughly up to 40-50 msec of steps.
- NOTE: Computation units are in steps, millimeters, and minutes.
-*/
-void st_prep_buffer()
-{
+/* Prepares step segment buffer. Continuously called from main program.
+
+ The segment buffer is an intermediary buffer interface between the execution of steps
+ by the stepper algorithm and the velocity profiles generated by the planner. The stepper
+ algorithm only executes steps within the segment buffer and is filled by the main program
+ when steps are "checked-out" from the first block in the planner buffer. This keeps the
+ step execution and planning optimization processes atomic and protected from each other.
+ The number of steps "checked-out" from the planner buffer and the number of segments in
+ the segment buffer is sized and computed such that no operation in the main program takes
+ longer than the time it takes the stepper algorithm to empty it before refilling it.
+ Currently, the segment buffer conservatively holds roughly up to 40-50 msec of steps.
+ NOTE: Computation units are in steps, millimeters, and minutes.
+*/
+void st_prep_buffer()
+{
+ float inv_2_accel;
+ float decel_dist;
+ segment_t *prep_segment;
+ float dt_max; // Maximum segment time
+ float dt; // Initialize segment time
+ float time_var; // Time worker variable
+ float mm_var; // mm-Distance worker variable
+ float speed_var; // Speed worker variable
+ float mm_remaining; // New segment distance from end of block.
+ float minimum_mm; // Guarantee at least one step.
+ float step_dist_remaining; // Convert mm_remaining to steps
+ float n_steps_remaining; // Round-up current steps remaining
+ float last_n_steps_remaining; // Round-up last steps remaining
+ float inv_rate;
+ uint32_t cycles;
+ uint8_t idx;
+ float exit_speed_sqr;
+ float intersect_distance;
+
// Block step prep buffer, while in a suspend state and there is no suspend motion to execute.
if (bit_istrue(sys.step_control,STEP_CONTROL_END_MOTION)) { return; }
-
- while (segment_buffer_tail != segment_next_head) { // Check if we need to fill the buffer.
-
- // Determine if we need to load a new planner block or if the block needs to be recomputed.
- if (pl_block == NULL) {
+
+ while (segment_buffer_tail != segment_next_head) { // Check if we need to fill the buffer.
+
+ // Determine if we need to load a new planner block or if the block needs to be recomputed.
+ if (pl_block == NULL) {
#ifdef PARKING_ENABLE
@@ -624,7 +859,6 @@ void st_prep_buffer()
// segment buffer finishes the prepped block, but the stepper ISR is still executing it.
st_prep_block = &st_block_buffer[prep.st_block_index];
st_prep_block->direction_bits = pl_block->direction_bits;
- uint8_t idx;
#ifndef ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING
for (idx=0; idxsteps[idx] = pl_block->steps[idx]; }
st_prep_block->step_event_count = pl_block->step_event_count;
@@ -658,13 +892,13 @@ void st_prep_buffer()
hold, override the planner velocities and decelerate to the target exit speed.
*/
prep.mm_complete = 0.0; // Default velocity profile complete at 0.0mm from end of block.
- float inv_2_accel = 0.5/pl_block->acceleration;
+ inv_2_accel = 0.5/pl_block->acceleration;
if (sys.step_control & STEP_CONTROL_EXECUTE_HOLD) { // [Forced Deceleration to Zero Velocity]
// Compute velocity profile parameters for a feed hold in-progress. This profile overrides
// the planner block profile, enforcing a deceleration to zero speed.
prep.ramp_type = RAMP_DECEL;
// Compute decelerate distance relative to end of block.
- float decel_dist = pl_block->millimeters - inv_2_accel*pl_block->entry_speed_sqr;
+ decel_dist = pl_block->millimeters - inv_2_accel*pl_block->entry_speed_sqr;
if (decel_dist < 0.0) {
// Deceleration through entire planner block. End of feed hold is not in this block.
prep.exit_speed = sqrt(pl_block->entry_speed_sqr-2*pl_block->acceleration*pl_block->millimeters);
@@ -684,8 +918,8 @@ void st_prep_buffer()
prep.exit_speed = plan_get_exec_block_exit_speed();
#endif
- float exit_speed_sqr = prep.exit_speed*prep.exit_speed;
- float intersect_distance =
+ exit_speed_sqr = prep.exit_speed*prep.exit_speed;
+ intersect_distance =
0.5*(pl_block->millimeters+inv_2_accel*(pl_block->entry_speed_sqr-exit_speed_sqr));
if (intersect_distance > 0.0) {
if (intersect_distance < pl_block->millimeters) { // Either trapezoid or triangle types
@@ -716,177 +950,175 @@ void st_prep_buffer()
prep.maximum_speed = prep.exit_speed;
}
}
- }
-
- // Initialize new segment
- segment_t *prep_segment = &segment_buffer[segment_buffer_head];
-
- // Set new segment to point to the current segment data block.
- prep_segment->st_block_index = prep.st_block_index;
-
- /*------------------------------------------------------------------------------------
- Compute the average velocity of this new segment by determining the total distance
- traveled over the segment time DT_SEGMENT. The following code first attempts to create
- a full segment based on the current ramp conditions. If the segment time is incomplete
- when terminating at a ramp state change, the code will continue to loop through the
- progressing ramp states to fill the remaining segment execution time. However, if
- an incomplete segment terminates at the end of the velocity profile, the segment is
- considered completed despite having a truncated execution time less than DT_SEGMENT.
- The velocity profile is always assumed to progress through the ramp sequence:
- acceleration ramp, cruising state, and deceleration ramp. Each ramp's travel distance
- may range from zero to the length of the block. Velocity profiles can end either at
- the end of planner block (typical) or mid-block at the end of a forced deceleration,
- such as from a feed hold.
- */
- float dt_max = DT_SEGMENT; // Maximum segment time
- float dt = 0.0; // Initialize segment time
- float time_var = dt_max; // Time worker variable
- float mm_var; // mm-Distance worker variable
- float speed_var; // Speed worker variable
- float mm_remaining = pl_block->millimeters; // New segment distance from end of block.
- float minimum_mm = mm_remaining-prep.req_mm_increment; // Guarantee at least one step.
- if (minimum_mm < 0.0) { minimum_mm = 0.0; }
-
- do {
- switch (prep.ramp_type) {
- case RAMP_ACCEL:
- // NOTE: Acceleration ramp only computes during first do-while loop.
- speed_var = pl_block->acceleration*time_var;
- mm_remaining -= time_var*(prep.current_speed + 0.5*speed_var);
- if (mm_remaining < prep.accelerate_until) { // End of acceleration ramp.
- // Acceleration-cruise, acceleration-deceleration ramp junction, or end of block.
- mm_remaining = prep.accelerate_until; // NOTE: 0.0 at EOB
- time_var = 2.0*(pl_block->millimeters-mm_remaining)/(prep.current_speed+prep.maximum_speed);
- if (mm_remaining == prep.decelerate_after) { prep.ramp_type = RAMP_DECEL; }
- else { prep.ramp_type = RAMP_CRUISE; }
- prep.current_speed = prep.maximum_speed;
- } else { // Acceleration only.
- prep.current_speed += speed_var;
- }
- break;
- case RAMP_CRUISE:
- // NOTE: mm_var used to retain the last mm_remaining for incomplete segment time_var calculations.
- // NOTE: If maximum_speed*time_var value is too low, round-off can cause mm_var to not change. To
- // prevent this, simply enforce a minimum speed threshold in the planner.
- mm_var = mm_remaining - prep.maximum_speed*time_var;
- if (mm_var < prep.decelerate_after) { // End of cruise.
- // Cruise-deceleration junction or end of block.
- time_var = (mm_remaining - prep.decelerate_after)/prep.maximum_speed;
- mm_remaining = prep.decelerate_after; // NOTE: 0.0 at EOB
- prep.ramp_type = RAMP_DECEL;
- } else { // Cruising only.
- mm_remaining = mm_var;
- }
- break;
- default: // case RAMP_DECEL:
- // NOTE: mm_var used as a misc worker variable to prevent errors when near zero speed.
- speed_var = pl_block->acceleration*time_var; // Used as delta speed (mm/min)
- if (prep.current_speed > speed_var) { // Check if at or below zero speed.
- // Compute distance from end of segment to end of block.
- mm_var = mm_remaining - time_var*(prep.current_speed - 0.5*speed_var); // (mm)
+ }
+
+ // Initialize new segment
+ prep_segment = &segment_buffer[segment_buffer_head];
+
+ // Set new segment to point to the current segment data block.
+ prep_segment->st_block_index = prep.st_block_index;
+
+ /*------------------------------------------------------------------------------------
+ Compute the average velocity of this new segment by determining the total distance
+ traveled over the segment time DT_SEGMENT. The following code first attempts to create
+ a full segment based on the current ramp conditions. If the segment time is incomplete
+ when terminating at a ramp state change, the code will continue to loop through the
+ progressing ramp states to fill the remaining segment execution time. However, if
+ an incomplete segment terminates at the end of the velocity profile, the segment is
+ considered completed despite having a truncated execution time less than DT_SEGMENT.
+ The velocity profile is always assumed to progress through the ramp sequence:
+ acceleration ramp, cruising state, and deceleration ramp. Each ramp's travel distance
+ may range from zero to the length of the block. Velocity profiles can end either at
+ the end of planner block (typical) or mid-block at the end of a forced deceleration,
+ such as from a feed hold.
+ */
+ dt_max = (float)DT_SEGMENT; // Maximum segment time
+ dt = (float)0.0; // Initialize segment time
+ time_var = dt_max; // Time worker variable
+ mm_remaining = pl_block->millimeters; // New segment distance from end of block.
+ minimum_mm = mm_remaining-prep.req_mm_increment; // Guarantee at least one step.
+ if (minimum_mm < 0.0) { minimum_mm = 0.0; }
+
+ do {
+ switch (prep.ramp_type) {
+ case RAMP_ACCEL:
+ // NOTE: Acceleration ramp only computes during first do-while loop.
+ speed_var = pl_block->acceleration*time_var;
+ mm_remaining -= (float)(time_var*(prep.current_speed + 0.5*speed_var));
+ if (mm_remaining < prep.accelerate_until) { // End of acceleration ramp.
+ // Acceleration-cruise, acceleration-deceleration ramp junction, or end of block.
+ mm_remaining = prep.accelerate_until; // NOTE: 0.0 at EOB
+ time_var = (float)(2.0*(pl_block->millimeters-mm_remaining)/(prep.current_speed+prep.maximum_speed));
+ if (mm_remaining == prep.decelerate_after) { prep.ramp_type = RAMP_DECEL; }
+ else { prep.ramp_type = RAMP_CRUISE; }
+ prep.current_speed = prep.maximum_speed;
+ } else { // Acceleration only.
+ prep.current_speed += speed_var;
+ }
+ break;
+ case RAMP_CRUISE:
+ // NOTE: mm_var used to retain the last mm_remaining for incomplete segment time_var calculations.
+ // NOTE: If maximum_speed*time_var value is too low, round-off can cause mm_var to not change. To
+ // prevent this, simply enforce a minimum speed threshold in the planner.
+ mm_var = mm_remaining - prep.maximum_speed*time_var;
+ if (mm_var < prep.decelerate_after) { // End of cruise.
+ // Cruise-deceleration junction or end of block.
+ time_var = (mm_remaining - prep.decelerate_after)/prep.maximum_speed;
+ mm_remaining = prep.decelerate_after; // NOTE: 0.0 at EOB
+ prep.ramp_type = RAMP_DECEL;
+ } else { // Cruising only.
+ mm_remaining = mm_var;
+ }
+ break;
+ default: // case RAMP_DECEL:
+ // NOTE: mm_var used as a misc worker variable to prevent errors when near zero speed.
+ speed_var = pl_block->acceleration*time_var; // Used as delta speed (mm/min)
+ if (prep.current_speed > speed_var) { // Check if at or below zero speed.
+ // Compute distance from end of segment to end of block.
+ mm_var = (float)(mm_remaining - time_var*(prep.current_speed - 0.5*speed_var)); // (mm)
if (mm_var > prep.mm_complete) { // Typical case. In deceleration ramp.
- mm_remaining = mm_var;
- prep.current_speed -= speed_var;
- break; // Segment complete. Exit switch-case statement. Continue do-while loop.
- }
+ mm_remaining = mm_var;
+ prep.current_speed -= speed_var;
+ break; // Segment complete. Exit switch-case statement. Continue do-while loop.
+ }
}
// Otherwise, at end of block or end of forced-deceleration.
- time_var = 2.0*(mm_remaining-prep.mm_complete)/(prep.current_speed+prep.exit_speed);
- mm_remaining = prep.mm_complete;
+ time_var = (float)(2.0*(mm_remaining-prep.mm_complete)/(prep.current_speed+prep.exit_speed));
+ mm_remaining = prep.mm_complete;
prep.current_speed = prep.exit_speed;
- }
- dt += time_var; // Add computed ramp time to total segment time.
- if (dt < dt_max) { time_var = dt_max - dt; } // **Incomplete** At ramp junction.
- else {
- if (mm_remaining > minimum_mm) { // Check for very slow segments with zero steps.
- // Increase segment time to ensure at least one step in segment. Override and loop
- // through distance calculations until minimum_mm or mm_complete.
- dt_max += DT_SEGMENT;
- time_var = dt_max - dt;
- } else {
- break; // **Complete** Exit loop. Segment execution time maxed.
- }
- }
- } while (mm_remaining > prep.mm_complete); // **Complete** Exit loop. Profile complete.
-
-
- /* -----------------------------------------------------------------------------------
- Compute segment step rate, steps to execute, and apply necessary rate corrections.
- NOTE: Steps are computed by direct scalar conversion of the millimeter distance
- remaining in the block, rather than incrementally tallying the steps executed per
- segment. This helps in removing floating point round-off issues of several additions.
- However, since floats have only 7.2 significant digits, long moves with extremely
- high step counts can exceed the precision of floats, which can lead to lost steps.
- Fortunately, this scenario is highly unlikely and unrealistic in CNC machines
- supported by Grbl (i.e. exceeding 10 meters axis travel at 200 step/mm).
- */
- float step_dist_remaining = prep.step_per_mm*mm_remaining; // Convert mm_remaining to steps
- float n_steps_remaining = ceil(step_dist_remaining); // Round-up current steps remaining
- float last_n_steps_remaining = ceil(prep.steps_remaining); // Round-up last steps remaining
- prep_segment->n_step = last_n_steps_remaining-n_steps_remaining; // Compute number of steps to execute.
-
- // Bail if we are at the end of a feed hold and don't have a step to execute.
- if (prep_segment->n_step == 0) {
+ }
+ dt += time_var; // Add computed ramp time to total segment time.
+ if (dt < dt_max) { time_var = dt_max - dt; } // **Incomplete** At ramp junction.
+ else {
+ if (mm_remaining > minimum_mm) { // Check for very slow segments with zero steps.
+ // Increase segment time to ensure at least one step in segment. Override and loop
+ // through distance calculations until minimum_mm or mm_complete.
+ dt_max += (float)DT_SEGMENT;
+ time_var = dt_max - dt;
+ } else {
+ break; // **Complete** Exit loop. Segment execution time maxed.
+ }
+ }
+ } while (mm_remaining > prep.mm_complete); // **Complete** Exit loop. Profile complete.
+
+
+ /* -----------------------------------------------------------------------------------
+ Compute segment step rate, steps to execute, and apply necessary rate corrections.
+ NOTE: Steps are computed by direct scalar conversion of the millimeter distance
+ remaining in the block, rather than incrementally tallying the steps executed per
+ segment. This helps in removing floating point round-off issues of several additions.
+ However, since floats have only 7.2 significant digits, long moves with extremely
+ high step counts can exceed the precision of floats, which can lead to lost steps.
+ Fortunately, this scenario is highly unlikely and unrealistic in CNC machines
+ supported by Grbl (i.e. exceeding 10 meters axis travel at 200 step/mm).
+ */
+ step_dist_remaining = prep.step_per_mm*mm_remaining; // Convert mm_remaining to steps
+ n_steps_remaining = ceil(step_dist_remaining); // Round-up current steps remaining
+ last_n_steps_remaining = (float)ceil(prep.steps_remaining); // Round-up last steps remaining
+ prep_segment->n_step = (uint16_t)(last_n_steps_remaining-n_steps_remaining); // Compute number of steps to execute.
+
+ // Bail if we are at the end of a feed hold and don't have a step to execute.
+ if (prep_segment->n_step == 0) {
if (sys.step_control & STEP_CONTROL_EXECUTE_HOLD) {
- // Less than one step to decelerate to zero speed, but already very close. AMASS
- // requires full steps to execute. So, just bail.
+ // Less than one step to decelerate to zero speed, but already very close. AMASS
+ // requires full steps to execute. So, just bail.
bit_true(sys.step_control,STEP_CONTROL_END_MOTION);
#ifdef PARKING_ENABLE
if (!(prep.recalculate_flag & PREP_FLAG_PARKING)) { prep.recalculate_flag |= PREP_FLAG_HOLD_PARTIAL_BLOCK; }
#endif
- return; // Segment not generated, but current step data still retained.
- }
- }
-
- // Compute segment step rate. Since steps are integers and mm distances traveled are not,
- // the end of every segment can have a partial step of varying magnitudes that are not
- // executed, because the stepper ISR requires whole steps due to the AMASS algorithm. To
- // compensate, we track the time to execute the previous segment's partial step and simply
- // apply it with the partial step distance to the current segment, so that it minutely
- // adjusts the whole segment rate to keep step output exact. These rate adjustments are
- // typically very small and do not adversely effect performance, but ensures that Grbl
- // outputs the exact acceleration and velocity profiles as computed by the planner.
- dt += prep.dt_remainder; // Apply previous segment partial step execute time
- float inv_rate = dt/(last_n_steps_remaining - step_dist_remaining); // Compute adjusted step rate inverse
-
- // Compute CPU cycles per step for the prepped segment.
- uint32_t cycles = ceil( (TICKS_PER_MICROSECOND*1000000*60)*inv_rate ); // (cycles/step)
-
- #ifdef ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING
- // Compute step timing and multi-axis smoothing level.
- // NOTE: AMASS overdrives the timer with each level, so only one prescalar is required.
- if (cycles < AMASS_LEVEL1) { prep_segment->amass_level = 0; }
- else {
- if (cycles < AMASS_LEVEL2) { prep_segment->amass_level = 1; }
- else if (cycles < AMASS_LEVEL3) { prep_segment->amass_level = 2; }
- else { prep_segment->amass_level = 3; }
- cycles >>= prep_segment->amass_level;
- prep_segment->n_step <<= prep_segment->amass_level;
- }
- if (cycles < (1UL << 16)) { prep_segment->cycles_per_tick = cycles; } // < 65536 (4.1ms @ 16MHz)
- else { prep_segment->cycles_per_tick = 0xffff; } // Just set the slowest speed possible.
- #else
- // Compute step timing and timer prescalar for normal step generation.
- if (cycles < (1UL << 16)) { // < 65536 (4.1ms @ 16MHz)
- prep_segment->prescaler = 1; // prescaler: 0
- prep_segment->cycles_per_tick = cycles;
- } else if (cycles < (1UL << 19)) { // < 524288 (32.8ms@16MHz)
- prep_segment->prescaler = 2; // prescaler: 8
- prep_segment->cycles_per_tick = cycles >> 3;
- } else {
- prep_segment->prescaler = 3; // prescaler: 64
- if (cycles < (1UL << 22)) { // < 4194304 (262ms@16MHz)
- prep_segment->cycles_per_tick = cycles >> 6;
- } else { // Just set the slowest speed possible. (Around 4 step/sec.)
- prep_segment->cycles_per_tick = 0xffff;
- }
- }
- #endif
-
+ return; // Segment not generated, but current step data still retained.
+ }
+ }
+
+ // Compute segment step rate. Since steps are integers and mm distances traveled are not,
+ // the end of every segment can have a partial step of varying magnitudes that are not
+ // executed, because the stepper ISR requires whole steps due to the AMASS algorithm. To
+ // compensate, we track the time to execute the previous segment's partial step and simply
+ // apply it with the partial step distance to the current segment, so that it minutely
+ // adjusts the whole segment rate to keep step output exact. These rate adjustments are
+ // typically very small and do not adversely effect performance, but ensures that Grbl
+ // outputs the exact acceleration and velocity profiles as computed by the planner.
+ dt += prep.dt_remainder; // Apply previous segment partial step execute time
+ inv_rate = dt/(last_n_steps_remaining - step_dist_remaining); // Compute adjusted step rate inverse
+
+ // Compute CPU cycles per step for the prepped segment.
+ cycles = (uint32_t)ceil( ((float)TICKS_PER_MICROSECOND*1000000*60)*inv_rate ); // (cycles/step)
+
+ #ifdef ADAPTIVE_MULTI_AXIS_STEP_SMOOTHING
+ // Compute step timing and multi-axis smoothing level.
+ // NOTE: AMASS overdrives the timer with each level, so only one prescalar is required.
+ if (cycles < AMASS_LEVEL1) { prep_segment->amass_level = 0; }
+ else {
+ if (cycles < AMASS_LEVEL2) { prep_segment->amass_level = 1; }
+ else if (cycles < AMASS_LEVEL3) { prep_segment->amass_level = 2; }
+ else { prep_segment->amass_level = 3; }
+ cycles >>= prep_segment->amass_level;
+ prep_segment->n_step <<= prep_segment->amass_level;
+ }
+ if (cycles < (1UL << 16)) { prep_segment->cycles_per_tick = cycles; } // < 65536 (4.1ms @ 16MHz)
+ else { prep_segment->cycles_per_tick = 0xffff; } // Just set the slowest speed possible.
+ #else
+ // Compute step timing and timer prescalar for normal step generation.
+ if (cycles < (1UL << 16)) { // < 65536 (4.1ms @ 16MHz)
+ prep_segment->prescaler = 1; // prescaler: 0
+ prep_segment->cycles_per_tick = cycles;
+ } else if (cycles < (1UL << 19)) { // < 524288 (32.8ms@16MHz)
+ prep_segment->prescaler = 2; // prescaler: 8
+ prep_segment->cycles_per_tick = cycles >> 3;
+ } else {
+ prep_segment->prescaler = 3; // prescaler: 64
+ if (cycles < (1UL << 22)) { // < 4194304 (262ms@16MHz)
+ prep_segment->cycles_per_tick = cycles >> 6;
+ } else { // Just set the slowest speed possible. (Around 4 step/sec.)
+ prep_segment->cycles_per_tick = 0xffff;
+ }
+ }
+ #endif
+
// Segment complete! Increment segment buffer indices, so stepper ISR can immediately execute it.
- segment_buffer_head = segment_next_head;
- if ( ++segment_next_head == SEGMENT_BUFFER_SIZE ) { segment_next_head = 0; }
-
+ segment_buffer_head = segment_next_head;
+ if ( ++segment_next_head == SEGMENT_BUFFER_SIZE ) { segment_next_head = 0; }
+
// Update the appropriate planner and segment data.
pl_block->millimeters = mm_remaining;
prep.steps_remaining = n_steps_remaining;
@@ -894,38 +1126,66 @@ void st_prep_buffer()
// Check for exit conditions and flag to load next planner block.
if (mm_remaining == prep.mm_complete) {
- // End of planner block or forced-termination. No more distance to be executed.
- if (mm_remaining > 0.0) { // At end of forced-termination.
- // Reset prep parameters for resuming and then bail. Allow the stepper ISR to complete
- // the segment queue, where realtime protocol will set new state upon receiving the
- // cycle stop flag from the ISR. Prep_segment is blocked until then.
+ // End of planner block or forced-termination. No more distance to be executed.
+ if (mm_remaining > 0.0) { // At end of forced-termination.
+ // Reset prep parameters for resuming and then bail. Allow the stepper ISR to complete
+ // the segment queue, where realtime protocol will set new state upon receiving the
+ // cycle stop flag from the ISR. Prep_segment is blocked until then.
bit_true(sys.step_control,STEP_CONTROL_END_MOTION);
#ifdef PARKING_ENABLE
if (!(prep.recalculate_flag & PREP_FLAG_PARKING)) { prep.recalculate_flag |= PREP_FLAG_HOLD_PARTIAL_BLOCK; }
#endif
- return; // Bail!
- } else { // End of planner block
- // The planner block is complete. All steps are set to be executed in the segment buffer.
+ return; // Bail!
+ } else { // End of planner block
+ // The planner block is complete. All steps are set to be executed in the segment buffer.
#ifdef PARKING_ENABLE
if (sys.step_control & STEP_CONTROL_EXECUTE_PARK) {
bit_true(sys.step_control,STEP_CONTROL_END_MOTION);
return;
}
#endif
- pl_block = NULL; // Set pointer to indicate check and load next planner block.
- plan_discard_current_block();
- }
- }
-
- }
-}
-
-
-// Called by realtime status reporting to fetch the current speed being executed. This value
-// however is not exactly the current speed, but the speed computed in the last step segment
-// in the segment buffer. It will always be behind by up to the number of segment blocks (-1)
-// divided by the ACCELERATION TICKS PER SECOND in seconds.
+ pl_block = NULL; // Set pointer to indicate check and load next planner block.
+ plan_discard_current_block();
+ }
+ }
+
+ }
+}
+
+
+// Called by realtime status reporting to fetch the current speed being executed. This value
+// however is not exactly the current speed, but the speed computed in the last step segment
+// in the segment buffer. It will always be behind by up to the number of segment blocks (-1)
+// divided by the ACCELERATION TICKS PER SECOND in seconds.
float st_get_realtime_rate()
{
return prep.current_speed;
}
+
+#ifdef STM32F103C8
+ void TIM_Configuration(TIM_TypeDef* TIMER,u16 Period,u16 Prescaler,u8 PP)
+ {
+ TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
+ NVIC_InitTypeDef NVIC_InitStructure;
+
+ TIM_TimeBaseStructure.TIM_Period = Period-1;
+ TIM_TimeBaseStructure.TIM_Prescaler =Prescaler-1;
+ TIM_TimeBaseStructure.TIM_ClockDivision = 0;
+ TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
+ TIM_TimeBaseInit(TIMER, &TIM_TimeBaseStructure);
+
+ TIM_ClearITPendingBit(TIMER, TIM_IT_Update);
+ TIM_ITConfig(TIMER, TIM_IT_Update, ENABLE);
+ TIM_Cmd(TIMER, ENABLE);
+
+ NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);
+ if(TIMER==TIM2){NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;}
+ else if(TIMER==TIM3){NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;}
+ else if(TIMER==TIM4){NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;}
+
+ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority =PP;
+ NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
+ NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
+ NVIC_Init(&NVIC_InitStructure);
+ }
+#endif
diff --git a/grbl/stepper.h b/grbl/stepper.h
index 55fd13dcf..cdfa4e51b 100644
--- a/grbl/stepper.h
+++ b/grbl/stepper.h
@@ -40,13 +40,13 @@ void st_generate_step_dir_invert_masks();
// Reset the stepper subsystem variables
void st_reset();
-
+#ifdef PARKING_ENABLE
// Changes the run state of the step segment buffer to execute the special parking motion.
void st_parking_setup_buffer();
// Restores the step segment buffer to the normal run state after a parking motion.
void st_parking_restore_buffer();
-
+#endif
// Reloads step segment buffer. Called continuously by realtime execution system.
void st_prep_buffer();
diff --git a/grbl/stm32grbl/cmsis/core_cm3.h b/grbl/stm32grbl/cmsis/core_cm3.h
new file mode 100755
index 000000000..db1716ad9
--- /dev/null
+++ b/grbl/stm32grbl/cmsis/core_cm3.h
@@ -0,0 +1,1612 @@
+/**************************************************************************//**
+ * @file core_cm3.h
+ * @brief CMSIS Cortex-M3 Core Peripheral Access Layer Header File
+ * @version V3.01
+ * @date 22. March 2012
+ *
+ * @note
+ * Copyright (C) 2009-2012 ARM Limited. All rights reserved.
+ *
+ * @par
+ * ARM Limited (ARM) is supplying this software for use with Cortex-M
+ * processor based microcontrollers. This file can be freely distributed
+ * within development tools that are supporting such ARM based processors.
+ *
+ * @par
+ * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
+ * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
+ * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR
+ * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
+ *
+ ******************************************************************************/
+#if defined ( __ICCARM__ )
+ #pragma system_include /* treat file as system include file for MISRA check */
+#endif
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#ifndef __CORE_CM3_H_GENERIC
+#define __CORE_CM3_H_GENERIC
+
+/** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions
+ CMSIS violates the following MISRA-C:2004 rules:
+
+ \li Required Rule 8.5, object/function definition in header file.
+ Function definitions in header files are used to allow 'inlining'.
+
+ \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.
+ Unions are used for effective representation of core registers.
+
+ \li Advisory Rule 19.7, Function-like macro defined.
+ Function-like macros are used to allow more efficient code.
+ */
+
+
+/*******************************************************************************
+ * CMSIS definitions
+ ******************************************************************************/
+/** \ingroup Cortex_M3
+ @{
+ */
+
+/* CMSIS CM3 definitions */
+#define __CM3_CMSIS_VERSION_MAIN (0x03) /*!< [31:16] CMSIS HAL main version */
+#define __CM3_CMSIS_VERSION_SUB (0x01) /*!< [15:0] CMSIS HAL sub version */
+#define __CM3_CMSIS_VERSION ((__CM3_CMSIS_VERSION_MAIN << 16) | \
+ __CM3_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */
+
+#define __CORTEX_M (0x03) /*!< Cortex-M Core */
+
+
+#if defined ( __CC_ARM )
+ #define __ASM __asm /*!< asm keyword for ARM Compiler */
+ #define __INLINE __inline /*!< inline keyword for ARM Compiler */
+ #define __STATIC_INLINE static __inline
+
+#elif defined ( __ICCARM__ )
+ #define __ASM __asm /*!< asm keyword for IAR Compiler */
+ #define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
+ #define __STATIC_INLINE static inline
+
+#elif defined ( __TMS470__ )
+ #define __ASM __asm /*!< asm keyword for TI CCS Compiler */
+ #define __STATIC_INLINE static inline
+
+#elif defined ( __GNUC__ )
+ #define __ASM __asm /*!< asm keyword for GNU Compiler */
+ #define __INLINE inline /*!< inline keyword for GNU Compiler */
+ #define __STATIC_INLINE static inline
+
+#elif defined ( __TASKING__ )
+ #define __ASM __asm /*!< asm keyword for TASKING Compiler */
+ #define __INLINE inline /*!< inline keyword for TASKING Compiler */
+ #define __STATIC_INLINE static inline
+
+#endif
+
+/** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all
+*/
+#define __FPU_USED 0
+
+#if defined ( __CC_ARM )
+ #if defined __TARGET_FPU_VFP
+ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+ #endif
+
+#elif defined ( __ICCARM__ )
+ #if defined __ARMVFP__
+ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+ #endif
+
+#elif defined ( __TMS470__ )
+ #if defined __TI__VFP_SUPPORT____
+ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+ #endif
+
+#elif defined ( __GNUC__ )
+ #if defined (__VFP_FP__) && !defined(__SOFTFP__)
+ #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+ #endif
+
+#elif defined ( __TASKING__ )
+ #if defined __FPU_VFP__
+ #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+ #endif
+#endif
+
+#include /* standard types definitions */
+#include /* Core Instruction Access */
+#include /* Core Function Access */
+
+#endif /* __CORE_CM3_H_GENERIC */
+
+#ifndef __CMSIS_GENERIC
+
+#ifndef __CORE_CM3_H_DEPENDANT
+#define __CORE_CM3_H_DEPENDANT
+
+/* check device defines and use defaults */
+#if defined __CHECK_DEVICE_DEFINES
+ #ifndef __CM3_REV
+ #define __CM3_REV 0x0200
+ #warning "__CM3_REV not defined in device header file; using default!"
+ #endif
+
+ #ifndef __MPU_PRESENT
+ #define __MPU_PRESENT 0
+ #warning "__MPU_PRESENT not defined in device header file; using default!"
+ #endif
+
+ #ifndef __NVIC_PRIO_BITS
+ #define __NVIC_PRIO_BITS 4
+ #warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
+ #endif
+
+ #ifndef __Vendor_SysTickConfig
+ #define __Vendor_SysTickConfig 0
+ #warning "__Vendor_SysTickConfig not defined in device header file; using default!"
+ #endif
+#endif
+
+/* IO definitions (access restrictions to peripheral registers) */
+/**
+ \defgroup CMSIS_glob_defs CMSIS Global Defines
+
+ IO Type Qualifiers are used
+ \li to specify the access to peripheral variables.
+ \li for automatic generation of peripheral register debug information.
+*/
+#ifdef __cplusplus
+ #define __I volatile /*!< Defines 'read only' permissions */
+#else
+ #define __I volatile const /*!< Defines 'read only' permissions */
+#endif
+#define __O volatile /*!< Defines 'write only' permissions */
+#define __IO volatile /*!< Defines 'read / write' permissions */
+
+/*@} end of group Cortex_M3 */
+
+
+
+/*******************************************************************************
+ * Register Abstraction
+ Core Register contain:
+ - Core Register
+ - Core NVIC Register
+ - Core SCB Register
+ - Core SysTick Register
+ - Core Debug Register
+ - Core MPU Register
+ ******************************************************************************/
+/** \defgroup CMSIS_core_register Defines and Type Definitions
+ \brief Type definitions and defines for Cortex-M processor based devices.
+*/
+
+/** \ingroup CMSIS_core_register
+ \defgroup CMSIS_CORE Status and Control Registers
+ \brief Core Register type definitions.
+ @{
+ */
+
+/** \brief Union type to access the Application Program Status Register (APSR).
+ */
+typedef union
+{
+ struct
+ {
+#if (__CORTEX_M != 0x04)
+ uint32_t _reserved0:27; /*!< bit: 0..26 Reserved */
+#else
+ uint32_t _reserved0:16; /*!< bit: 0..15 Reserved */
+ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */
+ uint32_t _reserved1:7; /*!< bit: 20..26 Reserved */
+#endif
+ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */
+ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
+ uint32_t C:1; /*!< bit: 29 Carry condition code flag */
+ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
+ uint32_t N:1; /*!< bit: 31 Negative condition code flag */
+ } b; /*!< Structure used for bit access */
+ uint32_t w; /*!< Type used for word access */
+} APSR_Type;
+
+
+/** \brief Union type to access the Interrupt Program Status Register (IPSR).
+ */
+typedef union
+{
+ struct
+ {
+ uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
+ uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */
+ } b; /*!< Structure used for bit access */
+ uint32_t w; /*!< Type used for word access */
+} IPSR_Type;
+
+
+/** \brief Union type to access the Special-Purpose Program Status Registers (xPSR).
+ */
+typedef union
+{
+ struct
+ {
+ uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
+#if (__CORTEX_M != 0x04)
+ uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */
+#else
+ uint32_t _reserved0:7; /*!< bit: 9..15 Reserved */
+ uint32_t GE:4; /*!< bit: 16..19 Greater than or Equal flags */
+ uint32_t _reserved1:4; /*!< bit: 20..23 Reserved */
+#endif
+ uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */
+ uint32_t IT:2; /*!< bit: 25..26 saved IT state (read 0) */
+ uint32_t Q:1; /*!< bit: 27 Saturation condition flag */
+ uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
+ uint32_t C:1; /*!< bit: 29 Carry condition code flag */
+ uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
+ uint32_t N:1; /*!< bit: 31 Negative condition code flag */
+ } b; /*!< Structure used for bit access */
+ uint32_t w; /*!< Type used for word access */
+} xPSR_Type;
+
+
+/** \brief Union type to access the Control Registers (CONTROL).
+ */
+typedef union
+{
+ struct
+ {
+ uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */
+ uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */
+ uint32_t FPCA:1; /*!< bit: 2 FP extension active flag */
+ uint32_t _reserved0:29; /*!< bit: 3..31 Reserved */
+ } b; /*!< Structure used for bit access */
+ uint32_t w; /*!< Type used for word access */
+} CONTROL_Type;
+
+/*@} end of group CMSIS_CORE */
+
+
+/** \ingroup CMSIS_core_register
+ \defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC)
+ \brief Type definitions for the NVIC Registers
+ @{
+ */
+
+/** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC).
+ */
+typedef struct
+{
+ __IO uint32_t ISER[8]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */
+ uint32_t RESERVED0[24];
+ __IO uint32_t ICER[8]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */
+ uint32_t RSERVED1[24];
+ __IO uint32_t ISPR[8]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */
+ uint32_t RESERVED2[24];
+ __IO uint32_t ICPR[8]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */
+ uint32_t RESERVED3[24];
+ __IO uint32_t IABR[8]; /*!< Offset: 0x200 (R/W) Interrupt Active bit Register */
+ uint32_t RESERVED4[56];
+ __IO uint8_t IP[240]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register (8Bit wide) */
+ uint32_t RESERVED5[644];
+ __O uint32_t STIR; /*!< Offset: 0xE00 ( /W) Software Trigger Interrupt Register */
+} NVIC_Type;
+
+/* Software Triggered Interrupt Register Definitions */
+#define NVIC_STIR_INTID_Pos 0 /*!< STIR: INTLINESNUM Position */
+#define NVIC_STIR_INTID_Msk (0x1FFUL << NVIC_STIR_INTID_Pos) /*!< STIR: INTLINESNUM Mask */
+
+/*@} end of group CMSIS_NVIC */
+
+
+/** \ingroup CMSIS_core_register
+ \defgroup CMSIS_SCB System Control Block (SCB)
+ \brief Type definitions for the System Control Block Registers
+ @{
+ */
+
+/** \brief Structure type to access the System Control Block (SCB).
+ */
+typedef struct
+{
+ __I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */
+ __IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */
+ __IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */
+ __IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */
+ __IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */
+ __IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */
+ __IO uint8_t SHP[12]; /*!< Offset: 0x018 (R/W) System Handlers Priority Registers (4-7, 8-11, 12-15) */
+ __IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */
+ __IO uint32_t CFSR; /*!< Offset: 0x028 (R/W) Configurable Fault Status Register */
+ __IO uint32_t HFSR; /*!< Offset: 0x02C (R/W) HardFault Status Register */
+ __IO uint32_t DFSR; /*!< Offset: 0x030 (R/W) Debug Fault Status Register */
+ __IO uint32_t MMFAR; /*!< Offset: 0x034 (R/W) MemManage Fault Address Register */
+ __IO uint32_t BFAR; /*!< Offset: 0x038 (R/W) BusFault Address Register */
+ __IO uint32_t AFSR; /*!< Offset: 0x03C (R/W) Auxiliary Fault Status Register */
+ __I uint32_t PFR[2]; /*!< Offset: 0x040 (R/ ) Processor Feature Register */
+ __I uint32_t DFR; /*!< Offset: 0x048 (R/ ) Debug Feature Register */
+ __I uint32_t ADR; /*!< Offset: 0x04C (R/ ) Auxiliary Feature Register */
+ __I uint32_t MMFR[4]; /*!< Offset: 0x050 (R/ ) Memory Model Feature Register */
+ __I uint32_t ISAR[5]; /*!< Offset: 0x060 (R/ ) Instruction Set Attributes Register */
+ uint32_t RESERVED0[5];
+ __IO uint32_t CPACR; /*!< Offset: 0x088 (R/W) Coprocessor Access Control Register */
+} SCB_Type;
+
+/* SCB CPUID Register Definitions */
+#define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */
+#define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */
+
+#define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */
+#define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */
+
+#define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */
+#define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */
+
+#define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */
+#define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */
+
+#define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */
+#define SCB_CPUID_REVISION_Msk (0xFUL << SCB_CPUID_REVISION_Pos) /*!< SCB CPUID: REVISION Mask */
+
+/* SCB Interrupt Control State Register Definitions */
+#define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */
+#define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */
+
+#define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */
+#define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */
+
+#define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */
+#define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */
+
+#define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */
+#define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */
+
+#define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */
+#define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */
+
+#define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */
+#define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */
+
+#define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */
+#define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */
+
+#define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */
+#define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */
+
+#define SCB_ICSR_RETTOBASE_Pos 11 /*!< SCB ICSR: RETTOBASE Position */
+#define SCB_ICSR_RETTOBASE_Msk (1UL << SCB_ICSR_RETTOBASE_Pos) /*!< SCB ICSR: RETTOBASE Mask */
+
+#define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */
+#define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos) /*!< SCB ICSR: VECTACTIVE Mask */
+
+/* SCB Vector Table Offset Register Definitions */
+#if (__CM3_REV < 0x0201) /* core r2p1 */
+#define SCB_VTOR_TBLBASE_Pos 29 /*!< SCB VTOR: TBLBASE Position */
+#define SCB_VTOR_TBLBASE_Msk (1UL << SCB_VTOR_TBLBASE_Pos) /*!< SCB VTOR: TBLBASE Mask */
+
+#define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */
+#define SCB_VTOR_TBLOFF_Msk (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */
+#else
+#define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */
+#define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */
+#endif
+
+/* SCB Application Interrupt and Reset Control Register Definitions */
+#define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */
+#define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */
+
+#define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */
+#define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */
+
+#define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */
+#define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */
+
+#define SCB_AIRCR_PRIGROUP_Pos 8 /*!< SCB AIRCR: PRIGROUP Position */
+#define SCB_AIRCR_PRIGROUP_Msk (7UL << SCB_AIRCR_PRIGROUP_Pos) /*!< SCB AIRCR: PRIGROUP Mask */
+
+#define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */
+#define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */
+
+#define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */
+#define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */
+
+#define SCB_AIRCR_VECTRESET_Pos 0 /*!< SCB AIRCR: VECTRESET Position */
+#define SCB_AIRCR_VECTRESET_Msk (1UL << SCB_AIRCR_VECTRESET_Pos) /*!< SCB AIRCR: VECTRESET Mask */
+
+/* SCB System Control Register Definitions */
+#define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */
+#define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */
+
+#define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */
+#define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */
+
+#define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */
+#define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */
+
+/* SCB Configuration Control Register Definitions */
+#define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */
+#define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */
+
+#define SCB_CCR_BFHFNMIGN_Pos 8 /*!< SCB CCR: BFHFNMIGN Position */
+#define SCB_CCR_BFHFNMIGN_Msk (1UL << SCB_CCR_BFHFNMIGN_Pos) /*!< SCB CCR: BFHFNMIGN Mask */
+
+#define SCB_CCR_DIV_0_TRP_Pos 4 /*!< SCB CCR: DIV_0_TRP Position */
+#define SCB_CCR_DIV_0_TRP_Msk (1UL << SCB_CCR_DIV_0_TRP_Pos) /*!< SCB CCR: DIV_0_TRP Mask */
+
+#define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */
+#define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */
+
+#define SCB_CCR_USERSETMPEND_Pos 1 /*!< SCB CCR: USERSETMPEND Position */
+#define SCB_CCR_USERSETMPEND_Msk (1UL << SCB_CCR_USERSETMPEND_Pos) /*!< SCB CCR: USERSETMPEND Mask */
+
+#define SCB_CCR_NONBASETHRDENA_Pos 0 /*!< SCB CCR: NONBASETHRDENA Position */
+#define SCB_CCR_NONBASETHRDENA_Msk (1UL << SCB_CCR_NONBASETHRDENA_Pos) /*!< SCB CCR: NONBASETHRDENA Mask */
+
+/* SCB System Handler Control and State Register Definitions */
+#define SCB_SHCSR_USGFAULTENA_Pos 18 /*!< SCB SHCSR: USGFAULTENA Position */
+#define SCB_SHCSR_USGFAULTENA_Msk (1UL << SCB_SHCSR_USGFAULTENA_Pos) /*!< SCB SHCSR: USGFAULTENA Mask */
+
+#define SCB_SHCSR_BUSFAULTENA_Pos 17 /*!< SCB SHCSR: BUSFAULTENA Position */
+#define SCB_SHCSR_BUSFAULTENA_Msk (1UL << SCB_SHCSR_BUSFAULTENA_Pos) /*!< SCB SHCSR: BUSFAULTENA Mask */
+
+#define SCB_SHCSR_MEMFAULTENA_Pos 16 /*!< SCB SHCSR: MEMFAULTENA Position */
+#define SCB_SHCSR_MEMFAULTENA_Msk (1UL << SCB_SHCSR_MEMFAULTENA_Pos) /*!< SCB SHCSR: MEMFAULTENA Mask */
+
+#define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */
+#define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */
+
+#define SCB_SHCSR_BUSFAULTPENDED_Pos 14 /*!< SCB SHCSR: BUSFAULTPENDED Position */
+#define SCB_SHCSR_BUSFAULTPENDED_Msk (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos) /*!< SCB SHCSR: BUSFAULTPENDED Mask */
+
+#define SCB_SHCSR_MEMFAULTPENDED_Pos 13 /*!< SCB SHCSR: MEMFAULTPENDED Position */
+#define SCB_SHCSR_MEMFAULTPENDED_Msk (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos) /*!< SCB SHCSR: MEMFAULTPENDED Mask */
+
+#define SCB_SHCSR_USGFAULTPENDED_Pos 12 /*!< SCB SHCSR: USGFAULTPENDED Position */
+#define SCB_SHCSR_USGFAULTPENDED_Msk (1UL << SCB_SHCSR_USGFAULTPENDED_Pos) /*!< SCB SHCSR: USGFAULTPENDED Mask */
+
+#define SCB_SHCSR_SYSTICKACT_Pos 11 /*!< SCB SHCSR: SYSTICKACT Position */
+#define SCB_SHCSR_SYSTICKACT_Msk (1UL << SCB_SHCSR_SYSTICKACT_Pos) /*!< SCB SHCSR: SYSTICKACT Mask */
+
+#define SCB_SHCSR_PENDSVACT_Pos 10 /*!< SCB SHCSR: PENDSVACT Position */
+#define SCB_SHCSR_PENDSVACT_Msk (1UL << SCB_SHCSR_PENDSVACT_Pos) /*!< SCB SHCSR: PENDSVACT Mask */
+
+#define SCB_SHCSR_MONITORACT_Pos 8 /*!< SCB SHCSR: MONITORACT Position */
+#define SCB_SHCSR_MONITORACT_Msk (1UL << SCB_SHCSR_MONITORACT_Pos) /*!< SCB SHCSR: MONITORACT Mask */
+
+#define SCB_SHCSR_SVCALLACT_Pos 7 /*!< SCB SHCSR: SVCALLACT Position */
+#define SCB_SHCSR_SVCALLACT_Msk (1UL << SCB_SHCSR_SVCALLACT_Pos) /*!< SCB SHCSR: SVCALLACT Mask */
+
+#define SCB_SHCSR_USGFAULTACT_Pos 3 /*!< SCB SHCSR: USGFAULTACT Position */
+#define SCB_SHCSR_USGFAULTACT_Msk (1UL << SCB_SHCSR_USGFAULTACT_Pos) /*!< SCB SHCSR: USGFAULTACT Mask */
+
+#define SCB_SHCSR_BUSFAULTACT_Pos 1 /*!< SCB SHCSR: BUSFAULTACT Position */
+#define SCB_SHCSR_BUSFAULTACT_Msk (1UL << SCB_SHCSR_BUSFAULTACT_Pos) /*!< SCB SHCSR: BUSFAULTACT Mask */
+
+#define SCB_SHCSR_MEMFAULTACT_Pos 0 /*!< SCB SHCSR: MEMFAULTACT Position */
+#define SCB_SHCSR_MEMFAULTACT_Msk (1UL << SCB_SHCSR_MEMFAULTACT_Pos) /*!< SCB SHCSR: MEMFAULTACT Mask */
+
+/* SCB Configurable Fault Status Registers Definitions */
+#define SCB_CFSR_USGFAULTSR_Pos 16 /*!< SCB CFSR: Usage Fault Status Register Position */
+#define SCB_CFSR_USGFAULTSR_Msk (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos) /*!< SCB CFSR: Usage Fault Status Register Mask */
+
+#define SCB_CFSR_BUSFAULTSR_Pos 8 /*!< SCB CFSR: Bus Fault Status Register Position */
+#define SCB_CFSR_BUSFAULTSR_Msk (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos) /*!< SCB CFSR: Bus Fault Status Register Mask */
+
+#define SCB_CFSR_MEMFAULTSR_Pos 0 /*!< SCB CFSR: Memory Manage Fault Status Register Position */
+#define SCB_CFSR_MEMFAULTSR_Msk (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos) /*!< SCB CFSR: Memory Manage Fault Status Register Mask */
+
+/* SCB Hard Fault Status Registers Definitions */
+#define SCB_HFSR_DEBUGEVT_Pos 31 /*!< SCB HFSR: DEBUGEVT Position */
+#define SCB_HFSR_DEBUGEVT_Msk (1UL << SCB_HFSR_DEBUGEVT_Pos) /*!< SCB HFSR: DEBUGEVT Mask */
+
+#define SCB_HFSR_FORCED_Pos 30 /*!< SCB HFSR: FORCED Position */
+#define SCB_HFSR_FORCED_Msk (1UL << SCB_HFSR_FORCED_Pos) /*!< SCB HFSR: FORCED Mask */
+
+#define SCB_HFSR_VECTTBL_Pos 1 /*!< SCB HFSR: VECTTBL Position */
+#define SCB_HFSR_VECTTBL_Msk (1UL << SCB_HFSR_VECTTBL_Pos) /*!< SCB HFSR: VECTTBL Mask */
+
+/* SCB Debug Fault Status Register Definitions */
+#define SCB_DFSR_EXTERNAL_Pos 4 /*!< SCB DFSR: EXTERNAL Position */
+#define SCB_DFSR_EXTERNAL_Msk (1UL << SCB_DFSR_EXTERNAL_Pos) /*!< SCB DFSR: EXTERNAL Mask */
+
+#define SCB_DFSR_VCATCH_Pos 3 /*!< SCB DFSR: VCATCH Position */
+#define SCB_DFSR_VCATCH_Msk (1UL << SCB_DFSR_VCATCH_Pos) /*!< SCB DFSR: VCATCH Mask */
+
+#define SCB_DFSR_DWTTRAP_Pos 2 /*!< SCB DFSR: DWTTRAP Position */
+#define SCB_DFSR_DWTTRAP_Msk (1UL << SCB_DFSR_DWTTRAP_Pos) /*!< SCB DFSR: DWTTRAP Mask */
+
+#define SCB_DFSR_BKPT_Pos 1 /*!< SCB DFSR: BKPT Position */
+#define SCB_DFSR_BKPT_Msk (1UL << SCB_DFSR_BKPT_Pos) /*!< SCB DFSR: BKPT Mask */
+
+#define SCB_DFSR_HALTED_Pos 0 /*!< SCB DFSR: HALTED Position */
+#define SCB_DFSR_HALTED_Msk (1UL << SCB_DFSR_HALTED_Pos) /*!< SCB DFSR: HALTED Mask */
+
+/*@} end of group CMSIS_SCB */
+
+
+/** \ingroup CMSIS_core_register
+ \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB)
+ \brief Type definitions for the System Control and ID Register not in the SCB
+ @{
+ */
+
+/** \brief Structure type to access the System Control and ID Register not in the SCB.
+ */
+typedef struct
+{
+ uint32_t RESERVED0[1];
+ __I uint32_t ICTR; /*!< Offset: 0x004 (R/ ) Interrupt Controller Type Register */
+#if ((defined __CM3_REV) && (__CM3_REV >= 0x200))
+ __IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */
+#else
+ uint32_t RESERVED1[1];
+#endif
+} SCnSCB_Type;
+
+/* Interrupt Controller Type Register Definitions */
+#define SCnSCB_ICTR_INTLINESNUM_Pos 0 /*!< ICTR: INTLINESNUM Position */
+#define SCnSCB_ICTR_INTLINESNUM_Msk (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos) /*!< ICTR: INTLINESNUM Mask */
+
+/* Auxiliary Control Register Definitions */
+
+#define SCnSCB_ACTLR_DISFOLD_Pos 2 /*!< ACTLR: DISFOLD Position */
+#define SCnSCB_ACTLR_DISFOLD_Msk (1UL << SCnSCB_ACTLR_DISFOLD_Pos) /*!< ACTLR: DISFOLD Mask */
+
+#define SCnSCB_ACTLR_DISDEFWBUF_Pos 1 /*!< ACTLR: DISDEFWBUF Position */
+#define SCnSCB_ACTLR_DISDEFWBUF_Msk (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos) /*!< ACTLR: DISDEFWBUF Mask */
+
+#define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */
+#define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL << SCnSCB_ACTLR_DISMCYCINT_Pos) /*!< ACTLR: DISMCYCINT Mask */
+
+/*@} end of group CMSIS_SCnotSCB */
+
+
+/** \ingroup CMSIS_core_register
+ \defgroup CMSIS_SysTick System Tick Timer (SysTick)
+ \brief Type definitions for the System Timer Registers.
+ @{
+ */
+
+/** \brief Structure type to access the System Timer (SysTick).
+ */
+typedef struct
+{
+ __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */
+ __IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */
+ __IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */
+ __I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */
+} SysTick_Type;
+
+/* SysTick Control / Status Register Definitions */
+#define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */
+#define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */
+
+#define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */
+#define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */
+
+#define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */
+#define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */
+
+#define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */
+#define SysTick_CTRL_ENABLE_Msk (1UL << SysTick_CTRL_ENABLE_Pos) /*!< SysTick CTRL: ENABLE Mask */
+
+/* SysTick Reload Register Definitions */
+#define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */
+#define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos) /*!< SysTick LOAD: RELOAD Mask */
+
+/* SysTick Current Register Definitions */
+#define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */
+#define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick VAL: CURRENT Mask */
+
+/* SysTick Calibration Register Definitions */
+#define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */
+#define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */
+
+#define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */
+#define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */
+
+#define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */
+#define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos) /*!< SysTick CALIB: TENMS Mask */
+
+/*@} end of group CMSIS_SysTick */
+
+
+/** \ingroup CMSIS_core_register
+ \defgroup CMSIS_ITM Instrumentation Trace Macrocell (ITM)
+ \brief Type definitions for the Instrumentation Trace Macrocell (ITM)
+ @{
+ */
+
+/** \brief Structure type to access the Instrumentation Trace Macrocell Register (ITM).
+ */
+typedef struct
+{
+ __O union
+ {
+ __O uint8_t u8; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 8-bit */
+ __O uint16_t u16; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 16-bit */
+ __O uint32_t u32; /*!< Offset: 0x000 ( /W) ITM Stimulus Port 32-bit */
+ } PORT [32]; /*!< Offset: 0x000 ( /W) ITM Stimulus Port Registers */
+ uint32_t RESERVED0[864];
+ __IO uint32_t TER; /*!< Offset: 0xE00 (R/W) ITM Trace Enable Register */
+ uint32_t RESERVED1[15];
+ __IO uint32_t TPR; /*!< Offset: 0xE40 (R/W) ITM Trace Privilege Register */
+ uint32_t RESERVED2[15];
+ __IO uint32_t TCR; /*!< Offset: 0xE80 (R/W) ITM Trace Control Register */
+ uint32_t RESERVED3[29];
+ __O uint32_t IWR; /*!< Offset: 0xEF8 ( /W) ITM Integration Write Register */
+ __I uint32_t IRR; /*!< Offset: 0xEFC (R/ ) ITM Integration Read Register */
+ __IO uint32_t IMCR; /*!< Offset: 0xF00 (R/W) ITM Integration Mode Control Register */
+ uint32_t RESERVED4[43];
+ __O uint32_t LAR; /*!< Offset: 0xFB0 ( /W) ITM Lock Access Register */
+ __I uint32_t LSR; /*!< Offset: 0xFB4 (R/ ) ITM Lock Status Register */
+ uint32_t RESERVED5[6];
+ __I uint32_t PID4; /*!< Offset: 0xFD0 (R/ ) ITM Peripheral Identification Register #4 */
+ __I uint32_t PID5; /*!< Offset: 0xFD4 (R/ ) ITM Peripheral Identification Register #5 */
+ __I uint32_t PID6; /*!< Offset: 0xFD8 (R/ ) ITM Peripheral Identification Register #6 */
+ __I uint32_t PID7; /*!< Offset: 0xFDC (R/ ) ITM Peripheral Identification Register #7 */
+ __I uint32_t PID0; /*!< Offset: 0xFE0 (R/ ) ITM Peripheral Identification Register #0 */
+ __I uint32_t PID1; /*!< Offset: 0xFE4 (R/ ) ITM Peripheral Identification Register #1 */
+ __I uint32_t PID2; /*!< Offset: 0xFE8 (R/ ) ITM Peripheral Identification Register #2 */
+ __I uint32_t PID3; /*!< Offset: 0xFEC (R/ ) ITM Peripheral Identification Register #3 */
+ __I uint32_t CID0; /*!< Offset: 0xFF0 (R/ ) ITM Component Identification Register #0 */
+ __I uint32_t CID1; /*!< Offset: 0xFF4 (R/ ) ITM Component Identification Register #1 */
+ __I uint32_t CID2; /*!< Offset: 0xFF8 (R/ ) ITM Component Identification Register #2 */
+ __I uint32_t CID3; /*!< Offset: 0xFFC (R/ ) ITM Component Identification Register #3 */
+} ITM_Type;
+
+/* ITM Trace Privilege Register Definitions */
+#define ITM_TPR_PRIVMASK_Pos 0 /*!< ITM TPR: PRIVMASK Position */
+#define ITM_TPR_PRIVMASK_Msk (0xFUL << ITM_TPR_PRIVMASK_Pos) /*!< ITM TPR: PRIVMASK Mask */
+
+/* ITM Trace Control Register Definitions */
+#define ITM_TCR_BUSY_Pos 23 /*!< ITM TCR: BUSY Position */
+#define ITM_TCR_BUSY_Msk (1UL << ITM_TCR_BUSY_Pos) /*!< ITM TCR: BUSY Mask */
+
+#define ITM_TCR_TraceBusID_Pos 16 /*!< ITM TCR: ATBID Position */
+#define ITM_TCR_TraceBusID_Msk (0x7FUL << ITM_TCR_TraceBusID_Pos) /*!< ITM TCR: ATBID Mask */
+
+#define ITM_TCR_GTSFREQ_Pos 10 /*!< ITM TCR: Global timestamp frequency Position */
+#define ITM_TCR_GTSFREQ_Msk (3UL << ITM_TCR_GTSFREQ_Pos) /*!< ITM TCR: Global timestamp frequency Mask */
+
+#define ITM_TCR_TSPrescale_Pos 8 /*!< ITM TCR: TSPrescale Position */
+#define ITM_TCR_TSPrescale_Msk (3UL << ITM_TCR_TSPrescale_Pos) /*!< ITM TCR: TSPrescale Mask */
+
+#define ITM_TCR_SWOENA_Pos 4 /*!< ITM TCR: SWOENA Position */
+#define ITM_TCR_SWOENA_Msk (1UL << ITM_TCR_SWOENA_Pos) /*!< ITM TCR: SWOENA Mask */
+
+#define ITM_TCR_DWTENA_Pos 3 /*!< ITM TCR: DWTENA Position */
+#define ITM_TCR_DWTENA_Msk (1UL << ITM_TCR_DWTENA_Pos) /*!< ITM TCR: DWTENA Mask */
+
+#define ITM_TCR_SYNCENA_Pos 2 /*!< ITM TCR: SYNCENA Position */
+#define ITM_TCR_SYNCENA_Msk (1UL << ITM_TCR_SYNCENA_Pos) /*!< ITM TCR: SYNCENA Mask */
+
+#define ITM_TCR_TSENA_Pos 1 /*!< ITM TCR: TSENA Position */
+#define ITM_TCR_TSENA_Msk (1UL << ITM_TCR_TSENA_Pos) /*!< ITM TCR: TSENA Mask */
+
+#define ITM_TCR_ITMENA_Pos 0 /*!< ITM TCR: ITM Enable bit Position */
+#define ITM_TCR_ITMENA_Msk (1UL << ITM_TCR_ITMENA_Pos) /*!< ITM TCR: ITM Enable bit Mask */
+
+/* ITM Integration Write Register Definitions */
+#define ITM_IWR_ATVALIDM_Pos 0 /*!< ITM IWR: ATVALIDM Position */
+#define ITM_IWR_ATVALIDM_Msk (1UL << ITM_IWR_ATVALIDM_Pos) /*!< ITM IWR: ATVALIDM Mask */
+
+/* ITM Integration Read Register Definitions */
+#define ITM_IRR_ATREADYM_Pos 0 /*!< ITM IRR: ATREADYM Position */
+#define ITM_IRR_ATREADYM_Msk (1UL << ITM_IRR_ATREADYM_Pos) /*!< ITM IRR: ATREADYM Mask */
+
+/* ITM Integration Mode Control Register Definitions */
+#define ITM_IMCR_INTEGRATION_Pos 0 /*!< ITM IMCR: INTEGRATION Position */
+#define ITM_IMCR_INTEGRATION_Msk (1UL << ITM_IMCR_INTEGRATION_Pos) /*!< ITM IMCR: INTEGRATION Mask */
+
+/* ITM Lock Status Register Definitions */
+#define ITM_LSR_ByteAcc_Pos 2 /*!< ITM LSR: ByteAcc Position */
+#define ITM_LSR_ByteAcc_Msk (1UL << ITM_LSR_ByteAcc_Pos) /*!< ITM LSR: ByteAcc Mask */
+
+#define ITM_LSR_Access_Pos 1 /*!< ITM LSR: Access Position */
+#define ITM_LSR_Access_Msk (1UL << ITM_LSR_Access_Pos) /*!< ITM LSR: Access Mask */
+
+#define ITM_LSR_Present_Pos 0 /*!< ITM LSR: Present Position */
+#define ITM_LSR_Present_Msk (1UL << ITM_LSR_Present_Pos) /*!< ITM LSR: Present Mask */
+
+/*@}*/ /* end of group CMSIS_ITM */
+
+
+/** \ingroup CMSIS_core_register
+ \defgroup CMSIS_DWT Data Watchpoint and Trace (DWT)
+ \brief Type definitions for the Data Watchpoint and Trace (DWT)
+ @{
+ */
+
+/** \brief Structure type to access the Data Watchpoint and Trace Register (DWT).
+ */
+typedef struct
+{
+ __IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) Control Register */
+ __IO uint32_t CYCCNT; /*!< Offset: 0x004 (R/W) Cycle Count Register */
+ __IO uint32_t CPICNT; /*!< Offset: 0x008 (R/W) CPI Count Register */
+ __IO uint32_t EXCCNT; /*!< Offset: 0x00C (R/W) Exception Overhead Count Register */
+ __IO uint32_t SLEEPCNT; /*!< Offset: 0x010 (R/W) Sleep Count Register */
+ __IO uint32_t LSUCNT; /*!< Offset: 0x014 (R/W) LSU Count Register */
+ __IO uint32_t FOLDCNT; /*!< Offset: 0x018 (R/W) Folded-instruction Count Register */
+ __I uint32_t PCSR; /*!< Offset: 0x01C (R/ ) Program Counter Sample Register */
+ __IO uint32_t COMP0; /*!< Offset: 0x020 (R/W) Comparator Register 0 */
+ __IO uint32_t MASK0; /*!< Offset: 0x024 (R/W) Mask Register 0 */
+ __IO uint32_t FUNCTION0; /*!< Offset: 0x028 (R/W) Function Register 0 */
+ uint32_t RESERVED0[1];
+ __IO uint32_t COMP1; /*!< Offset: 0x030 (R/W) Comparator Register 1 */
+ __IO uint32_t MASK1; /*!< Offset: 0x034 (R/W) Mask Register 1 */
+ __IO uint32_t FUNCTION1; /*!< Offset: 0x038 (R/W) Function Register 1 */
+ uint32_t RESERVED1[1];
+ __IO uint32_t COMP2; /*!< Offset: 0x040 (R/W) Comparator Register 2 */
+ __IO uint32_t MASK2; /*!< Offset: 0x044 (R/W) Mask Register 2 */
+ __IO uint32_t FUNCTION2; /*!< Offset: 0x048 (R/W) Function Register 2 */
+ uint32_t RESERVED2[1];
+ __IO uint32_t COMP3; /*!< Offset: 0x050 (R/W) Comparator Register 3 */
+ __IO uint32_t MASK3; /*!< Offset: 0x054 (R/W) Mask Register 3 */
+ __IO uint32_t FUNCTION3; /*!< Offset: 0x058 (R/W) Function Register 3 */
+} DWT_Type;
+
+/* DWT Control Register Definitions */
+#define DWT_CTRL_NUMCOMP_Pos 28 /*!< DWT CTRL: NUMCOMP Position */
+#define DWT_CTRL_NUMCOMP_Msk (0xFUL << DWT_CTRL_NUMCOMP_Pos) /*!< DWT CTRL: NUMCOMP Mask */
+
+#define DWT_CTRL_NOTRCPKT_Pos 27 /*!< DWT CTRL: NOTRCPKT Position */
+#define DWT_CTRL_NOTRCPKT_Msk (0x1UL << DWT_CTRL_NOTRCPKT_Pos) /*!< DWT CTRL: NOTRCPKT Mask */
+
+#define DWT_CTRL_NOEXTTRIG_Pos 26 /*!< DWT CTRL: NOEXTTRIG Position */
+#define DWT_CTRL_NOEXTTRIG_Msk (0x1UL << DWT_CTRL_NOEXTTRIG_Pos) /*!< DWT CTRL: NOEXTTRIG Mask */
+
+#define DWT_CTRL_NOCYCCNT_Pos 25 /*!< DWT CTRL: NOCYCCNT Position */
+#define DWT_CTRL_NOCYCCNT_Msk (0x1UL << DWT_CTRL_NOCYCCNT_Pos) /*!< DWT CTRL: NOCYCCNT Mask */
+
+#define DWT_CTRL_NOPRFCNT_Pos 24 /*!< DWT CTRL: NOPRFCNT Position */
+#define DWT_CTRL_NOPRFCNT_Msk (0x1UL << DWT_CTRL_NOPRFCNT_Pos) /*!< DWT CTRL: NOPRFCNT Mask */
+
+#define DWT_CTRL_CYCEVTENA_Pos 22 /*!< DWT CTRL: CYCEVTENA Position */
+#define DWT_CTRL_CYCEVTENA_Msk (0x1UL << DWT_CTRL_CYCEVTENA_Pos) /*!< DWT CTRL: CYCEVTENA Mask */
+
+#define DWT_CTRL_FOLDEVTENA_Pos 21 /*!< DWT CTRL: FOLDEVTENA Position */
+#define DWT_CTRL_FOLDEVTENA_Msk (0x1UL << DWT_CTRL_FOLDEVTENA_Pos) /*!< DWT CTRL: FOLDEVTENA Mask */
+
+#define DWT_CTRL_LSUEVTENA_Pos 20 /*!< DWT CTRL: LSUEVTENA Position */
+#define DWT_CTRL_LSUEVTENA_Msk (0x1UL << DWT_CTRL_LSUEVTENA_Pos) /*!< DWT CTRL: LSUEVTENA Mask */
+
+#define DWT_CTRL_SLEEPEVTENA_Pos 19 /*!< DWT CTRL: SLEEPEVTENA Position */
+#define DWT_CTRL_SLEEPEVTENA_Msk (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos) /*!< DWT CTRL: SLEEPEVTENA Mask */
+
+#define DWT_CTRL_EXCEVTENA_Pos 18 /*!< DWT CTRL: EXCEVTENA Position */
+#define DWT_CTRL_EXCEVTENA_Msk (0x1UL << DWT_CTRL_EXCEVTENA_Pos) /*!< DWT CTRL: EXCEVTENA Mask */
+
+#define DWT_CTRL_CPIEVTENA_Pos 17 /*!< DWT CTRL: CPIEVTENA Position */
+#define DWT_CTRL_CPIEVTENA_Msk (0x1UL << DWT_CTRL_CPIEVTENA_Pos) /*!< DWT CTRL: CPIEVTENA Mask */
+
+#define DWT_CTRL_EXCTRCENA_Pos 16 /*!< DWT CTRL: EXCTRCENA Position */
+#define DWT_CTRL_EXCTRCENA_Msk (0x1UL << DWT_CTRL_EXCTRCENA_Pos) /*!< DWT CTRL: EXCTRCENA Mask */
+
+#define DWT_CTRL_PCSAMPLENA_Pos 12 /*!< DWT CTRL: PCSAMPLENA Position */
+#define DWT_CTRL_PCSAMPLENA_Msk (0x1UL << DWT_CTRL_PCSAMPLENA_Pos) /*!< DWT CTRL: PCSAMPLENA Mask */
+
+#define DWT_CTRL_SYNCTAP_Pos 10 /*!< DWT CTRL: SYNCTAP Position */
+#define DWT_CTRL_SYNCTAP_Msk (0x3UL << DWT_CTRL_SYNCTAP_Pos) /*!< DWT CTRL: SYNCTAP Mask */
+
+#define DWT_CTRL_CYCTAP_Pos 9 /*!< DWT CTRL: CYCTAP Position */
+#define DWT_CTRL_CYCTAP_Msk (0x1UL << DWT_CTRL_CYCTAP_Pos) /*!< DWT CTRL: CYCTAP Mask */
+
+#define DWT_CTRL_POSTINIT_Pos 5 /*!< DWT CTRL: POSTINIT Position */
+#define DWT_CTRL_POSTINIT_Msk (0xFUL << DWT_CTRL_POSTINIT_Pos) /*!< DWT CTRL: POSTINIT Mask */
+
+#define DWT_CTRL_POSTPRESET_Pos 1 /*!< DWT CTRL: POSTPRESET Position */
+#define DWT_CTRL_POSTPRESET_Msk (0xFUL << DWT_CTRL_POSTPRESET_Pos) /*!< DWT CTRL: POSTPRESET Mask */
+
+#define DWT_CTRL_CYCCNTENA_Pos 0 /*!< DWT CTRL: CYCCNTENA Position */
+#define DWT_CTRL_CYCCNTENA_Msk (0x1UL << DWT_CTRL_CYCCNTENA_Pos) /*!< DWT CTRL: CYCCNTENA Mask */
+
+/* DWT CPI Count Register Definitions */
+#define DWT_CPICNT_CPICNT_Pos 0 /*!< DWT CPICNT: CPICNT Position */
+#define DWT_CPICNT_CPICNT_Msk (0xFFUL << DWT_CPICNT_CPICNT_Pos) /*!< DWT CPICNT: CPICNT Mask */
+
+/* DWT Exception Overhead Count Register Definitions */
+#define DWT_EXCCNT_EXCCNT_Pos 0 /*!< DWT EXCCNT: EXCCNT Position */
+#define DWT_EXCCNT_EXCCNT_Msk (0xFFUL << DWT_EXCCNT_EXCCNT_Pos) /*!< DWT EXCCNT: EXCCNT Mask */
+
+/* DWT Sleep Count Register Definitions */
+#define DWT_SLEEPCNT_SLEEPCNT_Pos 0 /*!< DWT SLEEPCNT: SLEEPCNT Position */
+#define DWT_SLEEPCNT_SLEEPCNT_Msk (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos) /*!< DWT SLEEPCNT: SLEEPCNT Mask */
+
+/* DWT LSU Count Register Definitions */
+#define DWT_LSUCNT_LSUCNT_Pos 0 /*!< DWT LSUCNT: LSUCNT Position */
+#define DWT_LSUCNT_LSUCNT_Msk (0xFFUL << DWT_LSUCNT_LSUCNT_Pos) /*!< DWT LSUCNT: LSUCNT Mask */
+
+/* DWT Folded-instruction Count Register Definitions */
+#define DWT_FOLDCNT_FOLDCNT_Pos 0 /*!< DWT FOLDCNT: FOLDCNT Position */
+#define DWT_FOLDCNT_FOLDCNT_Msk (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos) /*!< DWT FOLDCNT: FOLDCNT Mask */
+
+/* DWT Comparator Mask Register Definitions */
+#define DWT_MASK_MASK_Pos 0 /*!< DWT MASK: MASK Position */
+#define DWT_MASK_MASK_Msk (0x1FUL << DWT_MASK_MASK_Pos) /*!< DWT MASK: MASK Mask */
+
+/* DWT Comparator Function Register Definitions */
+#define DWT_FUNCTION_MATCHED_Pos 24 /*!< DWT FUNCTION: MATCHED Position */
+#define DWT_FUNCTION_MATCHED_Msk (0x1UL << DWT_FUNCTION_MATCHED_Pos) /*!< DWT FUNCTION: MATCHED Mask */
+
+#define DWT_FUNCTION_DATAVADDR1_Pos 16 /*!< DWT FUNCTION: DATAVADDR1 Position */
+#define DWT_FUNCTION_DATAVADDR1_Msk (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos) /*!< DWT FUNCTION: DATAVADDR1 Mask */
+
+#define DWT_FUNCTION_DATAVADDR0_Pos 12 /*!< DWT FUNCTION: DATAVADDR0 Position */
+#define DWT_FUNCTION_DATAVADDR0_Msk (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos) /*!< DWT FUNCTION: DATAVADDR0 Mask */
+
+#define DWT_FUNCTION_DATAVSIZE_Pos 10 /*!< DWT FUNCTION: DATAVSIZE Position */
+#define DWT_FUNCTION_DATAVSIZE_Msk (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos) /*!< DWT FUNCTION: DATAVSIZE Mask */
+
+#define DWT_FUNCTION_LNK1ENA_Pos 9 /*!< DWT FUNCTION: LNK1ENA Position */
+#define DWT_FUNCTION_LNK1ENA_Msk (0x1UL << DWT_FUNCTION_LNK1ENA_Pos) /*!< DWT FUNCTION: LNK1ENA Mask */
+
+#define DWT_FUNCTION_DATAVMATCH_Pos 8 /*!< DWT FUNCTION: DATAVMATCH Position */
+#define DWT_FUNCTION_DATAVMATCH_Msk (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos) /*!< DWT FUNCTION: DATAVMATCH Mask */
+
+#define DWT_FUNCTION_CYCMATCH_Pos 7 /*!< DWT FUNCTION: CYCMATCH Position */
+#define DWT_FUNCTION_CYCMATCH_Msk (0x1UL << DWT_FUNCTION_CYCMATCH_Pos) /*!< DWT FUNCTION: CYCMATCH Mask */
+
+#define DWT_FUNCTION_EMITRANGE_Pos 5 /*!< DWT FUNCTION: EMITRANGE Position */
+#define DWT_FUNCTION_EMITRANGE_Msk (0x1UL << DWT_FUNCTION_EMITRANGE_Pos) /*!< DWT FUNCTION: EMITRANGE Mask */
+
+#define DWT_FUNCTION_FUNCTION_Pos 0 /*!< DWT FUNCTION: FUNCTION Position */
+#define DWT_FUNCTION_FUNCTION_Msk (0xFUL << DWT_FUNCTION_FUNCTION_Pos) /*!< DWT FUNCTION: FUNCTION Mask */
+
+/*@}*/ /* end of group CMSIS_DWT */
+
+
+/** \ingroup CMSIS_core_register
+ \defgroup CMSIS_TPI Trace Port Interface (TPI)
+ \brief Type definitions for the Trace Port Interface (TPI)
+ @{
+ */
+
+/** \brief Structure type to access the Trace Port Interface Register (TPI).
+ */
+typedef struct
+{
+ __IO uint32_t SSPSR; /*!< Offset: 0x000 (R/ ) Supported Parallel Port Size Register */
+ __IO uint32_t CSPSR; /*!< Offset: 0x004 (R/W) Current Parallel Port Size Register */
+ uint32_t RESERVED0[2];
+ __IO uint32_t ACPR; /*!< Offset: 0x010 (R/W) Asynchronous Clock Prescaler Register */
+ uint32_t RESERVED1[55];
+ __IO uint32_t SPPR; /*!< Offset: 0x0F0 (R/W) Selected Pin Protocol Register */
+ uint32_t RESERVED2[131];
+ __I uint32_t FFSR; /*!< Offset: 0x300 (R/ ) Formatter and Flush Status Register */
+ __IO uint32_t FFCR; /*!< Offset: 0x304 (R/W) Formatter and Flush Control Register */
+ __I uint32_t FSCR; /*!< Offset: 0x308 (R/ ) Formatter Synchronization Counter Register */
+ uint32_t RESERVED3[759];
+ __I uint32_t TRIGGER; /*!< Offset: 0xEE8 (R/ ) TRIGGER */
+ __I uint32_t FIFO0; /*!< Offset: 0xEEC (R/ ) Integration ETM Data */
+ __I uint32_t ITATBCTR2; /*!< Offset: 0xEF0 (R/ ) ITATBCTR2 */
+ uint32_t RESERVED4[1];
+ __I uint32_t ITATBCTR0; /*!< Offset: 0xEF8 (R/ ) ITATBCTR0 */
+ __I uint32_t FIFO1; /*!< Offset: 0xEFC (R/ ) Integration ITM Data */
+ __IO uint32_t ITCTRL; /*!< Offset: 0xF00 (R/W) Integration Mode Control */
+ uint32_t RESERVED5[39];
+ __IO uint32_t CLAIMSET; /*!< Offset: 0xFA0 (R/W) Claim tag set */
+ __IO uint32_t CLAIMCLR; /*!< Offset: 0xFA4 (R/W) Claim tag clear */
+ uint32_t RESERVED7[8];
+ __I uint32_t DEVID; /*!< Offset: 0xFC8 (R/ ) TPIU_DEVID */
+ __I uint32_t DEVTYPE; /*!< Offset: 0xFCC (R/ ) TPIU_DEVTYPE */
+} TPI_Type;
+
+/* TPI Asynchronous Clock Prescaler Register Definitions */
+#define TPI_ACPR_PRESCALER_Pos 0 /*!< TPI ACPR: PRESCALER Position */
+#define TPI_ACPR_PRESCALER_Msk (0x1FFFUL << TPI_ACPR_PRESCALER_Pos) /*!< TPI ACPR: PRESCALER Mask */
+
+/* TPI Selected Pin Protocol Register Definitions */
+#define TPI_SPPR_TXMODE_Pos 0 /*!< TPI SPPR: TXMODE Position */
+#define TPI_SPPR_TXMODE_Msk (0x3UL << TPI_SPPR_TXMODE_Pos) /*!< TPI SPPR: TXMODE Mask */
+
+/* TPI Formatter and Flush Status Register Definitions */
+#define TPI_FFSR_FtNonStop_Pos 3 /*!< TPI FFSR: FtNonStop Position */
+#define TPI_FFSR_FtNonStop_Msk (0x1UL << TPI_FFSR_FtNonStop_Pos) /*!< TPI FFSR: FtNonStop Mask */
+
+#define TPI_FFSR_TCPresent_Pos 2 /*!< TPI FFSR: TCPresent Position */
+#define TPI_FFSR_TCPresent_Msk (0x1UL << TPI_FFSR_TCPresent_Pos) /*!< TPI FFSR: TCPresent Mask */
+
+#define TPI_FFSR_FtStopped_Pos 1 /*!< TPI FFSR: FtStopped Position */
+#define TPI_FFSR_FtStopped_Msk (0x1UL << TPI_FFSR_FtStopped_Pos) /*!< TPI FFSR: FtStopped Mask */
+
+#define TPI_FFSR_FlInProg_Pos 0 /*!< TPI FFSR: FlInProg Position */
+#define TPI_FFSR_FlInProg_Msk (0x1UL << TPI_FFSR_FlInProg_Pos) /*!< TPI FFSR: FlInProg Mask */
+
+/* TPI Formatter and Flush Control Register Definitions */
+#define TPI_FFCR_TrigIn_Pos 8 /*!< TPI FFCR: TrigIn Position */
+#define TPI_FFCR_TrigIn_Msk (0x1UL << TPI_FFCR_TrigIn_Pos) /*!< TPI FFCR: TrigIn Mask */
+
+#define TPI_FFCR_EnFCont_Pos 1 /*!< TPI FFCR: EnFCont Position */
+#define TPI_FFCR_EnFCont_Msk (0x1UL << TPI_FFCR_EnFCont_Pos) /*!< TPI FFCR: EnFCont Mask */
+
+/* TPI TRIGGER Register Definitions */
+#define TPI_TRIGGER_TRIGGER_Pos 0 /*!< TPI TRIGGER: TRIGGER Position */
+#define TPI_TRIGGER_TRIGGER_Msk (0x1UL << TPI_TRIGGER_TRIGGER_Pos) /*!< TPI TRIGGER: TRIGGER Mask */
+
+/* TPI Integration ETM Data Register Definitions (FIFO0) */
+#define TPI_FIFO0_ITM_ATVALID_Pos 29 /*!< TPI FIFO0: ITM_ATVALID Position */
+#define TPI_FIFO0_ITM_ATVALID_Msk (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos) /*!< TPI FIFO0: ITM_ATVALID Mask */
+
+#define TPI_FIFO0_ITM_bytecount_Pos 27 /*!< TPI FIFO0: ITM_bytecount Position */
+#define TPI_FIFO0_ITM_bytecount_Msk (0x3UL << TPI_FIFO0_ITM_bytecount_Pos) /*!< TPI FIFO0: ITM_bytecount Mask */
+
+#define TPI_FIFO0_ETM_ATVALID_Pos 26 /*!< TPI FIFO0: ETM_ATVALID Position */
+#define TPI_FIFO0_ETM_ATVALID_Msk (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos) /*!< TPI FIFO0: ETM_ATVALID Mask */
+
+#define TPI_FIFO0_ETM_bytecount_Pos 24 /*!< TPI FIFO0: ETM_bytecount Position */
+#define TPI_FIFO0_ETM_bytecount_Msk (0x3UL << TPI_FIFO0_ETM_bytecount_Pos) /*!< TPI FIFO0: ETM_bytecount Mask */
+
+#define TPI_FIFO0_ETM2_Pos 16 /*!< TPI FIFO0: ETM2 Position */
+#define TPI_FIFO0_ETM2_Msk (0xFFUL << TPI_FIFO0_ETM2_Pos) /*!< TPI FIFO0: ETM2 Mask */
+
+#define TPI_FIFO0_ETM1_Pos 8 /*!< TPI FIFO0: ETM1 Position */
+#define TPI_FIFO0_ETM1_Msk (0xFFUL << TPI_FIFO0_ETM1_Pos) /*!< TPI FIFO0: ETM1 Mask */
+
+#define TPI_FIFO0_ETM0_Pos 0 /*!< TPI FIFO0: ETM0 Position */
+#define TPI_FIFO0_ETM0_Msk (0xFFUL << TPI_FIFO0_ETM0_Pos) /*!< TPI FIFO0: ETM0 Mask */
+
+/* TPI ITATBCTR2 Register Definitions */
+#define TPI_ITATBCTR2_ATREADY_Pos 0 /*!< TPI ITATBCTR2: ATREADY Position */
+#define TPI_ITATBCTR2_ATREADY_Msk (0x1UL << TPI_ITATBCTR2_ATREADY_Pos) /*!< TPI ITATBCTR2: ATREADY Mask */
+
+/* TPI Integration ITM Data Register Definitions (FIFO1) */
+#define TPI_FIFO1_ITM_ATVALID_Pos 29 /*!< TPI FIFO1: ITM_ATVALID Position */
+#define TPI_FIFO1_ITM_ATVALID_Msk (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos) /*!< TPI FIFO1: ITM_ATVALID Mask */
+
+#define TPI_FIFO1_ITM_bytecount_Pos 27 /*!< TPI FIFO1: ITM_bytecount Position */
+#define TPI_FIFO1_ITM_bytecount_Msk (0x3UL << TPI_FIFO1_ITM_bytecount_Pos) /*!< TPI FIFO1: ITM_bytecount Mask */
+
+#define TPI_FIFO1_ETM_ATVALID_Pos 26 /*!< TPI FIFO1: ETM_ATVALID Position */
+#define TPI_FIFO1_ETM_ATVALID_Msk (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos) /*!< TPI FIFO1: ETM_ATVALID Mask */
+
+#define TPI_FIFO1_ETM_bytecount_Pos 24 /*!< TPI FIFO1: ETM_bytecount Position */
+#define TPI_FIFO1_ETM_bytecount_Msk (0x3UL << TPI_FIFO1_ETM_bytecount_Pos) /*!< TPI FIFO1: ETM_bytecount Mask */
+
+#define TPI_FIFO1_ITM2_Pos 16 /*!< TPI FIFO1: ITM2 Position */
+#define TPI_FIFO1_ITM2_Msk (0xFFUL << TPI_FIFO1_ITM2_Pos) /*!< TPI FIFO1: ITM2 Mask */
+
+#define TPI_FIFO1_ITM1_Pos 8 /*!< TPI FIFO1: ITM1 Position */
+#define TPI_FIFO1_ITM1_Msk (0xFFUL << TPI_FIFO1_ITM1_Pos) /*!< TPI FIFO1: ITM1 Mask */
+
+#define TPI_FIFO1_ITM0_Pos 0 /*!< TPI FIFO1: ITM0 Position */
+#define TPI_FIFO1_ITM0_Msk (0xFFUL << TPI_FIFO1_ITM0_Pos) /*!< TPI FIFO1: ITM0 Mask */
+
+/* TPI ITATBCTR0 Register Definitions */
+#define TPI_ITATBCTR0_ATREADY_Pos 0 /*!< TPI ITATBCTR0: ATREADY Position */
+#define TPI_ITATBCTR0_ATREADY_Msk (0x1UL << TPI_ITATBCTR0_ATREADY_Pos) /*!< TPI ITATBCTR0: ATREADY Mask */
+
+/* TPI Integration Mode Control Register Definitions */
+#define TPI_ITCTRL_Mode_Pos 0 /*!< TPI ITCTRL: Mode Position */
+#define TPI_ITCTRL_Mode_Msk (0x1UL << TPI_ITCTRL_Mode_Pos) /*!< TPI ITCTRL: Mode Mask */
+
+/* TPI DEVID Register Definitions */
+#define TPI_DEVID_NRZVALID_Pos 11 /*!< TPI DEVID: NRZVALID Position */
+#define TPI_DEVID_NRZVALID_Msk (0x1UL << TPI_DEVID_NRZVALID_Pos) /*!< TPI DEVID: NRZVALID Mask */
+
+#define TPI_DEVID_MANCVALID_Pos 10 /*!< TPI DEVID: MANCVALID Position */
+#define TPI_DEVID_MANCVALID_Msk (0x1UL << TPI_DEVID_MANCVALID_Pos) /*!< TPI DEVID: MANCVALID Mask */
+
+#define TPI_DEVID_PTINVALID_Pos 9 /*!< TPI DEVID: PTINVALID Position */
+#define TPI_DEVID_PTINVALID_Msk (0x1UL << TPI_DEVID_PTINVALID_Pos) /*!< TPI DEVID: PTINVALID Mask */
+
+#define TPI_DEVID_MinBufSz_Pos 6 /*!< TPI DEVID: MinBufSz Position */
+#define TPI_DEVID_MinBufSz_Msk (0x7UL << TPI_DEVID_MinBufSz_Pos) /*!< TPI DEVID: MinBufSz Mask */
+
+#define TPI_DEVID_AsynClkIn_Pos 5 /*!< TPI DEVID: AsynClkIn Position */
+#define TPI_DEVID_AsynClkIn_Msk (0x1UL << TPI_DEVID_AsynClkIn_Pos) /*!< TPI DEVID: AsynClkIn Mask */
+
+#define TPI_DEVID_NrTraceInput_Pos 0 /*!< TPI DEVID: NrTraceInput Position */
+#define TPI_DEVID_NrTraceInput_Msk (0x1FUL << TPI_DEVID_NrTraceInput_Pos) /*!< TPI DEVID: NrTraceInput Mask */
+
+/* TPI DEVTYPE Register Definitions */
+#define TPI_DEVTYPE_SubType_Pos 0 /*!< TPI DEVTYPE: SubType Position */
+#define TPI_DEVTYPE_SubType_Msk (0xFUL << TPI_DEVTYPE_SubType_Pos) /*!< TPI DEVTYPE: SubType Mask */
+
+#define TPI_DEVTYPE_MajorType_Pos 4 /*!< TPI DEVTYPE: MajorType Position */
+#define TPI_DEVTYPE_MajorType_Msk (0xFUL << TPI_DEVTYPE_MajorType_Pos) /*!< TPI DEVTYPE: MajorType Mask */
+
+/*@}*/ /* end of group CMSIS_TPI */
+
+
+#if (__MPU_PRESENT == 1)
+/** \ingroup CMSIS_core_register
+ \defgroup CMSIS_MPU Memory Protection Unit (MPU)
+ \brief Type definitions for the Memory Protection Unit (MPU)
+ @{
+ */
+
+/** \brief Structure type to access the Memory Protection Unit (MPU).
+ */
+typedef struct
+{
+ __I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */
+ __IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */
+ __IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */
+ __IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */
+ __IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */
+ __IO uint32_t RBAR_A1; /*!< Offset: 0x014 (R/W) MPU Alias 1 Region Base Address Register */
+ __IO uint32_t RASR_A1; /*!< Offset: 0x018 (R/W) MPU Alias 1 Region Attribute and Size Register */
+ __IO uint32_t RBAR_A2; /*!< Offset: 0x01C (R/W) MPU Alias 2 Region Base Address Register */
+ __IO uint32_t RASR_A2; /*!< Offset: 0x020 (R/W) MPU Alias 2 Region Attribute and Size Register */
+ __IO uint32_t RBAR_A3; /*!< Offset: 0x024 (R/W) MPU Alias 3 Region Base Address Register */
+ __IO uint32_t RASR_A3; /*!< Offset: 0x028 (R/W) MPU Alias 3 Region Attribute and Size Register */
+} MPU_Type;
+
+/* MPU Type Register */
+#define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */
+#define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */
+
+#define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */
+#define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */
+
+#define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */
+#define MPU_TYPE_SEPARATE_Msk (1UL << MPU_TYPE_SEPARATE_Pos) /*!< MPU TYPE: SEPARATE Mask */
+
+/* MPU Control Register */
+#define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */
+#define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */
+
+#define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */
+#define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */
+
+#define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */
+#define MPU_CTRL_ENABLE_Msk (1UL << MPU_CTRL_ENABLE_Pos) /*!< MPU CTRL: ENABLE Mask */
+
+/* MPU Region Number Register */
+#define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */
+#define MPU_RNR_REGION_Msk (0xFFUL << MPU_RNR_REGION_Pos) /*!< MPU RNR: REGION Mask */
+
+/* MPU Region Base Address Register */
+#define MPU_RBAR_ADDR_Pos 5 /*!< MPU RBAR: ADDR Position */
+#define MPU_RBAR_ADDR_Msk (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */
+
+#define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */
+#define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */
+
+#define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */
+#define MPU_RBAR_REGION_Msk (0xFUL << MPU_RBAR_REGION_Pos) /*!< MPU RBAR: REGION Mask */
+
+/* MPU Region Attribute and Size Register */
+#define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */
+#define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */
+
+#define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */
+#define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */
+
+#define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */
+#define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */
+
+#define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */
+#define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */
+
+#define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */
+#define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */
+
+#define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */
+#define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */
+
+#define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */
+#define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */
+
+#define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */
+#define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */
+
+#define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */
+#define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */
+
+#define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */
+#define MPU_RASR_ENABLE_Msk (1UL << MPU_RASR_ENABLE_Pos) /*!< MPU RASR: Region enable bit Disable Mask */
+
+/*@} end of group CMSIS_MPU */
+#endif
+
+
+/** \ingroup CMSIS_core_register
+ \defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug)
+ \brief Type definitions for the Core Debug Registers
+ @{
+ */
+
+/** \brief Structure type to access the Core Debug Register (CoreDebug).
+ */
+typedef struct
+{
+ __IO uint32_t DHCSR; /*!< Offset: 0x000 (R/W) Debug Halting Control and Status Register */
+ __O uint32_t DCRSR; /*!< Offset: 0x004 ( /W) Debug Core Register Selector Register */
+ __IO uint32_t DCRDR; /*!< Offset: 0x008 (R/W) Debug Core Register Data Register */
+ __IO uint32_t DEMCR; /*!< Offset: 0x00C (R/W) Debug Exception and Monitor Control Register */
+} CoreDebug_Type;
+
+/* Debug Halting Control and Status Register */
+#define CoreDebug_DHCSR_DBGKEY_Pos 16 /*!< CoreDebug DHCSR: DBGKEY Position */
+#define CoreDebug_DHCSR_DBGKEY_Msk (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos) /*!< CoreDebug DHCSR: DBGKEY Mask */
+
+#define CoreDebug_DHCSR_S_RESET_ST_Pos 25 /*!< CoreDebug DHCSR: S_RESET_ST Position */
+#define CoreDebug_DHCSR_S_RESET_ST_Msk (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos) /*!< CoreDebug DHCSR: S_RESET_ST Mask */
+
+#define CoreDebug_DHCSR_S_RETIRE_ST_Pos 24 /*!< CoreDebug DHCSR: S_RETIRE_ST Position */
+#define CoreDebug_DHCSR_S_RETIRE_ST_Msk (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos) /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */
+
+#define CoreDebug_DHCSR_S_LOCKUP_Pos 19 /*!< CoreDebug DHCSR: S_LOCKUP Position */
+#define CoreDebug_DHCSR_S_LOCKUP_Msk (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos) /*!< CoreDebug DHCSR: S_LOCKUP Mask */
+
+#define CoreDebug_DHCSR_S_SLEEP_Pos 18 /*!< CoreDebug DHCSR: S_SLEEP Position */
+#define CoreDebug_DHCSR_S_SLEEP_Msk (1UL << CoreDebug_DHCSR_S_SLEEP_Pos) /*!< CoreDebug DHCSR: S_SLEEP Mask */
+
+#define CoreDebug_DHCSR_S_HALT_Pos 17 /*!< CoreDebug DHCSR: S_HALT Position */
+#define CoreDebug_DHCSR_S_HALT_Msk (1UL << CoreDebug_DHCSR_S_HALT_Pos) /*!< CoreDebug DHCSR: S_HALT Mask */
+
+#define CoreDebug_DHCSR_S_REGRDY_Pos 16 /*!< CoreDebug DHCSR: S_REGRDY Position */
+#define CoreDebug_DHCSR_S_REGRDY_Msk (1UL << CoreDebug_DHCSR_S_REGRDY_Pos) /*!< CoreDebug DHCSR: S_REGRDY Mask */
+
+#define CoreDebug_DHCSR_C_SNAPSTALL_Pos 5 /*!< CoreDebug DHCSR: C_SNAPSTALL Position */
+#define CoreDebug_DHCSR_C_SNAPSTALL_Msk (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos) /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */
+
+#define CoreDebug_DHCSR_C_MASKINTS_Pos 3 /*!< CoreDebug DHCSR: C_MASKINTS Position */
+#define CoreDebug_DHCSR_C_MASKINTS_Msk (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos) /*!< CoreDebug DHCSR: C_MASKINTS Mask */
+
+#define CoreDebug_DHCSR_C_STEP_Pos 2 /*!< CoreDebug DHCSR: C_STEP Position */
+#define CoreDebug_DHCSR_C_STEP_Msk (1UL << CoreDebug_DHCSR_C_STEP_Pos) /*!< CoreDebug DHCSR: C_STEP Mask */
+
+#define CoreDebug_DHCSR_C_HALT_Pos 1 /*!< CoreDebug DHCSR: C_HALT Position */
+#define CoreDebug_DHCSR_C_HALT_Msk (1UL << CoreDebug_DHCSR_C_HALT_Pos) /*!< CoreDebug DHCSR: C_HALT Mask */
+
+#define CoreDebug_DHCSR_C_DEBUGEN_Pos 0 /*!< CoreDebug DHCSR: C_DEBUGEN Position */
+#define CoreDebug_DHCSR_C_DEBUGEN_Msk (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos) /*!< CoreDebug DHCSR: C_DEBUGEN Mask */
+
+/* Debug Core Register Selector Register */
+#define CoreDebug_DCRSR_REGWnR_Pos 16 /*!< CoreDebug DCRSR: REGWnR Position */
+#define CoreDebug_DCRSR_REGWnR_Msk (1UL << CoreDebug_DCRSR_REGWnR_Pos) /*!< CoreDebug DCRSR: REGWnR Mask */
+
+#define CoreDebug_DCRSR_REGSEL_Pos 0 /*!< CoreDebug DCRSR: REGSEL Position */
+#define CoreDebug_DCRSR_REGSEL_Msk (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos) /*!< CoreDebug DCRSR: REGSEL Mask */
+
+/* Debug Exception and Monitor Control Register */
+#define CoreDebug_DEMCR_TRCENA_Pos 24 /*!< CoreDebug DEMCR: TRCENA Position */
+#define CoreDebug_DEMCR_TRCENA_Msk (1UL << CoreDebug_DEMCR_TRCENA_Pos) /*!< CoreDebug DEMCR: TRCENA Mask */
+
+#define CoreDebug_DEMCR_MON_REQ_Pos 19 /*!< CoreDebug DEMCR: MON_REQ Position */
+#define CoreDebug_DEMCR_MON_REQ_Msk (1UL << CoreDebug_DEMCR_MON_REQ_Pos) /*!< CoreDebug DEMCR: MON_REQ Mask */
+
+#define CoreDebug_DEMCR_MON_STEP_Pos 18 /*!< CoreDebug DEMCR: MON_STEP Position */
+#define CoreDebug_DEMCR_MON_STEP_Msk (1UL << CoreDebug_DEMCR_MON_STEP_Pos) /*!< CoreDebug DEMCR: MON_STEP Mask */
+
+#define CoreDebug_DEMCR_MON_PEND_Pos 17 /*!< CoreDebug DEMCR: MON_PEND Position */
+#define CoreDebug_DEMCR_MON_PEND_Msk (1UL << CoreDebug_DEMCR_MON_PEND_Pos) /*!< CoreDebug DEMCR: MON_PEND Mask */
+
+#define CoreDebug_DEMCR_MON_EN_Pos 16 /*!< CoreDebug DEMCR: MON_EN Position */
+#define CoreDebug_DEMCR_MON_EN_Msk (1UL << CoreDebug_DEMCR_MON_EN_Pos) /*!< CoreDebug DEMCR: MON_EN Mask */
+
+#define CoreDebug_DEMCR_VC_HARDERR_Pos 10 /*!< CoreDebug DEMCR: VC_HARDERR Position */
+#define CoreDebug_DEMCR_VC_HARDERR_Msk (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos) /*!< CoreDebug DEMCR: VC_HARDERR Mask */
+
+#define CoreDebug_DEMCR_VC_INTERR_Pos 9 /*!< CoreDebug DEMCR: VC_INTERR Position */
+#define CoreDebug_DEMCR_VC_INTERR_Msk (1UL << CoreDebug_DEMCR_VC_INTERR_Pos) /*!< CoreDebug DEMCR: VC_INTERR Mask */
+
+#define CoreDebug_DEMCR_VC_BUSERR_Pos 8 /*!< CoreDebug DEMCR: VC_BUSERR Position */
+#define CoreDebug_DEMCR_VC_BUSERR_Msk (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos) /*!< CoreDebug DEMCR: VC_BUSERR Mask */
+
+#define CoreDebug_DEMCR_VC_STATERR_Pos 7 /*!< CoreDebug DEMCR: VC_STATERR Position */
+#define CoreDebug_DEMCR_VC_STATERR_Msk (1UL << CoreDebug_DEMCR_VC_STATERR_Pos) /*!< CoreDebug DEMCR: VC_STATERR Mask */
+
+#define CoreDebug_DEMCR_VC_CHKERR_Pos 6 /*!< CoreDebug DEMCR: VC_CHKERR Position */
+#define CoreDebug_DEMCR_VC_CHKERR_Msk (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos) /*!< CoreDebug DEMCR: VC_CHKERR Mask */
+
+#define CoreDebug_DEMCR_VC_NOCPERR_Pos 5 /*!< CoreDebug DEMCR: VC_NOCPERR Position */
+#define CoreDebug_DEMCR_VC_NOCPERR_Msk (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos) /*!< CoreDebug DEMCR: VC_NOCPERR Mask */
+
+#define CoreDebug_DEMCR_VC_MMERR_Pos 4 /*!< CoreDebug DEMCR: VC_MMERR Position */
+#define CoreDebug_DEMCR_VC_MMERR_Msk (1UL << CoreDebug_DEMCR_VC_MMERR_Pos) /*!< CoreDebug DEMCR: VC_MMERR Mask */
+
+#define CoreDebug_DEMCR_VC_CORERESET_Pos 0 /*!< CoreDebug DEMCR: VC_CORERESET Position */
+#define CoreDebug_DEMCR_VC_CORERESET_Msk (1UL << CoreDebug_DEMCR_VC_CORERESET_Pos) /*!< CoreDebug DEMCR: VC_CORERESET Mask */
+
+/*@} end of group CMSIS_CoreDebug */
+
+
+/** \ingroup CMSIS_core_register
+ \defgroup CMSIS_core_base Core Definitions
+ \brief Definitions for base addresses, unions, and structures.
+ @{
+ */
+
+/* Memory mapping of Cortex-M3 Hardware */
+#define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */
+#define ITM_BASE (0xE0000000UL) /*!< ITM Base Address */
+#define DWT_BASE (0xE0001000UL) /*!< DWT Base Address */
+#define TPI_BASE (0xE0040000UL) /*!< TPI Base Address */
+#define CoreDebug_BASE (0xE000EDF0UL) /*!< Core Debug Base Address */
+#define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */
+#define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */
+#define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */
+
+#define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */
+#define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */
+#define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */
+#define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */
+#define ITM ((ITM_Type *) ITM_BASE ) /*!< ITM configuration struct */
+#define DWT ((DWT_Type *) DWT_BASE ) /*!< DWT configuration struct */
+#define TPI ((TPI_Type *) TPI_BASE ) /*!< TPI configuration struct */
+#define CoreDebug ((CoreDebug_Type *) CoreDebug_BASE) /*!< Core Debug configuration struct */
+
+#if (__MPU_PRESENT == 1)
+ #define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */
+ #define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */
+#endif
+
+/*@} */
+
+
+
+/*******************************************************************************
+ * Hardware Abstraction Layer
+ Core Function Interface contains:
+ - Core NVIC Functions
+ - Core SysTick Functions
+ - Core Debug Functions
+ - Core Register Access Functions
+ ******************************************************************************/
+/** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
+*/
+
+
+
+/* ########################## NVIC functions #################################### */
+/** \ingroup CMSIS_Core_FunctionInterface
+ \defgroup CMSIS_Core_NVICFunctions NVIC Functions
+ \brief Functions that manage interrupts and exceptions via the NVIC.
+ @{
+ */
+
+/** \brief Set Priority Grouping
+
+ The function sets the priority grouping field using the required unlock sequence.
+ The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field.
+ Only values from 0..7 are used.
+ In case of a conflict between priority grouping and available
+ priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set.
+
+ \param [in] PriorityGroup Priority grouping field.
+ */
+__STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup)
+{
+ uint32_t reg_value;
+ uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07); /* only values 0..7 are used */
+
+ reg_value = SCB->AIRCR; /* read old register configuration */
+ reg_value &= ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk); /* clear bits to change */
+ reg_value = (reg_value |
+ ((uint32_t)0x5FA << SCB_AIRCR_VECTKEY_Pos) |
+ (PriorityGroupTmp << 8)); /* Insert write key and priorty group */
+ SCB->AIRCR = reg_value;
+}
+
+
+/** \brief Get Priority Grouping
+
+ The function reads the priority grouping field from the NVIC Interrupt Controller.
+
+ \return Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field).
+ */
+__STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void)
+{
+ return ((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos); /* read priority grouping field */
+}
+
+
+/** \brief Enable External Interrupt
+
+ The function enables a device-specific interrupt in the NVIC interrupt controller.
+
+ \param [in] IRQn External interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
+{
+ NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* enable interrupt */
+}
+
+
+/** \brief Disable External Interrupt
+
+ The function disables a device-specific interrupt in the NVIC interrupt controller.
+
+ \param [in] IRQn External interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
+{
+ NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */
+}
+
+
+/** \brief Get Pending Interrupt
+
+ The function reads the pending register in the NVIC and returns the pending bit
+ for the specified interrupt.
+
+ \param [in] IRQn Interrupt number.
+
+ \return 0 Interrupt status is not pending.
+ \return 1 Interrupt status is pending.
+ */
+__STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)
+{
+ return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */
+}
+
+
+/** \brief Set Pending Interrupt
+
+ The function sets the pending bit of an external interrupt.
+
+ \param [in] IRQn Interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)
+{
+ NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */
+}
+
+
+/** \brief Clear Pending Interrupt
+
+ The function clears the pending bit of an external interrupt.
+
+ \param [in] IRQn External interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)
+{
+ NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */
+}
+
+
+/** \brief Get Active Interrupt
+
+ The function reads the active register in NVIC and returns the active bit.
+
+ \param [in] IRQn Interrupt number.
+
+ \return 0 Interrupt status is not active.
+ \return 1 Interrupt status is active.
+ */
+__STATIC_INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn)
+{
+ return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */
+}
+
+
+/** \brief Set Interrupt Priority
+
+ The function sets the priority of an interrupt.
+
+ \note The priority cannot be set for every core interrupt.
+
+ \param [in] IRQn Interrupt number.
+ \param [in] priority Priority to set.
+ */
+__STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
+{
+ if(IRQn < 0) {
+ SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M System Interrupts */
+ else {
+ NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for device specific Interrupts */
+}
+
+
+/** \brief Get Interrupt Priority
+
+ The function reads the priority of an interrupt. The interrupt
+ number can be positive to specify an external (device specific)
+ interrupt, or negative to specify an internal (core) interrupt.
+
+
+ \param [in] IRQn Interrupt number.
+ \return Interrupt Priority. Value is aligned automatically to the implemented
+ priority bits of the microcontroller.
+ */
+__STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn)
+{
+
+ if(IRQn < 0) {
+ return((uint32_t)(SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for Cortex-M system interrupts */
+ else {
+ return((uint32_t)(NVIC->IP[(uint32_t)(IRQn)] >> (8 - __NVIC_PRIO_BITS))); } /* get priority for device specific interrupts */
+}
+
+
+/** \brief Encode Priority
+
+ The function encodes the priority for an interrupt with the given priority group,
+ preemptive priority value, and subpriority value.
+ In case of a conflict between priority grouping and available
+ priority bits (__NVIC_PRIO_BITS), the samllest possible priority group is set.
+
+ \param [in] PriorityGroup Used priority group.
+ \param [in] PreemptPriority Preemptive priority value (starting from 0).
+ \param [in] SubPriority Subpriority value (starting from 0).
+ \return Encoded priority. Value can be used in the function \ref NVIC_SetPriority().
+ */
+__STATIC_INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority)
+{
+ uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */
+ uint32_t PreemptPriorityBits;
+ uint32_t SubPriorityBits;
+
+ PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp;
+ SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS;
+
+ return (
+ ((PreemptPriority & ((1 << (PreemptPriorityBits)) - 1)) << SubPriorityBits) |
+ ((SubPriority & ((1 << (SubPriorityBits )) - 1)))
+ );
+}
+
+
+/** \brief Decode Priority
+
+ The function decodes an interrupt priority value with a given priority group to
+ preemptive priority value and subpriority value.
+ In case of a conflict between priority grouping and available
+ priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set.
+
+ \param [in] Priority Priority value, which can be retrieved with the function \ref NVIC_GetPriority().
+ \param [in] PriorityGroup Used priority group.
+ \param [out] pPreemptPriority Preemptive priority value (starting from 0).
+ \param [out] pSubPriority Subpriority value (starting from 0).
+ */
+__STATIC_INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority)
+{
+ uint32_t PriorityGroupTmp = (PriorityGroup & 0x07); /* only values 0..7 are used */
+ uint32_t PreemptPriorityBits;
+ uint32_t SubPriorityBits;
+
+ PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp;
+ SubPriorityBits = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS;
+
+ *pPreemptPriority = (Priority >> SubPriorityBits) & ((1 << (PreemptPriorityBits)) - 1);
+ *pSubPriority = (Priority ) & ((1 << (SubPriorityBits )) - 1);
+}
+
+
+/** \brief System Reset
+
+ The function initiates a system reset request to reset the MCU.
+ */
+__STATIC_INLINE void NVIC_SystemReset(void)
+{
+ __DSB(); /* Ensure all outstanding memory accesses included
+ buffered write are completed before reset */
+ SCB->AIRCR = ((0x5FA << SCB_AIRCR_VECTKEY_Pos) |
+ (SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) |
+ SCB_AIRCR_SYSRESETREQ_Msk); /* Keep priority group unchanged */
+ __DSB(); /* Ensure completion of memory access */
+ while(1); /* wait until reset */
+}
+
+/*@} end of CMSIS_Core_NVICFunctions */
+
+
+
+/* ################################## SysTick function ############################################ */
+/** \ingroup CMSIS_Core_FunctionInterface
+ \defgroup CMSIS_Core_SysTickFunctions SysTick Functions
+ \brief Functions that configure the System.
+ @{
+ */
+
+#if (__Vendor_SysTickConfig == 0)
+
+/** \brief System Tick Configuration
+
+ The function initializes the System Timer and its interrupt, and starts the System Tick Timer.
+ Counter is in free running mode to generate periodic interrupts.
+
+ \param [in] ticks Number of ticks between two interrupts.
+
+ \return 0 Function succeeded.
+ \return 1 Function failed.
+
+ \note When the variable __Vendor_SysTickConfig is set to 1, then the
+ function SysTick_Config is not included. In this case, the file device.h
+ must contain a vendor-specific implementation of this function.
+
+ */
+__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
+{
+ if (ticks > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */
+
+ SysTick->LOAD = (ticks & SysTick_LOAD_RELOAD_Msk) - 1; /* set reload register */
+ NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Systick Interrupt */
+ SysTick->VAL = 0; /* Load the SysTick Counter Value */
+ SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
+ SysTick_CTRL_TICKINT_Msk |
+ SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */
+ return (0); /* Function successful */
+}
+
+#endif
+
+/*@} end of CMSIS_Core_SysTickFunctions */
+
+
+
+/* ##################################### Debug In/Output function ########################################### */
+/** \ingroup CMSIS_Core_FunctionInterface
+ \defgroup CMSIS_core_DebugFunctions ITM Functions
+ \brief Functions that access the ITM debug interface.
+ @{
+ */
+
+extern volatile int32_t ITM_RxBuffer; /*!< External variable to receive characters. */
+#define ITM_RXBUFFER_EMPTY 0x5AA55AA5 /*!< Value identifying \ref ITM_RxBuffer is ready for next character. */
+
+
+/** \brief ITM Send Character
+
+ The function transmits a character via the ITM channel 0, and
+ \li Just returns when no debugger is connected that has booked the output.
+ \li Is blocking when a debugger is connected, but the previous character sent has not been transmitted.
+
+ \param [in] ch Character to transmit.
+
+ \returns Character to transmit.
+ */
+__STATIC_INLINE uint32_t ITM_SendChar (uint32_t ch)
+{
+ if ((ITM->TCR & ITM_TCR_ITMENA_Msk) && /* ITM enabled */
+ (ITM->TER & (1UL << 0) ) ) /* ITM Port #0 enabled */
+ {
+ while (ITM->PORT[0].u32 == 0);
+ ITM->PORT[0].u8 = (uint8_t) ch;
+ }
+ return (ch);
+}
+
+
+/** \brief ITM Receive Character
+
+ The function inputs a character via the external variable \ref ITM_RxBuffer.
+
+ \return Received character.
+ \return -1 No character pending.
+ */
+__STATIC_INLINE int32_t ITM_ReceiveChar (void) {
+ int32_t ch = -1; /* no character available */
+
+ if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) {
+ ch = ITM_RxBuffer;
+ ITM_RxBuffer = ITM_RXBUFFER_EMPTY; /* ready for next character */
+ }
+
+ return (ch);
+}
+
+
+/** \brief ITM Check Character
+
+ The function checks whether a character is pending for reading in the variable \ref ITM_RxBuffer.
+
+ \return 0 No character available.
+ \return 1 Character available.
+ */
+__STATIC_INLINE int32_t ITM_CheckChar (void) {
+
+ if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) {
+ return (0); /* no character available */
+ } else {
+ return (1); /* character available */
+ }
+}
+
+/*@} end of CMSIS_core_DebugFunctions */
+
+#endif /* __CORE_CM3_H_DEPENDANT */
+
+#endif /* __CMSIS_GENERIC */
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/grbl/stm32grbl/cmsis/core_cmFunc.h b/grbl/stm32grbl/cmsis/core_cmFunc.h
new file mode 100755
index 000000000..adb07b5d3
--- /dev/null
+++ b/grbl/stm32grbl/cmsis/core_cmFunc.h
@@ -0,0 +1,616 @@
+/**************************************************************************//**
+ * @file core_cmFunc.h
+ * @brief CMSIS Cortex-M Core Function Access Header File
+ * @version V3.01
+ * @date 06. March 2012
+ *
+ * @note
+ * Copyright (C) 2009-2012 ARM Limited. All rights reserved.
+ *
+ * @par
+ * ARM Limited (ARM) is supplying this software for use with Cortex-M
+ * processor based microcontrollers. This file can be freely distributed
+ * within development tools that are supporting such ARM based processors.
+ *
+ * @par
+ * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
+ * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
+ * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR
+ * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
+ *
+ ******************************************************************************/
+
+#ifndef __CORE_CMFUNC_H
+#define __CORE_CMFUNC_H
+
+
+/* ########################### Core Function Access ########################### */
+/** \ingroup CMSIS_Core_FunctionInterface
+ \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions
+ @{
+ */
+
+#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
+/* ARM armcc specific functions */
+
+#if (__ARMCC_VERSION < 400677)
+ #error "Please use ARM Compiler Toolchain V4.0.677 or later!"
+#endif
+
+/* intrinsic void __enable_irq(); */
+/* intrinsic void __disable_irq(); */
+
+/** \brief Get Control Register
+
+ This function returns the content of the Control Register.
+
+ \return Control Register value
+ */
+__STATIC_INLINE uint32_t __get_CONTROL(void)
+{
+ register uint32_t __regControl __ASM("control");
+ return(__regControl);
+}
+
+
+/** \brief Set Control Register
+
+ This function writes the given value to the Control Register.
+
+ \param [in] control Control Register value to set
+ */
+__STATIC_INLINE void __set_CONTROL(uint32_t control)
+{
+ register uint32_t __regControl __ASM("control");
+ __regControl = control;
+}
+
+
+/** \brief Get IPSR Register
+
+ This function returns the content of the IPSR Register.
+
+ \return IPSR Register value
+ */
+__STATIC_INLINE uint32_t __get_IPSR(void)
+{
+ register uint32_t __regIPSR __ASM("ipsr");
+ return(__regIPSR);
+}
+
+
+/** \brief Get APSR Register
+
+ This function returns the content of the APSR Register.
+
+ \return APSR Register value
+ */
+__STATIC_INLINE uint32_t __get_APSR(void)
+{
+ register uint32_t __regAPSR __ASM("apsr");
+ return(__regAPSR);
+}
+
+
+/** \brief Get xPSR Register
+
+ This function returns the content of the xPSR Register.
+
+ \return xPSR Register value
+ */
+__STATIC_INLINE uint32_t __get_xPSR(void)
+{
+ register uint32_t __regXPSR __ASM("xpsr");
+ return(__regXPSR);
+}
+
+
+/** \brief Get Process Stack Pointer
+
+ This function returns the current value of the Process Stack Pointer (PSP).
+
+ \return PSP Register value
+ */
+__STATIC_INLINE uint32_t __get_PSP(void)
+{
+ register uint32_t __regProcessStackPointer __ASM("psp");
+ return(__regProcessStackPointer);
+}
+
+
+/** \brief Set Process Stack Pointer
+
+ This function assigns the given value to the Process Stack Pointer (PSP).
+
+ \param [in] topOfProcStack Process Stack Pointer value to set
+ */
+__STATIC_INLINE void __set_PSP(uint32_t topOfProcStack)
+{
+ register uint32_t __regProcessStackPointer __ASM("psp");
+ __regProcessStackPointer = topOfProcStack;
+}
+
+
+/** \brief Get Main Stack Pointer
+
+ This function returns the current value of the Main Stack Pointer (MSP).
+
+ \return MSP Register value
+ */
+__STATIC_INLINE uint32_t __get_MSP(void)
+{
+ register uint32_t __regMainStackPointer __ASM("msp");
+ return(__regMainStackPointer);
+}
+
+
+/** \brief Set Main Stack Pointer
+
+ This function assigns the given value to the Main Stack Pointer (MSP).
+
+ \param [in] topOfMainStack Main Stack Pointer value to set
+ */
+__STATIC_INLINE void __set_MSP(uint32_t topOfMainStack)
+{
+ register uint32_t __regMainStackPointer __ASM("msp");
+ __regMainStackPointer = topOfMainStack;
+}
+
+
+/** \brief Get Priority Mask
+
+ This function returns the current state of the priority mask bit from the Priority Mask Register.
+
+ \return Priority Mask value
+ */
+__STATIC_INLINE uint32_t __get_PRIMASK(void)
+{
+ register uint32_t __regPriMask __ASM("primask");
+ return(__regPriMask);
+}
+
+
+/** \brief Set Priority Mask
+
+ This function assigns the given value to the Priority Mask Register.
+
+ \param [in] priMask Priority Mask
+ */
+__STATIC_INLINE void __set_PRIMASK(uint32_t priMask)
+{
+ register uint32_t __regPriMask __ASM("primask");
+ __regPriMask = (priMask);
+}
+
+
+#if (__CORTEX_M >= 0x03)
+
+/** \brief Enable FIQ
+
+ This function enables FIQ interrupts by clearing the F-bit in the CPSR.
+ Can only be executed in Privileged modes.
+ */
+#define __enable_fault_irq __enable_fiq
+
+
+/** \brief Disable FIQ
+
+ This function disables FIQ interrupts by setting the F-bit in the CPSR.
+ Can only be executed in Privileged modes.
+ */
+#define __disable_fault_irq __disable_fiq
+
+
+/** \brief Get Base Priority
+
+ This function returns the current value of the Base Priority register.
+
+ \return Base Priority register value
+ */
+__STATIC_INLINE uint32_t __get_BASEPRI(void)
+{
+ register uint32_t __regBasePri __ASM("basepri");
+ return(__regBasePri);
+}
+
+
+/** \brief Set Base Priority
+
+ This function assigns the given value to the Base Priority register.
+
+ \param [in] basePri Base Priority value to set
+ */
+__STATIC_INLINE void __set_BASEPRI(uint32_t basePri)
+{
+ register uint32_t __regBasePri __ASM("basepri");
+ __regBasePri = (basePri & 0xff);
+}
+
+
+/** \brief Get Fault Mask
+
+ This function returns the current value of the Fault Mask register.
+
+ \return Fault Mask register value
+ */
+__STATIC_INLINE uint32_t __get_FAULTMASK(void)
+{
+ register uint32_t __regFaultMask __ASM("faultmask");
+ return(__regFaultMask);
+}
+
+
+/** \brief Set Fault Mask
+
+ This function assigns the given value to the Fault Mask register.
+
+ \param [in] faultMask Fault Mask value to set
+ */
+__STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask)
+{
+ register uint32_t __regFaultMask __ASM("faultmask");
+ __regFaultMask = (faultMask & (uint32_t)1);
+}
+
+#endif /* (__CORTEX_M >= 0x03) */
+
+
+#if (__CORTEX_M == 0x04)
+
+/** \brief Get FPSCR
+
+ This function returns the current value of the Floating Point Status/Control register.
+
+ \return Floating Point Status/Control register value
+ */
+__STATIC_INLINE uint32_t __get_FPSCR(void)
+{
+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
+ register uint32_t __regfpscr __ASM("fpscr");
+ return(__regfpscr);
+#else
+ return(0);
+#endif
+}
+
+
+/** \brief Set FPSCR
+
+ This function assigns the given value to the Floating Point Status/Control register.
+
+ \param [in] fpscr Floating Point Status/Control value to set
+ */
+__STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
+{
+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
+ register uint32_t __regfpscr __ASM("fpscr");
+ __regfpscr = (fpscr);
+#endif
+}
+
+#endif /* (__CORTEX_M == 0x04) */
+
+
+#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/
+/* IAR iccarm specific functions */
+
+#include
+
+
+#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/
+/* TI CCS specific functions */
+
+#include
+
+
+#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/
+/* GNU gcc specific functions */
+
+/** \brief Enable IRQ Interrupts
+
+ This function enables IRQ interrupts by clearing the I-bit in the CPSR.
+ Can only be executed in Privileged modes.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void)
+{
+ __ASM volatile ("cpsie i");
+}
+
+
+/** \brief Disable IRQ Interrupts
+
+ This function disables IRQ interrupts by setting the I-bit in the CPSR.
+ Can only be executed in Privileged modes.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_irq(void)
+{
+ __ASM volatile ("cpsid i");
+}
+
+
+/** \brief Get Control Register
+
+ This function returns the content of the Control Register.
+
+ \return Control Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CONTROL(void)
+{
+ uint32_t result;
+
+ __ASM volatile ("MRS %0, control" : "=r" (result) );
+ return(result);
+}
+
+
+/** \brief Set Control Register
+
+ This function writes the given value to the Control Register.
+
+ \param [in] control Control Register value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CONTROL(uint32_t control)
+{
+ __ASM volatile ("MSR control, %0" : : "r" (control) );
+}
+
+
+/** \brief Get IPSR Register
+
+ This function returns the content of the IPSR Register.
+
+ \return IPSR Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_IPSR(void)
+{
+ uint32_t result;
+
+ __ASM volatile ("MRS %0, ipsr" : "=r" (result) );
+ return(result);
+}
+
+
+/** \brief Get APSR Register
+
+ This function returns the content of the APSR Register.
+
+ \return APSR Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void)
+{
+ uint32_t result;
+
+ __ASM volatile ("MRS %0, apsr" : "=r" (result) );
+ return(result);
+}
+
+
+/** \brief Get xPSR Register
+
+ This function returns the content of the xPSR Register.
+
+ \return xPSR Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_xPSR(void)
+{
+ uint32_t result;
+
+ __ASM volatile ("MRS %0, xpsr" : "=r" (result) );
+ return(result);
+}
+
+
+/** \brief Get Process Stack Pointer
+
+ This function returns the current value of the Process Stack Pointer (PSP).
+
+ \return PSP Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PSP(void)
+{
+ register uint32_t result;
+
+ __ASM volatile ("MRS %0, psp\n" : "=r" (result) );
+ return(result);
+}
+
+
+/** \brief Set Process Stack Pointer
+
+ This function assigns the given value to the Process Stack Pointer (PSP).
+
+ \param [in] topOfProcStack Process Stack Pointer value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack)
+{
+ __ASM volatile ("MSR psp, %0\n" : : "r" (topOfProcStack) );
+}
+
+
+/** \brief Get Main Stack Pointer
+
+ This function returns the current value of the Main Stack Pointer (MSP).
+
+ \return MSP Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_MSP(void)
+{
+ register uint32_t result;
+
+ __ASM volatile ("MRS %0, msp\n" : "=r" (result) );
+ return(result);
+}
+
+
+/** \brief Set Main Stack Pointer
+
+ This function assigns the given value to the Main Stack Pointer (MSP).
+
+ \param [in] topOfMainStack Main Stack Pointer value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack)
+{
+ __ASM volatile ("MSR msp, %0\n" : : "r" (topOfMainStack) );
+}
+
+
+/** \brief Get Priority Mask
+
+ This function returns the current state of the priority mask bit from the Priority Mask Register.
+
+ \return Priority Mask value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PRIMASK(void)
+{
+ uint32_t result;
+
+ __ASM volatile ("MRS %0, primask" : "=r" (result) );
+ return(result);
+}
+
+
+/** \brief Set Priority Mask
+
+ This function assigns the given value to the Priority Mask Register.
+
+ \param [in] priMask Priority Mask
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PRIMASK(uint32_t priMask)
+{
+ __ASM volatile ("MSR primask, %0" : : "r" (priMask) );
+}
+
+
+#if (__CORTEX_M >= 0x03)
+
+/** \brief Enable FIQ
+
+ This function enables FIQ interrupts by clearing the F-bit in the CPSR.
+ Can only be executed in Privileged modes.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_fault_irq(void)
+{
+ __ASM volatile ("cpsie f");
+}
+
+
+/** \brief Disable FIQ
+
+ This function disables FIQ interrupts by setting the F-bit in the CPSR.
+ Can only be executed in Privileged modes.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_fault_irq(void)
+{
+ __ASM volatile ("cpsid f");
+}
+
+
+/** \brief Get Base Priority
+
+ This function returns the current value of the Base Priority register.
+
+ \return Base Priority register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_BASEPRI(void)
+{
+ uint32_t result;
+
+ __ASM volatile ("MRS %0, basepri_max" : "=r" (result) );
+ return(result);
+}
+
+
+/** \brief Set Base Priority
+
+ This function assigns the given value to the Base Priority register.
+
+ \param [in] basePri Base Priority value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI(uint32_t value)
+{
+ __ASM volatile ("MSR basepri, %0" : : "r" (value) );
+}
+
+
+/** \brief Get Fault Mask
+
+ This function returns the current value of the Fault Mask register.
+
+ \return Fault Mask register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FAULTMASK(void)
+{
+ uint32_t result;
+
+ __ASM volatile ("MRS %0, faultmask" : "=r" (result) );
+ return(result);
+}
+
+
+/** \brief Set Fault Mask
+
+ This function assigns the given value to the Fault Mask register.
+
+ \param [in] faultMask Fault Mask value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask)
+{
+ __ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) );
+}
+
+#endif /* (__CORTEX_M >= 0x03) */
+
+
+#if (__CORTEX_M == 0x04)
+
+/** \brief Get FPSCR
+
+ This function returns the current value of the Floating Point Status/Control register.
+
+ \return Floating Point Status/Control register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void)
+{
+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
+ uint32_t result;
+
+ __ASM volatile ("VMRS %0, fpscr" : "=r" (result) );
+ return(result);
+#else
+ return(0);
+#endif
+}
+
+
+/** \brief Set FPSCR
+
+ This function assigns the given value to the Floating Point Status/Control register.
+
+ \param [in] fpscr Floating Point Status/Control value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
+{
+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
+ __ASM volatile ("VMSR fpscr, %0" : : "r" (fpscr) );
+#endif
+}
+
+#endif /* (__CORTEX_M == 0x04) */
+
+
+#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/
+/* TASKING carm specific functions */
+
+/*
+ * The CMSIS functions have been implemented as intrinsics in the compiler.
+ * Please use "carm -?i" to get an up to date list of all instrinsics,
+ * Including the CMSIS ones.
+ */
+
+#endif
+
+/*@} end of CMSIS_Core_RegAccFunctions */
+
+
+#endif /* __CORE_CMFUNC_H */
diff --git a/grbl/stm32grbl/cmsis/core_cmInstr.h b/grbl/stm32grbl/cmsis/core_cmInstr.h
new file mode 100755
index 000000000..624c175fd
--- /dev/null
+++ b/grbl/stm32grbl/cmsis/core_cmInstr.h
@@ -0,0 +1,618 @@
+/**************************************************************************//**
+ * @file core_cmInstr.h
+ * @brief CMSIS Cortex-M Core Instruction Access Header File
+ * @version V3.01
+ * @date 06. March 2012
+ *
+ * @note
+ * Copyright (C) 2009-2012 ARM Limited. All rights reserved.
+ *
+ * @par
+ * ARM Limited (ARM) is supplying this software for use with Cortex-M
+ * processor based microcontrollers. This file can be freely distributed
+ * within development tools that are supporting such ARM based processors.
+ *
+ * @par
+ * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
+ * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
+ * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR
+ * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
+ *
+ ******************************************************************************/
+
+#ifndef __CORE_CMINSTR_H
+#define __CORE_CMINSTR_H
+
+
+/* ########################## Core Instruction Access ######################### */
+/** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface
+ Access to dedicated instructions
+ @{
+*/
+
+#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
+/* ARM armcc specific functions */
+
+#if (__ARMCC_VERSION < 400677)
+ #error "Please use ARM Compiler Toolchain V4.0.677 or later!"
+#endif
+
+
+/** \brief No Operation
+
+ No Operation does nothing. This instruction can be used for code alignment purposes.
+ */
+#define __NOP __nop
+
+
+/** \brief Wait For Interrupt
+
+ Wait For Interrupt is a hint instruction that suspends execution
+ until one of a number of events occurs.
+ */
+#define __WFI __wfi
+
+
+/** \brief Wait For Event
+
+ Wait For Event is a hint instruction that permits the processor to enter
+ a low-power state until one of a number of events occurs.
+ */
+#define __WFE __wfe
+
+
+/** \brief Send Event
+
+ Send Event is a hint instruction. It causes an event to be signaled to the CPU.
+ */
+#define __SEV __sev
+
+
+/** \brief Instruction Synchronization Barrier
+
+ Instruction Synchronization Barrier flushes the pipeline in the processor,
+ so that all instructions following the ISB are fetched from cache or
+ memory, after the instruction has been completed.
+ */
+#define __ISB() __isb(0xF)
+
+
+/** \brief Data Synchronization Barrier
+
+ This function acts as a special kind of Data Memory Barrier.
+ It completes when all explicit memory accesses before this instruction complete.
+ */
+#define __DSB() __dsb(0xF)
+
+
+/** \brief Data Memory Barrier
+
+ This function ensures the apparent order of the explicit memory operations before
+ and after the instruction, without ensuring their completion.
+ */
+#define __DMB() __dmb(0xF)
+
+
+/** \brief Reverse byte order (32 bit)
+
+ This function reverses the byte order in integer value.
+
+ \param [in] value Value to reverse
+ \return Reversed value
+ */
+#define __REV __rev
+
+
+/** \brief Reverse byte order (16 bit)
+
+ This function reverses the byte order in two unsigned short values.
+
+ \param [in] value Value to reverse
+ \return Reversed value
+ */
+__attribute__((section(".rev16_text"))) __STATIC_INLINE __ASM uint32_t __REV16(uint32_t value)
+{
+ rev16 r0, r0
+ bx lr
+}
+
+
+/** \brief Reverse byte order in signed short value
+
+ This function reverses the byte order in a signed short value with sign extension to integer.
+
+ \param [in] value Value to reverse
+ \return Reversed value
+ */
+__attribute__((section(".revsh_text"))) __STATIC_INLINE __ASM int32_t __REVSH(int32_t value)
+{
+ revsh r0, r0
+ bx lr
+}
+
+
+/** \brief Rotate Right in unsigned value (32 bit)
+
+ This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits.
+
+ \param [in] value Value to rotate
+ \param [in] value Number of Bits to rotate
+ \return Rotated value
+ */
+#define __ROR __ror
+
+
+#if (__CORTEX_M >= 0x03)
+
+/** \brief Reverse bit order of value
+
+ This function reverses the bit order of the given value.
+
+ \param [in] value Value to reverse
+ \return Reversed value
+ */
+#define __RBIT __rbit
+
+
+/** \brief LDR Exclusive (8 bit)
+
+ This function performs a exclusive LDR command for 8 bit value.
+
+ \param [in] ptr Pointer to data
+ \return value of type uint8_t at (*ptr)
+ */
+#define __LDREXB(ptr) ((uint8_t ) __ldrex(ptr))
+
+
+/** \brief LDR Exclusive (16 bit)
+
+ This function performs a exclusive LDR command for 16 bit values.
+
+ \param [in] ptr Pointer to data
+ \return value of type uint16_t at (*ptr)
+ */
+#define __LDREXH(ptr) ((uint16_t) __ldrex(ptr))
+
+
+/** \brief LDR Exclusive (32 bit)
+
+ This function performs a exclusive LDR command for 32 bit values.
+
+ \param [in] ptr Pointer to data
+ \return value of type uint32_t at (*ptr)
+ */
+#define __LDREXW(ptr) ((uint32_t ) __ldrex(ptr))
+
+
+/** \brief STR Exclusive (8 bit)
+
+ This function performs a exclusive STR command for 8 bit values.
+
+ \param [in] value Value to store
+ \param [in] ptr Pointer to location
+ \return 0 Function succeeded
+ \return 1 Function failed
+ */
+#define __STREXB(value, ptr) __strex(value, ptr)
+
+
+/** \brief STR Exclusive (16 bit)
+
+ This function performs a exclusive STR command for 16 bit values.
+
+ \param [in] value Value to store
+ \param [in] ptr Pointer to location
+ \return 0 Function succeeded
+ \return 1 Function failed
+ */
+#define __STREXH(value, ptr) __strex(value, ptr)
+
+
+/** \brief STR Exclusive (32 bit)
+
+ This function performs a exclusive STR command for 32 bit values.
+
+ \param [in] value Value to store
+ \param [in] ptr Pointer to location
+ \return 0 Function succeeded
+ \return 1 Function failed
+ */
+#define __STREXW(value, ptr) __strex(value, ptr)
+
+
+/** \brief Remove the exclusive lock
+
+ This function removes the exclusive lock which is created by LDREX.
+
+ */
+#define __CLREX __clrex
+
+
+/** \brief Signed Saturate
+
+ This function saturates a signed value.
+
+ \param [in] value Value to be saturated
+ \param [in] sat Bit position to saturate to (1..32)
+ \return Saturated value
+ */
+#define __SSAT __ssat
+
+
+/** \brief Unsigned Saturate
+
+ This function saturates an unsigned value.
+
+ \param [in] value Value to be saturated
+ \param [in] sat Bit position to saturate to (0..31)
+ \return Saturated value
+ */
+#define __USAT __usat
+
+
+/** \brief Count leading zeros
+
+ This function counts the number of leading zeros of a data value.
+
+ \param [in] value Value to count the leading zeros
+ \return number of leading zeros in value
+ */
+#define __CLZ __clz
+
+#endif /* (__CORTEX_M >= 0x03) */
+
+
+
+#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/
+/* IAR iccarm specific functions */
+
+#include
+
+
+#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/
+/* TI CCS specific functions */
+
+#include
+
+
+#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/
+/* GNU gcc specific functions */
+
+/** \brief No Operation
+
+ No Operation does nothing. This instruction can be used for code alignment purposes.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __NOP(void)
+{
+ __ASM volatile ("nop");
+}
+
+
+/** \brief Wait For Interrupt
+
+ Wait For Interrupt is a hint instruction that suspends execution
+ until one of a number of events occurs.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __WFI(void)
+{
+ __ASM volatile ("wfi");
+}
+
+
+/** \brief Wait For Event
+
+ Wait For Event is a hint instruction that permits the processor to enter
+ a low-power state until one of a number of events occurs.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __WFE(void)
+{
+ __ASM volatile ("wfe");
+}
+
+
+/** \brief Send Event
+
+ Send Event is a hint instruction. It causes an event to be signaled to the CPU.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __SEV(void)
+{
+ __ASM volatile ("sev");
+}
+
+
+/** \brief Instruction Synchronization Barrier
+
+ Instruction Synchronization Barrier flushes the pipeline in the processor,
+ so that all instructions following the ISB are fetched from cache or
+ memory, after the instruction has been completed.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __ISB(void)
+{
+ __ASM volatile ("isb");
+}
+
+
+/** \brief Data Synchronization Barrier
+
+ This function acts as a special kind of Data Memory Barrier.
+ It completes when all explicit memory accesses before this instruction complete.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __DSB(void)
+{
+ __ASM volatile ("dsb");
+}
+
+
+/** \brief Data Memory Barrier
+
+ This function ensures the apparent order of the explicit memory operations before
+ and after the instruction, without ensuring their completion.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __DMB(void)
+{
+ __ASM volatile ("dmb");
+}
+
+
+/** \brief Reverse byte order (32 bit)
+
+ This function reverses the byte order in integer value.
+
+ \param [in] value Value to reverse
+ \return Reversed value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV(uint32_t value)
+{
+ uint32_t result;
+
+ __ASM volatile ("rev %0, %1" : "=r" (result) : "r" (value) );
+ return(result);
+}
+
+
+/** \brief Reverse byte order (16 bit)
+
+ This function reverses the byte order in two unsigned short values.
+
+ \param [in] value Value to reverse
+ \return Reversed value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV16(uint32_t value)
+{
+ uint32_t result;
+
+ __ASM volatile ("rev16 %0, %1" : "=r" (result) : "r" (value) );
+ return(result);
+}
+
+
+/** \brief Reverse byte order in signed short value
+
+ This function reverses the byte order in a signed short value with sign extension to integer.
+
+ \param [in] value Value to reverse
+ \return Reversed value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE int32_t __REVSH(int32_t value)
+{
+ uint32_t result;
+
+ __ASM volatile ("revsh %0, %1" : "=r" (result) : "r" (value) );
+ return(result);
+}
+
+
+/** \brief Rotate Right in unsigned value (32 bit)
+
+ This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits.
+
+ \param [in] value Value to rotate
+ \param [in] value Number of Bits to rotate
+ \return Rotated value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2)
+{
+
+ __ASM volatile ("ror %0, %0, %1" : "+r" (op1) : "r" (op2) );
+ return(op1);
+}
+
+
+#if (__CORTEX_M >= 0x03)
+
+/** \brief Reverse bit order of value
+
+ This function reverses the bit order of the given value.
+
+ \param [in] value Value to reverse
+ \return Reversed value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __RBIT(uint32_t value)
+{
+ uint32_t result;
+
+ __ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) );
+ return(result);
+}
+
+
+/** \brief LDR Exclusive (8 bit)
+
+ This function performs a exclusive LDR command for 8 bit value.
+
+ \param [in] ptr Pointer to data
+ \return value of type uint8_t at (*ptr)
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __LDREXB(volatile uint8_t *addr)
+{
+ uint8_t result;
+
+ __ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) );
+ return(result);
+}
+
+
+/** \brief LDR Exclusive (16 bit)
+
+ This function performs a exclusive LDR command for 16 bit values.
+
+ \param [in] ptr Pointer to data
+ \return value of type uint16_t at (*ptr)
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint16_t __LDREXH(volatile uint16_t *addr)
+{
+ uint16_t result;
+
+ __ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) );
+ return(result);
+}
+
+
+/** \brief LDR Exclusive (32 bit)
+
+ This function performs a exclusive LDR command for 32 bit values.
+
+ \param [in] ptr Pointer to data
+ \return value of type uint32_t at (*ptr)
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __LDREXW(volatile uint32_t *addr)
+{
+ uint32_t result;
+
+ __ASM volatile ("ldrex %0, [%1]" : "=r" (result) : "r" (addr) );
+ return(result);
+}
+
+
+/** \brief STR Exclusive (8 bit)
+
+ This function performs a exclusive STR command for 8 bit values.
+
+ \param [in] value Value to store
+ \param [in] ptr Pointer to location
+ \return 0 Function succeeded
+ \return 1 Function failed
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXB(uint8_t value, volatile uint8_t *addr)
+{
+ uint32_t result;
+
+ __ASM volatile ("strexb %0, %2, [%1]" : "=&r" (result) : "r" (addr), "r" (value) );
+ return(result);
+}
+
+
+/** \brief STR Exclusive (16 bit)
+
+ This function performs a exclusive STR command for 16 bit values.
+
+ \param [in] value Value to store
+ \param [in] ptr Pointer to location
+ \return 0 Function succeeded
+ \return 1 Function failed
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXH(uint16_t value, volatile uint16_t *addr)
+{
+ uint32_t result;
+
+ __ASM volatile ("strexh %0, %2, [%1]" : "=&r" (result) : "r" (addr), "r" (value) );
+ return(result);
+}
+
+
+/** \brief STR Exclusive (32 bit)
+
+ This function performs a exclusive STR command for 32 bit values.
+
+ \param [in] value Value to store
+ \param [in] ptr Pointer to location
+ \return 0 Function succeeded
+ \return 1 Function failed
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXW(uint32_t value, volatile uint32_t *addr)
+{
+ uint32_t result;
+
+ __ASM volatile ("strex %0, %2, [%1]" : "=&r" (result) : "r" (addr), "r" (value) );
+ return(result);
+}
+
+
+/** \brief Remove the exclusive lock
+
+ This function removes the exclusive lock which is created by LDREX.
+
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __CLREX(void)
+{
+ __ASM volatile ("clrex");
+}
+
+
+/** \brief Signed Saturate
+
+ This function saturates a signed value.
+
+ \param [in] value Value to be saturated
+ \param [in] sat Bit position to saturate to (1..32)
+ \return Saturated value
+ */
+#define __SSAT(ARG1,ARG2) \
+({ \
+ uint32_t __RES, __ARG1 = (ARG1); \
+ __ASM ("ssat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \
+ __RES; \
+ })
+
+
+/** \brief Unsigned Saturate
+
+ This function saturates an unsigned value.
+
+ \param [in] value Value to be saturated
+ \param [in] sat Bit position to saturate to (0..31)
+ \return Saturated value
+ */
+#define __USAT(ARG1,ARG2) \
+({ \
+ uint32_t __RES, __ARG1 = (ARG1); \
+ __ASM ("usat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \
+ __RES; \
+ })
+
+
+/** \brief Count leading zeros
+
+ This function counts the number of leading zeros of a data value.
+
+ \param [in] value Value to count the leading zeros
+ \return number of leading zeros in value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __CLZ(uint32_t value)
+{
+ uint8_t result;
+
+ __ASM volatile ("clz %0, %1" : "=r" (result) : "r" (value) );
+ return(result);
+}
+
+#endif /* (__CORTEX_M >= 0x03) */
+
+
+
+
+#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/
+/* TASKING carm specific functions */
+
+/*
+ * The CMSIS functions have been implemented as intrinsics in the compiler.
+ * Please use "carm -?i" to get an up to date list of all intrinsics,
+ * Including the CMSIS ones.
+ */
+
+#endif
+
+/*@}*/ /* end of group CMSIS_Core_InstructionInterface */
+
+#endif /* __CORE_CMINSTR_H */
diff --git a/grbl/stm32grbl/cmsis_boot/startup/startup_stm32f10x_md.c b/grbl/stm32grbl/cmsis_boot/startup/startup_stm32f10x_md.c
new file mode 100755
index 000000000..603b9b98f
--- /dev/null
+++ b/grbl/stm32grbl/cmsis_boot/startup/startup_stm32f10x_md.c
@@ -0,0 +1,292 @@
+/**
+ ******************************************************************************
+ * @file startup_stm32f10x_md.c
+ * @author Coocox
+ * @version V1.0
+ * @date 12/23/2009
+ * @brief STM32F10x Medium Density Devices Startup code.
+ * This module performs:
+ * - Set the initial SP
+ * - Set the vector table entries with the exceptions ISR address
+ * - Initialize data and bss
+ * - Setup the microcontroller system.
+ * - Call the application's entry point.
+ * After Reset the Cortex-M3 processor is in Thread mode,
+ * priority is Privileged, and the Stack is set to Main.
+ *******************************************************************************
+ */
+
+
+/*----------Stack Configuration-----------------------------------------------*/
+#define STACK_SIZE 0x00000100 /*!< The Stack size suggest using even number */
+__attribute__ ((section(".co_stack")))
+unsigned long pulStack[STACK_SIZE];
+
+
+/*----------Macro definition--------------------------------------------------*/
+#define WEAK __attribute__ ((weak))
+
+
+/*----------Declaration of the default fault handlers-------------------------*/
+/* System exception vector handler */
+__attribute__ ((used))
+void WEAK Reset_Handler(void);
+void WEAK NMI_Handler(void);
+void WEAK HardFault_Handler(void);
+void WEAK MemManage_Handler(void);
+void WEAK BusFault_Handler(void);
+void WEAK UsageFault_Handler(void);
+void WEAK SVC_Handler(void);
+void WEAK DebugMon_Handler(void);
+void WEAK PendSV_Handler(void);
+void WEAK SysTick_Handler(void);
+void WEAK WWDG_IRQHandler(void);
+void WEAK PVD_IRQHandler(void);
+void WEAK TAMPER_IRQHandler(void);
+void WEAK RTC_IRQHandler(void);
+void WEAK FLASH_IRQHandler(void);
+void WEAK RCC_IRQHandler(void);
+void WEAK EXTI0_IRQHandler(void);
+void WEAK EXTI1_IRQHandler(void);
+void WEAK EXTI2_IRQHandler(void);
+void WEAK EXTI3_IRQHandler(void);
+void WEAK EXTI4_IRQHandler(void);
+void WEAK DMA1_Channel1_IRQHandler(void);
+void WEAK DMA1_Channel2_IRQHandler(void);
+void WEAK DMA1_Channel3_IRQHandler(void);
+void WEAK DMA1_Channel4_IRQHandler(void);
+void WEAK DMA1_Channel5_IRQHandler(void);
+void WEAK DMA1_Channel6_IRQHandler(void);
+void WEAK DMA1_Channel7_IRQHandler(void);
+void WEAK ADC1_2_IRQHandler(void);
+void WEAK USB_HP_CAN1_TX_IRQHandler(void);
+void WEAK USB_LP_CAN1_RX0_IRQHandler(void);
+void WEAK CAN1_RX1_IRQHandler(void);
+void WEAK CAN1_SCE_IRQHandler(void);
+void WEAK EXTI9_5_IRQHandler(void);
+void WEAK TIM1_BRK_IRQHandler(void);
+void WEAK TIM1_UP_IRQHandler(void);
+void WEAK TIM1_TRG_COM_IRQHandler(void);
+void WEAK TIM1_CC_IRQHandler(void);
+void WEAK TIM2_IRQHandler(void);
+void WEAK TIM3_IRQHandler(void);
+void WEAK TIM4_IRQHandler(void);
+void WEAK I2C1_EV_IRQHandler(void);
+void WEAK I2C1_ER_IRQHandler(void);
+void WEAK I2C2_EV_IRQHandler(void);
+void WEAK I2C2_ER_IRQHandler(void);
+void WEAK SPI1_IRQHandler(void);
+void WEAK SPI2_IRQHandler(void);
+void WEAK USART1_IRQHandler(void);
+void WEAK USART2_IRQHandler(void);
+void WEAK USART3_IRQHandler(void);
+void WEAK EXTI15_10_IRQHandler(void);
+void WEAK RTCAlarm_IRQHandler(void);
+void WEAK USBWakeUp_IRQHandler(void);
+
+
+/*----------Symbols defined in linker script----------------------------------*/
+extern unsigned long _sidata; /*!< Start address for the initialization
+ values of the .data section. */
+extern unsigned long _sdata; /*!< Start address for the .data section */
+extern unsigned long _edata; /*!< End address for the .data section */
+extern unsigned long _sbss; /*!< Start address for the .bss section */
+extern unsigned long _ebss; /*!< End address for the .bss section */
+extern void _eram; /*!< End address for ram */
+
+
+/*----------Function prototypes-----------------------------------------------*/
+extern int main(void); /*!< The entry point for the application. */
+extern void SystemInit(void); /*!< Setup the microcontroller system(CMSIS) */
+void Default_Reset_Handler(void); /*!< Default reset handler */
+static void Default_Handler(void); /*!< Default exception handler */
+
+
+/**
+ *@brief The minimal vector table for a Cortex M3. Note that the proper constructs
+ * must be placed on this to ensure that it ends up at physical address
+ * 0x00000000.
+ */
+__attribute__ ((used,section(".isr_vector")))
+void (* const g_pfnVectors[])(void) =
+{
+ /*----------Core Exceptions-------------------------------------------------*/
+ (void *)&pulStack[STACK_SIZE], /*!< The initial stack pointer */
+ Reset_Handler, /*!< Reset Handler */
+ NMI_Handler, /*!< NMI Handler */
+ HardFault_Handler, /*!< Hard Fault Handler */
+ MemManage_Handler, /*!< MPU Fault Handler */
+ BusFault_Handler, /*!< Bus Fault Handler */
+ UsageFault_Handler, /*!< Usage Fault Handler */
+ 0,0,0,0, /*!< Reserved */
+ SVC_Handler, /*!< SVCall Handler */
+ DebugMon_Handler, /*!< Debug Monitor Handler */
+ 0, /*!< Reserved */
+ PendSV_Handler, /*!< PendSV Handler */
+ SysTick_Handler, /*!< SysTick Handler */
+
+ /*----------External Exceptions---------------------------------------------*/
+ WWDG_IRQHandler, /*!< 0: Window Watchdog */
+ PVD_IRQHandler, /*!< 1: PVD through EXTI Line detect */
+ TAMPER_IRQHandler, /*!< 2: Tamper */
+ RTC_IRQHandler, /*!< 3: RTC */
+ FLASH_IRQHandler, /*!< 4: Flash */
+ RCC_IRQHandler, /*!< 5: RCC */
+ EXTI0_IRQHandler, /*!< 6: EXTI Line 0 */
+ EXTI1_IRQHandler, /*!< 7: EXTI Line 1 */
+ EXTI2_IRQHandler, /*!< 8: EXTI Line 2 */
+ EXTI3_IRQHandler, /*!< 9: EXTI Line 3 */
+ EXTI4_IRQHandler, /*!< 10: EXTI Line 4 */
+ DMA1_Channel1_IRQHandler, /*!< 11: DMA1 Channel 1 */
+ DMA1_Channel2_IRQHandler, /*!< 12: DMA1 Channel 2 */
+ DMA1_Channel3_IRQHandler, /*!< 13: DMA1 Channel 3 */
+ DMA1_Channel4_IRQHandler, /*!< 14: DMA1 Channel 4 */
+ DMA1_Channel5_IRQHandler, /*!< 15: DMA1 Channel 5 */
+ DMA1_Channel6_IRQHandler, /*!< 16: DMA1 Channel 6 */
+ DMA1_Channel7_IRQHandler, /*!< 17: DMA1 Channel 7 */
+ ADC1_2_IRQHandler, /*!< 18: ADC1 & ADC2 */
+ USB_HP_CAN1_TX_IRQHandler, /*!< 19: USB High Priority or CAN1 TX */
+ USB_LP_CAN1_RX0_IRQHandler, /*!< 20: USB Low Priority or CAN1 RX0 */
+ CAN1_RX1_IRQHandler, /*!< 21: CAN1 RX1 */
+ CAN1_SCE_IRQHandler, /*!< 22: CAN1 SCE */
+ EXTI9_5_IRQHandler, /*!< 23: EXTI Line 9..5 */
+ TIM1_BRK_IRQHandler, /*!< 24: TIM1 Break */
+ TIM1_UP_IRQHandler, /*!< 25: TIM1 Update */
+ TIM1_TRG_COM_IRQHandler, /*!< 26: TIM1 Trigger and Commutation */
+ TIM1_CC_IRQHandler, /*!< 27: TIM1 Capture Compare */
+ TIM2_IRQHandler, /*!< 28: TIM2 */
+ TIM3_IRQHandler, /*!< 29: TIM3 */
+ TIM4_IRQHandler, /*!< 30: TIM4 */
+ I2C1_EV_IRQHandler, /*!< 31: I2C1 Event */
+ I2C1_ER_IRQHandler, /*!< 32: I2C1 Error */
+ I2C2_EV_IRQHandler, /*!< 33: I2C2 Event */
+ I2C2_ER_IRQHandler, /*!< 34: I2C2 Error */
+ SPI1_IRQHandler, /*!< 35: SPI1 */
+ SPI2_IRQHandler, /*!< 36: SPI2 */
+ USART1_IRQHandler, /*!< 37: USART1 */
+ USART2_IRQHandler, /*!< 38: USART2 */
+ USART3_IRQHandler, /*!< 39: USART3 */
+ EXTI15_10_IRQHandler, /*!< 40: EXTI Line 15..10 */
+ RTCAlarm_IRQHandler, /*!< 41: RTC Alarm through EXTI Line */
+ USBWakeUp_IRQHandler, /*!< 42: USB Wakeup from suspend */
+ 0,0,0,0,0,0,0, /*!< Reserved */
+ (void *)0xF108F85F /*!< Boot in RAM mode */
+};
+
+
+/**
+ * @brief This is the code that gets called when the processor first
+ * starts execution following a reset event. Only the absolutely
+ * necessary set is performed, after which the application
+ * supplied main() routine is called.
+ * @param None
+ * @retval None
+ */
+void Default_Reset_Handler(void)
+{
+ /* Initialize data and bss */
+ unsigned long *pulSrc, *pulDest;
+
+ /* Copy the data segment initializers from flash to SRAM */
+ pulSrc = &_sidata;
+
+ for(pulDest = &_sdata; pulDest < &_edata; )
+ {
+ *(pulDest++) = *(pulSrc++);
+ }
+
+ /* Zero fill the bss segment. This is done with inline assembly since this
+ will clear the value of pulDest if it is not kept in a register. */
+ __asm(" ldr r0, =_sbss\n"
+ " ldr r1, =_ebss\n"
+ " mov r2, #0\n"
+ " .thumb_func\n"
+ "zero_loop:\n"
+ " cmp r0, r1\n"
+ " it lt\n"
+ " strlt r2, [r0], #4\n"
+ " blt zero_loop");
+
+ /* Setup the microcontroller system. */
+ SystemInit();
+
+ /* Call the application's entry point.*/
+ main();
+}
+
+/**
+ *@brief Provide weak aliases for each Exception handler to the Default_Handler.
+ * As they are weak aliases, any function with the same name will override
+ * this definition.
+ */
+#pragma weak Reset_Handler = Default_Reset_Handler
+#pragma weak NMI_Handler = Default_Handler
+#pragma weak HardFault_Handler = Default_Handler
+#pragma weak MemManage_Handler = Default_Handler
+#pragma weak BusFault_Handler = Default_Handler
+#pragma weak UsageFault_Handler = Default_Handler
+#pragma weak SVC_Handler = Default_Handler
+#pragma weak DebugMon_Handler = Default_Handler
+#pragma weak PendSV_Handler = Default_Handler
+#pragma weak SysTick_Handler = Default_Handler
+#pragma weak WWDG_IRQHandler = Default_Handler
+#pragma weak PVD_IRQHandler = Default_Handler
+#pragma weak TAMPER_IRQHandler = Default_Handler
+#pragma weak RTC_IRQHandler = Default_Handler
+#pragma weak FLASH_IRQHandler = Default_Handler
+#pragma weak RCC_IRQHandler = Default_Handler
+#pragma weak EXTI0_IRQHandler = Default_Handler
+#pragma weak EXTI1_IRQHandler = Default_Handler
+#pragma weak EXTI2_IRQHandler = Default_Handler
+#pragma weak EXTI3_IRQHandler = Default_Handler
+#pragma weak EXTI4_IRQHandler = Default_Handler
+#pragma weak DMA1_Channel1_IRQHandler = Default_Handler
+#pragma weak DMA1_Channel2_IRQHandler = Default_Handler
+#pragma weak DMA1_Channel3_IRQHandler = Default_Handler
+#pragma weak DMA1_Channel4_IRQHandler = Default_Handler
+#pragma weak DMA1_Channel5_IRQHandler = Default_Handler
+#pragma weak DMA1_Channel6_IRQHandler = Default_Handler
+#pragma weak DMA1_Channel7_IRQHandler = Default_Handler
+#pragma weak ADC1_2_IRQHandler = Default_Handler
+#pragma weak USB_HP_CAN1_TX_IRQHandler = Default_Handler
+#pragma weak USB_LP_CAN1_RX0_IRQHandler = Default_Handler
+#pragma weak CAN1_RX1_IRQHandler = Default_Handler
+#pragma weak CAN1_SCE_IRQHandler = Default_Handler
+#pragma weak EXTI9_5_IRQHandler = Default_Handler
+#pragma weak TIM1_BRK_IRQHandler = Default_Handler
+#pragma weak TIM1_UP_IRQHandler = Default_Handler
+#pragma weak TIM1_TRG_COM_IRQHandler = Default_Handler
+#pragma weak TIM1_CC_IRQHandler = Default_Handler
+#pragma weak TIM2_IRQHandler = Default_Handler
+#pragma weak TIM3_IRQHandler = Default_Handler
+#pragma weak TIM4_IRQHandler = Default_Handler
+#pragma weak I2C1_EV_IRQHandler = Default_Handler
+#pragma weak I2C1_ER_IRQHandler = Default_Handler
+#pragma weak I2C2_EV_IRQHandler = Default_Handler
+#pragma weak I2C2_ER_IRQHandler = Default_Handler
+#pragma weak SPI1_IRQHandler = Default_Handler
+#pragma weak SPI2_IRQHandler = Default_Handler
+#pragma weak USART1_IRQHandler = Default_Handler
+#pragma weak USART2_IRQHandler = Default_Handler
+#pragma weak USART3_IRQHandler = Default_Handler
+#pragma weak EXTI15_10_IRQHandler = Default_Handler
+#pragma weak RTCAlarm_IRQHandler = Default_Handler
+#pragma weak USBWakeUp_IRQHandler = Default_Handler
+
+
+/**
+ * @brief This is the code that gets called when the processor receives an
+ * unexpected interrupt. This simply enters an infinite loop,
+ * preserving the system state for examination by a debugger.
+ * @param None
+ * @retval None
+ */
+static void Default_Handler(void)
+{
+ /* Go into an infinite loop. */
+ while (1)
+ {
+ }
+}
+
+/*********************** (C) COPYRIGHT 2009 Coocox ************END OF FILE*****/
diff --git a/grbl/stm32grbl/cmsis_boot/stm32f10x.h b/grbl/stm32grbl/cmsis_boot/stm32f10x.h
new file mode 100755
index 000000000..af0c7c9af
--- /dev/null
+++ b/grbl/stm32grbl/cmsis_boot/stm32f10x.h
@@ -0,0 +1,8336 @@
+/**
+ ******************************************************************************
+ * @file stm32f10x.h
+ * @author MCD Application Team
+ * @version V3.5.0
+ * @date 11-March-2011
+ * @brief CMSIS Cortex-M3 Device Peripheral Access Layer Header File.
+ * This file contains all the peripheral register's definitions, bits
+ * definitions and memory mapping for STM32F10x Connectivity line,
+ * High density, High density value line, Medium density,
+ * Medium density Value line, Low density, Low density Value line
+ * and XL-density devices.
+ *
+ * The file is the unique include file that the application programmer
+ * is using in the C source code, usually in main.c. This file contains:
+ * - Configuration section that allows to select:
+ * - The device used in the target application
+ * - To use or not the peripheral’s drivers in application code(i.e.
+ * code will be based on direct access to peripheral’s registers
+ * rather than drivers API), this option is controlled by
+ * "#define USE_STDPERIPH_DRIVER"
+ * - To change few application-specific parameters such as the HSE
+ * crystal frequency
+ * - Data structures and the address mapping for all peripherals
+ * - Peripheral's registers declarations and bits definition
+ * - Macros to access peripheral’s registers hardware
+ *
+ ******************************************************************************
+ * @attention
+ *
+ * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+ * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
+ * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
+ * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
+ * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
+ * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+ *
+ *
+ */
+
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __STM32F10x_CONF_H
+#define __STM32F10x_CONF_H
+
+/* Includes ------------------------------------------------------------------*/
+/* Uncomment the line below to enable peripheral header file inclusion */
+/* #include "stm32f10x_adc.h" */
+/* #include "stm32f10x_bkp.h" */
+/* #include "stm32f10x_can.h" */
+/* #include "stm32f10x_cec.h" */
+/* #include "stm32f10x_crc.h" */
+/* #include "stm32f10x_dac.h" */
+/* #include "stm32f10x_dbgmcu.h" */
+/* #include "stm32f10x_dma.h" */
+/* #include "stm32f10x_exti.h" */
+/* #include "stm32f10x_flash.h" */
+/* #include "stm32f10x_fsmc.h" */
+/* #include "stm32f10x_gpio.h" */
+/* #include "stm32f10x_i2c.h" */
+/* #include "stm32f10x_iwdg.h" */
+/* #include "stm32f10x_pwr.h" */
+/* #include "stm32f10x_rcc.h" */
+/* #include "stm32f10x_rtc.h" */
+/* #include "stm32f10x_sdio.h" */
+/* #include "stm32f10x_spi.h" */
+/* #include "stm32f10x_tim.h" */
+/* #include "stm32f10x_usart.h" */
+/* #include "stm32f10x_wwdg.h" */
+/* #include "misc.h" */ /* High level functions for NVIC and SysTick (add-on to CMSIS functions) */
+
+
+/* Exported types ------------------------------------------------------------*/
+/* Exported constants --------------------------------------------------------*/
+/* Uncomment the line below to expanse the "assert_param" macro in the
+ Standard Peripheral Library drivers code */
+/* #define USE_FULL_ASSERT 1 */
+
+/* Exported macro ------------------------------------------------------------*/
+#ifdef USE_FULL_ASSERT
+
+/**
+ * @brief The assert_param macro is used for function's parameters check.
+ * @param expr: If expr is false, it calls assert_failed function
+ * which reports the name of the source file and the source
+ * line number of the call that failed.
+ * If expr is true, it returns no value.
+ * @retval None
+ */
+ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__))
+/* Exported functions ------------------------------------------------------- */
+ void assert_failed(uint8_t* file, uint32_t line);
+#else
+ #define assert_param(expr) ((void)0)
+#endif /* USE_FULL_ASSERT */
+
+#endif /* __STM32F10x_CONF_H */
+
+/******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
diff --git a/grbl/stm32grbl/cmsis_boot/system_stm32f10x.c b/grbl/stm32grbl/cmsis_boot/system_stm32f10x.c
new file mode 100755
index 000000000..6fb4579ec
--- /dev/null
+++ b/grbl/stm32grbl/cmsis_boot/system_stm32f10x.c
@@ -0,0 +1,1094 @@
+/**
+ ******************************************************************************
+ * @file system_stm32f10x.c
+ * @author MCD Application Team
+ * @version V3.5.0
+ * @date 11-March-2011
+ * @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Source File.
+ *
+ * 1. This file provides two functions and one global variable to be called from
+ * user application:
+ * - SystemInit(): Setups the system clock (System clock source, PLL Multiplier
+ * factors, AHB/APBx prescalers and Flash settings).
+ * This function is called at startup just after reset and
+ * before branch to main program. This call is made inside
+ * the "startup_stm32f10x_xx.s" file.
+ *
+ * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used
+ * by the user application to setup the SysTick
+ * timer or configure other parameters.
+ *
+ * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must
+ * be called whenever the core clock is changed
+ * during program execution.
+ *
+ * 2. After each device reset the HSI (8 MHz) is used as system clock source.
+ * Then SystemInit() function is called, in "startup_stm32f10x_xx.s" file, to
+ * configure the system clock before to branch to main program.
+ *
+ * 3. If the system clock source selected by user fails to startup, the SystemInit()
+ * function will do nothing and HSI still used as system clock source. User can
+ * add some code to deal with this issue inside the SetSysClock() function.
+ *
+ * 4. The default value of HSE crystal is set to 8 MHz (or 25 MHz, depedning on
+ * the product used), refer to "HSE_VALUE" define in "stm32f10x.h" file.
+ * When HSE is used as system clock source, directly or through PLL, and you
+ * are using different crystal you have to adapt the HSE value to your own
+ * configuration.
+ *
+ ******************************************************************************
+ * @attention
+ *
+ * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+ * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
+ * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
+ * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
+ * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
+ * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+ *
+ *
+ ******************************************************************************
+ */
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f10x_flash.h"
+
+/** @addtogroup STM32F10x_StdPeriph_Driver
+ * @{
+ */
+
+/** @defgroup FLASH
+ * @brief FLASH driver modules
+ * @{
+ */
+
+/** @defgroup FLASH_Private_TypesDefinitions
+ * @{
+ */
+
+/**
+ * @}
+ */
+
+/** @defgroup FLASH_Private_Defines
+ * @{
+ */
+
+/* Flash Access Control Register bits */
+#define ACR_LATENCY_Mask ((uint32_t)0x00000038)
+#define ACR_HLFCYA_Mask ((uint32_t)0xFFFFFFF7)
+#define ACR_PRFTBE_Mask ((uint32_t)0xFFFFFFEF)
+
+/* Flash Access Control Register bits */
+#define ACR_PRFTBS_Mask ((uint32_t)0x00000020)
+
+/* Flash Control Register bits */
+#define CR_PG_Set ((uint32_t)0x00000001)
+#define CR_PG_Reset ((uint32_t)0x00001FFE)
+#define CR_PER_Set ((uint32_t)0x00000002)
+#define CR_PER_Reset ((uint32_t)0x00001FFD)
+#define CR_MER_Set ((uint32_t)0x00000004)
+#define CR_MER_Reset ((uint32_t)0x00001FFB)
+#define CR_OPTPG_Set ((uint32_t)0x00000010)
+#define CR_OPTPG_Reset ((uint32_t)0x00001FEF)
+#define CR_OPTER_Set ((uint32_t)0x00000020)
+#define CR_OPTER_Reset ((uint32_t)0x00001FDF)
+#define CR_STRT_Set ((uint32_t)0x00000040)
+#define CR_LOCK_Set ((uint32_t)0x00000080)
+
+/* FLASH Mask */
+#define RDPRT_Mask ((uint32_t)0x00000002)
+#define WRP0_Mask ((uint32_t)0x000000FF)
+#define WRP1_Mask ((uint32_t)0x0000FF00)
+#define WRP2_Mask ((uint32_t)0x00FF0000)
+#define WRP3_Mask ((uint32_t)0xFF000000)
+#define OB_USER_BFB2 ((uint16_t)0x0008)
+
+/* FLASH Keys */
+#define RDP_Key ((uint16_t)0x00A5)
+#define FLASH_KEY1 ((uint32_t)0x45670123)
+#define FLASH_KEY2 ((uint32_t)0xCDEF89AB)
+
+/* FLASH BANK address */
+#define FLASH_BANK1_END_ADDRESS ((uint32_t)0x807FFFF)
+
+/* Delay definition */
+#define EraseTimeout ((uint32_t)0x000B0000)
+#define ProgramTimeout ((uint32_t)0x00002000)
+/**
+ * @}
+ */
+
+/** @defgroup FLASH_Private_Macros
+ * @{
+ */
+
+/**
+ * @}
+ */
+
+/** @defgroup FLASH_Private_Variables
+ * @{
+ */
+
+/**
+ * @}
+ */
+
+/** @defgroup FLASH_Private_FunctionPrototypes
+ * @{
+ */
+
+/**
+ * @}
+ */
+
+/** @defgroup FLASH_Private_Functions
+ * @{
+ */
+
+/**
+@code
+
+ This driver provides functions to configure and program the Flash memory of all STM32F10x devices,
+ including the latest STM32F10x_XL density devices.
+
+ STM32F10x_XL devices feature up to 1 Mbyte with dual bank architecture for read-while-write (RWW) capability:
+ - bank1: fixed size of 512 Kbytes (256 pages of 2Kbytes each)
+ - bank2: up to 512 Kbytes (up to 256 pages of 2Kbytes each)
+ While other STM32F10x devices features only one bank with memory up to 512 Kbytes.
+
+ In version V3.3.0, some functions were updated and new ones were added to support
+ STM32F10x_XL devices. Thus some functions manages all devices, while other are
+ dedicated for XL devices only.
+
+ The table below presents the list of available functions depending on the used STM32F10x devices.
+
+ ***************************************************
+ * Legacy functions used for all STM32F10x devices *
+ ***************************************************
+ +----------------------------------------------------------------------------------------------------------------------------------+
+ | Functions prototypes |STM32F10x_XL|Other STM32F10x| Comments |
+ | | devices | devices | |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_SetLatency | Yes | Yes | No change |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_HalfCycleAccessCmd | Yes | Yes | No change |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_PrefetchBufferCmd | Yes | Yes | No change |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_Unlock | Yes | Yes | - For STM32F10X_XL devices: unlock Bank1 and Bank2. |
+ | | | | - For other devices: unlock Bank1 and it is equivalent |
+ | | | | to FLASH_UnlockBank1 function. |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_Lock | Yes | Yes | - For STM32F10X_XL devices: lock Bank1 and Bank2. |
+ | | | | - For other devices: lock Bank1 and it is equivalent |
+ | | | | to FLASH_LockBank1 function. |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_ErasePage | Yes | Yes | - For STM32F10x_XL devices: erase a page in Bank1 and Bank2 |
+ | | | | - For other devices: erase a page in Bank1 |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_EraseAllPages | Yes | Yes | - For STM32F10x_XL devices: erase all pages in Bank1 and Bank2 |
+ | | | | - For other devices: erase all pages in Bank1 |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_EraseOptionBytes | Yes | Yes | No change |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_ProgramWord | Yes | Yes | Updated to program up to 1MByte (depending on the used device) |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_ProgramHalfWord | Yes | Yes | Updated to program up to 1MByte (depending on the used device) |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_ProgramOptionByteData | Yes | Yes | No change |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_EnableWriteProtection | Yes | Yes | No change |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_ReadOutProtection | Yes | Yes | No change |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_UserOptionByteConfig | Yes | Yes | No change |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_GetUserOptionByte | Yes | Yes | No change |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_GetWriteProtectionOptionByte | Yes | Yes | No change |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_GetReadOutProtectionStatus | Yes | Yes | No change |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_GetPrefetchBufferStatus | Yes | Yes | No change |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_ITConfig | Yes | Yes | - For STM32F10x_XL devices: enable Bank1 and Bank2's interrupts|
+ | | | | - For other devices: enable Bank1's interrupts |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_GetFlagStatus | Yes | Yes | - For STM32F10x_XL devices: return Bank1 and Bank2's flag status|
+ | | | | - For other devices: return Bank1's flag status |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_ClearFlag | Yes | Yes | - For STM32F10x_XL devices: clear Bank1 and Bank2's flag |
+ | | | | - For other devices: clear Bank1's flag |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_GetStatus | Yes | Yes | - Return the status of Bank1 (for all devices) |
+ | | | | equivalent to FLASH_GetBank1Status function |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_WaitForLastOperation | Yes | Yes | - Wait for Bank1 last operation (for all devices) |
+ | | | | equivalent to: FLASH_WaitForLastBank1Operation function |
+ +----------------------------------------------------------------------------------------------------------------------------------+
+
+ ************************************************************************************************************************
+ * New functions used for all STM32F10x devices to manage Bank1: *
+ * - These functions are mainly useful for STM32F10x_XL density devices, to have separate control for Bank1 and bank2 *
+ * - For other devices, these functions are optional (covered by functions listed above) *
+ ************************************************************************************************************************
+ +----------------------------------------------------------------------------------------------------------------------------------+
+ | Functions prototypes |STM32F10x_XL|Other STM32F10x| Comments |
+ | | devices | devices | |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ | FLASH_UnlockBank1 | Yes | Yes | - Unlock Bank1 |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_LockBank1 | Yes | Yes | - Lock Bank1 |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ | FLASH_EraseAllBank1Pages | Yes | Yes | - Erase all pages in Bank1 |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ | FLASH_GetBank1Status | Yes | Yes | - Return the status of Bank1 |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ | FLASH_WaitForLastBank1Operation | Yes | Yes | - Wait for Bank1 last operation |
+ +----------------------------------------------------------------------------------------------------------------------------------+
+
+ *****************************************************************************
+ * New Functions used only with STM32F10x_XL density devices to manage Bank2 *
+ *****************************************************************************
+ +----------------------------------------------------------------------------------------------------------------------------------+
+ | Functions prototypes |STM32F10x_XL|Other STM32F10x| Comments |
+ | | devices | devices | |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ | FLASH_UnlockBank2 | Yes | No | - Unlock Bank2 |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ |FLASH_LockBank2 | Yes | No | - Lock Bank2 |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ | FLASH_EraseAllBank2Pages | Yes | No | - Erase all pages in Bank2 |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ | FLASH_GetBank2Status | Yes | No | - Return the status of Bank2 |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ | FLASH_WaitForLastBank2Operation | Yes | No | - Wait for Bank2 last operation |
+ |----------------------------------------------------------------------------------------------------------------------------------|
+ | FLASH_BootConfig | Yes | No | - Configure to boot from Bank1 or Bank2 |
+ +----------------------------------------------------------------------------------------------------------------------------------+
+@endcode
+*/
+
+
+/**
+ * @brief Sets the code latency value.
+ * @note This function can be used for all STM32F10x devices.
+ * @param FLASH_Latency: specifies the FLASH Latency value.
+ * This parameter can be one of the following values:
+ * @arg FLASH_Latency_0: FLASH Zero Latency cycle
+ * @arg FLASH_Latency_1: FLASH One Latency cycle
+ * @arg FLASH_Latency_2: FLASH Two Latency cycles
+ * @retval None
+ */
+void FLASH_SetLatency(uint32_t FLASH_Latency)
+{
+ uint32_t tmpreg = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FLASH_LATENCY(FLASH_Latency));
+
+ /* Read the ACR register */
+ tmpreg = FLASH->ACR;
+
+ /* Sets the Latency value */
+ tmpreg &= ACR_LATENCY_Mask;
+ tmpreg |= FLASH_Latency;
+
+ /* Write the ACR register */
+ FLASH->ACR = tmpreg;
+}
+
+/**
+ * @brief Enables or disables the Half cycle flash access.
+ * @note This function can be used for all STM32F10x devices.
+ * @param FLASH_HalfCycleAccess: specifies the FLASH Half cycle Access mode.
+ * This parameter can be one of the following values:
+ * @arg FLASH_HalfCycleAccess_Enable: FLASH Half Cycle Enable
+ * @arg FLASH_HalfCycleAccess_Disable: FLASH Half Cycle Disable
+ * @retval None
+ */
+void FLASH_HalfCycleAccessCmd(uint32_t FLASH_HalfCycleAccess)
+{
+ /* Check the parameters */
+ assert_param(IS_FLASH_HALFCYCLEACCESS_STATE(FLASH_HalfCycleAccess));
+
+ /* Enable or disable the Half cycle access */
+ FLASH->ACR &= ACR_HLFCYA_Mask;
+ FLASH->ACR |= FLASH_HalfCycleAccess;
+}
+
+/**
+ * @brief Enables or disables the Prefetch Buffer.
+ * @note This function can be used for all STM32F10x devices.
+ * @param FLASH_PrefetchBuffer: specifies the Prefetch buffer status.
+ * This parameter can be one of the following values:
+ * @arg FLASH_PrefetchBuffer_Enable: FLASH Prefetch Buffer Enable
+ * @arg FLASH_PrefetchBuffer_Disable: FLASH Prefetch Buffer Disable
+ * @retval None
+ */
+void FLASH_PrefetchBufferCmd(uint32_t FLASH_PrefetchBuffer)
+{
+ /* Check the parameters */
+ assert_param(IS_FLASH_PREFETCHBUFFER_STATE(FLASH_PrefetchBuffer));
+
+ /* Enable or disable the Prefetch Buffer */
+ FLASH->ACR &= ACR_PRFTBE_Mask;
+ FLASH->ACR |= FLASH_PrefetchBuffer;
+}
+
+/**
+ * @brief Unlocks the FLASH Program Erase Controller.
+ * @note This function can be used for all STM32F10x devices.
+ * - For STM32F10X_XL devices this function unlocks Bank1 and Bank2.
+ * - For all other devices it unlocks Bank1 and it is equivalent
+ * to FLASH_UnlockBank1 function..
+ * @param None
+ * @retval None
+ */
+void FLASH_Unlock(void)
+{
+ /* Authorize the FPEC of Bank1 Access */
+ FLASH->KEYR = FLASH_KEY1;
+ FLASH->KEYR = FLASH_KEY2;
+
+#ifdef STM32F10X_XL
+ /* Authorize the FPEC of Bank2 Access */
+ FLASH->KEYR2 = FLASH_KEY1;
+ FLASH->KEYR2 = FLASH_KEY2;
+#endif /* STM32F10X_XL */
+}
+/**
+ * @brief Unlocks the FLASH Bank1 Program Erase Controller.
+ * @note This function can be used for all STM32F10x devices.
+ * - For STM32F10X_XL devices this function unlocks Bank1.
+ * - For all other devices it unlocks Bank1 and it is
+ * equivalent to FLASH_Unlock function.
+ * @param None
+ * @retval None
+ */
+void FLASH_UnlockBank1(void)
+{
+ /* Authorize the FPEC of Bank1 Access */
+ FLASH->KEYR = FLASH_KEY1;
+ FLASH->KEYR = FLASH_KEY2;
+}
+
+#ifdef STM32F10X_XL
+/**
+ * @brief Unlocks the FLASH Bank2 Program Erase Controller.
+ * @note This function can be used only for STM32F10X_XL density devices.
+ * @param None
+ * @retval None
+ */
+void FLASH_UnlockBank2(void)
+{
+ /* Authorize the FPEC of Bank2 Access */
+ FLASH->KEYR2 = FLASH_KEY1;
+ FLASH->KEYR2 = FLASH_KEY2;
+
+}
+#endif /* STM32F10X_XL */
+
+/**
+ * @brief Locks the FLASH Program Erase Controller.
+ * @note This function can be used for all STM32F10x devices.
+ * - For STM32F10X_XL devices this function Locks Bank1 and Bank2.
+ * - For all other devices it Locks Bank1 and it is equivalent
+ * to FLASH_LockBank1 function.
+ * @param None
+ * @retval None
+ */
+void FLASH_Lock(void)
+{
+ /* Set the Lock Bit to lock the FPEC and the CR of Bank1 */
+ FLASH->CR |= CR_LOCK_Set;
+
+#ifdef STM32F10X_XL
+ /* Set the Lock Bit to lock the FPEC and the CR of Bank2 */
+ FLASH->CR2 |= CR_LOCK_Set;
+#endif /* STM32F10X_XL */
+}
+
+/**
+ * @brief Locks the FLASH Bank1 Program Erase Controller.
+ * @note this function can be used for all STM32F10x devices.
+ * - For STM32F10X_XL devices this function Locks Bank1.
+ * - For all other devices it Locks Bank1 and it is equivalent
+ * to FLASH_Lock function.
+ * @param None
+ * @retval None
+ */
+void FLASH_LockBank1(void)
+{
+ /* Set the Lock Bit to lock the FPEC and the CR of Bank1 */
+ FLASH->CR |= CR_LOCK_Set;
+}
+
+#ifdef STM32F10X_XL
+/**
+ * @brief Locks the FLASH Bank2 Program Erase Controller.
+ * @note This function can be used only for STM32F10X_XL density devices.
+ * @param None
+ * @retval None
+ */
+void FLASH_LockBank2(void)
+{
+ /* Set the Lock Bit to lock the FPEC and the CR of Bank2 */
+ FLASH->CR2 |= CR_LOCK_Set;
+}
+#endif /* STM32F10X_XL */
+
+/**
+ * @brief Erases a specified FLASH page.
+ * @note This function can be used for all STM32F10x devices.
+ * @param Page_Address: The page address to be erased.
+ * @retval FLASH Status: The returned value can be: FLASH_BUSY, FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_ErasePage(uint32_t Page_Address)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+ /* Check the parameters */
+ assert_param(IS_FLASH_ADDRESS(Page_Address));
+
+#ifdef STM32F10X_XL
+ if(Page_Address < FLASH_BANK1_END_ADDRESS)
+ {
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank1Operation(EraseTimeout);
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to erase the page */
+ FLASH->CR|= CR_PER_Set;
+ FLASH->AR = Page_Address;
+ FLASH->CR|= CR_STRT_Set;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank1Operation(EraseTimeout);
+
+ /* Disable the PER Bit */
+ FLASH->CR &= CR_PER_Reset;
+ }
+ }
+ else
+ {
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank2Operation(EraseTimeout);
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to erase the page */
+ FLASH->CR2|= CR_PER_Set;
+ FLASH->AR2 = Page_Address;
+ FLASH->CR2|= CR_STRT_Set;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank2Operation(EraseTimeout);
+
+ /* Disable the PER Bit */
+ FLASH->CR2 &= CR_PER_Reset;
+ }
+ }
+#else
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(EraseTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to erase the page */
+ FLASH->CR|= CR_PER_Set;
+ FLASH->AR = Page_Address;
+ FLASH->CR|= CR_STRT_Set;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(EraseTimeout);
+
+ /* Disable the PER Bit */
+ FLASH->CR &= CR_PER_Reset;
+ }
+#endif /* STM32F10X_XL */
+
+ /* Return the Erase Status */
+ return status;
+}
+
+/**
+ * @brief Erases all FLASH pages.
+ * @note This function can be used for all STM32F10x devices.
+ * @param None
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_EraseAllPages(void)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+
+#ifdef STM32F10X_XL
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank1Operation(EraseTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to erase all pages */
+ FLASH->CR |= CR_MER_Set;
+ FLASH->CR |= CR_STRT_Set;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank1Operation(EraseTimeout);
+
+ /* Disable the MER Bit */
+ FLASH->CR &= CR_MER_Reset;
+ }
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to erase all pages */
+ FLASH->CR2 |= CR_MER_Set;
+ FLASH->CR2 |= CR_STRT_Set;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank2Operation(EraseTimeout);
+
+ /* Disable the MER Bit */
+ FLASH->CR2 &= CR_MER_Reset;
+ }
+#else
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(EraseTimeout);
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to erase all pages */
+ FLASH->CR |= CR_MER_Set;
+ FLASH->CR |= CR_STRT_Set;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(EraseTimeout);
+
+ /* Disable the MER Bit */
+ FLASH->CR &= CR_MER_Reset;
+ }
+#endif /* STM32F10X_XL */
+
+ /* Return the Erase Status */
+ return status;
+}
+
+/**
+ * @brief Erases all Bank1 FLASH pages.
+ * @note This function can be used for all STM32F10x devices.
+ * - For STM32F10X_XL devices this function erases all Bank1 pages.
+ * - For all other devices it erases all Bank1 pages and it is equivalent
+ * to FLASH_EraseAllPages function.
+ * @param None
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_EraseAllBank1Pages(void)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank1Operation(EraseTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to erase all pages */
+ FLASH->CR |= CR_MER_Set;
+ FLASH->CR |= CR_STRT_Set;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank1Operation(EraseTimeout);
+
+ /* Disable the MER Bit */
+ FLASH->CR &= CR_MER_Reset;
+ }
+ /* Return the Erase Status */
+ return status;
+}
+
+#ifdef STM32F10X_XL
+/**
+ * @brief Erases all Bank2 FLASH pages.
+ * @note This function can be used only for STM32F10x_XL density devices.
+ * @param None
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_EraseAllBank2Pages(void)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank2Operation(EraseTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to erase all pages */
+ FLASH->CR2 |= CR_MER_Set;
+ FLASH->CR2 |= CR_STRT_Set;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank2Operation(EraseTimeout);
+
+ /* Disable the MER Bit */
+ FLASH->CR2 &= CR_MER_Reset;
+ }
+ /* Return the Erase Status */
+ return status;
+}
+#endif /* STM32F10X_XL */
+
+/**
+ * @brief Erases the FLASH option bytes.
+ * @note This functions erases all option bytes except the Read protection (RDP).
+ * @note This function can be used for all STM32F10x devices.
+ * @param None
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_EraseOptionBytes(void)
+{
+ uint16_t rdptmp = RDP_Key;
+
+ FLASH_Status status = FLASH_COMPLETE;
+
+ /* Get the actual read protection Option Byte value */
+ if(FLASH_GetReadOutProtectionStatus() != RESET)
+ {
+ rdptmp = 0x00;
+ }
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(EraseTimeout);
+ if(status == FLASH_COMPLETE)
+ {
+ /* Authorize the small information block programming */
+ FLASH->OPTKEYR = FLASH_KEY1;
+ FLASH->OPTKEYR = FLASH_KEY2;
+
+ /* if the previous operation is completed, proceed to erase the option bytes */
+ FLASH->CR |= CR_OPTER_Set;
+ FLASH->CR |= CR_STRT_Set;
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(EraseTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the erase operation is completed, disable the OPTER Bit */
+ FLASH->CR &= CR_OPTER_Reset;
+
+ /* Enable the Option Bytes Programming operation */
+ FLASH->CR |= CR_OPTPG_Set;
+ /* Restore the last read protection Option Byte value */
+ OB->RDP = (uint16_t)rdptmp;
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ if(status != FLASH_TIMEOUT)
+ {
+ /* if the program operation is completed, disable the OPTPG Bit */
+ FLASH->CR &= CR_OPTPG_Reset;
+ }
+ }
+ else
+ {
+ if (status != FLASH_TIMEOUT)
+ {
+ /* Disable the OPTPG Bit */
+ FLASH->CR &= CR_OPTPG_Reset;
+ }
+ }
+ }
+ /* Return the erase status */
+ return status;
+}
+
+/**
+ * @brief Programs a word at a specified address.
+ * @note This function can be used for all STM32F10x devices.
+ * @param Address: specifies the address to be programmed.
+ * @param Data: specifies the data to be programmed.
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_ProgramWord(uint32_t Address, uint32_t Data)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+ __IO uint32_t tmp = 0;
+
+ /* Check the parameters */
+ assert_param(IS_FLASH_ADDRESS(Address));
+
+#ifdef STM32F10X_XL
+ if(Address < FLASH_BANK1_END_ADDRESS - 2)
+ {
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank1Operation(ProgramTimeout);
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to program the new first
+ half word */
+ FLASH->CR |= CR_PG_Set;
+
+ *(__IO uint16_t*)Address = (uint16_t)Data;
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to program the new second
+ half word */
+ tmp = Address + 2;
+
+ *(__IO uint16_t*) tmp = Data >> 16;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ /* Disable the PG Bit */
+ FLASH->CR &= CR_PG_Reset;
+ }
+ else
+ {
+ /* Disable the PG Bit */
+ FLASH->CR &= CR_PG_Reset;
+ }
+ }
+ }
+ else if(Address == (FLASH_BANK1_END_ADDRESS - 1))
+ {
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank1Operation(ProgramTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to program the new first
+ half word */
+ FLASH->CR |= CR_PG_Set;
+
+ *(__IO uint16_t*)Address = (uint16_t)Data;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank1Operation(ProgramTimeout);
+
+ /* Disable the PG Bit */
+ FLASH->CR &= CR_PG_Reset;
+ }
+ else
+ {
+ /* Disable the PG Bit */
+ FLASH->CR &= CR_PG_Reset;
+ }
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank2Operation(ProgramTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to program the new second
+ half word */
+ FLASH->CR2 |= CR_PG_Set;
+ tmp = Address + 2;
+
+ *(__IO uint16_t*) tmp = Data >> 16;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank2Operation(ProgramTimeout);
+
+ /* Disable the PG Bit */
+ FLASH->CR2 &= CR_PG_Reset;
+ }
+ else
+ {
+ /* Disable the PG Bit */
+ FLASH->CR2 &= CR_PG_Reset;
+ }
+ }
+ else
+ {
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank2Operation(ProgramTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to program the new first
+ half word */
+ FLASH->CR2 |= CR_PG_Set;
+
+ *(__IO uint16_t*)Address = (uint16_t)Data;
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank2Operation(ProgramTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to program the new second
+ half word */
+ tmp = Address + 2;
+
+ *(__IO uint16_t*) tmp = Data >> 16;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank2Operation(ProgramTimeout);
+
+ /* Disable the PG Bit */
+ FLASH->CR2 &= CR_PG_Reset;
+ }
+ else
+ {
+ /* Disable the PG Bit */
+ FLASH->CR2 &= CR_PG_Reset;
+ }
+ }
+ }
+#else
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to program the new first
+ half word */
+ FLASH->CR |= CR_PG_Set;
+
+ *(__IO uint16_t*)Address = (uint16_t)Data;
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to program the new second
+ half word */
+ tmp = Address + 2;
+
+ *(__IO uint16_t*) tmp = Data >> 16;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ /* Disable the PG Bit */
+ FLASH->CR &= CR_PG_Reset;
+ }
+ else
+ {
+ /* Disable the PG Bit */
+ FLASH->CR &= CR_PG_Reset;
+ }
+ }
+#endif /* STM32F10X_XL */
+
+ /* Return the Program Status */
+ return status;
+}
+
+/**
+ * @brief Programs a half word at a specified address.
+ * @note This function can be used for all STM32F10x devices.
+ * @param Address: specifies the address to be programmed.
+ * @param Data: specifies the data to be programmed.
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_ProgramHalfWord(uint32_t Address, uint16_t Data)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+ /* Check the parameters */
+ assert_param(IS_FLASH_ADDRESS(Address));
+
+#ifdef STM32F10X_XL
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ if(Address < FLASH_BANK1_END_ADDRESS)
+ {
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to program the new data */
+ FLASH->CR |= CR_PG_Set;
+
+ *(__IO uint16_t*)Address = Data;
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank1Operation(ProgramTimeout);
+
+ /* Disable the PG Bit */
+ FLASH->CR &= CR_PG_Reset;
+ }
+ }
+ else
+ {
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to program the new data */
+ FLASH->CR2 |= CR_PG_Set;
+
+ *(__IO uint16_t*)Address = Data;
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastBank2Operation(ProgramTimeout);
+
+ /* Disable the PG Bit */
+ FLASH->CR2 &= CR_PG_Reset;
+ }
+ }
+#else
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the previous operation is completed, proceed to program the new data */
+ FLASH->CR |= CR_PG_Set;
+
+ *(__IO uint16_t*)Address = Data;
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ /* Disable the PG Bit */
+ FLASH->CR &= CR_PG_Reset;
+ }
+#endif /* STM32F10X_XL */
+
+ /* Return the Program Status */
+ return status;
+}
+
+/**
+ * @brief Programs a half word at a specified Option Byte Data address.
+ * @note This function can be used for all STM32F10x devices.
+ * @param Address: specifies the address to be programmed.
+ * This parameter can be 0x1FFFF804 or 0x1FFFF806.
+ * @param Data: specifies the data to be programmed.
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_ProgramOptionByteData(uint32_t Address, uint8_t Data)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+ /* Check the parameters */
+ assert_param(IS_OB_DATA_ADDRESS(Address));
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* Authorize the small information block programming */
+ FLASH->OPTKEYR = FLASH_KEY1;
+ FLASH->OPTKEYR = FLASH_KEY2;
+ /* Enables the Option Bytes Programming operation */
+ FLASH->CR |= CR_OPTPG_Set;
+ *(__IO uint16_t*)Address = Data;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+ if(status != FLASH_TIMEOUT)
+ {
+ /* if the program operation is completed, disable the OPTPG Bit */
+ FLASH->CR &= CR_OPTPG_Reset;
+ }
+ }
+ /* Return the Option Byte Data Program Status */
+ return status;
+}
+
+/**
+ * @brief Write protects the desired pages
+ * @note This function can be used for all STM32F10x devices.
+ * @param FLASH_Pages: specifies the address of the pages to be write protected.
+ * This parameter can be:
+ * @arg For @b STM32_Low-density_devices: value between FLASH_WRProt_Pages0to3 and FLASH_WRProt_Pages28to31
+ * @arg For @b STM32_Medium-density_devices: value between FLASH_WRProt_Pages0to3
+ * and FLASH_WRProt_Pages124to127
+ * @arg For @b STM32_High-density_devices: value between FLASH_WRProt_Pages0to1 and
+ * FLASH_WRProt_Pages60to61 or FLASH_WRProt_Pages62to255
+ * @arg For @b STM32_Connectivity_line_devices: value between FLASH_WRProt_Pages0to1 and
+ * FLASH_WRProt_Pages60to61 or FLASH_WRProt_Pages62to127
+ * @arg For @b STM32_XL-density_devices: value between FLASH_WRProt_Pages0to1 and
+ * FLASH_WRProt_Pages60to61 or FLASH_WRProt_Pages62to511
+ * @arg FLASH_WRProt_AllPages
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_EnableWriteProtection(uint32_t FLASH_Pages)
+{
+ uint16_t WRP0_Data = 0xFFFF, WRP1_Data = 0xFFFF, WRP2_Data = 0xFFFF, WRP3_Data = 0xFFFF;
+
+ FLASH_Status status = FLASH_COMPLETE;
+
+ /* Check the parameters */
+ assert_param(IS_FLASH_WRPROT_PAGE(FLASH_Pages));
+
+ FLASH_Pages = (uint32_t)(~FLASH_Pages);
+ WRP0_Data = (uint16_t)(FLASH_Pages & WRP0_Mask);
+ WRP1_Data = (uint16_t)((FLASH_Pages & WRP1_Mask) >> 8);
+ WRP2_Data = (uint16_t)((FLASH_Pages & WRP2_Mask) >> 16);
+ WRP3_Data = (uint16_t)((FLASH_Pages & WRP3_Mask) >> 24);
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* Authorizes the small information block programming */
+ FLASH->OPTKEYR = FLASH_KEY1;
+ FLASH->OPTKEYR = FLASH_KEY2;
+ FLASH->CR |= CR_OPTPG_Set;
+ if(WRP0_Data != 0xFF)
+ {
+ OB->WRP0 = WRP0_Data;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+ }
+ if((status == FLASH_COMPLETE) && (WRP1_Data != 0xFF))
+ {
+ OB->WRP1 = WRP1_Data;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+ }
+ if((status == FLASH_COMPLETE) && (WRP2_Data != 0xFF))
+ {
+ OB->WRP2 = WRP2_Data;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+ }
+
+ if((status == FLASH_COMPLETE)&& (WRP3_Data != 0xFF))
+ {
+ OB->WRP3 = WRP3_Data;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+ }
+
+ if(status != FLASH_TIMEOUT)
+ {
+ /* if the program operation is completed, disable the OPTPG Bit */
+ FLASH->CR &= CR_OPTPG_Reset;
+ }
+ }
+ /* Return the write protection operation Status */
+ return status;
+}
+
+/**
+ * @brief Enables or disables the read out protection.
+ * @note If the user has already programmed the other option bytes before calling
+ * this function, he must re-program them since this function erases all option bytes.
+ * @note This function can be used for all STM32F10x devices.
+ * @param Newstate: new state of the ReadOut Protection.
+ * This parameter can be: ENABLE or DISABLE.
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_ReadOutProtection(FunctionalState NewState)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+ /* Check the parameters */
+ assert_param(IS_FUNCTIONAL_STATE(NewState));
+ status = FLASH_WaitForLastOperation(EraseTimeout);
+ if(status == FLASH_COMPLETE)
+ {
+ /* Authorizes the small information block programming */
+ FLASH->OPTKEYR = FLASH_KEY1;
+ FLASH->OPTKEYR = FLASH_KEY2;
+ FLASH->CR |= CR_OPTER_Set;
+ FLASH->CR |= CR_STRT_Set;
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(EraseTimeout);
+ if(status == FLASH_COMPLETE)
+ {
+ /* if the erase operation is completed, disable the OPTER Bit */
+ FLASH->CR &= CR_OPTER_Reset;
+ /* Enable the Option Bytes Programming operation */
+ FLASH->CR |= CR_OPTPG_Set;
+ if(NewState != DISABLE)
+ {
+ OB->RDP = 0x00;
+ }
+ else
+ {
+ OB->RDP = RDP_Key;
+ }
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(EraseTimeout);
+
+ if(status != FLASH_TIMEOUT)
+ {
+ /* if the program operation is completed, disable the OPTPG Bit */
+ FLASH->CR &= CR_OPTPG_Reset;
+ }
+ }
+ else
+ {
+ if(status != FLASH_TIMEOUT)
+ {
+ /* Disable the OPTER Bit */
+ FLASH->CR &= CR_OPTER_Reset;
+ }
+ }
+ }
+ /* Return the protection operation Status */
+ return status;
+}
+
+/**
+ * @brief Programs the FLASH User Option Byte: IWDG_SW / RST_STOP / RST_STDBY.
+ * @note This function can be used for all STM32F10x devices.
+ * @param OB_IWDG: Selects the IWDG mode
+ * This parameter can be one of the following values:
+ * @arg OB_IWDG_SW: Software IWDG selected
+ * @arg OB_IWDG_HW: Hardware IWDG selected
+ * @param OB_STOP: Reset event when entering STOP mode.
+ * This parameter can be one of the following values:
+ * @arg OB_STOP_NoRST: No reset generated when entering in STOP
+ * @arg OB_STOP_RST: Reset generated when entering in STOP
+ * @param OB_STDBY: Reset event when entering Standby mode.
+ * This parameter can be one of the following values:
+ * @arg OB_STDBY_NoRST: No reset generated when entering in STANDBY
+ * @arg OB_STDBY_RST: Reset generated when entering in STANDBY
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_UserOptionByteConfig(uint16_t OB_IWDG, uint16_t OB_STOP, uint16_t OB_STDBY)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+
+ /* Check the parameters */
+ assert_param(IS_OB_IWDG_SOURCE(OB_IWDG));
+ assert_param(IS_OB_STOP_SOURCE(OB_STOP));
+ assert_param(IS_OB_STDBY_SOURCE(OB_STDBY));
+
+ /* Authorize the small information block programming */
+ FLASH->OPTKEYR = FLASH_KEY1;
+ FLASH->OPTKEYR = FLASH_KEY2;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* Enable the Option Bytes Programming operation */
+ FLASH->CR |= CR_OPTPG_Set;
+
+ OB->USER = OB_IWDG | (uint16_t)(OB_STOP | (uint16_t)(OB_STDBY | ((uint16_t)0xF8)));
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+ if(status != FLASH_TIMEOUT)
+ {
+ /* if the program operation is completed, disable the OPTPG Bit */
+ FLASH->CR &= CR_OPTPG_Reset;
+ }
+ }
+ /* Return the Option Byte program Status */
+ return status;
+}
+
+#ifdef STM32F10X_XL
+/**
+ * @brief Configures to boot from Bank1 or Bank2.
+ * @note This function can be used only for STM32F10x_XL density devices.
+ * @param FLASH_BOOT: select the FLASH Bank to boot from.
+ * This parameter can be one of the following values:
+ * @arg FLASH_BOOT_Bank1: At startup, if boot pins are set in boot from user Flash
+ * position and this parameter is selected the device will boot from Bank1(Default).
+ * @arg FLASH_BOOT_Bank2: At startup, if boot pins are set in boot from user Flash
+ * position and this parameter is selected the device will boot from Bank2 or Bank1,
+ * depending on the activation of the bank. The active banks are checked in
+ * the following order: Bank2, followed by Bank1.
+ * The active bank is recognized by the value programmed at the base address
+ * of the respective bank (corresponding to the initial stack pointer value
+ * in the interrupt vector table).
+ * For more information, please refer to AN2606 from www.st.com.
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_BootConfig(uint16_t FLASH_BOOT)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+ assert_param(IS_FLASH_BOOT(FLASH_BOOT));
+ /* Authorize the small information block programming */
+ FLASH->OPTKEYR = FLASH_KEY1;
+ FLASH->OPTKEYR = FLASH_KEY2;
+
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+
+ if(status == FLASH_COMPLETE)
+ {
+ /* Enable the Option Bytes Programming operation */
+ FLASH->CR |= CR_OPTPG_Set;
+
+ if(FLASH_BOOT == FLASH_BOOT_Bank1)
+ {
+ OB->USER |= OB_USER_BFB2;
+ }
+ else
+ {
+ OB->USER &= (uint16_t)(~(uint16_t)(OB_USER_BFB2));
+ }
+ /* Wait for last operation to be completed */
+ status = FLASH_WaitForLastOperation(ProgramTimeout);
+ if(status != FLASH_TIMEOUT)
+ {
+ /* if the program operation is completed, disable the OPTPG Bit */
+ FLASH->CR &= CR_OPTPG_Reset;
+ }
+ }
+ /* Return the Option Byte program Status */
+ return status;
+}
+#endif /* STM32F10X_XL */
+
+/**
+ * @brief Returns the FLASH User Option Bytes values.
+ * @note This function can be used for all STM32F10x devices.
+ * @param None
+ * @retval The FLASH User Option Bytes values:IWDG_SW(Bit0), RST_STOP(Bit1)
+ * and RST_STDBY(Bit2).
+ */
+uint32_t FLASH_GetUserOptionByte(void)
+{
+ /* Return the User Option Byte */
+ return (uint32_t)(FLASH->OBR >> 2);
+}
+
+/**
+ * @brief Returns the FLASH Write Protection Option Bytes Register value.
+ * @note This function can be used for all STM32F10x devices.
+ * @param None
+ * @retval The FLASH Write Protection Option Bytes Register value
+ */
+uint32_t FLASH_GetWriteProtectionOptionByte(void)
+{
+ /* Return the Flash write protection Register value */
+ return (uint32_t)(FLASH->WRPR);
+}
+
+/**
+ * @brief Checks whether the FLASH Read Out Protection Status is set or not.
+ * @note This function can be used for all STM32F10x devices.
+ * @param None
+ * @retval FLASH ReadOut Protection Status(SET or RESET)
+ */
+FlagStatus FLASH_GetReadOutProtectionStatus(void)
+{
+ FlagStatus readoutstatus = RESET;
+ if ((FLASH->OBR & RDPRT_Mask) != (uint32_t)RESET)
+ {
+ readoutstatus = SET;
+ }
+ else
+ {
+ readoutstatus = RESET;
+ }
+ return readoutstatus;
+}
+
+/**
+ * @brief Checks whether the FLASH Prefetch Buffer status is set or not.
+ * @note This function can be used for all STM32F10x devices.
+ * @param None
+ * @retval FLASH Prefetch Buffer Status (SET or RESET).
+ */
+FlagStatus FLASH_GetPrefetchBufferStatus(void)
+{
+ FlagStatus bitstatus = RESET;
+
+ if ((FLASH->ACR & ACR_PRFTBS_Mask) != (uint32_t)RESET)
+ {
+ bitstatus = SET;
+ }
+ else
+ {
+ bitstatus = RESET;
+ }
+ /* Return the new state of FLASH Prefetch Buffer Status (SET or RESET) */
+ return bitstatus;
+}
+
+/**
+ * @brief Enables or disables the specified FLASH interrupts.
+ * @note This function can be used for all STM32F10x devices.
+ * - For STM32F10X_XL devices, enables or disables the specified FLASH interrupts
+ for Bank1 and Bank2.
+ * - For other devices it enables or disables the specified FLASH interrupts for Bank1.
+ * @param FLASH_IT: specifies the FLASH interrupt sources to be enabled or disabled.
+ * This parameter can be any combination of the following values:
+ * @arg FLASH_IT_ERROR: FLASH Error Interrupt
+ * @arg FLASH_IT_EOP: FLASH end of operation Interrupt
+ * @param NewState: new state of the specified Flash interrupts.
+ * This parameter can be: ENABLE or DISABLE.
+ * @retval None
+ */
+void FLASH_ITConfig(uint32_t FLASH_IT, FunctionalState NewState)
+{
+#ifdef STM32F10X_XL
+ /* Check the parameters */
+ assert_param(IS_FLASH_IT(FLASH_IT));
+ assert_param(IS_FUNCTIONAL_STATE(NewState));
+
+ if((FLASH_IT & 0x80000000) != 0x0)
+ {
+ if(NewState != DISABLE)
+ {
+ /* Enable the interrupt sources */
+ FLASH->CR2 |= (FLASH_IT & 0x7FFFFFFF);
+ }
+ else
+ {
+ /* Disable the interrupt sources */
+ FLASH->CR2 &= ~(uint32_t)(FLASH_IT & 0x7FFFFFFF);
+ }
+ }
+ else
+ {
+ if(NewState != DISABLE)
+ {
+ /* Enable the interrupt sources */
+ FLASH->CR |= FLASH_IT;
+ }
+ else
+ {
+ /* Disable the interrupt sources */
+ FLASH->CR &= ~(uint32_t)FLASH_IT;
+ }
+ }
+#else
+ /* Check the parameters */
+ assert_param(IS_FLASH_IT(FLASH_IT));
+ assert_param(IS_FUNCTIONAL_STATE(NewState));
+
+ if(NewState != DISABLE)
+ {
+ /* Enable the interrupt sources */
+ FLASH->CR |= FLASH_IT;
+ }
+ else
+ {
+ /* Disable the interrupt sources */
+ FLASH->CR &= ~(uint32_t)FLASH_IT;
+ }
+#endif /* STM32F10X_XL */
+}
+
+/**
+ * @brief Checks whether the specified FLASH flag is set or not.
+ * @note This function can be used for all STM32F10x devices.
+ * - For STM32F10X_XL devices, this function checks whether the specified
+ * Bank1 or Bank2 flag is set or not.
+ * - For other devices, it checks whether the specified Bank1 flag is
+ * set or not.
+ * @param FLASH_FLAG: specifies the FLASH flag to check.
+ * This parameter can be one of the following values:
+ * @arg FLASH_FLAG_BSY: FLASH Busy flag
+ * @arg FLASH_FLAG_PGERR: FLASH Program error flag
+ * @arg FLASH_FLAG_WRPRTERR: FLASH Write protected error flag
+ * @arg FLASH_FLAG_EOP: FLASH End of Operation flag
+ * @arg FLASH_FLAG_OPTERR: FLASH Option Byte error flag
+ * @retval The new state of FLASH_FLAG (SET or RESET).
+ */
+FlagStatus FLASH_GetFlagStatus(uint32_t FLASH_FLAG)
+{
+ FlagStatus bitstatus = RESET;
+
+#ifdef STM32F10X_XL
+ /* Check the parameters */
+ assert_param(IS_FLASH_GET_FLAG(FLASH_FLAG)) ;
+ if(FLASH_FLAG == FLASH_FLAG_OPTERR)
+ {
+ if((FLASH->OBR & FLASH_FLAG_OPTERR) != (uint32_t)RESET)
+ {
+ bitstatus = SET;
+ }
+ else
+ {
+ bitstatus = RESET;
+ }
+ }
+ else
+ {
+ if((FLASH_FLAG & 0x80000000) != 0x0)
+ {
+ if((FLASH->SR2 & FLASH_FLAG) != (uint32_t)RESET)
+ {
+ bitstatus = SET;
+ }
+ else
+ {
+ bitstatus = RESET;
+ }
+ }
+ else
+ {
+ if((FLASH->SR & FLASH_FLAG) != (uint32_t)RESET)
+ {
+ bitstatus = SET;
+ }
+ else
+ {
+ bitstatus = RESET;
+ }
+ }
+ }
+#else
+ /* Check the parameters */
+ assert_param(IS_FLASH_GET_FLAG(FLASH_FLAG)) ;
+ if(FLASH_FLAG == FLASH_FLAG_OPTERR)
+ {
+ if((FLASH->OBR & FLASH_FLAG_OPTERR) != (uint32_t)RESET)
+ {
+ bitstatus = SET;
+ }
+ else
+ {
+ bitstatus = RESET;
+ }
+ }
+ else
+ {
+ if((FLASH->SR & FLASH_FLAG) != (uint32_t)RESET)
+ {
+ bitstatus = SET;
+ }
+ else
+ {
+ bitstatus = RESET;
+ }
+ }
+#endif /* STM32F10X_XL */
+
+ /* Return the new state of FLASH_FLAG (SET or RESET) */
+ return bitstatus;
+}
+
+/**
+ * @brief Clears the FLASH's pending flags.
+ * @note This function can be used for all STM32F10x devices.
+ * - For STM32F10X_XL devices, this function clears Bank1 or Bank2’s pending flags
+ * - For other devices, it clears Bank1’s pending flags.
+ * @param FLASH_FLAG: specifies the FLASH flags to clear.
+ * This parameter can be any combination of the following values:
+ * @arg FLASH_FLAG_PGERR: FLASH Program error flag
+ * @arg FLASH_FLAG_WRPRTERR: FLASH Write protected error flag
+ * @arg FLASH_FLAG_EOP: FLASH End of Operation flag
+ * @retval None
+ */
+void FLASH_ClearFlag(uint32_t FLASH_FLAG)
+{
+#ifdef STM32F10X_XL
+ /* Check the parameters */
+ assert_param(IS_FLASH_CLEAR_FLAG(FLASH_FLAG)) ;
+
+ if((FLASH_FLAG & 0x80000000) != 0x0)
+ {
+ /* Clear the flags */
+ FLASH->SR2 = FLASH_FLAG;
+ }
+ else
+ {
+ /* Clear the flags */
+ FLASH->SR = FLASH_FLAG;
+ }
+
+#else
+ /* Check the parameters */
+ assert_param(IS_FLASH_CLEAR_FLAG(FLASH_FLAG)) ;
+
+ /* Clear the flags */
+ FLASH->SR = FLASH_FLAG;
+#endif /* STM32F10X_XL */
+}
+
+/**
+ * @brief Returns the FLASH Status.
+ * @note This function can be used for all STM32F10x devices, it is equivalent
+ * to FLASH_GetBank1Status function.
+ * @param None
+ * @retval FLASH Status: The returned value can be: FLASH_BUSY, FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP or FLASH_COMPLETE
+ */
+FLASH_Status FLASH_GetStatus(void)
+{
+ FLASH_Status flashstatus = FLASH_COMPLETE;
+
+ if((FLASH->SR & FLASH_FLAG_BSY) == FLASH_FLAG_BSY)
+ {
+ flashstatus = FLASH_BUSY;
+ }
+ else
+ {
+ if((FLASH->SR & FLASH_FLAG_PGERR) != 0)
+ {
+ flashstatus = FLASH_ERROR_PG;
+ }
+ else
+ {
+ if((FLASH->SR & FLASH_FLAG_WRPRTERR) != 0 )
+ {
+ flashstatus = FLASH_ERROR_WRP;
+ }
+ else
+ {
+ flashstatus = FLASH_COMPLETE;
+ }
+ }
+ }
+ /* Return the Flash Status */
+ return flashstatus;
+}
+
+/**
+ * @brief Returns the FLASH Bank1 Status.
+ * @note This function can be used for all STM32F10x devices, it is equivalent
+ * to FLASH_GetStatus function.
+ * @param None
+ * @retval FLASH Status: The returned value can be: FLASH_BUSY, FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP or FLASH_COMPLETE
+ */
+FLASH_Status FLASH_GetBank1Status(void)
+{
+ FLASH_Status flashstatus = FLASH_COMPLETE;
+
+ if((FLASH->SR & FLASH_FLAG_BANK1_BSY) == FLASH_FLAG_BSY)
+ {
+ flashstatus = FLASH_BUSY;
+ }
+ else
+ {
+ if((FLASH->SR & FLASH_FLAG_BANK1_PGERR) != 0)
+ {
+ flashstatus = FLASH_ERROR_PG;
+ }
+ else
+ {
+ if((FLASH->SR & FLASH_FLAG_BANK1_WRPRTERR) != 0 )
+ {
+ flashstatus = FLASH_ERROR_WRP;
+ }
+ else
+ {
+ flashstatus = FLASH_COMPLETE;
+ }
+ }
+ }
+ /* Return the Flash Status */
+ return flashstatus;
+}
+
+#ifdef STM32F10X_XL
+/**
+ * @brief Returns the FLASH Bank2 Status.
+ * @note This function can be used for STM32F10x_XL density devices.
+ * @param None
+ * @retval FLASH Status: The returned value can be: FLASH_BUSY, FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP or FLASH_COMPLETE
+ */
+FLASH_Status FLASH_GetBank2Status(void)
+{
+ FLASH_Status flashstatus = FLASH_COMPLETE;
+
+ if((FLASH->SR2 & (FLASH_FLAG_BANK2_BSY & 0x7FFFFFFF)) == (FLASH_FLAG_BANK2_BSY & 0x7FFFFFFF))
+ {
+ flashstatus = FLASH_BUSY;
+ }
+ else
+ {
+ if((FLASH->SR2 & (FLASH_FLAG_BANK2_PGERR & 0x7FFFFFFF)) != 0)
+ {
+ flashstatus = FLASH_ERROR_PG;
+ }
+ else
+ {
+ if((FLASH->SR2 & (FLASH_FLAG_BANK2_WRPRTERR & 0x7FFFFFFF)) != 0 )
+ {
+ flashstatus = FLASH_ERROR_WRP;
+ }
+ else
+ {
+ flashstatus = FLASH_COMPLETE;
+ }
+ }
+ }
+ /* Return the Flash Status */
+ return flashstatus;
+}
+#endif /* STM32F10X_XL */
+/**
+ * @brief Waits for a Flash operation to complete or a TIMEOUT to occur.
+ * @note This function can be used for all STM32F10x devices,
+ * it is equivalent to FLASH_WaitForLastBank1Operation.
+ * - For STM32F10X_XL devices this function waits for a Bank1 Flash operation
+ * to complete or a TIMEOUT to occur.
+ * - For all other devices it waits for a Flash operation to complete
+ * or a TIMEOUT to occur.
+ * @param Timeout: FLASH programming Timeout
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_WaitForLastOperation(uint32_t Timeout)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+
+ /* Check for the Flash Status */
+ status = FLASH_GetBank1Status();
+ /* Wait for a Flash operation to complete or a TIMEOUT to occur */
+ while((status == FLASH_BUSY) && (Timeout != 0x00))
+ {
+ status = FLASH_GetBank1Status();
+ Timeout--;
+ }
+ if(Timeout == 0x00 )
+ {
+ status = FLASH_TIMEOUT;
+ }
+ /* Return the operation status */
+ return status;
+}
+
+/**
+ * @brief Waits for a Flash operation on Bank1 to complete or a TIMEOUT to occur.
+ * @note This function can be used for all STM32F10x devices,
+ * it is equivalent to FLASH_WaitForLastOperation.
+ * @param Timeout: FLASH programming Timeout
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_WaitForLastBank1Operation(uint32_t Timeout)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+
+ /* Check for the Flash Status */
+ status = FLASH_GetBank1Status();
+ /* Wait for a Flash operation to complete or a TIMEOUT to occur */
+ while((status == FLASH_FLAG_BANK1_BSY) && (Timeout != 0x00))
+ {
+ status = FLASH_GetBank1Status();
+ Timeout--;
+ }
+ if(Timeout == 0x00 )
+ {
+ status = FLASH_TIMEOUT;
+ }
+ /* Return the operation status */
+ return status;
+}
+
+#ifdef STM32F10X_XL
+/**
+ * @brief Waits for a Flash operation on Bank2 to complete or a TIMEOUT to occur.
+ * @note This function can be used only for STM32F10x_XL density devices.
+ * @param Timeout: FLASH programming Timeout
+ * @retval FLASH Status: The returned value can be: FLASH_ERROR_PG,
+ * FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT.
+ */
+FLASH_Status FLASH_WaitForLastBank2Operation(uint32_t Timeout)
+{
+ FLASH_Status status = FLASH_COMPLETE;
+
+ /* Check for the Flash Status */
+ status = FLASH_GetBank2Status();
+ /* Wait for a Flash operation to complete or a TIMEOUT to occur */
+ while((status == (FLASH_FLAG_BANK2_BSY & 0x7FFFFFFF)) && (Timeout != 0x00))
+ {
+ status = FLASH_GetBank2Status();
+ Timeout--;
+ }
+ if(Timeout == 0x00 )
+ {
+ status = FLASH_TIMEOUT;
+ }
+ /* Return the operation status */
+ return status;
+}
+#endif /* STM32F10X_XL */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/**
+ * @}
+ */
+
+/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
diff --git a/grbl/stm32grbl/stm_lib/src/stm32f10x_gpio.c b/grbl/stm32grbl/stm_lib/src/stm32f10x_gpio.c
new file mode 100755
index 000000000..93dbcd7ca
--- /dev/null
+++ b/grbl/stm32grbl/stm_lib/src/stm32f10x_gpio.c
@@ -0,0 +1,650 @@
+/**
+ ******************************************************************************
+ * @file stm32f10x_gpio.c
+ * @author MCD Application Team
+ * @version V3.5.0
+ * @date 11-March-2011
+ * @brief This file provides all the GPIO firmware functions.
+ ******************************************************************************
+ * @attention
+ *
+ * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+ * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
+ * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
+ * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
+ * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
+ * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+ *
+ *
+ */
+
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __EEPROM_H
+#define __EEPROM_H
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f10x_flash.h"
+
+/* Exported constants --------------------------------------------------------*/
+/* Define the STM32F10Xxx Flash page size depending on the used STM32 device */
+#if defined (STM32F10X_LD) || defined (STM32F10X_MD)
+ #define PAGE_SIZE (uint16_t)0x400 /* Page size = 1KByte */
+#elif defined (STM32F10X_HD) || defined (STM32F10X_CL)
+ #define PAGE_SIZE (uint16_t)0x800 /* Page size = 2KByte */
+#endif
+
+/* EEPROM start address in Flash */
+#define EEPROM_START_ADDRESS ((uint32_t)0x0801fc00) /* EEPROM emulation start address:
+ after 64KByte of used Flash memory */
+
+#endif /* __EEPROM_H */
+
+/******************* (C) COPYRIGHT 2009 STMicroelectronics *****END OF FILE****/
diff --git a/grbl/stm32grbl/util/stm32f10x_it.c b/grbl/stm32grbl/util/stm32f10x_it.c
new file mode 100755
index 000000000..597e445ab
--- /dev/null
+++ b/grbl/stm32grbl/util/stm32f10x_it.c
@@ -0,0 +1,227 @@
+/******************** (C) COPYRIGHT 2011 STMicroelectronics ********************
+* File Name : stm32f10x_it.c
+* Author : MCD Application Team
+* Version : V3.3.0
+* Date : 21-March-2011
+* Description : Main Interrupt Service Routines.
+* This file provides template for all exceptions handler
+* and peripherals interrupt service routine.
+********************************************************************************
+* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
+* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
+* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
+* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
+* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
+* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
+*******************************************************************************/
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32f10x_it.h"
+#include "usb_lib.h"
+#include "usb_istr.h"
+#include "hw_config.h"
+
+/* Private typedef -----------------------------------------------------------*/
+/* Private define ------------------------------------------------------------*/
+/* Private macro -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private function prototypes -----------------------------------------------*/
+/* Private functions ---------------------------------------------------------*/
+/******************************************************************************/
+/* Cortex-M3 Processor Exceptions Handlers */
+/******************************************************************************/
+
+/*******************************************************************************
+* Function Name : NMI_Handler
+* Description : This function handles NMI exception.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+void NMI_Handler(void)
+{
+}
+
+/*******************************************************************************
+* Function Name : HardFault_Handler
+* Description : This function handles Hard Fault exception.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+void HardFault_Handler(void)
+{
+ /* Go to infinite loop when Hard Fault exception occurs */
+ while (1)
+ {
+ }
+}
+
+/*******************************************************************************
+* Function Name : MemManage_Handler
+* Description : This function handles Memory Manage exception.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+void MemManage_Handler(void)
+{
+ /* Go to infinite loop when Memory Manage exception occurs */
+ while (1)
+ {
+ }
+}
+
+/*******************************************************************************
+* Function Name : BusFault_Handler
+* Description : This function handles Bus Fault exception.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+void BusFault_Handler(void)
+{
+ /* Go to infinite loop when Bus Fault exception occurs */
+ while (1)
+ {
+ }
+}
+
+/*******************************************************************************
+* Function Name : UsageFault_Handler
+* Description : This function handles Usage Fault exception.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+void UsageFault_Handler(void)
+{
+ /* Go to infinite loop when Usage Fault exception occurs */
+ while (1)
+ {
+ }
+}
+
+/*******************************************************************************
+* Function Name : SVC_Handler
+* Description : This function handles SVCall exception.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+void SVC_Handler(void)
+{
+}
+
+/*******************************************************************************
+* Function Name : DebugMon_Handler
+* Description : This function handles Debug Monitor exception.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+void DebugMon_Handler(void)
+{
+}
+
+/*******************************************************************************
+* Function Name : PendSV_Handler
+* Description : This function handles PendSVC exception.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+void PendSV_Handler(void)
+{
+}
+
+/*******************************************************************************
+* Function Name : SysTick_Handler
+* Description : This function handles SysTick Handler.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+#if 0
+void SysTick_Handler(void)
+{
+}
+#endif
+/******************************************************************************/
+/* STM32F10x Peripherals Interrupt Handlers */
+/******************************************************************************/
+
+#ifndef STM32F10X_CL
+/*******************************************************************************
+* Function Name : USB_LP_CAN1_RX0_IRQHandler
+* Description : This function handles USB Low Priority or CAN RX0 interrupts
+* requests.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+void USB_LP_CAN1_RX0_IRQHandler(void)
+{
+ USB_Istr();
+}
+#endif /* STM32F10X_CL */
+
+/*******************************************************************************
+* Function Name : EVAL_COM1_IRQHandler
+* Description : This function handles EVAL_COM1 global interrupt request.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+void EVAL_COM1_IRQHandler(void)
+{
+#if 0
+if (USART_GetITStatus(EVAL_COM1, USART_IT_RXNE) != RESET)
+ {
+ /* Send the received data to the PC Host*/
+ USART_To_USB_Send_Data();
+ }
+
+ /* If overrun condition occurs, clear the ORE flag and recover communication */
+ if (USART_GetFlagStatus(EVAL_COM1, USART_FLAG_ORE) != RESET)
+ {
+ (void)USART_ReceiveData(EVAL_COM1);
+ }
+#endif
+}
+
+
+#ifdef STM32F10X_CL
+/*******************************************************************************
+* Function Name : OTG_FS_IRQHandler
+* Description : This function handles USB-On-The-Go FS global interrupt request.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+void OTG_FS_IRQHandler(void)
+{
+ STM32_PCD_OTG_ISR_Handler();
+}
+#endif /* STM32F10X_CL */
+
+/******************************************************************************/
+/* STM32F10x Peripherals Interrupt Handlers */
+/* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */
+/* available peripheral interrupt handler's name please refer to the startup */
+/* file (startup_stm32f10x_xx.s). */
+/******************************************************************************/
+
+/*******************************************************************************
+* Function Name : PPP_IRQHandler
+* Description : This function handles PPP interrupt request.
+* Input : None
+* Output : None
+* Return : None
+*******************************************************************************/
+/*void PPP_IRQHandler(void)
+{
+}*/
+
+/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
+
diff --git a/grbl/system.c b/grbl/system.c
index c4c73e9df..9aea4d068 100644
--- a/grbl/system.c
+++ b/grbl/system.c
@@ -1,46 +1,85 @@
-/*
- system.c - Handles system level commands and real-time processes
- Part of Grbl
-
- Copyright (c) 2014-2015 Sungeun K. Jeon
-
- Grbl is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Grbl is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with Grbl. If not, see .
-*/
-
-#include "grbl.h"
-
-
-void system_init()
-{
- CONTROL_DDR &= ~(CONTROL_MASK); // Configure as input pins
- #ifdef DISABLE_CONTROL_PIN_PULL_UP
- CONTROL_PORT &= ~(CONTROL_MASK); // Normal low operation. Requires external pull-down.
- #else
- CONTROL_PORT |= CONTROL_MASK; // Enable internal pull-up resistors. Normal high operation.
- #endif
- CONTROL_PCMSK |= CONTROL_MASK; // Enable specific pins of the Pin Change Interrupt
- PCICR |= (1 << CONTROL_INT); // Enable Pin Change Interrupt
-}
-
-
+/*
+ system.c - Handles system level commands and real-time processes
+ Part of Grbl
+
+ Copyright (c) 2014-2015 Sungeun K. Jeon
+
+ Grbl is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Grbl is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with Grbl. If not, see .
+*/
+
+#include "grbl.h"
+
+void system_init()
+{
+#ifdef AVRTARGET
+ CONTROL_DDR &= ~(CONTROL_MASK); // Configure as input pins
+ #ifdef DISABLE_CONTROL_PIN_PULL_UP
+ CONTROL_PORT &= ~(CONTROL_MASK); // Normal low operation. Requires external pull-down.
+ #else
+ CONTROL_PORT |= CONTROL_MASK; // Enable internal pull-up resistors. Normal high operation.
+ #endif
+ CONTROL_PCMSK |= CONTROL_MASK; // Enable specific pins of the Pin Change Interrupt
+ PCICR |= (1 << CONTROL_INT); // Enable Pin Change Interrupt
+#endif
+#ifdef STM32F103C8
+ GPIO_InitTypeDef GPIO_InitStructure;
+ RCC_APB2PeriphClockCmd(RCC_CONTROL | RCC_APB2Periph_AFIO, ENABLE);
+ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
+#ifdef DISABLE_CONTROL_PIN_PULL_UP
+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
+#else
+ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
+#endif
+ GPIO_InitStructure.GPIO_Pin = CONTROL_MASK;
+ GPIO_Init(CONTROL_PORT, &GPIO_InitStructure);
+
+ GPIO_EXTILineConfig(GPIO_CONTROLPORT, CONTROL_RESET_BIT);
+ GPIO_EXTILineConfig(GPIO_CONTROLPORT, CONTROL_FEED_HOLD_BIT);
+ GPIO_EXTILineConfig(GPIO_CONTROLPORT, CONTROL_CYCLE_START_BIT);
+ GPIO_EXTILineConfig(GPIO_CONTROLPORT, CONTROL_SAFETY_DOOR_BIT);
+
+ EXTI_InitTypeDef EXTI_InitStructure;
+ EXTI_InitStructure.EXTI_Line= CONTROL_MASK; //
+ EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; //Interrupt mode, optional values for the interrupt EXTI_Mode_Interrupt and event EXTI_Mode_Event.
+ EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; //Trigger mode, can be a falling edge trigger EXTI_Trigger_Falling, the rising edge triggered EXTI_Trigger_Rising, or any level (rising edge and falling edge trigger EXTI_Trigger_Rising_Falling)
+ EXTI_InitStructure.EXTI_LineCmd = ENABLE;
+ EXTI_Init(&EXTI_InitStructure);
+
+ NVIC_InitTypeDef NVIC_InitStructure;
+ NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn; //Enable keypad external interrupt channel
+ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02; //Priority 2,
+ NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x02; //Sub priority 2
+ NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //Enable external interrupt channel
+ NVIC_Init(&NVIC_InitStructure);
+#endif
+}
+
// Returns control pin state as a uint8 bitfield. Each bit indicates the input pin state, where
// triggered is 1 and not triggered is 0. Invert mask is applied. Bitfield organization is
// defined by the CONTROL_PIN_INDEX in the header file.
uint8_t system_control_get_state()
{
uint8_t control_state = 0;
+#ifdef AVRTARGET
uint8_t pin = (CONTROL_PIN & CONTROL_MASK);
+#endif
+#ifdef WIN32
+ uint8_t pin = 0;
+#endif
+#ifdef STM32F103C8
+ uint16_t pin= GPIO_ReadInputData(CONTROL_PIN);
+#endif
#ifdef INVERT_CONTROL_PIN_MASK
pin ^= INVERT_CONTROL_PIN_MASK;
#endif
@@ -53,13 +92,14 @@ uint8_t system_control_get_state()
return(control_state);
}
-
-// Pin change interrupt for pin-out commands, i.e. cycle start, feed hold, and reset. Sets
-// only the realtime command execute variable to have the main program execute these when
-// its ready. This works exactly like the character-based realtime commands when picked off
-// directly from the incoming serial data stream.
-ISR(CONTROL_INT_vect)
-{
+
+// Pin change interrupt for pin-out commands, i.e. cycle start, feed hold, and reset. Sets
+// only the realtime command execute variable to have the main program execute these when
+// its ready. This works exactly like the character-based realtime commands when picked off
+// directly from the incoming serial data stream.
+#ifdef AVRTARGET
+ISR(CONTROL_INT_vect)
+{
uint8_t pin = system_control_get_state();
if (pin) {
if (bit_istrue(pin,CONTROL_PIN_INDEX_RESET)) {
@@ -70,245 +110,316 @@ ISR(CONTROL_INT_vect)
bit_true(sys_rt_exec_state, EXEC_FEED_HOLD);
} else if (bit_istrue(pin,CONTROL_PIN_INDEX_SAFETY_DOOR)) {
bit_true(sys_rt_exec_state, EXEC_SAFETY_DOOR);
- }
+ }
}
-}
-
-
-// Returns if safety door is ajar(T) or closed(F), based on pin state.
-uint8_t system_check_safety_door_ajar()
-{
- return(system_control_get_state() & CONTROL_PIN_INDEX_SAFETY_DOOR);
-}
-
-
-// Executes user startup script, if stored.
-void system_execute_startup(char *line)
-{
- uint8_t n;
- for (n=0; n < N_STARTUP_LINE; n++) {
- if (!(settings_read_startup_line(n, line))) {
- report_status_message(STATUS_SETTING_READ_FAIL);
- } else {
- if (line[0] != 0) {
- printString(line); // Echo startup line to indicate execution.
- report_status_message(gc_execute_line(line));
- }
- }
- }
-}
-
-
-// Directs and executes one line of formatted input from protocol_process. While mostly
-// incoming streaming g-code blocks, this also executes Grbl internal commands, such as
-// settings, initiating the homing cycle, and toggling switch states. This differs from
-// the realtime command module by being susceptible to when Grbl is ready to execute the
-// next line during a cycle, so for switches like block delete, the switch only effects
-// the lines that are processed afterward, not necessarily real-time during a cycle,
-// since there are motions already stored in the buffer. However, this 'lag' should not
-// be an issue, since these commands are not typically used during a cycle.
-uint8_t system_execute_line(char *line)
-{
- uint8_t char_counter = 1;
- uint8_t helper_var = 0; // Helper variable
- float parameter, value;
- switch( line[char_counter] ) {
- case 0 : report_grbl_help(); break;
- case '$': case 'G': case 'C': case 'X':
- if ( line[(char_counter+1)] != 0 ) { return(STATUS_INVALID_STATEMENT); }
- switch( line[char_counter] ) {
- case '$' : // Prints Grbl settings
- if ( sys.state & (STATE_CYCLE | STATE_HOLD) ) { return(STATUS_IDLE_ERROR); } // Block during cycle. Takes too long to print.
- else { report_grbl_settings(); }
- break;
- case 'G' : // Prints gcode parser state
- // TODO: Move this to realtime commands for GUIs to request this data during suspend-state.
- report_gcode_modes();
- break;
- case 'C' : // Set check g-code mode [IDLE/CHECK]
- // Perform reset when toggling off. Check g-code mode should only work if Grbl
- // is idle and ready, regardless of alarm locks. This is mainly to keep things
- // simple and consistent.
- if ( sys.state == STATE_CHECK_MODE ) {
- mc_reset();
- report_feedback_message(MESSAGE_DISABLED);
- } else {
- if (sys.state) { return(STATUS_IDLE_ERROR); } // Requires no alarm mode.
- sys.state = STATE_CHECK_MODE;
- report_feedback_message(MESSAGE_ENABLED);
- }
- break;
- case 'X' : // Disable alarm lock [ALARM]
- if (sys.state == STATE_ALARM) {
+}
+#endif
+#if defined (STM32F103C8)
+void EXTI9_5_IRQHandler(void)
+{
+ uint8_t pin = system_control_get_state();
+ if (pin)
+ {
+ if (bit_istrue(pin,CONTROL_PIN_INDEX_RESET))
+ {
+ mc_reset();
+ } else if (bit_istrue(pin,CONTROL_PIN_INDEX_CYCLE_START))
+ {
+ bit_true(sys_rt_exec_state, EXEC_CYCLE_START);
+ } else if (bit_istrue(pin,CONTROL_PIN_INDEX_FEED_HOLD))
+ {
+ bit_true(sys_rt_exec_state, EXEC_FEED_HOLD);
+ } else if (bit_istrue(pin,CONTROL_PIN_INDEX_SAFETY_DOOR))
+ {
+ bit_true(sys_rt_exec_state, EXEC_SAFETY_DOOR);
+ }
+ NVIC_ClearPendingIRQ(EXTI9_5_IRQn);
+ }
+}
+#endif
+
+// Returns if safety door is ajar(T) or closed(F), based on pin state.
+uint8_t system_check_safety_door_ajar()
+{
+ return(system_control_get_state() & CONTROL_PIN_INDEX_SAFETY_DOOR);
+}
+
+
+// Executes user startup script, if stored.
+void system_execute_startup(char *line)
+{
+ uint8_t n;
+ for (n=0; n < N_STARTUP_LINE; n++) {
+ if (!(settings_read_startup_line(n, line))) {
+ report_status_message(STATUS_SETTING_READ_FAIL);
+ } else {
+ if (line[0] != 0) {
+ printString(line); // Echo startup line to indicate execution.
+ report_status_message(gc_execute_line(line));
+ }
+ }
+ }
+}
+
+
+// Directs and executes one line of formatted input from protocol_process. While mostly
+// incoming streaming g-code blocks, this also executes Grbl internal commands, such as
+// settings, initiating the homing cycle, and toggling switch states. This differs from
+// the realtime command module by being susceptible to when Grbl is ready to execute the
+// next line during a cycle, so for switches like block delete, the switch only effects
+// the lines that are processed afterward, not necessarily real-time during a cycle,
+// since there are motions already stored in the buffer. However, this 'lag' should not
+// be an issue, since these commands are not typically used during a cycle.
+uint8_t system_execute_line(char *line)
+{
+ uint8_t char_counter = 1;
+ uint8_t helper_var = 0; // Helper variable
+ float parameter, value;
+ switch( line[char_counter] ) {
+ case 0 : report_grbl_help(); break;
+ case '$': case 'G': case 'C': case 'X':
+ if ( line[(char_counter+1)] != 0 ) { return(STATUS_INVALID_STATEMENT); }
+ switch( line[char_counter] ) {
+ case '$' : // Prints Grbl settings
+ if ( sys.state & (STATE_CYCLE | STATE_HOLD) ) { return(STATUS_IDLE_ERROR); } // Block during cycle. Takes too long to print.
+ else { report_grbl_settings(); }
+ break;
+ case 'G' : // Prints gcode parser state
+ // TODO: Move this to realtime commands for GUIs to request this data during suspend-state.
+ report_gcode_modes();
+ break;
+ case 'C' : // Set check g-code mode [IDLE/CHECK]
+ // Perform reset when toggling off. Check g-code mode should only work if Grbl
+ // is idle and ready, regardless of alarm locks. This is mainly to keep things
+ // simple and consistent.
+ if ( sys.state == STATE_CHECK_MODE ) {
+ mc_reset();
+ report_feedback_message(MESSAGE_DISABLED);
+ } else {
+ if (sys.state) { return(STATUS_IDLE_ERROR); } // Requires no alarm mode.
+ sys.state = STATE_CHECK_MODE;
+ report_feedback_message(MESSAGE_ENABLED);
+ }
+ break;
+ case 'X' : // Disable alarm lock [ALARM]
+ if (sys.state == STATE_ALARM) {
// Block if safety door is ajar.
if (system_check_safety_door_ajar()) { return(STATUS_CHECK_DOOR); }
- report_feedback_message(MESSAGE_ALARM_UNLOCK);
- sys.state = STATE_IDLE;
- // Don't run startup script. Prevents stored moves in startup from causing accidents.
- } // Otherwise, no effect.
- break;
- // case 'J' : break; // Jogging methods
- // TODO: Here jogging can be placed for execution as a seperate subprogram. It does not need to be
- // susceptible to other realtime commands except for e-stop. The jogging function is intended to
- // be a basic toggle on/off with controlled acceleration and deceleration to prevent skipped
- // steps. The user would supply the desired feedrate, axis to move, and direction. Toggle on would
- // start motion and toggle off would initiate a deceleration to stop. One could 'feather' the
- // motion by repeatedly toggling to slow the motion to the desired location. Location data would
- // need to be updated real-time and supplied to the user through status queries.
- // More controlled exact motions can be taken care of by inputting G0 or G1 commands, which are
- // handled by the planner. It would be possible for the jog subprogram to insert blocks into the
- // block buffer without having the planner plan them. It would need to manage de/ac-celerations
- // on its own carefully. This approach could be effective and possibly size/memory efficient.
- }
- break;
- default :
- // Block any system command that requires the state as IDLE/ALARM. (i.e. EEPROM, homing)
- if ( !(sys.state == STATE_IDLE || sys.state == STATE_ALARM) ) { return(STATUS_IDLE_ERROR); }
- switch( line[char_counter] ) {
- case '#' : // Print Grbl NGC parameters
- if ( line[++char_counter] != 0 ) { return(STATUS_INVALID_STATEMENT); }
- else { report_ngc_parameters(); }
- break;
- case 'H' : // Perform homing cycle [IDLE/ALARM]
- if (bit_istrue(settings.flags,BITFLAG_HOMING_ENABLE)) {
+ report_feedback_message(MESSAGE_ALARM_UNLOCK);
+ sys.state = STATE_IDLE;
+ } // Otherwise, no effect.
+ break;
+ // case 'J' : break; // Jogging methods
+ // TODO: Here jogging can be placed for execution as a seperate subprogram. It does not need to be
+ // susceptible to other realtime commands except for e-stop. The jogging function is intended to
+ // be a basic toggle on/off with controlled acceleration and deceleration to prevent skipped
+ // steps. The user would supply the desired feedrate, axis to move, and direction. Toggle on would
+ // start motion and toggle off would initiate a deceleration to stop. One could 'feather' the
+ // motion by repeatedly toggling to slow the motion to the desired location. Location data would
+ // need to be updated real-time and supplied to the user through status queries.
+ // More controlled exact motions can be taken care of by inputting G0 or G1 commands, which are
+ // handled by the planner. It would be possible for the jog subprogram to insert blocks into the
+ // block buffer without having the planner plan them. It would need to manage de/ac-celerations
+ // on its own carefully. This approach could be effective and possibly size/memory efficient.
+ }
+ break;
+ default :
+ // Block any system command that requires the state as IDLE/ALARM. (i.e. EEPROM, homing)
+ if ( !(sys.state == STATE_IDLE || sys.state == STATE_ALARM) ) { return(STATUS_IDLE_ERROR); }
+ switch( line[char_counter] ) {
+ case '#' : // Print Grbl NGC parameters
+ if ( line[++char_counter] != 0 ) { return(STATUS_INVALID_STATEMENT); }
+ else { report_ngc_parameters(); }
+ break;
+ case 'H' : // Perform homing cycle [IDLE/ALARM]
+ if (bit_istrue(settings.flags,BITFLAG_HOMING_ENABLE)) {
// Block if safety door is ajar.
if (system_check_safety_door_ajar()) { return(STATUS_CHECK_DOOR); }
- sys.state = STATE_HOMING; // Set system state variable
- mc_homing_cycle();
- if (!sys.abort) { // Execute startup scripts after successful homing.
- sys.state = STATE_IDLE; // Set to IDLE when complete.
- st_go_idle(); // Set steppers to the settings idle state before returning.
- system_execute_startup(line);
- }
- } else { return(STATUS_SETTING_DISABLED); }
- break;
- case 'I' : // Print or store build info. [IDLE/ALARM]
- if ( line[++char_counter] == 0 ) {
- settings_read_build_info(line);
- report_build_info(line);
- } else { // Store startup line [IDLE/ALARM]
- if(line[char_counter++] != '=') { return(STATUS_INVALID_STATEMENT); }
- helper_var = char_counter; // Set helper variable as counter to start of user info line.
- do {
- line[char_counter-helper_var] = line[char_counter];
- } while (line[char_counter++] != 0);
+ sys.state = STATE_HOMING; // Set system state variable
+
+ mc_homing_cycle();
+ if (!sys.abort) { // Execute startup scripts after successful homing.
+ sys.state = STATE_IDLE; // Set to IDLE when complete.
+ st_go_idle(); // Set steppers to the settings idle state before returning.
+ system_execute_startup(line);
+ }
+ } else { return(STATUS_SETTING_DISABLED); }
+ break;
+ case 'I' : // Print or store build info. [IDLE/ALARM]
+ if ( line[++char_counter] == 0 ) {
+ settings_read_build_info(line);
+ report_build_info(line);
+ } else { // Store startup line [IDLE/ALARM]
+ if(line[char_counter++] != '=') { return(STATUS_INVALID_STATEMENT); }
+ helper_var = char_counter; // Set helper variable as counter to start of user info line.
+ do {
+ line[char_counter-helper_var] = line[char_counter];
+ } while (line[char_counter++] != 0);
if (char_counter > (EEPROM_LINE_SIZE-helper_var)) { return(STATUS_LINE_LENGTH_EXCEEDED); }
- settings_store_build_info(line);
- }
- break;
- case 'R' : // Restore defaults [IDLE/ALARM]
- if (line[++char_counter] != 'S') { return(STATUS_INVALID_STATEMENT); }
- if (line[++char_counter] != 'T') { return(STATUS_INVALID_STATEMENT); }
- if (line[++char_counter] != '=') { return(STATUS_INVALID_STATEMENT); }
- if (line[char_counter+2] != 0) { return(STATUS_INVALID_STATEMENT); }
- switch (line[++char_counter]) {
- case '$': settings_restore(SETTINGS_RESTORE_DEFAULTS); break;
- case '#': settings_restore(SETTINGS_RESTORE_PARAMETERS); break;
- case '*': settings_restore(SETTINGS_RESTORE_ALL); break;
- default: return(STATUS_INVALID_STATEMENT);
- }
- report_feedback_message(MESSAGE_RESTORE_DEFAULTS);
- mc_reset(); // Force reset to ensure settings are initialized correctly.
- break;
- case 'N' : // Startup lines. [IDLE/ALARM]
- if ( line[++char_counter] == 0 ) { // Print startup lines
- for (helper_var=0; helper_var < N_STARTUP_LINE; helper_var++) {
- if (!(settings_read_startup_line(helper_var, line))) {
- report_status_message(STATUS_SETTING_READ_FAIL);
- } else {
- report_startup_line(helper_var,line);
- }
- }
- break;
- } else { // Store startup line [IDLE Only] Prevents motion during ALARM.
- if (sys.state != STATE_IDLE) { return(STATUS_IDLE_ERROR); } // Store only when idle.
- helper_var = true; // Set helper_var to flag storing method.
- // No break. Continues into default: to read remaining command characters.
- }
- default : // Storing setting methods [IDLE/ALARM]
- if(!read_float(line, &char_counter, ¶meter)) { return(STATUS_BAD_NUMBER_FORMAT); }
- if(line[char_counter++] != '=') { return(STATUS_INVALID_STATEMENT); }
- if (helper_var) { // Store startup line
- // Prepare sending gcode block to gcode parser by shifting all characters
- helper_var = char_counter; // Set helper variable as counter to start of gcode block
- do {
- line[char_counter-helper_var] = line[char_counter];
- } while (line[char_counter++] != 0);
+ settings_store_build_info(line);
+ }
+ break;
+ case 'R' : // Restore defaults [IDLE/ALARM]
+ if (line[++char_counter] != 'S') { return(STATUS_INVALID_STATEMENT); }
+ if (line[++char_counter] != 'T') { return(STATUS_INVALID_STATEMENT); }
+ if (line[++char_counter] != '=') { return(STATUS_INVALID_STATEMENT); }
+ if (line[char_counter+2] != 0) { return(STATUS_INVALID_STATEMENT); }
+ switch (line[++char_counter]) {
+ case '$': settings_restore(SETTINGS_RESTORE_DEFAULTS); break;
+ case '#': settings_restore(SETTINGS_RESTORE_PARAMETERS); break;
+ case '*': settings_restore(SETTINGS_RESTORE_ALL); break;
+ default: return(STATUS_INVALID_STATEMENT);
+ }
+ report_feedback_message(MESSAGE_RESTORE_DEFAULTS);
+ mc_reset(); // Force reset to ensure settings are initialized correctly.
+ break;
+ case 'N' : // Startup lines. [IDLE/ALARM]
+ if ( line[++char_counter] == 0 ) { // Print startup lines
+ for (helper_var=0; helper_var < N_STARTUP_LINE; helper_var++) {
+ if (!(settings_read_startup_line(helper_var, line))) {
+ report_status_message(STATUS_SETTING_READ_FAIL);
+ } else {
+ report_startup_line(helper_var,line);
+ }
+ }
+ break;
+ } else { // Store startup line [IDLE Only] Prevents motion during ALARM.
+ if (sys.state != STATE_IDLE) { return(STATUS_IDLE_ERROR); } // Store only when idle.
+ helper_var = true; // Set helper_var to flag storing method.
+ // No break. Continues into default: to read remaining command characters.
+ }
+ default : // Storing setting methods [IDLE/ALARM]
+ if(!read_float(line, &char_counter, ¶meter)) { return(STATUS_BAD_NUMBER_FORMAT); }
+ if(line[char_counter++] != '=') { return(STATUS_INVALID_STATEMENT); }
+ if (helper_var) { // Store startup line
+ // Prepare sending gcode block to gcode parser by shifting all characters
+ helper_var = char_counter; // Set helper variable as counter to start of gcode block
+ do {
+ line[char_counter-helper_var] = line[char_counter];
+ } while (line[char_counter++] != 0);
if (char_counter > EEPROM_LINE_SIZE) { return(STATUS_LINE_LENGTH_EXCEEDED); }
- // Execute gcode block to ensure block is valid.
- helper_var = gc_execute_line(line); // Set helper_var to returned status code.
+ // Execute gcode block to ensure block is valid.
+ helper_var = gc_execute_line(line); // Set helper_var to returned status code.
if (helper_var) { return(helper_var); } // Return error.
- else {
- helper_var = trunc(parameter); // Set helper_var to int value of parameter
- settings_store_startup_line(helper_var,line);
- }
- } else { // Store global setting.
- if(!read_float(line, &char_counter, &value)) { return(STATUS_BAD_NUMBER_FORMAT); }
- if((line[char_counter] != 0) || (parameter > 255)) { return(STATUS_INVALID_STATEMENT); }
- return(settings_store_global_setting((uint8_t)parameter, value));
- }
- }
- }
- return(STATUS_OK); // If '$' command makes it to here, then everything's ok.
-}
-
-
-// Returns machine position of axis 'idx'. Must be sent a 'step' array.
-// NOTE: If motor steps and machine position are not in the same coordinate frame, this function
-// serves as a central place to compute the transformation.
-float system_convert_axis_steps_to_mpos(int32_t *steps, uint8_t idx)
-{
- float pos;
- #ifdef COREXY
- if (idx==A_MOTOR) {
- pos = 0.5*((steps[A_MOTOR] + steps[B_MOTOR])/settings.steps_per_mm[idx]);
- } else if (idx==B_MOTOR) {
- pos = 0.5*((steps[A_MOTOR] - steps[B_MOTOR])/settings.steps_per_mm[idx]);
- } else {
- pos = steps[idx]/settings.steps_per_mm[idx];
- }
- #else
- pos = steps[idx]/settings.steps_per_mm[idx];
- #endif
- return(pos);
-}
-
-
-void system_convert_array_steps_to_mpos(float *position, int32_t *steps)
-{
- uint8_t idx;
- for (idx=0; idx 255)) { return(STATUS_INVALID_STATEMENT); }
+ return(settings_store_global_setting((uint8_t)parameter, value));
+ }
+ }
+ }
+ return(STATUS_OK); // If '$' command makes it to here, then everything's ok.
+}
+
+
+// Returns machine position of axis 'idx'. Must be sent a 'step' array.
+// NOTE: If motor steps and machine position are not in the same coordinate frame, this function
+// serves as a central place to compute the transformation.
+float system_convert_axis_steps_to_mpos(int32_t *steps, uint8_t idx)
+{
+ float pos;
+ #ifdef COREXY
+ if (idx==A_MOTOR) {
+ pos = 0.5*((steps[A_MOTOR] + steps[B_MOTOR])/settings.steps_per_mm[idx]);
+ } else if (idx==B_MOTOR) {
+ pos = 0.5*((steps[A_MOTOR] - steps[B_MOTOR])/settings.steps_per_mm[idx]);
+ } else {
+ pos = steps[idx]/settings.steps_per_mm[idx];
+ }
+ #else
+ pos = steps[idx]/settings.steps_per_mm[idx];
+ #endif
+ return(pos);
+}
+
+void system_convert_array_steps_to_mpos(float *position, int32_t *steps)
+{
+ uint8_t idx;
+ for (idx=0; idx