Browse Source

Merge pull request #9150 from Spawn32/bugfix-2.0.x

Bugfix 2.0.x New board and MCU for Marlin.
Scott Lahteine 6 years ago
parent
commit
d743d96886
No account linked to committer's email address
40 changed files with 7354 additions and 36 deletions
  1. 5
    1
      Marlin/Marlin.ino
  2. 4
    0
      Marlin/src/HAL/HAL.h
  3. 1
    1
      Marlin/src/HAL/HAL_STM32F1/HAL_Stm32f1.h
  4. 4
    4
      Marlin/src/HAL/HAL_STM32F1/fastio_Stm32f1.h
  5. 571
    0
      Marlin/src/HAL/HAL_STM32F7/EEPROM_Emul/eeprom_emul.cpp
  6. 118
    0
      Marlin/src/HAL/HAL_STM32F7/EEPROM_Emul/eeprom_emul.h
  7. 146
    0
      Marlin/src/HAL/HAL_STM32F7/EmulatedEeprom.cpp
  8. 140
    0
      Marlin/src/HAL/HAL_STM32F7/HAL_STM32F7.cpp
  9. 236
    0
      Marlin/src/HAL/HAL_STM32F7/HAL_STM32F7.h
  10. 52
    0
      Marlin/src/HAL/HAL_STM32F7/HAL_Servo_STM32F7.cpp
  11. 41
    0
      Marlin/src/HAL/HAL_STM32F7/HAL_Servo_STM32F7.h
  12. 167
    0
      Marlin/src/HAL/HAL_STM32F7/HAL_spi_STM32F7.cpp
  13. 150
    0
      Marlin/src/HAL/HAL_STM32F7/HAL_timers_STM32F7.cpp
  14. 105
    0
      Marlin/src/HAL/HAL_STM32F7/HAL_timers_STM32F7.h
  15. 28
    0
      Marlin/src/HAL/HAL_STM32F7/README.md
  16. 66
    0
      Marlin/src/HAL/HAL_STM32F7/SanityCheck_STM32F7.h
  17. 931
    0
      Marlin/src/HAL/HAL_STM32F7/TMC2660.cpp
  18. 607
    0
      Marlin/src/HAL/HAL_STM32F7/TMC2660.h
  19. 68
    0
      Marlin/src/HAL/HAL_STM32F7/endstop_interrupts.h
  20. 54
    0
      Marlin/src/HAL/HAL_STM32F7/fastio_STM32F7.h
  21. 82
    0
      Marlin/src/HAL/HAL_STM32F7/persistent_store_impl.cpp
  22. 33
    0
      Marlin/src/HAL/HAL_STM32F7/spi_pins.h
  23. 52
    0
      Marlin/src/HAL/HAL_STM32F7/watchdog_STM32F7.cpp
  24. 33
    0
      Marlin/src/HAL/HAL_STM32F7/watchdog_STM32F7.h
  25. 12
    4
      Marlin/src/HAL/HAL_SanityCheck.h
  26. 11
    11
      Marlin/src/HAL/HAL_TEENSY35_36/HAL_Servo_Teensy.h
  27. 4
    0
      Marlin/src/HAL/HAL_endstop_interrupts.h
  28. 6
    1
      Marlin/src/HAL/HAL_spi_pins.h
  29. 1793
    0
      Marlin/src/config/examples/TheBorg/Configuration.h
  30. 1594
    0
      Marlin/src/config/examples/TheBorg/Configuration_adv.h
  31. 6
    0
      Marlin/src/core/boards.h
  32. 1
    0
      Marlin/src/core/macros.h
  33. 9
    9
      Marlin/src/core/serial.h
  34. 1
    1
      Marlin/src/gcode/feature/trinamic/M122.cpp
  35. 1
    1
      Marlin/src/gcode/queue.cpp
  36. 1
    1
      Marlin/src/gcode/sdcard/M20-M30_M32-M34_M928.cpp
  37. 6
    1
      Marlin/src/module/stepper_indirection.cpp
  38. 5
    1
      Marlin/src/module/stepper_indirection.h
  39. 2
    0
      Marlin/src/pins/pins.h
  40. 208
    0
      Marlin/src/pins/pins_THE_BORG.h

+ 5
- 1
Marlin/Marlin.ino View File

@@ -50,7 +50,11 @@
50 50
 
51 51
 #if ENABLED(HAVE_TMCDRIVER)
52 52
   #include <SPI.h>
53
-  #include <TMC26XStepper.h>
53
+  #if defined(STM32F7)
54
+    #include "src/HAL/HAL_STM32F7/TMC2660.h"
55
+  #else
56
+    #include <TMC26XStepper.h>
57
+  #endif
54 58
 #endif
55 59
 
56 60
 #if ENABLED(HAVE_TMC2130)

+ 4
- 0
Marlin/src/HAL/HAL.h View File

@@ -48,6 +48,10 @@
48 48
 #elif defined(__STM32F1__) || defined(TARGET_STM32F1)
49 49
   #include "math_32bit.h"
50 50
   #include "HAL_STM32F1/HAL_Stm32f1.h"
51
+#elif defined(STM32F7)
52
+  #define CPU_32_BIT
53
+  #include "math_32bit.h"
54
+  #include "HAL_STM32F7/HAL_STM32F7.h"
51 55
 #else
52 56
   #error "Unsupported Platform!"
53 57
 #endif

+ 1
- 1
Marlin/src/HAL/HAL_STM32F1/HAL_Stm32f1.h View File

@@ -109,7 +109,7 @@
109 109
   #define analogInputToDigitalPin(p) (p)
110 110
 #endif
111 111
 
112
-#define CRITICAL_SECTION_START	noInterrupts();
112
+#define CRITICAL_SECTION_START  noInterrupts();
113 113
 #define CRITICAL_SECTION_END    interrupts();
114 114
 
115 115
 // On AVR this is in math.h?

+ 4
- 4
Marlin/src/HAL/HAL_STM32F1/fastio_Stm32f1.h View File

@@ -26,8 +26,8 @@
26 26
  * These use GPIO functions instead of Direct Port Manipulation, as on AVR.
27 27
  */
28 28
 
29
-#ifndef	_FASTIO_STM32F1_H
30
-#define	_FASTIO_STM32F1_H
29
+#ifndef _FASTIO_STM32F1_H
30
+#define _FASTIO_STM32F1_H
31 31
 
32 32
 #include <libmaple/gpio.h>
33 33
 
@@ -49,9 +49,9 @@
49 49
 #define GET_TIMER(IO)         (PIN_MAP[IO].timer_device != NULL)
50 50
 
51 51
 #define OUT_WRITE(IO, v)      { _SET_OUTPUT(IO); WRITE(IO, v); }
52
-/*
52
+/**
53 53
  * TODO: Write a macro to test if PIN is PWM or not.
54 54
  */
55 55
 #define PWM_PIN(p)            true
56 56
 
57
-#endif	/* _FASTIO_STM32F1_H */
57
+#endif // _FASTIO_STM32F1_H

+ 571
- 0
Marlin/src/HAL/HAL_STM32F7/EEPROM_Emul/eeprom_emul.cpp View File

@@ -0,0 +1,571 @@
1
+/**
2
+  ******************************************************************************
3
+  * @file    EEPROM/EEPROM_Emulation/src/eeprom.c
4
+  * @author  MCD Application Team
5
+  * @version V1.2.6
6
+  * @date    04-November-2016
7
+  * @brief   This file provides all the EEPROM emulation firmware functions.
8
+  ******************************************************************************
9
+  * @attention
10
+  *
11
+  * <h2><center>&copy; Copyright © 2016 STMicroelectronics International N.V.
12
+  * All rights reserved.</center></h2>
13
+  *
14
+  * Redistribution and use in source and binary forms, with or without
15
+  * modification, are permitted, provided that the following conditions are met:
16
+  *
17
+  * 1. Redistribution of source code must retain the above copyright notice,
18
+  *    this list of conditions and the following disclaimer.
19
+  * 2. Redistributions in binary form must reproduce the above copyright notice,
20
+  *    this list of conditions and the following disclaimer in the documentation
21
+  *    and/or other materials provided with the distribution.
22
+  * 3. Neither the name of STMicroelectronics nor the names of other
23
+  *    contributors to this software may be used to endorse or promote products
24
+  *    derived from this software without specific written permission.
25
+  * 4. This software, including modifications and/or derivative works of this
26
+  *    software, must execute solely and exclusively on microcontroller or
27
+  *    microprocessor devices manufactured by or for STMicroelectronics.
28
+  * 5. Redistribution and use of this software other than as permitted under
29
+  *    this license is void and will automatically terminate your rights under
30
+  *    this license.
31
+  *
32
+  * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
33
+  * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
34
+  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
35
+  * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
36
+  * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
37
+  * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
38
+  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
39
+  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
40
+  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
41
+  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
42
+  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
43
+  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44
+  *
45
+  ******************************************************************************
46
+  */
47
+/** @addtogroup EEPROM_Emulation
48
+  * @{
49
+  */
50
+#ifdef STM32F7
51
+  
52
+/* Includes ------------------------------------------------------------------*/
53
+#include "eeprom_emul.h"
54
+
55
+/* Private typedef -----------------------------------------------------------*/
56
+/* Private define ------------------------------------------------------------*/
57
+/* Private macro -------------------------------------------------------------*/
58
+/* Private variables ---------------------------------------------------------*/
59
+
60
+/* Global variable used to store variable value in read sequence */
61
+uint16_t DataVar = 0;
62
+
63
+/* Virtual address defined by the user: 0xFFFF value is prohibited */
64
+uint16_t VirtAddVarTab[NB_OF_VAR];
65
+
66
+/* Private function prototypes -----------------------------------------------*/
67
+/* Private functions ---------------------------------------------------------*/
68
+static HAL_StatusTypeDef EE_Format(void);
69
+static uint16_t EE_FindValidPage(uint8_t Operation);
70
+static uint16_t EE_VerifyPageFullWriteVariable(uint16_t VirtAddress, uint16_t Data);
71
+static uint16_t EE_PageTransfer(uint16_t VirtAddress, uint16_t Data);
72
+static uint16_t EE_VerifyPageFullyErased(uint32_t Address);
73
+
74
+/**
75
+  * @brief  Restore the pages to a known good state in case of page's status
76
+  *   corruption after a power loss.
77
+  * @param  None.
78
+  * @retval - Flash error code: on write Flash error
79
+  *         - FLASH_COMPLETE: on success
80
+  */
81
+uint16_t EE_Initialise(void) {
82
+  uint16_t PageStatus0 = 6, PageStatus1 = 6;
83
+  uint16_t VarIdx = 0;
84
+  uint16_t EepromStatus = 0, ReadStatus = 0;
85
+  int16_t x = -1;
86
+  HAL_StatusTypeDef  FlashStatus;
87
+  uint32_t SectorError = 0;
88
+  FLASH_EraseInitTypeDef pEraseInit;
89
+
90
+
91
+  /* Get Page0 status */
92
+  PageStatus0 = (*(__IO uint16_t*)PAGE0_BASE_ADDRESS);
93
+  /* Get Page1 status */
94
+  PageStatus1 = (*(__IO uint16_t*)PAGE1_BASE_ADDRESS);
95
+
96
+  pEraseInit.TypeErase = TYPEERASE_SECTORS;
97
+  pEraseInit.Sector = PAGE0_ID;
98
+  pEraseInit.NbSectors = 1;
99
+  pEraseInit.VoltageRange = VOLTAGE_RANGE;
100
+
101
+  /* Check for invalid header states and repair if necessary */
102
+  switch (PageStatus0) {
103
+    case ERASED:
104
+      if (PageStatus1 == VALID_PAGE) { /* Page0 erased, Page1 valid */
105
+          /* Erase Page0 */
106
+        if(!EE_VerifyPageFullyErased(PAGE0_BASE_ADDRESS)) {
107
+          FlashStatus = HAL_FLASHEx_Erase(&pEraseInit, &SectorError);
108
+          /* If erase operation was failed, a Flash error code is returned */
109
+          if (FlashStatus != HAL_OK) {
110
+            return FlashStatus;
111
+          }
112
+        }
113
+      }
114
+      else if (PageStatus1 == RECEIVE_DATA) { /* Page0 erased, Page1 receive */
115
+        /* Erase Page0 */
116
+        if (!EE_VerifyPageFullyErased(PAGE0_BASE_ADDRESS)) {
117
+          FlashStatus = HAL_FLASHEx_Erase(&pEraseInit, &SectorError);
118
+          /* If erase operation was failed, a Flash error code is returned */
119
+          if (FlashStatus != HAL_OK) return FlashStatus;
120
+        }
121
+        /* Mark Page1 as valid */
122
+        FlashStatus = HAL_FLASH_Program(TYPEPROGRAM_HALFWORD, PAGE1_BASE_ADDRESS, VALID_PAGE);
123
+        /* If program operation was failed, a Flash error code is returned */
124
+        if (FlashStatus != HAL_OK) return FlashStatus;
125
+      }
126
+      else { /* First EEPROM access (Page0&1 are erased) or invalid state -> format EEPROM */
127
+        /* Erase both Page0 and Page1 and set Page0 as valid page */
128
+        FlashStatus = EE_Format();
129
+        /* If erase/program operation was failed, a Flash error code is returned */
130
+        if (FlashStatus != HAL_OK) return FlashStatus;
131
+      }
132
+      break;
133
+
134
+    case RECEIVE_DATA:
135
+      if (PageStatus1 == VALID_PAGE) { /* Page0 receive, Page1 valid */
136
+        /* Transfer data from Page1 to Page0 */
137
+        for (VarIdx = 0; VarIdx < NB_OF_VAR; VarIdx++) {
138
+          if (( *(__IO uint16_t*)(PAGE0_BASE_ADDRESS + 6)) == VirtAddVarTab[VarIdx])
139
+            x = VarIdx;
140
+          if (VarIdx != x) {
141
+            /* Read the last variables' updates */
142
+            ReadStatus = EE_ReadVariable(VirtAddVarTab[VarIdx], &DataVar);
143
+            /* In case variable corresponding to the virtual address was found */
144
+            if (ReadStatus != 0x1) {
145
+              /* Transfer the variable to the Page0 */
146
+              EepromStatus = EE_VerifyPageFullWriteVariable(VirtAddVarTab[VarIdx], DataVar);
147
+              /* If program operation was failed, a Flash error code is returned */
148
+              if (EepromStatus != HAL_OK) return EepromStatus;
149
+            }
150
+          }
151
+        }
152
+        /* Mark Page0 as valid */
153
+        FlashStatus = HAL_FLASH_Program(TYPEPROGRAM_HALFWORD, PAGE0_BASE_ADDRESS, VALID_PAGE);
154
+        /* If program operation was failed, a Flash error code is returned */
155
+        if (FlashStatus != HAL_OK) return FlashStatus;
156
+        pEraseInit.Sector = PAGE1_ID;
157
+        pEraseInit.NbSectors = 1;
158
+        pEraseInit.VoltageRange = VOLTAGE_RANGE;
159
+        /* Erase Page1 */
160
+        if (!EE_VerifyPageFullyErased(PAGE1_BASE_ADDRESS)) {
161
+          FlashStatus = HAL_FLASHEx_Erase(&pEraseInit, &SectorError);
162
+          /* If erase operation was failed, a Flash error code is returned */
163
+          if (FlashStatus != HAL_OK) return FlashStatus;
164
+        }
165
+      }
166
+      else if (PageStatus1 == ERASED) { /* Page0 receive, Page1 erased */
167
+        pEraseInit.Sector = PAGE1_ID;
168
+        pEraseInit.NbSectors = 1;
169
+        pEraseInit.VoltageRange = VOLTAGE_RANGE;
170
+        /* Erase Page1 */
171
+        if (!EE_VerifyPageFullyErased(PAGE1_BASE_ADDRESS)) {
172
+          FlashStatus = HAL_FLASHEx_Erase(&pEraseInit, &SectorError);
173
+          /* If erase operation was failed, a Flash error code is returned */
174
+          if (FlashStatus != HAL_OK) return FlashStatus;
175
+        }
176
+        /* Mark Page0 as valid */
177
+        FlashStatus = HAL_FLASH_Program(TYPEPROGRAM_HALFWORD, PAGE0_BASE_ADDRESS, VALID_PAGE);
178
+        /* If program operation was failed, a Flash error code is returned */
179
+        if (FlashStatus != HAL_OK) return FlashStatus;
180
+      }
181
+      else { /* Invalid state -> format eeprom */
182
+        /* Erase both Page0 and Page1 and set Page0 as valid page */
183
+        FlashStatus = EE_Format();
184
+        /* If erase/program operation was failed, a Flash error code is returned */
185
+        if (FlashStatus != HAL_OK) return FlashStatus;
186
+      }
187
+      break;
188
+
189
+    case VALID_PAGE:
190
+      if (PageStatus1 == VALID_PAGE) { /* Invalid state -> format eeprom */
191
+        /* Erase both Page0 and Page1 and set Page0 as valid page */
192
+        FlashStatus = EE_Format();
193
+        /* If erase/program operation was failed, a Flash error code is returned */
194
+        if (FlashStatus != HAL_OK) return FlashStatus;
195
+      }
196
+      else if (PageStatus1 == ERASED) { /* Page0 valid, Page1 erased */
197
+        pEraseInit.Sector = PAGE1_ID;
198
+        pEraseInit.NbSectors = 1;
199
+        pEraseInit.VoltageRange = VOLTAGE_RANGE;
200
+        /* Erase Page1 */
201
+        if (!EE_VerifyPageFullyErased(PAGE1_BASE_ADDRESS)) {
202
+          FlashStatus = HAL_FLASHEx_Erase(&pEraseInit, &SectorError);
203
+          /* If erase operation was failed, a Flash error code is returned */
204
+          if (FlashStatus != HAL_OK) return FlashStatus;
205
+        }
206
+      }
207
+      else { /* Page0 valid, Page1 receive */
208
+        /* Transfer data from Page0 to Page1 */
209
+        for (VarIdx = 0; VarIdx < NB_OF_VAR; VarIdx++) {
210
+          if ((*(__IO uint16_t*)(PAGE1_BASE_ADDRESS + 6)) == VirtAddVarTab[VarIdx])
211
+            x = VarIdx;
212
+
213
+          if (VarIdx != x) {
214
+            /* Read the last variables' updates */
215
+            ReadStatus = EE_ReadVariable(VirtAddVarTab[VarIdx], &DataVar);
216
+            /* In case variable corresponding to the virtual address was found */
217
+            if (ReadStatus != 0x1) {
218
+              /* Transfer the variable to the Page1 */
219
+              EepromStatus = EE_VerifyPageFullWriteVariable(VirtAddVarTab[VarIdx], DataVar);
220
+              /* If program operation was failed, a Flash error code is returned */
221
+              if (EepromStatus != HAL_OK) return EepromStatus;
222
+            }
223
+          }
224
+        }
225
+        /* Mark Page1 as valid */
226
+        FlashStatus = HAL_FLASH_Program(TYPEPROGRAM_HALFWORD, PAGE1_BASE_ADDRESS, VALID_PAGE);
227
+        /* If program operation was failed, a Flash error code is returned */
228
+        if (FlashStatus != HAL_OK) return FlashStatus;
229
+        pEraseInit.Sector = PAGE0_ID;
230
+        pEraseInit.NbSectors = 1;
231
+        pEraseInit.VoltageRange = VOLTAGE_RANGE;
232
+        /* Erase Page0 */
233
+        if (!EE_VerifyPageFullyErased(PAGE0_BASE_ADDRESS)) {
234
+          FlashStatus = HAL_FLASHEx_Erase(&pEraseInit, &SectorError);
235
+          /* If erase operation was failed, a Flash error code is returned */
236
+          if (FlashStatus != HAL_OK) return FlashStatus;
237
+        }
238
+      }
239
+      break;
240
+
241
+    default:  /* Any other state -> format eeprom */
242
+      /* Erase both Page0 and Page1 and set Page0 as valid page */
243
+      FlashStatus = EE_Format();
244
+      /* If erase/program operation was failed, a Flash error code is returned */
245
+      if (FlashStatus != HAL_OK) return FlashStatus;
246
+      break;
247
+  }
248
+
249
+  return HAL_OK;
250
+}
251
+
252
+/**
253
+ * @brief  Verify if specified page is fully erased.
254
+ * @param  Address: page address
255
+ *   This parameter can be one of the following values:
256
+ *     @arg PAGE0_BASE_ADDRESS: Page0 base address
257
+ *     @arg PAGE1_BASE_ADDRESS: Page1 base address
258
+ * @retval page fully erased status:
259
+ *           - 0: if Page not erased
260
+ *           - 1: if Page erased
261
+ */
262
+uint16_t EE_VerifyPageFullyErased(uint32_t Address) {
263
+  uint32_t ReadStatus = 1;
264
+  uint16_t AddressValue = 0x5555;
265
+  /* Check each active page address starting from end */
266
+  while (Address <= PAGE0_END_ADDRESS) {
267
+    /* Get the current location content to be compared with virtual address */
268
+    AddressValue = (*(__IO uint16_t*)Address);
269
+    /* Compare the read address with the virtual address */
270
+    if (AddressValue != ERASED) {
271
+      /* In case variable value is read, reset ReadStatus flag */
272
+      ReadStatus = 0;
273
+      break;
274
+    }
275
+    /* Next address location */
276
+    Address += 4;
277
+  }
278
+  /* Return ReadStatus value: (0: Page not erased, 1: Sector erased) */
279
+  return ReadStatus;
280
+}
281
+
282
+/**
283
+ * @brief  Returns the last stored variable data, if found, which correspond to
284
+ *   the passed virtual address
285
+ * @param  VirtAddress: Variable virtual address
286
+ * @param  Data: Global variable contains the read variable value
287
+ * @retval Success or error status:
288
+ *           - 0: if variable was found
289
+ *           - 1: if the variable was not found
290
+ *           - NO_VALID_PAGE: if no valid page was found.
291
+ */
292
+uint16_t EE_ReadVariable(uint16_t VirtAddress, uint16_t* Data) {
293
+  uint16_t ValidPage = PAGE0;
294
+  uint16_t AddressValue = 0x5555, ReadStatus = 1;
295
+  uint32_t Address = EEPROM_START_ADDRESS, PageStartAddress = EEPROM_START_ADDRESS;
296
+
297
+  /* Get active Page for read operation */
298
+  ValidPage = EE_FindValidPage(READ_FROM_VALID_PAGE);
299
+
300
+  /* Check if there is no valid page */
301
+  if (ValidPage == NO_VALID_PAGE) return NO_VALID_PAGE;
302
+
303
+  /* Get the valid Page start Address */
304
+  PageStartAddress = (uint32_t)(EEPROM_START_ADDRESS + (uint32_t)(ValidPage * PAGE_SIZE));
305
+
306
+  /* Get the valid Page end Address */
307
+  Address = (uint32_t)((EEPROM_START_ADDRESS - 2) + (uint32_t)((1 + ValidPage) * PAGE_SIZE));
308
+
309
+  /* Check each active page address starting from end */
310
+  while (Address > (PageStartAddress + 2)) {
311
+    /* Get the current location content to be compared with virtual address */
312
+    AddressValue = (*(__IO uint16_t*)Address);
313
+
314
+    /* Compare the read address with the virtual address */
315
+    if (AddressValue == VirtAddress) {
316
+      /* Get content of Address-2 which is variable value */
317
+      *Data = (*(__IO uint16_t*)(Address - 2));
318
+      /* In case variable value is read, reset ReadStatus flag */
319
+      ReadStatus = 0;
320
+      break;
321
+    }
322
+    else /* Next address location */
323
+      Address -= 4;
324
+  }
325
+  /* Return ReadStatus value: (0: variable exist, 1: variable doesn't exist) */
326
+  return ReadStatus;
327
+}
328
+
329
+/**
330
+ * @brief  Writes/upadtes variable data in EEPROM.
331
+ * @param  VirtAddress: Variable virtual address
332
+ * @param  Data: 16 bit data to be written
333
+ * @retval Success or error status:
334
+ *           - FLASH_COMPLETE: on success
335
+ *           - PAGE_FULL: if valid page is full
336
+ *           - NO_VALID_PAGE: if no valid page was found
337
+ *           - Flash error code: on write Flash error
338
+ */
339
+uint16_t EE_WriteVariable(uint16_t VirtAddress, uint16_t Data) {
340
+  /* Write the variable virtual address and value in the EEPROM */
341
+  uint16_t Status = EE_VerifyPageFullWriteVariable(VirtAddress, Data);
342
+
343
+  /* In case the EEPROM active page is full */
344
+  if (Status == PAGE_FULL) /* Perform Page transfer */
345
+    Status = EE_PageTransfer(VirtAddress, Data);
346
+
347
+  /* Return last operation status */
348
+  return Status;
349
+}
350
+
351
+/**
352
+ * @brief  Erases PAGE and PAGE1 and writes VALID_PAGE header to PAGE
353
+ * @param  None
354
+ * @retval Status of the last operation (Flash write or erase) done during
355
+ *         EEPROM formating
356
+ */
357
+static HAL_StatusTypeDef EE_Format(void) {
358
+  HAL_StatusTypeDef FlashStatus = HAL_OK;
359
+  uint32_t SectorError = 0;
360
+  FLASH_EraseInitTypeDef pEraseInit;
361
+
362
+  pEraseInit.TypeErase = FLASH_TYPEERASE_SECTORS;
363
+  pEraseInit.Sector = PAGE0_ID;
364
+  pEraseInit.NbSectors = 1;
365
+  pEraseInit.VoltageRange = VOLTAGE_RANGE;
366
+  /* Erase Page0 */
367
+  if (!EE_VerifyPageFullyErased(PAGE0_BASE_ADDRESS)) {
368
+    FlashStatus = HAL_FLASHEx_Erase(&pEraseInit, &SectorError);
369
+    /* If erase operation was failed, a Flash error code is returned */
370
+    if (FlashStatus != HAL_OK) return FlashStatus;
371
+  }
372
+  /* Set Page0 as valid page: Write VALID_PAGE at Page0 base address */
373
+  FlashStatus = HAL_FLASH_Program(TYPEPROGRAM_HALFWORD, PAGE0_BASE_ADDRESS, VALID_PAGE);
374
+  /* If program operation was failed, a Flash error code is returned */
375
+  if (FlashStatus != HAL_OK) return FlashStatus;
376
+
377
+  pEraseInit.Sector = PAGE1_ID;
378
+  /* Erase Page1 */
379
+  if (!EE_VerifyPageFullyErased(PAGE1_BASE_ADDRESS)) {
380
+    FlashStatus = HAL_FLASHEx_Erase(&pEraseInit, &SectorError);
381
+    /* If erase operation was failed, a Flash error code is returned */
382
+    if (FlashStatus != HAL_OK) return FlashStatus;
383
+  }
384
+
385
+  return HAL_OK;
386
+}
387
+
388
+/**
389
+ * @brief  Find valid Page for write or read operation
390
+ * @param  Operation: operation to achieve on the valid page.
391
+ *   This parameter can be one of the following values:
392
+ *     @arg READ_FROM_VALID_PAGE: read operation from valid page
393
+ *     @arg WRITE_IN_VALID_PAGE: write operation from valid page
394
+ * @retval Valid page number (PAGE or PAGE1) or NO_VALID_PAGE in case
395
+ *   of no valid page was found
396
+ */
397
+static uint16_t EE_FindValidPage(uint8_t Operation) {
398
+  uint16_t PageStatus0 = 6, PageStatus1 = 6;
399
+
400
+  /* Get Page0 actual status */
401
+  PageStatus0 = (*(__IO uint16_t*)PAGE0_BASE_ADDRESS);
402
+
403
+  /* Get Page1 actual status */
404
+  PageStatus1 = (*(__IO uint16_t*)PAGE1_BASE_ADDRESS);
405
+
406
+  /* Write or read operation */
407
+  switch (Operation) {
408
+    case WRITE_IN_VALID_PAGE:   /* ---- Write operation ---- */
409
+      if (PageStatus1 == VALID_PAGE) {
410
+        /* Page0 receiving data */
411
+        if (PageStatus0 == RECEIVE_DATA) return PAGE0;         /* Page0 valid */
412
+        else                             return PAGE1;         /* Page1 valid */
413
+      }
414
+      else if (PageStatus0 == VALID_PAGE) {
415
+        /* Page1 receiving data */
416
+        if (PageStatus1 == RECEIVE_DATA) return PAGE1;         /* Page1 valid */
417
+        else                             return PAGE0;         /* Page0 valid */
418
+      }
419
+      else
420
+        return NO_VALID_PAGE;   /* No valid Page */
421
+
422
+    case READ_FROM_VALID_PAGE:  /* ---- Read operation ---- */
423
+      if (PageStatus0 == VALID_PAGE)
424
+        return PAGE0;           /* Page0 valid */
425
+      else if (PageStatus1 == VALID_PAGE)
426
+        return PAGE1;           /* Page1 valid */
427
+      else
428
+        return NO_VALID_PAGE;   /* No valid Page */
429
+
430
+    default:
431
+      return PAGE0;             /* Page0 valid */
432
+  }
433
+}
434
+
435
+/**
436
+ * @brief  Verify if active page is full and Writes variable in EEPROM.
437
+ * @param  VirtAddress: 16 bit virtual address of the variable
438
+ * @param  Data: 16 bit data to be written as variable value
439
+ * @retval Success or error status:
440
+ *           - FLASH_COMPLETE: on success
441
+ *           - PAGE_FULL: if valid page is full
442
+ *           - NO_VALID_PAGE: if no valid page was found
443
+ *           - Flash error code: on write Flash error
444
+ */
445
+static uint16_t EE_VerifyPageFullWriteVariable(uint16_t VirtAddress, uint16_t Data) {
446
+  HAL_StatusTypeDef FlashStatus = HAL_OK;
447
+  uint16_t ValidPage = PAGE0;
448
+  uint32_t Address = EEPROM_START_ADDRESS, PageEndAddress = EEPROM_START_ADDRESS+PAGE_SIZE;
449
+
450
+  /* Get valid Page for write operation */
451
+  ValidPage = EE_FindValidPage(WRITE_IN_VALID_PAGE);
452
+
453
+  /* Check if there is no valid page */
454
+  if (ValidPage == NO_VALID_PAGE) return NO_VALID_PAGE;
455
+
456
+  /* Get the valid Page start Address */
457
+  Address = (uint32_t)(EEPROM_START_ADDRESS + (uint32_t)(ValidPage * PAGE_SIZE));
458
+
459
+  /* Get the valid Page end Address */
460
+  PageEndAddress = (uint32_t)((EEPROM_START_ADDRESS - 1) + (uint32_t)((ValidPage + 1) * PAGE_SIZE));
461
+
462
+  /* Check each active page address starting from begining */
463
+  while (Address < PageEndAddress) {
464
+    /* Verify if Address and Address+2 contents are 0xFFFFFFFF */
465
+    if ((*(__IO uint32_t*)Address) == 0xFFFFFFFF) {
466
+      /* Set variable data */
467
+      FlashStatus = HAL_FLASH_Program(TYPEPROGRAM_HALFWORD, Address, Data);
468
+      /* If program operation was failed, a Flash error code is returned */
469
+      if (FlashStatus != HAL_OK) return FlashStatus;
470
+      /* Set variable virtual address */
471
+      FlashStatus = HAL_FLASH_Program(TYPEPROGRAM_HALFWORD, Address + 2, VirtAddress);
472
+      /* Return program operation status */
473
+      return FlashStatus;
474
+    }
475
+    else /* Next address location */
476
+      Address += 4;
477
+  }
478
+
479
+  /* Return PAGE_FULL in case the valid page is full */
480
+  return PAGE_FULL;
481
+}
482
+
483
+/**
484
+ * @brief  Transfers last updated variables data from the full Page to
485
+ *   an empty one.
486
+ * @param  VirtAddress: 16 bit virtual address of the variable
487
+ * @param  Data: 16 bit data to be written as variable value
488
+ * @retval Success or error status:
489
+ *           - FLASH_COMPLETE: on success
490
+ *           - PAGE_FULL: if valid page is full
491
+ *           - NO_VALID_PAGE: if no valid page was found
492
+ *           - Flash error code: on write Flash error
493
+ */
494
+static uint16_t EE_PageTransfer(uint16_t VirtAddress, uint16_t Data) {
495
+  HAL_StatusTypeDef FlashStatus = HAL_OK;
496
+  uint32_t NewPageAddress = EEPROM_START_ADDRESS;
497
+  uint16_t OldPageId=0;
498
+  uint16_t ValidPage = PAGE0, VarIdx = 0;
499
+  uint16_t EepromStatus = 0, ReadStatus = 0;
500
+  uint32_t SectorError = 0;
501
+  FLASH_EraseInitTypeDef pEraseInit;
502
+
503
+  /* Get active Page for read operation */
504
+  ValidPage = EE_FindValidPage(READ_FROM_VALID_PAGE);
505
+
506
+  if (ValidPage == PAGE1) {     /* Page1 valid */
507
+    /* New page address where variable will be moved to */
508
+    NewPageAddress = PAGE0_BASE_ADDRESS;
509
+    /* Old page ID where variable will be taken from */
510
+    OldPageId = PAGE1_ID;
511
+  }
512
+  else if (ValidPage == PAGE0) { /* Page0 valid */
513
+    /* New page address  where variable will be moved to */
514
+    NewPageAddress = PAGE1_BASE_ADDRESS;
515
+    /* Old page ID where variable will be taken from */
516
+    OldPageId = PAGE0_ID;
517
+  }
518
+  else
519
+    return NO_VALID_PAGE;       /* No valid Page */
520
+
521
+  /* Set the new Page status to RECEIVE_DATA status */
522
+  FlashStatus = HAL_FLASH_Program(TYPEPROGRAM_HALFWORD, NewPageAddress, RECEIVE_DATA);
523
+  /* If program operation was failed, a Flash error code is returned */
524
+  if (FlashStatus != HAL_OK) return FlashStatus;
525
+
526
+  /* Write the variable passed as parameter in the new active page */
527
+  EepromStatus = EE_VerifyPageFullWriteVariable(VirtAddress, Data);
528
+  /* If program operation was failed, a Flash error code is returned */
529
+  if (EepromStatus != HAL_OK) return EepromStatus;
530
+
531
+  /* Transfer process: transfer variables from old to the new active page */
532
+  for (VarIdx = 0; VarIdx < NB_OF_VAR; VarIdx++) {
533
+    if (VirtAddVarTab[VarIdx] != VirtAddress) { /* Check each variable except the one passed as parameter */
534
+      /* Read the other last variable updates */
535
+      ReadStatus = EE_ReadVariable(VirtAddVarTab[VarIdx], &DataVar);
536
+      /* In case variable corresponding to the virtual address was found */
537
+      if (ReadStatus != 0x1) {
538
+        /* Transfer the variable to the new active page */
539
+        EepromStatus = EE_VerifyPageFullWriteVariable(VirtAddVarTab[VarIdx], DataVar);
540
+        /* If program operation was failed, a Flash error code is returned */
541
+        if (EepromStatus != HAL_OK) return EepromStatus;
542
+      }
543
+    }
544
+  }
545
+
546
+  pEraseInit.TypeErase = TYPEERASE_SECTORS;
547
+  pEraseInit.Sector = OldPageId;
548
+  pEraseInit.NbSectors = 1;
549
+  pEraseInit.VoltageRange = VOLTAGE_RANGE;
550
+
551
+  /* Erase the old Page: Set old Page status to ERASED status */
552
+  FlashStatus = HAL_FLASHEx_Erase(&pEraseInit, &SectorError);
553
+  /* If erase operation was failed, a Flash error code is returned */
554
+  if (FlashStatus != HAL_OK) return FlashStatus;
555
+
556
+  /* Set new Page status to VALID_PAGE status */
557
+  FlashStatus = HAL_FLASH_Program(TYPEPROGRAM_HALFWORD, NewPageAddress, VALID_PAGE);
558
+  /* If program operation was failed, a Flash error code is returned */
559
+  if (FlashStatus != HAL_OK) return FlashStatus;
560
+
561
+  /* Return last operation flash status */
562
+  return FlashStatus;
563
+}
564
+
565
+#endif // STM32F7
566
+
567
+/**
568
+ * @}
569
+ */
570
+
571
+/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/

+ 118
- 0
Marlin/src/HAL/HAL_STM32F7/EEPROM_Emul/eeprom_emul.h View File

@@ -0,0 +1,118 @@
1
+/**
2
+  ******************************************************************************
3
+  * @file    EEPROM/EEPROM_Emulation/inc/eeprom.h
4
+  * @author  MCD Application Team
5
+  * @version V1.2.6
6
+  * @date    04-November-2016
7
+  * @brief   This file contains all the functions prototypes for the EEPROM
8
+  *          emulation firmware library.
9
+  ******************************************************************************
10
+  * @attention
11
+  *
12
+  * <h2><center>&copy; Copyright © 2016 STMicroelectronics International N.V.
13
+  * All rights reserved.</center></h2>
14
+  *
15
+  * Redistribution and use in source and binary forms, with or without
16
+  * modification, are permitted, provided that the following conditions are met:
17
+  *
18
+  * 1. Redistribution of source code must retain the above copyright notice,
19
+  *    this list of conditions and the following disclaimer.
20
+  * 2. Redistributions in binary form must reproduce the above copyright notice,
21
+  *    this list of conditions and the following disclaimer in the documentation
22
+  *    and/or other materials provided with the distribution.
23
+  * 3. Neither the name of STMicroelectronics nor the names of other
24
+  *    contributors to this software may be used to endorse or promote products
25
+  *    derived from this software without specific written permission.
26
+  * 4. This software, including modifications and/or derivative works of this
27
+  *    software, must execute solely and exclusively on microcontroller or
28
+  *    microprocessor devices manufactured by or for STMicroelectronics.
29
+  * 5. Redistribution and use of this software other than as permitted under
30
+  *    this license is void and will automatically terminate your rights under
31
+  *    this license.
32
+  *
33
+  * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
34
+  * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
35
+  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
36
+  * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
37
+  * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
38
+  * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
39
+  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
40
+  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
41
+  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
42
+  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
43
+  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
44
+  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45
+  *
46
+  ******************************************************************************
47
+  */
48
+
49
+/* Define to prevent recursive inclusion -------------------------------------*/
50
+#ifndef __EEEPROM_EMUL_H
51
+#define __EEEPROM_EMUL_H
52
+
53
+// --------------------------------------------------------------------------
54
+// Includes
55
+// --------------------------------------------------------------------------
56
+#include "../../../inc/MarlinConfig.h"
57
+#include "../../HAL.h"
58
+
59
+/* Exported constants --------------------------------------------------------*/
60
+/* EEPROM emulation firmware error codes */
61
+#define EE_OK      (uint32_t)HAL_OK
62
+#define EE_ERROR   (uint32_t)HAL_ERROR
63
+#define EE_BUSY    (uint32_t)HAL_BUSY
64
+#define EE_TIMEOUT (uint32_t)HAL_TIMEOUT
65
+
66
+/* Define the size of the sectors to be used */
67
+#define PAGE_SIZE               (uint32_t)0x4000  /* Page size = 16KByte */
68
+
69
+/* Device voltage range supposed to be [2.7V to 3.6V], the operation will
70
+   be done by word  */
71
+#define VOLTAGE_RANGE           (uint8_t)VOLTAGE_RANGE_3
72
+
73
+/* EEPROM start address in Flash */
74
+#define EEPROM_START_ADDRESS  ((uint32_t)0x08100000) /* EEPROM emulation start address:
75
+                                                  from sector2 : after 16KByte of used
76
+                                                  Flash memory */
77
+
78
+/* Pages 0 and 1 base and end addresses */
79
+#define PAGE0_BASE_ADDRESS    ((uint32_t)(EEPROM_START_ADDRESS + 0x0000))
80
+#define PAGE0_END_ADDRESS     ((uint32_t)(EEPROM_START_ADDRESS + (PAGE_SIZE - 1)))
81
+#define PAGE0_ID               FLASH_SECTOR_1
82
+
83
+#define PAGE1_BASE_ADDRESS    ((uint32_t)(EEPROM_START_ADDRESS + 0x4000))
84
+#define PAGE1_END_ADDRESS     ((uint32_t)(EEPROM_START_ADDRESS + (2 * PAGE_SIZE - 1)))
85
+#define PAGE1_ID               FLASH_SECTOR_2
86
+
87
+/* Used Flash pages for EEPROM emulation */
88
+#define PAGE0                 ((uint16_t)0x0000)
89
+#define PAGE1                 ((uint16_t)0x0001) /* Page nb between PAGE0_BASE_ADDRESS & PAGE1_BASE_ADDRESS*/
90
+
91
+/* No valid page define */
92
+#define NO_VALID_PAGE         ((uint16_t)0x00AB)
93
+
94
+/* Page status definitions */
95
+#define ERASED                ((uint16_t)0xFFFF)     /* Page is empty */
96
+#define RECEIVE_DATA          ((uint16_t)0xEEEE)     /* Page is marked to receive data */
97
+#define VALID_PAGE            ((uint16_t)0x0000)     /* Page containing valid data */
98
+
99
+/* Valid pages in read and write defines */
100
+#define READ_FROM_VALID_PAGE  ((uint8_t)0x00)
101
+#define WRITE_IN_VALID_PAGE   ((uint8_t)0x01)
102
+
103
+/* Page full define */
104
+#define PAGE_FULL             ((uint8_t)0x80)
105
+
106
+/* Variables' number */
107
+#define NB_OF_VAR             ((uint16_t)4096)
108
+
109
+/* Exported types ------------------------------------------------------------*/
110
+/* Exported macro ------------------------------------------------------------*/
111
+/* Exported functions ------------------------------------------------------- */
112
+uint16_t EE_Initialise(void);
113
+uint16_t EE_ReadVariable(uint16_t VirtAddress, uint16_t* Data);
114
+uint16_t EE_WriteVariable(uint16_t VirtAddress, uint16_t Data);
115
+
116
+#endif /* __EEEPROM_H */
117
+
118
+/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

+ 146
- 0
Marlin/src/HAL/HAL_STM32F7/EmulatedEeprom.cpp View File

@@ -0,0 +1,146 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
+ *
5
+ * This program is free software: you can redistribute it and/or modify
6
+ * it under the terms of the GNU General Public License as published by
7
+ * the Free Software Foundation, either version 3 of the License, or
8
+ * (at your option) any later version.
9
+ *
10
+ * This program is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
+ * GNU General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU General Public License
16
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
+ *
18
+ */
19
+
20
+#ifdef STM32F7
21
+
22
+/**
23
+ * Description: functions for I2C connected external EEPROM.
24
+ * Not platform dependent.
25
+ */
26
+
27
+#include "../../inc/MarlinConfig.h"
28
+
29
+// --------------------------------------------------------------------------
30
+// Includes
31
+// --------------------------------------------------------------------------
32
+
33
+#include "../HAL.h"
34
+#include "EEPROM_Emul/eeprom_emul.h"
35
+
36
+
37
+// --------------------------------------------------------------------------
38
+// Externals
39
+// --------------------------------------------------------------------------
40
+
41
+// --------------------------------------------------------------------------
42
+// Local defines
43
+// --------------------------------------------------------------------------
44
+
45
+// --------------------------------------------------------------------------
46
+// Types
47
+// --------------------------------------------------------------------------
48
+
49
+// --------------------------------------------------------------------------
50
+// Variables
51
+// --------------------------------------------------------------------------
52
+
53
+// --------------------------------------------------------------------------
54
+// Public Variables
55
+// --------------------------------------------------------------------------
56
+
57
+// --------------------------------------------------------------------------
58
+// Private Variables
59
+// --------------------------------------------------------------------------
60
+static bool eeprom_initialised = false;
61
+// --------------------------------------------------------------------------
62
+// Function prototypes
63
+// --------------------------------------------------------------------------
64
+
65
+// --------------------------------------------------------------------------
66
+// Private functions
67
+// --------------------------------------------------------------------------
68
+
69
+// --------------------------------------------------------------------------
70
+// Public functions
71
+// --------------------------------------------------------------------------
72
+
73
+// FLASH_FLAG_PGSERR (Programming Sequence Error) was renamed to
74
+// FLASH_FLAG_ERSERR (Erasing Sequence Error) in STM32F7
75
+#define FLASH_FLAG_PGSERR FLASH_FLAG_ERSERR
76
+
77
+// --------------------------------------------------------------------------
78
+// EEPROM
79
+// --------------------------------------------------------------------------
80
+
81
+
82
+void eeprom_init() {
83
+  if(!eeprom_initialised) {
84
+    HAL_FLASH_Unlock();
85
+
86
+    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);
87
+
88
+    /* EEPROM Init */
89
+    if(EE_Initialise() != EE_OK)
90
+    {
91
+      while(1) {
92
+        HAL_Delay(1);
93
+      }
94
+    }
95
+
96
+    HAL_FLASH_Lock();
97
+    eeprom_initialised = true;
98
+  }
99
+
100
+}
101
+
102
+void eeprom_write_byte(unsigned char *pos, unsigned char value) {
103
+  uint16_t eeprom_address = (unsigned) pos;
104
+
105
+  eeprom_init();
106
+
107
+  HAL_FLASH_Unlock();
108
+  __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);
109
+  if(EE_WriteVariable(eeprom_address, (uint16_t) value) != EE_OK) {
110
+    while(1) {
111
+      HAL_Delay(1);
112
+    }
113
+  }
114
+  HAL_FLASH_Lock();
115
+}
116
+
117
+unsigned char eeprom_read_byte(unsigned char *pos) {
118
+  uint16_t data = 0xFF;
119
+  uint16_t eeprom_address = (unsigned) pos;
120
+
121
+  eeprom_init();
122
+
123
+  if(EE_ReadVariable(eeprom_address, &data) != EE_OK) {
124
+    return (char) data;
125
+  }
126
+  return (char)data;
127
+}
128
+
129
+void eeprom_read_block (void *__dst, const void *__src, size_t __n) {
130
+  uint16_t data = 0xFF;
131
+  uint16_t eeprom_address = (unsigned) __src;
132
+
133
+  eeprom_init();
134
+
135
+  for(uint8_t c = 0; c < __n; c++) {
136
+    EE_ReadVariable(eeprom_address+c, &data);
137
+    *((uint8_t*)__dst + c) = data;
138
+  }
139
+}
140
+
141
+void eeprom_update_block (const void *__src, void *__dst, size_t __n) {
142
+
143
+}
144
+
145
+#endif // STM32F7
146
+

+ 140
- 0
Marlin/src/HAL/HAL_STM32F7/HAL_STM32F7.cpp View File

@@ -0,0 +1,140 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ *
4
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
5
+ * Copyright (c) 2016 Bob Cousins bobcousins42@googlemail.com
6
+ * Copyright (c) 2015-2016 Nico Tonnhofer wurstnase.reprap@gmail.com
7
+ * Copyright (c) 2017 Victor Perez
8
+ *
9
+ * This program is free software: you can redistribute it and/or modify
10
+ * it under the terms of the GNU General Public License as published by
11
+ * the Free Software Foundation, either version 3 of the License, or
12
+ * (at your option) any later version.
13
+ *
14
+ * This program is distributed in the hope that it will be useful,
15
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
+ * GNU General Public License for more details.
18
+ *
19
+ * You should have received a copy of the GNU General Public License
20
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
+ *
22
+ */
23
+
24
+
25
+#ifdef STM32F7
26
+
27
+// --------------------------------------------------------------------------
28
+// Includes
29
+// --------------------------------------------------------------------------
30
+
31
+#include "../HAL.h"
32
+
33
+//#include <Wire.h>
34
+
35
+// --------------------------------------------------------------------------
36
+// Externals
37
+// --------------------------------------------------------------------------
38
+
39
+// --------------------------------------------------------------------------
40
+// Local defines
41
+// --------------------------------------------------------------------------
42
+
43
+// --------------------------------------------------------------------------
44
+// Types
45
+// --------------------------------------------------------------------------
46
+
47
+// --------------------------------------------------------------------------
48
+// Variables
49
+// --------------------------------------------------------------------------
50
+
51
+// --------------------------------------------------------------------------
52
+// Public Variables
53
+// --------------------------------------------------------------------------
54
+
55
+uint16_t HAL_adc_result;
56
+
57
+// --------------------------------------------------------------------------
58
+// Private Variables
59
+// --------------------------------------------------------------------------
60
+
61
+// --------------------------------------------------------------------------
62
+// Function prototypes
63
+// --------------------------------------------------------------------------
64
+
65
+// --------------------------------------------------------------------------
66
+// Private functions
67
+// --------------------------------------------------------------------------
68
+
69
+// --------------------------------------------------------------------------
70
+// Public functions
71
+// --------------------------------------------------------------------------
72
+
73
+/* VGPV Done with defines
74
+// disable interrupts
75
+void cli(void) { noInterrupts(); }
76
+
77
+// enable interrupts
78
+void sei(void) { interrupts(); }
79
+*/
80
+
81
+void HAL_clear_reset_source(void) { __HAL_RCC_CLEAR_RESET_FLAGS(); }
82
+
83
+uint8_t HAL_get_reset_source (void) {
84
+  if (__HAL_RCC_GET_FLAG(RCC_FLAG_IWDGRST) != RESET)
85
+    return RST_WATCHDOG;
86
+
87
+  if (__HAL_RCC_GET_FLAG(RCC_FLAG_SFTRST) != RESET)
88
+    return RST_SOFTWARE;
89
+
90
+  if (__HAL_RCC_GET_FLAG(RCC_FLAG_PINRST) != RESET)
91
+    return RST_EXTERNAL;
92
+
93
+  if (__HAL_RCC_GET_FLAG(RCC_FLAG_PORRST) != RESET)
94
+    return RST_POWER_ON;
95
+  return 0;
96
+}
97
+
98
+void _delay_ms(const int delay_ms) { delay(delay_ms); }
99
+
100
+extern "C" {
101
+  extern unsigned int _ebss; // end of bss section
102
+}
103
+
104
+// return free memory between end of heap (or end bss) and whatever is current
105
+
106
+/*
107
+#include "wirish/syscalls.c"
108
+//extern caddr_t _sbrk(int incr);
109
+#ifndef CONFIG_HEAP_END
110
+extern char _lm_heap_end;
111
+#define CONFIG_HEAP_END ((caddr_t)&_lm_heap_end)
112
+#endif
113
+
114
+extern "C" {
115
+  static int freeMemory() {
116
+    char top = 't';
117
+    return &top - reinterpret_cast<char*>(sbrk(0));
118
+  }
119
+  int freeMemory() {
120
+    int free_memory;
121
+    int heap_end = (int)_sbrk(0);
122
+    free_memory = ((int)&free_memory) - ((int)heap_end);
123
+    return free_memory;
124
+  }
125
+}
126
+*/
127
+
128
+// --------------------------------------------------------------------------
129
+// ADC
130
+// --------------------------------------------------------------------------
131
+
132
+void HAL_adc_start_conversion(const uint8_t adc_pin) {
133
+  HAL_adc_result = analogRead(adc_pin);
134
+}
135
+
136
+uint16_t HAL_adc_get_result(void) {
137
+  return HAL_adc_result;
138
+}
139
+
140
+#endif // STM32F7

+ 236
- 0
Marlin/src/HAL/HAL_STM32F7/HAL_STM32F7.h View File

@@ -0,0 +1,236 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ *
4
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
5
+ * Copyright (c) 2016 Bob Cousins bobcousins42@googlemail.com
6
+ * Copyright (c) 2015-2016 Nico Tonnhofer wurstnase.reprap@gmail.com
7
+ * Copyright (c) 2017 Victor Perez
8
+ *
9
+ * This program is free software: you can redistribute it and/or modify
10
+ * it under the terms of the GNU General Public License as published by
11
+ * the Free Software Foundation, either version 3 of the License, or
12
+ * (at your option) any later version.
13
+ *
14
+ * This program is distributed in the hope that it will be useful,
15
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
+ * GNU General Public License for more details.
18
+ *
19
+ * You should have received a copy of the GNU General Public License
20
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
+ *
22
+ */
23
+
24
+
25
+
26
+#ifndef _HAL_STM32F7_H
27
+#define _HAL_STM32F7_H
28
+
29
+#undef DEBUG_NONE
30
+
31
+#ifndef vsnprintf_P
32
+  #define vsnprintf_P vsnprintf
33
+#endif
34
+
35
+// --------------------------------------------------------------------------
36
+// Includes
37
+// --------------------------------------------------------------------------
38
+
39
+#include <stdint.h>
40
+
41
+#include "Arduino.h"
42
+
43
+#include "fastio_STM32F7.h"
44
+#include "watchdog_STM32F7.h"
45
+
46
+#include "HAL_timers_STM32F7.h"
47
+
48
+
49
+// --------------------------------------------------------------------------
50
+// Defines
51
+// --------------------------------------------------------------------------
52
+
53
+//Serial override
54
+//extern HalSerial usb_serial;
55
+
56
+#if !WITHIN(SERIAL_PORT, -1, 6)
57
+  #error "SERIAL_PORT must be from -1 to 6"
58
+#endif
59
+#if SERIAL_PORT == -1
60
+  #define MYSERIAL0 SerialUSB
61
+#elif SERIAL_PORT == 1
62
+  #define MYSERIAL0 SerialUART1
63
+#elif SERIAL_PORT == 2
64
+  #define MYSERIAL0 SerialUART2
65
+#elif SERIAL_PORT == 3
66
+  #define MYSERIAL0 SerialUART3
67
+#elif SERIAL_PORT == 4
68
+  #define MYSERIAL0 SerialUART4
69
+#elif SERIAL_PORT == 5
70
+  #define MYSERIAL0 SerialUART5
71
+#elif SERIAL_PORT == 6
72
+  #define MYSERIAL0 SerialUART6
73
+#endif
74
+
75
+#ifdef SERIAL_PORT_2
76
+  #if !WITHIN(SERIAL_PORT_2, -1, 6)
77
+    #error "SERIAL_PORT_2 must be from -1 to 6"
78
+  #elif SERIAL_PORT_2 == SERIAL_PORT
79
+    #error "SERIAL_PORT_2 must be different than SERIAL_PORT"
80
+  #endif
81
+  #define NUM_SERIAL 2
82
+  #if SERIAL_PORT_2 == -1
83
+    #define MYSERIAL1 SerialUSB
84
+  #elif SERIAL_PORT_2 == 1
85
+    #define MYSERIAL1 SerialUART1
86
+  #elif SERIAL_PORT_2 == 2
87
+    #define MYSERIAL1 SerialUART2
88
+  #elif SERIAL_PORT_2 == 3
89
+    #define MYSERIAL1 SerialUART3
90
+  #elif SERIAL_PORT_2 == 4
91
+    #define MYSERIAL1 SerialUART4
92
+  #elif SERIAL_PORT_2 == 5
93
+    #define MYSERIAL1 SerialUART5
94
+  #elif SERIAL_PORT_2 == 6
95
+    #define MYSERIAL1 SerialUART6
96
+  #endif
97
+#else
98
+  #define NUM_SERIAL 1
99
+#endif
100
+
101
+#define _BV(bit) (1 << (bit))
102
+
103
+/**
104
+ * TODO: review this to return 1 for pins that are not analog input
105
+ */
106
+#ifndef analogInputToDigitalPin
107
+  #define analogInputToDigitalPin(p) (p)
108
+#endif
109
+
110
+#define CRITICAL_SECTION_START  noInterrupts();
111
+#define CRITICAL_SECTION_END    interrupts();
112
+
113
+// On AVR this is in math.h?
114
+#define square(x) ((x)*(x))
115
+
116
+#ifndef strncpy_P
117
+  #define strncpy_P(dest, src, num) strncpy((dest), (src), (num))
118
+#endif
119
+
120
+// Fix bug in pgm_read_ptr
121
+#undef pgm_read_ptr
122
+#define pgm_read_ptr(addr) (*(addr))
123
+
124
+#define RST_POWER_ON   1
125
+#define RST_EXTERNAL   2
126
+#define RST_BROWN_OUT  4
127
+#define RST_WATCHDOG   8
128
+#define RST_JTAG       16
129
+#define RST_SOFTWARE   32
130
+#define RST_BACKUP     64
131
+
132
+// --------------------------------------------------------------------------
133
+// Types
134
+// --------------------------------------------------------------------------
135
+
136
+typedef int8_t pin_t;
137
+
138
+// --------------------------------------------------------------------------
139
+// Public Variables
140
+// --------------------------------------------------------------------------
141
+
142
+/** result of last ADC conversion */
143
+extern uint16_t HAL_adc_result;
144
+
145
+// --------------------------------------------------------------------------
146
+// Public functions
147
+// --------------------------------------------------------------------------
148
+
149
+// Disable interrupts
150
+#define cli() do {  DISABLE_TEMPERATURE_INTERRUPT(); DISABLE_STEPPER_DRIVER_INTERRUPT(); } while(0)
151
+
152
+// Enable interrupts
153
+#define sei() do {  ENABLE_TEMPERATURE_INTERRUPT(); ENABLE_STEPPER_DRIVER_INTERRUPT(); } while(0)
154
+
155
+// Memory related
156
+#define __bss_end __bss_end__
157
+
158
+/** clear reset reason */
159
+void HAL_clear_reset_source (void);
160
+
161
+/** reset reason */
162
+uint8_t HAL_get_reset_source (void);
163
+
164
+void _delay_ms(const int delay);
165
+
166
+/*
167
+extern "C" {
168
+  int freeMemory(void);
169
+}
170
+*/
171
+
172
+extern "C" char* _sbrk(int incr);
173
+/*
174
+static int freeMemory() {
175
+  volatile int top;
176
+  top = (int)((char*)&top - reinterpret_cast<char*>(_sbrk(0)));
177
+  return top;
178
+}
179
+*/
180
+static int freeMemory() {
181
+  volatile char top;
182
+  return &top - reinterpret_cast<char*>(_sbrk(0));
183
+}
184
+
185
+// SPI: Extended functions which take a channel number (hardware SPI only)
186
+/** Write single byte to specified SPI channel */
187
+void spiSend(uint32_t chan, byte b);
188
+/** Write buffer to specified SPI channel */
189
+void spiSend(uint32_t chan, const uint8_t* buf, size_t n);
190
+/** Read single byte from specified SPI channel */
191
+uint8_t spiRec(uint32_t chan);
192
+
193
+
194
+// EEPROM
195
+
196
+/**
197
+ * TODO: Write all this eeprom stuff. Can emulate eeprom in flash as last resort.
198
+ * Wire library should work for i2c eeproms.
199
+ */
200
+void eeprom_write_byte(unsigned char *pos, unsigned char value);
201
+unsigned char eeprom_read_byte(unsigned char *pos);
202
+void eeprom_read_block (void *__dst, const void *__src, size_t __n);
203
+void eeprom_update_block (const void *__src, void *__dst, size_t __n);
204
+
205
+// ADC
206
+
207
+#define HAL_ANALOG_SELECT(pin) pinMode(pin, INPUT)
208
+
209
+inline void HAL_adc_init(void) {}
210
+
211
+#define HAL_START_ADC(pin)  HAL_adc_start_conversion(pin)
212
+#define HAL_READ_ADC        HAL_adc_result
213
+
214
+void HAL_adc_start_conversion(const uint8_t adc_pin);
215
+
216
+uint16_t HAL_adc_get_result(void);
217
+
218
+/* Todo: Confirm none of this is needed.
219
+uint16_t HAL_getAdcReading(uint8_t chan);
220
+
221
+void HAL_startAdcConversion(uint8_t chan);
222
+uint8_t HAL_pinToAdcChannel(int pin);
223
+
224
+uint16_t HAL_getAdcFreerun(uint8_t chan, bool wait_for_conversion = false);
225
+//uint16_t HAL_getAdcSuperSample(uint8_t chan);
226
+
227
+void HAL_enable_AdcFreerun(void);
228
+//void HAL_disable_AdcFreerun(uint8_t chan);
229
+
230
+*/
231
+
232
+#define GET_PIN_MAP_PIN(index) index
233
+#define GET_PIN_MAP_INDEX(pin) pin
234
+#define PARSED_PIN_INDEX(code, dval) parser.intval(code, dval)
235
+
236
+#endif // _HAL_STM32F7_H

+ 52
- 0
Marlin/src/HAL/HAL_STM32F7/HAL_Servo_STM32F7.cpp View File

@@ -0,0 +1,52 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
+ *
5
+ * Based on Sprinter and grbl.
6
+ * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
7
+ * Copyright (C) 2017 Victor Perez
8
+ *
9
+ * This program is free software: you can redistribute it and/or modify
10
+ * it under the terms of the GNU General Public License as published by
11
+ * the Free Software Foundation, either version 3 of the License, or
12
+ * (at your option) any later version.
13
+ *
14
+ * This program is distributed in the hope that it will be useful,
15
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
+ * GNU General Public License for more details.
18
+ *
19
+ * You should have received a copy of the GNU General Public License
20
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
+ *
22
+ */
23
+
24
+#ifdef STM32F7
25
+
26
+#include "../../../src/inc/MarlinConfig.h"
27
+
28
+#if HAS_SERVOS
29
+
30
+#include "HAL_Servo_STM32F7.h"
31
+
32
+int8_t libServo::attach(const int pin) {
33
+  if (this->servoIndex >= MAX_SERVOS) return -1;
34
+  return Servo::attach(pin);
35
+}
36
+
37
+int8_t libServo::attach(const int pin, const int min, const int max) {
38
+  return Servo::attach(pin, min, max);
39
+}
40
+
41
+void libServo::move(const int value) {
42
+  if (this->attach(0) >= 0) {
43
+    this->write(value);
44
+    delay(SERVO_DELAY);
45
+    #if ENABLED(DEACTIVATE_SERVOS_AFTER_MOVE)
46
+      this->detach();
47
+    #endif
48
+  }
49
+}
50
+#endif // HAS_SERVOS
51
+
52
+#endif // STM32F7

+ 41
- 0
Marlin/src/HAL/HAL_STM32F7/HAL_Servo_STM32F7.h View File

@@ -0,0 +1,41 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
+ *
5
+ * Based on Sprinter and grbl.
6
+ * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
7
+ * Copyright (C) 2017 Victor Perez
8
+ *
9
+ * This program is free software: you can redistribute it and/or modify
10
+ * it under the terms of the GNU General Public License as published by
11
+ * the Free Software Foundation, either version 3 of the License, or
12
+ * (at your option) any later version.
13
+ *
14
+ * This program is distributed in the hope that it will be useful,
15
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
+ * GNU General Public License for more details.
18
+ *
19
+ * You should have received a copy of the GNU General Public License
20
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
+ *
22
+ */
23
+
24
+#ifndef HAL_SERVO_STM32F7_H
25
+#define HAL_SERVO_STM32F7_H
26
+
27
+#include <../../libraries/Servo/src/Servo.h>
28
+
29
+// Inherit and expand on the official library
30
+class libServo : public Servo {
31
+public:
32
+    int8_t attach(const int pin);
33
+    int8_t attach(const int pin, const int min, const int max);
34
+    void move(const int value);
35
+private:
36
+    uint16_t min_ticks;
37
+    uint16_t max_ticks;
38
+    uint8_t servoIndex;               // index into the channel data for this servo
39
+};
40
+
41
+#endif // HAL_SERVO_STM32F7_H

+ 167
- 0
Marlin/src/HAL/HAL_STM32F7/HAL_spi_STM32F7.cpp View File

@@ -0,0 +1,167 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
+ *
5
+ * Based on Sprinter and grbl.
6
+ * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
7
+ * Copyright (C) 2017 Victor Perez
8
+ *
9
+ * This program is free software: you can redistribute it and/or modify
10
+ * it under the terms of the GNU General Public License as published by
11
+ * the Free Software Foundation, either version 3 of the License, or
12
+ * (at your option) any later version.
13
+ *
14
+ * This program is distributed in the hope that it will be useful,
15
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
+ * GNU General Public License for more details.
18
+ *
19
+ * You should have received a copy of the GNU General Public License
20
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
+ *
22
+ */
23
+
24
+/**
25
+ * Software SPI functions originally from Arduino Sd2Card Library
26
+ * Copyright (C) 2009 by William Greiman
27
+ */
28
+
29
+/**
30
+ * Adapted to the STM32F7 HAL
31
+ */
32
+
33
+#ifdef STM32F7
34
+
35
+// --------------------------------------------------------------------------
36
+// Includes
37
+// --------------------------------------------------------------------------
38
+
39
+#include "../HAL.h"
40
+//#include "../SPI.h"
41
+#include "SPI.h"
42
+//#include <SPI.h>
43
+#include "pins_arduino.h"
44
+#include "spi_pins.h"
45
+#include "../../core/macros.h"
46
+
47
+
48
+// --------------------------------------------------------------------------
49
+// Public Variables
50
+// --------------------------------------------------------------------------
51
+
52
+static SPISettings spiConfig;
53
+
54
+// --------------------------------------------------------------------------
55
+// Public functions
56
+// --------------------------------------------------------------------------
57
+
58
+#if ENABLED(SOFTWARE_SPI)
59
+  // --------------------------------------------------------------------------
60
+  // Software SPI
61
+  // --------------------------------------------------------------------------
62
+  #error "Software SPI not supported for STM32F7. Use hardware SPI."
63
+
64
+#else
65
+
66
+// --------------------------------------------------------------------------
67
+// Hardware SPI
68
+// --------------------------------------------------------------------------
69
+
70
+/**
71
+ * VGPV SPI speed start and F_CPU/2, by default 72/2 = 36Mhz
72
+ */
73
+
74
+/**
75
+ * @brief  Begin SPI port setup
76
+ *
77
+ * @return Nothing
78
+ *
79
+ * @details Only configures SS pin since libmaple creates and initialize the SPI object
80
+ */
81
+void spiBegin(void) {
82
+  #if !PIN_EXISTS(SS)
83
+    #error SS_PIN not defined!
84
+  #endif
85
+
86
+  SET_OUTPUT(SS_PIN);
87
+  WRITE(SS_PIN, HIGH);
88
+}
89
+
90
+/** Configure SPI for specified SPI speed */
91
+void spiInit(uint8_t spiRate) {
92
+  // Use datarates Marlin uses
93
+  uint32_t clock;
94
+  switch (spiRate) {
95
+  case SPI_FULL_SPEED:    clock = 20000000; break; // 13.9mhz=20000000  6.75mhz=10000000  3.38mhz=5000000  .833mhz=1000000
96
+  case SPI_HALF_SPEED:    clock =  5000000; break;
97
+  case SPI_QUARTER_SPEED: clock =  2500000; break;
98
+  case SPI_EIGHTH_SPEED:  clock =  1250000; break;
99
+  case SPI_SPEED_5:       clock =   625000; break;
100
+  case SPI_SPEED_6:       clock =   300000; break;
101
+  default:
102
+    clock = 4000000; // Default from the SPI libarary
103
+  }
104
+  spiConfig = SPISettings(clock, MSBFIRST, SPI_MODE0);
105
+  SPI.begin();
106
+}
107
+
108
+/**
109
+ * @brief  Receives a single byte from the SPI port.
110
+ *
111
+ * @return Byte received
112
+ *
113
+ * @details
114
+ */
115
+uint8_t spiRec(void) {
116
+  SPI.beginTransaction(spiConfig);
117
+  uint8_t returnByte = SPI.transfer(0xFF);
118
+  SPI.endTransaction();
119
+  return returnByte;
120
+}
121
+
122
+/**
123
+ * @brief  Receives a number of bytes from the SPI port to a buffer
124
+ *
125
+ * @param  buf   Pointer to starting address of buffer to write to.
126
+ * @param  nbyte Number of bytes to receive.
127
+ * @return Nothing
128
+ *
129
+ * @details Uses DMA
130
+ */
131
+void spiRead(uint8_t* buf, uint16_t nbyte) {
132
+  SPI.beginTransaction(spiConfig);
133
+  SPI.dmaTransfer(0, const_cast<uint8_t*>(buf), nbyte);
134
+  SPI.endTransaction();
135
+}
136
+
137
+/**
138
+ * @brief  Sends a single byte on SPI port
139
+ *
140
+ * @param  b Byte to send
141
+ *
142
+ * @details
143
+ */
144
+void spiSend(uint8_t b) {
145
+  SPI.beginTransaction(spiConfig);
146
+  SPI.transfer(b);
147
+  SPI.endTransaction();
148
+}
149
+
150
+/**
151
+ * @brief  Write token and then write from 512 byte buffer to SPI (for SD card)
152
+ *
153
+ * @param  buf   Pointer with buffer start address
154
+ * @return Nothing
155
+ *
156
+ * @details Use DMA
157
+ */
158
+void spiSendBlock(uint8_t token, const uint8_t* buf) {
159
+  SPI.beginTransaction(spiConfig);
160
+  SPI.transfer(token);
161
+  SPI.dmaSend(const_cast<uint8_t*>(buf), 512);
162
+  SPI.endTransaction();
163
+}
164
+
165
+#endif // SOFTWARE_SPI
166
+
167
+#endif // STM32F7

+ 150
- 0
Marlin/src/HAL/HAL_STM32F7/HAL_timers_STM32F7.cpp View File

@@ -0,0 +1,150 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ *
4
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
5
+ * Copyright (c) 2016 Bob Cousins bobcousins42@googlemail.com
6
+ * Copyright (c) 2015-2016 Nico Tonnhofer wurstnase.reprap@gmail.com
7
+ *
8
+ * This program is free software: you can redistribute it and/or modify
9
+ * it under the terms of the GNU General Public License as published by
10
+ * the Free Software Foundation, either version 3 of the License, or
11
+ * (at your option) any later version.
12
+ *
13
+ * This program is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
+ * GNU General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU General Public License
19
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
+ *
21
+ */
22
+
23
+#ifdef STM32F7
24
+
25
+// --------------------------------------------------------------------------
26
+// Includes
27
+// --------------------------------------------------------------------------
28
+
29
+#include "../HAL.h"
30
+
31
+#include "HAL_timers_STM32F7.h"
32
+
33
+// --------------------------------------------------------------------------
34
+// Externals
35
+// --------------------------------------------------------------------------
36
+
37
+// --------------------------------------------------------------------------
38
+// Local defines
39
+// --------------------------------------------------------------------------
40
+
41
+#define NUM_HARDWARE_TIMERS 2
42
+
43
+//#define PRESCALER 1
44
+// --------------------------------------------------------------------------
45
+// Types
46
+// --------------------------------------------------------------------------
47
+
48
+
49
+// --------------------------------------------------------------------------
50
+// Public Variables
51
+// --------------------------------------------------------------------------
52
+
53
+// --------------------------------------------------------------------------
54
+// Private Variables
55
+// --------------------------------------------------------------------------
56
+
57
+tTimerConfig timerConfig[NUM_HARDWARE_TIMERS];
58
+
59
+// --------------------------------------------------------------------------
60
+// Function prototypes
61
+// --------------------------------------------------------------------------
62
+
63
+// --------------------------------------------------------------------------
64
+// Private functions
65
+// --------------------------------------------------------------------------
66
+
67
+// --------------------------------------------------------------------------
68
+// Public functions
69
+// --------------------------------------------------------------------------
70
+
71
+
72
+bool timers_initialised[NUM_HARDWARE_TIMERS] = {false};
73
+
74
+void HAL_timer_start(const uint8_t timer_num, const uint32_t frequency) {
75
+
76
+  if (!timers_initialised[timer_num]) {
77
+    switch (timer_num) {
78
+      case STEP_TIMER_NUM:
79
+      //STEPPER TIMER TIM5 //use a 32bit timer
80
+      __HAL_RCC_TIM5_CLK_ENABLE();
81
+      timerConfig[0].timerdef.Instance               = TIM5;
82
+      timerConfig[0].timerdef.Init.Prescaler         = (STEPPER_TIMER_PRESCALE);
83
+      timerConfig[0].timerdef.Init.CounterMode       = TIM_COUNTERMODE_UP;
84
+      timerConfig[0].timerdef.Init.ClockDivision     = TIM_CLOCKDIVISION_DIV1;
85
+      timerConfig[0].IRQ_Id = TIM5_IRQn;
86
+      timerConfig[0].callback = (uint32_t)TC5_Handler;
87
+      HAL_NVIC_SetPriority(timerConfig[0].IRQ_Id, 1, 0);
88
+      pinMode(STEPPER_ENABLE_PIN,OUTPUT);
89
+      digitalWrite(STEPPER_ENABLE_PIN,LOW);
90
+      break;
91
+    case TEMP_TIMER_NUM:
92
+      //TEMP TIMER TIM7 // any available 16bit Timer (1 already used for PWM)
93
+      __HAL_RCC_TIM7_CLK_ENABLE();
94
+      timerConfig[1].timerdef.Instance               = TIM7;
95
+      timerConfig[1].timerdef.Init.Prescaler         = (TEMP_TIMER_PRESCALE);
96
+      timerConfig[1].timerdef.Init.CounterMode       = TIM_COUNTERMODE_UP;
97
+      timerConfig[1].timerdef.Init.ClockDivision     = TIM_CLOCKDIVISION_DIV1;
98
+      timerConfig[1].IRQ_Id = TIM7_IRQn;
99
+      timerConfig[1].callback = (uint32_t)TC7_Handler;
100
+      HAL_NVIC_SetPriority(timerConfig[1].IRQ_Id, 2, 0);
101
+      break;
102
+    }
103
+    timers_initialised[timer_num] = true;
104
+  }
105
+
106
+  timerConfig[timer_num].timerdef.Init.Period = (((HAL_TIMER_RATE) / timerConfig[timer_num].timerdef.Init.Prescaler) / frequency) - 1;
107
+
108
+  if (HAL_TIM_Base_Init(&timerConfig[timer_num].timerdef) == HAL_OK)
109
+    HAL_TIM_Base_Start_IT(&timerConfig[timer_num].timerdef);
110
+}
111
+
112
+//forward the interrupt
113
+extern "C" void TIM5_IRQHandler() {
114
+  ((void(*)(void))timerConfig[0].callback)();
115
+}
116
+extern "C" void TIM7_IRQHandler() {
117
+  ((void(*)(void))timerConfig[1].callback)();
118
+}
119
+
120
+void HAL_timer_set_count(const uint8_t timer_num, const uint32_t count) {
121
+  __HAL_TIM_SetAutoreload(&timerConfig[timer_num].timerdef, count);
122
+}
123
+
124
+void HAL_timer_set_current_count(const uint8_t timer_num, const uint32_t count) {
125
+  __HAL_TIM_SetAutoreload(&timerConfig[timer_num].timerdef, count);
126
+}
127
+
128
+void HAL_timer_enable_interrupt(const uint8_t timer_num) {
129
+  HAL_NVIC_EnableIRQ(timerConfig[timer_num].IRQ_Id);
130
+}
131
+
132
+void HAL_timer_disable_interrupt(const uint8_t timer_num) {
133
+  HAL_NVIC_DisableIRQ(timerConfig[timer_num].IRQ_Id);
134
+}
135
+
136
+hal_timer_t HAL_timer_get_count(const uint8_t timer_num) {
137
+  return __HAL_TIM_GetAutoreload(&timerConfig[timer_num].timerdef);
138
+}
139
+
140
+uint32_t HAL_timer_get_current_count(const uint8_t timer_num) {
141
+  return __HAL_TIM_GetCounter(&timerConfig[timer_num].timerdef);
142
+}
143
+
144
+void HAL_timer_isr_prologue(const uint8_t timer_num) {
145
+  if (__HAL_TIM_GET_FLAG(&timerConfig[timer_num].timerdef, TIM_FLAG_UPDATE) == SET) {
146
+    __HAL_TIM_CLEAR_FLAG(&timerConfig[timer_num].timerdef, TIM_FLAG_UPDATE);
147
+  }
148
+}
149
+
150
+#endif // STM32F7

+ 105
- 0
Marlin/src/HAL/HAL_STM32F7/HAL_timers_STM32F7.h View File

@@ -0,0 +1,105 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ *
4
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
5
+ * Copyright (c) 2016 Bob Cousins bobcousins42@googlemail.com
6
+ * Copyright (c) 2017 Victor Perez
7
+ *
8
+ * This program is free software: you can redistribute it and/or modify
9
+ * it under the terms of the GNU General Public License as published by
10
+ * the Free Software Foundation, either version 3 of the License, or
11
+ * (at your option) any later version.
12
+ *
13
+ * This program is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
+ * GNU General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU General Public License
19
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
+ *
21
+ */
22
+
23
+#ifndef _HAL_TIMERS_STM32F7_H
24
+#define _HAL_TIMERS_STM32F7_H
25
+
26
+// --------------------------------------------------------------------------
27
+// Includes
28
+// --------------------------------------------------------------------------
29
+
30
+#include <stdint.h>
31
+
32
+// --------------------------------------------------------------------------
33
+// Defines
34
+// --------------------------------------------------------------------------
35
+
36
+#define FORCE_INLINE __attribute__((always_inline)) inline
37
+
38
+#define hal_timer_t uint32_t  // TODO: One is 16-bit, one 32-bit - does this need to be checked?
39
+#define HAL_TIMER_TYPE_MAX 0xFFFF
40
+
41
+#define STEP_TIMER_NUM 0  // index of timer to use for stepper
42
+#define TEMP_TIMER_NUM 1  // index of timer to use for temperature
43
+
44
+#define HAL_TIMER_RATE         (HAL_RCC_GetSysClockFreq() / 2)  // frequency of timer peripherals
45
+#define STEPPER_TIMER_PRESCALE 54            // was 40,prescaler for setting stepper timer, 2Mhz
46
+#define HAL_STEPPER_TIMER_RATE (HAL_TIMER_RATE / STEPPER_TIMER_PRESCALE)   // frequency of stepper timer (HAL_TIMER_RATE / STEPPER_TIMER_PRESCALE)
47
+#define HAL_TICKS_PER_US       ((HAL_STEPPER_TIMER_RATE) / 1000000) // stepper timer ticks per us
48
+
49
+#define PULSE_TIMER_NUM STEP_TIMER_NUM
50
+#define PULSE_TIMER_PRESCALE STEPPER_TIMER_PRESCALE
51
+
52
+#define TEMP_TIMER_PRESCALE     1000 // prescaler for setting Temp timer, 72Khz
53
+#define TEMP_TIMER_FREQUENCY    1000 // temperature interrupt frequency
54
+
55
+#define ENABLE_STEPPER_DRIVER_INTERRUPT() HAL_timer_enable_interrupt(STEP_TIMER_NUM)
56
+#define DISABLE_STEPPER_DRIVER_INTERRUPT() HAL_timer_disable_interrupt(STEP_TIMER_NUM)
57
+
58
+#define ENABLE_TEMPERATURE_INTERRUPT() HAL_timer_enable_interrupt(TEMP_TIMER_NUM)
59
+#define DISABLE_TEMPERATURE_INTERRUPT() HAL_timer_disable_interrupt(TEMP_TIMER_NUM)
60
+
61
+#define HAL_ENABLE_ISRs() do { if (thermalManager.in_temp_isr)DISABLE_TEMPERATURE_INTERRUPT(); else ENABLE_TEMPERATURE_INTERRUPT(); ENABLE_STEPPER_DRIVER_INTERRUPT(); } while(0)
62
+// TODO change this
63
+
64
+
65
+extern void TC5_Handler();
66
+extern void TC7_Handler();
67
+#define HAL_STEP_TIMER_ISR  void TC5_Handler()
68
+#define HAL_TEMP_TIMER_ISR  void TC7_Handler()
69
+
70
+// --------------------------------------------------------------------------
71
+// Types
72
+// --------------------------------------------------------------------------
73
+
74
+typedef struct {
75
+  TIM_HandleTypeDef timerdef;
76
+  IRQn_Type   IRQ_Id;
77
+  uint32_t callback;
78
+} tTimerConfig;
79
+
80
+// --------------------------------------------------------------------------
81
+// Public Variables
82
+// --------------------------------------------------------------------------
83
+
84
+//extern const tTimerConfig timerConfig[];
85
+
86
+// --------------------------------------------------------------------------
87
+// Public functions
88
+// --------------------------------------------------------------------------
89
+
90
+void HAL_timer_start(const uint8_t timer_num, const uint32_t frequency);
91
+void HAL_timer_enable_interrupt(const uint8_t timer_num);
92
+void HAL_timer_disable_interrupt(const uint8_t timer_num);
93
+
94
+void HAL_timer_set_count(const uint8_t timer_num, const uint32_t count);
95
+hal_timer_t HAL_timer_get_count(const uint8_t timer_num);
96
+uint32_t HAL_timer_get_current_count(const uint8_t timer_num);
97
+
98
+void HAL_timer_set_current_count(const uint8_t timer_num, const uint32_t count); // New
99
+/*FORCE_INLINE static void HAL_timer_set_current_count(const uint8_t timer_num, const hal_timer_t count) {
100
+  // To do ??
101
+}*/
102
+
103
+void HAL_timer_isr_prologue(const uint8_t timer_num);
104
+
105
+#endif // _HAL_TIMERS_STM32F7_H

+ 28
- 0
Marlin/src/HAL/HAL_STM32F7/README.md View File

@@ -0,0 +1,28 @@
1
+# This HAL is for the STM32F765 board "The Borg" used with STM32Generic Arduino core by danieleff.
2
+
3
+# Original core is located at: 
4
+
5
+https://github.com/danieleff/STM32GENERIC
6
+
7
+but i have not committed the changes needed for the Borg there yet, so please use:
8
+
9
+https://github.com/Spawn32/STM32GENERIC 
10
+
11
+Unzip it into [Arduino]/hardware folder
12
+
13
+
14
+Download the latest GNU ARM Embedded Toolchain: 
15
+
16
+https://developer.arm.com/open-source/gnu-toolchain/gnu-rm/downloads
17
+
18
+(The one in Arduino dosen't support STM32F7).
19
+
20
+Change compiler.path in platform.txt to point to that you downloaded.
21
+
22
+# This HAL is in development.
23
+# Currently only tested on "The Borg".
24
+
25
+You will also need the latest Arduino 1.9.0-beta or newer.
26
+
27
+This HAL is a modified version of Chris Barr's Picoprint STM32F4 HAL, so shouldn't be to hard to get it to work on a F4.
28
+

+ 66
- 0
Marlin/src/HAL/HAL_STM32F7/SanityCheck_STM32F7.h View File

@@ -0,0 +1,66 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ * Copyright (C) 2016, 2017 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
+ *
5
+ * Based on Sprinter and grbl.
6
+ * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
7
+ *
8
+ * This program is free software: you can redistribute it and/or modify
9
+ * it under the terms of the GNU General Public License as published by
10
+ * the Free Software Foundation, either version 3 of the License, or
11
+ * (at your option) any later version.
12
+ *
13
+ * This program is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
+ * GNU General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU General Public License
19
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
+ *
21
+ */
22
+
23
+/**
24
+ * Test Re-ARM specific configuration values for errors at compile-time.
25
+ */
26
+#if ENABLED(SPINDLE_LASER_ENABLE)
27
+  #if !PIN_EXISTS(SPINDLE_LASER_ENABLE)
28
+    #error "SPINDLE_LASER_ENABLE requires SPINDLE_LASER_ENABLE_PIN."
29
+  #elif SPINDLE_DIR_CHANGE && !PIN_EXISTS(SPINDLE_DIR)
30
+    #error "SPINDLE_DIR_PIN not defined."
31
+  #elif ENABLED(SPINDLE_LASER_PWM) && PIN_EXISTS(SPINDLE_LASER_PWM)
32
+    #if !PWM_PIN(SPINDLE_LASER_PWM_PIN)
33
+      #error "SPINDLE_LASER_PWM_PIN not assigned to a PWM pin."
34
+    #elif !(SPINDLE_LASER_PWM_PIN == 4 || SPINDLE_LASER_PWM_PIN == 6 || SPINDLE_LASER_PWM_PIN == 11)
35
+      #error "SPINDLE_LASER_PWM_PIN must use SERVO0, SERVO1 or SERVO3 connector"
36
+    #elif SPINDLE_LASER_POWERUP_DELAY < 1
37
+      #error "SPINDLE_LASER_POWERUP_DELAY must be greater than 0."
38
+    #elif SPINDLE_LASER_POWERDOWN_DELAY < 1
39
+      #error "SPINDLE_LASER_POWERDOWN_DELAY must be greater than 0."
40
+    #elif !defined(SPINDLE_LASER_PWM_INVERT)
41
+      #error "SPINDLE_LASER_PWM_INVERT missing."
42
+    #elif !defined(SPEED_POWER_SLOPE) || !defined(SPEED_POWER_INTERCEPT) || !defined(SPEED_POWER_MIN) || !defined(SPEED_POWER_MAX)
43
+      #error "SPINDLE_LASER_PWM equation constant(s) missing."
44
+    #elif PIN_EXISTS(CASE_LIGHT) && SPINDLE_LASER_PWM_PIN == CASE_LIGHT_PIN
45
+      #error "SPINDLE_LASER_PWM_PIN is used by CASE_LIGHT_PIN."
46
+    #elif PIN_EXISTS(E0_AUTO_FAN) && SPINDLE_LASER_PWM_PIN == E0_AUTO_FAN_PIN
47
+      #error "SPINDLE_LASER_PWM_PIN is used by E0_AUTO_FAN_PIN."
48
+    #elif PIN_EXISTS(E1_AUTO_FAN) && SPINDLE_LASER_PWM_PIN == E1_AUTO_FAN_PIN
49
+      #error "SPINDLE_LASER_PWM_PIN is used by E1_AUTO_FAN_PIN."
50
+    #elif PIN_EXISTS(E2_AUTO_FAN) && SPINDLE_LASER_PWM_PIN == E2_AUTO_FAN_PIN
51
+      #error "SPINDLE_LASER_PWM_PIN is used by E2_AUTO_FAN_PIN."
52
+    #elif PIN_EXISTS(E3_AUTO_FAN) && SPINDLE_LASER_PWM_PIN == E3_AUTO_FAN_PIN
53
+      #error "SPINDLE_LASER_PWM_PIN is used by E3_AUTO_FAN_PIN."
54
+    #elif PIN_EXISTS(E4_AUTO_FAN) && SPINDLE_LASER_PWM_PIN == E4_AUTO_FAN_PIN
55
+      #error "SPINDLE_LASER_PWM_PIN is used by E4_AUTO_FAN_PIN."
56
+    #elif PIN_EXISTS(FAN) && SPINDLE_LASER_PWM_PIN == FAN_PIN
57
+      #error "SPINDLE_LASER_PWM_PIN is used FAN_PIN."
58
+    #elif PIN_EXISTS(FAN1) && SPINDLE_LASER_PWM_PIN == FAN1_PIN
59
+      #error "SPINDLE_LASER_PWM_PIN is used FAN1_PIN."
60
+    #elif PIN_EXISTS(FAN2) && SPINDLE_LASER_PWM_PIN == FAN2_PIN
61
+      #error "SPINDLE_LASER_PWM_PIN is used FAN2_PIN."
62
+    #elif PIN_EXISTS(CONTROLLERFAN) && SPINDLE_LASER_PWM_PIN == CONTROLLERFAN_PIN
63
+      #error "SPINDLE_LASER_PWM_PIN is used by CONTROLLERFAN_PIN."
64
+    #endif
65
+  #endif
66
+#endif // SPINDLE_LASER_ENABLE

+ 931
- 0
Marlin/src/HAL/HAL_STM32F7/TMC2660.cpp View File

@@ -0,0 +1,931 @@
1
+/**
2
+ * TMC26XStepper.cpp - - TMC26X Stepper library for Wiring/Arduino
3
+ * 
4
+ * based on the stepper library by Tom Igoe, et. al.
5
+ *
6
+ * Copyright (c) 2011, Interactive Matter, Marcus Nowotny
7
+ * 
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ * 
15
+ * The above copyright notice and this permission notice shall be included in
16
+ * all copies or substantial portions of the Software.
17
+ * 
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
+ * THE SOFTWARE.
25
+ *
26
+ */
27
+
28
+//#include "Arduino.h"
29
+
30
+#ifdef STM32F7
31
+
32
+#include <stdbool.h>
33
+#include <SPI.h>
34
+#include "TMC2660.h"
35
+
36
+#include "../../HAL/HAL_STM32F7/HAL_STM32F7.h"
37
+#include "../../core/serial.h"
38
+#include "../../inc/MarlinConfig.h"
39
+#include "../../Marlin.h"
40
+#include "../../module/stepper_indirection.h"
41
+#include "../../module/printcounter.h"
42
+#include "../../libs/duration_t.h"
43
+#include "../../libs/hex_print_routines.h"
44
+
45
+
46
+//some default values used in initialization
47
+#define DEFAULT_MICROSTEPPING_VALUE 32
48
+
49
+//TMC26X register definitions
50
+#define DRIVER_CONTROL_REGISTER 0x0ul
51
+#define CHOPPER_CONFIG_REGISTER 0x80000ul
52
+#define COOL_STEP_REGISTER  0xA0000ul
53
+#define STALL_GUARD2_LOAD_MEASURE_REGISTER 0xC0000ul
54
+#define DRIVER_CONFIG_REGISTER 0xE0000ul
55
+
56
+#define REGISTER_BIT_PATTERN 0xFFFFFul
57
+
58
+//definitions for the driver control register
59
+#define MICROSTEPPING_PATTERN 0xFul
60
+#define STEP_INTERPOLATION 0x200ul
61
+#define DOUBLE_EDGE_STEP 0x100ul
62
+#define VSENSE 0x40ul
63
+#define READ_MICROSTEP_POSTION 0x0ul
64
+#define READ_STALL_GUARD_READING 0x10ul
65
+#define READ_STALL_GUARD_AND_COOL_STEP 0x20ul
66
+#define READ_SELECTION_PATTERN 0x30ul
67
+
68
+//definitions for the chopper config register
69
+#define CHOPPER_MODE_STANDARD 0x0ul
70
+#define CHOPPER_MODE_T_OFF_FAST_DECAY 0x4000ul
71
+#define T_OFF_PATTERN 0xful
72
+#define RANDOM_TOFF_TIME 0x2000ul
73
+#define BLANK_TIMING_PATTERN 0x18000ul
74
+#define BLANK_TIMING_SHIFT 15
75
+#define HYSTERESIS_DECREMENT_PATTERN 0x1800ul
76
+#define HYSTERESIS_DECREMENT_SHIFT 11
77
+#define HYSTERESIS_LOW_VALUE_PATTERN 0x780ul
78
+#define HYSTERESIS_LOW_SHIFT 7
79
+#define HYSTERESIS_START_VALUE_PATTERN 0x78ul
80
+#define HYSTERESIS_START_VALUE_SHIFT 4
81
+#define T_OFF_TIMING_PATERN 0xFul
82
+
83
+//definitions for cool step register
84
+#define MINIMUM_CURRENT_FOURTH 0x8000ul
85
+#define CURRENT_DOWN_STEP_SPEED_PATTERN 0x6000ul
86
+#define SE_MAX_PATTERN 0xF00ul
87
+#define SE_CURRENT_STEP_WIDTH_PATTERN 0x60ul
88
+#define SE_MIN_PATTERN 0xful
89
+
90
+//definitions for stall guard2 current register
91
+#define STALL_GUARD_FILTER_ENABLED 0x10000ul
92
+#define STALL_GUARD_TRESHHOLD_VALUE_PATTERN 0x17F00ul
93
+#define CURRENT_SCALING_PATTERN 0x1Ful
94
+#define STALL_GUARD_CONFIG_PATTERN 0x17F00ul
95
+#define STALL_GUARD_VALUE_PATTERN 0x7F00ul
96
+
97
+//definitions for the input from the TCM260
98
+#define STATUS_STALL_GUARD_STATUS 0x1ul
99
+#define STATUS_OVER_TEMPERATURE_SHUTDOWN 0x2ul
100
+#define STATUS_OVER_TEMPERATURE_WARNING 0x4ul
101
+#define STATUS_SHORT_TO_GROUND_A 0x8ul
102
+#define STATUS_SHORT_TO_GROUND_B 0x10ul
103
+#define STATUS_OPEN_LOAD_A 0x20ul
104
+#define STATUS_OPEN_LOAD_B 0x40ul
105
+#define STATUS_STAND_STILL 0x80ul
106
+#define READOUT_VALUE_PATTERN 0xFFC00ul
107
+
108
+#define CPU_32_BIT
109
+
110
+//default values
111
+#define INITIAL_MICROSTEPPING 0x3ul //32th microstepping
112
+
113
+SPIClass SPI_6(SPI6, SPI6_MOSI_PIN, SPI6_MISO_PIN, SPI6_SCK_PIN);
114
+
115
+#define STEPPER_SPI SPI_6
116
+
117
+//debuging output
118
+
119
+//#define TMC_DEBUG1
120
+
121
+unsigned char current_scaling = 0;
122
+
123
+/**
124
+ * Constructor
125
+ * number_of_steps - the steps per rotation
126
+ * cs_pin - the SPI client select pin
127
+ * dir_pin - the pin where the direction pin is connected
128
+ * step_pin - the pin where the step pin is connected
129
+ */
130
+TMC26XStepper::TMC26XStepper(int number_of_steps, int cs_pin, int dir_pin, int step_pin, unsigned int current, unsigned int resistor) {
131
+  // We are not started yet
132
+  started = false;
133
+
134
+  // By default cool step is not enabled
135
+  cool_step_enabled = false;
136
+
137
+  // Save the pins for later use
138
+  this->cs_pin = cs_pin;
139
+  this->dir_pin = dir_pin;
140
+  this->step_pin = step_pin;
141
+
142
+  // Store the current sense resistor value for later use
143
+  this->resistor = resistor;
144
+
145
+  // Initizalize our status values
146
+  this->steps_left = 0;
147
+  this->direction = 0;
148
+
149
+  // Initialize register values
150
+  driver_control_register_value = DRIVER_CONTROL_REGISTER | INITIAL_MICROSTEPPING;
151
+  chopper_config_register = CHOPPER_CONFIG_REGISTER;
152
+
153
+  // Setting the default register values
154
+  driver_control_register_value = DRIVER_CONTROL_REGISTER|INITIAL_MICROSTEPPING;
155
+  microsteps = _BV(INITIAL_MICROSTEPPING);
156
+  chopper_config_register = CHOPPER_CONFIG_REGISTER;
157
+  cool_step_register_value = COOL_STEP_REGISTER;
158
+  stall_guard2_current_register_value = STALL_GUARD2_LOAD_MEASURE_REGISTER;
159
+  driver_configuration_register_value = DRIVER_CONFIG_REGISTER | READ_STALL_GUARD_READING;
160
+
161
+  // Set the current
162
+  setCurrent(current);
163
+  // Set to a conservative start value
164
+  setConstantOffTimeChopper(7, 54, 13,12,1);
165
+  // Set a nice microstepping value
166
+  setMicrosteps(DEFAULT_MICROSTEPPING_VALUE);
167
+  // Save the number of steps
168
+  this->number_of_steps = number_of_steps;
169
+}
170
+
171
+
172
+/**
173
+ * start & configure the stepper driver
174
+ * just must be called.
175
+ */
176
+void TMC26XStepper::start() {
177
+
178
+  #ifdef TMC_DEBUG1
179
+    SERIAL_ECHOPGM("\n  TMC26X stepper library  \n");
180
+    SERIAL_ECHOPAIR("\n  CS pin: ", cs_pin);
181
+    SERIAL_ECHOPAIR("\n  DIR pin: ", dir_pin);
182
+    SERIAL_ECHOPAIR("\n  STEP pin: ", step_pin);
183
+    SERIAL_PRINTF("\n  current scaling: %d", current_scaling);
184
+    SERIAL_PRINTF("\n  Resistor: %d", resistor);
185
+    //SERIAL_PRINTF("\n  current: %d", current);
186
+    SERIAL_ECHOPAIR("\n  Microstepping: ", microsteps);
187
+  #endif
188
+
189
+  //set the pins as output & its initial value
190
+  pinMode(step_pin, OUTPUT);
191
+  pinMode(dir_pin, OUTPUT);
192
+  pinMode(cs_pin, OUTPUT);
193
+  //pinMode(STEPPER_ENABLE_PIN, OUTPUT);
194
+  digitalWrite(step_pin, LOW);
195
+  digitalWrite(dir_pin, LOW);
196
+  digitalWrite(cs_pin, HIGH);
197
+
198
+  STEPPER_SPI.begin();
199
+  STEPPER_SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE3));
200
+
201
+  //set the initial values
202
+  send262(driver_control_register_value);
203
+  send262(chopper_config_register);
204
+  send262(cool_step_register_value);
205
+  send262(stall_guard2_current_register_value);
206
+  send262(driver_configuration_register_value);
207
+
208
+  //save that we are in running mode
209
+  started = true;
210
+}
211
+
212
+/**
213
+ * Mark the driver as unstarted to be able to start it again
214
+ */
215
+void TMC26XStepper::un_start() { started = false; }
216
+
217
+
218
+/**
219
+ * Sets the speed in revs per minute
220
+ */
221
+void TMC26XStepper::setSpeed(unsigned int whatSpeed) {
222
+  this->speed = whatSpeed;
223
+  this->step_delay = 60UL * sq(1000UL) / ((unsigned long)this->number_of_steps * (unsigned long)whatSpeed * (unsigned long)this->microsteps);
224
+  #ifdef TMC_DEBUG0 // crashes
225
+    //SERIAL_PRINTF("Step delay in micros: ");
226
+    SERIAL_ECHOPAIR("\nStep delay in micros: ", this->step_delay);
227
+  #endif
228
+  // Update the next step time
229
+  this->next_step_time = this->last_step_time + this->step_delay;
230
+}
231
+
232
+unsigned int TMC26XStepper::getSpeed(void) { return this->speed; }
233
+
234
+/**
235
+ * Moves the motor steps_to_move steps.
236
+ * Negative indicates the reverse direction.
237
+ */
238
+char TMC26XStepper::step(int steps_to_move) {
239
+  if (this->steps_left == 0) {
240
+    this->steps_left = abs(steps_to_move);  // how many steps to take
241
+
242
+    // determine direction based on whether steps_to_move is + or -:
243
+    if (steps_to_move > 0)
244
+      this->direction = 1;
245
+    else if (steps_to_move < 0)
246
+      this->direction = 0;
247
+    return 0;
248
+  }
249
+  return -1;
250
+}
251
+
252
+char TMC26XStepper::move(void) {
253
+  // decrement the number of steps, moving one step each time:
254
+  if (this->steps_left > 0) {
255
+    unsigned long time = micros();
256
+    // move only if the appropriate delay has passed:
257
+
258
+    // rem if (time >= this->next_step_time) {
259
+
260
+    if (abs(time - this->last_step_time) > this->step_delay) {
261
+      // increment or decrement the step number,
262
+      // depending on direction:
263
+      if (this->direction == 1)
264
+        digitalWrite(step_pin, HIGH);
265
+      else {
266
+        digitalWrite(dir_pin, HIGH);
267
+        digitalWrite(step_pin, HIGH);
268
+      }
269
+      // get the timeStamp of when you stepped:
270
+      this->last_step_time = time;
271
+      this->next_step_time = time + this->step_delay;
272
+      // decrement the steps left:
273
+      steps_left--;
274
+      //disable the step & dir pins
275
+      digitalWrite(step_pin, LOW);
276
+      digitalWrite(dir_pin, LOW);
277
+    }
278
+    return -1;
279
+  }
280
+  return 0;
281
+}
282
+
283
+char TMC26XStepper::isMoving(void) { return this->steps_left > 0; }
284
+
285
+unsigned int TMC26XStepper::getStepsLeft(void) { return this->steps_left; }
286
+
287
+char TMC26XStepper::stop(void) {
288
+  //note to self if the motor is currently moving
289
+  char state = isMoving();
290
+  //stop the motor
291
+  this->steps_left = 0;
292
+  this->direction = 0;
293
+  //return if it was moving
294
+  return state;
295
+}
296
+
297
+void TMC26XStepper::setCurrent(unsigned int current) {
298
+  unsigned char current_scaling = 0;
299
+  //calculate the current scaling from the max current setting (in mA)
300
+  double mASetting = (double)current,
301
+         resistor_value = (double)this->resistor;
302
+  // remove vsense flag
303
+  this->driver_configuration_register_value &= ~(VSENSE);
304
+  // Derived from I = (cs + 1) / 32 * (Vsense / Rsense)
305
+  //   leading to cs = 32 * R * I / V (with V = 0,31V oder 0,165V and I = 1000 * current)
306
+  // with Rsense = 0,15
307
+  // for vsense = 0,310V (VSENSE not set)
308
+  // or vsense = 0,165V (VSENSE set)
309
+  current_scaling = (byte)((resistor_value * mASetting * 32.0 / (0.31 * sq(1000.0))) - 0.5); //theoretically - 1.0 for better rounding it is 0.5
310
+
311
+  // Check if the current scalingis too low
312
+  if (current_scaling < 16) {
313
+    // Set the csense bit to get a use half the sense voltage (to support lower motor currents)
314
+    this->driver_configuration_register_value |= VSENSE;
315
+    // and recalculate the current setting
316
+    current_scaling = (byte)((resistor_value * mASetting * 32.0 / (0.165 * sq(1000.0))) - 0.5); //theoretically - 1.0 for better rounding it is 0.5
317
+    #ifdef TMC_DEBUG0 // crashes
318
+        //SERIAL_PRINTF("CS (Vsense=1): ");
319
+        SERIAL_ECHOPAIR("\nCS (Vsense=1): ",current_scaling);
320
+      } else {
321
+        //SERIAL_PRINTF("CS: ");
322
+        SERIAL_ECHOPAIR("\nCS: ", current_scaling);
323
+    #endif
324
+  }
325
+
326
+  // do some sanity checks
327
+  NOMORE(current_scaling, 31);
328
+
329
+  // delete the old value
330
+  stall_guard2_current_register_value &= ~(CURRENT_SCALING_PATTERN);
331
+  // set the new current scaling
332
+  stall_guard2_current_register_value |= current_scaling;
333
+  // if started we directly send it to the motor
334
+  if (started) {
335
+    send262(driver_configuration_register_value);
336
+    send262(stall_guard2_current_register_value);
337
+  }
338
+}
339
+
340
+unsigned int TMC26XStepper::getCurrent(void) {
341
+  // Calculate the current according to the datasheet to be on the safe side.
342
+  // This is not the fastest but the most accurate and illustrative way.
343
+  double result = (double)(stall_guard2_current_register_value & CURRENT_SCALING_PATTERN),
344
+         resistor_value = (double)this->resistor,
345
+         voltage = (driver_configuration_register_value & VSENSE) ? 0.165 : 0.31;
346
+  result = (result + 1.0) / 32.0 * voltage / resistor_value * sq(1000.0);
347
+  return (unsigned int)result;
348
+}
349
+
350
+void TMC26XStepper::setStallGuardThreshold(char stall_guard_threshold, char stall_guard_filter_enabled) {
351
+  // We just have 5 bits
352
+  LIMIT(stall_guard_threshold, -64, 63);
353
+
354
+  // Add trim down to 7 bits
355
+  stall_guard_threshold &= 0x7F;
356
+  // Delete old stall guard settings
357
+  stall_guard2_current_register_value &= ~(STALL_GUARD_CONFIG_PATTERN);
358
+  if (stall_guard_filter_enabled)
359
+    stall_guard2_current_register_value |= STALL_GUARD_FILTER_ENABLED;
360
+
361
+  // Set the new stall guard threshold
362
+  stall_guard2_current_register_value |= (((unsigned long)stall_guard_threshold << 8) & STALL_GUARD_CONFIG_PATTERN);
363
+  // If started we directly send it to the motor
364
+  if (started) send262(stall_guard2_current_register_value);
365
+}
366
+
367
+char TMC26XStepper::getStallGuardThreshold(void) {
368
+  unsigned long stall_guard_threshold = stall_guard2_current_register_value & STALL_GUARD_VALUE_PATTERN;
369
+  //shift it down to bit 0
370
+  stall_guard_threshold >>= 8;
371
+  //convert the value to an int to correctly handle the negative numbers
372
+  char result = stall_guard_threshold;
373
+  //check if it is negative and fill it up with leading 1 for proper negative number representation
374
+  //rem if (result & _BV(6)) {
375
+
376
+  if (TEST(result, 6)) result |= 0xC0;
377
+  return result;
378
+}
379
+
380
+char TMC26XStepper::getStallGuardFilter(void) {
381
+  if (stall_guard2_current_register_value & STALL_GUARD_FILTER_ENABLED)
382
+    return -1;
383
+  return 0;
384
+}
385
+
386
+/**
387
+ * Set the number of microsteps per step.
388
+ * 0,2,4,8,16,32,64,128,256 is supported
389
+ * any value in between will be mapped to the next smaller value
390
+ * 0 and 1 set the motor in full step mode
391
+ */
392
+void TMC26XStepper::setMicrosteps(int number_of_steps) {
393
+  long setting_pattern;
394
+  //poor mans log
395
+  if (number_of_steps >= 256) {
396
+    setting_pattern = 0;
397
+    microsteps = 256;
398
+  }
399
+  else if (number_of_steps >= 128) {
400
+    setting_pattern = 1;
401
+    microsteps = 128;
402
+  }
403
+  else if (number_of_steps >= 64) {
404
+    setting_pattern = 2;
405
+    microsteps = 64;
406
+  }
407
+  else if (number_of_steps >= 32) {
408
+    setting_pattern = 3;
409
+    microsteps = 32;
410
+  }
411
+  else if (number_of_steps >= 16) {
412
+    setting_pattern = 4;
413
+    microsteps = 16;
414
+  }
415
+  else if (number_of_steps >= 8) {
416
+    setting_pattern = 5;
417
+    microsteps = 8;
418
+  }
419
+  else if (number_of_steps >= 4) {
420
+    setting_pattern = 6;
421
+    microsteps = 4;
422
+  }
423
+  else if (number_of_steps >= 2) {
424
+    setting_pattern = 7;
425
+    microsteps = 2;
426
+    //1 and 0 lead to full step
427
+  }
428
+  else if (number_of_steps <= 1) {
429
+    setting_pattern = 8;
430
+    microsteps = 1;
431
+  }
432
+  #ifdef TMC_DEBUG0 // crashes
433
+    //SERIAL_PRINTF("Microstepping: ");
434
+    SERIAL_ECHOPAIR("\n Microstepping: ", microsteps);
435
+  #endif
436
+  // Delete the old value
437
+  this->driver_control_register_value &= 0xFFFF0UL;
438
+  // Set the new value
439
+  this->driver_control_register_value |= setting_pattern;
440
+
441
+  // If started we directly send it to the motor
442
+  if (started) send262(driver_control_register_value);
443
+
444
+  // Recalculate the stepping delay by simply setting the speed again
445
+  this->setSpeed(this->speed);
446
+}
447
+
448
+/**
449
+ * returns the effective number of microsteps at the moment
450
+ */
451
+int TMC26XStepper::getMicrosteps(void) { return microsteps }
452
+
453
+/**
454
+ * constant_off_time: The off time setting controls the minimum chopper frequency.
455
+ * For most applications an off time within the range of 5μs to 20μs will fit.
456
+ *    2...15: off time setting
457
+ *
458
+ * blank_time: Selects the comparator blank time. This time needs to safely cover the switching event and the
459
+ * duration of the ringing on the sense resistor. For
460
+ *    0: min. setting 3: max. setting
461
+ *
462
+ * fast_decay_time_setting: Fast decay time setting. With CHM=1, these bits control the portion of fast decay for each chopper cycle.
463
+ *    0: slow decay only
464
+ *    1...15: duration of fast decay phase
465
+ *
466
+ * sine_wave_offset: Sine wave offset. With CHM=1, these bits control the sine wave offset.
467
+ * A positive offset corrects for zero crossing error.
468
+ *    -3..-1: negative offset 0: no offset 1...12: positive offset
469
+ *
470
+ * use_current_comparator: Selects usage of the current comparator for termination of the fast decay cycle.
471
+ * If current comparator is enabled, it terminates the fast decay cycle in case the current
472
+ * reaches a higher negative value than the actual positive value.
473
+ *    1: enable comparator termination of fast decay cycle
474
+ *    0: end by time only
475
+ */
476
+void TMC26XStepper::setConstantOffTimeChopper(char constant_off_time, char blank_time, char fast_decay_time_setting, char sine_wave_offset, unsigned char use_current_comparator) {
477
+  // Perform some sanity checks
478
+  LIMIT(constant_off_time, 2, 15);
479
+
480
+  // Save the constant off time
481
+  this->constant_off_time = constant_off_time;
482
+
483
+  // Calculate the value acc to the clock cycles
484
+  const char blank_value = blank_time >= 54 ? 3 :
485
+                           blank_time >= 36 ? 2 :
486
+                           blank_time >= 24 ? 1 : 0;
487
+
488
+  LIMIT(fast_decay_time_setting, 0, 15);
489
+  LIMIT(sine_wave_offset, -3, 12);
490
+
491
+  // Shift the sine_wave_offset
492
+  sine_wave_offset += 3;
493
+
494
+  // Calculate the register setting
495
+  // First of all delete all the values for this
496
+  chopper_config_register &= ~(_BV(12) | BLANK_TIMING_PATTERN | HYSTERESIS_DECREMENT_PATTERN | HYSTERESIS_LOW_VALUE_PATTERN | HYSTERESIS_START_VALUE_PATTERN | T_OFF_TIMING_PATERN);
497
+  // Set the constant off pattern
498
+  chopper_config_register |= CHOPPER_MODE_T_OFF_FAST_DECAY;
499
+  // Set the blank timing value
500
+  chopper_config_register |= ((unsigned long)blank_value) << BLANK_TIMING_SHIFT;
501
+  // Setting the constant off time
502
+  chopper_config_register |= constant_off_time;
503
+  // Set the fast decay time
504
+  // Set msb
505
+  chopper_config_register |= (((unsigned long)(fast_decay_time_setting & 0x8)) << HYSTERESIS_DECREMENT_SHIFT);
506
+  // Other bits
507
+  chopper_config_register |= (((unsigned long)(fast_decay_time_setting & 0x7)) << HYSTERESIS_START_VALUE_SHIFT);
508
+  // Set the sine wave offset
509
+  chopper_config_register |= (unsigned long)sine_wave_offset << HYSTERESIS_LOW_SHIFT;
510
+  // Using the current comparator?
511
+  if (!use_current_comparator)
512
+    chopper_config_register |= _BV(12);
513
+
514
+  // If started we directly send it to the motor
515
+  if (started) {
516
+    // rem send262(driver_control_register_value);
517
+    send262(chopper_config_register);
518
+  }
519
+}
520
+
521
+/**
522
+ * constant_off_time: The off time setting controls the minimum chopper frequency.
523
+ * For most applications an off time within the range of 5μs to 20μs will fit.
524
+ *    2...15: off time setting
525
+ *
526
+ * blank_time: Selects the comparator blank time. This time needs to safely cover the switching event and the
527
+ * duration of the ringing on the sense resistor. For
528
+ *    0: min. setting 3: max. setting
529
+ *
530
+ * hysteresis_start: Hysteresis start setting. Please remark, that this value is an offset to the hysteresis end value HEND.
531
+ *    1...8
532
+ *
533
+ * hysteresis_end: Hysteresis end setting. Sets the hysteresis end value after a number of decrements. Decrement interval time is controlled by HDEC.
534
+ * The sum HSTRT+HEND must be <16. At a current setting CS of max. 30 (amplitude reduced to 240), the sum is not limited.
535
+ *    -3..-1: negative HEND 0: zero HEND 1...12: positive HEND
536
+ *
537
+ * hysteresis_decrement: Hysteresis decrement setting. This setting determines the slope of the hysteresis during on time and during fast decay time.
538
+ *    0: fast decrement 3: very slow decrement
539
+ */
540
+
541
+void TMC26XStepper::setSpreadCycleChopper(char constant_off_time, char blank_time, char hysteresis_start, char hysteresis_end, char hysteresis_decrement) {
542
+  // Perform some sanity checks
543
+  LIMIT(constant_off_time, 2, 15);
544
+
545
+  // Save the constant off time
546
+  this->constant_off_time = constant_off_time;
547
+
548
+  // Calculate the value acc to the clock cycles
549
+  const char blank_value = blank_time >= 54 ? 3 :
550
+                           blank_time >= 36 ? 2 :
551
+                           blank_time >= 24 ? 1 : 0;
552
+
553
+  LIMIT(hysteresis_start, 1, 8);
554
+  hysteresis_start--;
555
+
556
+  LIMIT(hysteresis_start, -3, 12);
557
+
558
+  // Shift the hysteresis_end
559
+  hysteresis_end += 3;
560
+
561
+  LIMIT(hysteresis_decrement, 0, 3);
562
+
563
+  //first of all delete all the values for this
564
+  chopper_config_register &= ~(CHOPPER_MODE_T_OFF_FAST_DECAY | BLANK_TIMING_PATTERN | HYSTERESIS_DECREMENT_PATTERN | HYSTERESIS_LOW_VALUE_PATTERN | HYSTERESIS_START_VALUE_PATTERN | T_OFF_TIMING_PATERN);
565
+
566
+  //set the blank timing value
567
+  chopper_config_register |= ((unsigned long)blank_value) << BLANK_TIMING_SHIFT;
568
+  //setting the constant off time
569
+  chopper_config_register |= constant_off_time;
570
+  //set the hysteresis_start
571
+  chopper_config_register |= ((unsigned long)hysteresis_start) << HYSTERESIS_START_VALUE_SHIFT;
572
+  //set the hysteresis end
573
+  chopper_config_register |= ((unsigned long)hysteresis_end) << HYSTERESIS_LOW_SHIFT;
574
+  //set the hystereis decrement
575
+  chopper_config_register |= ((unsigned long)blank_value) << BLANK_TIMING_SHIFT;
576
+  //if started we directly send it to the motor
577
+  if (started) {
578
+    //rem send262(driver_control_register_value);
579
+    send262(chopper_config_register);
580
+  }
581
+}
582
+
583
+/**
584
+ * In a constant off time chopper scheme both coil choppers run freely, i.e. are not synchronized.
585
+ * The frequency of each chopper mainly depends on the coil current and the position dependant motor coil inductivity, thus it depends on the microstep position.
586
+ * With some motors a slightly audible beat can occur between the chopper frequencies, especially when they are near to each other. This typically occurs at a
587
+ * few microstep positions within each quarter wave. This effect normally is not audible when compared to mechanical noise generated by ball bearings, etc.
588
+ * Further factors which can cause a similar effect are a poor layout of sense resistor GND connection.
589
+ * Hint: A common factor, which can cause motor noise, is a bad PCB layout causing coupling of both sense resistor voltages
590
+ * (please refer to sense resistor layout hint in chapter 8.1).
591
+ * In order to minimize the effect of a beat between both chopper frequencies, an internal random generator is provided.
592
+ * It modulates the slow decay time setting when switched on by the RNDTF bit. The RNDTF feature further spreads the chopper spectrum,
593
+ * reducing electromagnetic emission on single frequencies.
594
+ */
595
+void TMC26XStepper::setRandomOffTime(char value) {
596
+  if (value)
597
+    chopper_config_register |= RANDOM_TOFF_TIME;
598
+  else
599
+    chopper_config_register &= ~(RANDOM_TOFF_TIME);
600
+  //if started we directly send it to the motor
601
+  if (started) {
602
+    //rem send262(driver_control_register_value);
603
+    send262(chopper_config_register);
604
+  }
605
+}
606
+
607
+void TMC26XStepper::setCoolStepConfiguration(
608
+  unsigned int lower_SG_threshold,
609
+  unsigned int SG_hysteresis,
610
+  unsigned char current_decrement_step_size,
611
+  unsigned char current_increment_step_size,
612
+  unsigned char lower_current_limit)
613
+{
614
+  // Sanitize the input values
615
+  NOMORE(lower_SG_threshold, 480);
616
+  // Divide by 32
617
+  lower_SG_threshold >>= 5;
618
+  NOMORE(SG_hysteresis, 480);
619
+  // Divide by 32
620
+  SG_hysteresis >>= 5;
621
+  NOMORE(current_decrement_step_size, 3);
622
+  NOMORE(current_increment_step_size, 3);
623
+  NOMORE(lower_current_limit, 1);
624
+
625
+  // Store the lower level in order to enable/disable the cool step
626
+  this->cool_step_lower_threshold=lower_SG_threshold;
627
+  // If cool step is not enabled we delete the lower value to keep it disabled
628
+  if (!this->cool_step_enabled) lower_SG_threshold = 0;
629
+  // The good news is that we can start with a complete new cool step register value
630
+  // And simply set the values in the register
631
+  cool_step_register_value = ((unsigned long)lower_SG_threshold)
632
+                          | (((unsigned long)SG_hysteresis) << 8)
633
+                          | (((unsigned long)current_decrement_step_size) << 5)
634
+                          | (((unsigned long)current_increment_step_size) << 13)
635
+                          | (((unsigned long)lower_current_limit) << 15)
636
+                          | COOL_STEP_REGISTER; // Register signature
637
+
638
+  //SERIAL_PRINTFln(cool_step_register_value,HEX);
639
+  if (started) send262(cool_step_register_value);
640
+}
641
+
642
+void TMC26XStepper::setCoolStepEnabled(boolean enabled) {
643
+  // Simply delete the lower limit to disable the cool step
644
+  cool_step_register_value &= ~SE_MIN_PATTERN;
645
+  // And set it to the proper value if cool step is to be enabled
646
+  if (enabled)
647
+    cool_step_register_value |= this->cool_step_lower_threshold;
648
+  // And save the enabled status
649
+  this->cool_step_enabled = enabled;
650
+  // Save the register value
651
+  if (started) send262(cool_step_register_value);
652
+}
653
+
654
+boolean TMC26XStepper::isCoolStepEnabled(void) { return this->cool_step_enabled; }
655
+
656
+unsigned int TMC26XStepper::getCoolStepLowerSgThreshold() {
657
+  // We return our internally stored value - in order to provide the correct setting even if cool step is not enabled
658
+  return this->cool_step_lower_threshold<<5;
659
+}
660
+
661
+unsigned int TMC26XStepper::getCoolStepUpperSgThreshold() {
662
+  return (unsigned char)((cool_step_register_value & SE_MAX_PATTERN) >> 8) << 5;
663
+}
664
+
665
+unsigned char TMC26XStepper::getCoolStepCurrentIncrementSize() {
666
+  return (unsigned char)((cool_step_register_value & CURRENT_DOWN_STEP_SPEED_PATTERN) >> 13);
667
+}
668
+
669
+unsigned char TMC26XStepper::getCoolStepNumberOfSGReadings() {
670
+  return (unsigned char)((cool_step_register_value & SE_CURRENT_STEP_WIDTH_PATTERN) >> 5);
671
+}
672
+
673
+unsigned char TMC26XStepper::getCoolStepLowerCurrentLimit() {
674
+  return (unsigned char)((cool_step_register_value & MINIMUM_CURRENT_FOURTH) >> 15);
675
+}
676
+
677
+void TMC26XStepper::setEnabled(boolean enabled) {
678
+  //delete the t_off in the chopper config to get sure
679
+  chopper_config_register &= ~(T_OFF_PATTERN);
680
+  if (enabled) {
681
+    //and set the t_off time
682
+    chopper_config_register |= this->constant_off_time;
683
+  }
684
+  //if not enabled we don't have to do anything since we already delete t_off from the register
685
+  if (started) send262(chopper_config_register);
686
+}
687
+
688
+boolean TMC26XStepper::isEnabled() { return !!(chopper_config_register & T_OFF_PATTERN); }
689
+
690
+/**
691
+ * reads a value from the TMC26X status register. The value is not obtained directly but can then
692
+ * be read by the various status routines.
693
+ *
694
+ */
695
+void TMC26XStepper::readStatus(char read_value) {
696
+  unsigned long old_driver_configuration_register_value = driver_configuration_register_value;
697
+  //reset the readout configuration
698
+  driver_configuration_register_value &= ~(READ_SELECTION_PATTERN);
699
+  //this now equals TMC26X_READOUT_POSITION - so we just have to check the other two options
700
+  if (read_value == TMC26X_READOUT_STALLGUARD)
701
+    driver_configuration_register_value |= READ_STALL_GUARD_READING;
702
+  else if (read_value == TMC26X_READOUT_CURRENT)
703
+    driver_configuration_register_value |= READ_STALL_GUARD_AND_COOL_STEP;
704
+
705
+  //all other cases are ignored to prevent funny values
706
+  //check if the readout is configured for the value we are interested in
707
+  if (driver_configuration_register_value != old_driver_configuration_register_value) {
708
+    //because then we need to write the value twice - one time for configuring, second time to get the value, see below
709
+    send262(driver_configuration_register_value);
710
+  }
711
+  //write the configuration to get the last status
712
+  send262(driver_configuration_register_value);
713
+}
714
+
715
+int TMC26XStepper::getMotorPosition(void) {
716
+  //we read it out even if we are not started yet - perhaps it is useful information for somebody
717
+  readStatus(TMC26X_READOUT_POSITION);
718
+  return getReadoutValue();
719
+}
720
+
721
+//reads the stall guard setting from last status
722
+//returns -1 if stallguard information is not present
723
+int TMC26XStepper::getCurrentStallGuardReading(void) {
724
+  //if we don't yet started there cannot be a stall guard value
725
+  if (!started) return -1;
726
+  //not time optimal, but solution optiomal:
727
+  //first read out the stall guard value
728
+  readStatus(TMC26X_READOUT_STALLGUARD);
729
+  return getReadoutValue();
730
+}
731
+
732
+unsigned char TMC26XStepper::getCurrentCSReading(void) {
733
+  //if we don't yet started there cannot be a stall guard value
734
+  if (!started) return 0;
735
+  //not time optimal, but solution optiomal:
736
+  //first read out the stall guard value
737
+  readStatus(TMC26X_READOUT_CURRENT);
738
+  return (getReadoutValue() & 0x1F);
739
+}
740
+
741
+unsigned int TMC26XStepper::getCurrentCurrent(void) {
742
+    double result = (double)getCurrentCSReading(),
743
+           resistor_value = (double)this->resistor,
744
+           voltage = (driver_configuration_register_value & VSENSE)? 0.165 : 0.31;
745
+    result = (result + 1.0) / 32.0 * voltage / resistor_value * sq(1000.0);
746
+    return (unsigned int)result;
747
+}
748
+
749
+/**
750
+ * Return true if the stallguard threshold has been reached
751
+ */
752
+boolean TMC26XStepper::isStallGuardOverThreshold(void) {
753
+  if (!this->started) return false;
754
+  return (driver_status_result & STATUS_STALL_GUARD_STATUS);
755
+}
756
+
757
+/**
758
+ * returns if there is any over temperature condition:
759
+ * OVER_TEMPERATURE_PREWARING if pre warning level has been reached
760
+ * OVER_TEMPERATURE_SHUTDOWN if the temperature is so hot that the driver is shut down
761
+ * Any of those levels are not too good.
762
+ */
763
+char TMC26XStepper::getOverTemperature(void) {
764
+  if (!this->started) return 0;
765
+
766
+  if (driver_status_result & STATUS_OVER_TEMPERATURE_SHUTDOWN)
767
+    return TMC26X_OVERTEMPERATURE_SHUTDOWN;
768
+
769
+  if (driver_status_result & STATUS_OVER_TEMPERATURE_WARNING)
770
+    return TMC26X_OVERTEMPERATURE_PREWARING;
771
+
772
+  return 0;
773
+}
774
+
775
+// Is motor channel A shorted to ground
776
+boolean TMC26XStepper::isShortToGroundA(void) {
777
+  if (!this->started) return false;
778
+  return (driver_status_result & STATUS_SHORT_TO_GROUND_A);
779
+}
780
+
781
+// Is motor channel B shorted to ground
782
+boolean TMC26XStepper::isShortToGroundB(void) {
783
+  if (!this->started) return false;
784
+  return (driver_status_result & STATUS_SHORT_TO_GROUND_B);
785
+}
786
+
787
+// Is motor channel A connected
788
+boolean TMC26XStepper::isOpenLoadA(void) {
789
+  if (!this->started) return false;
790
+  return (driver_status_result & STATUS_OPEN_LOAD_A);
791
+}
792
+
793
+// Is motor channel B connected
794
+boolean TMC26XStepper::isOpenLoadB(void) {
795
+  if (!this->started) return false;
796
+  return (driver_status_result & STATUS_OPEN_LOAD_B);
797
+}
798
+
799
+// Is chopper inactive since 2^20 clock cycles - defaults to ~0,08s
800
+boolean TMC26XStepper::isStandStill(void) {
801
+  if (!this->started) return false;
802
+  return (driver_status_result & STATUS_STAND_STILL);
803
+}
804
+
805
+//is chopper inactive since 2^20 clock cycles - defaults to ~0,08s
806
+boolean TMC26XStepper::isStallGuardReached(void) {
807
+  if (!this->started) return false;
808
+  return (driver_status_result & STATUS_STALL_GUARD_STATUS);
809
+}
810
+
811
+//reads the stall guard setting from last status
812
+//returns -1 if stallguard inforamtion is not present
813
+int TMC26XStepper::getReadoutValue(void) {
814
+  return (int)(driver_status_result >> 10);
815
+}
816
+
817
+int TMC26XStepper::getResistor() { return this->resistor; }
818
+
819
+boolean TMC26XStepper::isCurrentScalingHalfed() {
820
+  return !!(this->driver_configuration_register_value & VSENSE);
821
+}
822
+/**
823
+ * version() returns the version of the library:
824
+ */
825
+int TMC26XStepper::version(void) { return 1; }
826
+
827
+void TMC26XStepper::debugLastStatus() {
828
+  #ifdef TMC_DEBUG1
829
+    if (this->started) {
830
+      if (this->getOverTemperature()&TMC26X_OVERTEMPERATURE_PREWARING)
831
+        SERIAL_ECHOLNPGM("\n  WARNING: Overtemperature Prewarning!");
832
+      else if (this->getOverTemperature()&TMC26X_OVERTEMPERATURE_SHUTDOWN)
833
+        SERIAL_ECHOLNPGM("\n  ERROR: Overtemperature Shutdown!");
834
+      
835
+      if (this->isShortToGroundA())
836
+        SERIAL_ECHOLNPGM("\n  ERROR: SHORT to ground on channel A!");
837
+
838
+      if (this->isShortToGroundB())
839
+        SERIAL_ECHOLNPGM("\n  ERROR: SHORT to ground on channel B!");
840
+
841
+      if (this->isOpenLoadA())
842
+        SERIAL_ECHOLNPGM("\n  ERROR: Channel A seems to be unconnected!");
843
+
844
+      if (this->isOpenLoadB())
845
+        SERIAL_ECHOLNPGM("\n  ERROR: Channel B seems to be unconnected!");
846
+
847
+      if (this->isStallGuardReached())
848
+        SERIAL_ECHOLNPGM("\n  INFO: Stall Guard level reached!");
849
+
850
+      if (this->isStandStill())
851
+        SERIAL_ECHOLNPGM("\n  INFO: Motor is standing still.");
852
+
853
+      unsigned long readout_config = driver_configuration_register_value & READ_SELECTION_PATTERN;
854
+      const int value = getReadoutValue();
855
+      if (readout_config == READ_MICROSTEP_POSTION) {
856
+        //SERIAL_PRINTF("Microstep postion phase A: ");
857
+        SERIAL_ECHOPAIR("\n  Microstep postion phase A: ", value);
858
+      }
859
+      else if (readout_config == READ_STALL_GUARD_READING) {
860
+        //SERIAL_PRINTF("Stall Guard value:");
861
+        SERIAL_ECHOPAIR("\n  Stall Guard value:", value);
862
+      }
863
+      else if (readout_config == READ_STALL_GUARD_AND_COOL_STEP) {
864
+        int stallGuard = value & 0xF, current = value & 0x1F0;
865
+        //SERIAL_PRINTF("Approx Stall Guard: ");
866
+        SERIAL_ECHOPAIR("\n  Approx Stall Guard: ", stallGuard);
867
+        //SERIAL_PRINTF("Current level");
868
+        SERIAL_ECHOPAIR("\n  Current level", current);
869
+      }
870
+    }
871
+  #endif
872
+}
873
+
874
+/**
875
+ * send register settings to the stepper driver via SPI
876
+ * returns the current status
877
+ */
878
+inline void TMC26XStepper::send262(unsigned long datagram) {
879
+  unsigned long i_datagram;
880
+
881
+  //preserver the previous spi mode
882
+  //unsigned char oldMode =  SPCR & SPI_MODE_MASK;
883
+
884
+  //if the mode is not correct set it to mode 3
885
+  //if (oldMode != SPI_MODE3) {
886
+  //  SPI.setDataMode(SPI_MODE3);
887
+  //}
888
+
889
+  //select the TMC driver
890
+  digitalWrite(cs_pin,LOW);
891
+
892
+  //ensure that only valid bist are set (0-19)
893
+  //datagram &=REGISTER_BIT_PATTERN;
894
+
895
+  #ifdef TMC_DEBUG1
896
+    //SERIAL_PRINTF("Sending ");
897
+    //SERIAL_PRINTF("Sending ", datagram,HEX);
898
+    //SERIAL_ECHOPAIR("\n\nSending \n", print_hex_long(datagram));
899
+    SERIAL_PRINTF("\n\nSending %x", datagram);
900
+  #endif
901
+
902
+  //write/read the values
903
+  i_datagram = STEPPER_SPI.transfer((datagram >> 16) & 0xFF);
904
+  i_datagram <<= 8;
905
+  i_datagram |= STEPPER_SPI.transfer((datagram >>  8) & 0xFF);
906
+  i_datagram <<= 8;
907
+  i_datagram |= STEPPER_SPI.transfer((datagram) & 0xFF);
908
+  i_datagram >>= 4;
909
+
910
+  #ifdef TMC_DEBUG1
911
+    //SERIAL_PRINTF("Received ");
912
+    //SERIAL_PRINTF("Received ", i_datagram,HEX);
913
+    //SERIAL_ECHOPAIR("\n\nReceived \n", i_datagram);
914
+    SERIAL_PRINTF("\n\nReceived %x", i_datagram);
915
+    debugLastStatus();
916
+  #endif
917
+
918
+  //deselect the TMC chip
919
+  digitalWrite(cs_pin,HIGH);
920
+
921
+  //restore the previous SPI mode if neccessary
922
+  //if the mode is not correct set it to mode 3
923
+  //if (oldMode != SPI_MODE3) {
924
+  //  SPI.setDataMode(oldMode);
925
+  //}
926
+
927
+  //store the datagram as status result
928
+  driver_status_result = i_datagram;
929
+}
930
+
931
+#endif // STM32F7

+ 607
- 0
Marlin/src/HAL/HAL_STM32F7/TMC2660.h View File

@@ -0,0 +1,607 @@
1
+/**
2
+ * TMC26XStepper.h - - TMC26X Stepper library for Wiring/Arduino
3
+ * 
4
+ * based on the stepper library by Tom Igoe, et. al.
5
+ *
6
+ * Copyright (c) 2011, Interactive Matter, Marcus Nowotny
7
+ * 
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ * 
15
+ * The above copyright notice and this permission notice shall be included in
16
+ * all copies or substantial portions of the Software.
17
+ * 
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
+ * THE SOFTWARE.
25
+ *
26
+ */
27
+
28
+#include "../../inc/MarlinConfig.h"
29
+
30
+// ensure this library description is only included once
31
+#ifndef _TMC26XSTEPPER_H_
32
+#define _TMC26XSTEPPER_H_
33
+
34
+//! return value for TMC26XStepper.getOverTemperature() if there is a overtemperature situation in the TMC chip
35
+/*!
36
+ * This warning indicates that the TCM chip is too warm. 
37
+ * It is still working but some parameters may be inferior. 
38
+ * You should do something against it.
39
+ */
40
+#define TMC26X_OVERTEMPERATURE_PREWARING 1
41
+//! return value for TMC26XStepper.getOverTemperature() if there is a overtemperature shutdown in the TMC chip
42
+/*!
43
+ * This warning indicates that the TCM chip is too warm to operate and has shut down to prevent damage. 
44
+ * It will stop working until it cools down again.
45
+ * If you encouter this situation you must do something against it. Like reducing the current or improving the PCB layout 
46
+ * and/or heat management.
47
+ */
48
+#define TMC26X_OVERTEMPERATURE_SHUTDOWN 2
49
+
50
+//which values can be read out
51
+/*!
52
+ * Selects to readout the microstep position from the motor.
53
+ *\sa readStatus()
54
+ */
55
+#define TMC26X_READOUT_POSITION 0
56
+/*!
57
+ * Selects to read out the StallGuard value of the motor.
58
+ *\sa readStatus()
59
+ */
60
+#define TMC26X_READOUT_STALLGUARD 1
61
+/*!
62
+ * Selects to read out the current current setting (acc. to CoolStep) and the upper bits of the StallGuard value from the motor.
63
+ *\sa readStatus(), setCurrent()
64
+ */
65
+#define TMC26X_READOUT_CURRENT 3
66
+
67
+/*!
68
+ * Define to set the minimum current for CoolStep operation to 1/2 of the selected CS minium.
69
+ *\sa setCoolStepConfiguration()
70
+ */
71
+#define COOL_STEP_HALF_CS_LIMIT 0
72
+/*!
73
+ * Define to set the minimum current for CoolStep operation to 1/4 of the selected CS minium.
74
+ *\sa setCoolStepConfiguration()
75
+ */
76
+#define COOL_STEP_QUARTDER_CS_LIMIT 1
77
+
78
+/*!
79
+ * \class TMC26XStepper
80
+ * \brief Class representing a TMC26X stepper driver
81
+ * 
82
+ * In order to use one fo those drivers in your Arduino code you have to create an object of that class:
83
+ * \code
84
+ * TMC26XStepper stepper = TMC26XStepper(200,1,2,3,500);
85
+ * \endcode
86
+ * see TMC26XStepper(int number_of_steps, int cs_pin, int dir_pin, int step_pin, unsigned int rms_current)
87
+ *
88
+ * Keep in mind that you need to start the driver with start() in order to get the TMC26X configured.
89
+ * 
90
+ * The most important function is the move(). It checks if the motor has to do a step or not.
91
+ * It is important that you call move() as often as possible in your Arduino loop() routine. I suggest
92
+ * to use a very fast loop routine and always call it at the beginning or the end.
93
+ *
94
+ * In order to move you have to provide a movement speed with setSpeed(). The speed is a positive value setting
95
+ * the rotations per minute.
96
+ *
97
+ * To really move the motor you have to call step() to tell the driver to move the motor the given number 
98
+ * of steps in the given direction. Positive values move the motor in one direction, negative values in the other direction.
99
+ *
100
+ * You can check with isMoving() if the mototr is still moving or stop it  apruptely with stop().
101
+ */
102
+class TMC26XStepper {
103
+  public:
104
+    /*!
105
+     * \brief creates a new represenatation of a stepper motor connected to a TMC26X stepper driver
106
+     *
107
+     * This is the main constructor. If in doubt use this. You must provide all parameters as described below.
108
+     *
109
+     * \param number_of_steps the number of steps the motor has per rotation.
110
+     * \param cs_pin The Arduino pin you have connected the Cient Select Pin (!CS) of the TMC26X for SPI
111
+     * \param dir_pin the number of the Arduino pin the Direction input of the TMC26X is connected
112
+     * \param step_pin the number of the Arduino pin the step pin of the TMC26X driver is connected.
113
+     * \param rms_current the maximum current to privide to the motor in mA (!). A value of 200 would send up to 200mA to the motor
114
+     * \param resistor the current sense resistor in milli Ohm, defaults to ,15 Ohm ( or 150 milli Ohm) as in the TMC260 Arduino Shield
115
+     *
116
+     * Keep in mind that you must also call TMC26XStepper.start() in order to configure the stepper driver for use.
117
+     *
118
+     * By default the Constant Off Time chopper is used, see TCM262Stepper.setConstantOffTimeChopper() for details. 
119
+     * This should work on most motors (YMMV). You may want to configure and use the Spread Cycle Chopper, see  setSpreadCycleChopper().
120
+     *
121
+     * By default a microstepping of 1/32th is used to provide a smooth motor run, while still giving a good progression per step.
122
+     * You can select a different stepping with setMicrosteps() to aa different value.
123
+     * \sa start(), setMicrosteps()
124
+     */
125
+    TMC26XStepper(int number_of_steps, int cs_pin, int dir_pin, int step_pin, unsigned int current, unsigned int resistor=100); //resistor=150
126
+    
127
+    /*!
128
+     * \brief configures and starts the TMC26X stepper driver. Before you called this function the stepper driver is in nonfunctional mode.
129
+     *
130
+     * This routine configures the TMC26X stepper driver for the given values via SPI. 
131
+     * Most member functions are non functional if the driver has not been started.
132
+     * Therefore it is best to call this in your Arduino setup() function.
133
+     */
134
+    void start();
135
+    
136
+    /*!
137
+     * \brief resets the stepper in unconfigured mode.
138
+     *
139
+     * This routine enables you to call start again. It does not change anything 
140
+     * in the internal stepper configuration or the desired configuration.
141
+     * It just marks the stepper as not yet startet. You do not have to reconfigure
142
+     * the stepper to start it again, but it is not reset to any factory settings
143
+     * this has to be configured back by yourself.
144
+     * (Hint: Normally you do not need this function)
145
+     */
146
+    void un_start();
147
+
148
+
149
+    /*!
150
+     * \brief Sets the rotation speed in revolutions per minute.
151
+     * \param whatSpeed the desired speed in rotations per minute.
152
+     */
153
+    void setSpeed(unsigned int whatSpeed);
154
+    
155
+    /*!
156
+     * \brief reads out the currently selected speed in revolutions per minute.
157
+     * \sa setSpeed()
158
+     */
159
+    unsigned int getSpeed(void);
160
+
161
+    /*!
162
+     * \brief Set the number of microsteps in 2^i values (rounded) up to 256
163
+     *
164
+     * This method set's the number of microsteps per step in 2^i interval.
165
+     * This means you can select 1, 2, 4, 16, 32, 64, 128 or 256 as valid microsteps.
166
+     * If you give any other value it will be rounded to the next smaller number (3 would give a microstepping of 2).
167
+     * You can always check the current microstepping with getMicrosteps(). 
168
+     */ 
169
+    void setMicrosteps(int number_of_steps);
170
+    
171
+    /*!
172
+     * \brief returns the effective current number of microsteps selected.
173
+     *
174
+     * This function always returns the effective number of microsteps. 
175
+     * This can be a bit different than the micro steps set in setMicrosteps() since it is rounded to 2^i.
176
+     *
177
+     * \sa setMicrosteps()
178
+     */
179
+    int getMicrosteps(void);
180
+
181
+    /*!
182
+     * \brief Initiate a movement for the given number of steps. Positive numbers move in one, negative numbers in the other direction.
183
+     *
184
+     * \param number_of_steps The number of steps to move the motor.
185
+     * \return 0 if the motor was not moving and moves now. -1 if the motor is moving and the new steps could not be set.
186
+     *
187
+     * If the previous movement is not finished yet the function will return -1 and not change the steps to move the motor.
188
+     * If the motor does not move it return 0
189
+     *
190
+     * The direction of the movement is indicated by the sign of the steps parameter. It is not determinable if positive values are right 
191
+     * or left This depends on the internal construction of the motor and how you connected it to the stepper driver.
192
+     *
193
+     * You can always verify with isMoving() or even use stop() to stop the motor before giving it new step directions.
194
+     * \sa isMoving(), getStepsLeft(), stop()
195
+     */
196
+    char step(int number_of_steps);
197
+    
198
+    /*!
199
+     * \brief Central movement method, must be called as often as possible in the lopp function and is very fast.
200
+     *
201
+     * This routine checks if the motor still has to move, if the waiting delay has passed to send a new step command to the motor 
202
+     * and manages the number of steps yet to move to fulfill the current move command.
203
+     *
204
+     * This function is implemented to be as fast as possible to call it as often as possible in your loop routine.
205
+     * The more regurlarly you call this function the better. In both senses of 'regularly': Calling it as often as
206
+     * possible is not a bad idea and if you even manage that the intervals you call this function are not too irregular helps too.
207
+     *
208
+     * You can call this routine even if you know that the motor is not miving. It introduces just a very small penalty in your code.
209
+     * You must not call isMoving() to determine if you need to call this function, since taht is done internally already and only 
210
+     * slows down you code.
211
+     * 
212
+     * How often you call this function directly influences your top miving speed for the motor. It may be a good idea to call this
213
+     * from an timer overflow interrupt to ensure proper calling.
214
+     * \sa step()
215
+     */
216
+    char move(void);
217
+
218
+    /*!
219
+     * \brief checks if the motor still has to move to fulfill the last movement command.
220
+     * \return 0 if the motor stops, -1 if the motor is moving.
221
+     *
222
+     * This method can be used to determine if the motor is ready for new movements.
223
+     *\sa step(), move()
224
+     */
225
+    char isMoving(void);
226
+    
227
+    /*!
228
+     * \brief Get the number of steps left in the current movement.
229
+     * \return The number of steps left in the movement. This number is always positive.
230
+     */
231
+    unsigned int getStepsLeft(void);
232
+    
233
+    /*!
234
+     * \brief Stops the motor regardless if it moves or not.
235
+     * \return -1 if the motor was moving and is really stoped or 0 if it was not moving at all.
236
+     *
237
+     * This method directly and apruptely stops the motor and may be used as an emergency stop.
238
+     */
239
+    char stop(void);
240
+    
241
+    /*!
242
+     * \brief Sets and configure the classical Constant Off Timer Chopper
243
+     * \param constant_off_time The off time setting controls the minimum chopper frequency. For most applications an off time within the range of 5μs to 20μs will fit. Setting this parameter to zero completely disables all driver transistors and the motor can free-wheel. 0: chopper off, 1:15: off time setting (1 will work with minimum blank time of 24 clocks)
244
+     * \param blank_time Selects the comparator blank time. This time needs to safely cover the switching event and the duration of the ringing on the sense resistor. For most low current drivers, a setting of 1 or 2 is good. For high current applications with large MOSFETs, a setting of 2 or 3 will be required. 0 (min setting) … (3) amx setting
245
+     * \param fast_decay_time_setting Fast decay time setting. Controls the portion of fast decay for each chopper cycle. 0: slow decay only, 1…15: duration of fast decay phase
246
+     * \param sine_wave_offset Sine wave offset. Controls the sine wave offset. A positive offset corrects for zero crossing error. -3…-1: negative offset, 0: no offset,1…12: positive offset
247
+     * \param use_curreent_comparator Selects usage of the current comparator for termination of the fast decay cycle. If current comparator is enabled, it terminates the fast decay cycle in case the current reaches a higher negative value than the actual positive value. (0 disable, -1 enable).
248
+     *
249
+     * The classic constant off time chopper uses a fixed portion of fast decay following each on phase. 
250
+     * While the duration of the on time is determined by the chopper comparator, the fast decay time needs 
251
+     * to be set by the user in a way, that the current decay is enough for the driver to be able to follow 
252
+     * the falling slope of the sine wave, and on the other hand it should not be too long, in order to minimize 
253
+     * motor current ripple and power dissipation. This best can be tuned using an oscilloscope or 
254
+     * trying out motor smoothness at different velocities. A good starting value is a fast decay time setting 
255
+     * similar to the slow decay time setting.
256
+     * After tuning of the fast decay time, the offset should be determined, in order to have a smooth zero transition. 
257
+     * This is necessary, because the fast decay phase leads to the absolute value of the motor current being lower 
258
+     * than the target current (see figure 17). If the zero offset is too low, the motor stands still for a short 
259
+     * moment during current zero crossing, if it is set too high, it makes a larger microstep.
260
+     * Typically, a positive offset setting is required for optimum operation.
261
+     *
262
+     * \sa setSpreadCycleChoper() for other alternatives.
263
+     * \sa setRandomOffTime() for spreading the noise over a wider spectrum
264
+     */
265
+    void setConstantOffTimeChopper(char constant_off_time, char blank_time, char fast_decay_time_setting, char sine_wave_offset, unsigned char use_current_comparator);
266
+    
267
+    /*!
268
+     * \brief Sets and configures with spread cycle chopper.
269
+     * \param constant_off_time The off time setting controls the minimum chopper frequency. For most applications an off time within the range of 5μs to 20μs will fit. Setting this parameter to zero completely disables all driver transistors and the motor can free-wheel. 0: chopper off, 1:15: off time setting (1 will work with minimum blank time of 24 clocks)
270
+     * \param blank_time Selects the comparator blank time. This time needs to safely cover the switching event and the duration of the ringing on the sense resistor. For most low current drivers, a setting of 1 or 2 is good. For high current applications with large MOSFETs, a setting of 2 or 3 will be required. 0 (min setting) … (3) amx setting
271
+     * \param hysteresis_start Hysteresis start setting. Please remark, that this value is an offset to the hysteresis end value. 1 … 8
272
+     * \param hysteresis_end Hysteresis end setting. Sets the hysteresis end value after a number of decrements. Decrement interval time is controlled by hysteresis_decrement. The sum hysteresis_start + hysteresis_end must be <16. At a current setting CS of max. 30 (amplitude reduced to 240), the sum is not limited.
273
+     * \param hysteresis_decrement Hysteresis decrement setting. This setting determines the slope of the hysteresis during on time and during fast decay time. 0 (fast decrement) … 3 (slow decrement).
274
+     *
275
+     * The spreadCycle chopper scheme (pat.fil.) is a precise and simple to use chopper principle, which automatically determines 
276
+     * the optimum fast decay portion for the motor. Anyhow, a number of settings can be made in order to optimally fit the driver 
277
+     * to the motor.
278
+     * Each chopper cycle is comprised of an on-phase, a slow decay phase, a fast decay phase and a second slow decay phase.
279
+     * The slow decay phases limit the maximum chopper frequency and are important for low motor and driver power dissipation. 
280
+     * The hysteresis start setting limits the chopper frequency by forcing the driver to introduce a minimum amount of 
281
+     * current ripple into the motor coils. The motor inductivity determines the ability to follow a changing motor current. 
282
+     * The duration of the on- and fast decay phase needs to cover at least the blank time, because the current comparator is 
283
+     * disabled during this time.
284
+     * 
285
+     * \sa setRandomOffTime() for spreading the noise over a wider spectrum
286
+     */
287
+    void setSpreadCycleChopper(char constant_off_time, char blank_time, char hysteresis_start, char hysteresis_end, char hysteresis_decrement);
288
+
289
+    /*!
290
+     * \brief Use random off time for noise reduction (0 for off, -1 for on).
291
+     * \param value 0 for off, -1 for on
292
+     *
293
+     * In a constant off time chopper scheme both coil choppers run freely, i.e. are not synchronized. 
294
+     * The frequency of each chopper mainly depends on the coil current and the position dependant motor coil inductivity, 
295
+     * thus it depends on the microstep position. With some motors a slightly audible beat can occur between the chopper 
296
+     * frequencies, especially when they are near to each other. This typically occurs at a few microstep positions within 
297
+     * each quarter wave. 
298
+     * This effect normally is not audible when compared to mechanical noise generated by ball bearings, 
299
+     * etc. Further factors which can cause a similar effect are a poor layout of sense resistor GND connection.
300
+     * In order to minimize the effect of a beat between both chopper frequencies, an internal random generator is provided. 
301
+     * It modulates the slow decay time setting when switched on. The random off time feature further spreads the chopper spectrum,
302
+     * reducing electromagnetic emission on single frequencies.
303
+     */
304
+    void setRandomOffTime(char value);
305
+    
306
+    /*!
307
+     * \brief set the maximum motor current in mA (1000 is 1 Amp)
308
+     * Keep in mind this is the maximum peak Current. The RMS current will be 1/sqrt(2) smaller. The actual current can also be smaller
309
+     * by employing CoolStep.
310
+     * \param current the maximum motor current in mA
311
+     * \sa getCurrent(), getCurrentCurrent()
312
+     */
313
+    void setCurrent(unsigned int current);
314
+    
315
+    /*!
316
+     * \brief readout the motor maximum current in mA (1000 is an Amp)
317
+     * This is the maximum current. to get the current current - which may be affected by CoolStep us getCurrentCurrent()
318
+     *\return the maximum motor current in milli amps
319
+     * \sa getCurrentCurrent()
320
+     */
321
+    unsigned int getCurrent(void);
322
+    
323
+    /*!
324
+     * \brief set the StallGuard threshold in order to get sensible StallGuard readings.
325
+     * \param stall_guard_threshold -64 … 63 the StallGuard threshold
326
+     * \param stall_guard_filter_enabled 0 if the filter is disabled, -1 if it is enabled
327
+     *
328
+     * The StallGuard threshold is used to optimize the StallGuard reading to sensible values. It should be at 0 at
329
+     * the maximum allowable load on the otor (but not before). = is a good starting point (and the default)
330
+     * If you get Stall Gaurd readings of 0 without any load or with too little laod increase the value.
331
+     * If you get readings of 1023 even with load decrease the setting.
332
+     *
333
+     * If you switch on the filter the StallGuard reading is only updated each 4th full step to reduce the noise in the
334
+     * reading.
335
+     * 
336
+     * \sa getCurrentStallGuardReading() to read out the current value.
337
+     */ 
338
+    void setStallGuardThreshold(char stall_guard_threshold, char stall_guard_filter_enabled);
339
+    
340
+    /*!
341
+     * \brief reads out the StallGuard threshold
342
+     * \return a number between -64 and 63.
343
+     */
344
+    char getStallGuardThreshold(void);
345
+    
346
+    /*!
347
+     * \brief returns the current setting of the StallGuard filter
348
+     * \return 0 if not set, -1 if set
349
+     */
350
+    char getStallGuardFilter(void);
351
+    
352
+    /*!
353
+     * \brief This method configures the CoolStep smart energy operation. You must have a proper StallGuard configuration for the motor situation (current, voltage, speed) in rder to use this feature.
354
+     * \param lower_SG_threshold Sets the lower threshold for stallGuard2TM reading. Below this value, the motor current becomes increased. Allowed values are 0...480
355
+     * \param SG_hysteresis Sets the distance between the lower and the upper threshold for stallGuard2TM reading. Above the upper threshold (which is lower_SG_threshold+SG_hysteresis+1) the motor current becomes decreased. Allowed values are 0...480
356
+     * \param current_decrement_step_size Sets the current decrement steps. If the StallGuard value is above the threshold the current gets decremented by this step size. 0...32
357
+     * \param current_increment_step_size Sets the current increment step. The current becomes incremented for each measured stallGuard2TM value below the lower threshold. 0...8
358
+     * \param lower_current_limit Sets the lower motor current limit for coolStepTM operation by scaling the CS value. Values can be COOL_STEP_HALF_CS_LIMIT, COOL_STEP_QUARTER_CS_LIMIT
359
+     * The CoolStep smart energy operation automatically adjust the current sent into the motor according to the current load,
360
+     * read out by the StallGuard in order to provide the optimum torque with the minimal current consumption.
361
+     * You configure the CoolStep current regulator by defining upper and lower bounds of StallGuard readouts. If the readout is above the 
362
+     * limit the current gets increased, below the limit the current gets decreased.
363
+     * You can specify the upper an lower threshold of the StallGuard readout in order to adjust the current. You can also set the number of
364
+     * StallGuard readings neccessary above or below the limit to get a more stable current adjustement.
365
+     * The current adjustement itself is configured by the number of steps the current gests in- or decreased and the absolut minimum current
366
+     * (1/2 or 1/4th otf the configured current).
367
+     * \sa COOL_STEP_HALF_CS_LIMIT, COOL_STEP_QUARTER_CS_LIMIT
368
+     */
369
+    void setCoolStepConfiguration(unsigned int lower_SG_threshold, unsigned int SG_hysteresis, unsigned char current_decrement_step_size,
370
+                                  unsigned char current_increment_step_size, unsigned char lower_current_limit);
371
+    
372
+    /*!
373
+     * \brief enables or disables the CoolStep smart energy operation feature. It must be configured before enabling it.
374
+     * \param enabled true if CoolStep should be enabled, false if not.
375
+     * \sa setCoolStepConfiguration()
376
+     */
377
+    void setCoolStepEnabled(boolean enabled);
378
+    
379
+    
380
+    /*!
381
+     * \brief check if the CoolStep feature is enabled
382
+     * \sa setCoolStepEnabled()
383
+     */
384
+    boolean isCoolStepEnabled();
385
+
386
+    /*!
387
+     * \brief returns the lower StallGuard threshold for the CoolStep operation
388
+     * \sa setCoolStepConfiguration()
389
+     */
390
+    unsigned int getCoolStepLowerSgThreshold();
391
+    
392
+    /*!
393
+     * \brief returns the upper StallGuard threshold for the CoolStep operation
394
+     * \sa setCoolStepConfiguration()
395
+     */
396
+    unsigned int getCoolStepUpperSgThreshold();
397
+    
398
+    /*!
399
+     * \brief returns the number of StallGuard readings befor CoolStep adjusts the motor current.
400
+     * \sa setCoolStepConfiguration()
401
+     */
402
+    unsigned char getCoolStepNumberOfSGReadings();
403
+    
404
+    /*!
405
+     * \brief returns the increment steps for the current for the CoolStep operation
406
+     * \sa setCoolStepConfiguration()
407
+     */
408
+    unsigned char getCoolStepCurrentIncrementSize();
409
+    
410
+    /*!
411
+     * \brief returns the absolut minium current for the CoolStep operation
412
+     * \sa setCoolStepConfiguration()
413
+     * \sa COOL_STEP_HALF_CS_LIMIT, COOL_STEP_QUARTER_CS_LIMIT
414
+     */
415
+    unsigned char getCoolStepLowerCurrentLimit();
416
+    
417
+    /*!
418
+     * \brief Get the current microstep position for phase A
419
+     * \return The current microstep position for phase A 0…255
420
+     * 
421
+     * Keep in mind that this routine reads and writes a value via SPI - so this may take a bit time.
422
+     */
423
+    int getMotorPosition(void);
424
+    
425
+    /*!
426
+     * \brief Reads the current StallGuard value.
427
+     * \return The current StallGuard value, lesser values indicate higher load, 0 means stall detected.
428
+     * Keep in mind that this routine reads and writes a value via SPI - so this may take a bit time.
429
+     * \sa setStallGuardThreshold() for tuning the readout to sensible ranges.
430
+     */
431
+    int getCurrentStallGuardReading(void);
432
+    
433
+    /*!
434
+     * \brief Reads the current current setting value as fraction of the maximum current
435
+     * Returns values between 0 and 31, representing 1/32 to 32/32 (=1)
436
+     * \sa setCoolStepConfiguration()
437
+     */
438
+    unsigned char getCurrentCSReading(void);
439
+    
440
+    
441
+    /*!
442
+     *\brief a convenience method to determine if the current scaling uses 0.31V or 0.165V as reference.
443
+     *\return false if 0.13V is the reference voltage, true if 0.165V is used.
444
+     */
445
+    boolean isCurrentScalingHalfed();
446
+
447
+    /*!
448
+     * \brief Reads the current current setting value and recalculates the absolute current in mA (1A would be 1000).
449
+     * This method calculates the currently used current setting (either by setting or by CoolStep) and reconstructs
450
+     * the current in mA by usinge the VSENSE and resistor value. This method uses floating point math - so it 
451
+     * may not be the fastest.
452
+     * \sa getCurrentCSReading(), getResistor(), isCurrentScalingHalfed(), getCurrent()
453
+     */
454
+    unsigned int getCurrentCurrent(void);
455
+    
456
+    /*!
457
+     * \brief checks if there is a StallGuard warning in the last status
458
+     * \return 0 if there was no warning, -1 if there was some warning.
459
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
460
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
461
+     *
462
+     * \sa setStallGuardThreshold() for tuning the readout to sensible ranges.
463
+     */
464
+    boolean isStallGuardOverThreshold(void);
465
+    
466
+    /*!
467
+     * \brief Return over temperature status of the last status readout
468
+     * return 0 is everything is OK, TMC26X_OVERTEMPERATURE_PREWARING if status is reached, TMC26X_OVERTEMPERATURE_SHUTDOWN is the chip is shutdown, -1 if the status is unknown.
469
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
470
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
471
+     */
472
+    char getOverTemperature(void);
473
+    
474
+    /*!
475
+     * \brief Is motor channel A shorted to ground detected in the last status readout.
476
+     * \return true is yes, false if not.
477
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
478
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
479
+     */
480
+     
481
+    boolean isShortToGroundA(void);
482
+
483
+    /*!
484
+     * \brief Is motor channel B shorted to ground detected in the last status readout.
485
+     * \return true is yes, false if not.
486
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
487
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
488
+     */
489
+    boolean isShortToGroundB(void);
490
+    /*!
491
+     * \brief iIs motor channel A connected according to the last statu readout.
492
+     * \return true is yes, false if not.
493
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
494
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
495
+     */
496
+    boolean isOpenLoadA(void);
497
+
498
+    /*!
499
+     * \brief iIs motor channel A connected according to the last statu readout.
500
+     * \return true is yes, false if not.
501
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
502
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
503
+     */
504
+    boolean isOpenLoadB(void);
505
+    
506
+    /*!
507
+     * \brief Is chopper inactive since 2^20 clock cycles - defaults to ~0,08s
508
+     * \return true is yes, false if not.
509
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
510
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
511
+     */
512
+    boolean isStandStill(void);
513
+
514
+    /*!
515
+     * \brief checks if there is a StallGuard warning in the last status
516
+     * \return 0 if there was no warning, -1 if there was some warning.
517
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
518
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
519
+     *
520
+     * \sa isStallGuardOverThreshold()
521
+     * TODO why?
522
+     *
523
+     * \sa setStallGuardThreshold() for tuning the readout to sensible ranges.
524
+     */
525
+    boolean isStallGuardReached(void);
526
+    
527
+    /*!
528
+     *\brief enables or disables the motor driver bridges. If disabled the motor can run freely. If enabled not.
529
+     *\param enabled a boolean value true if the motor should be enabled, false otherwise.
530
+     */
531
+    void setEnabled(boolean enabled);
532
+    
533
+    /*!
534
+     *\brief checks if the output bridges are enabled. If the bridges are not enabled the motor can run freely
535
+     *\return true if the bridges and by that the motor driver are enabled, false if not.
536
+     *\sa setEnabled()
537
+     */
538
+    boolean isEnabled();
539
+
540
+    /*!
541
+     * \brief Manually read out the status register
542
+     * This function sends a byte to the motor driver in order to get the current readout. The parameter read_value
543
+     * seletcs which value will get returned. If the read_vlaue changes in respect to the previous readout this method
544
+     * automatically send two bytes to the motor: one to set the redout and one to get the actual readout. So this method 
545
+     * may take time to send and read one or two bits - depending on the previous readout.
546
+     * \param read_value selects which value to read out (0..3). You can use the defines TMC26X_READOUT_POSITION, TMC_262_READOUT_STALLGUARD, or TMC_262_READOUT_CURRENT
547
+     * \sa TMC26X_READOUT_POSITION, TMC_262_READOUT_STALLGUARD, TMC_262_READOUT_CURRENT
548
+     */
549
+    void readStatus(char read_value);
550
+    
551
+    /*!
552
+     * \brief Returns the current sense resistor value in milliohm.
553
+     * The default value of ,15 Ohm will return 150.
554
+     */
555
+    int getResistor();
556
+
557
+    /*!
558
+     * \brief Prints out all the information that can be found in the last status read out - it does not force a status readout. 
559
+     * The result is printed via Serial
560
+     */
561
+    void debugLastStatus(void);
562
+    /*!
563
+     * \brief library version
564
+     * \return the version number as int.
565
+     */
566
+    int version(void);
567
+
568
+  private:    
569
+    unsigned int steps_left;    // The steps the motor has to do to complete the movement
570
+    int direction;              // Direction of rotation
571
+    unsigned long step_delay;   // Delay between steps, in ms, based on speed
572
+    int number_of_steps;        // Total number of steps this motor can take
573
+    unsigned int speed;         // Store the current speed in order to change the speed after changing microstepping
574
+    unsigned int resistor;      // Current sense resitor value in milliohm
575
+        
576
+    unsigned long last_step_time;   // Time stamp in ms of when the last step was taken
577
+    unsigned long next_step_time;   // Time stamp in ms of when the last step was taken
578
+    
579
+    // Driver control register copies to easily set & modify the registers
580
+    unsigned long driver_control_register_value;
581
+    unsigned long chopper_config_register;
582
+    unsigned long cool_step_register_value;
583
+    unsigned long stall_guard2_current_register_value;
584
+    unsigned long driver_configuration_register_value;
585
+    // The driver status result
586
+    unsigned long driver_status_result;
587
+    
588
+    // Helper routione to get the top 10 bit of the readout
589
+    inline int getReadoutValue();
590
+    
591
+    // The pins for the stepper driver
592
+    unsigned char cs_pin;
593
+    unsigned char step_pin;
594
+    unsigned char dir_pin;
595
+    
596
+    // Status values 
597
+    boolean started; // If the stepper has been started yet
598
+    int microsteps; // The current number of micro steps
599
+    char constant_off_time; // We need to remember this value in order to enable and disable the motor
600
+    unsigned char cool_step_lower_threshold; //  we need to remember the threshold to enable and disable the CoolStep feature
601
+    boolean cool_step_enabled; // We need to remember this to configure the coolstep if it si enabled
602
+    
603
+    // SPI sender
604
+    inline void send262(unsigned long datagram);
605
+};
606
+
607
+#endif // _TMC26XSTEPPER_H_

+ 68
- 0
Marlin/src/HAL/HAL_STM32F7/endstop_interrupts.h View File

@@ -0,0 +1,68 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
+ *
5
+ * Based on Sprinter and grbl.
6
+ * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
7
+ * Copyright (C) 2017 Victor Perez
8
+ *
9
+ * This program is free software: you can redistribute it and/or modify
10
+ * it under the terms of the GNU General Public License as published by
11
+ * the Free Software Foundation, either version 3 of the License, or
12
+ * (at your option) any later version.
13
+ *
14
+ * This program is distributed in the hope that it will be useful,
15
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
+ * GNU General Public License for more details.
18
+ *
19
+ * You should have received a copy of the GNU General Public License
20
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
+ *
22
+ */
23
+
24
+
25
+
26
+#ifndef _ENDSTOP_INTERRUPTS_H_
27
+#define _ENDSTOP_INTERRUPTS_H_
28
+
29
+void setup_endstop_interrupts(void) {
30
+  #if HAS_X_MAX
31
+    pinMode(X_MAX_PIN, INPUT);
32
+    attachInterrupt(X_MAX_PIN, endstop_ISR, CHANGE); // assign it
33
+  #endif
34
+  #if HAS_X_MIN
35
+    pinMode(X_MIN_PIN, INPUT);
36
+    attachInterrupt(X_MIN_PIN, endstop_ISR, CHANGE);
37
+  #endif
38
+  #if HAS_Y_MAX
39
+    pinMode(Y_MAX_PIN, INPUT);
40
+    attachInterrupt(Y_MAX_PIN, endstop_ISR, CHANGE);
41
+  #endif
42
+  #if HAS_Y_MIN
43
+    pinMode(Y_MIN_PIN, INPUT);
44
+    attachInterrupt(Y_MIN_PIN, endstop_ISR, CHANGE);
45
+  #endif
46
+  #if HAS_Z_MAX
47
+    pinMode(Z_MAX_PIN, INPUT);
48
+    attachInterrupt(Z_MAX_PIN, endstop_ISR, CHANGE);
49
+  #endif
50
+  #if HAS_Z_MIN
51
+    pinMode(Z_MIN_PIN, INPUT);
52
+    attachInterrupt(Z_MIN_PIN, endstop_ISR, CHANGE);
53
+  #endif
54
+  #if HAS_Z2_MAX
55
+    pinMode(Z2_MAX_PIN, INPUT);
56
+    attachInterrupt(Z2_MAX_PIN, endstop_ISR, CHANGE);
57
+  #endif
58
+  #if HAS_Z2_MIN
59
+    pinMode(Z2_MIN_PIN, INPUT);
60
+    attachInterrupt(Z2_MIN_PIN, endstop_ISR, CHANGE);
61
+  #endif
62
+  #if HAS_Z_MIN_PROBE_PIN
63
+    pinMode(Z_MIN_PROBE_PIN, INPUT);
64
+    attachInterrupt(Z_MIN_PROBE_PIN, endstop_ISR, CHANGE);
65
+  #endif
66
+}
67
+
68
+#endif //_ENDSTOP_INTERRUPTS_H_

+ 54
- 0
Marlin/src/HAL/HAL_STM32F7/fastio_STM32F7.h View File

@@ -0,0 +1,54 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
+ *
5
+ * Based on Sprinter and grbl.
6
+ * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
7
+ * Copyright (C) 2017 Victor Perez
8
+ *
9
+ * This program is free software: you can redistribute it and/or modify
10
+ * it under the terms of the GNU General Public License as published by
11
+ * the Free Software Foundation, either version 3 of the License, or
12
+ * (at your option) any later version.
13
+ *
14
+ * This program is distributed in the hope that it will be useful,
15
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
+ * GNU General Public License for more details.
18
+ *
19
+ * You should have received a copy of the GNU General Public License
20
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
+ *
22
+ */
23
+
24
+/**
25
+ * Fast I/O interfaces for STM32F7
26
+ * These use GPIO functions instead of Direct Port Manipulation, as on AVR.
27
+ */
28
+
29
+#ifndef _FASTIO_STM32F7_H
30
+#define _FASTIO_STM32F7_H
31
+
32
+#define _BV(bit) (1 << (bit))
33
+
34
+#define READ(IO)              digitalRead(IO)
35
+#define WRITE(IO, v)          digitalWrite(IO,v)
36
+#define TOGGLE(IO)            do{ _SET_OUTPUT(IO); digitalWrite(IO,!digitalRead(IO)); }while(0)
37
+#define WRITE_VAR(IO, v)      digitalWrite(IO,v)
38
+
39
+#define _GET_MODE(IO)
40
+#define _SET_MODE(IO,M)       pinMode(IO, M)
41
+#define _SET_OUTPUT(IO)       pinMode(IO, OUTPUT)                               /*!< Output Push Pull Mode & GPIO_NOPULL   */
42
+
43
+#define SET_INPUT(IO)         _SET_MODE(IO, INPUT)                              /*!< Input Floating Mode                   */
44
+#define SET_INPUT_PULLUP(IO)  _SET_MODE(IO, INPUT_PULLUP)                       /*!< Input with Pull-up activation         */
45
+#define SET_INPUT_PULLDOW(IO) _SET_MODE(IO, INPUT_PULLDOWN)                     /*!< Input with Pull-down activation       */
46
+#define SET_OUTPUT(IO)        do{ _SET_OUTPUT(IO); WRITE(IO, LOW); }while(0)
47
+
48
+#define GET_INPUT(IO)
49
+#define GET_OUTPUT(IO)
50
+#define GET_TIMER(IO)
51
+
52
+#define OUT_WRITE(IO, v) { _SET_OUTPUT(IO); WRITE(IO, v); }
53
+
54
+#endif // _FASTIO_STM32F7_H

+ 82
- 0
Marlin/src/HAL/HAL_STM32F7/persistent_store_impl.cpp View File

@@ -0,0 +1,82 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ *
4
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
5
+ * Copyright (c) 2016 Bob Cousins bobcousins42@googlemail.com
6
+ * Copyright (c) 2015-2016 Nico Tonnhofer wurstnase.reprap@gmail.com
7
+ * Copyright (c) 2016 Victor Perez victor_pv@hotmail.com
8
+ *
9
+ * This program is free software: you can redistribute it and/or modify
10
+ * it under the terms of the GNU General Public License as published by
11
+ * the Free Software Foundation, either version 3 of the License, or
12
+ * (at your option) any later version.
13
+ *
14
+ * This program is distributed in the hope that it will be useful,
15
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
+ * GNU General Public License for more details.
18
+ *
19
+ * You should have received a copy of the GNU General Public License
20
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
+ *
22
+ */
23
+
24
+
25
+#ifdef STM32F7
26
+
27
+#include "../persistent_store_api.h"
28
+
29
+#include "../../inc/MarlinConfig.h"
30
+
31
+#if ENABLED(EEPROM_SETTINGS)
32
+
33
+namespace HAL {
34
+namespace PersistentStore {
35
+
36
+bool access_start() {
37
+  return true;
38
+}
39
+
40
+bool access_finish(){
41
+  return true;
42
+}
43
+
44
+bool write_data(int &pos, const uint8_t *value, uint16_t size, uint16_t *crc) {
45
+  while (size--) {
46
+    uint8_t * const p = (uint8_t * const)pos;
47
+    uint8_t v = *value;
48
+    // EEPROM has only ~100,000 write cycles,
49
+    // so only write bytes that have changed!
50
+    if (v != eeprom_read_byte(p)) {
51
+      eeprom_write_byte(p, v);
52
+      if (eeprom_read_byte(p) != v) {
53
+        SERIAL_ECHO_START();
54
+        SERIAL_ECHOLNPGM(MSG_ERR_EEPROM_WRITE);
55
+        return true;
56
+      }
57
+    }
58
+    crc16(crc, &v, 1);
59
+    pos++;
60
+    value++;
61
+  };
62
+  return false;
63
+}
64
+
65
+bool read_data(int &pos, uint8_t* value, uint16_t size, uint16_t *crc) {
66
+  do {
67
+    uint8_t c = eeprom_read_byte((unsigned char*)pos);
68
+    *value = c;
69
+    crc16(crc, &c, 1);
70
+    pos++;
71
+    value++;
72
+  } while (--size);
73
+  return false;
74
+}
75
+
76
+}
77
+}
78
+
79
+#endif // EEPROM_SETTINGS
80
+#endif // STM32F7
81
+
82
+

+ 33
- 0
Marlin/src/HAL/HAL_STM32F7/spi_pins.h View File

@@ -0,0 +1,33 @@
1
+/**
2
+* Marlin 3D Printer Firmware
3
+* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
+*
5
+* This program is free software: you can redistribute it and/or modify
6
+* it under the terms of the GNU General Public License as published by
7
+* the Free Software Foundation, either version 3 of the License, or
8
+* (at your option) any later version.
9
+*
10
+* This program is distributed in the hope that it will be useful,
11
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
+* GNU General Public License for more details.
14
+*
15
+* You should have received a copy of the GNU General Public License
16
+* along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
+*
18
+*/
19
+
20
+#ifndef SPI_PINS_H_
21
+#define SPI_PINS_H_
22
+
23
+
24
+/**
25
+ * Define SPI Pins: SCK, MISO, MOSI, SS
26
+ *
27
+ */
28
+#define SCK_PIN   _STM32_PIN(PORTA, 5)
29
+#define MISO_PIN  _STM32_PIN(PORTA, 6)
30
+#define MOSI_PIN  _STM32_PIN(PORTA, 7)
31
+#define SS_PIN    _STM32_PIN(PORTA, 8)
32
+
33
+#endif // SPI_PINS_H_

+ 52
- 0
Marlin/src/HAL/HAL_STM32F7/watchdog_STM32F7.cpp View File

@@ -0,0 +1,52 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
+ *
5
+ * Based on Sprinter and grbl.
6
+ * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
7
+ *
8
+ * This program is free software: you can redistribute it and/or modify
9
+ * it under the terms of the GNU General Public License as published by
10
+ * the Free Software Foundation, either version 3 of the License, or
11
+ * (at your option) any later version.
12
+ *
13
+ * This program is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
+ * GNU General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU General Public License
19
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
+ *
21
+ */
22
+
23
+#ifdef STM32F7
24
+
25
+#include "../../inc/MarlinConfig.h"
26
+
27
+#if ENABLED(USE_WATCHDOG)
28
+
29
+  #include "watchdog_STM32F7.h"
30
+
31
+  IWDG_HandleTypeDef hiwdg;
32
+
33
+  void watchdog_init() {
34
+    hiwdg.Instance = IWDG;
35
+    hiwdg.Init.Prescaler = IWDG_PRESCALER_32; //32kHz LSI clock and 32x prescalar = 1024Hz IWDG clock
36
+    hiwdg.Init.Reload = 4095;           //4095 counts = 4 seconds at 1024Hz
37
+    if (HAL_IWDG_Init(&hiwdg) != HAL_OK) {
38
+      //Error_Handler();
39
+    }
40
+  }
41
+
42
+  void watchdog_reset() {
43
+    /* Refresh IWDG: reload counter */
44
+    if (HAL_IWDG_Refresh(&hiwdg) != HAL_OK) {
45
+      /* Refresh Error */
46
+      //Error_Handler();
47
+    }
48
+  }
49
+
50
+#endif // USE_WATCHDOG
51
+
52
+#endif // STM32F7

+ 33
- 0
Marlin/src/HAL/HAL_STM32F7/watchdog_STM32F7.h View File

@@ -0,0 +1,33 @@
1
+/**
2
+* Marlin 3D Printer Firmware
3
+* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
+*
5
+* Based on Sprinter and grbl.
6
+* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
7
+*
8
+* This program is free software: you can redistribute it and/or modify
9
+* it under the terms of the GNU General Public License as published by
10
+* the Free Software Foundation, either version 3 of the License, or
11
+* (at your option) any later version.
12
+*
13
+* This program is distributed in the hope that it will be useful,
14
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
+* GNU General Public License for more details.
17
+*
18
+* You should have received a copy of the GNU General Public License
19
+* along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
+*
21
+*/
22
+
23
+#ifndef WATCHDOG_STM32F7_H
24
+#define WATCHDOG_STM32F7_H
25
+
26
+#include "../../../src/inc/MarlinConfig.h"
27
+
28
+extern IWDG_HandleTypeDef hiwdg;
29
+
30
+void watchdog_init();
31
+void watchdog_reset();
32
+
33
+#endif // WATCHDOG_STM32F1_H

+ 12
- 4
Marlin/src/HAL/HAL_SanityCheck.h View File

@@ -24,14 +24,22 @@
24 24
 
25 25
 #ifdef __AVR__
26 26
   #include "HAL_AVR/SanityCheck_AVR_8_bit.h"
27
-#elif defined(ARDUINO_ARCH_SAM)
27
+
28
+  #elif defined(ARDUINO_ARCH_SAM)
28 29
   #include "HAL_DUE/SanityCheck_Due.h"
29
-#elif IS_32BIT_TEENSY
30
+
31
+  #elif IS_32BIT_TEENSY
30 32
   #include "HAL_TEENSY35_36/SanityCheck_Teensy_35_36.h"
31
-#elif defined(TARGET_LPC1768)
33
+
34
+  #elif defined(TARGET_LPC1768)
32 35
   #include "HAL_LPC1768/SanityCheck_Re_ARM.h"
33
-#elif defined(__STM32F1__)
36
+
37
+  #elif defined(__STM32F1__)
34 38
     #include "HAL_STM32F1/SanityCheck_Stm32f1.h"
39
+
40
+  #elif defined(STM32F7)
41
+    #include "HAL_STM32F7/SanityCheck_STM32F7.h"
42
+
35 43
 #else
36 44
   #error Unsupported Platform!
37 45
 #endif

+ 11
- 11
Marlin/src/HAL/HAL_TEENSY35_36/HAL_Servo_Teensy.h View File

@@ -1,18 +1,18 @@
1
-#ifndef HAL_Servo_Teensy_h
2
-#define HAL_Servo_Teensy_h
1
+#ifndef _HAL_SERVO_TEENSY_H_
2
+#define _HAL_SERVO_TEENSY_H_
3 3
 
4 4
 #include <Servo.h>
5 5
 
6 6
 // Inherit and expand on the official library
7 7
 class libServo : public Servo {
8
-	public:
9
-		int8_t attach(const int pin);
10
-		int8_t attach(const int pin, const int min, const int max);
11
-		void move(const int value);
12
-	private:
13
-	   uint16_t min_ticks;
14
-	   uint16_t max_ticks;
15
-	   uint8_t servoIndex;               // index into the channel data for this servo
8
+  public:
9
+    int8_t attach(const int pin);
10
+    int8_t attach(const int pin, const int min, const int max);
11
+    void move(const int value);
12
+  private:
13
+     uint16_t min_ticks;
14
+     uint16_t max_ticks;
15
+     uint8_t servoIndex;               // index into the channel data for this servo
16 16
 };
17 17
 
18
-#endif // HAL_Servo_Teensy_h
18
+#endif // _HAL_SERVO_TEENSY_H_

+ 4
- 0
Marlin/src/HAL/HAL_endstop_interrupts.h View File

@@ -46,6 +46,10 @@ void endstop_ISR(void) { endstop_ISR_worker(); }
46 46
 
47 47
   #include "HAL_TEENSY35_36/endstop_interrupts.h"
48 48
 
49
+#elif defined(STM32F7)
50
+
51
+  #include "HAL_STM32F7/endstop_interrupts.h"
52
+
49 53
 #else
50 54
 
51 55
   #error Unsupported Platform!

+ 6
- 1
Marlin/src/HAL/HAL_spi_pins.h View File

@@ -34,8 +34,13 @@
34 34
 
35 35
 #elif defined(TARGET_LPC1768)
36 36
   #include "HAL_LPC1768/spi_pins.h"
37
+
37 38
 #elif defined(__STM32F1__)
38
-    #include "HAL_STM32F1/spi_pins.h"
39
+  #include "HAL_STM32F1/spi_pins.h"
40
+
41
+#elif defined(STM32F7)
42
+  #include "HAL_STM32F7/spi_pins.h"
43
+
39 44
 #else
40 45
   #error "Unsupported Platform!"
41 46
 #endif

+ 1793
- 0
Marlin/src/config/examples/TheBorg/Configuration.h
File diff suppressed because it is too large
View File


+ 1594
- 0
Marlin/src/config/examples/TheBorg/Configuration_adv.h
File diff suppressed because it is too large
View File


+ 6
- 0
Marlin/src/core/boards.h View File

@@ -199,6 +199,12 @@
199 199
 #define BOARD_BEAST            1802  // STM32FxxxVxT6 Libmaple based stm32f4 controller
200 200
 #define BOARD_STM3R_MINI       1803  // STM32 Libmaple based stm32f1 controller
201 201
 
202
+//
203
+// ARM Cortex M7
204
+//
205
+#define BOARD_THE_BORG         1860   // THE-BORG (Power outputs: Hotend0, Hotend1, Bed, Fan)
206
+
207
+
202 208
 #define MB(board) (MOTHERBOARD==BOARD_##board)
203 209
 
204 210
 #endif // __BOARDS_H

+ 1
- 0
Marlin/src/core/macros.h View File

@@ -120,6 +120,7 @@
120 120
 // Macros to contrain values
121 121
 #define NOLESS(v,n) do{ if (v < n) v = n; }while(0)
122 122
 #define NOMORE(v,n) do{ if (v > n) v = n; }while(0)
123
+#define LIMIT(v,n1,n2) do{ if (v < n1) v = n1; else if (v > n2) v = n2; }while(0)
123 124
 
124 125
 // Macros to support option testing
125 126
 #define _CAT(a, ...) a ## __VA_ARGS__

+ 9
- 9
Marlin/src/core/serial.h View File

@@ -97,13 +97,13 @@ extern const char errormagic[] PROGMEM;
97 97
   #endif
98 98
 
99 99
   #define SERIAL_EOL_P(p) SERIAL_CHAR_P(p,'\n')
100
-  
100
+
101 101
   #define SERIAL_PROTOCOLCHAR_P(p,x)              SERIAL_CHAR_P(p,x)
102 102
   #define SERIAL_PROTOCOLPGM_P(p,x)               (serialprintPGM_P(p,PSTR(x)))
103 103
   #define SERIAL_PROTOCOLLNPGM_P(p,x)             (serialprintPGM_P(p,PSTR(x "\n")))
104 104
   #define SERIAL_PROTOCOLPAIR_P(p, pre, value)    (serial_echopair_PGM_P(p,PSTR(pre),(value)))
105 105
   #define SERIAL_PROTOCOLLNPAIR_P(p, pre, value)  do { SERIAL_PROTOCOLPAIR_P(p, pre, value); SERIAL_EOL_P(p); } while(0)
106
-  
106
+
107 107
   #define SERIAL_ECHO_START_P(p)             (serialprintPGM_P(p,echomagic))
108 108
   #define SERIAL_ECHO_P(p,x)                 SERIAL_PROTOCOL_P(p,x)
109 109
   #define SERIAL_ECHOPGM_P(p,x)              SERIAL_PROTOCOLPGM_P(p,x)
@@ -112,13 +112,13 @@ extern const char errormagic[] PROGMEM;
112 112
   #define SERIAL_ECHOPAIR_P(p,pre,value)     SERIAL_PROTOCOLPAIR_P(p, pre, value)
113 113
   #define SERIAL_ECHOLNPAIR_P(p,pre, value)  SERIAL_PROTOCOLLNPAIR_P(p, pre, value)
114 114
   #define SERIAL_ECHO_F_P(p,x,y)             SERIAL_PROTOCOL_F_P(p,x,y)
115
-  
115
+
116 116
   #define SERIAL_ERROR_START_P(p)            (serialprintPGM_P(p,errormagic))
117 117
   #define SERIAL_ERROR_P(p,x)                SERIAL_PROTOCOL_P(p,x)
118 118
   #define SERIAL_ERRORPGM_P(p,x)             SERIAL_PROTOCOLPGM_P(p,x)
119 119
   #define SERIAL_ERRORLN_P(p,x)              SERIAL_PROTOCOLLN_P(p,x)
120 120
   #define SERIAL_ERRORLNPGM_P(p,x)           SERIAL_PROTOCOLLNPGM_P(p,x)
121
-  
121
+
122 122
   // These macros compensate for float imprecision
123 123
   #define SERIAL_PROTOCOLPAIR_F_P(p, pre, value)    SERIAL_PROTOCOLPAIR_P(p, pre, FIXFLOAT(value))
124 124
   #define SERIAL_PROTOCOLLNPAIR_F_P(p, pre, value)  SERIAL_PROTOCOLLNPAIR_P(p, pre, FIXFLOAT(value))
@@ -149,7 +149,7 @@ extern const char errormagic[] PROGMEM;
149 149
   #define SERIAL_PROTOCOL_F_P(p,x,y)  SERIAL_PROTOCOL_F(x,y)
150 150
   #define SERIAL_PROTOCOLLN_P(p,x)    SERIAL_PROTOCOLLN(x)
151 151
   #define SERIAL_PRINT_P(p,x,b)       SERIAL_PRINT(x,b)
152
-  #define SERIAL_PRINTLN_P(p,x,b)     SERIAL_PRINTLN(x,b) 
152
+  #define SERIAL_PRINTLN_P(p,x,b)     SERIAL_PRINTLN(x,b)
153 153
   #define SERIAL_PRINTF_P(p,args...)  SERIAL_PRINTF(args)
154 154
 
155 155
   #define SERIAL_CHAR(x)              MYSERIAL0.write(x)
@@ -168,13 +168,13 @@ extern const char errormagic[] PROGMEM;
168 168
   #endif
169 169
 
170 170
   #define SERIAL_EOL_P(p) SERIAL_EOL()
171
-  
171
+
172 172
   #define SERIAL_PROTOCOLCHAR_P(p,x)              SERIAL_PROTOCOLCHAR(x)
173 173
   #define SERIAL_PROTOCOLPGM_P(p,x)               SERIAL_PROTOCOLPGM(x)
174 174
   #define SERIAL_PROTOCOLLNPGM_P(p,x)             SERIAL_PROTOCOLLNPGM(x)
175 175
   #define SERIAL_PROTOCOLPAIR_P(p, pre, value)    SERIAL_PROTOCOLPAIR(pre, value)
176 176
   #define SERIAL_PROTOCOLLNPAIR_P(p, pre, value)  SERIAL_PROTOCOLLNPAIR(pre, value)
177
-  
177
+
178 178
   #define SERIAL_ECHO_START_P(p)             SERIAL_ECHO_START()
179 179
   #define SERIAL_ECHO_P(p,x)                 SERIAL_ECHO(x)
180 180
   #define SERIAL_ECHOPGM_P(p,x)              SERIAL_ECHOPGM(x)
@@ -183,13 +183,13 @@ extern const char errormagic[] PROGMEM;
183 183
   #define SERIAL_ECHOPAIR_P(p,pre,value)     SERIAL_ECHOPAIR(pre, value)
184 184
   #define SERIAL_ECHOLNPAIR_P(p,pre, value)  SERIAL_ECHOLNPAIR(pre, value)
185 185
   #define SERIAL_ECHO_F_P(p,x,y)             SERIAL_ECHO_F(x,y)
186
-  
186
+
187 187
   #define SERIAL_ERROR_START_P(p)            SERIAL_ERROR_START()
188 188
   #define SERIAL_ERROR_P(p,x)                SERIAL_ERROR(x)
189 189
   #define SERIAL_ERRORPGM_P(p,x)             SERIAL_ERRORPGM(x)
190 190
   #define SERIAL_ERRORLN_P(p,x)              SERIAL_ERRORLN(x)
191 191
   #define SERIAL_ERRORLNPGM_P(p,x)           SERIAL_ERRORLNPGM(x)
192
-  
192
+
193 193
   // These macros compensate for float imprecision
194 194
   #define SERIAL_PROTOCOLPAIR_F_P(p, pre, value)    SERIAL_PROTOCOLPAIR_F(pre, value)
195 195
   #define SERIAL_PROTOCOLLNPAIR_F_P(p, pre, value)  SERIAL_PROTOCOLLNPAIR_F(pre, value)

+ 1
- 1
Marlin/src/gcode/feature/trinamic/M122.cpp View File

@@ -31,7 +31,7 @@
31 31
  * M122: Debug TMC drivers
32 32
  */
33 33
 void GcodeSuite::M122() {
34
-  if (parser.seen('S')) 
34
+  if (parser.seen('S'))
35 35
     tmc_set_report_status(parser.value_bool());
36 36
   else
37 37
     tmc_report_all();

+ 1
- 1
Marlin/src/gcode/queue.cpp View File

@@ -254,7 +254,7 @@ static bool serial_data_available() {
254 254
 static int read_serial(const int index) {
255 255
   switch (index) {
256 256
     case 0: return MYSERIAL0.read();
257
-    #if NUM_SERIAL > 1 
257
+    #if NUM_SERIAL > 1
258 258
       case 1: return MYSERIAL1.read();
259 259
     #endif
260 260
     default: return -1;

+ 1
- 1
Marlin/src/gcode/sdcard/M20-M30_M32-M34_M928.cpp View File

@@ -109,7 +109,7 @@ void GcodeSuite::M26() {
109 109
 /**
110 110
  * M27: Get SD Card status
111 111
  */
112
-void GcodeSuite::M27() { 
112
+void GcodeSuite::M27() {
113 113
   card.getStatus(
114 114
     #if NUM_SERIAL > 1
115 115
       command_queue_port[cmd_queue_index_r]

+ 6
- 1
Marlin/src/module/stepper_indirection.cpp View File

@@ -41,7 +41,12 @@
41 41
 #if ENABLED(HAVE_TMCDRIVER)
42 42
 
43 43
   #include <SPI.h>
44
-  #include <TMC26XStepper.h>
44
+  
45
+  #ifdef STM32F7
46
+    #include "../HAL/HAL_STM32F7/TMC2660.h"
47
+  #else
48
+    #include <TMC26XStepper.h>
49
+  #endif
45 50
 
46 51
   #define _TMC_DEFINE(ST) TMC26XStepper stepper##ST(200, ST##_ENABLE_PIN, ST##_STEP_PIN, ST##_DIR_PIN, ST##_MAX_CURRENT, ST##_SENSE_RESISTOR)
47 52
 

+ 5
- 1
Marlin/src/module/stepper_indirection.h View File

@@ -49,7 +49,11 @@
49 49
 // TMC26X drivers have STEP/DIR on normal pins, but ENABLE via SPI
50 50
 #if ENABLED(HAVE_TMCDRIVER)
51 51
   #include <SPI.h>
52
-  #include <TMC26XStepper.h>
52
+  #ifdef STM32F7
53
+    #include "../HAL/HAL_STM32F7/TMC2660.h"
54
+  #else
55
+    #include <TMC26XStepper.h>
56
+  #endif
53 57
   void tmc_init();
54 58
 #endif
55 59
 

+ 2
- 0
Marlin/src/pins/pins.h View File

@@ -337,6 +337,8 @@
337 337
   #include "pins_AZTEEG_X5_GT.h"
338 338
 #elif MB(BIQU_BQ111_A4)
339 339
   #include "pins_BIQU_BQ111_A4.h"
340
+#elif MB(THE_BORG)
341
+  #include "pins_THE_BORG.h"
340 342
 #else
341 343
   #error "Unknown MOTHERBOARD value set in Configuration.h"
342 344
 #endif

+ 208
- 0
Marlin/src/pins/pins_THE_BORG.h View File

@@ -0,0 +1,208 @@
1
+/**
2
+ * Marlin 3D Printer Firmware
3
+ * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
4
+ *
5
+ * Based on Sprinter and grbl.
6
+ * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
7
+ *
8
+ * This program is free software: you can redistribute it and/or modify
9
+ * it under the terms of the GNU General Public License as published by
10
+ * the Free Software Foundation, either version 3 of the License, or
11
+ * (at your option) any later version.
12
+ *
13
+ * This program is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
+ * GNU General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU General Public License
19
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
+ *
21
+ */
22
+
23
+#if !defined(STM32F7)
24
+    #error "Oops!  Make sure you have an STM32F7 board selected from the 'Tools -> Boards' menu."
25
+#endif
26
+
27
+#define DEFAULT_MACHINE_NAME "The-Borge"
28
+#define BOARD_NAME "The-Borge"
29
+
30
+#define LARGE_FLASH true
31
+
32
+#define E2END 0xFFF // EEPROM end address
33
+
34
+// Ignore temp readings during develpment.
35
+#define BOGUS_TEMPERATURE_FAILSAFE_OVERRIDE
36
+
37
+#if E_STEPPERS > 3 || HOTENDS > 3
38
+  #error "The-Borg supports up to 3 hotends / E-steppers."
39
+#endif
40
+
41
+#define PORTA 0
42
+#define PORTB 1
43
+#define PORTC 2
44
+#define PORTD 3
45
+#define PORTE 4
46
+#define PORTF 5
47
+#define PORTG 6
48
+
49
+#define _STM32_PIN(_PORT,_PIN) ((_PORT * 16) + _PIN)
50
+
51
+
52
+//
53
+// Limit Switches
54
+//
55
+#define X_MIN_PIN          _STM32_PIN(PORTE, 9)
56
+#define X_MAX_PIN          _STM32_PIN(PORTE, 10)
57
+#define Y_MIN_PIN          _STM32_PIN(PORTE, 7)
58
+#define Y_MAX_PIN          _STM32_PIN(PORTE, 8)
59
+#define Z_MIN_PIN          _STM32_PIN(PORTF, 15) 
60
+#define Z_MAX_PIN          _STM32_PIN(PORTG, 0)
61
+#define E_MIN_PIN          _STM32_PIN(PORTE, 2)  
62
+#define E_MAX_PIN          _STM32_PIN(PORTE, 3)
63
+//
64
+// Z Probe (when not Z_MIN_PIN)
65
+//
66
+#ifndef Z_MIN_PROBE_PIN
67
+  #define Z_MIN_PROBE_PIN  _STM32_PIN(PORTA, 4)
68
+#endif
69
+
70
+//
71
+// Steppers
72
+//
73
+
74
+#define STEPPER_ENABLE_PIN _STM32_PIN(PORTE, 0)
75
+
76
+#define X_STEP_PIN         _STM32_PIN(PORTC, 6) //96, 39 in arduino
77
+#define X_DIR_PIN          _STM32_PIN(PORTC, 7)
78
+#define X_ENABLE_PIN       _STM32_PIN(PORTC, 8)
79
+
80
+
81
+#define Y_STEP_PIN         _STM32_PIN(PORTD, 9)
82
+#define Y_DIR_PIN          _STM32_PIN(PORTD, 10)
83
+#define Y_ENABLE_PIN       _STM32_PIN(PORTD, 11)
84
+
85
+#define Z_STEP_PIN         _STM32_PIN(PORTE, 15)
86
+#define Z_DIR_PIN          _STM32_PIN(PORTG, 1)
87
+#define Z_ENABLE_PIN       _STM32_PIN(PORTD, 8)
88
+
89
+
90
+#define E0_STEP_PIN        _STM32_PIN(PORTB, 1)
91
+#define E0_DIR_PIN         _STM32_PIN(PORTB, 2)
92
+#define E0_ENABLE_PIN      _STM32_PIN(PORTE, 11)
93
+
94
+
95
+#define E1_STEP_PIN        _STM32_PIN(PORTC, 4)
96
+#define E1_DIR_PIN         _STM32_PIN(PORTC, 5)
97
+#define E1_ENABLE_PIN      _STM32_PIN(PORTB, 0)
98
+
99
+
100
+#define E2_STEP_PIN        _STM32_PIN(PORTC, 13)
101
+#define E2_DIR_PIN         _STM32_PIN(PORTC, 14)
102
+#define E2_ENABLE_PIN      _STM32_PIN(PORTC, 15)
103
+
104
+#define Z2_STEP_PIN        _STM32_PIN(PORTC, 13)
105
+#define Z2_DIR_PIN         _STM32_PIN(PORTC, 14)
106
+#define Z2_ENABLE_PIN      _STM32_PIN(PORTC, 15)
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+#define SCK_PIN            _STM32_PIN(PORTA, 5)
115
+#define MISO_PIN           _STM32_PIN(PORTA, 6)
116
+#define MOSI_PIN           _STM32_PIN(PORTA, 7)
117
+
118
+#define SPI1_SCK_PIN       _STM32_PIN(PORTA, 5)
119
+#define SPI1_MISO_PIN      _STM32_PIN(PORTA, 6)
120
+#define SPI1_MOSI_PIN      _STM32_PIN(PORTA, 7)
121
+
122
+#define SPI6_SCK_PIN       _STM32_PIN(PORTG, 13)
123
+#define SPI6_MISO_PIN      _STM32_PIN(PORTG, 12)
124
+#define SPI6_MOSI_PIN      _STM32_PIN(PORTG, 14)
125
+
126
+
127
+
128
+
129
+//
130
+// Temperature Sensors
131
+//
132
+
133
+#define TEMP_0_PIN         _STM32_PIN(PORTC, 3)   // Analog Input
134
+#define TEMP_1_PIN         _STM32_PIN(PORTC, 2)   // Analog Input
135
+#define TEMP_2_PIN         _STM32_PIN(PORTC, 1)   // Analog Input
136
+#define TEMP_3_PIN         _STM32_PIN(PORTC, 0)   // Analog Input
137
+
138
+#define TEMP_BED_PIN       _STM32_PIN(PORTF, 10)  // Analog Input
139
+
140
+#define TEMP_5_PIN         _STM32_PIN(PORTE, 12)  // Analog Input, Probe temp
141
+
142
+
143
+//
144
+// Heaters / Fans
145
+//
146
+#define HEATER_0_PIN       _STM32_PIN(PORTD, 15)
147
+#define HEATER_1_PIN       _STM32_PIN(PORTD, 14)
148
+#define HEATER_BED_PIN     _STM32_PIN(PORTF,  6)
149
+
150
+#define FAN_PIN            _STM32_PIN(PORTD, 13)
151
+#define FAN1_PIN           _STM32_PIN(PORTA, 0)
152
+#define FAN2_PIN           _STM32_PIN(PORTA, 1)
153
+
154
+//#define E0_AUTO_FAN_PIN  _STM32_PIN(PORTA, 1)
155
+
156
+//
157
+// Misc. Functions
158
+//
159
+
160
+//#define CASE_LIGHT_PIN_CI _STM32_PIN(PORTF, 13)  //
161
+//#define CASE_LIGHT_PIN_DO _STM32_PIN(PORTF, 14)  //
162
+//#define NEOPIXEL_PIN     _STM32_PIN(PORTF, 13)
163
+
164
+//
165
+// Prusa i3 MK2 Multi Material Multiplexer Support
166
+//
167
+
168
+#define E_MUX0_PIN         _STM32_PIN(PORTG, 3)  
169
+#define E_MUX1_PIN         _STM32_PIN(PORTG, 4)
170
+
171
+//
172
+// Servos
173
+//
174
+
175
+#define SERVO0_PIN         _STM32_PIN(PORTE, 13)  
176
+#define SERVO1_PIN         _STM32_PIN(PORTE, 14)  
177
+
178
+
179
+#define SDSS               _STM32_PIN(PORTA, 8)
180
+#define SS_PIN             _STM32_PIN(PORTA, 8)
181
+#define LED_PIN            _STM32_PIN(PORTA, 2)         //Alive
182
+#define PS_ON_PIN          _STM32_PIN(PORTA, 3)
183
+#define KILL_PIN           -1//_STM32_PIN(PORTD, 5)     //EXP2-10
184
+#define PWR_LOSS           _STM32_PIN(PORTG, 5)         //Power loss / nAC_FAULT
185
+
186
+//
187
+//MAX7219_DEBUG
188
+//
189
+#define MAX7219_CLK_PIN    _STM32_PIN(PORTG, 10)     //EXP1-1
190
+#define MAX7219_DIN_PIN    _STM32_PIN(PORTD, 7)      //EXP1-3
191
+#define MAX7219_LOAD_PIN   _STM32_PIN(PORTD, 1)     //EXP1-5
192
+
193
+//#define NEOPIXEL_PIN    4
194
+  
195
+//
196
+// LCD / Controller
197
+//
198
+//#define SD_DETECT_PIN      -1 //_STM32_PIN(PORTB, 6))     //EXP2-4
199
+#define BEEPER_PIN         _STM32_PIN(PORTG, 10)        //EXP1-1
200
+#define LCD_PINS_RS        _STM32_PIN(PORTG, 9)         //EXP1-4
201
+#define LCD_PINS_ENABLE    _STM32_PIN(PORTD, 7)         //EXP1-3
202
+#define LCD_PINS_D4        _STM32_PIN(PORTD, 1)         //EXP1-5
203
+#define LCD_PINS_D5        _STM32_PIN(PORTF, 0)         //EXP1-6
204
+#define LCD_PINS_D6        _STM32_PIN(PORTD, 3)         //EXP1-7
205
+#define LCD_PINS_D7        _STM32_PIN(PORTD, 4)         //EXP1-8
206
+#define BTN_EN1            _STM32_PIN(PORTD, 6)         //EXP2-5
207
+#define BTN_EN2            _STM32_PIN(PORTD, 0)         //EXP2-3
208
+#define BTN_ENC            _STM32_PIN(PORTG, 11)        //EXP1-2

Loading…
Cancel
Save